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": "orces spaces inside computed properties.\n# @author Jamund Ferguson\n###\n'use strict'\n\n#------------------------------",
"end": 103,
"score": 0.9998582601547241,
"start": 88,
"tag": "NAME",
"value": "Jamund Ferguson"
}
] | src/tests/rules/computed-property-spacing.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Disallows or enforces spaces inside computed properties.
# @author Jamund Ferguson
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/computed-property-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'computed-property-spacing', rule,
valid: [
# default - never
'obj[foo]'
"obj['foo']"
,
code: 'x = {[b]: a}'
,
# always
code: 'obj[ foo ]', options: ['always']
,
code: "obj[ 'foo' ]", options: ['always']
,
code: "obj[ 'foo' + 'bar' ]", options: ['always']
,
code: 'obj[ obj2[ foo ] ]', options: ['always']
,
code: '''
obj.map (item) -> return [
1
2
3
4
]
'''
options: ['always']
,
code: '''
obj[ 'map' ] (item) -> [
1,
2,
3,
4
]
'''
options: ['always']
,
code: '''
obj[ 'for' + 'Each' ] (item) -> return [
1,
2,
3,
4
]
'''
options: ['always']
,
code: 'foo = obj[ 1 ]', options: ['always']
,
code: "foo = obj[ 'foo' ]", options: ['always']
,
code: 'foo = obj[ [1, 1] ]', options: ['always']
,
# always - objectLiteralComputedProperties
code: 'x = {[ "a" ]: a}'
options: ['always']
,
code: 'x = [ "a" ]: a'
options: ['always']
,
code: 'y = {[ x ]: a}'
options: ['always']
,
code: 'x = {[ "a" ]: ->}'
options: ['always']
,
code: 'y = {[ x ]: ->}'
options: ['always']
,
# always - unrelated cases
code: 'foo = {}', options: ['always']
,
code: 'foo = []', options: ['always']
,
# never
code: 'obj[foo]', options: ['never']
,
code: "obj['foo']", options: ['never']
,
code: "obj['foo' + 'bar']", options: ['never']
,
code: "obj['foo'+'bar']", options: ['never']
,
code: 'obj[obj2[foo]]', options: ['never']
,
code: '''
obj.map (item) -> return [
1
2
3
4
]
'''
options: ['never']
,
code: '''
obj['map'] (item) -> [
1
2
3
4
]
'''
options: ['never']
,
code: '''
obj['for' + 'Each'] (item) -> return [
1,
2,
3,
4
]
'''
options: ['never']
,
,
code: 'foo = obj[1]', options: ['never']
,
code: "foo = obj['foo']", options: ['never']
,
code: 'foo = obj[[ 1, 1 ]]', options: ['never']
,
# never - objectLiteralComputedProperties
code: 'x = {["a"]: a}'
options: ['never']
,
code: 'y = {[x]: a}'
options: ['never']
,
code: 'y = [x]: a'
options: ['never']
,
code: 'x = {["a"]: ->}'
options: ['never']
,
code: 'y = {[x]: ->}'
options: ['never']
,
# never - unrelated cases
code: 'foo = {}', options: ['never']
,
code: 'foo = []', options: ['never']
]
invalid: [
code: 'foo = obj[ 1]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 13
line: 1
]
,
code: 'foo = obj[1 ]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'foo = obj[ 1]'
output: 'foo = obj[1]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'foo = obj[1 ]'
output: 'foo = obj[1]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
]
,
code: 'obj[ foo ]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 4
line: 1
,
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'obj[foo ]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 9
line: 1
]
,
code: 'obj[ foo]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 4
line: 1
]
,
code: 'foo = obj[1]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 12
line: 1
]
,
# always - objectLiteralComputedProperties
code: 'x = {[a]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 8
line: 1
]
,
code: 'x = [a]: b'
output: 'x = [ a ]: b'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 5
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 7
line: 1
]
,
code: 'x = {[a ]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
,
code: 'x = {[ a]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 9
line: 1
]
,
# never - objectLiteralComputedProperties
code: 'x = {[ a ]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
,
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 10
line: 1
]
,
code: 'x = {[a ]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 9
line: 1
]
,
code: 'x = {[ a]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
,
code: 'x = {[ a\n]: b}'
output: 'x = {[a\n]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
]
| 51935 | ###*
# @fileoverview Disallows or enforces spaces inside computed properties.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/computed-property-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'computed-property-spacing', rule,
valid: [
# default - never
'obj[foo]'
"obj['foo']"
,
code: 'x = {[b]: a}'
,
# always
code: 'obj[ foo ]', options: ['always']
,
code: "obj[ 'foo' ]", options: ['always']
,
code: "obj[ 'foo' + 'bar' ]", options: ['always']
,
code: 'obj[ obj2[ foo ] ]', options: ['always']
,
code: '''
obj.map (item) -> return [
1
2
3
4
]
'''
options: ['always']
,
code: '''
obj[ 'map' ] (item) -> [
1,
2,
3,
4
]
'''
options: ['always']
,
code: '''
obj[ 'for' + 'Each' ] (item) -> return [
1,
2,
3,
4
]
'''
options: ['always']
,
code: 'foo = obj[ 1 ]', options: ['always']
,
code: "foo = obj[ 'foo' ]", options: ['always']
,
code: 'foo = obj[ [1, 1] ]', options: ['always']
,
# always - objectLiteralComputedProperties
code: 'x = {[ "a" ]: a}'
options: ['always']
,
code: 'x = [ "a" ]: a'
options: ['always']
,
code: 'y = {[ x ]: a}'
options: ['always']
,
code: 'x = {[ "a" ]: ->}'
options: ['always']
,
code: 'y = {[ x ]: ->}'
options: ['always']
,
# always - unrelated cases
code: 'foo = {}', options: ['always']
,
code: 'foo = []', options: ['always']
,
# never
code: 'obj[foo]', options: ['never']
,
code: "obj['foo']", options: ['never']
,
code: "obj['foo' + 'bar']", options: ['never']
,
code: "obj['foo'+'bar']", options: ['never']
,
code: 'obj[obj2[foo]]', options: ['never']
,
code: '''
obj.map (item) -> return [
1
2
3
4
]
'''
options: ['never']
,
code: '''
obj['map'] (item) -> [
1
2
3
4
]
'''
options: ['never']
,
code: '''
obj['for' + 'Each'] (item) -> return [
1,
2,
3,
4
]
'''
options: ['never']
,
,
code: 'foo = obj[1]', options: ['never']
,
code: "foo = obj['foo']", options: ['never']
,
code: 'foo = obj[[ 1, 1 ]]', options: ['never']
,
# never - objectLiteralComputedProperties
code: 'x = {["a"]: a}'
options: ['never']
,
code: 'y = {[x]: a}'
options: ['never']
,
code: 'y = [x]: a'
options: ['never']
,
code: 'x = {["a"]: ->}'
options: ['never']
,
code: 'y = {[x]: ->}'
options: ['never']
,
# never - unrelated cases
code: 'foo = {}', options: ['never']
,
code: 'foo = []', options: ['never']
]
invalid: [
code: 'foo = obj[ 1]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 13
line: 1
]
,
code: 'foo = obj[1 ]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'foo = obj[ 1]'
output: 'foo = obj[1]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'foo = obj[1 ]'
output: 'foo = obj[1]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
]
,
code: 'obj[ foo ]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 4
line: 1
,
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'obj[foo ]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 9
line: 1
]
,
code: 'obj[ foo]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 4
line: 1
]
,
code: 'foo = obj[1]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 12
line: 1
]
,
# always - objectLiteralComputedProperties
code: 'x = {[a]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 8
line: 1
]
,
code: 'x = [a]: b'
output: 'x = [ a ]: b'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 5
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 7
line: 1
]
,
code: 'x = {[a ]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
,
code: 'x = {[ a]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 9
line: 1
]
,
# never - objectLiteralComputedProperties
code: 'x = {[ a ]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
,
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 10
line: 1
]
,
code: 'x = {[a ]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 9
line: 1
]
,
code: 'x = {[ a]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
,
code: 'x = {[ a\n]: b}'
output: 'x = {[a\n]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
]
| true | ###*
# @fileoverview Disallows or enforces spaces inside computed properties.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/computed-property-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'computed-property-spacing', rule,
valid: [
# default - never
'obj[foo]'
"obj['foo']"
,
code: 'x = {[b]: a}'
,
# always
code: 'obj[ foo ]', options: ['always']
,
code: "obj[ 'foo' ]", options: ['always']
,
code: "obj[ 'foo' + 'bar' ]", options: ['always']
,
code: 'obj[ obj2[ foo ] ]', options: ['always']
,
code: '''
obj.map (item) -> return [
1
2
3
4
]
'''
options: ['always']
,
code: '''
obj[ 'map' ] (item) -> [
1,
2,
3,
4
]
'''
options: ['always']
,
code: '''
obj[ 'for' + 'Each' ] (item) -> return [
1,
2,
3,
4
]
'''
options: ['always']
,
code: 'foo = obj[ 1 ]', options: ['always']
,
code: "foo = obj[ 'foo' ]", options: ['always']
,
code: 'foo = obj[ [1, 1] ]', options: ['always']
,
# always - objectLiteralComputedProperties
code: 'x = {[ "a" ]: a}'
options: ['always']
,
code: 'x = [ "a" ]: a'
options: ['always']
,
code: 'y = {[ x ]: a}'
options: ['always']
,
code: 'x = {[ "a" ]: ->}'
options: ['always']
,
code: 'y = {[ x ]: ->}'
options: ['always']
,
# always - unrelated cases
code: 'foo = {}', options: ['always']
,
code: 'foo = []', options: ['always']
,
# never
code: 'obj[foo]', options: ['never']
,
code: "obj['foo']", options: ['never']
,
code: "obj['foo' + 'bar']", options: ['never']
,
code: "obj['foo'+'bar']", options: ['never']
,
code: 'obj[obj2[foo]]', options: ['never']
,
code: '''
obj.map (item) -> return [
1
2
3
4
]
'''
options: ['never']
,
code: '''
obj['map'] (item) -> [
1
2
3
4
]
'''
options: ['never']
,
code: '''
obj['for' + 'Each'] (item) -> return [
1,
2,
3,
4
]
'''
options: ['never']
,
,
code: 'foo = obj[1]', options: ['never']
,
code: "foo = obj['foo']", options: ['never']
,
code: 'foo = obj[[ 1, 1 ]]', options: ['never']
,
# never - objectLiteralComputedProperties
code: 'x = {["a"]: a}'
options: ['never']
,
code: 'y = {[x]: a}'
options: ['never']
,
code: 'y = [x]: a'
options: ['never']
,
code: 'x = {["a"]: ->}'
options: ['never']
,
code: 'y = {[x]: ->}'
options: ['never']
,
# never - unrelated cases
code: 'foo = {}', options: ['never']
,
code: 'foo = []', options: ['never']
]
invalid: [
code: 'foo = obj[ 1]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 13
line: 1
]
,
code: 'foo = obj[1 ]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'foo = obj[ 1]'
output: 'foo = obj[1]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'foo = obj[1 ]'
output: 'foo = obj[1]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
]
,
code: 'obj[ foo ]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 4
line: 1
,
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 10
line: 1
]
,
code: 'obj[foo ]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 9
line: 1
]
,
code: 'obj[ foo]'
output: 'obj[foo]'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 4
line: 1
]
,
code: 'foo = obj[1]'
output: 'foo = obj[ 1 ]'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'MemberExpression'
column: 10
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'MemberExpression'
column: 12
line: 1
]
,
# always - objectLiteralComputedProperties
code: 'x = {[a]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 8
line: 1
]
,
code: 'x = [a]: b'
output: 'x = [ a ]: b'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 5
line: 1
,
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 7
line: 1
]
,
code: 'x = {[a ]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
,
code: 'x = {[ a]: b}'
output: 'x = {[ a ]: b}'
options: ['always']
errors: [
messageId: 'missingSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 9
line: 1
]
,
# never - objectLiteralComputedProperties
code: 'x = {[ a ]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
,
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 10
line: 1
]
,
code: 'x = {[a ]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceBefore'
data: tokenValue: ']'
type: 'Property'
column: 9
line: 1
]
,
code: 'x = {[ a]: b}'
output: 'x = {[a]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
,
code: 'x = {[ a\n]: b}'
output: 'x = {[a\n]: b}'
options: ['never']
errors: [
messageId: 'unexpectedSpaceAfter'
data: tokenValue: '['
type: 'Property'
column: 6
line: 1
]
]
|
[
{
"context": ".keys(env.skills).forEach (skill) =>\n key = \"skill#{skill.toUpperCase()}\"\n val = @skillIsSet(skill)\n @set(key, va",
"end": 151,
"score": 0.9966235160827637,
"start": 123,
"tag": "KEY",
"value": "skill#{skill.toUpperCase()}\""
},
{
"context": ".keys(e... | app/assets/javascripts/mixins/skill_settings.js.coffee | fwoeck/voice-rails | 1 | Voice.SkillSettings = Ember.Mixin.create({
splitSkills: ( ->
Ember.keys(env.skills).forEach (skill) =>
key = "skill#{skill.toUpperCase()}"
val = @skillIsSet(skill)
@set(key, val) if @get(key) != val
).observes('skills.[]')
skillIsSet: (skill) ->
@get('skills').indexOf(skill) > -1
joinSkills: ->
newSkills = []
Ember.keys(env.skills).forEach (skill) =>
key = "skill#{skill.toUpperCase()}"
newSkills.push(skill) if @get(key)
newVal = newSkills.sort()
@set('skills', newVal) if Ember.compare(newVal, @get 'skills')
observeSkills: ->
self = @
Ember.keys(env.skills).forEach (skill) =>
key = "skill#{skill.toUpperCase()}"
@addObserver(key, -> Ember.run.scheduleOnce 'actions', self, self.joinSkills)
})
| 206093 | Voice.SkillSettings = Ember.Mixin.create({
splitSkills: ( ->
Ember.keys(env.skills).forEach (skill) =>
key = "<KEY>
val = @skillIsSet(skill)
@set(key, val) if @get(key) != val
).observes('skills.[]')
skillIsSet: (skill) ->
@get('skills').indexOf(skill) > -1
joinSkills: ->
newSkills = []
Ember.keys(env.skills).forEach (skill) =>
key = "<KEY>
newSkills.push(skill) if @get(key)
newVal = newSkills.sort()
@set('skills', newVal) if Ember.compare(newVal, @get 'skills')
observeSkills: ->
self = @
Ember.keys(env.skills).forEach (skill) =>
key = "<KEY>
@addObserver(key, -> Ember.run.scheduleOnce 'actions', self, self.joinSkills)
})
| true | Voice.SkillSettings = Ember.Mixin.create({
splitSkills: ( ->
Ember.keys(env.skills).forEach (skill) =>
key = "PI:KEY:<KEY>END_PI
val = @skillIsSet(skill)
@set(key, val) if @get(key) != val
).observes('skills.[]')
skillIsSet: (skill) ->
@get('skills').indexOf(skill) > -1
joinSkills: ->
newSkills = []
Ember.keys(env.skills).forEach (skill) =>
key = "PI:KEY:<KEY>END_PI
newSkills.push(skill) if @get(key)
newVal = newSkills.sort()
@set('skills', newVal) if Ember.compare(newVal, @get 'skills')
observeSkills: ->
self = @
Ember.keys(env.skills).forEach (skill) =>
key = "PI:KEY:<KEY>END_PI
@addObserver(key, -> Ember.run.scheduleOnce 'actions', self, self.joinSkills)
})
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9989604949951172,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-status-code.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.
# Simple test of Node's HTTP ServerResponse.statusCode
# ServerResponse.prototype.statusCode
nextTest = ->
return s.close() if testIdx + 1 is tests.length
test = tests[testIdx]
http.get
port: common.PORT
, (response) ->
console.log "client: expected status: " + test
console.log "client: statusCode: " + response.statusCode
assert.equal response.statusCode, test
response.on "end", ->
testsComplete++
testIdx += 1
nextTest()
return
response.resume()
return
return
common = require("../common")
assert = require("assert")
http = require("http")
testsComplete = 0
tests = [
200
202
300
404
500
]
testIdx = 0
s = http.createServer((req, res) ->
t = tests[testIdx]
res.writeHead t,
"Content-Type": "text/plain"
console.log "--\nserver: statusCode after writeHead: " + res.statusCode
assert.equal res.statusCode, t
res.end "hello world\n"
return
)
s.listen common.PORT, nextTest
process.on "exit", ->
assert.equal 4, testsComplete
return
| 163882 | # 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.
# Simple test of Node's HTTP ServerResponse.statusCode
# ServerResponse.prototype.statusCode
nextTest = ->
return s.close() if testIdx + 1 is tests.length
test = tests[testIdx]
http.get
port: common.PORT
, (response) ->
console.log "client: expected status: " + test
console.log "client: statusCode: " + response.statusCode
assert.equal response.statusCode, test
response.on "end", ->
testsComplete++
testIdx += 1
nextTest()
return
response.resume()
return
return
common = require("../common")
assert = require("assert")
http = require("http")
testsComplete = 0
tests = [
200
202
300
404
500
]
testIdx = 0
s = http.createServer((req, res) ->
t = tests[testIdx]
res.writeHead t,
"Content-Type": "text/plain"
console.log "--\nserver: statusCode after writeHead: " + res.statusCode
assert.equal res.statusCode, t
res.end "hello world\n"
return
)
s.listen common.PORT, nextTest
process.on "exit", ->
assert.equal 4, testsComplete
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.
# Simple test of Node's HTTP ServerResponse.statusCode
# ServerResponse.prototype.statusCode
nextTest = ->
return s.close() if testIdx + 1 is tests.length
test = tests[testIdx]
http.get
port: common.PORT
, (response) ->
console.log "client: expected status: " + test
console.log "client: statusCode: " + response.statusCode
assert.equal response.statusCode, test
response.on "end", ->
testsComplete++
testIdx += 1
nextTest()
return
response.resume()
return
return
common = require("../common")
assert = require("assert")
http = require("http")
testsComplete = 0
tests = [
200
202
300
404
500
]
testIdx = 0
s = http.createServer((req, res) ->
t = tests[testIdx]
res.writeHead t,
"Content-Type": "text/plain"
console.log "--\nserver: statusCode after writeHead: " + res.statusCode
assert.equal res.statusCode, t
res.end "hello world\n"
return
)
s.listen common.PORT, nextTest
process.on "exit", ->
assert.equal 4, testsComplete
return
|
[
{
"context": "scura.PNG)\n - Studying the mechanism of vision: Hubel & Wiesel, 1959, Finding out that visual processin",
"end": 790,
"score": 0.9735404253005981,
"start": 785,
"tag": "NAME",
"value": "Hubel"
},
{
"context": "G)\n - Studying the mechanism of vision: Hubel & Wies... | _posts/notes/903a3585-b87c-419a-bf7d-5454ee6dd38d.cson | rpblic/rpblic.github.io | 0 | createdAt: "2018-09-22T05:43:10.328Z"
updatedAt: "2018-09-27T08:11:56.373Z"
type: "MARKDOWN_NOTE"
folder: "418af029155901b7f280"
title: ""
content: '''
---
layout: post
title: Lecture 1 Introduction to Convolutional Neural Networks for Visual Recognition
category: Dl.cs231n.lecture
tags: ['DeepLearning', 'CS231n']
---

#### Brief history of computer vision
- Biological Vision: 540 million years ago, vision sensory system has evolved.
- Humans use 50% of neurons in our contex involved in visual processing
- Mechanical Vision: 16th, Renaissance period - Camera Obscura

- Studying the mechanism of vision: Hubel & Wiesel, 1959, Finding out that visual processing starts with simple structure of visual world and moves along the visual processing pathway the brain buildup the complexity
- Larry Roberts, 1963, first thesis of computer vision as simplifing the visual structure into simple geometric shapes, to recognize and reconstruct the shape and structure
- David Marr, late 1970s, Defines Vision Process as Input >> Primal Sketch >> 2 1/2D Sketch >> 3D Model Representation
- To make primitive computer to understand the visual structure, it has to be reduced to simple structures.
- Brooks & Binford, 1979, Generalized Cylinder Model
- Fischler and Elschlager, 1973, Pictorial Structure Model
- David Lowe, 1987, Lines & Edges Model

- Shi & Malic, 1997, Using a Grapy Theory algorithm to obtain Image Segmentation
- Viola & Jones, 2001, Face Detection using AdaBoost

- David Lowe, 1999, SIFT feature - finding the diagnostic and invariant features to recognize object
- Schmid & Ponce, 2006,Spatial Pyramid Matching- finding clues of which type of scene it is, by feature descriptor, then use SVM algorithm
- Recognizing Human Body: Dalal & Triggs, 2005, Histogram of Gradients / Felzenswalb, McAllester, Ramanan, 2009, Deformable Part Model
- LeCun et al, 1998, Use Convolutional NN for MNIST digit classification

- number of computation matters(10^6 transistors to 10^9 transistors & GPU)
- number of data matters(10^7 to 10^14)
- Data of evaluating Visual Recognition
- PASCAL Visual Object Challenge
- IMAGENET: label ALL categories we could see in real world with HUGE data. (By the bunch of categories, there might be a overfitting bottleneck problem for almost every ML algorithms, then How we could recognize every images?)


'''
tags: []
isStarred: false
isTrashed: false
| 70786 | createdAt: "2018-09-22T05:43:10.328Z"
updatedAt: "2018-09-27T08:11:56.373Z"
type: "MARKDOWN_NOTE"
folder: "418af029155901b7f280"
title: ""
content: '''
---
layout: post
title: Lecture 1 Introduction to Convolutional Neural Networks for Visual Recognition
category: Dl.cs231n.lecture
tags: ['DeepLearning', 'CS231n']
---

#### Brief history of computer vision
- Biological Vision: 540 million years ago, vision sensory system has evolved.
- Humans use 50% of neurons in our contex involved in visual processing
- Mechanical Vision: 16th, Renaissance period - Camera Obscura

- Studying the mechanism of vision: <NAME> & <NAME>, 1959, Finding out that visual processing starts with simple structure of visual world and moves along the visual processing pathway the brain buildup the complexity
- <NAME>, 1963, first thesis of computer vision as simplifing the visual structure into simple geometric shapes, to recognize and reconstruct the shape and structure
- <NAME>, late 1970s, Defines Vision Process as Input >> Primal Sketch >> 2 1/2D Sketch >> 3D Model Representation
- To make primitive computer to understand the visual structure, it has to be reduced to simple structures.
- Brooks & Binford, 1979, Generalized Cylinder Model
- Fischler and Elschlager, 1973, Pictorial Structure Model
- <NAME>, 1987, Lines & Edges Model

- <NAME> & <NAME>, 1997, Using a Grapy Theory algorithm to obtain Image Segmentation
- <NAME> & <NAME>, 2001, Face Detection using AdaBoost

- <NAME>, 1999, SIFT feature - finding the diagnostic and invariant features to recognize object
- <NAME> & <NAME>, 2006,Spatial Pyramid Matching- finding clues of which type of scene it is, by feature descriptor, then use SVM algorithm
- Recognizing Human Body: <NAME> & T<NAME>, 2005, Histogram of Gradients / Felzenswalb, McAllester, Ramanan, 2009, Deformable Part Model
- LeCun et al, 1998, Use Convolutional NN for MNIST digit classification

- number of computation matters(10^6 transistors to 10^9 transistors & GPU)
- number of data matters(10^7 to 10^14)
- Data of evaluating Visual Recognition
- PASCAL Visual Object Challenge
- IMAGENET: label ALL categories we could see in real world with HUGE data. (By the bunch of categories, there might be a overfitting bottleneck problem for almost every ML algorithms, then How we could recognize every images?)


'''
tags: []
isStarred: false
isTrashed: false
| true | createdAt: "2018-09-22T05:43:10.328Z"
updatedAt: "2018-09-27T08:11:56.373Z"
type: "MARKDOWN_NOTE"
folder: "418af029155901b7f280"
title: ""
content: '''
---
layout: post
title: Lecture 1 Introduction to Convolutional Neural Networks for Visual Recognition
category: Dl.cs231n.lecture
tags: ['DeepLearning', 'CS231n']
---

#### Brief history of computer vision
- Biological Vision: 540 million years ago, vision sensory system has evolved.
- Humans use 50% of neurons in our contex involved in visual processing
- Mechanical Vision: 16th, Renaissance period - Camera Obscura

- Studying the mechanism of vision: PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI, 1959, Finding out that visual processing starts with simple structure of visual world and moves along the visual processing pathway the brain buildup the complexity
- PI:NAME:<NAME>END_PI, 1963, first thesis of computer vision as simplifing the visual structure into simple geometric shapes, to recognize and reconstruct the shape and structure
- PI:NAME:<NAME>END_PI, late 1970s, Defines Vision Process as Input >> Primal Sketch >> 2 1/2D Sketch >> 3D Model Representation
- To make primitive computer to understand the visual structure, it has to be reduced to simple structures.
- Brooks & Binford, 1979, Generalized Cylinder Model
- Fischler and Elschlager, 1973, Pictorial Structure Model
- PI:NAME:<NAME>END_PI, 1987, Lines & Edges Model

- PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI, 1997, Using a Grapy Theory algorithm to obtain Image Segmentation
- PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI, 2001, Face Detection using AdaBoost

- PI:NAME:<NAME>END_PI, 1999, SIFT feature - finding the diagnostic and invariant features to recognize object
- PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI, 2006,Spatial Pyramid Matching- finding clues of which type of scene it is, by feature descriptor, then use SVM algorithm
- Recognizing Human Body: PI:NAME:<NAME>END_PI & TPI:NAME:<NAME>END_PI, 2005, Histogram of Gradients / Felzenswalb, McAllester, Ramanan, 2009, Deformable Part Model
- LeCun et al, 1998, Use Convolutional NN for MNIST digit classification

- number of computation matters(10^6 transistors to 10^9 transistors & GPU)
- number of data matters(10^7 to 10^14)
- Data of evaluating Visual Recognition
- PASCAL Visual Object Challenge
- IMAGENET: label ALL categories we could see in real world with HUGE data. (By the bunch of categories, there might be a overfitting bottleneck problem for almost every ML algorithms, then How we could recognize every images?)


'''
tags: []
isStarred: false
isTrashed: false
|
[
{
"context": "over to the actual wrappers\n#\n# Copyright (C) 2013 Nikolay Nemshilov\n#\next Wrapper,\n Cache: Wrapper_Cache # the dom-w",
"end": 175,
"score": 0.9998860359191895,
"start": 158,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/dom/src/casting.coffee | lovely-io/lovely.io-stl | 2 | #
# The `Wrapper` auto-casting extensions
# we keep them in a separated file so that
# they weren't copied over to the actual wrappers
#
# Copyright (C) 2013 Nikolay Nemshilov
#
ext Wrapper,
Cache: Wrapper_Cache # the dom-wrappers registry
Tags: {} # tags specific wrappers
#
# Sets a default dom wrapper for the tag
#
# @param {String} tag name
# @param {Element} tag specific dom-wrapper
# @return {Wrapper} this
#
set: (tag, wrapper)->
Wrapper.Tags[tag.toUpperCase()] = wrapper
Wrapper
#
# Tries to return a tag-specific dom-wrapper for the tag
#
# @param {String} tag name
# @return {Element} wrapper of `undefined`
#
get: (tag)->
Wrapper.Tags[tag.toUpperCase()]
#
# Removes a default tag-specific dom-wrapper for the tag
#
# @param {String} tag name
# @return {Wrapper} this
#
remove: (tag)->
delete Wrapper.Tags[tag.toUpperCase()]
Wrapper
#
# Finds appropriate wrapper for the raw-dom element
#
find: (element)->
Wrapper.Tags[element.tagName] || Element
| 132634 | #
# The `Wrapper` auto-casting extensions
# we keep them in a separated file so that
# they weren't copied over to the actual wrappers
#
# Copyright (C) 2013 <NAME>
#
ext Wrapper,
Cache: Wrapper_Cache # the dom-wrappers registry
Tags: {} # tags specific wrappers
#
# Sets a default dom wrapper for the tag
#
# @param {String} tag name
# @param {Element} tag specific dom-wrapper
# @return {Wrapper} this
#
set: (tag, wrapper)->
Wrapper.Tags[tag.toUpperCase()] = wrapper
Wrapper
#
# Tries to return a tag-specific dom-wrapper for the tag
#
# @param {String} tag name
# @return {Element} wrapper of `undefined`
#
get: (tag)->
Wrapper.Tags[tag.toUpperCase()]
#
# Removes a default tag-specific dom-wrapper for the tag
#
# @param {String} tag name
# @return {Wrapper} this
#
remove: (tag)->
delete Wrapper.Tags[tag.toUpperCase()]
Wrapper
#
# Finds appropriate wrapper for the raw-dom element
#
find: (element)->
Wrapper.Tags[element.tagName] || Element
| true | #
# The `Wrapper` auto-casting extensions
# we keep them in a separated file so that
# they weren't copied over to the actual wrappers
#
# Copyright (C) 2013 PI:NAME:<NAME>END_PI
#
ext Wrapper,
Cache: Wrapper_Cache # the dom-wrappers registry
Tags: {} # tags specific wrappers
#
# Sets a default dom wrapper for the tag
#
# @param {String} tag name
# @param {Element} tag specific dom-wrapper
# @return {Wrapper} this
#
set: (tag, wrapper)->
Wrapper.Tags[tag.toUpperCase()] = wrapper
Wrapper
#
# Tries to return a tag-specific dom-wrapper for the tag
#
# @param {String} tag name
# @return {Element} wrapper of `undefined`
#
get: (tag)->
Wrapper.Tags[tag.toUpperCase()]
#
# Removes a default tag-specific dom-wrapper for the tag
#
# @param {String} tag name
# @return {Wrapper} this
#
remove: (tag)->
delete Wrapper.Tags[tag.toUpperCase()]
Wrapper
#
# Finds appropriate wrapper for the raw-dom element
#
find: (element)->
Wrapper.Tags[element.tagName] || Element
|
[
{
"context": "\n## Env\n{ NODE_ENV, PORT } = process.env\n\nNAME = 'StahkPhotos'\nENV_KEY = \"#{NAME}-Env\"\n\n## New Relic\nrequire('n",
"end": 113,
"score": 0.9982923269271851,
"start": 102,
"tag": "USERNAME",
"value": "StahkPhotos"
},
{
"context": "RT } = process.env\n\nNAME = 'St... | src/backend/server.coffee | geekjuice/StahkPhotos | 8 |
###
Backend
###
Enviro = require('./lib/enviro')
## Env
{ NODE_ENV, PORT } = process.env
NAME = 'StahkPhotos'
ENV_KEY = "#{NAME}-Env"
## New Relic
require('newrelic') if Enviro.isDeployed()
## Requires
express = require('express')
bodyParser = require('body-parser')
logger = require('morgan')
debug = require('debug')(NAME)
## Start Express
app = express()
## Setup Middleware
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(extended: true))
app.use (req, res, next) ->
res.cookie(ENV_KEY, NODE_ENV)
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,POST')
res.header("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Type')
next()
## Static
app.use(express.static("#{__dirname}/public"))
## Routes
require('./router')(app)
## Start Server
app.set('port', PORT or 7000)
server = app.listen app.get('port'), ->
debug('Server listening on port ' + server.address().port)
## Export App
module.exports = app
| 85579 |
###
Backend
###
Enviro = require('./lib/enviro')
## Env
{ NODE_ENV, PORT } = process.env
NAME = 'StahkPhotos'
ENV_KEY = <KEY>"
## New Relic
require('newrelic') if Enviro.isDeployed()
## Requires
express = require('express')
bodyParser = require('body-parser')
logger = require('morgan')
debug = require('debug')(NAME)
## Start Express
app = express()
## Setup Middleware
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(extended: true))
app.use (req, res, next) ->
res.cookie(ENV_KEY, NODE_ENV)
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,POST')
res.header("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Type')
next()
## Static
app.use(express.static("#{__dirname}/public"))
## Routes
require('./router')(app)
## Start Server
app.set('port', PORT or 7000)
server = app.listen app.get('port'), ->
debug('Server listening on port ' + server.address().port)
## Export App
module.exports = app
| true |
###
Backend
###
Enviro = require('./lib/enviro')
## Env
{ NODE_ENV, PORT } = process.env
NAME = 'StahkPhotos'
ENV_KEY = PI:KEY:<KEY>END_PI"
## New Relic
require('newrelic') if Enviro.isDeployed()
## Requires
express = require('express')
bodyParser = require('body-parser')
logger = require('morgan')
debug = require('debug')(NAME)
## Start Express
app = express()
## Setup Middleware
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(extended: true))
app.use (req, res, next) ->
res.cookie(ENV_KEY, NODE_ENV)
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,POST')
res.header("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Type')
next()
## Static
app.use(express.static("#{__dirname}/public"))
## Routes
require('./router')(app)
## Start Server
app.set('port', PORT or 7000)
server = app.listen app.get('port'), ->
debug('Server listening on port ' + server.address().port)
## Export App
module.exports = app
|
[
{
"context": " \"Should Map\", ->\n # See: https://github.com/codecombat/aether/issues/97\n code = \"return (num for nu",
"end": 2164,
"score": 0.9995452761650085,
"start": 2154,
"tag": "USERNAME",
"value": "codecombat"
},
{
"context": "r is not supported in CSR yet: https:... | spec/aether/cs_spec.coffee | cihatislamdede/codecombat | 4,858 | Aether = require '../aether'
describe "CS test Suite!", ->
describe "CS compilation", ->
aether = new Aether language: "coffeescript"
it "Should compile functions", ->
code = """
return 1000
"""
aether.transpile(code)
expect(aether.run()).toEqual 1000
expect(aether.problems.errors).toEqual []
describe "CS compilation with lang set after contruction", ->
aether = new Aether()
it "Should compile functions", ->
code = """
return 2000 if false
return 1000
"""
aether.setLanguage "coffeescript"
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.problems.errors).toEqual []
describe "CS Test Spec #1", ->
aether = new Aether language: "coffeescript"
it "mathmetics order", ->
code = "
return (2*2 + 2/2 - 2*2/2)
"
aether.transpile(code)
expect(aether.run()).toEqual 3
expect(aether.problems.errors).toEqual []
describe "CS Test Spec #2", ->
aether = new Aether language: "coffeescript"
it "function call", ->
code = """
fib = (n) ->
(if n < 2 then n else fib(n - 1) + fib(n - 2))
chupacabra = fib(6)
"""
aether.transpile(code)
fn = aether.createFunction()
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 8 # fail
expect(aether.problems.errors).toEqual []
describe "Basics", ->
aether = new Aether language: "coffeescript"
it "Simple For", ->
code = """
count = 0
count++ for num in [1..10]
return count
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 10
expect(aether.problems.errors).toEqual []
it "Simple While", ->
code = """
count = 0
count++ until count is 100
return count
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 100
expect(aether.problems.errors).toEqual []
it "Should Map", ->
# See: https://github.com/codecombat/aether/issues/97
code = "return (num for num in [10..1])"
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
expect(aether.problems.errors).toEqual []
it "Should Map properties", ->
code = '''
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
return ages
'''
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual ["max is 10", "ida is 9", "tim is 11"]
expect(aether.problems.errors).toEqual []
it "Should compile empty function", ->
code = """
func = () ->
return typeof func
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 'function'
expect(aether.problems.errors).toEqual []
it "Should compile objects", ->
code = """
singers = {Jagger: 'Rock', Elvis: 'Roll'}
return singers
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual ({Jagger: 'Rock', Elvis: 'Roll'})
expect(aether.problems.errors).toEqual []
it "Should compile classes", ->
code = """
class MyClass
test: ->
return 1000
myClass = new MyClass()
return myClass.test()
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 1000
expect(aether.problems.errors).toEqual []
xit "Should compile super", ->
# super is not supported in CSR yet: https://github.com/michaelficarra/CoffeeScriptRedux/search?q=super&ref=cmdform&type=Issues
code = '''
class Animal
constructor: (@name) ->
move: (meters) ->
@name + " moved " + meters + "m."
class Snake extends Animal
move: ->
super 5
sam = new Snake "Sammy the Python"
sam.move()
'''
aether.transpile(code)
expect(aether.run()).toEqual "Sammy the Python moved 5m."
expect(aether.problems.errors).toEqual []
it "Should compile string interpolation", ->
code = '''
meters = 5
"Sammy the Python moved #{meters}m."
'''
aether.transpile(code)
expect(aether.run()).toEqual "Sammy the Python moved 5m."
expect(aether.problems.errors).toEqual []
it "Should implicitly return the last statement", ->
aether.transpile('"hi"')
expect(aether.run()).toEqual 'hi'
expect(aether.problems.errors).toEqual []
describe "Errors", ->
aether = new Aether language: "coffeescript"
it "Bad indent", ->
code = """
fn = ->
x = 45
x += 5
return x
return fn()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
# TODO: No range information for this error
# https://github.com/codecombat/aether/issues/114
expect(aether.problems.errors[0].message.indexOf("Syntax error on line 5, column 10: unexpected '+'")).toBe(0)
it "Transpile error, missing )", ->
code = """
fn = ->
return 45
x = fn(
return x
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
# TODO: No range information for this error
# https://github.com/codecombat/aether/issues/114
expect(aether.problems.errors[0].message.indexOf("Unexpected DEDENT")).toBe(0)
xit "Missing @: x() row 0", ->
# TODO: error ranges incorrect
# https://github.com/codecombat/aether/issues/153
code = """x()"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 3, row: 0, col: 3 } ])
it "Missing @: x() row 1", ->
code = """
y = 5
x()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
# https://github.com/codecombat/aether/issues/115
# expect(aether.problems.errors[0].range).toEqual([ { ofs: 6, row: 1, col: 0 }, { ofs: 9, row: 1, col: 3 } ])
it "Missing @: x() row 3", ->
code = """
y = 5
s = 'some other stuff'
if y is 5
x()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
# https://github.com/codecombat/aether/issues/115
# expect(aether.problems.errors[0].range).toEqual([ { ofs: 42, row: 3, col: 2 }, { ofs: 45, row: 3, col: 5 } ])
xit "@getItems missing parentheses", ->
# https://github.com/codecombat/aether/issues/111
history = []
getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}]
move = (i) -> history.push i
thisValue = {getItems: getItems, move: move}
code = """
@getItems
"""
aether.transpile code
method = aether.createMethod thisValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual('@getItems has no effect.')
expect(aether.problems.errors[0].hint).toEqual('Is it a method? Those need parentheses: @getItems()')
expect(aether.problems.errors[0].range).toEqual([ { ofs : 0, row : 0, col : 0 }, { ofs : 10, row : 0, col : 10 } ])
xit "@getItems missing parentheses row 1", ->
# https://github.com/codecombat/aether/issues/110
history = []
getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}]
move = (i) -> history.push i
thisValue = {getItems: getItems, move: move}
code = """
x = 5
@getItems
y = 6
"""
aether.transpile code
method = aether.createMethod thisValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual('@getItems has no effect.')
expect(aether.problems.errors[0].hint).toEqual('Is it a method? Those need parentheses: @getItems()')
expect(aether.problems.errors[0].range).toEqual([ { ofs : 7, row : 1, col : 0 }, { ofs : 16, row : 1, col : 9 } ])
it "Incomplete string", ->
code = """
s = 'hi
return s
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Unclosed \"'\" at EOF")
# https://github.com/codecombat/aether/issues/114
# expect(aether.problems.errors[0].range).toEqual([ { ofs : 4, row : 0, col : 4 }, { ofs : 7, row : 0, col : 7 } ])
xit "Runtime ReferenceError", ->
# TODO: error ranges incorrect
# https://github.com/codecombat/aether/issues/153
code = """
x = 5
y = x + z
"""
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(/ReferenceError/.test(aether.problems.errors[0].message)).toBe(true)
expect(aether.problems.errors[0].range).toEqual([ { ofs : 14, row : 1, col : 8 }, { ofs : 15, row : 1, col : 9 } ])
| 145025 | Aether = require '../aether'
describe "CS test Suite!", ->
describe "CS compilation", ->
aether = new Aether language: "coffeescript"
it "Should compile functions", ->
code = """
return 1000
"""
aether.transpile(code)
expect(aether.run()).toEqual 1000
expect(aether.problems.errors).toEqual []
describe "CS compilation with lang set after contruction", ->
aether = new Aether()
it "Should compile functions", ->
code = """
return 2000 if false
return 1000
"""
aether.setLanguage "coffeescript"
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.problems.errors).toEqual []
describe "CS Test Spec #1", ->
aether = new Aether language: "coffeescript"
it "mathmetics order", ->
code = "
return (2*2 + 2/2 - 2*2/2)
"
aether.transpile(code)
expect(aether.run()).toEqual 3
expect(aether.problems.errors).toEqual []
describe "CS Test Spec #2", ->
aether = new Aether language: "coffeescript"
it "function call", ->
code = """
fib = (n) ->
(if n < 2 then n else fib(n - 1) + fib(n - 2))
chupacabra = fib(6)
"""
aether.transpile(code)
fn = aether.createFunction()
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 8 # fail
expect(aether.problems.errors).toEqual []
describe "Basics", ->
aether = new Aether language: "coffeescript"
it "Simple For", ->
code = """
count = 0
count++ for num in [1..10]
return count
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 10
expect(aether.problems.errors).toEqual []
it "Simple While", ->
code = """
count = 0
count++ until count is 100
return count
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 100
expect(aether.problems.errors).toEqual []
it "Should Map", ->
# See: https://github.com/codecombat/aether/issues/97
code = "return (num for num in [10..1])"
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
expect(aether.problems.errors).toEqual []
it "Should Map properties", ->
code = '''
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
return ages
'''
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual ["max is 10", "ida is 9", "tim is 11"]
expect(aether.problems.errors).toEqual []
it "Should compile empty function", ->
code = """
func = () ->
return typeof func
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 'function'
expect(aether.problems.errors).toEqual []
it "Should compile objects", ->
code = """
singers = {Jagger: 'Rock', Elvis: 'Roll'}
return singers
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual ({Jagger: 'Rock', Elvis: 'Roll'})
expect(aether.problems.errors).toEqual []
it "Should compile classes", ->
code = """
class MyClass
test: ->
return 1000
myClass = new MyClass()
return myClass.test()
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 1000
expect(aether.problems.errors).toEqual []
xit "Should compile super", ->
# super is not supported in CSR yet: https://github.com/michaelficarra/CoffeeScriptRedux/search?q=super&ref=cmdform&type=Issues
code = '''
class Animal
constructor: (@name) ->
move: (meters) ->
@name + " moved " + meters + "m."
class Snake extends Animal
move: ->
super 5
sam = new Snake "Sam<NAME> Python"
sam.move()
'''
aether.transpile(code)
expect(aether.run()).toEqual "Sammy the Python moved 5m."
expect(aether.problems.errors).toEqual []
it "Should compile string interpolation", ->
code = '''
meters = 5
"Sam<NAME> the Python moved #{meters}m."
'''
aether.transpile(code)
expect(aether.run()).toEqual "Sammy the Python moved 5m."
expect(aether.problems.errors).toEqual []
it "Should implicitly return the last statement", ->
aether.transpile('"hi"')
expect(aether.run()).toEqual 'hi'
expect(aether.problems.errors).toEqual []
describe "Errors", ->
aether = new Aether language: "coffeescript"
it "Bad indent", ->
code = """
fn = ->
x = 45
x += 5
return x
return fn()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
# TODO: No range information for this error
# https://github.com/codecombat/aether/issues/114
expect(aether.problems.errors[0].message.indexOf("Syntax error on line 5, column 10: unexpected '+'")).toBe(0)
it "Transpile error, missing )", ->
code = """
fn = ->
return 45
x = fn(
return x
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
# TODO: No range information for this error
# https://github.com/codecombat/aether/issues/114
expect(aether.problems.errors[0].message.indexOf("Unexpected DEDENT")).toBe(0)
xit "Missing @: x() row 0", ->
# TODO: error ranges incorrect
# https://github.com/codecombat/aether/issues/153
code = """x()"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 3, row: 0, col: 3 } ])
it "Missing @: x() row 1", ->
code = """
y = 5
x()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
# https://github.com/codecombat/aether/issues/115
# expect(aether.problems.errors[0].range).toEqual([ { ofs: 6, row: 1, col: 0 }, { ofs: 9, row: 1, col: 3 } ])
it "Missing @: x() row 3", ->
code = """
y = 5
s = 'some other stuff'
if y is 5
x()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
# https://github.com/codecombat/aether/issues/115
# expect(aether.problems.errors[0].range).toEqual([ { ofs: 42, row: 3, col: 2 }, { ofs: 45, row: 3, col: 5 } ])
xit "@getItems missing parentheses", ->
# https://github.com/codecombat/aether/issues/111
history = []
getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}]
move = (i) -> history.push i
thisValue = {getItems: getItems, move: move}
code = """
@getItems
"""
aether.transpile code
method = aether.createMethod thisValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual('@getItems has no effect.')
expect(aether.problems.errors[0].hint).toEqual('Is it a method? Those need parentheses: @getItems()')
expect(aether.problems.errors[0].range).toEqual([ { ofs : 0, row : 0, col : 0 }, { ofs : 10, row : 0, col : 10 } ])
xit "@getItems missing parentheses row 1", ->
# https://github.com/codecombat/aether/issues/110
history = []
getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}]
move = (i) -> history.push i
thisValue = {getItems: getItems, move: move}
code = """
x = 5
@getItems
y = 6
"""
aether.transpile code
method = aether.createMethod thisValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual('@getItems has no effect.')
expect(aether.problems.errors[0].hint).toEqual('Is it a method? Those need parentheses: @getItems()')
expect(aether.problems.errors[0].range).toEqual([ { ofs : 7, row : 1, col : 0 }, { ofs : 16, row : 1, col : 9 } ])
it "Incomplete string", ->
code = """
s = 'hi
return s
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Unclosed \"'\" at EOF")
# https://github.com/codecombat/aether/issues/114
# expect(aether.problems.errors[0].range).toEqual([ { ofs : 4, row : 0, col : 4 }, { ofs : 7, row : 0, col : 7 } ])
xit "Runtime ReferenceError", ->
# TODO: error ranges incorrect
# https://github.com/codecombat/aether/issues/153
code = """
x = 5
y = x + z
"""
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(/ReferenceError/.test(aether.problems.errors[0].message)).toBe(true)
expect(aether.problems.errors[0].range).toEqual([ { ofs : 14, row : 1, col : 8 }, { ofs : 15, row : 1, col : 9 } ])
| true | Aether = require '../aether'
describe "CS test Suite!", ->
describe "CS compilation", ->
aether = new Aether language: "coffeescript"
it "Should compile functions", ->
code = """
return 1000
"""
aether.transpile(code)
expect(aether.run()).toEqual 1000
expect(aether.problems.errors).toEqual []
describe "CS compilation with lang set after contruction", ->
aether = new Aether()
it "Should compile functions", ->
code = """
return 2000 if false
return 1000
"""
aether.setLanguage "coffeescript"
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.problems.errors).toEqual []
describe "CS Test Spec #1", ->
aether = new Aether language: "coffeescript"
it "mathmetics order", ->
code = "
return (2*2 + 2/2 - 2*2/2)
"
aether.transpile(code)
expect(aether.run()).toEqual 3
expect(aether.problems.errors).toEqual []
describe "CS Test Spec #2", ->
aether = new Aether language: "coffeescript"
it "function call", ->
code = """
fib = (n) ->
(if n < 2 then n else fib(n - 1) + fib(n - 2))
chupacabra = fib(6)
"""
aether.transpile(code)
fn = aether.createFunction()
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 8 # fail
expect(aether.problems.errors).toEqual []
describe "Basics", ->
aether = new Aether language: "coffeescript"
it "Simple For", ->
code = """
count = 0
count++ for num in [1..10]
return count
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 10
expect(aether.problems.errors).toEqual []
it "Simple While", ->
code = """
count = 0
count++ until count is 100
return count
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 100
expect(aether.problems.errors).toEqual []
it "Should Map", ->
# See: https://github.com/codecombat/aether/issues/97
code = "return (num for num in [10..1])"
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
expect(aether.problems.errors).toEqual []
it "Should Map properties", ->
code = '''
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
return ages
'''
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual ["max is 10", "ida is 9", "tim is 11"]
expect(aether.problems.errors).toEqual []
it "Should compile empty function", ->
code = """
func = () ->
return typeof func
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 'function'
expect(aether.problems.errors).toEqual []
it "Should compile objects", ->
code = """
singers = {Jagger: 'Rock', Elvis: 'Roll'}
return singers
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual ({Jagger: 'Rock', Elvis: 'Roll'})
expect(aether.problems.errors).toEqual []
it "Should compile classes", ->
code = """
class MyClass
test: ->
return 1000
myClass = new MyClass()
return myClass.test()
"""
aether.transpile(code)
expect(aether.canTranspile(code)).toEqual true
expect(aether.run()).toEqual 1000
expect(aether.problems.errors).toEqual []
xit "Should compile super", ->
# super is not supported in CSR yet: https://github.com/michaelficarra/CoffeeScriptRedux/search?q=super&ref=cmdform&type=Issues
code = '''
class Animal
constructor: (@name) ->
move: (meters) ->
@name + " moved " + meters + "m."
class Snake extends Animal
move: ->
super 5
sam = new Snake "SamPI:NAME:<NAME>END_PI Python"
sam.move()
'''
aether.transpile(code)
expect(aether.run()).toEqual "Sammy the Python moved 5m."
expect(aether.problems.errors).toEqual []
it "Should compile string interpolation", ->
code = '''
meters = 5
"SamPI:NAME:<NAME>END_PI the Python moved #{meters}m."
'''
aether.transpile(code)
expect(aether.run()).toEqual "Sammy the Python moved 5m."
expect(aether.problems.errors).toEqual []
it "Should implicitly return the last statement", ->
aether.transpile('"hi"')
expect(aether.run()).toEqual 'hi'
expect(aether.problems.errors).toEqual []
describe "Errors", ->
aether = new Aether language: "coffeescript"
it "Bad indent", ->
code = """
fn = ->
x = 45
x += 5
return x
return fn()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
# TODO: No range information for this error
# https://github.com/codecombat/aether/issues/114
expect(aether.problems.errors[0].message.indexOf("Syntax error on line 5, column 10: unexpected '+'")).toBe(0)
it "Transpile error, missing )", ->
code = """
fn = ->
return 45
x = fn(
return x
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
# TODO: No range information for this error
# https://github.com/codecombat/aether/issues/114
expect(aether.problems.errors[0].message.indexOf("Unexpected DEDENT")).toBe(0)
xit "Missing @: x() row 0", ->
# TODO: error ranges incorrect
# https://github.com/codecombat/aether/issues/153
code = """x()"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 3, row: 0, col: 3 } ])
it "Missing @: x() row 1", ->
code = """
y = 5
x()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
# https://github.com/codecombat/aether/issues/115
# expect(aether.problems.errors[0].range).toEqual([ { ofs: 6, row: 1, col: 0 }, { ofs: 9, row: 1, col: 3 } ])
it "Missing @: x() row 3", ->
code = """
y = 5
s = 'some other stuff'
if y is 5
x()
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Missing `@` keyword; should be `@x`.")
# https://github.com/codecombat/aether/issues/115
# expect(aether.problems.errors[0].range).toEqual([ { ofs: 42, row: 3, col: 2 }, { ofs: 45, row: 3, col: 5 } ])
xit "@getItems missing parentheses", ->
# https://github.com/codecombat/aether/issues/111
history = []
getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}]
move = (i) -> history.push i
thisValue = {getItems: getItems, move: move}
code = """
@getItems
"""
aether.transpile code
method = aether.createMethod thisValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual('@getItems has no effect.')
expect(aether.problems.errors[0].hint).toEqual('Is it a method? Those need parentheses: @getItems()')
expect(aether.problems.errors[0].range).toEqual([ { ofs : 0, row : 0, col : 0 }, { ofs : 10, row : 0, col : 10 } ])
xit "@getItems missing parentheses row 1", ->
# https://github.com/codecombat/aether/issues/110
history = []
getItems = -> [{'pos':1}, {'pos':4}, {'pos':3}, {'pos':5}]
move = (i) -> history.push i
thisValue = {getItems: getItems, move: move}
code = """
x = 5
@getItems
y = 6
"""
aether.transpile code
method = aether.createMethod thisValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual('@getItems has no effect.')
expect(aether.problems.errors[0].hint).toEqual('Is it a method? Those need parentheses: @getItems()')
expect(aether.problems.errors[0].range).toEqual([ { ofs : 7, row : 1, col : 0 }, { ofs : 16, row : 1, col : 9 } ])
it "Incomplete string", ->
code = """
s = 'hi
return s
"""
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Unclosed \"'\" at EOF")
# https://github.com/codecombat/aether/issues/114
# expect(aether.problems.errors[0].range).toEqual([ { ofs : 4, row : 0, col : 4 }, { ofs : 7, row : 0, col : 7 } ])
xit "Runtime ReferenceError", ->
# TODO: error ranges incorrect
# https://github.com/codecombat/aether/issues/153
code = """
x = 5
y = x + z
"""
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(/ReferenceError/.test(aether.problems.errors[0].message)).toBe(true)
expect(aether.problems.errors[0].range).toEqual([ { ofs : 14, row : 1, col : 8 }, { ofs : 15, row : 1, col : 9 } ])
|
[
{
"context": ".query -> mysql select where, order, limit\n@author Alex Suslov <suslov@me.com>\n@copyright MIT\n###\nQuery =\n quer",
"end": 90,
"score": 0.999589741230011,
"start": 79,
"tag": "NAME",
"value": "Alex Suslov"
},
{
"context": "l select where, order, limit\n@author Alex ... | coffee/index.coffee | alexsuslov/wc-sql-query | 0 | 'use strict'
###
Express req.query -> mysql select where, order, limit
@author Alex Suslov <suslov@me.com>
@copyright MIT
###
Query =
query:false
###
main
@param query[String] string from EXPRESS req
@return Object
where: String
order: String
limit: String
###
main:(@query, @types)->
@where = ''
@order = ''
# @todo: логические операции
# for name in ['or','and']
# @logical(name)
@sort().lim().opt()
# @order().limit().opt()
@
###
@param value[String] 'name=test'
@return Object {name:'test'}
###
expression:(value)->
data = value.split '='
ret = {}
ret[data[0]] = @parse data[1]
ret
#create logical function
# @param name[String] function name ['or','and']
# @return Object
logical:(name)->
if @query[name]
Arr = @query[name].split ','
if Arr.length
@conditions['$' + name] = (for value in Arr
@expression value)
delete @query[name]
@
parseVal:(val)->
return parseFloat val if @type is 'Number'
return !!val if @type is 'Boolean'
return new Date val if @type is 'Date'
"'#{val}'"
###
Clean regexp simbols
@param str[String] string to clean
@return [String] cleaning string
###
escapeRegExp: (str)->
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
###
Parse ~, !, ....
@param str[String] '!name'
@return Object condition value
###
parse:(str)->
tr = @_str str
eqv = (simbol, val)->
simbol + val
switch str[0]
# when '%'
# return $mod: tr.split '|' if str[0] is '%'
# # in
# return $in: tr.split '|' if str[0] is '@'
# # nin
# return $nin: tr.split '|' if str[0] is '#'
# gt
when '>'
eqv '>', @parseVal(tr)
# gte
when ']'
eqv '=>', @parseVal(tr)
# lt
when '<'
eqv '<', @parseVal(tr)
# lte
# return $lte: @parseVal tr if str[0] is
when '['
eqv '<=', @parseVal(tr)
# not eq
when '!'
eqv '!=', @parseVal(tr)
# Exists
# return "$exists": true if str is '+'
# return "$exists": false if str is '-'
# # ~
when '~'
" LIKE '%#{tr}%'"
# text
# return $text:$search:tr if str[0] is '$'
else
eqv '=', @parseVal(str)
###
Cut first char from string
@param str[String] '!test'
@return String 'test'
###
_str:(str)->
str.substr( 1 , str.length)
###
Create options from query
###
opt:->
if @query
comma = ''
for name of @query
@query[name] = decodeURI @query[name]
# detect type
@type = @detectType name
if @query[name]
nm = name
val = @parse @query[name]
@where += "#{comma}`#{nm}`#{val}"
comma = ' and '
@
detectType: (name)->
# return 'String' unless @types
return 'String' unless @types?[name]
@types[name].name
###
Create sort from query
###
sort:->
if @query.order
if @query.order[0] is '-'
@order = "#{@_str(@query.order)} DESC"
else
@order = "#{@query.order}"
delete @query.order
@
###
Create limit from query
###
lim:->
skip = parseInt @query.skip || 0
delete @query.skip
limit = parseInt @query.limit || 25
delete @query.limit
@limit = "#{skip}, #{limit}"
@
module.exports = (query, types)->
Query.main query, types
module.exports.Query = Query | 204689 | 'use strict'
###
Express req.query -> mysql select where, order, limit
@author <NAME> <<EMAIL>>
@copyright MIT
###
Query =
query:false
###
main
@param query[String] string from EXPRESS req
@return Object
where: String
order: String
limit: String
###
main:(@query, @types)->
@where = ''
@order = ''
# @todo: логические операции
# for name in ['or','and']
# @logical(name)
@sort().lim().opt()
# @order().limit().opt()
@
###
@param value[String] 'name=test'
@return Object {name:'test'}
###
expression:(value)->
data = value.split '='
ret = {}
ret[data[0]] = @parse data[1]
ret
#create logical function
# @param name[String] function name ['or','and']
# @return Object
logical:(name)->
if @query[name]
Arr = @query[name].split ','
if Arr.length
@conditions['$' + name] = (for value in Arr
@expression value)
delete @query[name]
@
parseVal:(val)->
return parseFloat val if @type is 'Number'
return !!val if @type is 'Boolean'
return new Date val if @type is 'Date'
"'#{val}'"
###
Clean regexp simbols
@param str[String] string to clean
@return [String] cleaning string
###
escapeRegExp: (str)->
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
###
Parse ~, !, ....
@param str[String] '!name'
@return Object condition value
###
parse:(str)->
tr = @_str str
eqv = (simbol, val)->
simbol + val
switch str[0]
# when '%'
# return $mod: tr.split '|' if str[0] is '%'
# # in
# return $in: tr.split '|' if str[0] is '@'
# # nin
# return $nin: tr.split '|' if str[0] is '#'
# gt
when '>'
eqv '>', @parseVal(tr)
# gte
when ']'
eqv '=>', @parseVal(tr)
# lt
when '<'
eqv '<', @parseVal(tr)
# lte
# return $lte: @parseVal tr if str[0] is
when '['
eqv '<=', @parseVal(tr)
# not eq
when '!'
eqv '!=', @parseVal(tr)
# Exists
# return "$exists": true if str is '+'
# return "$exists": false if str is '-'
# # ~
when '~'
" LIKE '%#{tr}%'"
# text
# return $text:$search:tr if str[0] is '$'
else
eqv '=', @parseVal(str)
###
Cut first char from string
@param str[String] '!test'
@return String 'test'
###
_str:(str)->
str.substr( 1 , str.length)
###
Create options from query
###
opt:->
if @query
comma = ''
for name of @query
@query[name] = decodeURI @query[name]
# detect type
@type = @detectType name
if @query[name]
nm = name
val = @parse @query[name]
@where += "#{comma}`#{nm}`#{val}"
comma = ' and '
@
detectType: (name)->
# return 'String' unless @types
return 'String' unless @types?[name]
@types[name].name
###
Create sort from query
###
sort:->
if @query.order
if @query.order[0] is '-'
@order = "#{@_str(@query.order)} DESC"
else
@order = "#{@query.order}"
delete @query.order
@
###
Create limit from query
###
lim:->
skip = parseInt @query.skip || 0
delete @query.skip
limit = parseInt @query.limit || 25
delete @query.limit
@limit = "#{skip}, #{limit}"
@
module.exports = (query, types)->
Query.main query, types
module.exports.Query = Query | true | 'use strict'
###
Express req.query -> mysql select where, order, limit
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@copyright MIT
###
Query =
query:false
###
main
@param query[String] string from EXPRESS req
@return Object
where: String
order: String
limit: String
###
main:(@query, @types)->
@where = ''
@order = ''
# @todo: логические операции
# for name in ['or','and']
# @logical(name)
@sort().lim().opt()
# @order().limit().opt()
@
###
@param value[String] 'name=test'
@return Object {name:'test'}
###
expression:(value)->
data = value.split '='
ret = {}
ret[data[0]] = @parse data[1]
ret
#create logical function
# @param name[String] function name ['or','and']
# @return Object
logical:(name)->
if @query[name]
Arr = @query[name].split ','
if Arr.length
@conditions['$' + name] = (for value in Arr
@expression value)
delete @query[name]
@
parseVal:(val)->
return parseFloat val if @type is 'Number'
return !!val if @type is 'Boolean'
return new Date val if @type is 'Date'
"'#{val}'"
###
Clean regexp simbols
@param str[String] string to clean
@return [String] cleaning string
###
escapeRegExp: (str)->
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
###
Parse ~, !, ....
@param str[String] '!name'
@return Object condition value
###
parse:(str)->
tr = @_str str
eqv = (simbol, val)->
simbol + val
switch str[0]
# when '%'
# return $mod: tr.split '|' if str[0] is '%'
# # in
# return $in: tr.split '|' if str[0] is '@'
# # nin
# return $nin: tr.split '|' if str[0] is '#'
# gt
when '>'
eqv '>', @parseVal(tr)
# gte
when ']'
eqv '=>', @parseVal(tr)
# lt
when '<'
eqv '<', @parseVal(tr)
# lte
# return $lte: @parseVal tr if str[0] is
when '['
eqv '<=', @parseVal(tr)
# not eq
when '!'
eqv '!=', @parseVal(tr)
# Exists
# return "$exists": true if str is '+'
# return "$exists": false if str is '-'
# # ~
when '~'
" LIKE '%#{tr}%'"
# text
# return $text:$search:tr if str[0] is '$'
else
eqv '=', @parseVal(str)
###
Cut first char from string
@param str[String] '!test'
@return String 'test'
###
_str:(str)->
str.substr( 1 , str.length)
###
Create options from query
###
opt:->
if @query
comma = ''
for name of @query
@query[name] = decodeURI @query[name]
# detect type
@type = @detectType name
if @query[name]
nm = name
val = @parse @query[name]
@where += "#{comma}`#{nm}`#{val}"
comma = ' and '
@
detectType: (name)->
# return 'String' unless @types
return 'String' unless @types?[name]
@types[name].name
###
Create sort from query
###
sort:->
if @query.order
if @query.order[0] is '-'
@order = "#{@_str(@query.order)} DESC"
else
@order = "#{@query.order}"
delete @query.order
@
###
Create limit from query
###
lim:->
skip = parseInt @query.skip || 0
delete @query.skip
limit = parseInt @query.limit || 25
delete @query.limit
@limit = "#{skip}, #{limit}"
@
module.exports = (query, types)->
Query.main query, types
module.exports.Query = Query |
[
{
"context": "oap\"\n\ncompJID = \"comp.exmaple.tld\"\nclientJID = \"client@exmaple.tld\"\n\nmockComp =\n channels: {}\n send: (data) ->\n ",
"end": 347,
"score": 0.9998481273651123,
"start": 329,
"tag": "EMAIL",
"value": "client@exmaple.tld"
},
{
"context": " new ltx.Element \... | spec/Application.spec.coffee | flosse/node-xmpp-joap | 0 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use sinonChai
should = chai.should()
ltx = require 'ltx'
Application = require '../src/Application'
{ JID } = require "node-xmpp-core"
JOAP_NS = "jabber:iq:joap"
compJID = "comp.exmaple.tld"
clientJID = "client@exmaple.tld"
mockComp =
channels: {}
send: (data) ->
process.nextTick -> mockClient.onData data
onData: (data) ->
on: (channel, cb) ->
@channels[channel] = cb
connection: jid: new JID compJID
mockClient =
send: (data) ->
process.nextTick -> mockComp.channels.stanza data
onData: (data) ->
describe "Application", ->
beforeEach ->
mockClient.onData = ->
@app = new Application mockComp
@req = new ltx.Element "iq",
id:"test"
to: "class@comp.example.tld"
from: "user@example.tld"
type:'set'
@req.c "describe", xmlns:JOAP_NS
@addReq = new ltx.Element "iq",
id:"add"
to: "class@comp.example.tld"
from: "user@example.tld"
type:'set'
@addReq.c "add", xmlns:JOAP_NS
it "is a function", ->
Application.should.be.a.function
it "takes a xmpp component as first argumen", ->
(-> new Application).should.throw()
(-> new Application {connection:{}}).should.throw()
(-> new Application mockComp).should.not.throw()
(new Application mockComp).xmpp.should.equal mockComp
describe "'use' method", ->
it "is a function", ->
Application::use.should.be.a.function
@app.use.should.be.a.function
it "takes a function that gets called on every received message", (done) ->
spy = new sinon.spy()
cb = (req, res, next) ->
spy()
next()
@app.use cb
i = 0
@app.use (req, res, next) ->
if ++i is 2
spy.should.have.been.calledTwice
done()
mockClient.send @req
mockClient.send @req
it "runs the functions asynchonously and in series", (done) ->
cb1 = new sinon.spy()
cb2 = new sinon.spy()
@app.use (req, res, next) ->
cb2.should.not.have.been.called
cb1()
next()
@app.use (req, res, next) ->
cb1.should.have.been.calledOnce
cb2.should.not.have.been.called
cb2()
next()
@app.use (req, res, next) ->
cb1.should.have.been.calledOnce
cb2.should.have.been.calledOnce
done()
mockClient.send @req
it "passes the request and result objects", (done) ->
@app.use (req, res, next) ->
req.foo = "bar"
res.bar = 99
next()
@app.use (req, res, next) ->
req.foo.should.equal "bar"
res.bar.should.equal 99
next()
done()
mockClient.send @req
describe "'add' method", ->
it "is a function", ->
Application::add.should.be.a.function
@app.add.should.be.a.function
it "takes a function that gets called on an 'add' request", (done) ->
@app.add (req, res, next) ->
req.type.should.equal 'add'
next()
done()
mockClient.send @addReq
it "only calles the function on an 'add' request", (done) ->
cb = new sinon.spy()
@app.add (req, res, next) ->
cb()
next()
cb.should.have.been.calledOnce
done()
mockClient.send @req
mockClient.send @addReq
describe "result object", ->
it "has an end method", (done) ->
@app.use (req, res, next) ->
res.end.should.be.a.function
done()
mockClient.send @req
it "has a error method", (done) ->
@app.use (req, res, next) ->
res.error.should.be.a.function
res.error new Error "foo"
mockClient.send @req
mockClient.onData = (data) ->
data.children[1].name.should.equal 'error'
done()
| 215362 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use sinonChai
should = chai.should()
ltx = require 'ltx'
Application = require '../src/Application'
{ JID } = require "node-xmpp-core"
JOAP_NS = "jabber:iq:joap"
compJID = "comp.exmaple.tld"
clientJID = "<EMAIL>"
mockComp =
channels: {}
send: (data) ->
process.nextTick -> mockClient.onData data
onData: (data) ->
on: (channel, cb) ->
@channels[channel] = cb
connection: jid: new JID compJID
mockClient =
send: (data) ->
process.nextTick -> mockComp.channels.stanza data
onData: (data) ->
describe "Application", ->
beforeEach ->
mockClient.onData = ->
@app = new Application mockComp
@req = new ltx.Element "iq",
id:"test"
to: "<EMAIL>"
from: "<EMAIL>"
type:'set'
@req.c "describe", xmlns:JOAP_NS
@addReq = new ltx.Element "iq",
id:"add"
to: "<EMAIL>"
from: "<EMAIL>"
type:'set'
@addReq.c "add", xmlns:JOAP_NS
it "is a function", ->
Application.should.be.a.function
it "takes a xmpp component as first argumen", ->
(-> new Application).should.throw()
(-> new Application {connection:{}}).should.throw()
(-> new Application mockComp).should.not.throw()
(new Application mockComp).xmpp.should.equal mockComp
describe "'use' method", ->
it "is a function", ->
Application::use.should.be.a.function
@app.use.should.be.a.function
it "takes a function that gets called on every received message", (done) ->
spy = new sinon.spy()
cb = (req, res, next) ->
spy()
next()
@app.use cb
i = 0
@app.use (req, res, next) ->
if ++i is 2
spy.should.have.been.calledTwice
done()
mockClient.send @req
mockClient.send @req
it "runs the functions asynchonously and in series", (done) ->
cb1 = new sinon.spy()
cb2 = new sinon.spy()
@app.use (req, res, next) ->
cb2.should.not.have.been.called
cb1()
next()
@app.use (req, res, next) ->
cb1.should.have.been.calledOnce
cb2.should.not.have.been.called
cb2()
next()
@app.use (req, res, next) ->
cb1.should.have.been.calledOnce
cb2.should.have.been.calledOnce
done()
mockClient.send @req
it "passes the request and result objects", (done) ->
@app.use (req, res, next) ->
req.foo = "bar"
res.bar = 99
next()
@app.use (req, res, next) ->
req.foo.should.equal "bar"
res.bar.should.equal 99
next()
done()
mockClient.send @req
describe "'add' method", ->
it "is a function", ->
Application::add.should.be.a.function
@app.add.should.be.a.function
it "takes a function that gets called on an 'add' request", (done) ->
@app.add (req, res, next) ->
req.type.should.equal 'add'
next()
done()
mockClient.send @addReq
it "only calles the function on an 'add' request", (done) ->
cb = new sinon.spy()
@app.add (req, res, next) ->
cb()
next()
cb.should.have.been.calledOnce
done()
mockClient.send @req
mockClient.send @addReq
describe "result object", ->
it "has an end method", (done) ->
@app.use (req, res, next) ->
res.end.should.be.a.function
done()
mockClient.send @req
it "has a error method", (done) ->
@app.use (req, res, next) ->
res.error.should.be.a.function
res.error new Error "foo"
mockClient.send @req
mockClient.onData = (data) ->
data.children[1].name.should.equal 'error'
done()
| true | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use sinonChai
should = chai.should()
ltx = require 'ltx'
Application = require '../src/Application'
{ JID } = require "node-xmpp-core"
JOAP_NS = "jabber:iq:joap"
compJID = "comp.exmaple.tld"
clientJID = "PI:EMAIL:<EMAIL>END_PI"
mockComp =
channels: {}
send: (data) ->
process.nextTick -> mockClient.onData data
onData: (data) ->
on: (channel, cb) ->
@channels[channel] = cb
connection: jid: new JID compJID
mockClient =
send: (data) ->
process.nextTick -> mockComp.channels.stanza data
onData: (data) ->
describe "Application", ->
beforeEach ->
mockClient.onData = ->
@app = new Application mockComp
@req = new ltx.Element "iq",
id:"test"
to: "PI:EMAIL:<EMAIL>END_PI"
from: "PI:EMAIL:<EMAIL>END_PI"
type:'set'
@req.c "describe", xmlns:JOAP_NS
@addReq = new ltx.Element "iq",
id:"add"
to: "PI:EMAIL:<EMAIL>END_PI"
from: "PI:EMAIL:<EMAIL>END_PI"
type:'set'
@addReq.c "add", xmlns:JOAP_NS
it "is a function", ->
Application.should.be.a.function
it "takes a xmpp component as first argumen", ->
(-> new Application).should.throw()
(-> new Application {connection:{}}).should.throw()
(-> new Application mockComp).should.not.throw()
(new Application mockComp).xmpp.should.equal mockComp
describe "'use' method", ->
it "is a function", ->
Application::use.should.be.a.function
@app.use.should.be.a.function
it "takes a function that gets called on every received message", (done) ->
spy = new sinon.spy()
cb = (req, res, next) ->
spy()
next()
@app.use cb
i = 0
@app.use (req, res, next) ->
if ++i is 2
spy.should.have.been.calledTwice
done()
mockClient.send @req
mockClient.send @req
it "runs the functions asynchonously and in series", (done) ->
cb1 = new sinon.spy()
cb2 = new sinon.spy()
@app.use (req, res, next) ->
cb2.should.not.have.been.called
cb1()
next()
@app.use (req, res, next) ->
cb1.should.have.been.calledOnce
cb2.should.not.have.been.called
cb2()
next()
@app.use (req, res, next) ->
cb1.should.have.been.calledOnce
cb2.should.have.been.calledOnce
done()
mockClient.send @req
it "passes the request and result objects", (done) ->
@app.use (req, res, next) ->
req.foo = "bar"
res.bar = 99
next()
@app.use (req, res, next) ->
req.foo.should.equal "bar"
res.bar.should.equal 99
next()
done()
mockClient.send @req
describe "'add' method", ->
it "is a function", ->
Application::add.should.be.a.function
@app.add.should.be.a.function
it "takes a function that gets called on an 'add' request", (done) ->
@app.add (req, res, next) ->
req.type.should.equal 'add'
next()
done()
mockClient.send @addReq
it "only calles the function on an 'add' request", (done) ->
cb = new sinon.spy()
@app.add (req, res, next) ->
cb()
next()
cb.should.have.been.calledOnce
done()
mockClient.send @req
mockClient.send @addReq
describe "result object", ->
it "has an end method", (done) ->
@app.use (req, res, next) ->
res.end.should.be.a.function
done()
mockClient.send @req
it "has a error method", (done) ->
@app.use (req, res, next) ->
res.error.should.be.a.function
res.error new Error "foo"
mockClient.send @req
mockClient.onData = (data) ->
data.children[1].name.should.equal 'error'
done()
|
[
{
"context": "r c in [0 ... num]\n i += 1\n name = 'キャラクター ' + i\n characters.push\n name: ",
"end": 3178,
"score": 0.9953145384788513,
"start": 3172,
"tag": "NAME",
"value": "キャラクター"
}
] | src/main/coffeescript/nz/SceneTitleMenu.coffee | fukuyama/nineteen | 2 | ###*
* @file SceneTitleMenu.coffee
* タイトルシーン
###
phina.define 'nz.SceneTitleMenu',
superClass: nz.SceneBase
###* 初期化
* @classdesc タイトルシーンクラス
* @constructor nz.SceneTitleMenu
###
init: (options) ->
@superInit(options)
@one 'enter', ->
@_main_menu()
return
#@on 'resume', ->
# @_sample_game()
# return
return
_main_menu: ->
menus = [{
# name: 'New Game'
# description: '新しいゲームをはじめる'
# func: @_new_game
#},{
# name: 'Sample Game'
# description: 'サンプルゲームをはじめる'
# func: @_sample_game
#},{
text: 'Debug Game'
description: 'デバッグゲームをはじめる'
fn: @_debug_game.bind @
},{
text: 'Load Game'
description: '保存したゲームをはじめる'
fn: @_load_game.bind @
},{
text: 'Option'
description: 'ゲームオプション'
fn: @_option.bind @
}]
@openMenuDialog
title: 'title'
menus: menus
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_new_game: ->
@app.replaceScene nz.SceneBattle(
mapId: 1
controlTeam: ['teamA']
characters: [
{text:'キャラクター1',team:'teamA'}
{text:'キャラクター2',team:'teamA'}
{text:'キャラクター3',team:'teamA'}
{text:'キャラクター4',team:'teamB'}
{text:'キャラクター5',team:'teamB'}
{text:'キャラクター6',team:'teamB'}
]
)
return
###* ゲームをロード
* @memberof nz.SceneTitleMenu#
###
_load_game: ->
console.log 'load game'
return
###* システムオプション
* @memberof nz.SceneTitleMenu#
###
_option: ->
console.log 'option'
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_sample_game: ->
menu = [{
text: 'Player vs Computer'
description: 'プレイヤー 対 コンピューター'
func: -> @_sample_game_2 true
},{
text: 'Computer vs Computer'
description: 'コンピューター 対 コンピューター'
func: -> @_sample_game_2 false
}]
@openMenuDialog
self: @
title: 'サンプルゲーム'
menu: menu
return
_sample_game_2: (flag) ->
menu = [{
text: '1 vs 1'
description: '1 対 1'
func: -> @_generate_game
player: flag
team: [1,1]
mapId: 0
},{
text: '3 vs 3'
description: '3 対 3'
func: -> @_generate_game
player: flag
team: [3,3]
mapId: 0
},{
text: 'Return'
description: '戻る'
func: -> @_sample_game()
}]
@openMenuDialog
self: @
title: 'サンプルゲーム'
menu: menu
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_debug_game: ->
@exit 'battle',
mapId : 0
characters : [1,{}]
teams :
teamA : [1]
teamB : [2]
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_generate_game: (param)->
{
player
team
mapId
} = {
player: true
mapId: 0
}.$extend param
ai = ['Shooter','Chaser','Runner']
#ai = ['Runner']
teamColors = nz.system.team.colors.clone().shuffle()
i = 0
characters = []
for num,n in team
teamName = 'team ' + (n + 1)
teamColor = teamColors.pop()
for c in [0 ... num]
i += 1
name = 'キャラクター ' + i
characters.push
name: name
team: teamName
teamColor: teamColor
ai:
name: ai.random()
controlTeam = []
controlTeam.push 'team 1' if player
@app.replaceScene nz.SceneBattle
mapId: mapId
controlTeam: controlTeam
characters: characters
#endCondition:
# type: 'time'
# turn: 1
return
| 91742 | ###*
* @file SceneTitleMenu.coffee
* タイトルシーン
###
phina.define 'nz.SceneTitleMenu',
superClass: nz.SceneBase
###* 初期化
* @classdesc タイトルシーンクラス
* @constructor nz.SceneTitleMenu
###
init: (options) ->
@superInit(options)
@one 'enter', ->
@_main_menu()
return
#@on 'resume', ->
# @_sample_game()
# return
return
_main_menu: ->
menus = [{
# name: 'New Game'
# description: '新しいゲームをはじめる'
# func: @_new_game
#},{
# name: 'Sample Game'
# description: 'サンプルゲームをはじめる'
# func: @_sample_game
#},{
text: 'Debug Game'
description: 'デバッグゲームをはじめる'
fn: @_debug_game.bind @
},{
text: 'Load Game'
description: '保存したゲームをはじめる'
fn: @_load_game.bind @
},{
text: 'Option'
description: 'ゲームオプション'
fn: @_option.bind @
}]
@openMenuDialog
title: 'title'
menus: menus
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_new_game: ->
@app.replaceScene nz.SceneBattle(
mapId: 1
controlTeam: ['teamA']
characters: [
{text:'キャラクター1',team:'teamA'}
{text:'キャラクター2',team:'teamA'}
{text:'キャラクター3',team:'teamA'}
{text:'キャラクター4',team:'teamB'}
{text:'キャラクター5',team:'teamB'}
{text:'キャラクター6',team:'teamB'}
]
)
return
###* ゲームをロード
* @memberof nz.SceneTitleMenu#
###
_load_game: ->
console.log 'load game'
return
###* システムオプション
* @memberof nz.SceneTitleMenu#
###
_option: ->
console.log 'option'
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_sample_game: ->
menu = [{
text: 'Player vs Computer'
description: 'プレイヤー 対 コンピューター'
func: -> @_sample_game_2 true
},{
text: 'Computer vs Computer'
description: 'コンピューター 対 コンピューター'
func: -> @_sample_game_2 false
}]
@openMenuDialog
self: @
title: 'サンプルゲーム'
menu: menu
return
_sample_game_2: (flag) ->
menu = [{
text: '1 vs 1'
description: '1 対 1'
func: -> @_generate_game
player: flag
team: [1,1]
mapId: 0
},{
text: '3 vs 3'
description: '3 対 3'
func: -> @_generate_game
player: flag
team: [3,3]
mapId: 0
},{
text: 'Return'
description: '戻る'
func: -> @_sample_game()
}]
@openMenuDialog
self: @
title: 'サンプルゲーム'
menu: menu
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_debug_game: ->
@exit 'battle',
mapId : 0
characters : [1,{}]
teams :
teamA : [1]
teamB : [2]
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_generate_game: (param)->
{
player
team
mapId
} = {
player: true
mapId: 0
}.$extend param
ai = ['Shooter','Chaser','Runner']
#ai = ['Runner']
teamColors = nz.system.team.colors.clone().shuffle()
i = 0
characters = []
for num,n in team
teamName = 'team ' + (n + 1)
teamColor = teamColors.pop()
for c in [0 ... num]
i += 1
name = '<NAME> ' + i
characters.push
name: name
team: teamName
teamColor: teamColor
ai:
name: ai.random()
controlTeam = []
controlTeam.push 'team 1' if player
@app.replaceScene nz.SceneBattle
mapId: mapId
controlTeam: controlTeam
characters: characters
#endCondition:
# type: 'time'
# turn: 1
return
| true | ###*
* @file SceneTitleMenu.coffee
* タイトルシーン
###
phina.define 'nz.SceneTitleMenu',
superClass: nz.SceneBase
###* 初期化
* @classdesc タイトルシーンクラス
* @constructor nz.SceneTitleMenu
###
init: (options) ->
@superInit(options)
@one 'enter', ->
@_main_menu()
return
#@on 'resume', ->
# @_sample_game()
# return
return
_main_menu: ->
menus = [{
# name: 'New Game'
# description: '新しいゲームをはじめる'
# func: @_new_game
#},{
# name: 'Sample Game'
# description: 'サンプルゲームをはじめる'
# func: @_sample_game
#},{
text: 'Debug Game'
description: 'デバッグゲームをはじめる'
fn: @_debug_game.bind @
},{
text: 'Load Game'
description: '保存したゲームをはじめる'
fn: @_load_game.bind @
},{
text: 'Option'
description: 'ゲームオプション'
fn: @_option.bind @
}]
@openMenuDialog
title: 'title'
menus: menus
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_new_game: ->
@app.replaceScene nz.SceneBattle(
mapId: 1
controlTeam: ['teamA']
characters: [
{text:'キャラクター1',team:'teamA'}
{text:'キャラクター2',team:'teamA'}
{text:'キャラクター3',team:'teamA'}
{text:'キャラクター4',team:'teamB'}
{text:'キャラクター5',team:'teamB'}
{text:'キャラクター6',team:'teamB'}
]
)
return
###* ゲームをロード
* @memberof nz.SceneTitleMenu#
###
_load_game: ->
console.log 'load game'
return
###* システムオプション
* @memberof nz.SceneTitleMenu#
###
_option: ->
console.log 'option'
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_sample_game: ->
menu = [{
text: 'Player vs Computer'
description: 'プレイヤー 対 コンピューター'
func: -> @_sample_game_2 true
},{
text: 'Computer vs Computer'
description: 'コンピューター 対 コンピューター'
func: -> @_sample_game_2 false
}]
@openMenuDialog
self: @
title: 'サンプルゲーム'
menu: menu
return
_sample_game_2: (flag) ->
menu = [{
text: '1 vs 1'
description: '1 対 1'
func: -> @_generate_game
player: flag
team: [1,1]
mapId: 0
},{
text: '3 vs 3'
description: '3 対 3'
func: -> @_generate_game
player: flag
team: [3,3]
mapId: 0
},{
text: 'Return'
description: '戻る'
func: -> @_sample_game()
}]
@openMenuDialog
self: @
title: 'サンプルゲーム'
menu: menu
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_debug_game: ->
@exit 'battle',
mapId : 0
characters : [1,{}]
teams :
teamA : [1]
teamB : [2]
return
###* 新しいゲームを開始
* @memberof nz.SceneTitleMenu#
###
_generate_game: (param)->
{
player
team
mapId
} = {
player: true
mapId: 0
}.$extend param
ai = ['Shooter','Chaser','Runner']
#ai = ['Runner']
teamColors = nz.system.team.colors.clone().shuffle()
i = 0
characters = []
for num,n in team
teamName = 'team ' + (n + 1)
teamColor = teamColors.pop()
for c in [0 ... num]
i += 1
name = 'PI:NAME:<NAME>END_PI ' + i
characters.push
name: name
team: teamName
teamColor: teamColor
ai:
name: ai.random()
controlTeam = []
controlTeam.push 'team 1' if player
@app.replaceScene nz.SceneBattle
mapId: mapId
controlTeam: controlTeam
characters: characters
#endCondition:
# type: 'time'
# turn: 1
return
|
[
{
"context": ".addprinc\n admin: krb5\n principal: \"nikita@#{krb5.realm}\"\n .should.be.rejectedWith\n ",
"end": 844,
"score": 0.9476397037506104,
"start": 838,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": " await @krb5.delprinc\n principal... | packages/krb5/test/addprinc.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 0 |
nikita = require '@nikitajs/core/lib'
{tags, config, krb5} = require './test'
they = require('mocha-they')(config)
return unless tags.krb5_addprinc
describe 'krb5.addprinc', ->
describe 'schema', ->
it 'admin and principal must be provided', ->
nikita
.krb5.addprinc
randkey: true
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.addprinc`:'
'#/required config must have required property \'admin\';'
'#/required config must have required property \'principal\'.'
].join ' '
it 'one of password or randkey must be provided', ->
nikita
.krb5.addprinc
admin: krb5
principal: "nikita@#{krb5.realm}"
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.addprinc`:'
'#/oneOf config must match exactly one schema in oneOf, passingSchemas is null;'
'#/oneOf/0/required config must have required property \'password\';'
'#/oneOf/1/required config must have required property \'randkey\'.'
].join ' '
describe 'action', ->
they 'create a new principal with a randkey', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nikita@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
randkey: true
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
randkey: true
$status.should.be.false()
they 'create a new principal with a password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nikita@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'password1'
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'password2'
password_sync: true
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'password2'
password_sync: true
$status.should.be.false()
they 'dont overwrite password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nikita@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'password1'
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'password2'
password_sync: false # Default
$status.should.be.false()
await @execute
command: "echo password1 | kinit nikita@#{krb5.realm}"
they 'call function with new style', ({ssh}) ->
user =
password: 'user123'
password_sync: true
principal: 'user2@NODE.DC1.CONSUL'
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @fs.remove
target: '/etc/security/keytabs/user1.service.keytab'
await @krb5.delprinc
principal: user.principal
await @krb5.delprinc
principal: "user1/krb5@NODE.DC1.CONSUL"
await @krb5.addprinc
principal: "user1/krb5@NODE.DC1.CONSUL"
randkey: true
keytab: '/etc/security/keytabs/user1.service.keytab'
{$status} = await @krb5.addprinc user
$status.should.be.true()
{$status} = await @execute
command: "echo #{user.password} | kinit #{user.principal}"
$status.should.be.true()
| 215391 |
nikita = require '@nikitajs/core/lib'
{tags, config, krb5} = require './test'
they = require('mocha-they')(config)
return unless tags.krb5_addprinc
describe 'krb5.addprinc', ->
describe 'schema', ->
it 'admin and principal must be provided', ->
nikita
.krb5.addprinc
randkey: true
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.addprinc`:'
'#/required config must have required property \'admin\';'
'#/required config must have required property \'principal\'.'
].join ' '
it 'one of password or randkey must be provided', ->
nikita
.krb5.addprinc
admin: krb5
principal: "<EMAIL>@#{krb5.realm}"
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.addprinc`:'
'#/oneOf config must match exactly one schema in oneOf, passingSchemas is null;'
'#/oneOf/0/required config must have required property \'password\';'
'#/oneOf/1/required config must have required property \'randkey\'.'
].join ' '
describe 'action', ->
they 'create a new principal with a randkey', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "<EMAIL>@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "<EMAIL>@#{krb5.<EMAIL>}"
randkey: true
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "<EMAIL>@#{krb5.<EMAIL>}"
randkey: true
$status.should.be.false()
they 'create a new principal with a password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nik<EMAIL>@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: '<PASSWORD>'
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nik<EMAIL>@#{krb5.realm}"
password: '<PASSWORD>'
password_sync: true
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita<EMAIL>@#{krb5.realm}"
password: '<PASSWORD>'
password_sync: true
$status.should.be.false()
they 'dont overwrite password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nik<EMAIL>@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nik<EMAIL>@#{krb5.realm}"
password: '<PASSWORD>'
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: '<PASSWORD>'
password_sync: false # Default
$status.should.be.false()
await @execute
command: "echo <PASSWORD>1 | kinit nikita@#{krb5.realm}"
they 'call function with new style', ({ssh}) ->
user =
password: '<PASSWORD>'
password_sync: true
principal: 'user2@NODE.DC1.CONSUL'
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @fs.remove
target: '/etc/security/keytabs/user1.service.keytab'
await @krb5.delprinc
principal: user.principal
await @krb5.delprinc
principal: "user1/krb5@NODE.DC1.CONSUL"
await @krb5.addprinc
principal: "user1/krb5@NODE.DC1.CONSUL"
randkey: true
keytab: '/etc/security/keytabs/user1.service.keytab'
{$status} = await @krb5.addprinc user
$status.should.be.true()
{$status} = await @execute
command: "echo #{user.password} | kinit #{user.principal}"
$status.should.be.true()
| true |
nikita = require '@nikitajs/core/lib'
{tags, config, krb5} = require './test'
they = require('mocha-they')(config)
return unless tags.krb5_addprinc
describe 'krb5.addprinc', ->
describe 'schema', ->
it 'admin and principal must be provided', ->
nikita
.krb5.addprinc
randkey: true
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.addprinc`:'
'#/required config must have required property \'admin\';'
'#/required config must have required property \'principal\'.'
].join ' '
it 'one of password or randkey must be provided', ->
nikita
.krb5.addprinc
admin: krb5
principal: "PI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.addprinc`:'
'#/oneOf config must match exactly one schema in oneOf, passingSchemas is null;'
'#/oneOf/0/required config must have required property \'password\';'
'#/oneOf/1/required config must have required property \'randkey\'.'
].join ' '
describe 'action', ->
they 'create a new principal with a randkey', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{krb5.PI:EMAIL:<EMAIL>END_PI}"
randkey: true
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{krb5.PI:EMAIL:<EMAIL>END_PI}"
randkey: true
$status.should.be.false()
they 'create a new principal with a password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_sync: true
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikitaPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_sync: true
$status.should.be.false()
they 'dont overwrite password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
{$status} = await @krb5.addprinc
principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
$status.should.be.true()
{$status} = await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_sync: false # Default
$status.should.be.false()
await @execute
command: "echo PI:PASSWORD:<PASSWORD>END_PI1 | kinit nikita@#{krb5.realm}"
they 'call function with new style', ({ssh}) ->
user =
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_sync: true
principal: 'user2@NODE.DC1.CONSUL'
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @fs.remove
target: '/etc/security/keytabs/user1.service.keytab'
await @krb5.delprinc
principal: user.principal
await @krb5.delprinc
principal: "user1/krb5@NODE.DC1.CONSUL"
await @krb5.addprinc
principal: "user1/krb5@NODE.DC1.CONSUL"
randkey: true
keytab: '/etc/security/keytabs/user1.service.keytab'
{$status} = await @krb5.addprinc user
$status.should.be.true()
{$status} = await @execute
command: "echo #{user.password} | kinit #{user.principal}"
$status.should.be.true()
|
[
{
"context": "e label tags have an associated control.\n# @author Jesse Beach\n###\n\n# ------------------------------------------",
"end": 113,
"score": 0.9998565912246704,
"start": 102,
"tag": "NAME",
"value": "Jesse Beach"
}
] | src/tests/rules/label-has-associated-control.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce label tags have an associated control.
# @author Jesse Beach
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/label-has-associated-control'
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleName = 'label-has-associated-control'
expectedError =
message: 'A form label must be associated with a control.'
type: 'JSXOpeningElement'
htmlForValid = [
code:
'<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>'
options: [depth: 4]
,
code: '<label htmlFor="js_id" aria-label="A label" />'
,
code: '<label htmlFor="js_id" aria-labelledby="A label" />'
,
# Custom label component.
code: '<CustomLabel htmlFor="js_id" aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
,
code: '<CustomLabel htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label']]
]
nestingValid = [
code: '<label>A label<input /></label>'
,
code: '<label>A label<textarea /></label>'
,
code: '<label><img alt="A label" /><input /></label>'
,
code: '<label><img aria-label="A label" /><input /></label>'
,
code: '<label><span>A label<input /></span></label>'
,
code: '<label><span><span>A label<input /></span></span></label>'
options: [depth: 3]
,
code: '<label><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
,
code:
'<label><span><span><span><span>A label</span><input /></span></span></span></label>'
options: [depth: 5]
,
code:
'<label><span><span><span><span aria-label="A label" /><input /></span></span></span></label>'
options: [depth: 5]
,
code:
'<label><span><span><span><input aria-label="A label" /></span></span></span></label>'
options: [depth: 5]
,
# Custom controlComponents.
code: '<label><span>A label<CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
,
code: '<CustomLabel><span>A label<CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
,
code:
'<CustomLabel><span label="A label"><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
]
bothValid = [
code:
'<label htmlFor="js_id"><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
,
code: '<label htmlFor="js_id" aria-label="A label"><input /></label>'
,
code: '<label htmlFor="js_id" aria-labelledby="A label"><input /></label>'
,
code: '<label htmlFor="js_id" aria-labelledby="A label"><textarea /></label>'
,
# Custom label component.
code:
'<CustomLabel htmlFor="js_id" aria-label="A label"><input /></CustomLabel>'
options: [labelComponents: ['CustomLabel']]
,
code: '<CustomLabel htmlFor="js_id" label="A label"><input /></CustomLabel>'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label"><input /></label>'
options: [labelAttributes: ['label']]
,
code:
'<label htmlFor="selectInput">Some text<select id="selectInput" /></label>'
]
alwaysValid = [{code: '<div />'}, {code: '<CustomElement />'}]
htmlForInvalid = [
code:
'<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>'
options: [depth: 4]
errors: [expectedError]
,
code: '<label htmlFor="js_id" aria-label="A label" />'
errors: [expectedError]
,
code: '<label htmlFor="js_id" aria-labelledby="A label" />'
errors: [expectedError]
,
# Custom label component.
code: '<CustomLabel htmlFor="js_id" aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
errors: [expectedError]
,
code: '<CustomLabel htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
errors: [expectedError]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label']]
errors: [expectedError]
]
nestingInvalid = [
code: '<label>A label<input /></label>', errors: [expectedError]
,
code: '<label>A label<textarea /></label>', errors: [expectedError]
,
code: '<label><img alt="A label" /><input /></label>', errors: [expectedError]
,
code: '<label><img aria-label="A label" /><input /></label>'
errors: [expectedError]
,
code: '<label><span>A label<input /></span></label>', errors: [expectedError]
,
code: '<label><span><span>A label<input /></span></span></label>'
options: [depth: 3]
errors: [expectedError]
,
code: '<label><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
errors: [expectedError]
,
code:
'<label><span><span><span><span>A label</span><input /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
code:
'<label><span><span><span><span aria-label="A label" /><input /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
code:
'<label><span><span><span><input aria-label="A label" /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
# Custom controlComponents.
code: '<label><span>A label<CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
errors: [expectedError]
,
code: '<CustomLabel><span>A label<CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
errors: [expectedError]
,
code:
'<CustomLabel><span label="A label"><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
errors: [expectedError]
]
neverValid = [
code: '<label htmlFor="js_id" />', errors: [expectedError]
,
code: '<label htmlFor="js_id"><input /></label>', errors: [expectedError]
,
code: '<label htmlFor="js_id"><textarea /></label>', errors: [expectedError]
,
code: '<label></label>', errors: [expectedError]
,
code: '<label>A label</label>', errors: [expectedError]
,
code: '<div><label /><input /></div>', errors: [expectedError]
,
code: '<div><label>A label</label><input /></div>', errors: [expectedError]
,
# Custom label component.
code: '<CustomLabel aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
errors: [expectedError]
,
code: '<CustomLabel label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
errors: [expectedError]
,
# Custom label attributes.
code: '<label label="A label" />'
options: [labelAttributes: ['label']]
errors: [expectedError]
,
# Custom controlComponents.
code: '<label><span><CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
errors: [expectedError]
,
code: '<CustomLabel><span><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
errors: [expectedError]
,
code: '<CustomLabel><span><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
errors: [expectedError]
]
# htmlFor valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...htmlForValid]
.map(ruleOptionsMapperFactory assert: 'htmlFor')
.map(parserOptionsMapper)
invalid:
[...neverValid, ...nestingInvalid]
.map(ruleOptionsMapperFactory assert: 'htmlFor')
.map parserOptionsMapper
# nesting valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...nestingValid]
.map(ruleOptionsMapperFactory assert: 'nesting')
.map(parserOptionsMapper)
invalid:
[...neverValid, ...htmlForInvalid]
.map(ruleOptionsMapperFactory assert: 'nesting')
.map parserOptionsMapper
# either valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...htmlForValid, ...nestingValid]
.map(ruleOptionsMapperFactory assert: 'either')
.map(parserOptionsMapper)
invalid: [...neverValid].map parserOptionsMapper
# both valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...bothValid]
.map(ruleOptionsMapperFactory assert: 'both')
.map(parserOptionsMapper)
invalid: [...neverValid].map parserOptionsMapper
| 180167 | ### eslint-env jest ###
###*
# @fileoverview Enforce label tags have an associated control.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/label-has-associated-control'
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleName = 'label-has-associated-control'
expectedError =
message: 'A form label must be associated with a control.'
type: 'JSXOpeningElement'
htmlForValid = [
code:
'<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>'
options: [depth: 4]
,
code: '<label htmlFor="js_id" aria-label="A label" />'
,
code: '<label htmlFor="js_id" aria-labelledby="A label" />'
,
# Custom label component.
code: '<CustomLabel htmlFor="js_id" aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
,
code: '<CustomLabel htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label']]
]
nestingValid = [
code: '<label>A label<input /></label>'
,
code: '<label>A label<textarea /></label>'
,
code: '<label><img alt="A label" /><input /></label>'
,
code: '<label><img aria-label="A label" /><input /></label>'
,
code: '<label><span>A label<input /></span></label>'
,
code: '<label><span><span>A label<input /></span></span></label>'
options: [depth: 3]
,
code: '<label><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
,
code:
'<label><span><span><span><span>A label</span><input /></span></span></span></label>'
options: [depth: 5]
,
code:
'<label><span><span><span><span aria-label="A label" /><input /></span></span></span></label>'
options: [depth: 5]
,
code:
'<label><span><span><span><input aria-label="A label" /></span></span></span></label>'
options: [depth: 5]
,
# Custom controlComponents.
code: '<label><span>A label<CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
,
code: '<CustomLabel><span>A label<CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
,
code:
'<CustomLabel><span label="A label"><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
]
bothValid = [
code:
'<label htmlFor="js_id"><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
,
code: '<label htmlFor="js_id" aria-label="A label"><input /></label>'
,
code: '<label htmlFor="js_id" aria-labelledby="A label"><input /></label>'
,
code: '<label htmlFor="js_id" aria-labelledby="A label"><textarea /></label>'
,
# Custom label component.
code:
'<CustomLabel htmlFor="js_id" aria-label="A label"><input /></CustomLabel>'
options: [labelComponents: ['CustomLabel']]
,
code: '<CustomLabel htmlFor="js_id" label="A label"><input /></CustomLabel>'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label"><input /></label>'
options: [labelAttributes: ['label']]
,
code:
'<label htmlFor="selectInput">Some text<select id="selectInput" /></label>'
]
alwaysValid = [{code: '<div />'}, {code: '<CustomElement />'}]
htmlForInvalid = [
code:
'<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>'
options: [depth: 4]
errors: [expectedError]
,
code: '<label htmlFor="js_id" aria-label="A label" />'
errors: [expectedError]
,
code: '<label htmlFor="js_id" aria-labelledby="A label" />'
errors: [expectedError]
,
# Custom label component.
code: '<CustomLabel htmlFor="js_id" aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
errors: [expectedError]
,
code: '<CustomLabel htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
errors: [expectedError]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label']]
errors: [expectedError]
]
nestingInvalid = [
code: '<label>A label<input /></label>', errors: [expectedError]
,
code: '<label>A label<textarea /></label>', errors: [expectedError]
,
code: '<label><img alt="A label" /><input /></label>', errors: [expectedError]
,
code: '<label><img aria-label="A label" /><input /></label>'
errors: [expectedError]
,
code: '<label><span>A label<input /></span></label>', errors: [expectedError]
,
code: '<label><span><span>A label<input /></span></span></label>'
options: [depth: 3]
errors: [expectedError]
,
code: '<label><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
errors: [expectedError]
,
code:
'<label><span><span><span><span>A label</span><input /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
code:
'<label><span><span><span><span aria-label="A label" /><input /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
code:
'<label><span><span><span><input aria-label="A label" /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
# Custom controlComponents.
code: '<label><span>A label<CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
errors: [expectedError]
,
code: '<CustomLabel><span>A label<CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
errors: [expectedError]
,
code:
'<CustomLabel><span label="A label"><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
errors: [expectedError]
]
neverValid = [
code: '<label htmlFor="js_id" />', errors: [expectedError]
,
code: '<label htmlFor="js_id"><input /></label>', errors: [expectedError]
,
code: '<label htmlFor="js_id"><textarea /></label>', errors: [expectedError]
,
code: '<label></label>', errors: [expectedError]
,
code: '<label>A label</label>', errors: [expectedError]
,
code: '<div><label /><input /></div>', errors: [expectedError]
,
code: '<div><label>A label</label><input /></div>', errors: [expectedError]
,
# Custom label component.
code: '<CustomLabel aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
errors: [expectedError]
,
code: '<CustomLabel label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
errors: [expectedError]
,
# Custom label attributes.
code: '<label label="A label" />'
options: [labelAttributes: ['label']]
errors: [expectedError]
,
# Custom controlComponents.
code: '<label><span><CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
errors: [expectedError]
,
code: '<CustomLabel><span><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
errors: [expectedError]
,
code: '<CustomLabel><span><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
errors: [expectedError]
]
# htmlFor valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...htmlForValid]
.map(ruleOptionsMapperFactory assert: 'htmlFor')
.map(parserOptionsMapper)
invalid:
[...neverValid, ...nestingInvalid]
.map(ruleOptionsMapperFactory assert: 'htmlFor')
.map parserOptionsMapper
# nesting valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...nestingValid]
.map(ruleOptionsMapperFactory assert: 'nesting')
.map(parserOptionsMapper)
invalid:
[...neverValid, ...htmlForInvalid]
.map(ruleOptionsMapperFactory assert: 'nesting')
.map parserOptionsMapper
# either valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...htmlForValid, ...nestingValid]
.map(ruleOptionsMapperFactory assert: 'either')
.map(parserOptionsMapper)
invalid: [...neverValid].map parserOptionsMapper
# both valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...bothValid]
.map(ruleOptionsMapperFactory assert: 'both')
.map(parserOptionsMapper)
invalid: [...neverValid].map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce label tags have an associated control.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/label-has-associated-control'
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleName = 'label-has-associated-control'
expectedError =
message: 'A form label must be associated with a control.'
type: 'JSXOpeningElement'
htmlForValid = [
code:
'<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>'
options: [depth: 4]
,
code: '<label htmlFor="js_id" aria-label="A label" />'
,
code: '<label htmlFor="js_id" aria-labelledby="A label" />'
,
# Custom label component.
code: '<CustomLabel htmlFor="js_id" aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
,
code: '<CustomLabel htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label']]
]
nestingValid = [
code: '<label>A label<input /></label>'
,
code: '<label>A label<textarea /></label>'
,
code: '<label><img alt="A label" /><input /></label>'
,
code: '<label><img aria-label="A label" /><input /></label>'
,
code: '<label><span>A label<input /></span></label>'
,
code: '<label><span><span>A label<input /></span></span></label>'
options: [depth: 3]
,
code: '<label><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
,
code:
'<label><span><span><span><span>A label</span><input /></span></span></span></label>'
options: [depth: 5]
,
code:
'<label><span><span><span><span aria-label="A label" /><input /></span></span></span></label>'
options: [depth: 5]
,
code:
'<label><span><span><span><input aria-label="A label" /></span></span></span></label>'
options: [depth: 5]
,
# Custom controlComponents.
code: '<label><span>A label<CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
,
code: '<CustomLabel><span>A label<CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
,
code:
'<CustomLabel><span label="A label"><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
]
bothValid = [
code:
'<label htmlFor="js_id"><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
,
code: '<label htmlFor="js_id" aria-label="A label"><input /></label>'
,
code: '<label htmlFor="js_id" aria-labelledby="A label"><input /></label>'
,
code: '<label htmlFor="js_id" aria-labelledby="A label"><textarea /></label>'
,
# Custom label component.
code:
'<CustomLabel htmlFor="js_id" aria-label="A label"><input /></CustomLabel>'
options: [labelComponents: ['CustomLabel']]
,
code: '<CustomLabel htmlFor="js_id" label="A label"><input /></CustomLabel>'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label"><input /></label>'
options: [labelAttributes: ['label']]
,
code:
'<label htmlFor="selectInput">Some text<select id="selectInput" /></label>'
]
alwaysValid = [{code: '<div />'}, {code: '<CustomElement />'}]
htmlForInvalid = [
code:
'<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>'
options: [depth: 4]
errors: [expectedError]
,
code: '<label htmlFor="js_id" aria-label="A label" />'
errors: [expectedError]
,
code: '<label htmlFor="js_id" aria-labelledby="A label" />'
errors: [expectedError]
,
# Custom label component.
code: '<CustomLabel htmlFor="js_id" aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
errors: [expectedError]
,
code: '<CustomLabel htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
errors: [expectedError]
,
# Custom label attributes.
code: '<label htmlFor="js_id" label="A label" />'
options: [labelAttributes: ['label']]
errors: [expectedError]
]
nestingInvalid = [
code: '<label>A label<input /></label>', errors: [expectedError]
,
code: '<label>A label<textarea /></label>', errors: [expectedError]
,
code: '<label><img alt="A label" /><input /></label>', errors: [expectedError]
,
code: '<label><img aria-label="A label" /><input /></label>'
errors: [expectedError]
,
code: '<label><span>A label<input /></span></label>', errors: [expectedError]
,
code: '<label><span><span>A label<input /></span></span></label>'
options: [depth: 3]
errors: [expectedError]
,
code: '<label><span><span><span>A label<input /></span></span></span></label>'
options: [depth: 4]
errors: [expectedError]
,
code:
'<label><span><span><span><span>A label</span><input /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
code:
'<label><span><span><span><span aria-label="A label" /><input /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
code:
'<label><span><span><span><input aria-label="A label" /></span></span></span></label>'
options: [depth: 5]
errors: [expectedError]
,
# Custom controlComponents.
code: '<label><span>A label<CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
errors: [expectedError]
,
code: '<CustomLabel><span>A label<CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
errors: [expectedError]
,
code:
'<CustomLabel><span label="A label"><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
errors: [expectedError]
]
neverValid = [
code: '<label htmlFor="js_id" />', errors: [expectedError]
,
code: '<label htmlFor="js_id"><input /></label>', errors: [expectedError]
,
code: '<label htmlFor="js_id"><textarea /></label>', errors: [expectedError]
,
code: '<label></label>', errors: [expectedError]
,
code: '<label>A label</label>', errors: [expectedError]
,
code: '<div><label /><input /></div>', errors: [expectedError]
,
code: '<div><label>A label</label><input /></div>', errors: [expectedError]
,
# Custom label component.
code: '<CustomLabel aria-label="A label" />'
options: [labelComponents: ['CustomLabel']]
errors: [expectedError]
,
code: '<CustomLabel label="A label" />'
options: [labelAttributes: ['label'], labelComponents: ['CustomLabel']]
errors: [expectedError]
,
# Custom label attributes.
code: '<label label="A label" />'
options: [labelAttributes: ['label']]
errors: [expectedError]
,
# Custom controlComponents.
code: '<label><span><CustomInput /></span></label>'
options: [controlComponents: ['CustomInput']]
errors: [expectedError]
,
code: '<CustomLabel><span><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput'], labelComponents: ['CustomLabel']
]
errors: [expectedError]
,
code: '<CustomLabel><span><CustomInput /></span></CustomLabel>'
options: [
controlComponents: ['CustomInput']
labelComponents: ['CustomLabel']
labelAttributes: ['label']
]
errors: [expectedError]
]
# htmlFor valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...htmlForValid]
.map(ruleOptionsMapperFactory assert: 'htmlFor')
.map(parserOptionsMapper)
invalid:
[...neverValid, ...nestingInvalid]
.map(ruleOptionsMapperFactory assert: 'htmlFor')
.map parserOptionsMapper
# nesting valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...nestingValid]
.map(ruleOptionsMapperFactory assert: 'nesting')
.map(parserOptionsMapper)
invalid:
[...neverValid, ...htmlForInvalid]
.map(ruleOptionsMapperFactory assert: 'nesting')
.map parserOptionsMapper
# either valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...htmlForValid, ...nestingValid]
.map(ruleOptionsMapperFactory assert: 'either')
.map(parserOptionsMapper)
invalid: [...neverValid].map parserOptionsMapper
# both valid
ruleTester.run ruleName, rule,
valid:
[...alwaysValid, ...bothValid]
.map(ruleOptionsMapperFactory assert: 'both')
.map(parserOptionsMapper)
invalid: [...neverValid].map parserOptionsMapper
|
[
{
"context": "rts = [\n {\n \"id\": 0,\n \"password\": \"$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y\",\n \"name\": \"Cortez Waters\",\n \"email",
"end": 123,
"score": 0.9920067191123962,
"start": 62,
"tag": "PASSWORD",
"value": "\"$2a$10$I168m... | _src/test/dummydata.coffee | mpneuried/tcs_node_auth | 1 | module.exports = [
{
"id": 0,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Cortez Waters",
"email": "cortezwaters@example.com"
},
{
"id": 1,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Ramsey Moon",
"email": "ramseymoon@example.com"
},
{
"id": 2,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Daphne Schroeder",
"email": "daphneschroeder@example.com"
},
{
"id": 3,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Kris Sanford",
"email": "krissanford@example.com"
},
{
"id": 4,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Mcintyre Rhodes",
"email": "mcintyrerhodes@example.com"
},
{
"id": 5,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Harding Johnston",
"email": "hardingjohnston@example.com"
},
{
"id": 6,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Latasha Ferrell",
"email": "latashaferrell@example.com"
},
{
"id": 7,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Green Palmer",
"email": "greenpalmer@example.com"
},
{
"id": 8,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Berg Noble",
"email": "bergnoble@example.com"
},
{
"id": 9,
"password": "$2a$10$I168m1WzybPQvNsQdzodZeF/YdjKOccdicgK5GYqDYe8idsRTwB/y",
"name": "Peters Hodge",
"email": "petershodge@example.com"
},
{
"id": 10,
"password": null,
"name": "Missing Passowrd",
"email": "petershodge@example.com"
}
] | 75401 | module.exports = [
{
"id": 0,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 1,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 2,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 3,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 4,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 5,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 6,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 7,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 8,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 9,
"password": <PASSWORD>",
"name": "<NAME>",
"email": "<EMAIL>"
},
{
"id": 10,
"password": null,
"name": "Missing Pass<PASSWORD>",
"email": "<EMAIL>"
}
] | true | module.exports = [
{
"id": 0,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 1,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 2,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 3,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 4,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 5,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 6,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 7,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 8,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 9,
"password": PI:PASSWORD:<PASSWORD>END_PI",
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
},
{
"id": 10,
"password": null,
"name": "Missing PassPI:PASSWORD:<PASSWORD>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI"
}
] |
[
{
"context": "ar-plot.coffee)\n#\n# Air Sciences Inc. - 2016\n# Jacob Fielding\n#\n\nwindow.Plotter ||= {}\n\nwindow.Plotter.BarPlot ",
"end": 144,
"score": 0.9997162818908691,
"start": 130,
"tag": "NAME",
"value": "Jacob Fielding"
},
{
"context": "y, row of data\n result[ke... | coffee/bar-plot.coffee | airsciences/metplotter | 0 | #
# Northwest Avalanche Center (NWAC)
# Plotter Tools - D3 V.4 Line Plot (bar-plot.coffee)
#
# Air Sciences Inc. - 2016
# Jacob Fielding
#
window.Plotter ||= {}
window.Plotter.BarPlot = class BarPlot
constructor: (plotter, data, options) ->
@preError = "BarPlot."
@plotter = plotter
@initialized = false
_y = [
dataLoggerId: null
variable: null
ticks: 5
min: null
max: null
maxBar: null
color: "rgb(41, 128, 185)"
band:
minVariable: null
maxVariable: null
]
# Default Configuration
@defaults =
plotId: null
uuid: ''
debug: true
target: null
width: null
merge: false
decimals: 1
x:
variable: null
format: "%Y-%m-%dT%H:%M:%S-08:00"
min: null
max: null
ticks: 7
y: _y
zoom:
scale:
min: 0.05
max: 5
aspectDivisor: 5
transitionDuration: 500
weight: 2
axisColor: "rgb(0,0,0)"
font:
weight: 100
size: 12
focusX:
color: "rgb(52, 52, 52)"
crosshairX:
weight: 1
color: "rgb(149,165,166)"
requestInterval: 336
if options.x
options.x = @plotter.lib.mergeDefaults(options.x, @defaults.x)
options.y[0] = @plotter.lib.mergeDefaults(options.y[0], @defaults.y[0])
@options = @plotter.lib.mergeDefaults(options, @defaults)
@device = 'full'
@transform = d3.zoomIdentity
@links = [
{"variable": "battery_voltage", "title": "Battery Voltage"},
{"variable": "temperature", "title": "Temperature"},
{"variable": "relative_humidity", "title": "Relative Humidity"},
{"variable": "precipitation", "title": "Precipitation"},
{"variable": "snow_depth", "title": "Snow Depth"},
{"variable": "wind_direction", "title": "Wind Direction"},
{"variable": "wind_speed_average", "title": "Wind Speed"},
{"variable": "net_solar", "title": "Net Solar"},
{"variable": "solar_pyranometer", "title": "Solar Pyranometer"},
{"variable": "equip_temperature", "title": "Equipment Temperature"},
{"variable": "barometric_pressure", "title": "Barometric Pressure"},
{"variable": "snowfall_24_hour", "title": "24-Hr Snowfall"},
{"variable": "intermittent_snow", "title": "Intermittent Snow"}
]
# Wrapped Logging Functions
@log = (log...) ->
if @options.debug
@log = (log...) -> console.log(log)
# Minor Prototype Support Functions
@parseDate = d3.timeParse(@options.x.format)
@bisectDate = d3.bisector((d) -> d.x).left
@displayDate = d3.timeFormat("%b. %e, %I:%M %p")
@sortDatetimeAsc = (a, b) -> a.x - b.x
# Prepare the Data & Definition
@data = @processData(data)
@getDefinition()
@clipPathId = "bar-plot-clip-path-#{@plotter.lib.uuid()}"
@bars = []
@focusRect = []
@focusText = []
@skipBandDomainSet = false
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state =
range:
data: []
scale: _domainScale
length:
data: []
interval:
data: []
zoom: 1
request:
data: []
requested:
data: []
mean:
scale: _domainMean
if data[0].length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
processData: (data) ->
# Process a data set.
result = []
for setId, set of data
result[setId] = @processDataSet(set, setId)
return result
processDataSet: (data, dataSetId) ->
# Process a single set of data (Flat, versus 2-Level in processData)
_yOptions = @options.y[dataSetId]
result = []
for key, row of data
result[key] =
#x: row[@options.x.variable]
x: new Date(
@parseDate(row[@options.x.variable]).getTime())
y: row[_yOptions.variable]
if _yOptions.band?
if _yOptions.band.minVariable
result[key].yMin = row[_yOptions.band.minVariable]
if _yOptions.band.maxVariable
result[key].yMax = row[_yOptions.band.maxVariable]
_result = new Plotter.Data(result)
result = _result._clean(_result.get())
return result.sort(@sortDatetimeAsc)
setData: (data) ->
# Set the initial data.
@data = [@processDataSet(data, 0)]
@getDefinition()
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state.range.scale = _domainScale
@state.mean.scale = _domainMean
if data.length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
addData: (data, dataSetId) ->
# Set the initial data.
@data[dataSetId] = @processDataSet(data, dataSetId)
@getDefinition()
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state.range.scale = _domainScale
@state.mean.scale = _domainMean
if data.length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
appendData: (data, dataSetId) ->
# Append the full data set.
_data = @processDataSet(data, dataSetId)
_set = new window.Plotter.Data(@data[dataSetId])
_set.append(_data, ["x"])
@data[dataSetId] = _set._clean(_set.get())
@data[dataSetId] = @data[dataSetId].sort(@sortDatetimeAsc)
# Reset the Data Range
if @initialized
@setDataState()
@setIntervalState()
@setDataRequirement()
removeData: (key) ->
# Removing sub key from data.
if key >= 0
delete @data[key]
delete @options[key]
@svg.select(".bar-plot-area-#{key}").remove()
@svg.select(".bar-plot-path-#{key}").remove()
@svg.select(".focus-rect-#{key}").remove()
@svg.select(".focus-text-#{key}").remove()
if @initialized
@setDataState()
@setIntervalState()
@setDataRequirement()
setDataState: ->
# Set Data Ranges
_len = @data.length-1
# for i in [0.._len]
# if @data[i] is undefined
# console.log("data[i] is (i, row)", i, @data[i])
for key, row of @data
@state.range.data[key] =
min: d3.min(@data[key], (d)-> d.x)
max: d3.max(@data[key], (d)-> d.x)
# Set Data Length States
@state.length.data[key] = @data[key].length
setIntervalState: ->
# Set the Data Collection Padding Intervals in Hours
for key, row of @data
@state.interval.data[key] =
min: ((@state.range.scale.min.getTime() -
@state.range.data[key].min.getTime())/3600000)
max: ((@state.range.data[key].max.getTime() -
@state.range.scale.max.getTime())/3600000)
setDataRequirement: ->
# Calculate how necessary a download, in what direction, and/or data
_now = new Date()
for key, row of @data
_data_max = @state.interval.data[key].max <
@options.requestInterval
@state.request.data[key] =
min: @state.interval.data[key].min < @options.requestInterval
max: _data_max
if !(@state.requested.data[key]?)
@state.requested.data[key] =
min: false
max: false
setZoomState: (k)->
@state.zoom = k
getDomainScale: (axis) ->
# Calculate the Min & Max Range of an Axis
result =
min: axis.domain()[0]
max: axis.domain()[1]
getDomainMean: (axis) ->
# Calculat the Mean of an Axis
center = new Date(d3.mean(axis.domain()))
center.setHours(center.getHours() + Math.round(center.getMinutes()/60))
center.setMinutes(0)
center.setSeconds(0)
center.setMilliseconds(0)
return center
getDefinition: ->
preError = "#{@preError}getDefinition():"
_ = @
# Define the Definition
@definition = {}
@calculateChartDims()
@calculateAxisDims(@data)
# Define D3 Methods
@definition.xAxis = d3.axisBottom().scale(@definition.x)
.ticks(Math.round(@definition.dimensions.width / 100))
@definition.yAxis = d3.axisLeft().scale(@definition.y)
.ticks(@options.y[0].ticks)
# Define the Domains
@definition.x.domain([@definition.x.min, @definition.x.max])
if !@skipBandDomainSet
@definition.x1.domain(@data[0].map((d) -> d.x))
@skipBandDomainSet = false
@definition.y.domain([@definition.y.min, @definition.y.max]).nice()
# Define the Zoom Method
_extent = [
[-Infinity, 0],
[(@definition.x(new Date()) + @definition.dimensions.margin.left),
@definition.dimensions.innerHeight]
]
@definition.zoom = d3.zoom()
.scaleExtent([@options.zoom.scale.min, @options.zoom.scale.max])
.translateExtent(_extent)
.on("zoom", () ->
transform = _.setZoomTransform()
_.plotter.i.zoom.set(transform)
)
setBandDomain: (bandDomain) ->
@definition.x1 = bandDomain
calculateChartDims: ->
# Calculate Basic DOM & SVG Dimensions
if @options.width?
width = Math.round(@options.width)
else
width = Math.round($(@options.target).width()) - 24
height = Math.round(width/@options.aspectDivisor)
if width > 1000
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.12)
left: Math.round(Math.pow(width, 0.6))
else if width > 600
@device = 'mid'
@options.font.size = @options.font.size/1.25
_height = @options.aspectDivisor/1.25
height = Math.round(width/_height)
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.14)
left: Math.round(Math.pow(width, 0.6))
else
@device = 'small'
@options.font.size = @options.font.size/1.5
_height = @options.aspectDivisor/1.5
height = Math.round(width/_height)
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.18)
left: Math.round(Math.pow(width, 0.6))
# Basic Dimention
@definition.dimensions =
width: width
height: height
margin: margin
# Define Translate Padding
@definition.dimensions.topPadding =
parseInt(@definition.dimensions.margin.top)
@definition.dimensions.bottomPadding =
parseInt(@definition.dimensions.height -
@definition.dimensions.margin.bottom)
@definition.dimensions.leftPadding =
parseInt(@definition.dimensions.margin.left)
@definition.dimensions.innerHeight =
parseInt(@definition.dimensions.height -
@definition.dimensions.margin.bottom - @definition.dimensions.margin.top)
@definition.dimensions.innerWidth =
parseInt(@definition.dimensions.width -
@definition.dimensions.margin.left - @definition.dimensions.margin.right)
# Define the X & Y Scales
@definition.x = d3.scaleTime().range([margin.left, (width-margin.right)])
@definition.x1 = d3.scaleBand()
.rangeRound([margin.left, (width-margin.right)], 0.05)
.padding(0.1)
@definition.y = d3.scaleLinear().range([(height-margin.bottom),
(margin.top)])
calculateAxisDims: (data) ->
@calculateXAxisDims(data)
@calculateYAxisDims(data)
calculateXAxisDims: (data) ->
# Calculate Min & Max X Values
if @options.x.min is null
@definition.x.min = d3.min(data[0], (d)-> d.x)
else
@definition.x.min = @parseDate(@options.x.min)
if @options.x.max is null
@definition.x.max = d3.max(data[0], (d)-> d.x)
else
@definition.x.max = @parseDate(@options.x.max)
calculateYAxisDims: (data) ->
# Calculate Min & Max Y Values
@definition.y.min = 0
@definition.y.max = 0
for subId, set of data
_setMin = d3.min([
d3.min(set, (d)-> d.y)
d3.min(set, (d)-> d.yMin)
])
_setMax = d3.max([
d3.max(set, (d)-> d.y)
d3.max(set, (d)-> d.yMax)
])
if _setMin < @definition.y.min or @definition.y.min is undefined
@definition.y.min = _setMin
if _setMax > @definition.y.max or @definition.y.max is undefined
@definition.y.max = _setMax
# Restore Viewability if Y-Min = Y-Max
if @definition.y.min == @definition.y.max
@definition.y.min = @definition.y.min * 0.8
@definition.y.max = @definition.y.min * 1.2
# Revert to Options
if @options.y[0].min?
@definition.y.min = @options.y[0].min
if @options.y[0].max?
@definition.y.max = @options.y[0].max
preAppend: ->
preError = "#{@preError}preAppend()"
_ = @
# Create the SVG Div
@outer = d3.select(@options.target).append("div")
.attr("class", "bar-plot-body")
.style("width", "#{@definition.dimensions.width}px")
.style("height", "#{@definition.dimensions.height}px")
.style("display", "inline-block")
# Create the Controls Div
@ctls = d3.select(@options.target).append("div")
.attr("class", "plot-controls")
.style("width", '23px')
.style("height", "#{@definition.dimensions.height}px")
.style("display", "inline-block")
.style("vertical-align", "top")
#if @data[0].length == 0
# if @options.type is "station"
# add_text = "Select the Plot's Station"
# sub_text = "Station type plots allow comparison of different variab\
# les from the same station."
# else if @options.type is "parameter"
# add_text = "Select the Plot's Parameter"
# sub_text = "Parameter type plots allow comparison of a single parama\
# ter at multiple stations"
# _offset = $(@options.target).offset()
# @temp = @outer.append("div")
# .attr("class", "new-temp-#{@options.plotId}")
# .style("position", "Relative")
# .style("top",
# "#{parseInt(@definition.dimensions.innerHeight/1.74)}px")
# .style("left",
# "#{parseInt(@definition.dimensions.innerWidth/6.5)}px")
# .style("width", "#{@definition.dimensions.innerWidth}px")
# .style("text-align", "center")
# @temp.append("p")
# .text(sub_text)
# .style("color", "#ggg")
# .style("font-size", "12px")
# Create the SVG
@svg = @outer.append("svg")
.attr("class", "bar-plot")
.attr("width", @definition.dimensions.width)
.attr("height", @definition.dimensions.height)
# Append a Clip Path
@svg.append("defs")
.append("clipPath")
.attr("id", @clipPathId)
.append("rect")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
# Append the X-Axis
@svg.append("g")
.attr("class", "bar-plot-axis-x")
.style("fill", "none")\
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.call(@definition.xAxis)
.attr("transform",
"translate(0, #{@definition.dimensions.bottomPadding})"
)
# Append the Y-Axis
@svg.append("g")
.attr("class", "bar-plot-axis-y")
.style("fill", "none")
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.call(@definition.yAxis)
.attr("transform", "translate(#{@definition.dimensions.leftPadding}, 0)")
append: ->
@initialized = true
if !@initialized
return
preError = "#{@preError}append()"
_ = @
# Update the X-Axis
@svg.select(".bar-plot-axis-x")
.call(@definition.xAxis)
@svg.select(".bar-plot-axis-y")
.call(@definition.yAxis)
# Append Axis Label
_y_title = "#{@options.y[0].title}"
if @options.y[0].units
_y_title = "#{_y_title} #{@options.y[0].units}"
_y_vert = -@definition.dimensions.margin.top
_y_offset = -@definition.dimensions.margin.left
# Y-Axis Title
@svg.select(".bar-plot-axis-y")
.append("text")
.text(_y_title)
.attr("class", "bar-plot-y-label")
.attr("x", _y_vert)
.attr("y", _y_offset)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.attr("fill", @options.axisColor)
# Append Bands & Bar Path
@barWrapper = @svg.append("g")
.attr("class", "bar-wrapper")
for key, row of @data
@bars[key] = @barWrapper.append("g")
.attr("clip-path", "url(\#" + @clipPathId + ")")
.selectAll(".bar-#{key}")
.data(row)
.enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _.definition.x(d.x))
.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
if @options.y[0].maxBar?
@barWrapper.append("rect")
.attr("class", "bar-plot-max-bar")
.attr("x", @definition.dimensions.leftPadding)
.attr("y", @definition.y(@options.y[0].maxBar))
.attr("width", (@definition.dimensions.innerWidth))
.attr("height", 1)
.style("color", '#gggggg')
.style("opacity", 0.4)
@hoverWrapper = @svg.append("g")
.attr("class", "hover-wrapper")
# Create Crosshairs
@crosshairs = @hoverWrapper.append("g")
.attr("class", "crosshair")
# Create Vertical line
@crosshairs.append("line")
.attr("class", "crosshair-x")
.style("stroke", @options.crosshairX.color)
.style("stroke-width", @options.crosshairX.weight)
.style("stroke-dasharray", ("3, 3"))
.style("fill", "none")
# Create the Focus Label Underlay
@crosshairs.append("rect")
.attr("class", "crosshair-x-under")
.style("fill", "rgb(255,255,255)")
.style("opacity", 0.1)
@focusDateText = @hoverWrapper.append("text")
.attr("class", "focus-date-text")
.attr("x", 9)
.attr("y", 7)
.style("display", "none")
.style("fill", "#000000")
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
for key, row of @data
# Create Focus Circles and Labels
@focusRect[key] = @hoverWrapper.append("rect")
.attr("width", @definition.x1.bandwidth())
.attr("height", 2)
.attr("class", "focus-rect-#{key}")
.attr("fill", @options.focusX.color)
#.attr("fill", @options.y[key].color)
.attr("transform", "translate(-10, -10)")
.style("display", "none")
.style("stroke", "rgb(255,255,255)")
.style("opacity", 0.75)
@focusText[key] = @hoverWrapper.append("text")
.attr("class", "focus-text-#{key}")
.attr("x", 11)
.attr("y", 7)
.style("display", "none")
.style("fill", @options.y[key].color)
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
# Append the Crosshair & Zoom Event Rectangle
@overlay = @svg.append("rect")
.attr("class", "plot-event-target")
# Append Crosshair & Zoom Listening Targets
@appendCrosshairTarget(@transform)
@appendZoomTarget(@transform)
update: ->
preError = "#{@preError}update()"
_ = @
_rescaleX = @transform.rescaleX(@definition.x)
_bandwidth = Math.floor(@transform.k * @definition.x1.bandwidth())
# Pre-Append Data For Smooth transform
for key, row of @data
if row? and _.options.y[key]?
if @svg.selectAll(".bar-#{key}").node()[0] is null
console.log("Adding new BarPlot data set.")
@bars[key] = @barWrapper.append("g")
.attr("clip-path", "url(\#" + @clipPathId + ")")
.selectAll(".bar-#{key}")
.data(row)
.enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
# Create Focus Circles and Labels
@focusRect[key] = @hoverWrapper.append("rect")
.attr("width", @definition.x1.bandwidth())
.attr("height", 2)
.attr("class", "focus-rect-#{key}")
.attr("fill", @options.focusX.color)
#.attr("fill", @options.y[key].color)
.attr("transform", "translate(-10, -10)")
.style("display", "none")
.style("stroke", "rgb(255,255,255)")
.style("opacity", 0.75)
@focusText[key] = @hoverWrapper.append("text")
.attr("class", "focus-text-#{key}")
.attr("x", 11)
.attr("y", 7)
.style("display", "none")
.style("fill", @options.y[key].color)
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
else
# Update Data
@bars[key] = @barWrapper.select("g")
.selectAll(".bar-#{key}")
.data(row)
# Append new rect.
@bars[key].enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
# Remove deleted rect.
@bars[key].exit()
.remove()
# transitionDurationbar
@bars[key].attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
# Reset the overlay to last position.
@overlay.remove()
@overlay = @svg.append("rect")
.attr("class", "plot-event-target")
@appendCrosshairTarget(@transform)
@appendZoomTarget(@transform)
@calculateYAxisDims(@data)
@definition.y.domain([@definition.y.min, @definition.y.max]).nice()
#_rescaleX = @transform.rescaleX(@definition.x)
#for key, row of @data
# # Redraw the Bars
# @svg.selectAll(".bar-#{key}")
# .attr("x", (d) -> _rescaleX(d.x))
# .attr("width", Math.floor(@transform.k * @definition.x1.bandwidth()))
# Redraw the Y-Axis
@svg.select(".bar-plot-axis-y")
.call(@definition.yAxis)
if @options.y[0].maxBar?
@barWrapper.select(".bar-plot-max-bar")
.attr("y", @definition.y(@options.y[0].maxBar))
# Reset the zoom state
@setZoomTransform(@transform)
removeTemp: ->
@temp.remove()
appendCrosshairTarget: (transform) ->
# Move Crosshairs and Focus Circle Based on Mouse Location
if !@initialized
return
preError = "#{@preError}appendCrosshairTarget()"
_ = @
@overlay.datum(@data)
.attr("class", "overlay")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", () -> _.plotter.i.crosshairs.show())
.on("mouseout", () -> _.plotter.i.crosshairs.hide())
.on("mousemove", () ->
mouse = _.setCrosshair(transform)
_.plotter.i.crosshairs.set(transform, mouse)
)
appendZoomTarget: (transform) ->
if !@initialized
return
preError = "#{@preError}appendZoomTarget()"
_ = @
# Append the Zoom Rectangle
@overlay.attr("class", "zoom-pane")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
.style("fill", "none")
.style("pointer-events", "all")
.style("cursor", "move")
@svg.call(@definition.zoom, transform)
setZoomTransform: (transform) ->
# Set the current zoom transform state.
if !@initialized
return
preError = "#{@preError}.setZoomTransform(transform)"
_ = @
#_transform = if transform then transform else d3.event.transform
if transform?
@transform = transform
else if d3.event?
@transform = d3.event.transform
_transform = @transform
# Zoom the X-Axis
_rescaleX = _transform.rescaleX(@definition.x)
#_rescaleX1 = _transform.rescaleX(@definition.x1)
@svg.select(".bar-plot-axis-x").call(
@definition.xAxis.scale(_rescaleX)
)
# Set the scaleRange
@state.range.scale = @getDomainScale(_rescaleX)
@state.mean.scale = @getDomainMean(_rescaleX)
@setDataState()
@setIntervalState()
@setDataRequirement()
@setZoomState(_transform.k)
# Redraw Bars
for key, row of @data
@svg.selectAll(".bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width",
d3.max([1, Math.floor(_transform.k * @definition.x1.bandwidth())]))
@appendCrosshairTarget(_transform)
return _transform
setCrosshair: (transform, mouse) ->
# Set the Crosshair position
if !@initialized
return
preError = "#{@preError}.setCrosshair(mouse)"
_ = @
_dims = @definition.dimensions
directionLabel = (dir) ->
# Return a direction label for wind direction type items.
return switch
when dir > 360 or dir < 0 then "INV"
when dir >= 0 and dir < 11.25 then "N"
when dir >= 11.25 and dir < 33.75 then "NNE"
when dir >= 33.75 and dir < 56.25 then "NE"
when dir >= 56.25 and dir < 78.75 then "ENE"
when dir >= 78.75 and dir < 101.25 then "E"
when dir >= 101.25 and dir < 123.75 then "ESE"
when dir >= 123.75 and dir < 146.25 then "SE"
when dir >= 146.25 and dir < 168.75 then "SSE"
when dir >= 168.75 and dir < 191.25 then "S"
when dir >= 191.25 and dir < 213.75 then "SSW"
when dir >= 213.75 and dir < 236.25 then "SW"
when dir >= 236.25 and dir < 258.75 then "WSW"
when dir >= 258.75 and dir < 281.25 then "W"
when dir >= 281.25 and dir < 303.75 then "WNW"
when dir >= 303.75 and dir < 326.25 then "NW"
when dir >= 326.25 and dir < 348.75 then "NNW"
when dir >= 348.75 and dir <= 360 then "N"
for key, row of @data
_mouseTarget = @overlay.node()
#_datum = @overlay.datum()
_datum = row
mouse = if mouse then mouse else d3.mouse(_mouseTarget)
x0 = @definition.x.invert(mouse[0] + _dims.leftPadding)
if transform
x0 = @definition.x.invert(
transform.invertX(mouse[0] + _dims.leftPadding))
i1 = _.bisectDate(_datum, x0, 1)
i = if x0.getMinutes() >= 30 then i1 else (i1 - 1)
# Correct for Max & Min
if x0.getTime() <= @state.range.data[key].min.getTime()
i = i1
if x0.getTime() >= @state.range.data[key].max.getTime()
i = i1 - 1
if _datum[i]?
if transform
dx = transform.applyX(@definition.x(_datum[i].x))
else
dx = @definition.x(_datum[i].x)
dy = []
_value = []
if @options.y[key].variable != null
_value[key] = _datum[i]
if _value[key]?
dy[key] = @definition.y(_value[key].y)
_date = @displayDate(_value[key].x)
if !isNaN(dy[key]) and _value[key].y?
@focusRect[key].attr("transform", "translate(0, 0)")
cx = dx - _dims.leftPadding
if cx >= 0
@crosshairs.select(".crosshair-x")
.attr("x1", cx)
.attr("y1", _dims.topPadding)
.attr("x2", cx)
.attr("y2", _dims.innerHeight + _dims.topPadding)
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
@crosshairs.select(".crosshair-x-under")
.attr("x", cx)
.attr("y", _dims.topPadding)
.attr("width", (_dims.innerWidth - cx))
.attr("height", _dims.innerHeight)
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
fdtx = cx - 120
# [Disabled] - Tooltip Flip
# if cx < 150
# fdtx = cx + 10
@focusDateText
.attr("x", fdtx)
.attr("y", (_dims.topPadding + _dims.innerHeight - 3))
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
.text(_date)
if (
@options.y[key].variable != null and !isNaN(dy[key]) and
_value[key].y?
)
@focusRect[key]
.attr("width", transform.k * @definition.x1.bandwidth())
.attr("x", dx)
.attr("y", dy[key])
# [Disabled] - Tooltip Flip
textAnchor = "start"
# if dx + 80 > @definition.dimensions.width
# dx = dx - 14
# textAnchor = "end"
@focusText[key]
.attr("x", dx + _dims.leftPadding / 10 +
transform.k * @definition.x1.bandwidth() + 2)
.attr("y", dy[key] - _dims.topPadding / 10)
.attr("text-anchor", textAnchor)
.text(
if _value[key].y?
if _.options.y[0].variable is "wind_direction"
directionLabel(_value[key].y)
else
_value[key].y.toFixed(@options.decimals) + " " +
@options.y[key].units)
# Tooltip Overlap Prevention
#if (
# @options.y.variable != null and
# @options.y2.variable != null and
# @options.y3.variable != null
#)
# ypos = []
# @svg.selectAll('.focus-text')
# .attr("transform", (d, i) ->
# row =
# ind: i
# y: parseInt(d3.select(@).attr("y"))
# offset: 0
# ypos.push(row)
# return ""
# )
# .call((sel) ->
# ypos.sort((a, b) -> a.y - b.y)
# ypos.forEach ((p, i) ->
# if i > 0
# offset = Math.max(0, (ypos[i-1].y + 18) - ypos[i].y)
# if ypos[i].ind == 0
# offset = -offset
# ypos[i].offset = offset
# )
# )
# .attr("transform", (d, i) ->
# return "translate (0, #{ypos[i].offset})"
# )
return mouse
showCrosshair: ->
# Show the Crosshair
if !@initialized
return
@crosshairs.select(".crosshair-x")
.style("display", null)
@crosshairs.select(".crosshair-x-under")
.style("display", null)
@focusDateText.style("display", null)
for setId, row of @options.y
if row.variable != null
if @focusRect[setId]?
@focusRect[setId].style("display", null)
.attr("fill", @options.focusX.color)
#.attr("fill", row.color)
if @focusText[setId]?
@focusText[setId].style("display", null)
.style("color", row.color)
.style("fill", row.color)
hideCrosshair: ->
# Hide the Crosshair
if !@initialized
return
@crosshairs.select(".crosshair-x")
.style("display", "none")
@crosshairs.select(".crosshair-x-under")
.style("display", "none")
@focusDateText.style("display", "none")
for setId, row of @options.y
if row.variable != null
if @focusRect[setId]?
@focusRect[setId].style("display", "none")
if @focusText[setId]?
@focusText[setId].style("display", "none")
appendTitle: (title, subtitle) ->
# Append a Plot Title
_offsetFactor = 1
_mainSize = '16px'
_subSize = '12px'
if @device == 'small'
_offsetFactor = 0.4
_mainSize = '10px'
_subSize = '7px'
@title = @svg.append("g")
.attr("class", "bar-plot-title")
@title.append("text")
.attr("x", (@definition.dimensions.margin.left + 10))
.attr("y", (@definition.dimensions.margin.top / 2 - (4*_offsetFactor)))
.style("font-size", _mainSize)
.style("font-weight", 600)
.text(title)
if subtitle
@title.append("text")
.attr("x", (@definition.dimensions.margin.left + 10))
.attr("y", (@definition.dimensions.margin.top / 2 + (12*_offsetFactor)))
.style("font-size", _subSize)
.text(subtitle)
getState: ->
# Return the Current Plot state.
return @state
| 34488 | #
# Northwest Avalanche Center (NWAC)
# Plotter Tools - D3 V.4 Line Plot (bar-plot.coffee)
#
# Air Sciences Inc. - 2016
# <NAME>
#
window.Plotter ||= {}
window.Plotter.BarPlot = class BarPlot
constructor: (plotter, data, options) ->
@preError = "BarPlot."
@plotter = plotter
@initialized = false
_y = [
dataLoggerId: null
variable: null
ticks: 5
min: null
max: null
maxBar: null
color: "rgb(41, 128, 185)"
band:
minVariable: null
maxVariable: null
]
# Default Configuration
@defaults =
plotId: null
uuid: ''
debug: true
target: null
width: null
merge: false
decimals: 1
x:
variable: null
format: "%Y-%m-%dT%H:%M:%S-08:00"
min: null
max: null
ticks: 7
y: _y
zoom:
scale:
min: 0.05
max: 5
aspectDivisor: 5
transitionDuration: 500
weight: 2
axisColor: "rgb(0,0,0)"
font:
weight: 100
size: 12
focusX:
color: "rgb(52, 52, 52)"
crosshairX:
weight: 1
color: "rgb(149,165,166)"
requestInterval: 336
if options.x
options.x = @plotter.lib.mergeDefaults(options.x, @defaults.x)
options.y[0] = @plotter.lib.mergeDefaults(options.y[0], @defaults.y[0])
@options = @plotter.lib.mergeDefaults(options, @defaults)
@device = 'full'
@transform = d3.zoomIdentity
@links = [
{"variable": "battery_voltage", "title": "Battery Voltage"},
{"variable": "temperature", "title": "Temperature"},
{"variable": "relative_humidity", "title": "Relative Humidity"},
{"variable": "precipitation", "title": "Precipitation"},
{"variable": "snow_depth", "title": "Snow Depth"},
{"variable": "wind_direction", "title": "Wind Direction"},
{"variable": "wind_speed_average", "title": "Wind Speed"},
{"variable": "net_solar", "title": "Net Solar"},
{"variable": "solar_pyranometer", "title": "Solar Pyranometer"},
{"variable": "equip_temperature", "title": "Equipment Temperature"},
{"variable": "barometric_pressure", "title": "Barometric Pressure"},
{"variable": "snowfall_24_hour", "title": "24-Hr Snowfall"},
{"variable": "intermittent_snow", "title": "Intermittent Snow"}
]
# Wrapped Logging Functions
@log = (log...) ->
if @options.debug
@log = (log...) -> console.log(log)
# Minor Prototype Support Functions
@parseDate = d3.timeParse(@options.x.format)
@bisectDate = d3.bisector((d) -> d.x).left
@displayDate = d3.timeFormat("%b. %e, %I:%M %p")
@sortDatetimeAsc = (a, b) -> a.x - b.x
# Prepare the Data & Definition
@data = @processData(data)
@getDefinition()
@clipPathId = "bar-plot-clip-path-#{@plotter.lib.uuid()}"
@bars = []
@focusRect = []
@focusText = []
@skipBandDomainSet = false
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state =
range:
data: []
scale: _domainScale
length:
data: []
interval:
data: []
zoom: 1
request:
data: []
requested:
data: []
mean:
scale: _domainMean
if data[0].length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
processData: (data) ->
# Process a data set.
result = []
for setId, set of data
result[setId] = @processDataSet(set, setId)
return result
processDataSet: (data, dataSetId) ->
# Process a single set of data (Flat, versus 2-Level in processData)
_yOptions = @options.y[dataSetId]
result = []
for key, row of data
result[key] =
#x: row[<EMAIL>]
x: new Date(
@parseDate(row[@options.x.variable]).getTime())
y: row[_yOptions.variable]
if _yOptions.band?
if _yOptions.band.minVariable
result[key].yMin = row[_yOptions.band.minVariable]
if _yOptions.band.maxVariable
result[key].yMax = row[_yOptions.band.maxVariable]
_result = new Plotter.Data(result)
result = _result._clean(_result.get())
return result.sort(@sortDatetimeAsc)
setData: (data) ->
# Set the initial data.
@data = [@processDataSet(data, 0)]
@getDefinition()
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state.range.scale = _domainScale
@state.mean.scale = _domainMean
if data.length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
addData: (data, dataSetId) ->
# Set the initial data.
@data[dataSetId] = @processDataSet(data, dataSetId)
@getDefinition()
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state.range.scale = _domainScale
@state.mean.scale = _domainMean
if data.length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
appendData: (data, dataSetId) ->
# Append the full data set.
_data = @processDataSet(data, dataSetId)
_set = new window.Plotter.Data(@data[dataSetId])
_set.append(_data, ["x"])
@data[dataSetId] = _set._clean(_set.get())
@data[dataSetId] = @data[dataSetId].sort(@sortDatetimeAsc)
# Reset the Data Range
if @initialized
@setDataState()
@setIntervalState()
@setDataRequirement()
removeData: (key) ->
# Removing sub key from data.
if key >= 0
delete @data[key]
delete @options[key]
@svg.select(".bar-plot-area-#{key}").remove()
@svg.select(".bar-plot-path-#{key}").remove()
@svg.select(".focus-rect-#{key}").remove()
@svg.select(".focus-text-#{key}").remove()
if @initialized
@setDataState()
@setIntervalState()
@setDataRequirement()
setDataState: ->
# Set Data Ranges
_len = @data.length-1
# for i in [0.._len]
# if @data[i] is undefined
# console.log("data[i] is (i, row)", i, @data[i])
for key, row of @data
@state.range.data[key] =
min: d3.min(@data[key], (d)-> d.x)
max: d3.max(@data[key], (d)-> d.x)
# Set Data Length States
@state.length.data[key] = @data[key].length
setIntervalState: ->
# Set the Data Collection Padding Intervals in Hours
for key, row of @data
@state.interval.data[key] =
min: ((@state.range.scale.min.getTime() -
@state.range.data[key].min.getTime())/3600000)
max: ((@state.range.data[key].max.getTime() -
@state.range.scale.max.getTime())/3600000)
setDataRequirement: ->
# Calculate how necessary a download, in what direction, and/or data
_now = new Date()
for key, row of @data
_data_max = @state.interval.data[key].max <
@options.requestInterval
@state.request.data[key] =
min: @state.interval.data[key].min < @options.requestInterval
max: _data_max
if !(@state.requested.data[key]?)
@state.requested.data[key] =
min: false
max: false
setZoomState: (k)->
@state.zoom = k
getDomainScale: (axis) ->
# Calculate the Min & Max Range of an Axis
result =
min: axis.domain()[0]
max: axis.domain()[1]
getDomainMean: (axis) ->
# Calculat the Mean of an Axis
center = new Date(d3.mean(axis.domain()))
center.setHours(center.getHours() + Math.round(center.getMinutes()/60))
center.setMinutes(0)
center.setSeconds(0)
center.setMilliseconds(0)
return center
getDefinition: ->
preError = "#{@preError}getDefinition():"
_ = @
# Define the Definition
@definition = {}
@calculateChartDims()
@calculateAxisDims(@data)
# Define D3 Methods
@definition.xAxis = d3.axisBottom().scale(@definition.x)
.ticks(Math.round(@definition.dimensions.width / 100))
@definition.yAxis = d3.axisLeft().scale(@definition.y)
.ticks(@options.y[0].ticks)
# Define the Domains
@definition.x.domain([@definition.x.min, @definition.x.max])
if !@skipBandDomainSet
@definition.x1.domain(@data[0].map((d) -> d.x))
@skipBandDomainSet = false
@definition.y.domain([@definition.y.min, @definition.y.max]).nice()
# Define the Zoom Method
_extent = [
[-Infinity, 0],
[(@definition.x(new Date()) + @definition.dimensions.margin.left),
@definition.dimensions.innerHeight]
]
@definition.zoom = d3.zoom()
.scaleExtent([@options.zoom.scale.min, @options.zoom.scale.max])
.translateExtent(_extent)
.on("zoom", () ->
transform = _.setZoomTransform()
_.plotter.i.zoom.set(transform)
)
setBandDomain: (bandDomain) ->
@definition.x1 = bandDomain
calculateChartDims: ->
# Calculate Basic DOM & SVG Dimensions
if @options.width?
width = Math.round(@options.width)
else
width = Math.round($(@options.target).width()) - 24
height = Math.round(width/@options.aspectDivisor)
if width > 1000
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.12)
left: Math.round(Math.pow(width, 0.6))
else if width > 600
@device = 'mid'
@options.font.size = @options.font.size/1.25
_height = @options.aspectDivisor/1.25
height = Math.round(width/_height)
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.14)
left: Math.round(Math.pow(width, 0.6))
else
@device = 'small'
@options.font.size = @options.font.size/1.5
_height = @options.aspectDivisor/1.5
height = Math.round(width/_height)
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.18)
left: Math.round(Math.pow(width, 0.6))
# Basic Dimention
@definition.dimensions =
width: width
height: height
margin: margin
# Define Translate Padding
@definition.dimensions.topPadding =
parseInt(@definition.dimensions.margin.top)
@definition.dimensions.bottomPadding =
parseInt(@definition.dimensions.height -
@definition.dimensions.margin.bottom)
@definition.dimensions.leftPadding =
parseInt(@definition.dimensions.margin.left)
@definition.dimensions.innerHeight =
parseInt(@definition.dimensions.height -
@definition.dimensions.margin.bottom - @definition.dimensions.margin.top)
@definition.dimensions.innerWidth =
parseInt(@definition.dimensions.width -
@definition.dimensions.margin.left - @definition.dimensions.margin.right)
# Define the X & Y Scales
@definition.x = d3.scaleTime().range([margin.left, (width-margin.right)])
@definition.x1 = d3.scaleBand()
.rangeRound([margin.left, (width-margin.right)], 0.05)
.padding(0.1)
@definition.y = d3.scaleLinear().range([(height-margin.bottom),
(margin.top)])
calculateAxisDims: (data) ->
@calculateXAxisDims(data)
@calculateYAxisDims(data)
calculateXAxisDims: (data) ->
# Calculate Min & Max X Values
if @options.x.min is null
@definition.x.min = d3.min(data[0], (d)-> d.x)
else
@definition.x.min = @parseDate(@options.x.min)
if @options.x.max is null
@definition.x.max = d3.max(data[0], (d)-> d.x)
else
@definition.x.max = @parseDate(@options.x.max)
calculateYAxisDims: (data) ->
# Calculate Min & Max Y Values
@definition.y.min = 0
@definition.y.max = 0
for subId, set of data
_setMin = d3.min([
d3.min(set, (d)-> d.y)
d3.min(set, (d)-> d.yMin)
])
_setMax = d3.max([
d3.max(set, (d)-> d.y)
d3.max(set, (d)-> d.yMax)
])
if _setMin < @definition.y.min or @definition.y.min is undefined
@definition.y.min = _setMin
if _setMax > @definition.y.max or @definition.y.max is undefined
@definition.y.max = _setMax
# Restore Viewability if Y-Min = Y-Max
if @definition.y.min == @definition.y.max
@definition.y.min = @definition.y.min * 0.8
@definition.y.max = @definition.y.min * 1.2
# Revert to Options
if @options.y[0].min?
@definition.y.min = @options.y[0].min
if @options.y[0].max?
@definition.y.max = @options.y[0].max
preAppend: ->
preError = "#{@preError}preAppend()"
_ = @
# Create the SVG Div
@outer = d3.select(@options.target).append("div")
.attr("class", "bar-plot-body")
.style("width", "#{@definition.dimensions.width}px")
.style("height", "#{@definition.dimensions.height}px")
.style("display", "inline-block")
# Create the Controls Div
@ctls = d3.select(@options.target).append("div")
.attr("class", "plot-controls")
.style("width", '23px')
.style("height", "#{@definition.dimensions.height}px")
.style("display", "inline-block")
.style("vertical-align", "top")
#if @data[0].length == 0
# if @options.type is "station"
# add_text = "Select the Plot's Station"
# sub_text = "Station type plots allow comparison of different variab\
# les from the same station."
# else if @options.type is "parameter"
# add_text = "Select the Plot's Parameter"
# sub_text = "Parameter type plots allow comparison of a single parama\
# ter at multiple stations"
# _offset = $(@options.target).offset()
# @temp = @outer.append("div")
# .attr("class", "new-temp-#{@options.plotId}")
# .style("position", "Relative")
# .style("top",
# "#{parseInt(@definition.dimensions.innerHeight/1.74)}px")
# .style("left",
# "#{parseInt(@definition.dimensions.innerWidth/6.5)}px")
# .style("width", "#{@definition.dimensions.innerWidth}px")
# .style("text-align", "center")
# @temp.append("p")
# .text(sub_text)
# .style("color", "#ggg")
# .style("font-size", "12px")
# Create the SVG
@svg = @outer.append("svg")
.attr("class", "bar-plot")
.attr("width", @definition.dimensions.width)
.attr("height", @definition.dimensions.height)
# Append a Clip Path
@svg.append("defs")
.append("clipPath")
.attr("id", @clipPathId)
.append("rect")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
# Append the X-Axis
@svg.append("g")
.attr("class", "bar-plot-axis-x")
.style("fill", "none")\
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.call(@definition.xAxis)
.attr("transform",
"translate(0, #{@definition.dimensions.bottomPadding})"
)
# Append the Y-Axis
@svg.append("g")
.attr("class", "bar-plot-axis-y")
.style("fill", "none")
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.call(@definition.yAxis)
.attr("transform", "translate(#{@definition.dimensions.leftPadding}, 0)")
append: ->
@initialized = true
if !@initialized
return
preError = "#{@preError}append()"
_ = @
# Update the X-Axis
@svg.select(".bar-plot-axis-x")
.call(@definition.xAxis)
@svg.select(".bar-plot-axis-y")
.call(@definition.yAxis)
# Append Axis Label
_y_title = "#{@options.y[0].title}"
if @options.y[0].units
_y_title = "#{_y_title} #{@options.y[0].units}"
_y_vert = -@definition.dimensions.margin.top
_y_offset = -@definition.dimensions.margin.left
# Y-Axis Title
@svg.select(".bar-plot-axis-y")
.append("text")
.text(_y_title)
.attr("class", "bar-plot-y-label")
.attr("x", _y_vert)
.attr("y", _y_offset)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.attr("fill", @options.axisColor)
# Append Bands & Bar Path
@barWrapper = @svg.append("g")
.attr("class", "bar-wrapper")
for key, row of @data
@bars[key] = @barWrapper.append("g")
.attr("clip-path", "url(\#" + @clipPathId + ")")
.selectAll(".bar-#{key}")
.data(row)
.enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _.definition.x(d.x))
.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
if @options.y[0].maxBar?
@barWrapper.append("rect")
.attr("class", "bar-plot-max-bar")
.attr("x", @definition.dimensions.leftPadding)
.attr("y", @definition.y(@options.y[0].maxBar))
.attr("width", (@definition.dimensions.innerWidth))
.attr("height", 1)
.style("color", '#gggggg')
.style("opacity", 0.4)
@hoverWrapper = @svg.append("g")
.attr("class", "hover-wrapper")
# Create Crosshairs
@crosshairs = @hoverWrapper.append("g")
.attr("class", "crosshair")
# Create Vertical line
@crosshairs.append("line")
.attr("class", "crosshair-x")
.style("stroke", @options.crosshairX.color)
.style("stroke-width", @options.crosshairX.weight)
.style("stroke-dasharray", ("3, 3"))
.style("fill", "none")
# Create the Focus Label Underlay
@crosshairs.append("rect")
.attr("class", "crosshair-x-under")
.style("fill", "rgb(255,255,255)")
.style("opacity", 0.1)
@focusDateText = @hoverWrapper.append("text")
.attr("class", "focus-date-text")
.attr("x", 9)
.attr("y", 7)
.style("display", "none")
.style("fill", "#000000")
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
for key, row of @data
# Create Focus Circles and Labels
@focusRect[key] = @hoverWrapper.append("rect")
.attr("width", @definition.x1.bandwidth())
.attr("height", 2)
.attr("class", "focus-rect-#{key}")
.attr("fill", @options.focusX.color)
#.attr("fill", @options.y[key].color)
.attr("transform", "translate(-10, -10)")
.style("display", "none")
.style("stroke", "rgb(255,255,255)")
.style("opacity", 0.75)
@focusText[key] = @hoverWrapper.append("text")
.attr("class", "focus-text-#{key}")
.attr("x", 11)
.attr("y", 7)
.style("display", "none")
.style("fill", @options.y[key].color)
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
# Append the Crosshair & Zoom Event Rectangle
@overlay = @svg.append("rect")
.attr("class", "plot-event-target")
# Append Crosshair & Zoom Listening Targets
@appendCrosshairTarget(@transform)
@appendZoomTarget(@transform)
update: ->
preError = "#{@preError}update()"
_ = @
_rescaleX = @transform.rescaleX(@definition.x)
_bandwidth = Math.floor(@transform.k * @definition.x1.bandwidth())
# Pre-Append Data For Smooth transform
for key, row of @data
if row? and _.options.y[key]?
if @svg.selectAll(".bar-#{key}").node()[0] is null
console.log("Adding new BarPlot data set.")
@bars[key] = @barWrapper.append("g")
.attr("clip-path", "url(\#" + @clipPathId + ")")
.selectAll(".bar-#{key}")
.data(row)
.enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
# Create Focus Circles and Labels
@focusRect[key] = @hoverWrapper.append("rect")
.attr("width", @definition.x1.bandwidth())
.attr("height", 2)
.attr("class", "focus-rect-#{key}")
.attr("fill", @options.focusX.color)
#.attr("fill", @options.y[key].color)
.attr("transform", "translate(-10, -10)")
.style("display", "none")
.style("stroke", "rgb(255,255,255)")
.style("opacity", 0.75)
@focusText[key] = @hoverWrapper.append("text")
.attr("class", "focus-text-#{key}")
.attr("x", 11)
.attr("y", 7)
.style("display", "none")
.style("fill", @options.y[key].color)
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
else
# Update Data
@bars[key] = @barWrapper.select("g")
.selectAll(".bar-#{key}")
.data(row)
# Append new rect.
@bars[key].enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
# Remove deleted rect.
@bars[key].exit()
.remove()
# transitionDurationbar
@bars[key].attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
# Reset the overlay to last position.
@overlay.remove()
@overlay = @svg.append("rect")
.attr("class", "plot-event-target")
@appendCrosshairTarget(@transform)
@appendZoomTarget(@transform)
@calculateYAxisDims(@data)
@definition.y.domain([@definition.y.min, @definition.y.max]).nice()
#_rescaleX = @transform.rescaleX(@definition.x)
#for key, row of @data
# # Redraw the Bars
# @svg.selectAll(".bar-#{key}")
# .attr("x", (d) -> _rescaleX(d.x))
# .attr("width", Math.floor(@transform.k * @definition.x1.bandwidth()))
# Redraw the Y-Axis
@svg.select(".bar-plot-axis-y")
.call(@definition.yAxis)
if @options.y[0].maxBar?
@barWrapper.select(".bar-plot-max-bar")
.attr("y", @definition.y(@options.y[0].maxBar))
# Reset the zoom state
@setZoomTransform(@transform)
removeTemp: ->
@temp.remove()
appendCrosshairTarget: (transform) ->
# Move Crosshairs and Focus Circle Based on Mouse Location
if !@initialized
return
preError = "#{@preError}appendCrosshairTarget()"
_ = @
@overlay.datum(@data)
.attr("class", "overlay")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", () -> _.plotter.i.crosshairs.show())
.on("mouseout", () -> _.plotter.i.crosshairs.hide())
.on("mousemove", () ->
mouse = _.setCrosshair(transform)
_.plotter.i.crosshairs.set(transform, mouse)
)
appendZoomTarget: (transform) ->
if !@initialized
return
preError = "#{@preError}appendZoomTarget()"
_ = @
# Append the Zoom Rectangle
@overlay.attr("class", "zoom-pane")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
.style("fill", "none")
.style("pointer-events", "all")
.style("cursor", "move")
@svg.call(@definition.zoom, transform)
setZoomTransform: (transform) ->
# Set the current zoom transform state.
if !@initialized
return
preError = "#{@preError}.setZoomTransform(transform)"
_ = @
#_transform = if transform then transform else d3.event.transform
if transform?
@transform = transform
else if d3.event?
@transform = d3.event.transform
_transform = @transform
# Zoom the X-Axis
_rescaleX = _transform.rescaleX(@definition.x)
#_rescaleX1 = _transform.rescaleX(@definition.x1)
@svg.select(".bar-plot-axis-x").call(
@definition.xAxis.scale(_rescaleX)
)
# Set the scaleRange
@state.range.scale = @getDomainScale(_rescaleX)
@state.mean.scale = @getDomainMean(_rescaleX)
@setDataState()
@setIntervalState()
@setDataRequirement()
@setZoomState(_transform.k)
# Redraw Bars
for key, row of @data
@svg.selectAll(".bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width",
d3.max([1, Math.floor(_transform.k * @definition.x1.bandwidth())]))
@appendCrosshairTarget(_transform)
return _transform
setCrosshair: (transform, mouse) ->
# Set the Crosshair position
if !@initialized
return
preError = "#{@preError}.setCrosshair(mouse)"
_ = @
_dims = @definition.dimensions
directionLabel = (dir) ->
# Return a direction label for wind direction type items.
return switch
when dir > 360 or dir < 0 then "INV"
when dir >= 0 and dir < 11.25 then "N"
when dir >= 11.25 and dir < 33.75 then "NNE"
when dir >= 33.75 and dir < 56.25 then "NE"
when dir >= 56.25 and dir < 78.75 then "ENE"
when dir >= 78.75 and dir < 101.25 then "E"
when dir >= 101.25 and dir < 123.75 then "ESE"
when dir >= 123.75 and dir < 146.25 then "SE"
when dir >= 146.25 and dir < 168.75 then "SSE"
when dir >= 168.75 and dir < 191.25 then "S"
when dir >= 191.25 and dir < 213.75 then "SSW"
when dir >= 213.75 and dir < 236.25 then "SW"
when dir >= 236.25 and dir < 258.75 then "WSW"
when dir >= 258.75 and dir < 281.25 then "W"
when dir >= 281.25 and dir < 303.75 then "WNW"
when dir >= 303.75 and dir < 326.25 then "NW"
when dir >= 326.25 and dir < 348.75 then "NNW"
when dir >= 348.75 and dir <= 360 then "N"
for key, row of @data
_mouseTarget = @overlay.node()
#_datum = @overlay.datum()
_datum = row
mouse = if mouse then mouse else d3.mouse(_mouseTarget)
x0 = @definition.x.invert(mouse[0] + _dims.leftPadding)
if transform
x0 = @definition.x.invert(
transform.invertX(mouse[0] + _dims.leftPadding))
i1 = _.bisectDate(_datum, x0, 1)
i = if x0.getMinutes() >= 30 then i1 else (i1 - 1)
# Correct for Max & Min
if x0.getTime() <= @state.range.data[key].min.getTime()
i = i1
if x0.getTime() >= @state.range.data[key].max.getTime()
i = i1 - 1
if _datum[i]?
if transform
dx = transform.applyX(@definition.x(_datum[i].x))
else
dx = @definition.x(_datum[i].x)
dy = []
_value = []
if @options.y[key].variable != null
_value[key] = _datum[i]
if _value[key]?
dy[key] = @definition.y(_value[key].y)
_date = @displayDate(_value[key].x)
if !isNaN(dy[key]) and _value[key].y?
@focusRect[key].attr("transform", "translate(0, 0)")
cx = dx - _dims.leftPadding
if cx >= 0
@crosshairs.select(".crosshair-x")
.attr("x1", cx)
.attr("y1", _dims.topPadding)
.attr("x2", cx)
.attr("y2", _dims.innerHeight + _dims.topPadding)
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
@crosshairs.select(".crosshair-x-under")
.attr("x", cx)
.attr("y", _dims.topPadding)
.attr("width", (_dims.innerWidth - cx))
.attr("height", _dims.innerHeight)
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
fdtx = cx - 120
# [Disabled] - Tooltip Flip
# if cx < 150
# fdtx = cx + 10
@focusDateText
.attr("x", fdtx)
.attr("y", (_dims.topPadding + _dims.innerHeight - 3))
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
.text(_date)
if (
@options.y[key].variable != null and !isNaN(dy[key]) and
_value[key].y?
)
@focusRect[key]
.attr("width", transform.k * @definition.x1.bandwidth())
.attr("x", dx)
.attr("y", dy[key])
# [Disabled] - Tooltip Flip
textAnchor = "start"
# if dx + 80 > @definition.dimensions.width
# dx = dx - 14
# textAnchor = "end"
@focusText[key]
.attr("x", dx + _dims.leftPadding / 10 +
transform.k * @definition.x1.bandwidth() + 2)
.attr("y", dy[key] - _dims.topPadding / 10)
.attr("text-anchor", textAnchor)
.text(
if _value[key].y?
if _.options.y[0].variable is "wind_direction"
directionLabel(_value[key].y)
else
_value[key].y.toFixed(@options.decimals) + " " +
@options.y[key].units)
# Tooltip Overlap Prevention
#if (
# @options.y.variable != null and
# @options.y2.variable != null and
# @options.y3.variable != null
#)
# ypos = []
# @svg.selectAll('.focus-text')
# .attr("transform", (d, i) ->
# row =
# ind: i
# y: parseInt(d3.select(@).attr("y"))
# offset: 0
# ypos.push(row)
# return ""
# )
# .call((sel) ->
# ypos.sort((a, b) -> a.y - b.y)
# ypos.forEach ((p, i) ->
# if i > 0
# offset = Math.max(0, (ypos[i-1].y + 18) - ypos[i].y)
# if ypos[i].ind == 0
# offset = -offset
# ypos[i].offset = offset
# )
# )
# .attr("transform", (d, i) ->
# return "translate (0, #{ypos[i].offset})"
# )
return mouse
showCrosshair: ->
# Show the Crosshair
if !@initialized
return
@crosshairs.select(".crosshair-x")
.style("display", null)
@crosshairs.select(".crosshair-x-under")
.style("display", null)
@focusDateText.style("display", null)
for setId, row of @options.y
if row.variable != null
if @focusRect[setId]?
@focusRect[setId].style("display", null)
.attr("fill", @options.focusX.color)
#.attr("fill", row.color)
if @focusText[setId]?
@focusText[setId].style("display", null)
.style("color", row.color)
.style("fill", row.color)
hideCrosshair: ->
# Hide the Crosshair
if !@initialized
return
@crosshairs.select(".crosshair-x")
.style("display", "none")
@crosshairs.select(".crosshair-x-under")
.style("display", "none")
@focusDateText.style("display", "none")
for setId, row of @options.y
if row.variable != null
if @focusRect[setId]?
@focusRect[setId].style("display", "none")
if @focusText[setId]?
@focusText[setId].style("display", "none")
appendTitle: (title, subtitle) ->
# Append a Plot Title
_offsetFactor = 1
_mainSize = '16px'
_subSize = '12px'
if @device == 'small'
_offsetFactor = 0.4
_mainSize = '10px'
_subSize = '7px'
@title = @svg.append("g")
.attr("class", "bar-plot-title")
@title.append("text")
.attr("x", (@definition.dimensions.margin.left + 10))
.attr("y", (@definition.dimensions.margin.top / 2 - (4*_offsetFactor)))
.style("font-size", _mainSize)
.style("font-weight", 600)
.text(title)
if subtitle
@title.append("text")
.attr("x", (@definition.dimensions.margin.left + 10))
.attr("y", (@definition.dimensions.margin.top / 2 + (12*_offsetFactor)))
.style("font-size", _subSize)
.text(subtitle)
getState: ->
# Return the Current Plot state.
return @state
| true | #
# Northwest Avalanche Center (NWAC)
# Plotter Tools - D3 V.4 Line Plot (bar-plot.coffee)
#
# Air Sciences Inc. - 2016
# PI:NAME:<NAME>END_PI
#
window.Plotter ||= {}
window.Plotter.BarPlot = class BarPlot
constructor: (plotter, data, options) ->
@preError = "BarPlot."
@plotter = plotter
@initialized = false
_y = [
dataLoggerId: null
variable: null
ticks: 5
min: null
max: null
maxBar: null
color: "rgb(41, 128, 185)"
band:
minVariable: null
maxVariable: null
]
# Default Configuration
@defaults =
plotId: null
uuid: ''
debug: true
target: null
width: null
merge: false
decimals: 1
x:
variable: null
format: "%Y-%m-%dT%H:%M:%S-08:00"
min: null
max: null
ticks: 7
y: _y
zoom:
scale:
min: 0.05
max: 5
aspectDivisor: 5
transitionDuration: 500
weight: 2
axisColor: "rgb(0,0,0)"
font:
weight: 100
size: 12
focusX:
color: "rgb(52, 52, 52)"
crosshairX:
weight: 1
color: "rgb(149,165,166)"
requestInterval: 336
if options.x
options.x = @plotter.lib.mergeDefaults(options.x, @defaults.x)
options.y[0] = @plotter.lib.mergeDefaults(options.y[0], @defaults.y[0])
@options = @plotter.lib.mergeDefaults(options, @defaults)
@device = 'full'
@transform = d3.zoomIdentity
@links = [
{"variable": "battery_voltage", "title": "Battery Voltage"},
{"variable": "temperature", "title": "Temperature"},
{"variable": "relative_humidity", "title": "Relative Humidity"},
{"variable": "precipitation", "title": "Precipitation"},
{"variable": "snow_depth", "title": "Snow Depth"},
{"variable": "wind_direction", "title": "Wind Direction"},
{"variable": "wind_speed_average", "title": "Wind Speed"},
{"variable": "net_solar", "title": "Net Solar"},
{"variable": "solar_pyranometer", "title": "Solar Pyranometer"},
{"variable": "equip_temperature", "title": "Equipment Temperature"},
{"variable": "barometric_pressure", "title": "Barometric Pressure"},
{"variable": "snowfall_24_hour", "title": "24-Hr Snowfall"},
{"variable": "intermittent_snow", "title": "Intermittent Snow"}
]
# Wrapped Logging Functions
@log = (log...) ->
if @options.debug
@log = (log...) -> console.log(log)
# Minor Prototype Support Functions
@parseDate = d3.timeParse(@options.x.format)
@bisectDate = d3.bisector((d) -> d.x).left
@displayDate = d3.timeFormat("%b. %e, %I:%M %p")
@sortDatetimeAsc = (a, b) -> a.x - b.x
# Prepare the Data & Definition
@data = @processData(data)
@getDefinition()
@clipPathId = "bar-plot-clip-path-#{@plotter.lib.uuid()}"
@bars = []
@focusRect = []
@focusText = []
@skipBandDomainSet = false
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state =
range:
data: []
scale: _domainScale
length:
data: []
interval:
data: []
zoom: 1
request:
data: []
requested:
data: []
mean:
scale: _domainMean
if data[0].length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
processData: (data) ->
# Process a data set.
result = []
for setId, set of data
result[setId] = @processDataSet(set, setId)
return result
processDataSet: (data, dataSetId) ->
# Process a single set of data (Flat, versus 2-Level in processData)
_yOptions = @options.y[dataSetId]
result = []
for key, row of data
result[key] =
#x: row[PI:EMAIL:<EMAIL>END_PI]
x: new Date(
@parseDate(row[@options.x.variable]).getTime())
y: row[_yOptions.variable]
if _yOptions.band?
if _yOptions.band.minVariable
result[key].yMin = row[_yOptions.band.minVariable]
if _yOptions.band.maxVariable
result[key].yMax = row[_yOptions.band.maxVariable]
_result = new Plotter.Data(result)
result = _result._clean(_result.get())
return result.sort(@sortDatetimeAsc)
setData: (data) ->
# Set the initial data.
@data = [@processDataSet(data, 0)]
@getDefinition()
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state.range.scale = _domainScale
@state.mean.scale = _domainMean
if data.length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
addData: (data, dataSetId) ->
# Set the initial data.
@data[dataSetId] = @processDataSet(data, dataSetId)
@getDefinition()
# Initialize the State
_domainScale = null
_domainMean = null
if data.length > 0
_domainScale = @getDomainScale(@definition.x)
_domainMean = @getDomainMean(@definition.x)
@state.range.scale = _domainScale
@state.mean.scale = _domainMean
if data.length > 0
@setDataState()
@setIntervalState()
@setDataRequirement()
appendData: (data, dataSetId) ->
# Append the full data set.
_data = @processDataSet(data, dataSetId)
_set = new window.Plotter.Data(@data[dataSetId])
_set.append(_data, ["x"])
@data[dataSetId] = _set._clean(_set.get())
@data[dataSetId] = @data[dataSetId].sort(@sortDatetimeAsc)
# Reset the Data Range
if @initialized
@setDataState()
@setIntervalState()
@setDataRequirement()
removeData: (key) ->
# Removing sub key from data.
if key >= 0
delete @data[key]
delete @options[key]
@svg.select(".bar-plot-area-#{key}").remove()
@svg.select(".bar-plot-path-#{key}").remove()
@svg.select(".focus-rect-#{key}").remove()
@svg.select(".focus-text-#{key}").remove()
if @initialized
@setDataState()
@setIntervalState()
@setDataRequirement()
setDataState: ->
# Set Data Ranges
_len = @data.length-1
# for i in [0.._len]
# if @data[i] is undefined
# console.log("data[i] is (i, row)", i, @data[i])
for key, row of @data
@state.range.data[key] =
min: d3.min(@data[key], (d)-> d.x)
max: d3.max(@data[key], (d)-> d.x)
# Set Data Length States
@state.length.data[key] = @data[key].length
setIntervalState: ->
# Set the Data Collection Padding Intervals in Hours
for key, row of @data
@state.interval.data[key] =
min: ((@state.range.scale.min.getTime() -
@state.range.data[key].min.getTime())/3600000)
max: ((@state.range.data[key].max.getTime() -
@state.range.scale.max.getTime())/3600000)
setDataRequirement: ->
# Calculate how necessary a download, in what direction, and/or data
_now = new Date()
for key, row of @data
_data_max = @state.interval.data[key].max <
@options.requestInterval
@state.request.data[key] =
min: @state.interval.data[key].min < @options.requestInterval
max: _data_max
if !(@state.requested.data[key]?)
@state.requested.data[key] =
min: false
max: false
setZoomState: (k)->
@state.zoom = k
getDomainScale: (axis) ->
# Calculate the Min & Max Range of an Axis
result =
min: axis.domain()[0]
max: axis.domain()[1]
getDomainMean: (axis) ->
# Calculat the Mean of an Axis
center = new Date(d3.mean(axis.domain()))
center.setHours(center.getHours() + Math.round(center.getMinutes()/60))
center.setMinutes(0)
center.setSeconds(0)
center.setMilliseconds(0)
return center
getDefinition: ->
preError = "#{@preError}getDefinition():"
_ = @
# Define the Definition
@definition = {}
@calculateChartDims()
@calculateAxisDims(@data)
# Define D3 Methods
@definition.xAxis = d3.axisBottom().scale(@definition.x)
.ticks(Math.round(@definition.dimensions.width / 100))
@definition.yAxis = d3.axisLeft().scale(@definition.y)
.ticks(@options.y[0].ticks)
# Define the Domains
@definition.x.domain([@definition.x.min, @definition.x.max])
if !@skipBandDomainSet
@definition.x1.domain(@data[0].map((d) -> d.x))
@skipBandDomainSet = false
@definition.y.domain([@definition.y.min, @definition.y.max]).nice()
# Define the Zoom Method
_extent = [
[-Infinity, 0],
[(@definition.x(new Date()) + @definition.dimensions.margin.left),
@definition.dimensions.innerHeight]
]
@definition.zoom = d3.zoom()
.scaleExtent([@options.zoom.scale.min, @options.zoom.scale.max])
.translateExtent(_extent)
.on("zoom", () ->
transform = _.setZoomTransform()
_.plotter.i.zoom.set(transform)
)
setBandDomain: (bandDomain) ->
@definition.x1 = bandDomain
calculateChartDims: ->
# Calculate Basic DOM & SVG Dimensions
if @options.width?
width = Math.round(@options.width)
else
width = Math.round($(@options.target).width()) - 24
height = Math.round(width/@options.aspectDivisor)
if width > 1000
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.12)
left: Math.round(Math.pow(width, 0.6))
else if width > 600
@device = 'mid'
@options.font.size = @options.font.size/1.25
_height = @options.aspectDivisor/1.25
height = Math.round(width/_height)
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.14)
left: Math.round(Math.pow(width, 0.6))
else
@device = 'small'
@options.font.size = @options.font.size/1.5
_height = @options.aspectDivisor/1.5
height = Math.round(width/_height)
margin =
top: Math.round(height * 0.04)
right: Math.round(Math.pow(width, 0.3))
bottom: Math.round(height * 0.18)
left: Math.round(Math.pow(width, 0.6))
# Basic Dimention
@definition.dimensions =
width: width
height: height
margin: margin
# Define Translate Padding
@definition.dimensions.topPadding =
parseInt(@definition.dimensions.margin.top)
@definition.dimensions.bottomPadding =
parseInt(@definition.dimensions.height -
@definition.dimensions.margin.bottom)
@definition.dimensions.leftPadding =
parseInt(@definition.dimensions.margin.left)
@definition.dimensions.innerHeight =
parseInt(@definition.dimensions.height -
@definition.dimensions.margin.bottom - @definition.dimensions.margin.top)
@definition.dimensions.innerWidth =
parseInt(@definition.dimensions.width -
@definition.dimensions.margin.left - @definition.dimensions.margin.right)
# Define the X & Y Scales
@definition.x = d3.scaleTime().range([margin.left, (width-margin.right)])
@definition.x1 = d3.scaleBand()
.rangeRound([margin.left, (width-margin.right)], 0.05)
.padding(0.1)
@definition.y = d3.scaleLinear().range([(height-margin.bottom),
(margin.top)])
calculateAxisDims: (data) ->
@calculateXAxisDims(data)
@calculateYAxisDims(data)
calculateXAxisDims: (data) ->
# Calculate Min & Max X Values
if @options.x.min is null
@definition.x.min = d3.min(data[0], (d)-> d.x)
else
@definition.x.min = @parseDate(@options.x.min)
if @options.x.max is null
@definition.x.max = d3.max(data[0], (d)-> d.x)
else
@definition.x.max = @parseDate(@options.x.max)
calculateYAxisDims: (data) ->
# Calculate Min & Max Y Values
@definition.y.min = 0
@definition.y.max = 0
for subId, set of data
_setMin = d3.min([
d3.min(set, (d)-> d.y)
d3.min(set, (d)-> d.yMin)
])
_setMax = d3.max([
d3.max(set, (d)-> d.y)
d3.max(set, (d)-> d.yMax)
])
if _setMin < @definition.y.min or @definition.y.min is undefined
@definition.y.min = _setMin
if _setMax > @definition.y.max or @definition.y.max is undefined
@definition.y.max = _setMax
# Restore Viewability if Y-Min = Y-Max
if @definition.y.min == @definition.y.max
@definition.y.min = @definition.y.min * 0.8
@definition.y.max = @definition.y.min * 1.2
# Revert to Options
if @options.y[0].min?
@definition.y.min = @options.y[0].min
if @options.y[0].max?
@definition.y.max = @options.y[0].max
preAppend: ->
preError = "#{@preError}preAppend()"
_ = @
# Create the SVG Div
@outer = d3.select(@options.target).append("div")
.attr("class", "bar-plot-body")
.style("width", "#{@definition.dimensions.width}px")
.style("height", "#{@definition.dimensions.height}px")
.style("display", "inline-block")
# Create the Controls Div
@ctls = d3.select(@options.target).append("div")
.attr("class", "plot-controls")
.style("width", '23px')
.style("height", "#{@definition.dimensions.height}px")
.style("display", "inline-block")
.style("vertical-align", "top")
#if @data[0].length == 0
# if @options.type is "station"
# add_text = "Select the Plot's Station"
# sub_text = "Station type plots allow comparison of different variab\
# les from the same station."
# else if @options.type is "parameter"
# add_text = "Select the Plot's Parameter"
# sub_text = "Parameter type plots allow comparison of a single parama\
# ter at multiple stations"
# _offset = $(@options.target).offset()
# @temp = @outer.append("div")
# .attr("class", "new-temp-#{@options.plotId}")
# .style("position", "Relative")
# .style("top",
# "#{parseInt(@definition.dimensions.innerHeight/1.74)}px")
# .style("left",
# "#{parseInt(@definition.dimensions.innerWidth/6.5)}px")
# .style("width", "#{@definition.dimensions.innerWidth}px")
# .style("text-align", "center")
# @temp.append("p")
# .text(sub_text)
# .style("color", "#ggg")
# .style("font-size", "12px")
# Create the SVG
@svg = @outer.append("svg")
.attr("class", "bar-plot")
.attr("width", @definition.dimensions.width)
.attr("height", @definition.dimensions.height)
# Append a Clip Path
@svg.append("defs")
.append("clipPath")
.attr("id", @clipPathId)
.append("rect")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
# Append the X-Axis
@svg.append("g")
.attr("class", "bar-plot-axis-x")
.style("fill", "none")\
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.call(@definition.xAxis)
.attr("transform",
"translate(0, #{@definition.dimensions.bottomPadding})"
)
# Append the Y-Axis
@svg.append("g")
.attr("class", "bar-plot-axis-y")
.style("fill", "none")
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.call(@definition.yAxis)
.attr("transform", "translate(#{@definition.dimensions.leftPadding}, 0)")
append: ->
@initialized = true
if !@initialized
return
preError = "#{@preError}append()"
_ = @
# Update the X-Axis
@svg.select(".bar-plot-axis-x")
.call(@definition.xAxis)
@svg.select(".bar-plot-axis-y")
.call(@definition.yAxis)
# Append Axis Label
_y_title = "#{@options.y[0].title}"
if @options.y[0].units
_y_title = "#{_y_title} #{@options.y[0].units}"
_y_vert = -@definition.dimensions.margin.top
_y_offset = -@definition.dimensions.margin.left
# Y-Axis Title
@svg.select(".bar-plot-axis-y")
.append("text")
.text(_y_title)
.attr("class", "bar-plot-y-label")
.attr("x", _y_vert)
.attr("y", _y_offset)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.style("font-size", @options.font.size)
.style("font-weight", @options.font.weight)
.attr("fill", @options.axisColor)
# Append Bands & Bar Path
@barWrapper = @svg.append("g")
.attr("class", "bar-wrapper")
for key, row of @data
@bars[key] = @barWrapper.append("g")
.attr("clip-path", "url(\#" + @clipPathId + ")")
.selectAll(".bar-#{key}")
.data(row)
.enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _.definition.x(d.x))
.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
if @options.y[0].maxBar?
@barWrapper.append("rect")
.attr("class", "bar-plot-max-bar")
.attr("x", @definition.dimensions.leftPadding)
.attr("y", @definition.y(@options.y[0].maxBar))
.attr("width", (@definition.dimensions.innerWidth))
.attr("height", 1)
.style("color", '#gggggg')
.style("opacity", 0.4)
@hoverWrapper = @svg.append("g")
.attr("class", "hover-wrapper")
# Create Crosshairs
@crosshairs = @hoverWrapper.append("g")
.attr("class", "crosshair")
# Create Vertical line
@crosshairs.append("line")
.attr("class", "crosshair-x")
.style("stroke", @options.crosshairX.color)
.style("stroke-width", @options.crosshairX.weight)
.style("stroke-dasharray", ("3, 3"))
.style("fill", "none")
# Create the Focus Label Underlay
@crosshairs.append("rect")
.attr("class", "crosshair-x-under")
.style("fill", "rgb(255,255,255)")
.style("opacity", 0.1)
@focusDateText = @hoverWrapper.append("text")
.attr("class", "focus-date-text")
.attr("x", 9)
.attr("y", 7)
.style("display", "none")
.style("fill", "#000000")
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
for key, row of @data
# Create Focus Circles and Labels
@focusRect[key] = @hoverWrapper.append("rect")
.attr("width", @definition.x1.bandwidth())
.attr("height", 2)
.attr("class", "focus-rect-#{key}")
.attr("fill", @options.focusX.color)
#.attr("fill", @options.y[key].color)
.attr("transform", "translate(-10, -10)")
.style("display", "none")
.style("stroke", "rgb(255,255,255)")
.style("opacity", 0.75)
@focusText[key] = @hoverWrapper.append("text")
.attr("class", "focus-text-#{key}")
.attr("x", 11)
.attr("y", 7)
.style("display", "none")
.style("fill", @options.y[key].color)
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
# Append the Crosshair & Zoom Event Rectangle
@overlay = @svg.append("rect")
.attr("class", "plot-event-target")
# Append Crosshair & Zoom Listening Targets
@appendCrosshairTarget(@transform)
@appendZoomTarget(@transform)
update: ->
preError = "#{@preError}update()"
_ = @
_rescaleX = @transform.rescaleX(@definition.x)
_bandwidth = Math.floor(@transform.k * @definition.x1.bandwidth())
# Pre-Append Data For Smooth transform
for key, row of @data
if row? and _.options.y[key]?
if @svg.selectAll(".bar-#{key}").node()[0] is null
console.log("Adding new BarPlot data set.")
@bars[key] = @barWrapper.append("g")
.attr("clip-path", "url(\#" + @clipPathId + ")")
.selectAll(".bar-#{key}")
.data(row)
.enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
# Create Focus Circles and Labels
@focusRect[key] = @hoverWrapper.append("rect")
.attr("width", @definition.x1.bandwidth())
.attr("height", 2)
.attr("class", "focus-rect-#{key}")
.attr("fill", @options.focusX.color)
#.attr("fill", @options.y[key].color)
.attr("transform", "translate(-10, -10)")
.style("display", "none")
.style("stroke", "rgb(255,255,255)")
.style("opacity", 0.75)
@focusText[key] = @hoverWrapper.append("text")
.attr("class", "focus-text-#{key}")
.attr("x", 11)
.attr("y", 7)
.style("display", "none")
.style("fill", @options.y[key].color)
.style("text-shadow", "-2px -2px 0 rgb(255,255,255),
2px -2px 0 rgb(255,255,255), -2px 2px 0 rgb(255,255,255),
2px 2px 0 rgb(255,255,255)")
else
# Update Data
@bars[key] = @barWrapper.select("g")
.selectAll(".bar-#{key}")
.data(row)
# Append new rect.
@bars[key].enter()
.append("rect")
.attr("class", "bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
.style("fill", @options.y[key].color)
# Remove deleted rect.
@bars[key].exit()
.remove()
# transitionDurationbar
@bars[key].attr("x", (d) -> _rescaleX(d.x))
.attr("width", d3.max([1, _bandwidth]))
#.attr("x", (d) -> _.definition.x(d.x))
#.attr("width", d3.max([1, @definition.x1.bandwidth()]))
.attr("y", (d) -> _.definition.y(d.y))
.attr("height", (d) ->
_.definition.dimensions.innerHeight +
_.definition.dimensions.margin.top - _.definition.y(d.y)
)
# Reset the overlay to last position.
@overlay.remove()
@overlay = @svg.append("rect")
.attr("class", "plot-event-target")
@appendCrosshairTarget(@transform)
@appendZoomTarget(@transform)
@calculateYAxisDims(@data)
@definition.y.domain([@definition.y.min, @definition.y.max]).nice()
#_rescaleX = @transform.rescaleX(@definition.x)
#for key, row of @data
# # Redraw the Bars
# @svg.selectAll(".bar-#{key}")
# .attr("x", (d) -> _rescaleX(d.x))
# .attr("width", Math.floor(@transform.k * @definition.x1.bandwidth()))
# Redraw the Y-Axis
@svg.select(".bar-plot-axis-y")
.call(@definition.yAxis)
if @options.y[0].maxBar?
@barWrapper.select(".bar-plot-max-bar")
.attr("y", @definition.y(@options.y[0].maxBar))
# Reset the zoom state
@setZoomTransform(@transform)
removeTemp: ->
@temp.remove()
appendCrosshairTarget: (transform) ->
# Move Crosshairs and Focus Circle Based on Mouse Location
if !@initialized
return
preError = "#{@preError}appendCrosshairTarget()"
_ = @
@overlay.datum(@data)
.attr("class", "overlay")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", () -> _.plotter.i.crosshairs.show())
.on("mouseout", () -> _.plotter.i.crosshairs.hide())
.on("mousemove", () ->
mouse = _.setCrosshair(transform)
_.plotter.i.crosshairs.set(transform, mouse)
)
appendZoomTarget: (transform) ->
if !@initialized
return
preError = "#{@preError}appendZoomTarget()"
_ = @
# Append the Zoom Rectangle
@overlay.attr("class", "zoom-pane")
.attr("width", @definition.dimensions.innerWidth)
.attr("height", @definition.dimensions.innerHeight)
.attr("transform",
"translate(#{@definition.dimensions.leftPadding},
#{@definition.dimensions.topPadding})"
)
.style("fill", "none")
.style("pointer-events", "all")
.style("cursor", "move")
@svg.call(@definition.zoom, transform)
setZoomTransform: (transform) ->
# Set the current zoom transform state.
if !@initialized
return
preError = "#{@preError}.setZoomTransform(transform)"
_ = @
#_transform = if transform then transform else d3.event.transform
if transform?
@transform = transform
else if d3.event?
@transform = d3.event.transform
_transform = @transform
# Zoom the X-Axis
_rescaleX = _transform.rescaleX(@definition.x)
#_rescaleX1 = _transform.rescaleX(@definition.x1)
@svg.select(".bar-plot-axis-x").call(
@definition.xAxis.scale(_rescaleX)
)
# Set the scaleRange
@state.range.scale = @getDomainScale(_rescaleX)
@state.mean.scale = @getDomainMean(_rescaleX)
@setDataState()
@setIntervalState()
@setDataRequirement()
@setZoomState(_transform.k)
# Redraw Bars
for key, row of @data
@svg.selectAll(".bar-#{key}")
.attr("x", (d) -> _rescaleX(d.x))
.attr("width",
d3.max([1, Math.floor(_transform.k * @definition.x1.bandwidth())]))
@appendCrosshairTarget(_transform)
return _transform
setCrosshair: (transform, mouse) ->
# Set the Crosshair position
if !@initialized
return
preError = "#{@preError}.setCrosshair(mouse)"
_ = @
_dims = @definition.dimensions
directionLabel = (dir) ->
# Return a direction label for wind direction type items.
return switch
when dir > 360 or dir < 0 then "INV"
when dir >= 0 and dir < 11.25 then "N"
when dir >= 11.25 and dir < 33.75 then "NNE"
when dir >= 33.75 and dir < 56.25 then "NE"
when dir >= 56.25 and dir < 78.75 then "ENE"
when dir >= 78.75 and dir < 101.25 then "E"
when dir >= 101.25 and dir < 123.75 then "ESE"
when dir >= 123.75 and dir < 146.25 then "SE"
when dir >= 146.25 and dir < 168.75 then "SSE"
when dir >= 168.75 and dir < 191.25 then "S"
when dir >= 191.25 and dir < 213.75 then "SSW"
when dir >= 213.75 and dir < 236.25 then "SW"
when dir >= 236.25 and dir < 258.75 then "WSW"
when dir >= 258.75 and dir < 281.25 then "W"
when dir >= 281.25 and dir < 303.75 then "WNW"
when dir >= 303.75 and dir < 326.25 then "NW"
when dir >= 326.25 and dir < 348.75 then "NNW"
when dir >= 348.75 and dir <= 360 then "N"
for key, row of @data
_mouseTarget = @overlay.node()
#_datum = @overlay.datum()
_datum = row
mouse = if mouse then mouse else d3.mouse(_mouseTarget)
x0 = @definition.x.invert(mouse[0] + _dims.leftPadding)
if transform
x0 = @definition.x.invert(
transform.invertX(mouse[0] + _dims.leftPadding))
i1 = _.bisectDate(_datum, x0, 1)
i = if x0.getMinutes() >= 30 then i1 else (i1 - 1)
# Correct for Max & Min
if x0.getTime() <= @state.range.data[key].min.getTime()
i = i1
if x0.getTime() >= @state.range.data[key].max.getTime()
i = i1 - 1
if _datum[i]?
if transform
dx = transform.applyX(@definition.x(_datum[i].x))
else
dx = @definition.x(_datum[i].x)
dy = []
_value = []
if @options.y[key].variable != null
_value[key] = _datum[i]
if _value[key]?
dy[key] = @definition.y(_value[key].y)
_date = @displayDate(_value[key].x)
if !isNaN(dy[key]) and _value[key].y?
@focusRect[key].attr("transform", "translate(0, 0)")
cx = dx - _dims.leftPadding
if cx >= 0
@crosshairs.select(".crosshair-x")
.attr("x1", cx)
.attr("y1", _dims.topPadding)
.attr("x2", cx)
.attr("y2", _dims.innerHeight + _dims.topPadding)
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
@crosshairs.select(".crosshair-x-under")
.attr("x", cx)
.attr("y", _dims.topPadding)
.attr("width", (_dims.innerWidth - cx))
.attr("height", _dims.innerHeight)
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
fdtx = cx - 120
# [Disabled] - Tooltip Flip
# if cx < 150
# fdtx = cx + 10
@focusDateText
.attr("x", fdtx)
.attr("y", (_dims.topPadding + _dims.innerHeight - 3))
.attr("transform", "translate(#{_dims.leftPadding}, 0)")
.text(_date)
if (
@options.y[key].variable != null and !isNaN(dy[key]) and
_value[key].y?
)
@focusRect[key]
.attr("width", transform.k * @definition.x1.bandwidth())
.attr("x", dx)
.attr("y", dy[key])
# [Disabled] - Tooltip Flip
textAnchor = "start"
# if dx + 80 > @definition.dimensions.width
# dx = dx - 14
# textAnchor = "end"
@focusText[key]
.attr("x", dx + _dims.leftPadding / 10 +
transform.k * @definition.x1.bandwidth() + 2)
.attr("y", dy[key] - _dims.topPadding / 10)
.attr("text-anchor", textAnchor)
.text(
if _value[key].y?
if _.options.y[0].variable is "wind_direction"
directionLabel(_value[key].y)
else
_value[key].y.toFixed(@options.decimals) + " " +
@options.y[key].units)
# Tooltip Overlap Prevention
#if (
# @options.y.variable != null and
# @options.y2.variable != null and
# @options.y3.variable != null
#)
# ypos = []
# @svg.selectAll('.focus-text')
# .attr("transform", (d, i) ->
# row =
# ind: i
# y: parseInt(d3.select(@).attr("y"))
# offset: 0
# ypos.push(row)
# return ""
# )
# .call((sel) ->
# ypos.sort((a, b) -> a.y - b.y)
# ypos.forEach ((p, i) ->
# if i > 0
# offset = Math.max(0, (ypos[i-1].y + 18) - ypos[i].y)
# if ypos[i].ind == 0
# offset = -offset
# ypos[i].offset = offset
# )
# )
# .attr("transform", (d, i) ->
# return "translate (0, #{ypos[i].offset})"
# )
return mouse
showCrosshair: ->
# Show the Crosshair
if !@initialized
return
@crosshairs.select(".crosshair-x")
.style("display", null)
@crosshairs.select(".crosshair-x-under")
.style("display", null)
@focusDateText.style("display", null)
for setId, row of @options.y
if row.variable != null
if @focusRect[setId]?
@focusRect[setId].style("display", null)
.attr("fill", @options.focusX.color)
#.attr("fill", row.color)
if @focusText[setId]?
@focusText[setId].style("display", null)
.style("color", row.color)
.style("fill", row.color)
hideCrosshair: ->
# Hide the Crosshair
if !@initialized
return
@crosshairs.select(".crosshair-x")
.style("display", "none")
@crosshairs.select(".crosshair-x-under")
.style("display", "none")
@focusDateText.style("display", "none")
for setId, row of @options.y
if row.variable != null
if @focusRect[setId]?
@focusRect[setId].style("display", "none")
if @focusText[setId]?
@focusText[setId].style("display", "none")
appendTitle: (title, subtitle) ->
# Append a Plot Title
_offsetFactor = 1
_mainSize = '16px'
_subSize = '12px'
if @device == 'small'
_offsetFactor = 0.4
_mainSize = '10px'
_subSize = '7px'
@title = @svg.append("g")
.attr("class", "bar-plot-title")
@title.append("text")
.attr("x", (@definition.dimensions.margin.left + 10))
.attr("y", (@definition.dimensions.margin.top / 2 - (4*_offsetFactor)))
.style("font-size", _mainSize)
.style("font-weight", 600)
.text(title)
if subtitle
@title.append("text")
.attr("x", (@definition.dimensions.margin.left + 10))
.attr("y", (@definition.dimensions.margin.top / 2 + (12*_offsetFactor)))
.style("font-size", _subSize)
.text(subtitle)
getState: ->
# Return the Current Plot state.
return @state
|
[
{
"context": " key: 'app-key-1', id: 42 }\n @app2 = { key: 'app-key-2', id: 5 }\n @errorObject = {error: ''}\n ",
"end": 3983,
"score": 0.8069885969161987,
"start": 3975,
"tag": "KEY",
"value": "app-key-"
},
{
"context": "app).to.equal @app1\n expect(key).to.equa... | test/app_cache_test.coffee | jjzhang166/w3gram-server | 0 | async = require 'async'
AppList = W3gramServer.AppList
AppCache = W3gramServer.AppCache
describe 'AppCache', ->
beforeEach ->
@mockList = {}
@cache = new AppCache @mockList
describe '#getMak', ->
beforeEach ->
@mockList.getMakCallCount = 0
@mockList.getMak = (callback) ->
@getMakCallCount += 1
callback null, 'mock-mack'
return
it 'calls AppList#getMak only once', (done) ->
getValue = (_, callback) => @cache.getMak callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal 'mock-mack'
expect(@mockList.getMakCallCount).to.equal 1
done()
it 'reports errors', (done) ->
errorObject = {error: ''}
@mockList.getMak = (callback) ->
@getMakCallCount += 1
callback errorObject
return
@cache.getMak (error, mak) =>
expect(error).to.equal errorObject
expect(mak).not.to.be.ok
expect(@mockList.getMakCallCount).to.equal 1
done()
describe '#hasApps', ->
beforeEach ->
@apps = [{ key: 'app-key-1', id: 42 }, { key: 'app-key-2', id: 7 }]
@mockList.listCallCount = 0
@mockList.list = (callback) =>
@mockList.listCallCount += 1
callback null, @apps
return
it 'calls list as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) => @cache.hasApps callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal false
expect(@mockList.listCallCount).to.equal 5
done()
it 'calls list once if it returns apps', (done) ->
getValue = (_, callback) => @cache.hasApps callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal true
expect(@mockList.listCallCount).to.equal 1
done()
it 'updates key cache with returned apps', (done) ->
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
# The mock list doesn't have a findByKey method, so this will error out
# if the cache makes a call to AppList#findbyKey.
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[0]
@cache.getAppByKey 'app-key-2', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[1]
done()
it 'updates key cache with returned apps', (done) ->
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
# The mock list doesn't have a findByKey method, so this will error out
# if the cache makes a call to AppList#findbyKey.
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[0]
@cache.getAppById 7, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[1]
done()
it 'reports errors', (done) ->
errorObject = {error: ''}
@mockList.list = (callback) ->
@listCallCount += 1
callback errorObject
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.listCallCount).to.equal 1
done()
describe '#getAppByKey', ->
beforeEach ->
@app1 = { key: 'app-key-1', id: 42 }
@app2 = { key: 'app-key-2', id: 5 }
@errorObject = {error: ''}
@mockList.findByKeyCallCount = 0
@mockList.findByKey = (key, callback) =>
@mockList.findByKeyCallCount += 1
if key is 'app-key-1'
callback null, @app1
else if key is 'app-key-2'
callback null, @app2
else if key is 'error-key'
callback @errorObject
else
callback null, null
return
it 'calls AppList#findByKey as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) =>
@cache.getAppByKey 'missing-app-key', callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal null
expect(@mockList.findByKeyCallCount).to.equal 5
done()
it 'calls AppList#findByKey once if it returns apps', (done) ->
getValue = (_, callback) => @cache.getAppByKey 'app-key-1', callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.getAppByKey 'error-key', (error, hasApps) =>
expect(error).to.equal @errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'updates the hasApps cache if it returns an app', (done) ->
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'updates the app ID cache if it returns an app', (done) ->
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
@cache.getAppById 42, (error, cachedApp) =>
expect(error).to.equal null
expect(cachedApp).to.equal app
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'does not update the hasApps cache if it returns no apps', (done) ->
@cache.getAppByKey 'missing-app-key', (error, app) =>
expect(error).to.equal null
expect(app).to.equal null
expect(@mockList.findByKeyCallCount).to.equal 1
@mockList.listCallCount = 0
@mockList.list = (callback) ->
@listCallCount += 1
callback null, []
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal false
expect(@mockList.findByKeyCallCount).to.equal 1
expect(@mockList.listCallCount).to.equal 1
done()
describe '#getAppById', ->
beforeEach ->
@app1 = { key: 'app-key-1', id: 42 }
@app2 = { key: 'app-key-2', id: 5 }
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'calls AppList#findById as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) => @cache.getAppById 999, callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal null
expect(@mockList.findByIdCallCount).to.equal 5
done()
it 'calls AppList#findById once if it returns apps', (done) ->
getValue = (_, callback) => @cache.getAppById 42, callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.getAppById 666, (error, hasApps) =>
expect(error).to.equal @errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'updates the hasApps cache if it returns an app', (done) ->
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'updates the app key cache if it returns an app', (done) ->
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
@cache.getAppByKey 'app-key-1', (error, cachedApp) =>
expect(error).to.equal null
expect(cachedApp).to.equal app
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'does not update the hasApps cache if it returns no apps', (done) ->
@cache.getAppById 999, (error, app) =>
expect(error).to.equal null
expect(app).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
@mockList.listCallCount = 0
@mockList.list = (callback) ->
@listCallCount += 1
callback null, []
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal false
expect(@mockList.findByIdCallCount).to.equal 1
expect(@mockList.listCallCount).to.equal 1
done()
describe '#decodeReceiverId', ->
beforeEach ->
@app1 = new AppList.App key: 'app-key-1', id: 42, idKey: 'id-key-1'
@app2 = new AppList.App key: 'app-key-2', id: 5, idKey: 'id-key-2'
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'returns null for an empty id', (done) ->
@cache.decodeReceiverId '', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for a mis-formatted id', (done) ->
@cache.decodeReceiverId 'misformatted-id', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for an incorrect HMAC', (done) ->
@cache.decodeReceiverId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for an incorrect app id', (done) ->
@cache.decodeReceiverId '999.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for a poorly formatted device ID', (done) ->
@cache.decodeReceiverId '42.tablet device id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns the correct app and key for a good HMAC', (done) ->
hmac = @app1.receiverIdHmac 'tablet-device-id'
receiverId = "42.tablet-device-id.#{hmac}"
@cache.decodeReceiverId receiverId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '42_tablet-device-id'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'uses the app cache', (done) ->
@cache.decodeReceiverId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
hmac = @app1.receiverIdHmac 'tablet-device-id'
receiverId = "42.tablet-device-id.#{hmac}"
@cache.decodeReceiverId receiverId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '42_tablet-device-id'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.decodeReceiverId '666.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal @errorObject
expect(@mockList.findByIdCallCount).to.equal 1
done()
describe '#decodeListenerId', ->
beforeEach ->
@app1 = new AppList.App key: 'app-key-1', id: 42, idKey: 'id-key-1'
@app2 = new AppList.App key: 'app-key-2', id: 5, idKey: 'id-key-2'
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'returns null for an empty id', (done) ->
@cache.decodeListenerId '', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for a mis-formatted id', (done) ->
@cache.decodeListenerId 'misformatted-id', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for an incorrect HMAC', (done) ->
@cache.decodeListenerId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for an incorrect app id', (done) ->
@cache.decodeListenerId '999.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for a poorly formatted device ID', (done) ->
@cache.decodeListenerId '42.tablet device id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns the correct app and key for a good HMAC', (done) ->
hmac = @app1.listenerIdHmac 'tablet-device-id'
listenerId = "42.tablet-device-id.#{hmac}"
@cache.decodeListenerId listenerId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '42_tablet-device-id'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'uses the app cache', (done) ->
@cache.decodeListenerId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
hmac = @app1.listenerIdHmac 'tablet-device-id'
listenerId = "42.tablet-device-id.#{hmac}"
@cache.decodeListenerId listenerId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '42_tablet-device-id'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.decodeListenerId '666.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal @errorObject
expect(@mockList.findByIdCallCount).to.equal 1
done()
| 191154 | async = require 'async'
AppList = W3gramServer.AppList
AppCache = W3gramServer.AppCache
describe 'AppCache', ->
beforeEach ->
@mockList = {}
@cache = new AppCache @mockList
describe '#getMak', ->
beforeEach ->
@mockList.getMakCallCount = 0
@mockList.getMak = (callback) ->
@getMakCallCount += 1
callback null, 'mock-mack'
return
it 'calls AppList#getMak only once', (done) ->
getValue = (_, callback) => @cache.getMak callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal 'mock-mack'
expect(@mockList.getMakCallCount).to.equal 1
done()
it 'reports errors', (done) ->
errorObject = {error: ''}
@mockList.getMak = (callback) ->
@getMakCallCount += 1
callback errorObject
return
@cache.getMak (error, mak) =>
expect(error).to.equal errorObject
expect(mak).not.to.be.ok
expect(@mockList.getMakCallCount).to.equal 1
done()
describe '#hasApps', ->
beforeEach ->
@apps = [{ key: 'app-key-1', id: 42 }, { key: 'app-key-2', id: 7 }]
@mockList.listCallCount = 0
@mockList.list = (callback) =>
@mockList.listCallCount += 1
callback null, @apps
return
it 'calls list as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) => @cache.hasApps callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal false
expect(@mockList.listCallCount).to.equal 5
done()
it 'calls list once if it returns apps', (done) ->
getValue = (_, callback) => @cache.hasApps callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal true
expect(@mockList.listCallCount).to.equal 1
done()
it 'updates key cache with returned apps', (done) ->
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
# The mock list doesn't have a findByKey method, so this will error out
# if the cache makes a call to AppList#findbyKey.
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[0]
@cache.getAppByKey 'app-key-2', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[1]
done()
it 'updates key cache with returned apps', (done) ->
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
# The mock list doesn't have a findByKey method, so this will error out
# if the cache makes a call to AppList#findbyKey.
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[0]
@cache.getAppById 7, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[1]
done()
it 'reports errors', (done) ->
errorObject = {error: ''}
@mockList.list = (callback) ->
@listCallCount += 1
callback errorObject
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.listCallCount).to.equal 1
done()
describe '#getAppByKey', ->
beforeEach ->
@app1 = { key: 'app-key-1', id: 42 }
@app2 = { key: '<KEY>2', id: 5 }
@errorObject = {error: ''}
@mockList.findByKeyCallCount = 0
@mockList.findByKey = (key, callback) =>
@mockList.findByKeyCallCount += 1
if key is 'app-key-1'
callback null, @app1
else if key is 'app-key-2'
callback null, @app2
else if key is 'error-key'
callback @errorObject
else
callback null, null
return
it 'calls AppList#findByKey as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) =>
@cache.getAppByKey 'missing-app-key', callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal null
expect(@mockList.findByKeyCallCount).to.equal 5
done()
it 'calls AppList#findByKey once if it returns apps', (done) ->
getValue = (_, callback) => @cache.getAppByKey 'app-key-1', callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.getAppByKey 'error-key', (error, hasApps) =>
expect(error).to.equal @errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'updates the hasApps cache if it returns an app', (done) ->
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'updates the app ID cache if it returns an app', (done) ->
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
@cache.getAppById 42, (error, cachedApp) =>
expect(error).to.equal null
expect(cachedApp).to.equal app
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'does not update the hasApps cache if it returns no apps', (done) ->
@cache.getAppByKey 'missing-app-key', (error, app) =>
expect(error).to.equal null
expect(app).to.equal null
expect(@mockList.findByKeyCallCount).to.equal 1
@mockList.listCallCount = 0
@mockList.list = (callback) ->
@listCallCount += 1
callback null, []
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal false
expect(@mockList.findByKeyCallCount).to.equal 1
expect(@mockList.listCallCount).to.equal 1
done()
describe '#getAppById', ->
beforeEach ->
@app1 = { key: 'app-key-1', id: 42 }
@app2 = { key: 'app-key-2', id: 5 }
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'calls AppList#findById as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) => @cache.getAppById 999, callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal null
expect(@mockList.findByIdCallCount).to.equal 5
done()
it 'calls AppList#findById once if it returns apps', (done) ->
getValue = (_, callback) => @cache.getAppById 42, callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.getAppById 666, (error, hasApps) =>
expect(error).to.equal @errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'updates the hasApps cache if it returns an app', (done) ->
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'updates the app key cache if it returns an app', (done) ->
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
@cache.getAppByKey 'app-key-1', (error, cachedApp) =>
expect(error).to.equal null
expect(cachedApp).to.equal app
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'does not update the hasApps cache if it returns no apps', (done) ->
@cache.getAppById 999, (error, app) =>
expect(error).to.equal null
expect(app).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
@mockList.listCallCount = 0
@mockList.list = (callback) ->
@listCallCount += 1
callback null, []
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal false
expect(@mockList.findByIdCallCount).to.equal 1
expect(@mockList.listCallCount).to.equal 1
done()
describe '#decodeReceiverId', ->
beforeEach ->
@app1 = new AppList.App key: 'app-key-1', id: 42, idKey: 'id-key-1'
@app2 = new AppList.App key: 'app-key-2', id: 5, idKey: 'id-key-2'
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'returns null for an empty id', (done) ->
@cache.decodeReceiverId '', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for a mis-formatted id', (done) ->
@cache.decodeReceiverId 'misformatted-id', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for an incorrect HMAC', (done) ->
@cache.decodeReceiverId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for an incorrect app id', (done) ->
@cache.decodeReceiverId '999.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for a poorly formatted device ID', (done) ->
@cache.decodeReceiverId '42.tablet device id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns the correct app and key for a good HMAC', (done) ->
hmac = @app1.receiverIdHmac 'tablet-device-id'
receiverId = "42.tablet-device-id.#{hmac}"
@cache.decodeReceiverId receiverId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '<KEY>'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'uses the app cache', (done) ->
@cache.decodeReceiverId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
hmac = @app1.receiverIdHmac 'tablet-device-id'
receiverId = "42.tablet-device-id.#{hmac}"
@cache.decodeReceiverId receiverId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '<KEY>'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.decodeReceiverId '666.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal @errorObject
expect(@mockList.findByIdCallCount).to.equal 1
done()
describe '#decodeListenerId', ->
beforeEach ->
@app1 = new AppList.App key: 'app-key-1', id: 42, idKey: 'id-key-1'
@app2 = new AppList.App key: 'app-key-2', id: 5, idKey: 'id-key-2'
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'returns null for an empty id', (done) ->
@cache.decodeListenerId '', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for a mis-formatted id', (done) ->
@cache.decodeListenerId 'misformatted-id', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for an incorrect HMAC', (done) ->
@cache.decodeListenerId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for an incorrect app id', (done) ->
@cache.decodeListenerId '999.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for a poorly formatted device ID', (done) ->
@cache.decodeListenerId '42.tablet device id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns the correct app and key for a good HMAC', (done) ->
hmac = @app1.listenerIdHmac 'tablet-device-id'
listenerId = "42.tablet-device-id.#{hmac}"
@cache.decodeListenerId listenerId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '<KEY>id'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'uses the app cache', (done) ->
@cache.decodeListenerId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
hmac = @app1.listenerIdHmac 'tablet-device-id'
listenerId = "42.tablet-device-id.#{hmac}"
@cache.decodeListenerId listenerId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal '<KEY>'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.decodeListenerId '666.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal @errorObject
expect(@mockList.findByIdCallCount).to.equal 1
done()
| true | async = require 'async'
AppList = W3gramServer.AppList
AppCache = W3gramServer.AppCache
describe 'AppCache', ->
beforeEach ->
@mockList = {}
@cache = new AppCache @mockList
describe '#getMak', ->
beforeEach ->
@mockList.getMakCallCount = 0
@mockList.getMak = (callback) ->
@getMakCallCount += 1
callback null, 'mock-mack'
return
it 'calls AppList#getMak only once', (done) ->
getValue = (_, callback) => @cache.getMak callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal 'mock-mack'
expect(@mockList.getMakCallCount).to.equal 1
done()
it 'reports errors', (done) ->
errorObject = {error: ''}
@mockList.getMak = (callback) ->
@getMakCallCount += 1
callback errorObject
return
@cache.getMak (error, mak) =>
expect(error).to.equal errorObject
expect(mak).not.to.be.ok
expect(@mockList.getMakCallCount).to.equal 1
done()
describe '#hasApps', ->
beforeEach ->
@apps = [{ key: 'app-key-1', id: 42 }, { key: 'app-key-2', id: 7 }]
@mockList.listCallCount = 0
@mockList.list = (callback) =>
@mockList.listCallCount += 1
callback null, @apps
return
it 'calls list as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) => @cache.hasApps callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal false
expect(@mockList.listCallCount).to.equal 5
done()
it 'calls list once if it returns apps', (done) ->
getValue = (_, callback) => @cache.hasApps callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal true
expect(@mockList.listCallCount).to.equal 1
done()
it 'updates key cache with returned apps', (done) ->
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
# The mock list doesn't have a findByKey method, so this will error out
# if the cache makes a call to AppList#findbyKey.
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[0]
@cache.getAppByKey 'app-key-2', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[1]
done()
it 'updates key cache with returned apps', (done) ->
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
# The mock list doesn't have a findByKey method, so this will error out
# if the cache makes a call to AppList#findbyKey.
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[0]
@cache.getAppById 7, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @apps[1]
done()
it 'reports errors', (done) ->
errorObject = {error: ''}
@mockList.list = (callback) ->
@listCallCount += 1
callback errorObject
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.listCallCount).to.equal 1
done()
describe '#getAppByKey', ->
beforeEach ->
@app1 = { key: 'app-key-1', id: 42 }
@app2 = { key: 'PI:KEY:<KEY>END_PI2', id: 5 }
@errorObject = {error: ''}
@mockList.findByKeyCallCount = 0
@mockList.findByKey = (key, callback) =>
@mockList.findByKeyCallCount += 1
if key is 'app-key-1'
callback null, @app1
else if key is 'app-key-2'
callback null, @app2
else if key is 'error-key'
callback @errorObject
else
callback null, null
return
it 'calls AppList#findByKey as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) =>
@cache.getAppByKey 'missing-app-key', callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal null
expect(@mockList.findByKeyCallCount).to.equal 5
done()
it 'calls AppList#findByKey once if it returns apps', (done) ->
getValue = (_, callback) => @cache.getAppByKey 'app-key-1', callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.getAppByKey 'error-key', (error, hasApps) =>
expect(error).to.equal @errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'updates the hasApps cache if it returns an app', (done) ->
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'updates the app ID cache if it returns an app', (done) ->
@cache.getAppByKey 'app-key-1', (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByKeyCallCount).to.equal 1
@cache.getAppById 42, (error, cachedApp) =>
expect(error).to.equal null
expect(cachedApp).to.equal app
expect(@mockList.findByKeyCallCount).to.equal 1
done()
it 'does not update the hasApps cache if it returns no apps', (done) ->
@cache.getAppByKey 'missing-app-key', (error, app) =>
expect(error).to.equal null
expect(app).to.equal null
expect(@mockList.findByKeyCallCount).to.equal 1
@mockList.listCallCount = 0
@mockList.list = (callback) ->
@listCallCount += 1
callback null, []
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal false
expect(@mockList.findByKeyCallCount).to.equal 1
expect(@mockList.listCallCount).to.equal 1
done()
describe '#getAppById', ->
beforeEach ->
@app1 = { key: 'app-key-1', id: 42 }
@app2 = { key: 'app-key-2', id: 5 }
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'calls AppList#findById as long as it returns no apps', (done) ->
@apps = []
getValue = (_, callback) => @cache.getAppById 999, callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal null
expect(@mockList.findByIdCallCount).to.equal 5
done()
it 'calls AppList#findById once if it returns apps', (done) ->
getValue = (_, callback) => @cache.getAppById 42, callback
async.mapSeries [1..5], getValue, (error, result) =>
expect(error).not.to.be.ok
expect(result).to.be.an 'array'
expect(result.length).to.equal 5
for i in [1...5]
expect(result[i]).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.getAppById 666, (error, hasApps) =>
expect(error).to.equal @errorObject
expect(hasApps).not.to.be.ok
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'updates the hasApps cache if it returns an app', (done) ->
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal true
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'updates the app key cache if it returns an app', (done) ->
@cache.getAppById 42, (error, app) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(@mockList.findByIdCallCount).to.equal 1
@cache.getAppByKey 'app-key-1', (error, cachedApp) =>
expect(error).to.equal null
expect(cachedApp).to.equal app
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'does not update the hasApps cache if it returns no apps', (done) ->
@cache.getAppById 999, (error, app) =>
expect(error).to.equal null
expect(app).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
@mockList.listCallCount = 0
@mockList.list = (callback) ->
@listCallCount += 1
callback null, []
return
@cache.hasApps (error, hasApps) =>
expect(error).to.equal null
expect(hasApps).to.equal false
expect(@mockList.findByIdCallCount).to.equal 1
expect(@mockList.listCallCount).to.equal 1
done()
describe '#decodeReceiverId', ->
beforeEach ->
@app1 = new AppList.App key: 'app-key-1', id: 42, idKey: 'id-key-1'
@app2 = new AppList.App key: 'app-key-2', id: 5, idKey: 'id-key-2'
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'returns null for an empty id', (done) ->
@cache.decodeReceiverId '', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for a mis-formatted id', (done) ->
@cache.decodeReceiverId 'misformatted-id', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for an incorrect HMAC', (done) ->
@cache.decodeReceiverId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for an incorrect app id', (done) ->
@cache.decodeReceiverId '999.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for a poorly formatted device ID', (done) ->
@cache.decodeReceiverId '42.tablet device id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns the correct app and key for a good HMAC', (done) ->
hmac = @app1.receiverIdHmac 'tablet-device-id'
receiverId = "42.tablet-device-id.#{hmac}"
@cache.decodeReceiverId receiverId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal 'PI:KEY:<KEY>END_PI'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'uses the app cache', (done) ->
@cache.decodeReceiverId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
hmac = @app1.receiverIdHmac 'tablet-device-id'
receiverId = "42.tablet-device-id.#{hmac}"
@cache.decodeReceiverId receiverId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal 'PI:KEY:<KEY>END_PI'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.decodeReceiverId '666.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal @errorObject
expect(@mockList.findByIdCallCount).to.equal 1
done()
describe '#decodeListenerId', ->
beforeEach ->
@app1 = new AppList.App key: 'app-key-1', id: 42, idKey: 'id-key-1'
@app2 = new AppList.App key: 'app-key-2', id: 5, idKey: 'id-key-2'
@errorObject = {error: ''}
@mockList.findByIdCallCount = 0
@mockList.findById = (id, callback) =>
@mockList.findByIdCallCount += 1
if id is 42
callback null, @app1
else if id is 5
callback null, @app2
else if id is 666
callback @errorObject
else
callback null, null
return
it 'returns null for an empty id', (done) ->
@cache.decodeListenerId '', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for a mis-formatted id', (done) ->
@cache.decodeListenerId 'misformatted-id', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 0
done()
it 'returns null for an incorrect HMAC', (done) ->
@cache.decodeListenerId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for an incorrect app id', (done) ->
@cache.decodeListenerId '999.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns null for a poorly formatted device ID', (done) ->
@cache.decodeListenerId '42.tablet device id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'returns the correct app and key for a good HMAC', (done) ->
hmac = @app1.listenerIdHmac 'tablet-device-id'
listenerId = "42.tablet-device-id.#{hmac}"
@cache.decodeListenerId listenerId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal 'PI:KEY:<KEY>END_PIid'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'uses the app cache', (done) ->
@cache.decodeListenerId '42.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal null
expect(key).to.equal null
expect(@mockList.findByIdCallCount).to.equal 1
hmac = @app1.listenerIdHmac 'tablet-device-id'
listenerId = "42.tablet-device-id.#{hmac}"
@cache.decodeListenerId listenerId, (error, app, key) =>
expect(error).to.equal null
expect(app).to.equal @app1
expect(key).to.equal 'PI:KEY:<KEY>END_PI'
expect(@mockList.findByIdCallCount).to.equal 1
done()
it 'reports errors', (done) ->
@cache.decodeListenerId '666.tablet-device-id.aaa', (error, app, key) =>
expect(error).to.equal @errorObject
expect(@mockList.findByIdCallCount).to.equal 1
done()
|
[
{
"context": " for the language (\"js\", \"php\", \"c\", etc.)\nname: 'Cordy' # The title that will show up in grammar selecti",
"end": 123,
"score": 0.9851115345954895,
"start": 118,
"tag": "NAME",
"value": "Cordy"
}
] | grammars/cordy.cson | The-White-Dragon/language-cordy | 0 | scopeName: 'source.co' # <scope> should be a short, unique indicator for the language ("js", "php", "c", etc.)
name: 'Cordy' # The title that will show up in grammar selection and on your status bar.
fileTypes: [ # An array of file extensions.
'co'
]
firstLineMatch: '' # A regular expression that is matched against the first line of the document when Atom is trying to decide if the grammar is appropriate. Useful for shell scripts, mostly.
patterns: [ # An array of individual pattern declarations.
{ include: '#comment' }
{ include: '#directives' }
{ include: '#attribute' }
{ include: '#parameter' }
{ include: '#declarations' }
]
repository: # An array of rules. If you're going to be referencing one bit of code over and over again, stick it here so that you can edit all in one place.
declarations:
patterns: [
{ include: '#comment' }
{ include: '#preprocessor' }
{ include: '#type-declarations' }
]
parameter:
begin: '^\\{'
beginCaptures:
0: name: 'punctuation.parameter.open.cordy'
end: '\\}$'
endCaptures:
0: name: 'punctuation.parameter.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
attribute:
begin: '^\\['
beginCaptures:
0: name: 'punctuation.attribute.open.cordy'
end: '\\]$'
endCaptures:
0: name: 'punctuation.attribute.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
"type-declarations":
patterns: [
{ include: '#comment' }
{ include: '#storage-modifier' }
{ include: '#class-declaration' }
{ include: '#enum-declaration' }
{ include: '#interface-declaration' }
]
comment:
patterns: [
{
name: 'comment.block.cordy'
begin: '\\#\\*'
beginCaptures:
0: name: 'punctuation.definition.comment.cordy'
end: '\\*\\#'
endCaptures:
0: name: 'punctuation.definition.comment.cordy'
}
{
name: 'comment.line.cordy'
begin: '\\#\\#'
beginCaptures:
0: name: 'punctuation.definition.comment.cordy'
end: '\\#\\#|$'
endCaptures:
0: name: 'punctuation.definition.comment.cordy'
}
]
"storage-modifier":
match: '\\b(public|protected|internal|private|sealed|static)\\b'
name: 'storage.modifier.cordy'
"class-declaration":
begin: '(?=\\bclass\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(class)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.class.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-parameter-list' }
{ include: '#type-settings-list' }
{ include: '#base-types' }
{ include: '#generic-constraints' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#class-members' }
]
"interface-declaration":
begin: '(?=\\binterface\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(interface)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.interface.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-parameter-list' }
{ include: '#type-settings-list' }
{ include: '#base-types' }
{ include: '#generic-constraints' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#interface-members' }
]
"enum-declaration":
begin: '(?=\\benum\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(enum)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.enum.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-settings-list' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#expression'}
]
"base-types":
name: 'meta.basetypes.cordy'
begin: ':'
beginCaptures:
0: name: 'punctuation.separator.colon'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#type' }
{ include: '#punctuation-comma' }
{ include: '#preprocessor' }
{ include: '#comment' }
]
type:
name: 'meta.type.cordy'
patterns: [
{ include: '#comment' }
{ include: '#tuple-type' }
{ include: '#type-name' }
{ include: '#type-args' }
{ include: '#type-params' }
{ include: '#type-array-suffix' }
]
value:
name: 'container.value.cordy'
patterns: [
{ include: '#string' }
{ # integer binary
match: '-?0[bB][01][01_]*'
name: 'constant.numeric.integer.binary.cordy'
}
{ # integer octal
match: '-?0[oO][0-7][0-7_]*'
name: 'constant.numeric.integer.octal.cordy'
}
{ # integer hexadecimal
match: '-?0[xX][0-9a-fA-F][0-9a-fA-F_]*'
name: 'constant.numeric.integer.hexadecimal.cordy'
}
{ # float
match: '-?(?:\\d[\\d_]*)?[.,]\\d[\\d_]*'
name: 'constant.numeric.float.cordy'
}
{ # integer decimal
match: '-?[0-9][0-9_]*'
name: 'constant.numeric.integer.decimal.cordy'
}
]
string:
patterns: [
{ #default string
name: 'string.quoted.cordy'
begin: '(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
]
}
{ # verbatim string
name: 'string.verbatim.cordy'
begin: '@(["\'`])'
end: '((?!\\1\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(["\'`])\\1'
name: 'constant.character.escape.cordy'
}
]
}
{ # interpolated string
name: 'string.interpolated.cordy'
begin: '\\$(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
{
name: 'meta.interpolation.cordy'
begin: '\\{'
beginCaptures:
0: name: 'punctuation.curlybracket.open.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.curlybracket.closed.cordy'
patterns: [
{include: '#expression'}
]
}
]
}
{ # interpolated verbatim string
name: 'string.interpolated-verbatim.cordy'
begin: '(?:\\$@|@\\$)(["\'`])'
end: '((?!\\1\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(["\'`])\\1'
name: 'constant.character.escape.cordy'
}
{
name: 'meta.interpolation.cordy'
begin: '\\{'
beginCaptures:
0: name: 'punctuation.curlybracket.open.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.curlybracket.closed.cordy'
patterns: [
{include: '#expression'}
]
}
]
}
{ # regex string
name: 'string.regex.cordy'
begin: '\\~(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
#TODO: make highlighting support of different regex elements
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
]
}
]
"type-array-suffix":
begin: '\\['
beginCaptures:
0: name: 'punctuation.squarebracket.open.cordy'
end: '\\]'
endCaptures:
0: name: 'punctuation.squarebracket.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"type-params":
begin: '\\{'
beginCaptures:
0: name: 'punctuation.definition.typeparameters.begin.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.definition.typeparameters.end.cordy'
patterns: [
{ include: '#comment' }
{ include: '#value' }
{ include: '#punctuation-comma' }
]
"type-args":
begin: '\\<'
beginCaptures:
0: name: 'punctuation.definition.typearguments.begin.cordy'
end: '\\>'
endCaptures:
0: name: 'punctuation.definition.typearguments.end.cordy'
patterns: [
{ include: '#comment' }
{ include: '#type' }
{ include: '#punctuation-comma' }
]
"type-name":
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\s*(\\.)'
captures:
1: name: 'entity.name.type.cordy'
2: name: 'punctuation.accessor.cordy'
}
{
match: '(\\.)\\s*([@$_a-zA-Z]\\w*)'
captures:
1: name: 'punctuation.accessor.cordy'
2: name: 'entity.name.type.cordy'
}
{
match: '[@$_a-zA-Z]\\w*'
name: 'entity.name.type.cordy'
}
]
"tuple-type":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [
{ include: '#tuple-element' }
{ include: '#punctuation-comma' }
]
"tuple-element":
match: '''(?x)
(?<type>
(?:
(?<nameAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\s*)*
)
)
(?:(\\g<id>)\\b)?
'''
captures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.variable.tuple-element.cordy'
"type-parameter-list":
begin: '\\<'
beginCaptures:
0: name: 'punctuation.definition.typeparameters.begin.cordy'
end: '\\>'
endCaptures:
0: name: 'punctuation.definition.typeparameters.end.cordy'
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\b'
captures:
1: name: 'entity.name.type.type-parameter.cordy'
}
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"type-settings-list":
begin: '\\{'
beginCaptures:
0: name: 'punctuation.definition.typesettings.begin.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.definition.typesettings.end.cordy'
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\b'
captures:
1: name: 'variable.other.parameter.cordy'
}
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"punctuation-comma":
match: ','
name: 'punctuation.separator.comma.cordy'
"class-members":
patterns: [
{ include: '#comment' }
{ include: '#parameter' }
{ include: '#attribute' }
{ include: '#preprocessor' }
{ include: '#storage-modifier' }
{ include: '#event-declaration'}
{ include: '#property-declaration' }
{ include: '#operator-declaration' }
{ include: '#function-declaration' }
{ include: '#constructor-declaration' }
{ include: '#indexer-declaration' }
]
"interface-members":
patterns: [
{ include: '#comment' }
{ include: '#parameter' }
{ include: '#attribute' }
{ include: '#preprocessor' }
{ include: '#event-definition'}
{ include: '#operator-definition' }
{ include: '#function-definition' }
{ include: '#property-definition' }
{ include: '#constructor-definition' }
{ include: '#indexer-definition' }
]
"event-declaration":
begin: '(\\bevent\\b)\\s+([$@_a-zA-Z]\\w*)\\s*(?=\\()'
beginCaptures:
1: name: 'keyword.other.event.cordy'
2: name: 'entity.name.event.$2.cordy'
end: '^$'
patterns: [
{include: '#comment'}
{include: '#function-args'}
{
begin: '\\t(?:(internal|private)\\s+)?(?:(protected)\\s+)?(\\badd\\b)'
beginCaptures:
1: patterns: [{include: '#storage-modifier'}]
2: patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.add.cordy'
end: '(?=^$|^\\t[^\\t])'
patterns: [{include: '#code-block'}]
}
{
begin: '\\t(?:(internal|private)\\s+)?(?:(protected)\\s+)?(\\bremove\\b)'
beginCaptures:
1: patterns: [{include: '#storage-modifier'}]
2: patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.remove.cordy'
end: '(?=^$|^\\t[^\\t])'
patterns: [{include: '#code-block'}]
}
]
"event-definition":
begin: '(\\bevent\\b)\\s+([$@_a-zA-Z]\\w*)\\s*(?=\\()'
beginCaptures:
1: name: 'keyword.other.event.cordy'
2: name: 'entity.name.event.$2.cordy'
end: '^$'
patterns: [
{include: '#comment'}
{include: '#function-args'}
]
"constructor-declaration":
begin: '''(?x)
\\s*(new)\\s*
(?=\\()
'''
beginCaptures:
1: name: 'entity.name.constructor.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
{ include: '#code-block' }
]
"constructor-definition":
begin: '''(?x)
\\s*(new)\\s*
(?=\\()
'''
beginCaptures:
1: name: 'entity.name.constructor.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
]
"indexer-declaration":
begin: '''(?x)
\\s*(this)\\s*
(?=\\[)
'''
beginCaptures:
1: name: 'entity.name.indexer.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#indexer-args' }
{ include: '#code-block' }
]
"indexer-definition":
begin: '''(?x)
\\s*(this)\\s*
(?=\\[)
'''
beginCaptures:
1: name: 'entity.name.indexer.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#indexer-args' }
]
"operator-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+([<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3})\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'keyword.operator.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#operator-args' }
{ include: '#code-block' }
]
"operator-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+([<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3})\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'keyword.operator.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#operator-args' }
]
"function-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.function.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
{ include: '#code-block' }
]
"function-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.function.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
]
"code-block":
name: 'block'
begin: '(\\t*)\\t'
end: '(?=^\\1\\t*|^$)'
patterns: [
{ include: '#comment'}
{ include: '$self' }
{ include: '#statement' }
]
statement:
patterns: [
{ include: '#comment' }
{ include: '#return-statement' }
{ include: '#if-statement' }
{ include: '#elif-statement' }
{ include: '#else-statement' }
{ include: '#for-statement' }
{ include: '#while-statement' }
{ include: '#do-while-statement' }
{ include: '#try-statement' }
{ include: '#catch-statement' }
{ include: '#finally-statement' }
{ include: '#switch-statement'}
{ include: '#switch-default-statement'}
{ include: '#break-statement'}
{ include: '#continue-statement'}
{ include: '#expression' }
]
"break-statement":
match: '\\bbreak\\b'
name: 'keyword.control.break.cordy'
"continue-statement":
match: '\\bcontinue\\b'
name: 'keyword.control.continue.cordy'
"switch-statement":
begin: '(\\t*)(\\bswitch\\b)'
beginCaptures:
2: name: 'keyword.control.switch.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"switch-default-statement":
begin: '(\\bdefault\\b)\\s*(:)\\s*(.*)'
beginCaptures:
1: name: 'keyword.control.default.cordy'
2: name: 'punctuation.separator.colon.cordy'
3: patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"try-statement":
begin: '(\\t*)(\\btry\\b)'
beginCaptures:
2: name: 'keyword.control.try.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"catch-statement":
begin: '(\\t*)(\\bcatch\\b)\\s*(.*)'
beginCaptures:
2: name: 'keyword.control.catch.cordy'
3: patterns: [include: '#expression']
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"finally-statement":
begin: '(\\t*)(\\bfinally\\b)'
beginCaptures:
2: name: 'keyword.control.finally.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"do-while-statement":
begin: '(\\t*)(\\bdo\\b)'
beginCaptures:
2: name: 'keyword.control.do.cordy'
3:
patterns: [{include: '#expression'}]
end: '\\t+(\\bwhile\\b)(.*)'
endCaptures:
1: name: 'keyword.control.while.cordy'
2: patterns: [{include: '#expression'}]
patterns: [{include: '#code-block'}]
"while-statement":
begin: '(\\t*)(\\bwhile\\b)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.while.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"for-statement":
begin: '(\\t*)(\\bfor\\b)\\s+'
beginCaptures:
2: name: 'keyword.control.for.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [
{include: '#expression'}
{include: '#separator-comma'}
{include: '#code-block'}
]
"if-statement":
name: 'if'
begin: '(\\t*)(\\bif\\b)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.if.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*)'
patterns: [{include: '#code-block'}]
"else-statement":
begin: '(\\t*)(else)\\s*$'
beginCaptures:
2: name: 'keyword.control.else.cordy'
end: '(?=^\\1\\t*)'
patterns: [{include: '#code-block'}]
"elif-statement":
begin: '(\\t*)(el(?:se\\s*)?if)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.elseif.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*)'
captures: [
{ include: '#code-block' }
]
"return-statement":
name: 'return'
begin: '\\breturn\\b\\s*'
beginCaptures:
0: name: 'keyword.control.return.cordy'
end: '(?=\\t+|^$)'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
"indexer-args":
begin: '\\['
beginCaptures:
0: name: 'punctuation.squarebracket.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#punctuation-comma' }
{
match: '\\]'
name: 'punctuation.squarebracket.close.cordy'
}
]
"function-args":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#punctuation-comma' }
{
match: '\\)'
name: 'punctuation.parenthesis.close.cordy'
}
]
"operator-args":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#expression-operators' }
{
match: '\\)'
name: 'punctuation.parenthesis.close.cordy'
}
]
arg:
name: 'arg'
match: '''(?x)
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
'''
captures:
1:
patterns: [{include: '#type'}]
7: name: 'variable.parameter.function.cordy'
"property-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?==|\\bis\\b)
'''
end: '(?=^$)'
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'variable.other.cordy'
patterns: [
{ include: '#comment' }
{ include: '#variable-initializer' }
{ include: '#property-get' }
{ include: '#property-set' }
{ include: '#class-members' }
]
"property-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)
'''
end: '(?=^$)'
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'variable.other.cordy'
patterns: [
{ include: '#comment' }
]
"property-accessors":
patterns: [
{ include: '#property-get' }
{ include: '#property-set' }
]
"property-get":
begin: '\\t\\b(get)\\b'
beginCaptures:
1: name: 'keyword.other.get.cordy'
end: '^$|(?=^\\t[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#code-block' }
]
"property-set":
begin: '\\t(?:(private|internal)\\s+)?(?:(protected)\\s+)?(set)\\s*'
beginCaptures:
1:
patterns: [{include: '#storage-modifier'}]
2:
patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.set.cordy'
end: '^$'
patterns: [
{ include: '#comment' }
{ include: '#code-block' }
]
"variable-initializer":
name: 'var.init'
begin: '\\s*(=|\\bis\\b)\\s*'
beginCaptures:
1: name: 'keyword.operator.assignment.cordy'
end: '(?=^(?:\\t+|$))'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
expression:
name: 'container.expression.cordy'
patterns: [
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#throw-expression' }
{ include: '#value' }
{ include: '#this-or-base-expression' }
{ include: '#expression-operators' }
{ include: '#parenthesized-expression' }
{ include: '#cast-expression' }
{ include: '#call-expression' }
{ include: '#identifier' }
]
"parenthesized-expression":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [{include: '#expression'}]
"cast-expression":
# result of this cast must be assigned to something
name: 'container.expression.cast.cordy'
match: '''(?x)
((?:(?!\\s*\\|\\>\\s*).)+) # expression that will be casted
\\s*(\\|\\>)\\s* # cast operator
(?<type> # new type of expression's result
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
(?:
\\s*(\\-\\>)\\s*
((?:\\g<id>\\.)*\\g<id>(?:\\([^)]*\\)|\\[[^\\]]\\])?)
)?
'''
captures:
1:
patterns: [{include: '#expression'}]
2: name: 'keyword.operator.cast.cordy'
3:
patterns: [{include: '#type'}]
8: name: 'keyword.operator.casted-accessor.cordy'
9:
patterns: [{include: '#expression'}]
"throw-expression":
match: '(?<!\\.)\\b(throw)\\b'
captures:
1: name: 'keyword.control.flow.throw.cordy'
"this-or-base-expression":
match: '\\b(?:(base)|(this))\\b'
captures:
1: name: 'keyword.other.base.cordy'
2: name: 'keyword.other.this.cordy'
"expression-operators":
patterns: [
{
name: 'keyword.operator.cordy'
match: '[<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3}'
}
]
"call-expression":
patterns: [
{ # constructor without arguments
begin: '(new)\\s*(\\()'
beginCaptures:
1: name: 'keyword.other.new.cordy'
2: name: 'punctuation.parenthesis.open.cordy'
patterns: [{include: '#type'}]
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
}
{ # constructor with arguments
begin: '''(?x)
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s*(\\.)\\s*
(new)
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'keyword.other.new.cordy'
end: '(?<=\\))'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [{include: '#callee-arg-list'}]
}
{ # function call
begin: '''(?x)
(?:
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)\\s*(\\.)\\s*
)?
(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'entity.name.function.$8.cordy'
end: '(?<=\\))'
patterns: [{include: '#callee-arg-list'}]
}
{ # indexer call
begin: '''(?x)
(?:
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<nameArgsAndMods>)*|
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)\\s*(\\.)\\s*
)?
(\\g<id>)\\s*
(?=\\[)
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'variable.other.cordy'
end: '(?<=\\])'
patterns: [{include: '#callee-arg-list'}]
}
]
"callee-arg-list":
begin: '\\(|\\[|\\{'
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)|\\]|\\}'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [
{ include: '#named-arg' }
{ include: '#comment'}
{ include: '#expression' }
{ include: '#punctuation-comma' }
]
"named-arg":
begin: '([@$_a-zA-Z0-9]\\w*)\\s*(:)'
beginCaptures:
1: name: 'variable.parameter.cordy'
2: name: 'punctuation.separator.colon.cordy'
end: '(?=(,|\\)|\\]))'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
| 90365 | scopeName: 'source.co' # <scope> should be a short, unique indicator for the language ("js", "php", "c", etc.)
name: '<NAME>' # The title that will show up in grammar selection and on your status bar.
fileTypes: [ # An array of file extensions.
'co'
]
firstLineMatch: '' # A regular expression that is matched against the first line of the document when Atom is trying to decide if the grammar is appropriate. Useful for shell scripts, mostly.
patterns: [ # An array of individual pattern declarations.
{ include: '#comment' }
{ include: '#directives' }
{ include: '#attribute' }
{ include: '#parameter' }
{ include: '#declarations' }
]
repository: # An array of rules. If you're going to be referencing one bit of code over and over again, stick it here so that you can edit all in one place.
declarations:
patterns: [
{ include: '#comment' }
{ include: '#preprocessor' }
{ include: '#type-declarations' }
]
parameter:
begin: '^\\{'
beginCaptures:
0: name: 'punctuation.parameter.open.cordy'
end: '\\}$'
endCaptures:
0: name: 'punctuation.parameter.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
attribute:
begin: '^\\['
beginCaptures:
0: name: 'punctuation.attribute.open.cordy'
end: '\\]$'
endCaptures:
0: name: 'punctuation.attribute.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
"type-declarations":
patterns: [
{ include: '#comment' }
{ include: '#storage-modifier' }
{ include: '#class-declaration' }
{ include: '#enum-declaration' }
{ include: '#interface-declaration' }
]
comment:
patterns: [
{
name: 'comment.block.cordy'
begin: '\\#\\*'
beginCaptures:
0: name: 'punctuation.definition.comment.cordy'
end: '\\*\\#'
endCaptures:
0: name: 'punctuation.definition.comment.cordy'
}
{
name: 'comment.line.cordy'
begin: '\\#\\#'
beginCaptures:
0: name: 'punctuation.definition.comment.cordy'
end: '\\#\\#|$'
endCaptures:
0: name: 'punctuation.definition.comment.cordy'
}
]
"storage-modifier":
match: '\\b(public|protected|internal|private|sealed|static)\\b'
name: 'storage.modifier.cordy'
"class-declaration":
begin: '(?=\\bclass\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(class)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.class.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-parameter-list' }
{ include: '#type-settings-list' }
{ include: '#base-types' }
{ include: '#generic-constraints' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#class-members' }
]
"interface-declaration":
begin: '(?=\\binterface\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(interface)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.interface.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-parameter-list' }
{ include: '#type-settings-list' }
{ include: '#base-types' }
{ include: '#generic-constraints' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#interface-members' }
]
"enum-declaration":
begin: '(?=\\benum\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(enum)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.enum.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-settings-list' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#expression'}
]
"base-types":
name: 'meta.basetypes.cordy'
begin: ':'
beginCaptures:
0: name: 'punctuation.separator.colon'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#type' }
{ include: '#punctuation-comma' }
{ include: '#preprocessor' }
{ include: '#comment' }
]
type:
name: 'meta.type.cordy'
patterns: [
{ include: '#comment' }
{ include: '#tuple-type' }
{ include: '#type-name' }
{ include: '#type-args' }
{ include: '#type-params' }
{ include: '#type-array-suffix' }
]
value:
name: 'container.value.cordy'
patterns: [
{ include: '#string' }
{ # integer binary
match: '-?0[bB][01][01_]*'
name: 'constant.numeric.integer.binary.cordy'
}
{ # integer octal
match: '-?0[oO][0-7][0-7_]*'
name: 'constant.numeric.integer.octal.cordy'
}
{ # integer hexadecimal
match: '-?0[xX][0-9a-fA-F][0-9a-fA-F_]*'
name: 'constant.numeric.integer.hexadecimal.cordy'
}
{ # float
match: '-?(?:\\d[\\d_]*)?[.,]\\d[\\d_]*'
name: 'constant.numeric.float.cordy'
}
{ # integer decimal
match: '-?[0-9][0-9_]*'
name: 'constant.numeric.integer.decimal.cordy'
}
]
string:
patterns: [
{ #default string
name: 'string.quoted.cordy'
begin: '(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
]
}
{ # verbatim string
name: 'string.verbatim.cordy'
begin: '@(["\'`])'
end: '((?!\\1\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(["\'`])\\1'
name: 'constant.character.escape.cordy'
}
]
}
{ # interpolated string
name: 'string.interpolated.cordy'
begin: '\\$(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
{
name: 'meta.interpolation.cordy'
begin: '\\{'
beginCaptures:
0: name: 'punctuation.curlybracket.open.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.curlybracket.closed.cordy'
patterns: [
{include: '#expression'}
]
}
]
}
{ # interpolated verbatim string
name: 'string.interpolated-verbatim.cordy'
begin: '(?:\\$@|@\\$)(["\'`])'
end: '((?!\\1\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(["\'`])\\1'
name: 'constant.character.escape.cordy'
}
{
name: 'meta.interpolation.cordy'
begin: '\\{'
beginCaptures:
0: name: 'punctuation.curlybracket.open.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.curlybracket.closed.cordy'
patterns: [
{include: '#expression'}
]
}
]
}
{ # regex string
name: 'string.regex.cordy'
begin: '\\~(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
#TODO: make highlighting support of different regex elements
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
]
}
]
"type-array-suffix":
begin: '\\['
beginCaptures:
0: name: 'punctuation.squarebracket.open.cordy'
end: '\\]'
endCaptures:
0: name: 'punctuation.squarebracket.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"type-params":
begin: '\\{'
beginCaptures:
0: name: 'punctuation.definition.typeparameters.begin.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.definition.typeparameters.end.cordy'
patterns: [
{ include: '#comment' }
{ include: '#value' }
{ include: '#punctuation-comma' }
]
"type-args":
begin: '\\<'
beginCaptures:
0: name: 'punctuation.definition.typearguments.begin.cordy'
end: '\\>'
endCaptures:
0: name: 'punctuation.definition.typearguments.end.cordy'
patterns: [
{ include: '#comment' }
{ include: '#type' }
{ include: '#punctuation-comma' }
]
"type-name":
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\s*(\\.)'
captures:
1: name: 'entity.name.type.cordy'
2: name: 'punctuation.accessor.cordy'
}
{
match: '(\\.)\\s*([@$_a-zA-Z]\\w*)'
captures:
1: name: 'punctuation.accessor.cordy'
2: name: 'entity.name.type.cordy'
}
{
match: '[@$_a-zA-Z]\\w*'
name: 'entity.name.type.cordy'
}
]
"tuple-type":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [
{ include: '#tuple-element' }
{ include: '#punctuation-comma' }
]
"tuple-element":
match: '''(?x)
(?<type>
(?:
(?<nameAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\s*)*
)
)
(?:(\\g<id>)\\b)?
'''
captures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.variable.tuple-element.cordy'
"type-parameter-list":
begin: '\\<'
beginCaptures:
0: name: 'punctuation.definition.typeparameters.begin.cordy'
end: '\\>'
endCaptures:
0: name: 'punctuation.definition.typeparameters.end.cordy'
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\b'
captures:
1: name: 'entity.name.type.type-parameter.cordy'
}
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"type-settings-list":
begin: '\\{'
beginCaptures:
0: name: 'punctuation.definition.typesettings.begin.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.definition.typesettings.end.cordy'
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\b'
captures:
1: name: 'variable.other.parameter.cordy'
}
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"punctuation-comma":
match: ','
name: 'punctuation.separator.comma.cordy'
"class-members":
patterns: [
{ include: '#comment' }
{ include: '#parameter' }
{ include: '#attribute' }
{ include: '#preprocessor' }
{ include: '#storage-modifier' }
{ include: '#event-declaration'}
{ include: '#property-declaration' }
{ include: '#operator-declaration' }
{ include: '#function-declaration' }
{ include: '#constructor-declaration' }
{ include: '#indexer-declaration' }
]
"interface-members":
patterns: [
{ include: '#comment' }
{ include: '#parameter' }
{ include: '#attribute' }
{ include: '#preprocessor' }
{ include: '#event-definition'}
{ include: '#operator-definition' }
{ include: '#function-definition' }
{ include: '#property-definition' }
{ include: '#constructor-definition' }
{ include: '#indexer-definition' }
]
"event-declaration":
begin: '(\\bevent\\b)\\s+([$@_a-zA-Z]\\w*)\\s*(?=\\()'
beginCaptures:
1: name: 'keyword.other.event.cordy'
2: name: 'entity.name.event.$2.cordy'
end: '^$'
patterns: [
{include: '#comment'}
{include: '#function-args'}
{
begin: '\\t(?:(internal|private)\\s+)?(?:(protected)\\s+)?(\\badd\\b)'
beginCaptures:
1: patterns: [{include: '#storage-modifier'}]
2: patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.add.cordy'
end: '(?=^$|^\\t[^\\t])'
patterns: [{include: '#code-block'}]
}
{
begin: '\\t(?:(internal|private)\\s+)?(?:(protected)\\s+)?(\\bremove\\b)'
beginCaptures:
1: patterns: [{include: '#storage-modifier'}]
2: patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.remove.cordy'
end: '(?=^$|^\\t[^\\t])'
patterns: [{include: '#code-block'}]
}
]
"event-definition":
begin: '(\\bevent\\b)\\s+([$@_a-zA-Z]\\w*)\\s*(?=\\()'
beginCaptures:
1: name: 'keyword.other.event.cordy'
2: name: 'entity.name.event.$2.cordy'
end: '^$'
patterns: [
{include: '#comment'}
{include: '#function-args'}
]
"constructor-declaration":
begin: '''(?x)
\\s*(new)\\s*
(?=\\()
'''
beginCaptures:
1: name: 'entity.name.constructor.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
{ include: '#code-block' }
]
"constructor-definition":
begin: '''(?x)
\\s*(new)\\s*
(?=\\()
'''
beginCaptures:
1: name: 'entity.name.constructor.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
]
"indexer-declaration":
begin: '''(?x)
\\s*(this)\\s*
(?=\\[)
'''
beginCaptures:
1: name: 'entity.name.indexer.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#indexer-args' }
{ include: '#code-block' }
]
"indexer-definition":
begin: '''(?x)
\\s*(this)\\s*
(?=\\[)
'''
beginCaptures:
1: name: 'entity.name.indexer.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#indexer-args' }
]
"operator-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+([<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3})\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'keyword.operator.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#operator-args' }
{ include: '#code-block' }
]
"operator-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+([<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3})\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'keyword.operator.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#operator-args' }
]
"function-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.function.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
{ include: '#code-block' }
]
"function-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.function.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
]
"code-block":
name: 'block'
begin: '(\\t*)\\t'
end: '(?=^\\1\\t*|^$)'
patterns: [
{ include: '#comment'}
{ include: '$self' }
{ include: '#statement' }
]
statement:
patterns: [
{ include: '#comment' }
{ include: '#return-statement' }
{ include: '#if-statement' }
{ include: '#elif-statement' }
{ include: '#else-statement' }
{ include: '#for-statement' }
{ include: '#while-statement' }
{ include: '#do-while-statement' }
{ include: '#try-statement' }
{ include: '#catch-statement' }
{ include: '#finally-statement' }
{ include: '#switch-statement'}
{ include: '#switch-default-statement'}
{ include: '#break-statement'}
{ include: '#continue-statement'}
{ include: '#expression' }
]
"break-statement":
match: '\\bbreak\\b'
name: 'keyword.control.break.cordy'
"continue-statement":
match: '\\bcontinue\\b'
name: 'keyword.control.continue.cordy'
"switch-statement":
begin: '(\\t*)(\\bswitch\\b)'
beginCaptures:
2: name: 'keyword.control.switch.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"switch-default-statement":
begin: '(\\bdefault\\b)\\s*(:)\\s*(.*)'
beginCaptures:
1: name: 'keyword.control.default.cordy'
2: name: 'punctuation.separator.colon.cordy'
3: patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"try-statement":
begin: '(\\t*)(\\btry\\b)'
beginCaptures:
2: name: 'keyword.control.try.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"catch-statement":
begin: '(\\t*)(\\bcatch\\b)\\s*(.*)'
beginCaptures:
2: name: 'keyword.control.catch.cordy'
3: patterns: [include: '#expression']
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"finally-statement":
begin: '(\\t*)(\\bfinally\\b)'
beginCaptures:
2: name: 'keyword.control.finally.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"do-while-statement":
begin: '(\\t*)(\\bdo\\b)'
beginCaptures:
2: name: 'keyword.control.do.cordy'
3:
patterns: [{include: '#expression'}]
end: '\\t+(\\bwhile\\b)(.*)'
endCaptures:
1: name: 'keyword.control.while.cordy'
2: patterns: [{include: '#expression'}]
patterns: [{include: '#code-block'}]
"while-statement":
begin: '(\\t*)(\\bwhile\\b)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.while.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"for-statement":
begin: '(\\t*)(\\bfor\\b)\\s+'
beginCaptures:
2: name: 'keyword.control.for.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [
{include: '#expression'}
{include: '#separator-comma'}
{include: '#code-block'}
]
"if-statement":
name: 'if'
begin: '(\\t*)(\\bif\\b)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.if.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*)'
patterns: [{include: '#code-block'}]
"else-statement":
begin: '(\\t*)(else)\\s*$'
beginCaptures:
2: name: 'keyword.control.else.cordy'
end: '(?=^\\1\\t*)'
patterns: [{include: '#code-block'}]
"elif-statement":
begin: '(\\t*)(el(?:se\\s*)?if)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.elseif.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*)'
captures: [
{ include: '#code-block' }
]
"return-statement":
name: 'return'
begin: '\\breturn\\b\\s*'
beginCaptures:
0: name: 'keyword.control.return.cordy'
end: '(?=\\t+|^$)'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
"indexer-args":
begin: '\\['
beginCaptures:
0: name: 'punctuation.squarebracket.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#punctuation-comma' }
{
match: '\\]'
name: 'punctuation.squarebracket.close.cordy'
}
]
"function-args":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#punctuation-comma' }
{
match: '\\)'
name: 'punctuation.parenthesis.close.cordy'
}
]
"operator-args":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#expression-operators' }
{
match: '\\)'
name: 'punctuation.parenthesis.close.cordy'
}
]
arg:
name: 'arg'
match: '''(?x)
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
'''
captures:
1:
patterns: [{include: '#type'}]
7: name: 'variable.parameter.function.cordy'
"property-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?==|\\bis\\b)
'''
end: '(?=^$)'
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'variable.other.cordy'
patterns: [
{ include: '#comment' }
{ include: '#variable-initializer' }
{ include: '#property-get' }
{ include: '#property-set' }
{ include: '#class-members' }
]
"property-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)
'''
end: '(?=^$)'
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'variable.other.cordy'
patterns: [
{ include: '#comment' }
]
"property-accessors":
patterns: [
{ include: '#property-get' }
{ include: '#property-set' }
]
"property-get":
begin: '\\t\\b(get)\\b'
beginCaptures:
1: name: 'keyword.other.get.cordy'
end: '^$|(?=^\\t[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#code-block' }
]
"property-set":
begin: '\\t(?:(private|internal)\\s+)?(?:(protected)\\s+)?(set)\\s*'
beginCaptures:
1:
patterns: [{include: '#storage-modifier'}]
2:
patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.set.cordy'
end: '^$'
patterns: [
{ include: '#comment' }
{ include: '#code-block' }
]
"variable-initializer":
name: 'var.init'
begin: '\\s*(=|\\bis\\b)\\s*'
beginCaptures:
1: name: 'keyword.operator.assignment.cordy'
end: '(?=^(?:\\t+|$))'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
expression:
name: 'container.expression.cordy'
patterns: [
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#throw-expression' }
{ include: '#value' }
{ include: '#this-or-base-expression' }
{ include: '#expression-operators' }
{ include: '#parenthesized-expression' }
{ include: '#cast-expression' }
{ include: '#call-expression' }
{ include: '#identifier' }
]
"parenthesized-expression":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [{include: '#expression'}]
"cast-expression":
# result of this cast must be assigned to something
name: 'container.expression.cast.cordy'
match: '''(?x)
((?:(?!\\s*\\|\\>\\s*).)+) # expression that will be casted
\\s*(\\|\\>)\\s* # cast operator
(?<type> # new type of expression's result
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
(?:
\\s*(\\-\\>)\\s*
((?:\\g<id>\\.)*\\g<id>(?:\\([^)]*\\)|\\[[^\\]]\\])?)
)?
'''
captures:
1:
patterns: [{include: '#expression'}]
2: name: 'keyword.operator.cast.cordy'
3:
patterns: [{include: '#type'}]
8: name: 'keyword.operator.casted-accessor.cordy'
9:
patterns: [{include: '#expression'}]
"throw-expression":
match: '(?<!\\.)\\b(throw)\\b'
captures:
1: name: 'keyword.control.flow.throw.cordy'
"this-or-base-expression":
match: '\\b(?:(base)|(this))\\b'
captures:
1: name: 'keyword.other.base.cordy'
2: name: 'keyword.other.this.cordy'
"expression-operators":
patterns: [
{
name: 'keyword.operator.cordy'
match: '[<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3}'
}
]
"call-expression":
patterns: [
{ # constructor without arguments
begin: '(new)\\s*(\\()'
beginCaptures:
1: name: 'keyword.other.new.cordy'
2: name: 'punctuation.parenthesis.open.cordy'
patterns: [{include: '#type'}]
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
}
{ # constructor with arguments
begin: '''(?x)
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s*(\\.)\\s*
(new)
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'keyword.other.new.cordy'
end: '(?<=\\))'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [{include: '#callee-arg-list'}]
}
{ # function call
begin: '''(?x)
(?:
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)\\s*(\\.)\\s*
)?
(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'entity.name.function.$8.cordy'
end: '(?<=\\))'
patterns: [{include: '#callee-arg-list'}]
}
{ # indexer call
begin: '''(?x)
(?:
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<nameArgsAndMods>)*|
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)\\s*(\\.)\\s*
)?
(\\g<id>)\\s*
(?=\\[)
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'variable.other.cordy'
end: '(?<=\\])'
patterns: [{include: '#callee-arg-list'}]
}
]
"callee-arg-list":
begin: '\\(|\\[|\\{'
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)|\\]|\\}'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [
{ include: '#named-arg' }
{ include: '#comment'}
{ include: '#expression' }
{ include: '#punctuation-comma' }
]
"named-arg":
begin: '([@$_a-zA-Z0-9]\\w*)\\s*(:)'
beginCaptures:
1: name: 'variable.parameter.cordy'
2: name: 'punctuation.separator.colon.cordy'
end: '(?=(,|\\)|\\]))'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
| true | scopeName: 'source.co' # <scope> should be a short, unique indicator for the language ("js", "php", "c", etc.)
name: 'PI:NAME:<NAME>END_PI' # The title that will show up in grammar selection and on your status bar.
fileTypes: [ # An array of file extensions.
'co'
]
firstLineMatch: '' # A regular expression that is matched against the first line of the document when Atom is trying to decide if the grammar is appropriate. Useful for shell scripts, mostly.
patterns: [ # An array of individual pattern declarations.
{ include: '#comment' }
{ include: '#directives' }
{ include: '#attribute' }
{ include: '#parameter' }
{ include: '#declarations' }
]
repository: # An array of rules. If you're going to be referencing one bit of code over and over again, stick it here so that you can edit all in one place.
declarations:
patterns: [
{ include: '#comment' }
{ include: '#preprocessor' }
{ include: '#type-declarations' }
]
parameter:
begin: '^\\{'
beginCaptures:
0: name: 'punctuation.parameter.open.cordy'
end: '\\}$'
endCaptures:
0: name: 'punctuation.parameter.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
attribute:
begin: '^\\['
beginCaptures:
0: name: 'punctuation.attribute.open.cordy'
end: '\\]$'
endCaptures:
0: name: 'punctuation.attribute.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
"type-declarations":
patterns: [
{ include: '#comment' }
{ include: '#storage-modifier' }
{ include: '#class-declaration' }
{ include: '#enum-declaration' }
{ include: '#interface-declaration' }
]
comment:
patterns: [
{
name: 'comment.block.cordy'
begin: '\\#\\*'
beginCaptures:
0: name: 'punctuation.definition.comment.cordy'
end: '\\*\\#'
endCaptures:
0: name: 'punctuation.definition.comment.cordy'
}
{
name: 'comment.line.cordy'
begin: '\\#\\#'
beginCaptures:
0: name: 'punctuation.definition.comment.cordy'
end: '\\#\\#|$'
endCaptures:
0: name: 'punctuation.definition.comment.cordy'
}
]
"storage-modifier":
match: '\\b(public|protected|internal|private|sealed|static)\\b'
name: 'storage.modifier.cordy'
"class-declaration":
begin: '(?=\\bclass\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(class)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.class.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-parameter-list' }
{ include: '#type-settings-list' }
{ include: '#base-types' }
{ include: '#generic-constraints' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#class-members' }
]
"interface-declaration":
begin: '(?=\\binterface\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(interface)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.interface.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-parameter-list' }
{ include: '#type-settings-list' }
{ include: '#base-types' }
{ include: '#generic-constraints' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#interface-members' }
]
"enum-declaration":
begin: '(?=\\benum\\b)'
end: '\\z'
patterns: [
{
begin: '\\b(enum)\\b\\s*'
beginCaptures:
1: name: 'keyword.other.enum.cordy'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#comment' }
{ include: '#type-settings-list' }
]
}
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#expression'}
]
"base-types":
name: 'meta.basetypes.cordy'
begin: ':'
beginCaptures:
0: name: 'punctuation.separator.colon'
end: '(?=^(?:\\w|\\W))'
patterns: [
{ include: '#type' }
{ include: '#punctuation-comma' }
{ include: '#preprocessor' }
{ include: '#comment' }
]
type:
name: 'meta.type.cordy'
patterns: [
{ include: '#comment' }
{ include: '#tuple-type' }
{ include: '#type-name' }
{ include: '#type-args' }
{ include: '#type-params' }
{ include: '#type-array-suffix' }
]
value:
name: 'container.value.cordy'
patterns: [
{ include: '#string' }
{ # integer binary
match: '-?0[bB][01][01_]*'
name: 'constant.numeric.integer.binary.cordy'
}
{ # integer octal
match: '-?0[oO][0-7][0-7_]*'
name: 'constant.numeric.integer.octal.cordy'
}
{ # integer hexadecimal
match: '-?0[xX][0-9a-fA-F][0-9a-fA-F_]*'
name: 'constant.numeric.integer.hexadecimal.cordy'
}
{ # float
match: '-?(?:\\d[\\d_]*)?[.,]\\d[\\d_]*'
name: 'constant.numeric.float.cordy'
}
{ # integer decimal
match: '-?[0-9][0-9_]*'
name: 'constant.numeric.integer.decimal.cordy'
}
]
string:
patterns: [
{ #default string
name: 'string.quoted.cordy'
begin: '(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
]
}
{ # verbatim string
name: 'string.verbatim.cordy'
begin: '@(["\'`])'
end: '((?!\\1\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(["\'`])\\1'
name: 'constant.character.escape.cordy'
}
]
}
{ # interpolated string
name: 'string.interpolated.cordy'
begin: '\\$(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
{
name: 'meta.interpolation.cordy'
begin: '\\{'
beginCaptures:
0: name: 'punctuation.curlybracket.open.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.curlybracket.closed.cordy'
patterns: [
{include: '#expression'}
]
}
]
}
{ # interpolated verbatim string
name: 'string.interpolated-verbatim.cordy'
begin: '(?:\\$@|@\\$)(["\'`])'
end: '((?!\\1\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
match: '(["\'`])\\1'
name: 'constant.character.escape.cordy'
}
{
name: 'meta.interpolation.cordy'
begin: '\\{'
beginCaptures:
0: name: 'punctuation.curlybracket.open.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.curlybracket.closed.cordy'
patterns: [
{include: '#expression'}
]
}
]
}
{ # regex string
name: 'string.regex.cordy'
begin: '\\~(["\'`])'
end: '((?!\\\\\\1)\\1)'
beginCaptures:
1: name: 'punctuation.quote.cordy'
endCaptures:
1: name: 'punctuation.quote.cordy'
patterns: [
{
#TODO: make highlighting support of different regex elements
match: '(\\\\.)'
name: 'constant.character.escape.cordy'
}
]
}
]
"type-array-suffix":
begin: '\\['
beginCaptures:
0: name: 'punctuation.squarebracket.open.cordy'
end: '\\]'
endCaptures:
0: name: 'punctuation.squarebracket.close.cordy'
patterns: [
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"type-params":
begin: '\\{'
beginCaptures:
0: name: 'punctuation.definition.typeparameters.begin.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.definition.typeparameters.end.cordy'
patterns: [
{ include: '#comment' }
{ include: '#value' }
{ include: '#punctuation-comma' }
]
"type-args":
begin: '\\<'
beginCaptures:
0: name: 'punctuation.definition.typearguments.begin.cordy'
end: '\\>'
endCaptures:
0: name: 'punctuation.definition.typearguments.end.cordy'
patterns: [
{ include: '#comment' }
{ include: '#type' }
{ include: '#punctuation-comma' }
]
"type-name":
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\s*(\\.)'
captures:
1: name: 'entity.name.type.cordy'
2: name: 'punctuation.accessor.cordy'
}
{
match: '(\\.)\\s*([@$_a-zA-Z]\\w*)'
captures:
1: name: 'punctuation.accessor.cordy'
2: name: 'entity.name.type.cordy'
}
{
match: '[@$_a-zA-Z]\\w*'
name: 'entity.name.type.cordy'
}
]
"tuple-type":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [
{ include: '#tuple-element' }
{ include: '#punctuation-comma' }
]
"tuple-element":
match: '''(?x)
(?<type>
(?:
(?<nameAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\s*)*
)
)
(?:(\\g<id>)\\b)?
'''
captures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.variable.tuple-element.cordy'
"type-parameter-list":
begin: '\\<'
beginCaptures:
0: name: 'punctuation.definition.typeparameters.begin.cordy'
end: '\\>'
endCaptures:
0: name: 'punctuation.definition.typeparameters.end.cordy'
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\b'
captures:
1: name: 'entity.name.type.type-parameter.cordy'
}
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"type-settings-list":
begin: '\\{'
beginCaptures:
0: name: 'punctuation.definition.typesettings.begin.cordy'
end: '\\}'
endCaptures:
0: name: 'punctuation.definition.typesettings.end.cordy'
patterns: [
{
match: '([@$_a-zA-Z]\\w*)\\b'
captures:
1: name: 'variable.other.parameter.cordy'
}
{ include: '#comment' }
{ include: '#punctuation-comma' }
]
"punctuation-comma":
match: ','
name: 'punctuation.separator.comma.cordy'
"class-members":
patterns: [
{ include: '#comment' }
{ include: '#parameter' }
{ include: '#attribute' }
{ include: '#preprocessor' }
{ include: '#storage-modifier' }
{ include: '#event-declaration'}
{ include: '#property-declaration' }
{ include: '#operator-declaration' }
{ include: '#function-declaration' }
{ include: '#constructor-declaration' }
{ include: '#indexer-declaration' }
]
"interface-members":
patterns: [
{ include: '#comment' }
{ include: '#parameter' }
{ include: '#attribute' }
{ include: '#preprocessor' }
{ include: '#event-definition'}
{ include: '#operator-definition' }
{ include: '#function-definition' }
{ include: '#property-definition' }
{ include: '#constructor-definition' }
{ include: '#indexer-definition' }
]
"event-declaration":
begin: '(\\bevent\\b)\\s+([$@_a-zA-Z]\\w*)\\s*(?=\\()'
beginCaptures:
1: name: 'keyword.other.event.cordy'
2: name: 'entity.name.event.$2.cordy'
end: '^$'
patterns: [
{include: '#comment'}
{include: '#function-args'}
{
begin: '\\t(?:(internal|private)\\s+)?(?:(protected)\\s+)?(\\badd\\b)'
beginCaptures:
1: patterns: [{include: '#storage-modifier'}]
2: patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.add.cordy'
end: '(?=^$|^\\t[^\\t])'
patterns: [{include: '#code-block'}]
}
{
begin: '\\t(?:(internal|private)\\s+)?(?:(protected)\\s+)?(\\bremove\\b)'
beginCaptures:
1: patterns: [{include: '#storage-modifier'}]
2: patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.remove.cordy'
end: '(?=^$|^\\t[^\\t])'
patterns: [{include: '#code-block'}]
}
]
"event-definition":
begin: '(\\bevent\\b)\\s+([$@_a-zA-Z]\\w*)\\s*(?=\\()'
beginCaptures:
1: name: 'keyword.other.event.cordy'
2: name: 'entity.name.event.$2.cordy'
end: '^$'
patterns: [
{include: '#comment'}
{include: '#function-args'}
]
"constructor-declaration":
begin: '''(?x)
\\s*(new)\\s*
(?=\\()
'''
beginCaptures:
1: name: 'entity.name.constructor.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
{ include: '#code-block' }
]
"constructor-definition":
begin: '''(?x)
\\s*(new)\\s*
(?=\\()
'''
beginCaptures:
1: name: 'entity.name.constructor.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
]
"indexer-declaration":
begin: '''(?x)
\\s*(this)\\s*
(?=\\[)
'''
beginCaptures:
1: name: 'entity.name.indexer.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#indexer-args' }
{ include: '#code-block' }
]
"indexer-definition":
begin: '''(?x)
\\s*(this)\\s*
(?=\\[)
'''
beginCaptures:
1: name: 'entity.name.indexer.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#indexer-args' }
]
"operator-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+([<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3})\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'keyword.operator.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#operator-args' }
{ include: '#code-block' }
]
"operator-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+([<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3})\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'keyword.operator.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#operator-args' }
]
"function-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.function.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
{ include: '#code-block' }
]
"function-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'entity.name.function.$6.cordy'
end: '(?=^$)'
patterns: [
{ include: '#comment' }
{ include: '#function-args' }
]
"code-block":
name: 'block'
begin: '(\\t*)\\t'
end: '(?=^\\1\\t*|^$)'
patterns: [
{ include: '#comment'}
{ include: '$self' }
{ include: '#statement' }
]
statement:
patterns: [
{ include: '#comment' }
{ include: '#return-statement' }
{ include: '#if-statement' }
{ include: '#elif-statement' }
{ include: '#else-statement' }
{ include: '#for-statement' }
{ include: '#while-statement' }
{ include: '#do-while-statement' }
{ include: '#try-statement' }
{ include: '#catch-statement' }
{ include: '#finally-statement' }
{ include: '#switch-statement'}
{ include: '#switch-default-statement'}
{ include: '#break-statement'}
{ include: '#continue-statement'}
{ include: '#expression' }
]
"break-statement":
match: '\\bbreak\\b'
name: 'keyword.control.break.cordy'
"continue-statement":
match: '\\bcontinue\\b'
name: 'keyword.control.continue.cordy'
"switch-statement":
begin: '(\\t*)(\\bswitch\\b)'
beginCaptures:
2: name: 'keyword.control.switch.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"switch-default-statement":
begin: '(\\bdefault\\b)\\s*(:)\\s*(.*)'
beginCaptures:
1: name: 'keyword.control.default.cordy'
2: name: 'punctuation.separator.colon.cordy'
3: patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"try-statement":
begin: '(\\t*)(\\btry\\b)'
beginCaptures:
2: name: 'keyword.control.try.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"catch-statement":
begin: '(\\t*)(\\bcatch\\b)\\s*(.*)'
beginCaptures:
2: name: 'keyword.control.catch.cordy'
3: patterns: [include: '#expression']
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"finally-statement":
begin: '(\\t*)(\\bfinally\\b)'
beginCaptures:
2: name: 'keyword.control.finally.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"do-while-statement":
begin: '(\\t*)(\\bdo\\b)'
beginCaptures:
2: name: 'keyword.control.do.cordy'
3:
patterns: [{include: '#expression'}]
end: '\\t+(\\bwhile\\b)(.*)'
endCaptures:
1: name: 'keyword.control.while.cordy'
2: patterns: [{include: '#expression'}]
patterns: [{include: '#code-block'}]
"while-statement":
begin: '(\\t*)(\\bwhile\\b)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.while.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*|^$)'
patterns: [{include: '#code-block'}]
"for-statement":
begin: '(\\t*)(\\bfor\\b)\\s+'
beginCaptures:
2: name: 'keyword.control.for.cordy'
end: '(?=^\\1\\t*|^$)'
patterns: [
{include: '#expression'}
{include: '#separator-comma'}
{include: '#code-block'}
]
"if-statement":
name: 'if'
begin: '(\\t*)(\\bif\\b)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.if.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*)'
patterns: [{include: '#code-block'}]
"else-statement":
begin: '(\\t*)(else)\\s*$'
beginCaptures:
2: name: 'keyword.control.else.cordy'
end: '(?=^\\1\\t*)'
patterns: [{include: '#code-block'}]
"elif-statement":
begin: '(\\t*)(el(?:se\\s*)?if)\\s+(.*)'
beginCaptures:
2: name: 'keyword.control.elseif.cordy'
3:
patterns: [{include: '#expression'}]
end: '(?=^\\1\\t*)'
captures: [
{ include: '#code-block' }
]
"return-statement":
name: 'return'
begin: '\\breturn\\b\\s*'
beginCaptures:
0: name: 'keyword.control.return.cordy'
end: '(?=\\t+|^$)'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
"indexer-args":
begin: '\\['
beginCaptures:
0: name: 'punctuation.squarebracket.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#punctuation-comma' }
{
match: '\\]'
name: 'punctuation.squarebracket.close.cordy'
}
]
"function-args":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#punctuation-comma' }
{
match: '\\)'
name: 'punctuation.parenthesis.close.cordy'
}
]
"operator-args":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '(?=^$|^\\t+[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#arg' }
{ include: '#variable-initializer' }
{ include: '#expression-operators' }
{
match: '\\)'
name: 'punctuation.parenthesis.close.cordy'
}
]
arg:
name: 'arg'
match: '''(?x)
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
'''
captures:
1:
patterns: [{include: '#type'}]
7: name: 'variable.parameter.function.cordy'
"property-declaration":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)\\s*
(?==|\\bis\\b)
'''
end: '(?=^$)'
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'variable.other.cordy'
patterns: [
{ include: '#comment' }
{ include: '#variable-initializer' }
{ include: '#property-get' }
{ include: '#property-set' }
{ include: '#class-members' }
]
"property-definition":
begin: '''(?x)
(?<type>
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s+(\\g<id>)
'''
end: '(?=^$)'
beginCaptures:
1:
patterns: [{include: '#type'}]
6: name: 'variable.other.cordy'
patterns: [
{ include: '#comment' }
]
"property-accessors":
patterns: [
{ include: '#property-get' }
{ include: '#property-set' }
]
"property-get":
begin: '\\t\\b(get)\\b'
beginCaptures:
1: name: 'keyword.other.get.cordy'
end: '^$|(?=^\\t[^\\t])'
patterns: [
{ include: '#comment' }
{ include: '#code-block' }
]
"property-set":
begin: '\\t(?:(private|internal)\\s+)?(?:(protected)\\s+)?(set)\\s*'
beginCaptures:
1:
patterns: [{include: '#storage-modifier'}]
2:
patterns: [{include: '#storage-modifier'}]
3: name: 'keyword.other.set.cordy'
end: '^$'
patterns: [
{ include: '#comment' }
{ include: '#code-block' }
]
"variable-initializer":
name: 'var.init'
begin: '\\s*(=|\\bis\\b)\\s*'
beginCaptures:
1: name: 'keyword.operator.assignment.cordy'
end: '(?=^(?:\\t+|$))'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
expression:
name: 'container.expression.cordy'
patterns: [
{ include: '#preprocessor' }
{ include: '#comment' }
{ include: '#throw-expression' }
{ include: '#value' }
{ include: '#this-or-base-expression' }
{ include: '#expression-operators' }
{ include: '#parenthesized-expression' }
{ include: '#cast-expression' }
{ include: '#call-expression' }
{ include: '#identifier' }
]
"parenthesized-expression":
begin: '\\('
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [{include: '#expression'}]
"cast-expression":
# result of this cast must be assigned to something
name: 'container.expression.cast.cordy'
match: '''(?x)
((?:(?!\\s*\\|\\>\\s*).)+) # expression that will be casted
\\s*(\\|\\>)\\s* # cast operator
(?<type> # new type of expression's result
(?<nameArgsAndMods>
(?<id>[@$_a-zA-Z]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}])+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)*
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
(?:
\\s*(\\-\\>)\\s*
((?:\\g<id>\\.)*\\g<id>(?:\\([^)]*\\)|\\[[^\\]]\\])?)
)?
'''
captures:
1:
patterns: [{include: '#expression'}]
2: name: 'keyword.operator.cast.cordy'
3:
patterns: [{include: '#type'}]
8: name: 'keyword.operator.casted-accessor.cordy'
9:
patterns: [{include: '#expression'}]
"throw-expression":
match: '(?<!\\.)\\b(throw)\\b'
captures:
1: name: 'keyword.control.flow.throw.cordy'
"this-or-base-expression":
match: '\\b(?:(base)|(this))\\b'
captures:
1: name: 'keyword.other.base.cordy'
2: name: 'keyword.other.this.cordy'
"expression-operators":
patterns: [
{
name: 'keyword.operator.cordy'
match: '[<>=!#%^?:&*\\-+\\$\\\\\\/_~]{1,3}'
}
]
"call-expression":
patterns: [
{ # constructor without arguments
begin: '(new)\\s*(\\()'
beginCaptures:
1: name: 'keyword.other.new.cordy'
2: name: 'punctuation.parenthesis.open.cordy'
patterns: [{include: '#type'}]
end: '\\)'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
}
{ # constructor with arguments
begin: '''(?x)
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)
\\s*(\\.)\\s*
(new)
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'keyword.other.new.cordy'
end: '(?<=\\))'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [{include: '#callee-arg-list'}]
}
{ # function call
begin: '''(?x)
(?:
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<type>)* |
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)\\s*(\\.)\\s*
)?
(\\g<id>)\\s*
(?=\\()
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'entity.name.function.$8.cordy'
end: '(?<=\\))'
patterns: [{include: '#callee-arg-list'}]
}
{ # indexer call
begin: '''(?x)
(?:
(?<type>
(?:
(?<nameArgsAndMods>
(?<id>[a-z-A-Z_$@]\\w*)\\s*
(?<targs>\\s*<(?:[^<>]|\\g<targs>)+>\\s*)?
(?<tmods>\\s*\\{(?:[^\\{\\}]|\\g<tmods>)+\\}\\s*)?
)
(?:\\s*\\.\\s*\\g<nameArgsAndMods>)*|
(?<tuple>\\s*\\((?:[^\\(\\)]|\\g<tuple>)+\\))
)
(?:\\s*\\[(?:\\s*,\\s*)*\\]\\s*)*
)\\s*(\\.)\\s*
)?
(\\g<id>)\\s*
(?=\\[)
'''
beginCaptures:
1:
patterns: [{include: '#type'}]
7: name: 'punctuation.accessor.cordy'
8: name: 'variable.other.cordy'
end: '(?<=\\])'
patterns: [{include: '#callee-arg-list'}]
}
]
"callee-arg-list":
begin: '\\(|\\[|\\{'
beginCaptures:
0: name: 'punctuation.parenthesis.open.cordy'
end: '\\)|\\]|\\}'
endCaptures:
0: name: 'punctuation.parenthesis.close.cordy'
patterns: [
{ include: '#named-arg' }
{ include: '#comment'}
{ include: '#expression' }
{ include: '#punctuation-comma' }
]
"named-arg":
begin: '([@$_a-zA-Z0-9]\\w*)\\s*(:)'
beginCaptures:
1: name: 'variable.parameter.cordy'
2: name: 'punctuation.separator.colon.cordy'
end: '(?=(,|\\)|\\]))'
patterns: [
{ include: '#comment' }
{ include: '#expression' }
]
|
[
{
"context": "showing', ->\n SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'\n\n # Tes",
"end": 969,
"score": 0.9990857839584351,
"start": 958,
"tag": "EMAIL",
"value": "foo@bar.baz"
},
{
"context": " SettingsHelper.setCredentials 'foo@bar... | spec/views/select-core-view-spec.coffee | lukehoban/spark-dev | 1 | {WorkspaceView} = require 'atom'
$ = require('atom').$
SettingsHelper = require '../../lib/utils/settings-helper'
SparkStub = require('spark-dev-spec-stubs').spark
spark = require 'spark'
describe 'Select Core View', ->
activationPromise = null
selectCoreView = null
originalProfile = null
sparkIde = null
beforeEach ->
atom.workspaceView = new WorkspaceView
activationPromise = atom.packages.activatePackage('spark-dev').then ({mainModule}) ->
sparkIde = mainModule
sparkIde.initView 'select-core'
originalProfile = SettingsHelper.getProfile()
# For tests not to mess up our profile, we have to switch to test one...
SettingsHelper.setProfile 'spark-dev-test'
SparkStub.stubSuccess spark, 'listDevices'
waitsForPromise ->
activationPromise
afterEach ->
SettingsHelper.setProfile originalProfile
describe '', ->
it 'tests hiding and showing', ->
SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'
# Test core:cancel
sparkIde.selectCore()
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
atom.workspaceView.trigger 'core:cancel'
expect(atom.workspaceView.find('#spark-dev-select-core-view')).not.toExist()
# # Test core:close
sparkIde.selectCore()
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
atom.workspaceView.trigger 'core:close'
expect(atom.workspaceView.find('#spark-dev-select-core-view')).not.toExist()
SettingsHelper.clearCredentials()
it 'tests loading items', ->
SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'
sparkIde.selectCore()
selectCoreView = sparkIde.selectCoreView
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
expect(selectCoreView.find('div.loading').css('display')).toEqual('block')
expect(selectCoreView.find('span.loading-message').text()).toEqual('Loading devices...')
expect(selectCoreView.find('ol.list-group li').length).toEqual(0)
waitsFor ->
!selectCoreView.listDevicesPromise
runs ->
devices = selectCoreView.find('ol.list-group li')
expect(devices.length).toEqual(3)
expect(devices.eq(0).find('.primary-line').hasClass('core-online')).toEqual(true)
expect(devices.eq(1).find('.primary-line').hasClass('core-offline')).toEqual(true)
expect(devices.eq(2).find('.primary-line').hasClass('core-offline')).toEqual(true)
expect(devices.eq(0).find('.primary-line').text()).toEqual('Online Core')
expect(devices.eq(1).find('.primary-line').text()).toEqual('Offline Core')
expect(devices.eq(2).find('.primary-line').text()).toEqual('Unnamed')
expect(devices.eq(0).find('.secondary-line').text()).toEqual('51ff6e065067545724680187')
expect(devices.eq(1).find('.secondary-line').text()).toEqual('51ff67258067545724380687')
expect(devices.eq(2).find('.secondary-line').text()).toEqual('51ff61258067545724380687')
selectCoreView.hide()
SettingsHelper.clearCredentials()
it 'tests choosing core', ->
SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'
sparkIde.selectCore()
selectCoreView = sparkIde.selectCoreView
waitsFor ->
!selectCoreView.listDevicesPromise
runs ->
spyOn SettingsHelper, 'setCurrentCore'
spyOn atom.workspaceView, 'trigger'
devices = selectCoreView.find('ol.list-group li')
devices.eq(0).addClass 'selected'
selectCoreView.trigger 'core:confirm'
expect(SettingsHelper.setCurrentCore).toHaveBeenCalled()
expect(SettingsHelper.setCurrentCore).toHaveBeenCalledWith('51ff6e065067545724680187', 'Online Core')
expect(atom.workspaceView.trigger).toHaveBeenCalled()
expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-core-status')
expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-menu')
jasmine.unspy atom.workspaceView, 'trigger'
jasmine.unspy SettingsHelper, 'setCurrentCore'
SettingsHelper.clearCredentials()
| 205138 | {WorkspaceView} = require 'atom'
$ = require('atom').$
SettingsHelper = require '../../lib/utils/settings-helper'
SparkStub = require('spark-dev-spec-stubs').spark
spark = require 'spark'
describe 'Select Core View', ->
activationPromise = null
selectCoreView = null
originalProfile = null
sparkIde = null
beforeEach ->
atom.workspaceView = new WorkspaceView
activationPromise = atom.packages.activatePackage('spark-dev').then ({mainModule}) ->
sparkIde = mainModule
sparkIde.initView 'select-core'
originalProfile = SettingsHelper.getProfile()
# For tests not to mess up our profile, we have to switch to test one...
SettingsHelper.setProfile 'spark-dev-test'
SparkStub.stubSuccess spark, 'listDevices'
waitsForPromise ->
activationPromise
afterEach ->
SettingsHelper.setProfile originalProfile
describe '', ->
it 'tests hiding and showing', ->
SettingsHelper.setCredentials '<EMAIL>', '<KEY>'
# Test core:cancel
sparkIde.selectCore()
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
atom.workspaceView.trigger 'core:cancel'
expect(atom.workspaceView.find('#spark-dev-select-core-view')).not.toExist()
# # Test core:close
sparkIde.selectCore()
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
atom.workspaceView.trigger 'core:close'
expect(atom.workspaceView.find('#spark-dev-select-core-view')).not.toExist()
SettingsHelper.clearCredentials()
it 'tests loading items', ->
SettingsHelper.setCredentials '<EMAIL>', '<KEY>'
sparkIde.selectCore()
selectCoreView = sparkIde.selectCoreView
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
expect(selectCoreView.find('div.loading').css('display')).toEqual('block')
expect(selectCoreView.find('span.loading-message').text()).toEqual('Loading devices...')
expect(selectCoreView.find('ol.list-group li').length).toEqual(0)
waitsFor ->
!selectCoreView.listDevicesPromise
runs ->
devices = selectCoreView.find('ol.list-group li')
expect(devices.length).toEqual(3)
expect(devices.eq(0).find('.primary-line').hasClass('core-online')).toEqual(true)
expect(devices.eq(1).find('.primary-line').hasClass('core-offline')).toEqual(true)
expect(devices.eq(2).find('.primary-line').hasClass('core-offline')).toEqual(true)
expect(devices.eq(0).find('.primary-line').text()).toEqual('Online Core')
expect(devices.eq(1).find('.primary-line').text()).toEqual('Offline Core')
expect(devices.eq(2).find('.primary-line').text()).toEqual('Unnamed')
expect(devices.eq(0).find('.secondary-line').text()).toEqual('51ff6e065067545724680187')
expect(devices.eq(1).find('.secondary-line').text()).toEqual('51ff67258067545724380687')
expect(devices.eq(2).find('.secondary-line').text()).toEqual('51ff61258067545724380687')
selectCoreView.hide()
SettingsHelper.clearCredentials()
it 'tests choosing core', ->
SettingsHelper.setCredentials 'foo<EMAIL>', '0123456789abcdef0123456789abcdef'
sparkIde.selectCore()
selectCoreView = sparkIde.selectCoreView
waitsFor ->
!selectCoreView.listDevicesPromise
runs ->
spyOn SettingsHelper, 'setCurrentCore'
spyOn atom.workspaceView, 'trigger'
devices = selectCoreView.find('ol.list-group li')
devices.eq(0).addClass 'selected'
selectCoreView.trigger 'core:confirm'
expect(SettingsHelper.setCurrentCore).toHaveBeenCalled()
expect(SettingsHelper.setCurrentCore).toHaveBeenCalledWith('51ff6e065067545724680187', 'Online Core')
expect(atom.workspaceView.trigger).toHaveBeenCalled()
expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-core-status')
expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-menu')
jasmine.unspy atom.workspaceView, 'trigger'
jasmine.unspy SettingsHelper, 'setCurrentCore'
SettingsHelper.clearCredentials()
| true | {WorkspaceView} = require 'atom'
$ = require('atom').$
SettingsHelper = require '../../lib/utils/settings-helper'
SparkStub = require('spark-dev-spec-stubs').spark
spark = require 'spark'
describe 'Select Core View', ->
activationPromise = null
selectCoreView = null
originalProfile = null
sparkIde = null
beforeEach ->
atom.workspaceView = new WorkspaceView
activationPromise = atom.packages.activatePackage('spark-dev').then ({mainModule}) ->
sparkIde = mainModule
sparkIde.initView 'select-core'
originalProfile = SettingsHelper.getProfile()
# For tests not to mess up our profile, we have to switch to test one...
SettingsHelper.setProfile 'spark-dev-test'
SparkStub.stubSuccess spark, 'listDevices'
waitsForPromise ->
activationPromise
afterEach ->
SettingsHelper.setProfile originalProfile
describe '', ->
it 'tests hiding and showing', ->
SettingsHelper.setCredentials 'PI:EMAIL:<EMAIL>END_PI', 'PI:KEY:<KEY>END_PI'
# Test core:cancel
sparkIde.selectCore()
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
atom.workspaceView.trigger 'core:cancel'
expect(atom.workspaceView.find('#spark-dev-select-core-view')).not.toExist()
# # Test core:close
sparkIde.selectCore()
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
atom.workspaceView.trigger 'core:close'
expect(atom.workspaceView.find('#spark-dev-select-core-view')).not.toExist()
SettingsHelper.clearCredentials()
it 'tests loading items', ->
SettingsHelper.setCredentials 'PI:EMAIL:<EMAIL>END_PI', 'PI:KEY:<KEY>END_PI'
sparkIde.selectCore()
selectCoreView = sparkIde.selectCoreView
expect(atom.workspaceView.find('#spark-dev-select-core-view')).toExist()
expect(selectCoreView.find('div.loading').css('display')).toEqual('block')
expect(selectCoreView.find('span.loading-message').text()).toEqual('Loading devices...')
expect(selectCoreView.find('ol.list-group li').length).toEqual(0)
waitsFor ->
!selectCoreView.listDevicesPromise
runs ->
devices = selectCoreView.find('ol.list-group li')
expect(devices.length).toEqual(3)
expect(devices.eq(0).find('.primary-line').hasClass('core-online')).toEqual(true)
expect(devices.eq(1).find('.primary-line').hasClass('core-offline')).toEqual(true)
expect(devices.eq(2).find('.primary-line').hasClass('core-offline')).toEqual(true)
expect(devices.eq(0).find('.primary-line').text()).toEqual('Online Core')
expect(devices.eq(1).find('.primary-line').text()).toEqual('Offline Core')
expect(devices.eq(2).find('.primary-line').text()).toEqual('Unnamed')
expect(devices.eq(0).find('.secondary-line').text()).toEqual('51ff6e065067545724680187')
expect(devices.eq(1).find('.secondary-line').text()).toEqual('51ff67258067545724380687')
expect(devices.eq(2).find('.secondary-line').text()).toEqual('51ff61258067545724380687')
selectCoreView.hide()
SettingsHelper.clearCredentials()
it 'tests choosing core', ->
SettingsHelper.setCredentials 'fooPI:EMAIL:<EMAIL>END_PI', '0123456789abcdef0123456789abcdef'
sparkIde.selectCore()
selectCoreView = sparkIde.selectCoreView
waitsFor ->
!selectCoreView.listDevicesPromise
runs ->
spyOn SettingsHelper, 'setCurrentCore'
spyOn atom.workspaceView, 'trigger'
devices = selectCoreView.find('ol.list-group li')
devices.eq(0).addClass 'selected'
selectCoreView.trigger 'core:confirm'
expect(SettingsHelper.setCurrentCore).toHaveBeenCalled()
expect(SettingsHelper.setCurrentCore).toHaveBeenCalledWith('51ff6e065067545724680187', 'Online Core')
expect(atom.workspaceView.trigger).toHaveBeenCalled()
expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-core-status')
expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-menu')
jasmine.unspy atom.workspaceView, 'trigger'
jasmine.unspy SettingsHelper, 'setCurrentCore'
SettingsHelper.clearCredentials()
|
[
{
"context": "tocol module', ->\n protocolName = 'sp'\n text = 'valar morghulis'\n\n afterEach (done) ->\n protocol.unregisterPr",
"end": 224,
"score": 0.9997420907020569,
"start": 209,
"tag": "NAME",
"value": "valar morghulis"
},
{
"context": "t)\n server.close()\n ... | spec/api-protocol-spec.coffee | Evpok/electron | 1 | assert = require 'assert'
http = require 'http'
path = require 'path'
remote = require 'remote'
protocol = remote.require 'protocol'
describe 'protocol module', ->
protocolName = 'sp'
text = 'valar morghulis'
afterEach (done) ->
protocol.unregisterProtocol protocolName, ->
protocol.uninterceptProtocol 'http', -> done()
describe 'protocol.register(Any)Protocol', ->
emptyHandler = (request, callback) -> callback()
it 'throws error when scheme is already registered', (done) ->
protocol.registerStringProtocol protocolName, emptyHandler, (error) ->
assert.equal error, null
protocol.registerBufferProtocol protocolName, emptyHandler, (error) ->
assert.notEqual error, null
done()
it 'does not crash when handler is called twice', (done) ->
doubleHandler = (request, callback) ->
callback(text)
callback()
protocol.registerStringProtocol protocolName, doubleHandler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends error when callback is called with nothing', (done) ->
protocol.registerBufferProtocol protocolName, emptyHandler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'does not crash when callback is called in next tick', (done) ->
handler = (request, callback) ->
setImmediate -> callback(text)
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.unregisterProtocol', ->
it 'returns error when scheme does not exist', (done) ->
protocol.unregisterProtocol 'not-exist', (error) ->
assert.notEqual error, null
done()
describe 'protocol.registerStringProtocol', ->
it 'sends string as response', (done) ->
handler = (request, callback) -> callback(text)
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(data: text, mimeType: 'text/html')
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending object other than string', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerBufferProtocol', ->
buffer = new Buffer(text)
it 'sends Buffer as response', (done) ->
handler = (request, callback) -> callback(buffer)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(data: buffer, mimeType: 'text/html')
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending string', (done) ->
handler = (request, callback) -> callback(text)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerFileProtocol', ->
filePath = path.join __dirname, 'fixtures', 'asar', 'a.asar', 'file1'
fileContent = require('fs').readFileSync(filePath)
normalPath = path.join __dirname, 'fixtures', 'pages', 'a.html'
normalContent = require('fs').readFileSync(normalPath)
it 'sends file path as response', (done) ->
handler = (request, callback) -> callback(filePath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, String(fileContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(path: filePath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, String(fileContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'can send normal file', (done) ->
handler = (request, callback) -> callback(normalPath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, String(normalContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending unexist-file', (done) ->
fakeFilePath = path.join __dirname, 'fixtures', 'asar', 'a.asar', 'not-exist'
handler = (request, callback) -> callback(fakeFilePath)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'fails when sending unsupported content', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerHttpProtocol', ->
it 'sends url as response', (done) ->
server = http.createServer (req, res) ->
assert.notEqual req.headers.accept, ''
res.end(text)
server.close()
server.listen 0, '127.0.0.1', ->
{port} = server.address()
url = "http://127.0.0.1:#{port}"
handler = (request, callback) -> callback({url})
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending invalid url', (done) ->
handler = (request, callback) -> callback({url: 'url'})
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'fails when sending unsupported content', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.isProtocolHandled', ->
it 'returns true for file:', (done) ->
protocol.isProtocolHandled 'file', (result) ->
assert.equal result, true
done()
it 'returns true for http:', (done) ->
protocol.isProtocolHandled 'http', (result) ->
assert.equal result, true
done()
it 'returns true for https:', (done) ->
protocol.isProtocolHandled 'https', (result) ->
assert.equal result, true
done()
it 'returns false when scheme is not registred', (done) ->
protocol.isProtocolHandled 'no-exist', (result) ->
assert.equal result, false
done()
it 'returns true for custom protocol', (done) ->
emptyHandler = (request, callback) -> callback()
protocol.registerStringProtocol protocolName, emptyHandler, (error) ->
assert.equal error, null
protocol.isProtocolHandled protocolName, (result) ->
assert.equal result, true
done()
it 'returns true for intercepted protocol', (done) ->
emptyHandler = (request, callback) -> callback()
protocol.interceptStringProtocol 'http', emptyHandler, (error) ->
assert.equal error, null
protocol.isProtocolHandled 'http', (result) ->
assert.equal result, true
done()
describe 'protocol.intercept(Any)Protocol', ->
emptyHandler = (request, callback) -> callback()
it 'throws error when scheme is already intercepted', (done) ->
protocol.interceptStringProtocol 'http', emptyHandler, (error) ->
assert.equal error, null
protocol.interceptBufferProtocol 'http', emptyHandler, (error) ->
assert.notEqual error, null
done()
it 'does not crash when handler is called twice', (done) ->
doubleHandler = (request, callback) ->
callback(text)
callback()
protocol.interceptStringProtocol 'http', doubleHandler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends error when callback is called with nothing', (done) ->
protocol.interceptBufferProtocol 'http', emptyHandler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.interceptStringProtocol', ->
it 'can intercept http protocol', (done) ->
handler = (request, callback) -> callback(text)
protocol.interceptStringProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'can set content-type', (done) ->
handler = (request, callback) ->
callback({mimeType: 'application/json', data: '{"value": 1}'})
protocol.interceptStringProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal typeof(data), 'object'
assert.equal data.value, 1
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.interceptBufferProtocol', ->
it 'can intercept http protocol', (done) ->
handler = (request, callback) -> callback(new Buffer(text))
protocol.interceptBufferProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.uninterceptProtocol', ->
it 'returns error when scheme does not exist', (done) ->
protocol.uninterceptProtocol 'not-exist', (error) ->
assert.notEqual error, null
done()
it 'returns error when scheme is not intercepted', (done) ->
protocol.uninterceptProtocol 'http', (error) ->
assert.notEqual error, null
done()
| 195396 | assert = require 'assert'
http = require 'http'
path = require 'path'
remote = require 'remote'
protocol = remote.require 'protocol'
describe 'protocol module', ->
protocolName = 'sp'
text = '<NAME>'
afterEach (done) ->
protocol.unregisterProtocol protocolName, ->
protocol.uninterceptProtocol 'http', -> done()
describe 'protocol.register(Any)Protocol', ->
emptyHandler = (request, callback) -> callback()
it 'throws error when scheme is already registered', (done) ->
protocol.registerStringProtocol protocolName, emptyHandler, (error) ->
assert.equal error, null
protocol.registerBufferProtocol protocolName, emptyHandler, (error) ->
assert.notEqual error, null
done()
it 'does not crash when handler is called twice', (done) ->
doubleHandler = (request, callback) ->
callback(text)
callback()
protocol.registerStringProtocol protocolName, doubleHandler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends error when callback is called with nothing', (done) ->
protocol.registerBufferProtocol protocolName, emptyHandler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'does not crash when callback is called in next tick', (done) ->
handler = (request, callback) ->
setImmediate -> callback(text)
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.unregisterProtocol', ->
it 'returns error when scheme does not exist', (done) ->
protocol.unregisterProtocol 'not-exist', (error) ->
assert.notEqual error, null
done()
describe 'protocol.registerStringProtocol', ->
it 'sends string as response', (done) ->
handler = (request, callback) -> callback(text)
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(data: text, mimeType: 'text/html')
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending object other than string', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerBufferProtocol', ->
buffer = new Buffer(text)
it 'sends Buffer as response', (done) ->
handler = (request, callback) -> callback(buffer)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(data: buffer, mimeType: 'text/html')
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending string', (done) ->
handler = (request, callback) -> callback(text)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerFileProtocol', ->
filePath = path.join __dirname, 'fixtures', 'asar', 'a.asar', 'file1'
fileContent = require('fs').readFileSync(filePath)
normalPath = path.join __dirname, 'fixtures', 'pages', 'a.html'
normalContent = require('fs').readFileSync(normalPath)
it 'sends file path as response', (done) ->
handler = (request, callback) -> callback(filePath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, String(fileContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(path: filePath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, String(fileContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'can send normal file', (done) ->
handler = (request, callback) -> callback(normalPath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, String(normalContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending unexist-file', (done) ->
fakeFilePath = path.join __dirname, 'fixtures', 'asar', 'a.asar', 'not-exist'
handler = (request, callback) -> callback(fakeFilePath)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'fails when sending unsupported content', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerHttpProtocol', ->
it 'sends url as response', (done) ->
server = http.createServer (req, res) ->
assert.notEqual req.headers.accept, ''
res.end(text)
server.close()
server.listen 0, '127.0.0.1', ->
{port} = server.address()
url = "http://127.0.0.1:#{port}"
handler = (request, callback) -> callback({url})
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending invalid url', (done) ->
handler = (request, callback) -> callback({url: 'url'})
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'fails when sending unsupported content', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.isProtocolHandled', ->
it 'returns true for file:', (done) ->
protocol.isProtocolHandled 'file', (result) ->
assert.equal result, true
done()
it 'returns true for http:', (done) ->
protocol.isProtocolHandled 'http', (result) ->
assert.equal result, true
done()
it 'returns true for https:', (done) ->
protocol.isProtocolHandled 'https', (result) ->
assert.equal result, true
done()
it 'returns false when scheme is not registred', (done) ->
protocol.isProtocolHandled 'no-exist', (result) ->
assert.equal result, false
done()
it 'returns true for custom protocol', (done) ->
emptyHandler = (request, callback) -> callback()
protocol.registerStringProtocol protocolName, emptyHandler, (error) ->
assert.equal error, null
protocol.isProtocolHandled protocolName, (result) ->
assert.equal result, true
done()
it 'returns true for intercepted protocol', (done) ->
emptyHandler = (request, callback) -> callback()
protocol.interceptStringProtocol 'http', emptyHandler, (error) ->
assert.equal error, null
protocol.isProtocolHandled 'http', (result) ->
assert.equal result, true
done()
describe 'protocol.intercept(Any)Protocol', ->
emptyHandler = (request, callback) -> callback()
it 'throws error when scheme is already intercepted', (done) ->
protocol.interceptStringProtocol 'http', emptyHandler, (error) ->
assert.equal error, null
protocol.interceptBufferProtocol 'http', emptyHandler, (error) ->
assert.notEqual error, null
done()
it 'does not crash when handler is called twice', (done) ->
doubleHandler = (request, callback) ->
callback(text)
callback()
protocol.interceptStringProtocol 'http', doubleHandler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends error when callback is called with nothing', (done) ->
protocol.interceptBufferProtocol 'http', emptyHandler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.interceptStringProtocol', ->
it 'can intercept http protocol', (done) ->
handler = (request, callback) -> callback(text)
protocol.interceptStringProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'can set content-type', (done) ->
handler = (request, callback) ->
callback({mimeType: 'application/json', data: '{"value": 1}'})
protocol.interceptStringProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal typeof(data), 'object'
assert.equal data.value, 1
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.interceptBufferProtocol', ->
it 'can intercept http protocol', (done) ->
handler = (request, callback) -> callback(new Buffer(text))
protocol.interceptBufferProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.uninterceptProtocol', ->
it 'returns error when scheme does not exist', (done) ->
protocol.uninterceptProtocol 'not-exist', (error) ->
assert.notEqual error, null
done()
it 'returns error when scheme is not intercepted', (done) ->
protocol.uninterceptProtocol 'http', (error) ->
assert.notEqual error, null
done()
| true | assert = require 'assert'
http = require 'http'
path = require 'path'
remote = require 'remote'
protocol = remote.require 'protocol'
describe 'protocol module', ->
protocolName = 'sp'
text = 'PI:NAME:<NAME>END_PI'
afterEach (done) ->
protocol.unregisterProtocol protocolName, ->
protocol.uninterceptProtocol 'http', -> done()
describe 'protocol.register(Any)Protocol', ->
emptyHandler = (request, callback) -> callback()
it 'throws error when scheme is already registered', (done) ->
protocol.registerStringProtocol protocolName, emptyHandler, (error) ->
assert.equal error, null
protocol.registerBufferProtocol protocolName, emptyHandler, (error) ->
assert.notEqual error, null
done()
it 'does not crash when handler is called twice', (done) ->
doubleHandler = (request, callback) ->
callback(text)
callback()
protocol.registerStringProtocol protocolName, doubleHandler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends error when callback is called with nothing', (done) ->
protocol.registerBufferProtocol protocolName, emptyHandler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'does not crash when callback is called in next tick', (done) ->
handler = (request, callback) ->
setImmediate -> callback(text)
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.unregisterProtocol', ->
it 'returns error when scheme does not exist', (done) ->
protocol.unregisterProtocol 'not-exist', (error) ->
assert.notEqual error, null
done()
describe 'protocol.registerStringProtocol', ->
it 'sends string as response', (done) ->
handler = (request, callback) -> callback(text)
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(data: text, mimeType: 'text/html')
protocol.registerStringProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending object other than string', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerBufferProtocol', ->
buffer = new Buffer(text)
it 'sends Buffer as response', (done) ->
handler = (request, callback) -> callback(buffer)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(data: buffer, mimeType: 'text/html')
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending string', (done) ->
handler = (request, callback) -> callback(text)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerFileProtocol', ->
filePath = path.join __dirname, 'fixtures', 'asar', 'a.asar', 'file1'
fileContent = require('fs').readFileSync(filePath)
normalPath = path.join __dirname, 'fixtures', 'pages', 'a.html'
normalContent = require('fs').readFileSync(normalPath)
it 'sends file path as response', (done) ->
handler = (request, callback) -> callback(filePath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, String(fileContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends object as response', (done) ->
handler = (request, callback) -> callback(path: filePath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data, statux, request) ->
assert.equal data, String(fileContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'can send normal file', (done) ->
handler = (request, callback) -> callback(normalPath)
protocol.registerFileProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, String(normalContent)
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending unexist-file', (done) ->
fakeFilePath = path.join __dirname, 'fixtures', 'asar', 'a.asar', 'not-exist'
handler = (request, callback) -> callback(fakeFilePath)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'fails when sending unsupported content', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerBufferProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.registerHttpProtocol', ->
it 'sends url as response', (done) ->
server = http.createServer (req, res) ->
assert.notEqual req.headers.accept, ''
res.end(text)
server.close()
server.listen 0, '127.0.0.1', ->
{port} = server.address()
url = "http://127.0.0.1:#{port}"
handler = (request, callback) -> callback({url})
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'fails when sending invalid url', (done) ->
handler = (request, callback) -> callback({url: 'url'})
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
it 'fails when sending unsupported content', (done) ->
handler = (request, callback) -> callback(new Date)
protocol.registerHttpProtocol protocolName, handler, (error) ->
$.ajax
url: "#{protocolName}://fake-host"
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.isProtocolHandled', ->
it 'returns true for file:', (done) ->
protocol.isProtocolHandled 'file', (result) ->
assert.equal result, true
done()
it 'returns true for http:', (done) ->
protocol.isProtocolHandled 'http', (result) ->
assert.equal result, true
done()
it 'returns true for https:', (done) ->
protocol.isProtocolHandled 'https', (result) ->
assert.equal result, true
done()
it 'returns false when scheme is not registred', (done) ->
protocol.isProtocolHandled 'no-exist', (result) ->
assert.equal result, false
done()
it 'returns true for custom protocol', (done) ->
emptyHandler = (request, callback) -> callback()
protocol.registerStringProtocol protocolName, emptyHandler, (error) ->
assert.equal error, null
protocol.isProtocolHandled protocolName, (result) ->
assert.equal result, true
done()
it 'returns true for intercepted protocol', (done) ->
emptyHandler = (request, callback) -> callback()
protocol.interceptStringProtocol 'http', emptyHandler, (error) ->
assert.equal error, null
protocol.isProtocolHandled 'http', (result) ->
assert.equal result, true
done()
describe 'protocol.intercept(Any)Protocol', ->
emptyHandler = (request, callback) -> callback()
it 'throws error when scheme is already intercepted', (done) ->
protocol.interceptStringProtocol 'http', emptyHandler, (error) ->
assert.equal error, null
protocol.interceptBufferProtocol 'http', emptyHandler, (error) ->
assert.notEqual error, null
done()
it 'does not crash when handler is called twice', (done) ->
doubleHandler = (request, callback) ->
callback(text)
callback()
protocol.interceptStringProtocol 'http', doubleHandler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'sends error when callback is called with nothing', (done) ->
protocol.interceptBufferProtocol 'http', emptyHandler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
done('request succeeded but it should not')
error: (xhr, errorType, error) ->
assert.equal errorType, 'error'
done()
describe 'protocol.interceptStringProtocol', ->
it 'can intercept http protocol', (done) ->
handler = (request, callback) -> callback(text)
protocol.interceptStringProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
it 'can set content-type', (done) ->
handler = (request, callback) ->
callback({mimeType: 'application/json', data: '{"value": 1}'})
protocol.interceptStringProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal typeof(data), 'object'
assert.equal data.value, 1
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.interceptBufferProtocol', ->
it 'can intercept http protocol', (done) ->
handler = (request, callback) -> callback(new Buffer(text))
protocol.interceptBufferProtocol 'http', handler, (error) ->
$.ajax
url: 'http://fake-host'
success: (data) ->
assert.equal data, text
done()
error: (xhr, errorType, error) ->
done(error)
describe 'protocol.uninterceptProtocol', ->
it 'returns error when scheme does not exist', (done) ->
protocol.uninterceptProtocol 'not-exist', (error) ->
assert.notEqual error, null
done()
it 'returns error when scheme is not intercepted', (done) ->
protocol.uninterceptProtocol 'http', (error) ->
assert.notEqual error, null
done()
|
[
{
"context": "thub.com/thrustlabs/contact-parser\n\nCopyright 2014 Jason Doucette, Thrust Labs\n\nPermission is hereby granted, free ",
"end": 132,
"score": 0.9998777508735657,
"start": 118,
"tag": "NAME",
"value": "Jason Doucette"
}
] | src/contact-parser.coffee | thrustlabs/contact-parser | 10 | ###
ContactParser: an address parser class
Version 1.0
https://github.com/thrustlabs/contact-parser
Copyright 2014 Jason Doucette, Thrust Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
###
class ContactParser
class ContactParserResult
constructor: () ->
@name = ''
@email = ''
@province = ''
@country = ''
@address = ''
@city = ''
@postal = ''
@website = ''
@phone = ''
score: () ->
return 0 if !@address
return 50 if @address && @city && !@province && !@postal && !@country
return 80 if @address && @city && @province && !@postal && !@country
return 90 if !@phone || !@email || !@website
return 100
canadianProvinces = {
'british_columbia': 'BC', 'bc': 'BC',
'alberta': 'AB', 'ab': 'AB',
'saskatchewan': 'sk', 'sk': 'SK',
'manitoba': 'MB', 'mb': 'MB',
'ontario': 'ON', 'on': 'ON'
'quebec': 'QC', 'qc': 'QC',
'newfoundland': 'NL', 'newfoundland_and_labrador': 'NL', 'labrador': 'NL', 'nl': 'NL',
'new_brunswick': 'NB', 'nb': 'NB',
'prince_edward_island': 'PE', 'PEI': 'PE', 'pe': 'PE',
'nova_scotia': 'NS', 'ns': 'NS',
'yukon_territories': 'YT', 'yukon': 'YT', 'yt': 'YT',
'northwest_territories': 'NT', 'nt': 'NT',
'nunavut': 'NU', 'nu': 'NU'
}
americanStates = {
'alabama': 'AL', 'al': 'AL',
'alaska': 'AK', 'ak': 'AK',
'american_samoa': 'AS', 'as': 'AS',
'arizona': 'AZ', 'az': 'AZ',
'arkansas': 'AR', 'ar': 'AR',
'california': 'CA', 'ca': 'CA',
'colorado': 'CO', 'co': 'CO',
'connecticut': 'CT', 'ct': 'CT',
'delaware': 'DE', 'de': 'DE',
'district_of_columbia': 'DC', 'd.c.': 'DC', 'dc': 'DC',
'federated_states_of_micronesia': 'FM', 'fm': 'FM',
'florida': 'FL', 'fl': 'FL',
'georgia': 'GA', 'ga': 'GA',
'guam': 'GU', 'gu': 'GU',
'hawaii': 'HI', 'hi': 'HI',
'idaho': 'ID', 'id': 'ID',
'illinois': 'IL', 'il': 'IL',
'indiana': 'IN', 'in': 'IN',
'iowa': 'IA', 'ia': 'IA',
'kansas': 'KS', 'ks': 'KS',
'kentucky': 'KY', 'ky': 'KY',
'louisiana': 'LA', 'la': 'LA',
'maine': 'ME', 'me': 'ME',
'marshall_islands': 'MH', 'mh': 'MH',
'maryland': 'MD', 'md': 'MD',
'massachusetts': 'MA', 'ma': 'MA',
'michigan': 'MI', 'mi': 'MI',
'minnesota': 'MN', 'mn': 'MN',
'mississippi': 'MS', 'ms': 'MS',
'missouri': 'MO', 'mo': 'MO',
'montana': 'MT', 'mt': 'MT',
'nebraska': 'NE', 'ne': 'NE',
'nevada': 'NV', 'nv': 'NV',
'new_hampshire': 'NH', 'nh': 'NH',
'new_jersey': 'NJ', 'nj': 'NJ',
'new_mexico': 'NM', 'nm': 'NM',
'new_york': 'NY', 'ny': 'NY',
'north_carolina': 'NC', 'nc': 'NC',
'north_dakota': 'ND', 'nd': 'ND',
'northern_mariana_islands': 'MP', 'mp': 'MP',
'ohio': 'OH', 'oh': 'OH',
'oklahoma': 'OK', 'ok': 'OK',
'oregon': 'OR', 'or': 'OR',
'palau': 'PW', 'pw': 'PW',
'pennsylvania': 'PA', 'pa': 'PA',
'puerto_rico': 'PR', 'pr': 'PR',
'rhode_island': 'RI', 'ri': 'RI',
'south_carolina': 'SC', 'sc': 'SC',
'south_dakota': 'SD', 'sd': 'SD',
'tennessee': 'TN', 'tn': 'TN',
'texas': 'TX', 'tx': 'TX',
'utah': 'UT', 'ut': 'UT',
'vermont': 'VT', 'vt': 'VT',
'virgin_islands': 'VI', 'vi': 'VI',
'virginia': 'VA', 'va': 'VA',
'washington': 'WA', 'wa': 'WA',
'west_virginia': 'WV', 'wv': 'WV',
'wisconsin': 'WI', 'wi': 'WI',
'wyoming': 'WY', 'wy': 'WY'
}
parse: (address) ->
result = new ContactParserResult
if address is undefined || address is null || address.trim() == ''
return result
indexes = {}
usedFields = []
trim = (txt) ->
return (txt || '').replace(/^\s+|\s+$/g, '')
canadianPostalRegex = /[a-z]\d[a-z]\s*\d[a-z]\d/i
usZipRegex = /\w(?:,\s*|\s+)(\d\d\d\d\d(-\d\d\d\d){0,1})/ # Check that zip follows *something* so it's not confused with a street #
emailRegex = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/i
websiteRegex = /(http|www)\S+/
streetNameRegex = /\s(dr\.{0,1}|drive|st\.{0,1}|street|(?:alle?y)|(?:app(?:roach)?)|(?:arc(?:ade)?)|(?:av(?:e|enue)?)|(?:(?:boulevard|blvd))|(?:brow)|(?:bypa(?:ss)?)|(?:c(?:ause)?way)|(?:(?:circuit|cct))|(?:circ(?:us)?)|(?:cl(?:ose)?)|(?:co?pse)|(?:(?:corner|cnr))|(?:(?:c(?:(?:our)|r)?t|crt))|(?:cres(?:cent)?)|(?:dr(?:ive)?)|(?:esp(?:lanande)?)|(?:f(?:ree)?way)|(?:(?:frontage|frnt))|(?:(?:glade|gld))|(?:gr(?:ee)?n)|(?:(?:highway|hwy))|(?:(?:lane|ln))|(?:link)|(?:loop)|(?:mall)|(?:mews)|(?:(?:packet|pckt))|(?:p(?:ara)?de)|(?:(?:parkway|pkwy))|(?:pl(?:ace)?)|(?:prom(?:enade)?)|(?:res(?:erve)?)|(?:rise)|(?:r(?:oa)?d)|(?:row)|(?:sq(?:uare)?)|(?:st(?:reet)?)|(?:stri?p)|(?:tarn)|(?:t(?:erra)?ce)|(?:(?:thoroughfare|tfre))|(?:track?)|(?:t(?:runk)?way)|(?:vi?sta)|(?:walk)|(?:wa?y)|(?:w(?:alk)?way)|(?:yard))\s*(#\S+|((suite|unit|apt\.{0,1}|apartment)\s*\S+)){0,1}(\s|$)/i
phoneRegex = /(\s*phone\s*\:{0,1}\s*){0,1}(\d\d\d)[ \-\.](\d\d\d)[ \-\.](\d\d\d\d)/ig
addressRegex = /^(\w*\d\w*)+\s+.*/
poBoxRegex = /^\s*(((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))\s+[\d\.#\-]+)/i
if poBoxRegex.test(address)
matches = address.match(poBoxRegex)
result.address = matches[0]
address = address.replace(matches[0], ',')
if canadianPostalRegex.test(address)
matches = address.match(canadianPostalRegex)
result.postal = matches[0]
address = address.replace(matches[0], ',')
if usZipRegex.test(address)
matches = address.match(usZipRegex)
result.postal = matches[1]
address = address.replace(matches[1], ',')
if matches = emailRegex.exec(address)
result.email = matches[0]
address = address.replace(matches[0], ',')
if matches = phoneRegex.exec(address)
# Is there another, maybe better match?
secondCheck = phoneRegex.exec(address)
if secondCheck && matches[0].length < secondCheck[0].length
matches = secondCheck
result.phone = "(#{matches[2]}) #{matches[3]}-#{matches[4]}"
address = address.replace(matches[0], ',')
fields = address.split(/\s*[,\n\|\u2022\u2219]\s*/)
if !addressRegex.test(trim(fields[0]))
result.name = trim(fields[0])
fields.shift
for field, i in fields
field = trim(field)
if !result.address && addressRegex.test(field)
result.address = field
indexes['address'] = i
usedFields.push(i)
matches = result.address.match(streetNameRegex)
if matches
if result.address.indexOf(matches[0]) < result.address.length - matches[0].length - 1
extraInfo = result.address.substring(result.address.indexOf(matches[0]) + matches[0].length)
result.city = trim(extraInfo)
result.address = trim(result.address.substring(0, result.address.indexOf(matches[0]) + matches[0].length - 1))
else if websiteRegex.test(field)
result.website = field
result.website = "http://#{result.website}" if result.website.indexOf('http') != 0
indexes['website'] = i
usedFields.push(i)
else
subfields = fields[i]
for key, value of require('util')._extend({}, americanStates, canadianProvinces)
if key.indexOf('_') > 0
search = "(#{key.replace('_', ') (')})"
replacement = key.replace(/[^_]+/g, "$$$$")
ri = 1
while(replacement.indexOf("$$") >= 0)
replacement = replacement.replace("$$", "$#{ri++}")
subfields = subfields.replace(new RegExp(search, 'i'), replacement)
subfields = subfields.split(/\s+/)
for subfield, ix in subfields
if subfield.toLowerCase() of canadianProvinces
result.province = canadianProvinces[subfield.toLowerCase()]
result.country = 'Canada'
fields[i] = fields[i].replace(subfield, '')
indexes['province'] = i + (trim(fields[i]).length > 0 ? 1 : 0)
usedFields.push(i)
break;
else if subfield.toLowerCase() of americanStates
result.province = americanStates[subfield.toLowerCase()]
result.country = 'USA'
fields[i] = fields[i].replace(subfield.replace('_', ' '), '')
indexes['province'] = i + (trim(fields[i]).length > 0 ? 1 : 0)
usedFields.push(i)
break;
if !result.city && indexes['province']
possibleCity = trim(fields[indexes['province']-1])
if (indexes['province']-1) in usedFields
# We've used this for something else
if indexes['address'] == indexes['province']-1
# We've already used the field before the province for the address, so give up on city parsing.
possibleCity = '';
result.city = possibleCity
usedFields.push(indexes['province']-1)
if indexes['address']
i = indexes['address']
#result.address = "#{i} #{fields[i+1]} #{usedFields[i+1]} #{fields.length}"
while i+1 <= fields.length && (i+1) not in usedFields
i++
if trim(fields[i]) != ''
result.address = "#{result.address}, #{trim(fields[i])}"
return result
module.exports = () ->
return new ContactParser
| 83298 | ###
ContactParser: an address parser class
Version 1.0
https://github.com/thrustlabs/contact-parser
Copyright 2014 <NAME>, Thrust Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
###
class ContactParser
class ContactParserResult
constructor: () ->
@name = ''
@email = ''
@province = ''
@country = ''
@address = ''
@city = ''
@postal = ''
@website = ''
@phone = ''
score: () ->
return 0 if !@address
return 50 if @address && @city && !@province && !@postal && !@country
return 80 if @address && @city && @province && !@postal && !@country
return 90 if !@phone || !@email || !@website
return 100
canadianProvinces = {
'british_columbia': 'BC', 'bc': 'BC',
'alberta': 'AB', 'ab': 'AB',
'saskatchewan': 'sk', 'sk': 'SK',
'manitoba': 'MB', 'mb': 'MB',
'ontario': 'ON', 'on': 'ON'
'quebec': 'QC', 'qc': 'QC',
'newfoundland': 'NL', 'newfoundland_and_labrador': 'NL', 'labrador': 'NL', 'nl': 'NL',
'new_brunswick': 'NB', 'nb': 'NB',
'prince_edward_island': 'PE', 'PEI': 'PE', 'pe': 'PE',
'nova_scotia': 'NS', 'ns': 'NS',
'yukon_territories': 'YT', 'yukon': 'YT', 'yt': 'YT',
'northwest_territories': 'NT', 'nt': 'NT',
'nunavut': 'NU', 'nu': 'NU'
}
americanStates = {
'alabama': 'AL', 'al': 'AL',
'alaska': 'AK', 'ak': 'AK',
'american_samoa': 'AS', 'as': 'AS',
'arizona': 'AZ', 'az': 'AZ',
'arkansas': 'AR', 'ar': 'AR',
'california': 'CA', 'ca': 'CA',
'colorado': 'CO', 'co': 'CO',
'connecticut': 'CT', 'ct': 'CT',
'delaware': 'DE', 'de': 'DE',
'district_of_columbia': 'DC', 'd.c.': 'DC', 'dc': 'DC',
'federated_states_of_micronesia': 'FM', 'fm': 'FM',
'florida': 'FL', 'fl': 'FL',
'georgia': 'GA', 'ga': 'GA',
'guam': 'GU', 'gu': 'GU',
'hawaii': 'HI', 'hi': 'HI',
'idaho': 'ID', 'id': 'ID',
'illinois': 'IL', 'il': 'IL',
'indiana': 'IN', 'in': 'IN',
'iowa': 'IA', 'ia': 'IA',
'kansas': 'KS', 'ks': 'KS',
'kentucky': 'KY', 'ky': 'KY',
'louisiana': 'LA', 'la': 'LA',
'maine': 'ME', 'me': 'ME',
'marshall_islands': 'MH', 'mh': 'MH',
'maryland': 'MD', 'md': 'MD',
'massachusetts': 'MA', 'ma': 'MA',
'michigan': 'MI', 'mi': 'MI',
'minnesota': 'MN', 'mn': 'MN',
'mississippi': 'MS', 'ms': 'MS',
'missouri': 'MO', 'mo': 'MO',
'montana': 'MT', 'mt': 'MT',
'nebraska': 'NE', 'ne': 'NE',
'nevada': 'NV', 'nv': 'NV',
'new_hampshire': 'NH', 'nh': 'NH',
'new_jersey': 'NJ', 'nj': 'NJ',
'new_mexico': 'NM', 'nm': 'NM',
'new_york': 'NY', 'ny': 'NY',
'north_carolina': 'NC', 'nc': 'NC',
'north_dakota': 'ND', 'nd': 'ND',
'northern_mariana_islands': 'MP', 'mp': 'MP',
'ohio': 'OH', 'oh': 'OH',
'oklahoma': 'OK', 'ok': 'OK',
'oregon': 'OR', 'or': 'OR',
'palau': 'PW', 'pw': 'PW',
'pennsylvania': 'PA', 'pa': 'PA',
'puerto_rico': 'PR', 'pr': 'PR',
'rhode_island': 'RI', 'ri': 'RI',
'south_carolina': 'SC', 'sc': 'SC',
'south_dakota': 'SD', 'sd': 'SD',
'tennessee': 'TN', 'tn': 'TN',
'texas': 'TX', 'tx': 'TX',
'utah': 'UT', 'ut': 'UT',
'vermont': 'VT', 'vt': 'VT',
'virgin_islands': 'VI', 'vi': 'VI',
'virginia': 'VA', 'va': 'VA',
'washington': 'WA', 'wa': 'WA',
'west_virginia': 'WV', 'wv': 'WV',
'wisconsin': 'WI', 'wi': 'WI',
'wyoming': 'WY', 'wy': 'WY'
}
parse: (address) ->
result = new ContactParserResult
if address is undefined || address is null || address.trim() == ''
return result
indexes = {}
usedFields = []
trim = (txt) ->
return (txt || '').replace(/^\s+|\s+$/g, '')
canadianPostalRegex = /[a-z]\d[a-z]\s*\d[a-z]\d/i
usZipRegex = /\w(?:,\s*|\s+)(\d\d\d\d\d(-\d\d\d\d){0,1})/ # Check that zip follows *something* so it's not confused with a street #
emailRegex = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/i
websiteRegex = /(http|www)\S+/
streetNameRegex = /\s(dr\.{0,1}|drive|st\.{0,1}|street|(?:alle?y)|(?:app(?:roach)?)|(?:arc(?:ade)?)|(?:av(?:e|enue)?)|(?:(?:boulevard|blvd))|(?:brow)|(?:bypa(?:ss)?)|(?:c(?:ause)?way)|(?:(?:circuit|cct))|(?:circ(?:us)?)|(?:cl(?:ose)?)|(?:co?pse)|(?:(?:corner|cnr))|(?:(?:c(?:(?:our)|r)?t|crt))|(?:cres(?:cent)?)|(?:dr(?:ive)?)|(?:esp(?:lanande)?)|(?:f(?:ree)?way)|(?:(?:frontage|frnt))|(?:(?:glade|gld))|(?:gr(?:ee)?n)|(?:(?:highway|hwy))|(?:(?:lane|ln))|(?:link)|(?:loop)|(?:mall)|(?:mews)|(?:(?:packet|pckt))|(?:p(?:ara)?de)|(?:(?:parkway|pkwy))|(?:pl(?:ace)?)|(?:prom(?:enade)?)|(?:res(?:erve)?)|(?:rise)|(?:r(?:oa)?d)|(?:row)|(?:sq(?:uare)?)|(?:st(?:reet)?)|(?:stri?p)|(?:tarn)|(?:t(?:erra)?ce)|(?:(?:thoroughfare|tfre))|(?:track?)|(?:t(?:runk)?way)|(?:vi?sta)|(?:walk)|(?:wa?y)|(?:w(?:alk)?way)|(?:yard))\s*(#\S+|((suite|unit|apt\.{0,1}|apartment)\s*\S+)){0,1}(\s|$)/i
phoneRegex = /(\s*phone\s*\:{0,1}\s*){0,1}(\d\d\d)[ \-\.](\d\d\d)[ \-\.](\d\d\d\d)/ig
addressRegex = /^(\w*\d\w*)+\s+.*/
poBoxRegex = /^\s*(((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))\s+[\d\.#\-]+)/i
if poBoxRegex.test(address)
matches = address.match(poBoxRegex)
result.address = matches[0]
address = address.replace(matches[0], ',')
if canadianPostalRegex.test(address)
matches = address.match(canadianPostalRegex)
result.postal = matches[0]
address = address.replace(matches[0], ',')
if usZipRegex.test(address)
matches = address.match(usZipRegex)
result.postal = matches[1]
address = address.replace(matches[1], ',')
if matches = emailRegex.exec(address)
result.email = matches[0]
address = address.replace(matches[0], ',')
if matches = phoneRegex.exec(address)
# Is there another, maybe better match?
secondCheck = phoneRegex.exec(address)
if secondCheck && matches[0].length < secondCheck[0].length
matches = secondCheck
result.phone = "(#{matches[2]}) #{matches[3]}-#{matches[4]}"
address = address.replace(matches[0], ',')
fields = address.split(/\s*[,\n\|\u2022\u2219]\s*/)
if !addressRegex.test(trim(fields[0]))
result.name = trim(fields[0])
fields.shift
for field, i in fields
field = trim(field)
if !result.address && addressRegex.test(field)
result.address = field
indexes['address'] = i
usedFields.push(i)
matches = result.address.match(streetNameRegex)
if matches
if result.address.indexOf(matches[0]) < result.address.length - matches[0].length - 1
extraInfo = result.address.substring(result.address.indexOf(matches[0]) + matches[0].length)
result.city = trim(extraInfo)
result.address = trim(result.address.substring(0, result.address.indexOf(matches[0]) + matches[0].length - 1))
else if websiteRegex.test(field)
result.website = field
result.website = "http://#{result.website}" if result.website.indexOf('http') != 0
indexes['website'] = i
usedFields.push(i)
else
subfields = fields[i]
for key, value of require('util')._extend({}, americanStates, canadianProvinces)
if key.indexOf('_') > 0
search = "(#{key.replace('_', ') (')})"
replacement = key.replace(/[^_]+/g, "$$$$")
ri = 1
while(replacement.indexOf("$$") >= 0)
replacement = replacement.replace("$$", "$#{ri++}")
subfields = subfields.replace(new RegExp(search, 'i'), replacement)
subfields = subfields.split(/\s+/)
for subfield, ix in subfields
if subfield.toLowerCase() of canadianProvinces
result.province = canadianProvinces[subfield.toLowerCase()]
result.country = 'Canada'
fields[i] = fields[i].replace(subfield, '')
indexes['province'] = i + (trim(fields[i]).length > 0 ? 1 : 0)
usedFields.push(i)
break;
else if subfield.toLowerCase() of americanStates
result.province = americanStates[subfield.toLowerCase()]
result.country = 'USA'
fields[i] = fields[i].replace(subfield.replace('_', ' '), '')
indexes['province'] = i + (trim(fields[i]).length > 0 ? 1 : 0)
usedFields.push(i)
break;
if !result.city && indexes['province']
possibleCity = trim(fields[indexes['province']-1])
if (indexes['province']-1) in usedFields
# We've used this for something else
if indexes['address'] == indexes['province']-1
# We've already used the field before the province for the address, so give up on city parsing.
possibleCity = '';
result.city = possibleCity
usedFields.push(indexes['province']-1)
if indexes['address']
i = indexes['address']
#result.address = "#{i} #{fields[i+1]} #{usedFields[i+1]} #{fields.length}"
while i+1 <= fields.length && (i+1) not in usedFields
i++
if trim(fields[i]) != ''
result.address = "#{result.address}, #{trim(fields[i])}"
return result
module.exports = () ->
return new ContactParser
| true | ###
ContactParser: an address parser class
Version 1.0
https://github.com/thrustlabs/contact-parser
Copyright 2014 PI:NAME:<NAME>END_PI, Thrust Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
###
class ContactParser
class ContactParserResult
constructor: () ->
@name = ''
@email = ''
@province = ''
@country = ''
@address = ''
@city = ''
@postal = ''
@website = ''
@phone = ''
score: () ->
return 0 if !@address
return 50 if @address && @city && !@province && !@postal && !@country
return 80 if @address && @city && @province && !@postal && !@country
return 90 if !@phone || !@email || !@website
return 100
canadianProvinces = {
'british_columbia': 'BC', 'bc': 'BC',
'alberta': 'AB', 'ab': 'AB',
'saskatchewan': 'sk', 'sk': 'SK',
'manitoba': 'MB', 'mb': 'MB',
'ontario': 'ON', 'on': 'ON'
'quebec': 'QC', 'qc': 'QC',
'newfoundland': 'NL', 'newfoundland_and_labrador': 'NL', 'labrador': 'NL', 'nl': 'NL',
'new_brunswick': 'NB', 'nb': 'NB',
'prince_edward_island': 'PE', 'PEI': 'PE', 'pe': 'PE',
'nova_scotia': 'NS', 'ns': 'NS',
'yukon_territories': 'YT', 'yukon': 'YT', 'yt': 'YT',
'northwest_territories': 'NT', 'nt': 'NT',
'nunavut': 'NU', 'nu': 'NU'
}
americanStates = {
'alabama': 'AL', 'al': 'AL',
'alaska': 'AK', 'ak': 'AK',
'american_samoa': 'AS', 'as': 'AS',
'arizona': 'AZ', 'az': 'AZ',
'arkansas': 'AR', 'ar': 'AR',
'california': 'CA', 'ca': 'CA',
'colorado': 'CO', 'co': 'CO',
'connecticut': 'CT', 'ct': 'CT',
'delaware': 'DE', 'de': 'DE',
'district_of_columbia': 'DC', 'd.c.': 'DC', 'dc': 'DC',
'federated_states_of_micronesia': 'FM', 'fm': 'FM',
'florida': 'FL', 'fl': 'FL',
'georgia': 'GA', 'ga': 'GA',
'guam': 'GU', 'gu': 'GU',
'hawaii': 'HI', 'hi': 'HI',
'idaho': 'ID', 'id': 'ID',
'illinois': 'IL', 'il': 'IL',
'indiana': 'IN', 'in': 'IN',
'iowa': 'IA', 'ia': 'IA',
'kansas': 'KS', 'ks': 'KS',
'kentucky': 'KY', 'ky': 'KY',
'louisiana': 'LA', 'la': 'LA',
'maine': 'ME', 'me': 'ME',
'marshall_islands': 'MH', 'mh': 'MH',
'maryland': 'MD', 'md': 'MD',
'massachusetts': 'MA', 'ma': 'MA',
'michigan': 'MI', 'mi': 'MI',
'minnesota': 'MN', 'mn': 'MN',
'mississippi': 'MS', 'ms': 'MS',
'missouri': 'MO', 'mo': 'MO',
'montana': 'MT', 'mt': 'MT',
'nebraska': 'NE', 'ne': 'NE',
'nevada': 'NV', 'nv': 'NV',
'new_hampshire': 'NH', 'nh': 'NH',
'new_jersey': 'NJ', 'nj': 'NJ',
'new_mexico': 'NM', 'nm': 'NM',
'new_york': 'NY', 'ny': 'NY',
'north_carolina': 'NC', 'nc': 'NC',
'north_dakota': 'ND', 'nd': 'ND',
'northern_mariana_islands': 'MP', 'mp': 'MP',
'ohio': 'OH', 'oh': 'OH',
'oklahoma': 'OK', 'ok': 'OK',
'oregon': 'OR', 'or': 'OR',
'palau': 'PW', 'pw': 'PW',
'pennsylvania': 'PA', 'pa': 'PA',
'puerto_rico': 'PR', 'pr': 'PR',
'rhode_island': 'RI', 'ri': 'RI',
'south_carolina': 'SC', 'sc': 'SC',
'south_dakota': 'SD', 'sd': 'SD',
'tennessee': 'TN', 'tn': 'TN',
'texas': 'TX', 'tx': 'TX',
'utah': 'UT', 'ut': 'UT',
'vermont': 'VT', 'vt': 'VT',
'virgin_islands': 'VI', 'vi': 'VI',
'virginia': 'VA', 'va': 'VA',
'washington': 'WA', 'wa': 'WA',
'west_virginia': 'WV', 'wv': 'WV',
'wisconsin': 'WI', 'wi': 'WI',
'wyoming': 'WY', 'wy': 'WY'
}
parse: (address) ->
result = new ContactParserResult
if address is undefined || address is null || address.trim() == ''
return result
indexes = {}
usedFields = []
trim = (txt) ->
return (txt || '').replace(/^\s+|\s+$/g, '')
canadianPostalRegex = /[a-z]\d[a-z]\s*\d[a-z]\d/i
usZipRegex = /\w(?:,\s*|\s+)(\d\d\d\d\d(-\d\d\d\d){0,1})/ # Check that zip follows *something* so it's not confused with a street #
emailRegex = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/i
websiteRegex = /(http|www)\S+/
streetNameRegex = /\s(dr\.{0,1}|drive|st\.{0,1}|street|(?:alle?y)|(?:app(?:roach)?)|(?:arc(?:ade)?)|(?:av(?:e|enue)?)|(?:(?:boulevard|blvd))|(?:brow)|(?:bypa(?:ss)?)|(?:c(?:ause)?way)|(?:(?:circuit|cct))|(?:circ(?:us)?)|(?:cl(?:ose)?)|(?:co?pse)|(?:(?:corner|cnr))|(?:(?:c(?:(?:our)|r)?t|crt))|(?:cres(?:cent)?)|(?:dr(?:ive)?)|(?:esp(?:lanande)?)|(?:f(?:ree)?way)|(?:(?:frontage|frnt))|(?:(?:glade|gld))|(?:gr(?:ee)?n)|(?:(?:highway|hwy))|(?:(?:lane|ln))|(?:link)|(?:loop)|(?:mall)|(?:mews)|(?:(?:packet|pckt))|(?:p(?:ara)?de)|(?:(?:parkway|pkwy))|(?:pl(?:ace)?)|(?:prom(?:enade)?)|(?:res(?:erve)?)|(?:rise)|(?:r(?:oa)?d)|(?:row)|(?:sq(?:uare)?)|(?:st(?:reet)?)|(?:stri?p)|(?:tarn)|(?:t(?:erra)?ce)|(?:(?:thoroughfare|tfre))|(?:track?)|(?:t(?:runk)?way)|(?:vi?sta)|(?:walk)|(?:wa?y)|(?:w(?:alk)?way)|(?:yard))\s*(#\S+|((suite|unit|apt\.{0,1}|apartment)\s*\S+)){0,1}(\s|$)/i
phoneRegex = /(\s*phone\s*\:{0,1}\s*){0,1}(\d\d\d)[ \-\.](\d\d\d)[ \-\.](\d\d\d\d)/ig
addressRegex = /^(\w*\d\w*)+\s+.*/
poBoxRegex = /^\s*(((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))\s+[\d\.#\-]+)/i
if poBoxRegex.test(address)
matches = address.match(poBoxRegex)
result.address = matches[0]
address = address.replace(matches[0], ',')
if canadianPostalRegex.test(address)
matches = address.match(canadianPostalRegex)
result.postal = matches[0]
address = address.replace(matches[0], ',')
if usZipRegex.test(address)
matches = address.match(usZipRegex)
result.postal = matches[1]
address = address.replace(matches[1], ',')
if matches = emailRegex.exec(address)
result.email = matches[0]
address = address.replace(matches[0], ',')
if matches = phoneRegex.exec(address)
# Is there another, maybe better match?
secondCheck = phoneRegex.exec(address)
if secondCheck && matches[0].length < secondCheck[0].length
matches = secondCheck
result.phone = "(#{matches[2]}) #{matches[3]}-#{matches[4]}"
address = address.replace(matches[0], ',')
fields = address.split(/\s*[,\n\|\u2022\u2219]\s*/)
if !addressRegex.test(trim(fields[0]))
result.name = trim(fields[0])
fields.shift
for field, i in fields
field = trim(field)
if !result.address && addressRegex.test(field)
result.address = field
indexes['address'] = i
usedFields.push(i)
matches = result.address.match(streetNameRegex)
if matches
if result.address.indexOf(matches[0]) < result.address.length - matches[0].length - 1
extraInfo = result.address.substring(result.address.indexOf(matches[0]) + matches[0].length)
result.city = trim(extraInfo)
result.address = trim(result.address.substring(0, result.address.indexOf(matches[0]) + matches[0].length - 1))
else if websiteRegex.test(field)
result.website = field
result.website = "http://#{result.website}" if result.website.indexOf('http') != 0
indexes['website'] = i
usedFields.push(i)
else
subfields = fields[i]
for key, value of require('util')._extend({}, americanStates, canadianProvinces)
if key.indexOf('_') > 0
search = "(#{key.replace('_', ') (')})"
replacement = key.replace(/[^_]+/g, "$$$$")
ri = 1
while(replacement.indexOf("$$") >= 0)
replacement = replacement.replace("$$", "$#{ri++}")
subfields = subfields.replace(new RegExp(search, 'i'), replacement)
subfields = subfields.split(/\s+/)
for subfield, ix in subfields
if subfield.toLowerCase() of canadianProvinces
result.province = canadianProvinces[subfield.toLowerCase()]
result.country = 'Canada'
fields[i] = fields[i].replace(subfield, '')
indexes['province'] = i + (trim(fields[i]).length > 0 ? 1 : 0)
usedFields.push(i)
break;
else if subfield.toLowerCase() of americanStates
result.province = americanStates[subfield.toLowerCase()]
result.country = 'USA'
fields[i] = fields[i].replace(subfield.replace('_', ' '), '')
indexes['province'] = i + (trim(fields[i]).length > 0 ? 1 : 0)
usedFields.push(i)
break;
if !result.city && indexes['province']
possibleCity = trim(fields[indexes['province']-1])
if (indexes['province']-1) in usedFields
# We've used this for something else
if indexes['address'] == indexes['province']-1
# We've already used the field before the province for the address, so give up on city parsing.
possibleCity = '';
result.city = possibleCity
usedFields.push(indexes['province']-1)
if indexes['address']
i = indexes['address']
#result.address = "#{i} #{fields[i+1]} #{usedFields[i+1]} #{fields.length}"
while i+1 <= fields.length && (i+1) not in usedFields
i++
if trim(fields[i]) != ''
result.address = "#{result.address}, #{trim(fields[i])}"
return result
module.exports = () ->
return new ContactParser
|
[
{
"context": "require('./pg_connection')\r\n\r\nmq_server = 'amqp://54.76.183.35:5672'\r\ncontext = require('rabbit.js').createConte",
"end": 135,
"score": 0.9995997548103333,
"start": 123,
"tag": "IP_ADDRESS",
"value": "54.76.183.35"
},
{
"context": ".js').createContext(mq_server);\... | python/environment_movement/world_movement.coffee | douglassquirrel/microservices-hackathon-july-2014 | 1 | Array.prototype.last = ()->
return this[-1..][0]
data_provider = require('./pg_connection')
mq_server = 'amqp://54.76.183.35:5672'
context = require('rabbit.js').createContext(mq_server);
exchange_name = 'alex2'
connected_rooms = []
users = {}
publish_movement_success = (user_id,room)->
console.log('Ready to publish success')
pub = context.socket('PUB',{routing:'topic'});
pub.on('error',(err)-> console.log('Crashed',err))
pub.connect('alex2',->
console.log('Publishing movement_successful for',user_id)
pub.publish('movement_successful',JSON.stringify(
{
user_id:user_id,
room_name:room
}
));
)
publish_movement_failed = (user_id,room)->
console.log('Ready to publish failure')
pub = context.socket('PUB',{routing:'topic'});
pub.on('error',(err)-> console.log('Crashed',err))
pub.connect('alex2',->
console.log('Publishing movement_failed for',user_id)
pub.publish('movement_failed',JSON.stringify(
{
user_id:user_id,
room_name:room
}
));
)
handlers = {
'door_created': (message)->
console.log('door_created :',message)
connected_rooms.push([message.room_one_name, message.room_two_name])
'movement_successful': (message)->
console.log('movement_successful :', message)
users[message.user_id] = users[message.user_id] || {}
users[message.user_id].current_location = message.room_name
'user_intended_to_move' : (message,isReplay)->
if isReplay then return
console.log('user_intended_to_move :',message)
user = users[message.user_id]
if not user
console.log('\tuser does not exist')
return
location = user.current_location
for door in connected_rooms
if location in door and message.room_id in door
publish_movement_success(message.user_id,message.room_id)
return;
publish_movement_failed(message.user_id,message.room_id)
}
context.on('ready', ->
data_provider.getPreviousData( (data)->
for row in data
handlers[row.topic]?(row.content,true)
)
# console.log('\n****ready to listen for new stuff****\n')
Object.keys(handlers).forEach((topic_name)->
subscriber = context.socket('SUB',{routing:'topic'})
subscriber.connect(exchange_name,topic_name,->
console.log("#{topic_name} listener started")
subscriber.on('data',(string_message)->
handlers[topic_name](JSON.parse(string_message))
)
)
)
) | 112832 | Array.prototype.last = ()->
return this[-1..][0]
data_provider = require('./pg_connection')
mq_server = 'amqp://192.168.3.11:5672'
context = require('rabbit.js').createContext(mq_server);
exchange_name = 'alex2'
connected_rooms = []
users = {}
publish_movement_success = (user_id,room)->
console.log('Ready to publish success')
pub = context.socket('PUB',{routing:'topic'});
pub.on('error',(err)-> console.log('Crashed',err))
pub.connect('alex2',->
console.log('Publishing movement_successful for',user_id)
pub.publish('movement_successful',JSON.stringify(
{
user_id:user_id,
room_name:room
}
));
)
publish_movement_failed = (user_id,room)->
console.log('Ready to publish failure')
pub = context.socket('PUB',{routing:'topic'});
pub.on('error',(err)-> console.log('Crashed',err))
pub.connect('alex2',->
console.log('Publishing movement_failed for',user_id)
pub.publish('movement_failed',JSON.stringify(
{
user_id:user_id,
room_name:room
}
));
)
handlers = {
'door_created': (message)->
console.log('door_created :',message)
connected_rooms.push([message.room_one_name, message.room_two_name])
'movement_successful': (message)->
console.log('movement_successful :', message)
users[message.user_id] = users[message.user_id] || {}
users[message.user_id].current_location = message.room_name
'user_intended_to_move' : (message,isReplay)->
if isReplay then return
console.log('user_intended_to_move :',message)
user = users[message.user_id]
if not user
console.log('\tuser does not exist')
return
location = user.current_location
for door in connected_rooms
if location in door and message.room_id in door
publish_movement_success(message.user_id,message.room_id)
return;
publish_movement_failed(message.user_id,message.room_id)
}
context.on('ready', ->
data_provider.getPreviousData( (data)->
for row in data
handlers[row.topic]?(row.content,true)
)
# console.log('\n****ready to listen for new stuff****\n')
Object.keys(handlers).forEach((topic_name)->
subscriber = context.socket('SUB',{routing:'topic'})
subscriber.connect(exchange_name,topic_name,->
console.log("#{topic_name} listener started")
subscriber.on('data',(string_message)->
handlers[topic_name](JSON.parse(string_message))
)
)
)
) | true | Array.prototype.last = ()->
return this[-1..][0]
data_provider = require('./pg_connection')
mq_server = 'amqp://PI:IP_ADDRESS:192.168.3.11END_PI:5672'
context = require('rabbit.js').createContext(mq_server);
exchange_name = 'alex2'
connected_rooms = []
users = {}
publish_movement_success = (user_id,room)->
console.log('Ready to publish success')
pub = context.socket('PUB',{routing:'topic'});
pub.on('error',(err)-> console.log('Crashed',err))
pub.connect('alex2',->
console.log('Publishing movement_successful for',user_id)
pub.publish('movement_successful',JSON.stringify(
{
user_id:user_id,
room_name:room
}
));
)
publish_movement_failed = (user_id,room)->
console.log('Ready to publish failure')
pub = context.socket('PUB',{routing:'topic'});
pub.on('error',(err)-> console.log('Crashed',err))
pub.connect('alex2',->
console.log('Publishing movement_failed for',user_id)
pub.publish('movement_failed',JSON.stringify(
{
user_id:user_id,
room_name:room
}
));
)
handlers = {
'door_created': (message)->
console.log('door_created :',message)
connected_rooms.push([message.room_one_name, message.room_two_name])
'movement_successful': (message)->
console.log('movement_successful :', message)
users[message.user_id] = users[message.user_id] || {}
users[message.user_id].current_location = message.room_name
'user_intended_to_move' : (message,isReplay)->
if isReplay then return
console.log('user_intended_to_move :',message)
user = users[message.user_id]
if not user
console.log('\tuser does not exist')
return
location = user.current_location
for door in connected_rooms
if location in door and message.room_id in door
publish_movement_success(message.user_id,message.room_id)
return;
publish_movement_failed(message.user_id,message.room_id)
}
context.on('ready', ->
data_provider.getPreviousData( (data)->
for row in data
handlers[row.topic]?(row.content,true)
)
# console.log('\n****ready to listen for new stuff****\n')
Object.keys(handlers).forEach((topic_name)->
subscriber = context.socket('SUB',{routing:'topic'})
subscriber.connect(exchange_name,topic_name,->
console.log("#{topic_name} listener started")
subscriber.on('data',(string_message)->
handlers[topic_name](JSON.parse(string_message))
)
)
)
) |
[
{
"context": "###*\n@license Sticky-kit v1.1.3 | MIT | Leaf Corcoran 2015 | http://leafo.net\n###\n\n$ = window.jQuery\n\nw",
"end": 53,
"score": 0.9993537664413452,
"start": 40,
"tag": "NAME",
"value": "Leaf Corcoran"
}
] | dist/assets/bower_components/sticky-kit/sticky-kit.coffee | pourabkarchaudhuri/supervised-data-tagger-dashboard | 0 | ###*
@license Sticky-kit v1.1.3 | MIT | Leaf Corcoran 2015 | http://leafo.net
###
$ = window.jQuery
win = $ window
$.fn.stick_in_parent = (opts={}) ->
{
sticky_class
inner_scrolling
recalc_every
parent: parent_selector
offset_top
spacer: manual_spacer
bottoming: enable_bottoming
} = opts
offset_top ?= 0
parent_selector ?= undefined
inner_scrolling ?= true
sticky_class ?= "is_stuck"
doc = $(document)
enable_bottoming = true unless enable_bottoming?
# we need this because jquery's version (along with css()) rounds everything
outer_width = (el) ->
if window.getComputedStyle
_el = el[0]
computed = window.getComputedStyle el[0]
w = parseFloat(computed.getPropertyValue("width")) + parseFloat(computed.getPropertyValue("margin-left")) + parseFloat(computed.getPropertyValue("margin-right"))
if computed.getPropertyValue("box-sizing") != "border-box"
w += parseFloat(computed.getPropertyValue("border-left-width")) + parseFloat(computed.getPropertyValue("border-right-width")) + parseFloat(computed.getPropertyValue("padding-left")) + parseFloat(computed.getPropertyValue("padding-right"))
w
else
el.outerWidth true
for elm in @
((elm, padding_bottom, parent_top, parent_height, top, height, el_float, detached) ->
return if elm.data "sticky_kit"
elm.data "sticky_kit", true
last_scroll_height = doc.height()
parent = elm.parent()
parent = parent.closest(parent_selector) if parent_selector?
throw "failed to find stick parent" unless parent.length
fixed = false
bottomed = false
spacer = if manual_spacer?
manual_spacer && elm.closest manual_spacer
else
$("<div />")
spacer.css('position', elm.css('position')) if spacer
recalc = ->
return if detached
last_scroll_height = doc.height()
border_top = parseInt parent.css("border-top-width"), 10
padding_top = parseInt parent.css("padding-top"), 10
padding_bottom = parseInt parent.css("padding-bottom"), 10
parent_top = parent.offset().top + border_top + padding_top
parent_height = parent.height()
if fixed
fixed = false
bottomed = false
unless manual_spacer?
elm.insertAfter(spacer)
spacer.detach()
elm.css({
position: ""
top: ""
width: ""
bottom: ""
}).removeClass(sticky_class)
restore = true
top = elm.offset().top - (parseInt(elm.css("margin-top"), 10) or 0) - offset_top
height = elm.outerHeight true
el_float = elm.css "float"
spacer.css({
width: outer_width elm
height: height
display: elm.css "display"
"vertical-align": elm.css "vertical-align"
"float": el_float
}) if spacer
if restore
tick()
recalc()
return if height == parent_height
last_pos = undefined
offset = offset_top
recalc_counter = recalc_every
tick = ->
return if detached
recalced = false
if recalc_counter?
recalc_counter -= 1
if recalc_counter <= 0
recalc_counter = recalc_every
recalc()
recalced = true
if !recalced && doc.height() != last_scroll_height
recalc()
recalced = true
scroll = win.scrollTop()
if last_pos?
delta = scroll - last_pos
last_pos = scroll
if fixed
if enable_bottoming
will_bottom = scroll + height + offset > parent_height + parent_top
# unbottom
if bottomed && !will_bottom
bottomed = false
elm.css({
position: "fixed"
bottom: ""
top: offset
}).trigger("sticky_kit:unbottom")
# unfixing
if scroll < top
fixed = false
offset = offset_top
unless manual_spacer?
if el_float == "left" || el_float == "right"
elm.insertAfter spacer
spacer.detach()
css = {
position: ""
width: ""
top: ""
}
elm.css(css).removeClass(sticky_class).trigger("sticky_kit:unstick")
# updated offset
if inner_scrolling
win_height = win.height()
if height + offset_top > win_height # bigger than viewport
unless bottomed
offset -= delta
offset = Math.max win_height - height, offset
offset = Math.min offset_top, offset
if fixed
elm.css {
top: offset + "px"
}
else
# fixing
if scroll > top
fixed = true
css = {
position: "fixed"
top: offset
}
css.width = if elm.css("box-sizing") == "border-box"
elm.outerWidth() + "px"
else
elm.width() + "px"
elm.css(css).addClass(sticky_class)
unless manual_spacer?
elm.after(spacer)
if el_float == "left" || el_float == "right"
spacer.append elm
elm.trigger("sticky_kit:stick")
# this is down here because we can fix and bottom in same step when
# scrolling huge
if fixed && enable_bottoming
will_bottom ?= scroll + height + offset > parent_height + parent_top
# bottomed
if !bottomed && will_bottom
# bottomed out
bottomed = true
if parent.css("position") == "static"
parent.css {
position: "relative"
}
elm.css({
position: "absolute"
bottom: padding_bottom
top: "auto"
}).trigger("sticky_kit:bottom")
recalc_and_tick = ->
recalc()
tick()
detach = ->
detached = true
win.off "touchmove", tick
win.off "scroll", tick
win.off "resize", recalc_and_tick
$(document.body).off "sticky_kit:recalc", recalc_and_tick
elm.off "sticky_kit:detach", detach
elm.removeData "sticky_kit"
elm.css {
position: ""
bottom: ""
top: ""
width: ""
}
parent.position "position", ""
if fixed
unless manual_spacer?
if el_float == "left" || el_float == "right"
elm.insertAfter spacer
spacer.remove()
elm.removeClass sticky_class
win.on "touchmove", tick
win.on "scroll", tick
win.on "resize", recalc_and_tick
$(document.body).on "sticky_kit:recalc", recalc_and_tick
elm.on "sticky_kit:detach", detach
setTimeout tick, 0
) $ elm
@
| 143287 | ###*
@license Sticky-kit v1.1.3 | MIT | <NAME> 2015 | http://leafo.net
###
$ = window.jQuery
win = $ window
$.fn.stick_in_parent = (opts={}) ->
{
sticky_class
inner_scrolling
recalc_every
parent: parent_selector
offset_top
spacer: manual_spacer
bottoming: enable_bottoming
} = opts
offset_top ?= 0
parent_selector ?= undefined
inner_scrolling ?= true
sticky_class ?= "is_stuck"
doc = $(document)
enable_bottoming = true unless enable_bottoming?
# we need this because jquery's version (along with css()) rounds everything
outer_width = (el) ->
if window.getComputedStyle
_el = el[0]
computed = window.getComputedStyle el[0]
w = parseFloat(computed.getPropertyValue("width")) + parseFloat(computed.getPropertyValue("margin-left")) + parseFloat(computed.getPropertyValue("margin-right"))
if computed.getPropertyValue("box-sizing") != "border-box"
w += parseFloat(computed.getPropertyValue("border-left-width")) + parseFloat(computed.getPropertyValue("border-right-width")) + parseFloat(computed.getPropertyValue("padding-left")) + parseFloat(computed.getPropertyValue("padding-right"))
w
else
el.outerWidth true
for elm in @
((elm, padding_bottom, parent_top, parent_height, top, height, el_float, detached) ->
return if elm.data "sticky_kit"
elm.data "sticky_kit", true
last_scroll_height = doc.height()
parent = elm.parent()
parent = parent.closest(parent_selector) if parent_selector?
throw "failed to find stick parent" unless parent.length
fixed = false
bottomed = false
spacer = if manual_spacer?
manual_spacer && elm.closest manual_spacer
else
$("<div />")
spacer.css('position', elm.css('position')) if spacer
recalc = ->
return if detached
last_scroll_height = doc.height()
border_top = parseInt parent.css("border-top-width"), 10
padding_top = parseInt parent.css("padding-top"), 10
padding_bottom = parseInt parent.css("padding-bottom"), 10
parent_top = parent.offset().top + border_top + padding_top
parent_height = parent.height()
if fixed
fixed = false
bottomed = false
unless manual_spacer?
elm.insertAfter(spacer)
spacer.detach()
elm.css({
position: ""
top: ""
width: ""
bottom: ""
}).removeClass(sticky_class)
restore = true
top = elm.offset().top - (parseInt(elm.css("margin-top"), 10) or 0) - offset_top
height = elm.outerHeight true
el_float = elm.css "float"
spacer.css({
width: outer_width elm
height: height
display: elm.css "display"
"vertical-align": elm.css "vertical-align"
"float": el_float
}) if spacer
if restore
tick()
recalc()
return if height == parent_height
last_pos = undefined
offset = offset_top
recalc_counter = recalc_every
tick = ->
return if detached
recalced = false
if recalc_counter?
recalc_counter -= 1
if recalc_counter <= 0
recalc_counter = recalc_every
recalc()
recalced = true
if !recalced && doc.height() != last_scroll_height
recalc()
recalced = true
scroll = win.scrollTop()
if last_pos?
delta = scroll - last_pos
last_pos = scroll
if fixed
if enable_bottoming
will_bottom = scroll + height + offset > parent_height + parent_top
# unbottom
if bottomed && !will_bottom
bottomed = false
elm.css({
position: "fixed"
bottom: ""
top: offset
}).trigger("sticky_kit:unbottom")
# unfixing
if scroll < top
fixed = false
offset = offset_top
unless manual_spacer?
if el_float == "left" || el_float == "right"
elm.insertAfter spacer
spacer.detach()
css = {
position: ""
width: ""
top: ""
}
elm.css(css).removeClass(sticky_class).trigger("sticky_kit:unstick")
# updated offset
if inner_scrolling
win_height = win.height()
if height + offset_top > win_height # bigger than viewport
unless bottomed
offset -= delta
offset = Math.max win_height - height, offset
offset = Math.min offset_top, offset
if fixed
elm.css {
top: offset + "px"
}
else
# fixing
if scroll > top
fixed = true
css = {
position: "fixed"
top: offset
}
css.width = if elm.css("box-sizing") == "border-box"
elm.outerWidth() + "px"
else
elm.width() + "px"
elm.css(css).addClass(sticky_class)
unless manual_spacer?
elm.after(spacer)
if el_float == "left" || el_float == "right"
spacer.append elm
elm.trigger("sticky_kit:stick")
# this is down here because we can fix and bottom in same step when
# scrolling huge
if fixed && enable_bottoming
will_bottom ?= scroll + height + offset > parent_height + parent_top
# bottomed
if !bottomed && will_bottom
# bottomed out
bottomed = true
if parent.css("position") == "static"
parent.css {
position: "relative"
}
elm.css({
position: "absolute"
bottom: padding_bottom
top: "auto"
}).trigger("sticky_kit:bottom")
recalc_and_tick = ->
recalc()
tick()
detach = ->
detached = true
win.off "touchmove", tick
win.off "scroll", tick
win.off "resize", recalc_and_tick
$(document.body).off "sticky_kit:recalc", recalc_and_tick
elm.off "sticky_kit:detach", detach
elm.removeData "sticky_kit"
elm.css {
position: ""
bottom: ""
top: ""
width: ""
}
parent.position "position", ""
if fixed
unless manual_spacer?
if el_float == "left" || el_float == "right"
elm.insertAfter spacer
spacer.remove()
elm.removeClass sticky_class
win.on "touchmove", tick
win.on "scroll", tick
win.on "resize", recalc_and_tick
$(document.body).on "sticky_kit:recalc", recalc_and_tick
elm.on "sticky_kit:detach", detach
setTimeout tick, 0
) $ elm
@
| true | ###*
@license Sticky-kit v1.1.3 | MIT | PI:NAME:<NAME>END_PI 2015 | http://leafo.net
###
$ = window.jQuery
win = $ window
$.fn.stick_in_parent = (opts={}) ->
{
sticky_class
inner_scrolling
recalc_every
parent: parent_selector
offset_top
spacer: manual_spacer
bottoming: enable_bottoming
} = opts
offset_top ?= 0
parent_selector ?= undefined
inner_scrolling ?= true
sticky_class ?= "is_stuck"
doc = $(document)
enable_bottoming = true unless enable_bottoming?
# we need this because jquery's version (along with css()) rounds everything
outer_width = (el) ->
if window.getComputedStyle
_el = el[0]
computed = window.getComputedStyle el[0]
w = parseFloat(computed.getPropertyValue("width")) + parseFloat(computed.getPropertyValue("margin-left")) + parseFloat(computed.getPropertyValue("margin-right"))
if computed.getPropertyValue("box-sizing") != "border-box"
w += parseFloat(computed.getPropertyValue("border-left-width")) + parseFloat(computed.getPropertyValue("border-right-width")) + parseFloat(computed.getPropertyValue("padding-left")) + parseFloat(computed.getPropertyValue("padding-right"))
w
else
el.outerWidth true
for elm in @
((elm, padding_bottom, parent_top, parent_height, top, height, el_float, detached) ->
return if elm.data "sticky_kit"
elm.data "sticky_kit", true
last_scroll_height = doc.height()
parent = elm.parent()
parent = parent.closest(parent_selector) if parent_selector?
throw "failed to find stick parent" unless parent.length
fixed = false
bottomed = false
spacer = if manual_spacer?
manual_spacer && elm.closest manual_spacer
else
$("<div />")
spacer.css('position', elm.css('position')) if spacer
recalc = ->
return if detached
last_scroll_height = doc.height()
border_top = parseInt parent.css("border-top-width"), 10
padding_top = parseInt parent.css("padding-top"), 10
padding_bottom = parseInt parent.css("padding-bottom"), 10
parent_top = parent.offset().top + border_top + padding_top
parent_height = parent.height()
if fixed
fixed = false
bottomed = false
unless manual_spacer?
elm.insertAfter(spacer)
spacer.detach()
elm.css({
position: ""
top: ""
width: ""
bottom: ""
}).removeClass(sticky_class)
restore = true
top = elm.offset().top - (parseInt(elm.css("margin-top"), 10) or 0) - offset_top
height = elm.outerHeight true
el_float = elm.css "float"
spacer.css({
width: outer_width elm
height: height
display: elm.css "display"
"vertical-align": elm.css "vertical-align"
"float": el_float
}) if spacer
if restore
tick()
recalc()
return if height == parent_height
last_pos = undefined
offset = offset_top
recalc_counter = recalc_every
tick = ->
return if detached
recalced = false
if recalc_counter?
recalc_counter -= 1
if recalc_counter <= 0
recalc_counter = recalc_every
recalc()
recalced = true
if !recalced && doc.height() != last_scroll_height
recalc()
recalced = true
scroll = win.scrollTop()
if last_pos?
delta = scroll - last_pos
last_pos = scroll
if fixed
if enable_bottoming
will_bottom = scroll + height + offset > parent_height + parent_top
# unbottom
if bottomed && !will_bottom
bottomed = false
elm.css({
position: "fixed"
bottom: ""
top: offset
}).trigger("sticky_kit:unbottom")
# unfixing
if scroll < top
fixed = false
offset = offset_top
unless manual_spacer?
if el_float == "left" || el_float == "right"
elm.insertAfter spacer
spacer.detach()
css = {
position: ""
width: ""
top: ""
}
elm.css(css).removeClass(sticky_class).trigger("sticky_kit:unstick")
# updated offset
if inner_scrolling
win_height = win.height()
if height + offset_top > win_height # bigger than viewport
unless bottomed
offset -= delta
offset = Math.max win_height - height, offset
offset = Math.min offset_top, offset
if fixed
elm.css {
top: offset + "px"
}
else
# fixing
if scroll > top
fixed = true
css = {
position: "fixed"
top: offset
}
css.width = if elm.css("box-sizing") == "border-box"
elm.outerWidth() + "px"
else
elm.width() + "px"
elm.css(css).addClass(sticky_class)
unless manual_spacer?
elm.after(spacer)
if el_float == "left" || el_float == "right"
spacer.append elm
elm.trigger("sticky_kit:stick")
# this is down here because we can fix and bottom in same step when
# scrolling huge
if fixed && enable_bottoming
will_bottom ?= scroll + height + offset > parent_height + parent_top
# bottomed
if !bottomed && will_bottom
# bottomed out
bottomed = true
if parent.css("position") == "static"
parent.css {
position: "relative"
}
elm.css({
position: "absolute"
bottom: padding_bottom
top: "auto"
}).trigger("sticky_kit:bottom")
recalc_and_tick = ->
recalc()
tick()
detach = ->
detached = true
win.off "touchmove", tick
win.off "scroll", tick
win.off "resize", recalc_and_tick
$(document.body).off "sticky_kit:recalc", recalc_and_tick
elm.off "sticky_kit:detach", detach
elm.removeData "sticky_kit"
elm.css {
position: ""
bottom: ""
top: ""
width: ""
}
parent.position "position", ""
if fixed
unless manual_spacer?
if el_float == "left" || el_float == "right"
elm.insertAfter spacer
spacer.remove()
elm.removeClass sticky_class
win.on "touchmove", tick
win.on "scroll", tick
win.on "resize", recalc_and_tick
$(document.body).on "sticky_kit:recalc", recalc_and_tick
elm.on "sticky_kit:detach", detach
setTimeout tick, 0
) $ elm
@
|
[
{
"context": "fierStackingShadowsBonusDamage\"\n\n\t@modifierName: \"Shadow Creep Bonus Damage\"\n\n\tactiveInHand: false\n\tactive",
"end": 267,
"score": 0.5755980610847473,
"start": 261,
"tag": "NAME",
"value": "Shadow"
},
{
"context": "adowsBonusDamage\"\n\n\t@modifierName: \"Shad... | app/sdk/modifiers/modifierStackingShadowsBonusDamage.coffee | willroberts/duelyst | 5 | Modifier = require './modifier'
ModifierStackingShadows = require './modifierStackingShadows'
class ModifierStackingShadowsBonusDamage extends Modifier
type: "ModifierStackingShadowsBonusDamage"
@type: "ModifierStackingShadowsBonusDamage"
@modifierName: "Shadow Creep Bonus Damage"
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
@isHiddenToUI: true
fxResource: ["FX.Modifiers.ModifierShadowCreep"]
@createContextObject: (flatBonus=0, multiplierBonus=1) ->
contextObject = super()
contextObject.bonusDamageAmount = flatBonus
contextObject.multiplierBonusDamage = multiplierBonus
return contextObject
getFlatBonusDamage: () ->
return @bonusDamageAmount
getMultiplierBonusDamage: () ->
return @multiplierBonusDamage
onActivate: () ->
super()
# flush cached atk attribute for this card
@getCard().flushCachedAttribute("atk")
onDeactivate: () ->
super()
# flush cached atk attribute for this card
@getCard().flushCachedAttribute("atk")
module.exports = ModifierStackingShadowsBonusDamage
| 159779 | Modifier = require './modifier'
ModifierStackingShadows = require './modifierStackingShadows'
class ModifierStackingShadowsBonusDamage extends Modifier
type: "ModifierStackingShadowsBonusDamage"
@type: "ModifierStackingShadowsBonusDamage"
@modifierName: "<NAME> Creep B<NAME> Damage"
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
@isHiddenToUI: true
fxResource: ["FX.Modifiers.ModifierShadowCreep"]
@createContextObject: (flatBonus=0, multiplierBonus=1) ->
contextObject = super()
contextObject.bonusDamageAmount = flatBonus
contextObject.multiplierBonusDamage = multiplierBonus
return contextObject
getFlatBonusDamage: () ->
return @bonusDamageAmount
getMultiplierBonusDamage: () ->
return @multiplierBonusDamage
onActivate: () ->
super()
# flush cached atk attribute for this card
@getCard().flushCachedAttribute("atk")
onDeactivate: () ->
super()
# flush cached atk attribute for this card
@getCard().flushCachedAttribute("atk")
module.exports = ModifierStackingShadowsBonusDamage
| true | Modifier = require './modifier'
ModifierStackingShadows = require './modifierStackingShadows'
class ModifierStackingShadowsBonusDamage extends Modifier
type: "ModifierStackingShadowsBonusDamage"
@type: "ModifierStackingShadowsBonusDamage"
@modifierName: "PI:NAME:<NAME>END_PI Creep BPI:NAME:<NAME>END_PI Damage"
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
@isHiddenToUI: true
fxResource: ["FX.Modifiers.ModifierShadowCreep"]
@createContextObject: (flatBonus=0, multiplierBonus=1) ->
contextObject = super()
contextObject.bonusDamageAmount = flatBonus
contextObject.multiplierBonusDamage = multiplierBonus
return contextObject
getFlatBonusDamage: () ->
return @bonusDamageAmount
getMultiplierBonusDamage: () ->
return @multiplierBonusDamage
onActivate: () ->
super()
# flush cached atk attribute for this card
@getCard().flushCachedAttribute("atk")
onDeactivate: () ->
super()
# flush cached atk attribute for this card
@getCard().flushCachedAttribute("atk")
module.exports = ModifierStackingShadowsBonusDamage
|
[
{
"context": "if logged_in\r\n Accounts.createUser email: \"you@example.com\", password: \"bob\", ->\r\n if as_admin\r\n ",
"end": 375,
"score": 0.999915599822998,
"start": 360,
"tag": "EMAIL",
"value": "you@example.com"
},
{
"context": "s.createUser email: \"you@ex... | packages/houston/test/test_app/tests/jasmine/client/integration/Login.coffee | reillyisawesome/Nectar | 3 | eventually = (condition, cb) ->
poll = setInterval(->
if condition()
clearInterval poll
cb()
, 200)
setup = ({logged_in, as_admin, other_admin}, cb) ->
run_actual_test = cb
Meteor.call "test/clear_users", (err) ->
expect(err).toBeUndefined()
_setup_user = ->
if logged_in
Accounts.createUser email: "you@example.com", password: "bob", ->
if as_admin
Houston._call 'make_admin', Meteor.userId(), (err) ->
expect(err).toBeUndefined()
run_actual_test()
else
run_actual_test()
else
run_actual_test()
if other_admin
Accounts.createUser email: "other@example.com", password: "bob", ->
Houston._call 'make_admin', Meteor.userId(), (err) ->
expect(err).toBeUndefined()
Meteor.logout (err) ->
expect(err).toBeUndefined()
_setup_user()
else
_setup_user()
describe "Can't access Meteor unless logged in", ->
it "not logged in, no admin? offer to crete admin",
(done) ->
setup {logged_in: false, as_admin: false, other_admin: false}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
$signin_form = $('#houston-sign-in-form')
expect($signin_form[0]).not.toBeUndefined()
expect($signin_form.html()).toMatch(/Create an admin account/)
done()
it "not logged in, and there's an admin? You should log in to admin!",
(done) ->
setup {logged_in: false, as_admin: false, other_admin: true}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
$signin_form = $('#houston-sign-in-form')
expect($signin_form[0]).not.toBeUndefined()
expect($signin_form.html()).toMatch(/Log In/)
done()
it "logged in, no admin? should offer to Claim Admin",
(done) ->
setup {logged_in: true, as_admin: false, other_admin: false}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
expect($('#become-houston-admin').length).toEqual(1)
expect($('.form-heading').first().html()).toMatch(/You are not an Admin./)
done()
it "tells you to go away if an admin exists",
(done) ->
setup {logged_in: true, as_admin: false, other_admin: true}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
expect($('#become-houston-admin').length).toEqual(0)
expect($('.form-heading').first().html()).toMatch(/You are not an Admin./)
done()
it "logged in as admin? come see the page", ->
setup {logged_in: true, as_admin: true, other_admin: false}, ->
Houston._go "home"
expect($('.houston').html()).toMatch(/Meteor Admin Panel/)
| 76337 | eventually = (condition, cb) ->
poll = setInterval(->
if condition()
clearInterval poll
cb()
, 200)
setup = ({logged_in, as_admin, other_admin}, cb) ->
run_actual_test = cb
Meteor.call "test/clear_users", (err) ->
expect(err).toBeUndefined()
_setup_user = ->
if logged_in
Accounts.createUser email: "<EMAIL>", password: "<PASSWORD>", ->
if as_admin
Houston._call 'make_admin', Meteor.userId(), (err) ->
expect(err).toBeUndefined()
run_actual_test()
else
run_actual_test()
else
run_actual_test()
if other_admin
Accounts.createUser email: "<EMAIL>", password: "<PASSWORD>", ->
Houston._call 'make_admin', Meteor.userId(), (err) ->
expect(err).toBeUndefined()
Meteor.logout (err) ->
expect(err).toBeUndefined()
_setup_user()
else
_setup_user()
describe "Can't access Meteor unless logged in", ->
it "not logged in, no admin? offer to crete admin",
(done) ->
setup {logged_in: false, as_admin: false, other_admin: false}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
$signin_form = $('#houston-sign-in-form')
expect($signin_form[0]).not.toBeUndefined()
expect($signin_form.html()).toMatch(/Create an admin account/)
done()
it "not logged in, and there's an admin? You should log in to admin!",
(done) ->
setup {logged_in: false, as_admin: false, other_admin: true}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
$signin_form = $('#houston-sign-in-form')
expect($signin_form[0]).not.toBeUndefined()
expect($signin_form.html()).toMatch(/Log In/)
done()
it "logged in, no admin? should offer to Claim Admin",
(done) ->
setup {logged_in: true, as_admin: false, other_admin: false}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
expect($('#become-houston-admin').length).toEqual(1)
expect($('.form-heading').first().html()).toMatch(/You are not an Admin./)
done()
it "tells you to go away if an admin exists",
(done) ->
setup {logged_in: true, as_admin: false, other_admin: true}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
expect($('#become-houston-admin').length).toEqual(0)
expect($('.form-heading').first().html()).toMatch(/You are not an Admin./)
done()
it "logged in as admin? come see the page", ->
setup {logged_in: true, as_admin: true, other_admin: false}, ->
Houston._go "home"
expect($('.houston').html()).toMatch(/Meteor Admin Panel/)
| true | eventually = (condition, cb) ->
poll = setInterval(->
if condition()
clearInterval poll
cb()
, 200)
setup = ({logged_in, as_admin, other_admin}, cb) ->
run_actual_test = cb
Meteor.call "test/clear_users", (err) ->
expect(err).toBeUndefined()
_setup_user = ->
if logged_in
Accounts.createUser email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI", ->
if as_admin
Houston._call 'make_admin', Meteor.userId(), (err) ->
expect(err).toBeUndefined()
run_actual_test()
else
run_actual_test()
else
run_actual_test()
if other_admin
Accounts.createUser email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI", ->
Houston._call 'make_admin', Meteor.userId(), (err) ->
expect(err).toBeUndefined()
Meteor.logout (err) ->
expect(err).toBeUndefined()
_setup_user()
else
_setup_user()
describe "Can't access Meteor unless logged in", ->
it "not logged in, no admin? offer to crete admin",
(done) ->
setup {logged_in: false, as_admin: false, other_admin: false}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
$signin_form = $('#houston-sign-in-form')
expect($signin_form[0]).not.toBeUndefined()
expect($signin_form.html()).toMatch(/Create an admin account/)
done()
it "not logged in, and there's an admin? You should log in to admin!",
(done) ->
setup {logged_in: false, as_admin: false, other_admin: true}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
$signin_form = $('#houston-sign-in-form')
expect($signin_form[0]).not.toBeUndefined()
expect($signin_form.html()).toMatch(/Log In/)
done()
it "logged in, no admin? should offer to Claim Admin",
(done) ->
setup {logged_in: true, as_admin: false, other_admin: false}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
expect($('#become-houston-admin').length).toEqual(1)
expect($('.form-heading').first().html()).toMatch(/You are not an Admin./)
done()
it "tells you to go away if an admin exists",
(done) ->
setup {logged_in: true, as_admin: false, other_admin: true}, ->
Houston._go "home"
url_changed = -> window.location.pathname is "/admin/login"
eventually url_changed, ->
expect($('#become-houston-admin').length).toEqual(0)
expect($('.form-heading').first().html()).toMatch(/You are not an Admin./)
done()
it "logged in as admin? come see the page", ->
setup {logged_in: true, as_admin: true, other_admin: false}, ->
Houston._go "home"
expect($('.houston').html()).toMatch(/Meteor Admin Panel/)
|
[
{
"context": " collection = new Collection([\n person('john')\n person('fred')\n ])\n\n it \"",
"end": 12298,
"score": 0.9984258413314819,
"start": 12294,
"tag": "NAME",
"value": "john"
},
{
"context": "tion([\n person('john')\n person... | public/js/plugins/onionjs-master/test/collection_spec.coffee | kemiedon/android_project | 6 | Collection = requirejs('onion/collection')
eventEmitter = requirejs('onion/event_emitter')
extend = requirejs('onion/utils/extend')
describe "Collection", ->
describe "array-like properties", ->
collection = null
beforeEach ->
collection = new Collection([
{number: 4}
{number: 27}
])
it "implements forEach", ->
result = []
collection.forEach (obj, i)->
result.push [obj, i]
expect( result ).to.eql([
[{number: 4}, 0]
[{number: 27}, 1]
])
it "implements map", ->
result = collection.map (obj, i) ->
[obj, i]
expect( result ).to.eql([
[{number: 4}, 0]
[{number: 27}, 1]
])
it "implements filter", ->
result = collection.filter (obj, i) ->
obj.number == 27 && i == 1
expect( result ).to.eql([
{number: 27}
])
it "implements reduce", ->
result = collection.reduce (str, obj, i) ->
str += "#{obj.number}-#{i} "
str
, ""
expect( result ).to.eql("4-0 27-1 ")
it "implements slice", ->
result = collection.slice(1, 2)
expect( result ).to.eql([
{number: 27}
])
it "implements join", ->
collection = new Collection([3,5,7])
expect( collection.join(',') ).to.equal("3,5,7")
it "implements concat", ->
expect( collection.concat([32]) ).to.eql([
{number: 4}
{number: 27}
32
])
it "implements some", ->
expect( collection.some (i) -> i.number == 4 ).to.be.true
it "implements every", ->
expect( collection.every (i) -> i.number == 4 ).to.be.false
describe "count", ->
it "returns the length", ->
collection = new Collection([2, 4])
expect( collection.count() ).to.equal(2)
describe "at", ->
collection = null
beforeEach ->
collection = new Collection([2, 4, 19])
it "returns the nth value", ->
expect( collection.at(1) ).to.equal(4)
it "returns values from the end", ->
expect( collection.at(-1) ).to.equal(19)
it "returns undefined if non-existent", ->
expect( collection.at(17) ).to.be.undefined
describe "add", ->
collection = null
beforeEach ->
collection = new Collection([6, 22, 44])
it "defaults to a push when the collection has no order", ->
collection.add(35)
expect( collection.toArray() ).to.eql([6, 22, 44, 35])
it "emits an add event", ->
x = null
collection.on 'add', (item) -> x = item
collection.add(44)
expect( x ).to.eql(44)
it "emits a change event", ->
expect ->
collection.add(33)
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event", ->
expect ->
collection.add(33)
.toEmitOn(collection, 'itemsAdded', [33])
describe "addMany", ->
collection = null
beforeEach ->
collection = new Collection([33, 76], orderBy: (a, b) -> Collection.compare(a, b))
it "adds many, in the correct order", ->
collection.addMany([56, 44])
expect( collection.toArray() ).to.eql([33, 44, 56, 76])
it "emits an addMany event", ->
expect ->
collection.addMany([56, 44])
.toEmitOn(collection, 'addMany', [56, 44])
it "should work with a collection", ->
miniCollection = new Collection([56, 44])
expect ->
collection.addMany(miniCollection)
.toEmitOn(collection, 'addMany', [56, 44])
expect( collection.toArray() ).to.eql([33, 44, 56, 76])
it "emits a change event", ->
expect ->
collection.addMany([33])
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event", ->
expect ->
collection.addMany([22, 33])
.toEmitOn(collection, 'itemsAdded', [22, 33])
describe "remove", ->
collection = null
beforeEach ->
collection = new Collection([4, 4, 5])
it "removes the first element that matches", ->
result = collection.remove(4)
expect( result ).to.eql(true)
expect( collection.toArray() ).to.eql([4, 5])
it "does nothing if the element doesn't exist", ->
result = collection.remove(36)
expect( result ).to.eql(false)
expect( collection.toArray() ).to.eql([4, 4, 5])
it "emits a remove event", ->
collection.add(95)
expect ->
collection.remove(95)
.toEmitOn(collection, 'remove', 95, 3)
it "emits a change event", ->
expect ->
collection.remove(4)
.toEmitOn(collection, 'change', collection)
it "doesn't emit any events if not removed", ->
expect ->
collection.remove(400)
.not.toEmitOn(collection)
it "emits an itemsRemoved event", ->
collection.add(7)
expect ->
collection.remove(7)
.toEmitOn(collection, 'itemsRemoved', [7])
describe "removeMany", ->
collection = null
beforeEach ->
collection = new Collection([4, 4, 5, 6, 7])
it "removes all elements that match", ->
result = collection.removeMany([4, 6])
expect( collection.toArray() ).to.eql([5, 7])
it "emits a removeMany event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'removeMany', [4, 4, 6])
it "works with a collection", ->
miniCollection = new Collection([6, 4])
expect ->
collection.removeMany(miniCollection)
.toEmitOn(collection, 'removeMany', [6, 4, 4])
expect( collection.toArray() ).to.eql([5, 7])
it "emits a change event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'change', collection)
it "doesn't emit any events if nothing is removed", ->
expect ->
collection.removeMany([9, 10])
.not.toEmitOn(collection)
it "emits an itemsRemoved event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'itemsRemoved', [4, 4, 6])
describe "using 'isEqualTo'", ->
isEqualTo = (other) -> @name == other.name
newObject = (name) ->
name: name
isEqualTo: isEqualTo
collection = null
sparky = null
otherSparky = null
bilf = null
otherBilf = null
beforeEach ->
sparky = newObject('Sparky')
otherSparky = newObject('Sparky')
bilf = newObject('Bilf')
otherBilf = newObject('Bilf')
collection = new Collection([bilf, sparky, bilf])
it "removes using 'isEqualTo' if implemented on the objects", ->
collection.remove(otherSparky)
expect( collection.toArray() ).to.eql([bilf, bilf])
it "emits the remove event with the actual removed object (not the matched one)", ->
removedItem = null
collection.on 'remove', (item) -> removedItem = item
collection.remove(otherSparky)
expect( removedItem == sparky ).to.eql(true)
it "removes many using 'isEqualTo' if implemented on the objects", ->
collection.removeMany([otherBilf])
expect( collection.toArray() ).to.eql([sparky])
it "emits the remove many event with the actual removed objects (not the matched ones)", ->
removedItems = null
collection.on 'removeMany', (items) -> removedItems = items
collection.removeMany([otherBilf])
expect( removedItems.length ).to.eql(2)
expect( removedItems[0] == bilf ).to.eql(true)
expect( removedItems[1] == bilf ).to.eql(true)
describe "ordering", ->
collection = null
beforeEach ->
collection = new Collection([21, 44, 5])
it "orders the items", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
expect( collection.toArray() ).to.eql([5, 21, 44])
it "adds items in the correct position", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
collection.add(36)
expect( collection.toArray() ).to.eql([5, 21, 36, 44])
it "returns the insertion index", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
expect( collection.add(36) ).to.eql(2)
it "allows passing the order as an arg", ->
collection = new Collection([21, 44, 5], orderBy: (a, b) -> Collection.compare(a, b))
expect( collection.toArray() ).to.eql([5, 21, 44])
describe "isEmpty", ->
it "is empty if there are no items", ->
collection = new Collection([])
expect( collection.isEmpty() ).to.eql(true)
it "is not empty if there are items", ->
collection = new Collection([1])
expect( collection.isEmpty() ).to.eql(false)
describe "set", ->
collection = null
beforeEach ->
collection = new Collection([7, 65])
it "resets all elements", ->
collection.set([4,2,3])
expect( collection.toArray() ).to.eql([4,2,3])
it "accepts another collection", ->
collection2 = new Collection([4,2,3])
collection.set(collection2)
expect( collection.toArray() ).to.eql([4,2,3])
it "orders according to its own order", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
collection.set([4,2,3])
expect( collection.toArray() ).to.eql([2,3,4])
it "emits a set event", ->
newItems = null
collection.on 'set', (a) -> newItems = a
collection.set([4,5])
expect( newItems ).to.eql([4,5])
it "emits a change event", ->
expect ->
collection.set([4])
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event for new items (even items that existed in the old collection)", ->
expect ->
collection.set([2, 65])
.toEmitOn(collection, 'itemsAdded', [2, 65])
it "emits an itemsRemoved event for old items (even items that exist in the new collection)", ->
expect ->
collection.set([2, 65])
.toEmitOn(collection, 'itemsRemoved', [7, 65])
describe "clone", ->
collection = null
cloned = null
beforeEach ->
collection = new Collection([3, 6, 8], orderBy: -> 0)
cloned = collection.clone()
it "copies the items", ->
expect( collection.toArray() ).to.eql( cloned.toArray() )
it "copies the comparator function", ->
expect( collection.__comparator__ ).to.eql( cloned.__comparator__ )
it "doesn't effect the original", ->
cloned.add(42)
expect( collection.toArray() ).to.eql( [3, 6, 8] )
expect( cloned.toArray() ).to.eql( [3, 6, 8, 42] )
describe "contains", ->
collection = null
beforeEach ->
collection = new Collection()
it "returns false if it doesn't contain an item", ->
expect( collection.contains('dice') ).to.eql(false)
it "returns true if it does contain an item", ->
collection.add('dice')
expect( collection.contains('dice') ).to.eql(true)
describe "onItem", ->
item = null
callback = ->
beforeEach ->
item =
on: sinon.spy()
off: sinon.spy()
it "subscribes to items currently in the collection", ->
collection = new Collection([item])
collection.onItem('change', callback)
assert.isTrue( item.on.calledWith('change', callback) )
it "subscribes to new items", ->
collection = new Collection()
collection.onItem('change', callback)
collection.add(item)
assert.isTrue( item.on.calledWith('change', callback) )
it "unsubscribes when items are removed", ->
collection = new Collection([item])
collection.onItem('change', callback)
assert.isFalse( item.off.called )
collection.remove(item)
assert.isTrue( item.off.calledWith('change', callback) )
it "does nothing if the item doesn't respond to on", ->
collection = new Collection([4])
collection.onItem('change', callback)
collection.add(5)
describe "indexFor", ->
collection = null
describe "indexOf functionality", ->
beforeEach ->
collection = new Collection([6,3,2])
it "returns the index of an item", ->
expect( collection.indexFor(3) ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexFor(33) ).to.eql(-1)
describe "using isEqualTo", ->
person = (name) ->
name: name
isEqualTo: (other) ->
other.name == @name
beforeEach ->
collection = new Collection([
person('john')
person('fred')
])
it "returns the correct index", ->
expect( collection.indexFor(person('fred')) ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexFor(345) ).to.eql(-1)
describe "indexWhere", ->
collection = null
beforeEach ->
collection = new Collection(['john', 'fred', 'egg'])
it "returns the correct index", ->
expect( collection.indexWhere (name) -> name == 'fred' ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexWhere (name) -> name == 'blurgh' ).to.eql(-1)
describe "special positions", ->
collection = null
beforeEach ->
collection = new Collection([4, 25, 235])
it "returns the first", ->
expect( collection.first() ).to.eql(4)
it "returns the last", ->
expect( collection.last() ).to.eql(235)
it "returns undefined if it doesn't exist", ->
collection = new Collection()
expect( collection.first() ).to.eql(undefined)
expect( collection.last() ).to.eql(undefined)
describe "filtering", ->
newModel = (attributes) -> {attrs: -> attributes}
collection = null
[m1, m2, m3, m4] = []
beforeEach ->
m1 = newModel(kung: 1, fu: 1)
m2 = newModel(kung: 1, fu: 2)
m3 = newModel(kung: 2, fu: 1)
m4 = newModel(kung: 1, fu: 1)
collection = new Collection [m1, m2, m3, m4]
describe "where", ->
it "returns an array of ones that exactly match", ->
expect( collection.where(kung: 1, fu: 1) ).to.eql([m1, m4])
it "ignores items that don't have an 'attrs' method", ->
collection.add(4)
expect( collection.where(kung: 1, fu: 1) ).to.eql([m1, m4])
describe "removeWhere", ->
it "remove ones that exactly match", ->
collection.removeWhere(kung: 1, fu: 1)
expect( collection.toArray() ).to.eql([m2, m3])
it "ignores items that don't have an 'attrs' method", ->
collection.add(4)
collection.removeWhere(kung: 1, fu: 1)
expect( collection.toArray() ).to.eql([m2, m3, 4])
describe "uuid", ->
it "has a uuid", ->
expect( new Collection().uuid() ).to.match(/^[\w-]+$/)
describe "pluck", ->
collection = null
beforeEach ->
collection = new Collection()
it "plucks an attribute", ->
collection.set [
{name: 'wing'}
{name: 'nut'}
]
expect( collection.pluck('name') ).to.eql(['wing', 'nut'])
it "calls if a function", ->
collection.set [
{name: -> 'wing'}
{name: -> 'nut'}
]
expect( collection.pluck('name') ).to.eql(['wing', 'nut'])
| 35708 | Collection = requirejs('onion/collection')
eventEmitter = requirejs('onion/event_emitter')
extend = requirejs('onion/utils/extend')
describe "Collection", ->
describe "array-like properties", ->
collection = null
beforeEach ->
collection = new Collection([
{number: 4}
{number: 27}
])
it "implements forEach", ->
result = []
collection.forEach (obj, i)->
result.push [obj, i]
expect( result ).to.eql([
[{number: 4}, 0]
[{number: 27}, 1]
])
it "implements map", ->
result = collection.map (obj, i) ->
[obj, i]
expect( result ).to.eql([
[{number: 4}, 0]
[{number: 27}, 1]
])
it "implements filter", ->
result = collection.filter (obj, i) ->
obj.number == 27 && i == 1
expect( result ).to.eql([
{number: 27}
])
it "implements reduce", ->
result = collection.reduce (str, obj, i) ->
str += "#{obj.number}-#{i} "
str
, ""
expect( result ).to.eql("4-0 27-1 ")
it "implements slice", ->
result = collection.slice(1, 2)
expect( result ).to.eql([
{number: 27}
])
it "implements join", ->
collection = new Collection([3,5,7])
expect( collection.join(',') ).to.equal("3,5,7")
it "implements concat", ->
expect( collection.concat([32]) ).to.eql([
{number: 4}
{number: 27}
32
])
it "implements some", ->
expect( collection.some (i) -> i.number == 4 ).to.be.true
it "implements every", ->
expect( collection.every (i) -> i.number == 4 ).to.be.false
describe "count", ->
it "returns the length", ->
collection = new Collection([2, 4])
expect( collection.count() ).to.equal(2)
describe "at", ->
collection = null
beforeEach ->
collection = new Collection([2, 4, 19])
it "returns the nth value", ->
expect( collection.at(1) ).to.equal(4)
it "returns values from the end", ->
expect( collection.at(-1) ).to.equal(19)
it "returns undefined if non-existent", ->
expect( collection.at(17) ).to.be.undefined
describe "add", ->
collection = null
beforeEach ->
collection = new Collection([6, 22, 44])
it "defaults to a push when the collection has no order", ->
collection.add(35)
expect( collection.toArray() ).to.eql([6, 22, 44, 35])
it "emits an add event", ->
x = null
collection.on 'add', (item) -> x = item
collection.add(44)
expect( x ).to.eql(44)
it "emits a change event", ->
expect ->
collection.add(33)
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event", ->
expect ->
collection.add(33)
.toEmitOn(collection, 'itemsAdded', [33])
describe "addMany", ->
collection = null
beforeEach ->
collection = new Collection([33, 76], orderBy: (a, b) -> Collection.compare(a, b))
it "adds many, in the correct order", ->
collection.addMany([56, 44])
expect( collection.toArray() ).to.eql([33, 44, 56, 76])
it "emits an addMany event", ->
expect ->
collection.addMany([56, 44])
.toEmitOn(collection, 'addMany', [56, 44])
it "should work with a collection", ->
miniCollection = new Collection([56, 44])
expect ->
collection.addMany(miniCollection)
.toEmitOn(collection, 'addMany', [56, 44])
expect( collection.toArray() ).to.eql([33, 44, 56, 76])
it "emits a change event", ->
expect ->
collection.addMany([33])
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event", ->
expect ->
collection.addMany([22, 33])
.toEmitOn(collection, 'itemsAdded', [22, 33])
describe "remove", ->
collection = null
beforeEach ->
collection = new Collection([4, 4, 5])
it "removes the first element that matches", ->
result = collection.remove(4)
expect( result ).to.eql(true)
expect( collection.toArray() ).to.eql([4, 5])
it "does nothing if the element doesn't exist", ->
result = collection.remove(36)
expect( result ).to.eql(false)
expect( collection.toArray() ).to.eql([4, 4, 5])
it "emits a remove event", ->
collection.add(95)
expect ->
collection.remove(95)
.toEmitOn(collection, 'remove', 95, 3)
it "emits a change event", ->
expect ->
collection.remove(4)
.toEmitOn(collection, 'change', collection)
it "doesn't emit any events if not removed", ->
expect ->
collection.remove(400)
.not.toEmitOn(collection)
it "emits an itemsRemoved event", ->
collection.add(7)
expect ->
collection.remove(7)
.toEmitOn(collection, 'itemsRemoved', [7])
describe "removeMany", ->
collection = null
beforeEach ->
collection = new Collection([4, 4, 5, 6, 7])
it "removes all elements that match", ->
result = collection.removeMany([4, 6])
expect( collection.toArray() ).to.eql([5, 7])
it "emits a removeMany event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'removeMany', [4, 4, 6])
it "works with a collection", ->
miniCollection = new Collection([6, 4])
expect ->
collection.removeMany(miniCollection)
.toEmitOn(collection, 'removeMany', [6, 4, 4])
expect( collection.toArray() ).to.eql([5, 7])
it "emits a change event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'change', collection)
it "doesn't emit any events if nothing is removed", ->
expect ->
collection.removeMany([9, 10])
.not.toEmitOn(collection)
it "emits an itemsRemoved event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'itemsRemoved', [4, 4, 6])
describe "using 'isEqualTo'", ->
isEqualTo = (other) -> @name == other.name
newObject = (name) ->
name: name
isEqualTo: isEqualTo
collection = null
sparky = null
otherSparky = null
bilf = null
otherBilf = null
beforeEach ->
sparky = newObject('Sparky')
otherSparky = newObject('Sparky')
bilf = newObject('Bilf')
otherBilf = newObject('Bilf')
collection = new Collection([bilf, sparky, bilf])
it "removes using 'isEqualTo' if implemented on the objects", ->
collection.remove(otherSparky)
expect( collection.toArray() ).to.eql([bilf, bilf])
it "emits the remove event with the actual removed object (not the matched one)", ->
removedItem = null
collection.on 'remove', (item) -> removedItem = item
collection.remove(otherSparky)
expect( removedItem == sparky ).to.eql(true)
it "removes many using 'isEqualTo' if implemented on the objects", ->
collection.removeMany([otherBilf])
expect( collection.toArray() ).to.eql([sparky])
it "emits the remove many event with the actual removed objects (not the matched ones)", ->
removedItems = null
collection.on 'removeMany', (items) -> removedItems = items
collection.removeMany([otherBilf])
expect( removedItems.length ).to.eql(2)
expect( removedItems[0] == bilf ).to.eql(true)
expect( removedItems[1] == bilf ).to.eql(true)
describe "ordering", ->
collection = null
beforeEach ->
collection = new Collection([21, 44, 5])
it "orders the items", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
expect( collection.toArray() ).to.eql([5, 21, 44])
it "adds items in the correct position", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
collection.add(36)
expect( collection.toArray() ).to.eql([5, 21, 36, 44])
it "returns the insertion index", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
expect( collection.add(36) ).to.eql(2)
it "allows passing the order as an arg", ->
collection = new Collection([21, 44, 5], orderBy: (a, b) -> Collection.compare(a, b))
expect( collection.toArray() ).to.eql([5, 21, 44])
describe "isEmpty", ->
it "is empty if there are no items", ->
collection = new Collection([])
expect( collection.isEmpty() ).to.eql(true)
it "is not empty if there are items", ->
collection = new Collection([1])
expect( collection.isEmpty() ).to.eql(false)
describe "set", ->
collection = null
beforeEach ->
collection = new Collection([7, 65])
it "resets all elements", ->
collection.set([4,2,3])
expect( collection.toArray() ).to.eql([4,2,3])
it "accepts another collection", ->
collection2 = new Collection([4,2,3])
collection.set(collection2)
expect( collection.toArray() ).to.eql([4,2,3])
it "orders according to its own order", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
collection.set([4,2,3])
expect( collection.toArray() ).to.eql([2,3,4])
it "emits a set event", ->
newItems = null
collection.on 'set', (a) -> newItems = a
collection.set([4,5])
expect( newItems ).to.eql([4,5])
it "emits a change event", ->
expect ->
collection.set([4])
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event for new items (even items that existed in the old collection)", ->
expect ->
collection.set([2, 65])
.toEmitOn(collection, 'itemsAdded', [2, 65])
it "emits an itemsRemoved event for old items (even items that exist in the new collection)", ->
expect ->
collection.set([2, 65])
.toEmitOn(collection, 'itemsRemoved', [7, 65])
describe "clone", ->
collection = null
cloned = null
beforeEach ->
collection = new Collection([3, 6, 8], orderBy: -> 0)
cloned = collection.clone()
it "copies the items", ->
expect( collection.toArray() ).to.eql( cloned.toArray() )
it "copies the comparator function", ->
expect( collection.__comparator__ ).to.eql( cloned.__comparator__ )
it "doesn't effect the original", ->
cloned.add(42)
expect( collection.toArray() ).to.eql( [3, 6, 8] )
expect( cloned.toArray() ).to.eql( [3, 6, 8, 42] )
describe "contains", ->
collection = null
beforeEach ->
collection = new Collection()
it "returns false if it doesn't contain an item", ->
expect( collection.contains('dice') ).to.eql(false)
it "returns true if it does contain an item", ->
collection.add('dice')
expect( collection.contains('dice') ).to.eql(true)
describe "onItem", ->
item = null
callback = ->
beforeEach ->
item =
on: sinon.spy()
off: sinon.spy()
it "subscribes to items currently in the collection", ->
collection = new Collection([item])
collection.onItem('change', callback)
assert.isTrue( item.on.calledWith('change', callback) )
it "subscribes to new items", ->
collection = new Collection()
collection.onItem('change', callback)
collection.add(item)
assert.isTrue( item.on.calledWith('change', callback) )
it "unsubscribes when items are removed", ->
collection = new Collection([item])
collection.onItem('change', callback)
assert.isFalse( item.off.called )
collection.remove(item)
assert.isTrue( item.off.calledWith('change', callback) )
it "does nothing if the item doesn't respond to on", ->
collection = new Collection([4])
collection.onItem('change', callback)
collection.add(5)
describe "indexFor", ->
collection = null
describe "indexOf functionality", ->
beforeEach ->
collection = new Collection([6,3,2])
it "returns the index of an item", ->
expect( collection.indexFor(3) ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexFor(33) ).to.eql(-1)
describe "using isEqualTo", ->
person = (name) ->
name: name
isEqualTo: (other) ->
other.name == @name
beforeEach ->
collection = new Collection([
person('<NAME>')
person('<NAME>')
])
it "returns the correct index", ->
expect( collection.indexFor(person('<NAME>')) ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexFor(345) ).to.eql(-1)
describe "indexWhere", ->
collection = null
beforeEach ->
collection = new Collection(['<NAME>', '<NAME>', 'egg'])
it "returns the correct index", ->
expect( collection.indexWhere (name) -> name == '<NAME>' ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexWhere (name) -> name == 'blurgh' ).to.eql(-1)
describe "special positions", ->
collection = null
beforeEach ->
collection = new Collection([4, 25, 235])
it "returns the first", ->
expect( collection.first() ).to.eql(4)
it "returns the last", ->
expect( collection.last() ).to.eql(235)
it "returns undefined if it doesn't exist", ->
collection = new Collection()
expect( collection.first() ).to.eql(undefined)
expect( collection.last() ).to.eql(undefined)
describe "filtering", ->
newModel = (attributes) -> {attrs: -> attributes}
collection = null
[m1, m2, m3, m4] = []
beforeEach ->
m1 = newModel(kung: 1, fu: 1)
m2 = newModel(kung: 1, fu: 2)
m3 = newModel(kung: 2, fu: 1)
m4 = newModel(kung: 1, fu: 1)
collection = new Collection [m1, m2, m3, m4]
describe "where", ->
it "returns an array of ones that exactly match", ->
expect( collection.where(kung: 1, fu: 1) ).to.eql([m1, m4])
it "ignores items that don't have an 'attrs' method", ->
collection.add(4)
expect( collection.where(kung: 1, fu: 1) ).to.eql([m1, m4])
describe "removeWhere", ->
it "remove ones that exactly match", ->
collection.removeWhere(kung: 1, fu: 1)
expect( collection.toArray() ).to.eql([m2, m3])
it "ignores items that don't have an 'attrs' method", ->
collection.add(4)
collection.removeWhere(kung: 1, fu: 1)
expect( collection.toArray() ).to.eql([m2, m3, 4])
describe "uuid", ->
it "has a uuid", ->
expect( new Collection().uuid() ).to.match(/^[\w-]+$/)
describe "pluck", ->
collection = null
beforeEach ->
collection = new Collection()
it "plucks an attribute", ->
collection.set [
{name: 'wing'}
{name: 'nut'}
]
expect( collection.pluck('name') ).to.eql(['wing', 'nut'])
it "calls if a function", ->
collection.set [
{name: -> 'wing'}
{name: -> 'nut'}
]
expect( collection.pluck('name') ).to.eql(['wing', 'nut'])
| true | Collection = requirejs('onion/collection')
eventEmitter = requirejs('onion/event_emitter')
extend = requirejs('onion/utils/extend')
describe "Collection", ->
describe "array-like properties", ->
collection = null
beforeEach ->
collection = new Collection([
{number: 4}
{number: 27}
])
it "implements forEach", ->
result = []
collection.forEach (obj, i)->
result.push [obj, i]
expect( result ).to.eql([
[{number: 4}, 0]
[{number: 27}, 1]
])
it "implements map", ->
result = collection.map (obj, i) ->
[obj, i]
expect( result ).to.eql([
[{number: 4}, 0]
[{number: 27}, 1]
])
it "implements filter", ->
result = collection.filter (obj, i) ->
obj.number == 27 && i == 1
expect( result ).to.eql([
{number: 27}
])
it "implements reduce", ->
result = collection.reduce (str, obj, i) ->
str += "#{obj.number}-#{i} "
str
, ""
expect( result ).to.eql("4-0 27-1 ")
it "implements slice", ->
result = collection.slice(1, 2)
expect( result ).to.eql([
{number: 27}
])
it "implements join", ->
collection = new Collection([3,5,7])
expect( collection.join(',') ).to.equal("3,5,7")
it "implements concat", ->
expect( collection.concat([32]) ).to.eql([
{number: 4}
{number: 27}
32
])
it "implements some", ->
expect( collection.some (i) -> i.number == 4 ).to.be.true
it "implements every", ->
expect( collection.every (i) -> i.number == 4 ).to.be.false
describe "count", ->
it "returns the length", ->
collection = new Collection([2, 4])
expect( collection.count() ).to.equal(2)
describe "at", ->
collection = null
beforeEach ->
collection = new Collection([2, 4, 19])
it "returns the nth value", ->
expect( collection.at(1) ).to.equal(4)
it "returns values from the end", ->
expect( collection.at(-1) ).to.equal(19)
it "returns undefined if non-existent", ->
expect( collection.at(17) ).to.be.undefined
describe "add", ->
collection = null
beforeEach ->
collection = new Collection([6, 22, 44])
it "defaults to a push when the collection has no order", ->
collection.add(35)
expect( collection.toArray() ).to.eql([6, 22, 44, 35])
it "emits an add event", ->
x = null
collection.on 'add', (item) -> x = item
collection.add(44)
expect( x ).to.eql(44)
it "emits a change event", ->
expect ->
collection.add(33)
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event", ->
expect ->
collection.add(33)
.toEmitOn(collection, 'itemsAdded', [33])
describe "addMany", ->
collection = null
beforeEach ->
collection = new Collection([33, 76], orderBy: (a, b) -> Collection.compare(a, b))
it "adds many, in the correct order", ->
collection.addMany([56, 44])
expect( collection.toArray() ).to.eql([33, 44, 56, 76])
it "emits an addMany event", ->
expect ->
collection.addMany([56, 44])
.toEmitOn(collection, 'addMany', [56, 44])
it "should work with a collection", ->
miniCollection = new Collection([56, 44])
expect ->
collection.addMany(miniCollection)
.toEmitOn(collection, 'addMany', [56, 44])
expect( collection.toArray() ).to.eql([33, 44, 56, 76])
it "emits a change event", ->
expect ->
collection.addMany([33])
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event", ->
expect ->
collection.addMany([22, 33])
.toEmitOn(collection, 'itemsAdded', [22, 33])
describe "remove", ->
collection = null
beforeEach ->
collection = new Collection([4, 4, 5])
it "removes the first element that matches", ->
result = collection.remove(4)
expect( result ).to.eql(true)
expect( collection.toArray() ).to.eql([4, 5])
it "does nothing if the element doesn't exist", ->
result = collection.remove(36)
expect( result ).to.eql(false)
expect( collection.toArray() ).to.eql([4, 4, 5])
it "emits a remove event", ->
collection.add(95)
expect ->
collection.remove(95)
.toEmitOn(collection, 'remove', 95, 3)
it "emits a change event", ->
expect ->
collection.remove(4)
.toEmitOn(collection, 'change', collection)
it "doesn't emit any events if not removed", ->
expect ->
collection.remove(400)
.not.toEmitOn(collection)
it "emits an itemsRemoved event", ->
collection.add(7)
expect ->
collection.remove(7)
.toEmitOn(collection, 'itemsRemoved', [7])
describe "removeMany", ->
collection = null
beforeEach ->
collection = new Collection([4, 4, 5, 6, 7])
it "removes all elements that match", ->
result = collection.removeMany([4, 6])
expect( collection.toArray() ).to.eql([5, 7])
it "emits a removeMany event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'removeMany', [4, 4, 6])
it "works with a collection", ->
miniCollection = new Collection([6, 4])
expect ->
collection.removeMany(miniCollection)
.toEmitOn(collection, 'removeMany', [6, 4, 4])
expect( collection.toArray() ).to.eql([5, 7])
it "emits a change event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'change', collection)
it "doesn't emit any events if nothing is removed", ->
expect ->
collection.removeMany([9, 10])
.not.toEmitOn(collection)
it "emits an itemsRemoved event", ->
expect ->
collection.removeMany([4, 6])
.toEmitOn(collection, 'itemsRemoved', [4, 4, 6])
describe "using 'isEqualTo'", ->
isEqualTo = (other) -> @name == other.name
newObject = (name) ->
name: name
isEqualTo: isEqualTo
collection = null
sparky = null
otherSparky = null
bilf = null
otherBilf = null
beforeEach ->
sparky = newObject('Sparky')
otherSparky = newObject('Sparky')
bilf = newObject('Bilf')
otherBilf = newObject('Bilf')
collection = new Collection([bilf, sparky, bilf])
it "removes using 'isEqualTo' if implemented on the objects", ->
collection.remove(otherSparky)
expect( collection.toArray() ).to.eql([bilf, bilf])
it "emits the remove event with the actual removed object (not the matched one)", ->
removedItem = null
collection.on 'remove', (item) -> removedItem = item
collection.remove(otherSparky)
expect( removedItem == sparky ).to.eql(true)
it "removes many using 'isEqualTo' if implemented on the objects", ->
collection.removeMany([otherBilf])
expect( collection.toArray() ).to.eql([sparky])
it "emits the remove many event with the actual removed objects (not the matched ones)", ->
removedItems = null
collection.on 'removeMany', (items) -> removedItems = items
collection.removeMany([otherBilf])
expect( removedItems.length ).to.eql(2)
expect( removedItems[0] == bilf ).to.eql(true)
expect( removedItems[1] == bilf ).to.eql(true)
describe "ordering", ->
collection = null
beforeEach ->
collection = new Collection([21, 44, 5])
it "orders the items", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
expect( collection.toArray() ).to.eql([5, 21, 44])
it "adds items in the correct position", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
collection.add(36)
expect( collection.toArray() ).to.eql([5, 21, 36, 44])
it "returns the insertion index", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
expect( collection.add(36) ).to.eql(2)
it "allows passing the order as an arg", ->
collection = new Collection([21, 44, 5], orderBy: (a, b) -> Collection.compare(a, b))
expect( collection.toArray() ).to.eql([5, 21, 44])
describe "isEmpty", ->
it "is empty if there are no items", ->
collection = new Collection([])
expect( collection.isEmpty() ).to.eql(true)
it "is not empty if there are items", ->
collection = new Collection([1])
expect( collection.isEmpty() ).to.eql(false)
describe "set", ->
collection = null
beforeEach ->
collection = new Collection([7, 65])
it "resets all elements", ->
collection.set([4,2,3])
expect( collection.toArray() ).to.eql([4,2,3])
it "accepts another collection", ->
collection2 = new Collection([4,2,3])
collection.set(collection2)
expect( collection.toArray() ).to.eql([4,2,3])
it "orders according to its own order", ->
collection.orderBy (a, b) -> Collection.compare(a, b)
collection.set([4,2,3])
expect( collection.toArray() ).to.eql([2,3,4])
it "emits a set event", ->
newItems = null
collection.on 'set', (a) -> newItems = a
collection.set([4,5])
expect( newItems ).to.eql([4,5])
it "emits a change event", ->
expect ->
collection.set([4])
.toEmitOn(collection, 'change', collection)
it "emits an itemsAdded event for new items (even items that existed in the old collection)", ->
expect ->
collection.set([2, 65])
.toEmitOn(collection, 'itemsAdded', [2, 65])
it "emits an itemsRemoved event for old items (even items that exist in the new collection)", ->
expect ->
collection.set([2, 65])
.toEmitOn(collection, 'itemsRemoved', [7, 65])
describe "clone", ->
collection = null
cloned = null
beforeEach ->
collection = new Collection([3, 6, 8], orderBy: -> 0)
cloned = collection.clone()
it "copies the items", ->
expect( collection.toArray() ).to.eql( cloned.toArray() )
it "copies the comparator function", ->
expect( collection.__comparator__ ).to.eql( cloned.__comparator__ )
it "doesn't effect the original", ->
cloned.add(42)
expect( collection.toArray() ).to.eql( [3, 6, 8] )
expect( cloned.toArray() ).to.eql( [3, 6, 8, 42] )
describe "contains", ->
collection = null
beforeEach ->
collection = new Collection()
it "returns false if it doesn't contain an item", ->
expect( collection.contains('dice') ).to.eql(false)
it "returns true if it does contain an item", ->
collection.add('dice')
expect( collection.contains('dice') ).to.eql(true)
describe "onItem", ->
item = null
callback = ->
beforeEach ->
item =
on: sinon.spy()
off: sinon.spy()
it "subscribes to items currently in the collection", ->
collection = new Collection([item])
collection.onItem('change', callback)
assert.isTrue( item.on.calledWith('change', callback) )
it "subscribes to new items", ->
collection = new Collection()
collection.onItem('change', callback)
collection.add(item)
assert.isTrue( item.on.calledWith('change', callback) )
it "unsubscribes when items are removed", ->
collection = new Collection([item])
collection.onItem('change', callback)
assert.isFalse( item.off.called )
collection.remove(item)
assert.isTrue( item.off.calledWith('change', callback) )
it "does nothing if the item doesn't respond to on", ->
collection = new Collection([4])
collection.onItem('change', callback)
collection.add(5)
describe "indexFor", ->
collection = null
describe "indexOf functionality", ->
beforeEach ->
collection = new Collection([6,3,2])
it "returns the index of an item", ->
expect( collection.indexFor(3) ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexFor(33) ).to.eql(-1)
describe "using isEqualTo", ->
person = (name) ->
name: name
isEqualTo: (other) ->
other.name == @name
beforeEach ->
collection = new Collection([
person('PI:NAME:<NAME>END_PI')
person('PI:NAME:<NAME>END_PI')
])
it "returns the correct index", ->
expect( collection.indexFor(person('PI:NAME:<NAME>END_PI')) ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexFor(345) ).to.eql(-1)
describe "indexWhere", ->
collection = null
beforeEach ->
collection = new Collection(['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'egg'])
it "returns the correct index", ->
expect( collection.indexWhere (name) -> name == 'PI:NAME:<NAME>END_PI' ).to.eql(1)
it "returns -1 if not found", ->
expect( collection.indexWhere (name) -> name == 'blurgh' ).to.eql(-1)
describe "special positions", ->
collection = null
beforeEach ->
collection = new Collection([4, 25, 235])
it "returns the first", ->
expect( collection.first() ).to.eql(4)
it "returns the last", ->
expect( collection.last() ).to.eql(235)
it "returns undefined if it doesn't exist", ->
collection = new Collection()
expect( collection.first() ).to.eql(undefined)
expect( collection.last() ).to.eql(undefined)
describe "filtering", ->
newModel = (attributes) -> {attrs: -> attributes}
collection = null
[m1, m2, m3, m4] = []
beforeEach ->
m1 = newModel(kung: 1, fu: 1)
m2 = newModel(kung: 1, fu: 2)
m3 = newModel(kung: 2, fu: 1)
m4 = newModel(kung: 1, fu: 1)
collection = new Collection [m1, m2, m3, m4]
describe "where", ->
it "returns an array of ones that exactly match", ->
expect( collection.where(kung: 1, fu: 1) ).to.eql([m1, m4])
it "ignores items that don't have an 'attrs' method", ->
collection.add(4)
expect( collection.where(kung: 1, fu: 1) ).to.eql([m1, m4])
describe "removeWhere", ->
it "remove ones that exactly match", ->
collection.removeWhere(kung: 1, fu: 1)
expect( collection.toArray() ).to.eql([m2, m3])
it "ignores items that don't have an 'attrs' method", ->
collection.add(4)
collection.removeWhere(kung: 1, fu: 1)
expect( collection.toArray() ).to.eql([m2, m3, 4])
describe "uuid", ->
it "has a uuid", ->
expect( new Collection().uuid() ).to.match(/^[\w-]+$/)
describe "pluck", ->
collection = null
beforeEach ->
collection = new Collection()
it "plucks an attribute", ->
collection.set [
{name: 'wing'}
{name: 'nut'}
]
expect( collection.pluck('name') ).to.eql(['wing', 'nut'])
it "calls if a function", ->
collection.set [
{name: -> 'wing'}
{name: -> 'nut'}
]
expect( collection.pluck('name') ).to.eql(['wing', 'nut'])
|
[
{
"context": "\n duration = duration_in_seconds*1000\n key = \"#{workspace_id}|#{user_id}\"\n ignore_until = Date.now()+duration\n @ignor",
"end": 2048,
"score": 0.9992135167121887,
"start": 2020,
"tag": "KEY",
"value": "\"#{workspace_id}|#{user_id}\""
},
{
"context": " s... | team-one/bmf/lib/base-bot.coffee | BroadSoft-Xtended/sample-apps | 2 | #-------------------------------------------------------------------------------
# Base Imports
#-------------------------------------------------------------------------------
LogUtil = require('inote-util').LogUtil
Util = require('inote-util').Util
WebSocket = require 'ws'
EventEmitter = require 'events'
IntellinoteClient = require("intellinote-client").IntellinoteClient
https = require 'https'
#-------------------------------------------------------------------------------
# "Abstract" base class to extend when creating Team-One bots.
#
# Provides convenience methods to simplify bot creation and some default
# behaviors like heartbeat (ping) and set-presence-to-online timers.
#
# Subclasses should implement `on_rtm_message`, probably invoking
# `reply` or `send_payload` at some point within it.
#
# Subclasses may hook into other methods to handle additional message types
# or provide other specialized behavior. See comments below.
#
# Note that `log`, `debug` and `error` methods are provided for
# configuration-aware logging. Subclasses should typically use that rather
# than `console.log` or `console.error` for most logging purposes.
#
# See `./basic/basic-bot.coffee` for a tiny example of extending this class
# to implement a bot.
#
# See the [README file](../README.md) for a long-winded description of how to
# extend this class.
#
class BaseBot extends EventEmitter
constructor:(options)->
@config = @_configure(options)
@_register_internal_listeners()
@_maybe_register_sigint_handler(@config)
@_configure_logging(@config)
@ignoring = {}
@ping_count = 0
if @config.start_protocol is "http"
https = require 'http'
# ignore the specified user within the specified workspace for
# duration seconds.
ignore:(workspace_id, user_id, duration_in_seconds)=>
duration_in_seconds ?= @config.default_ignore_duration_seconds
duration = duration_in_seconds*1000
key = "#{workspace_id}|#{user_id}"
ignore_until = Date.now()+duration
@ignoring[key] = ignore_until
stop_ignoring = ()=>
if @ignoring[key] is ignore_until
delete @ignoring[key]
setTimeout(stop,duration)
# stop ignoring the specified user within the specified
# workspace, even if the previously defined duration has
# not elapsed.
stop_ignoring:(workspace_id, user_id)=>
key = "#{workspace_id}|#{user_id}"
delete @ignoring[key]
# returns `true` if we should ignore the specified payload,
# `false` otherwise.
should_ignore:(payload)=>
if payload.type in ["message","user_typing"]
key = "#{payload.workspace_id}|#{payload.user}"
else if payload.type is "note"
key = "#{payload.workspace_id}|#{payload.note?.creator?.user_id ? payload.previous_note?.creator?.user_id}"
if key?
ignore_until = @ignoring[key]
if ignore_until?
if ignore_until >= Date.now()
return true
else
delete @ignoring[key]
return false
else
return false
else
return false
# The REST client (`rest_client`) is automatically initialized in `launch_bot`,
# but you can use this method to exert more control over the initialization
# or to init and use the REST client before `launch_bot` is called.
init_rest_client:(api_key,base_url,debug)=>
# if a config map is passed as the first parameter rather than an api key,
# use that instaed
if api_key? and typeof api_key is "object" and (api_key.access_token? or api_key.api_key?) and not base_url? and not debug?
config = api_key
if config.api_key and not config.access_token
config.access_token = config.api_key
delete config.api_key
else
client_config = {
access_token: api_key
base_url: base_url ? "#{@config.start_protocol}://#{@config.start_host}:#{@config.start_port}/rest/v2"
debug: debug ? false
}
@rest_client = new IntellinoteClient(client_config)
# Connect to the RTM API with the given `api_key` (string) and
# `filters` (string or array of strings). Once launched the
# `@on_rtm_message` method will be invoked every time a
# `message` payload is received from the RTM API.
launch_bot:(api_key, filters)=>
@log @Cg "Launching bot."
@debug "Fetching WSS URL."
unless @rest_client?
@init_rest_client(api_key)
@get_wss_url api_key, filters, (err, url)=>
if err?
@error "while fetching WSS URL:", err
@error "can't establish WSS connection. Exiting"
process.exit(2)
else
@debug "Fetched WSS URL:", url
@debug @Cg "Opening websocket."
@ws = new WebSocket(url)
@ws.on "open", ()=>
@emit "ws/open"
@ws.on "close", (code, reason)=>
@emit "ws/status", code, reason
@ws.on "error", (err)=>
@emit "ws/error", err
@ws.on "message", (data, flags)=>
@emit "ws/message", data,flags
# Hits the `/rest/v2/rtms/start` endpoint to obtain a WSS URL
# that can be used to initiate an RTM session.
get_wss_url:(api_key,filters,callback)=>
filters ?= []
if typeof filters is 'string'
filters = [filters]
filters.push("event_type=message_added")
filters.push("from_me=false")
full_path = "#{@config.start_path}?#{filters.join('&')}"
options = {
method: "GET"
host: @config.start_host
path: full_path
port: @config.start_port
headers: {
Authorization: "Bearer #{api_key}"
}
}
handler = (response)->
unless /^2[0-9]{2}$/.test "#{response?.statusCode}"
callback new Error("Expected 2xx-series status code but found #{response?.statusCode}.")
else
body = ""
response.on "data", (chunk)->
body += chunk
response.on "end", ()->
try
json = JSON.parse(body)
callback(null, json.href)
catch e
callback e
https.request(options, handler).end()
# Invoked (via `@launch_bot`) when the websocket is first connected.
on_ws_open:()=>
@log @Cg "Websocket connection established."
# Invoked (via `@launch_bot`) when the websocket is closed.
on_ws_close:(code,reason)=>
process.nextTick ()=> # allow other event listeners to run
@log "Websocket connection closed (code=#{code},reason=#{reason}). exiting."
@ws = null
process.exit 0
# Invoked (via `@launch_bot`) when an websocket error is encountered.
on_ws_error:(err)=>
@error "from websocket:",err
# Invoked (via `@launch_bot`) when an websocket message is receieved.
# Invokes `@on_hello`, `@on_ping`, @on_rtm_message`, etc. based on the
# contents of the message.
on_ws_message:(data,flags)=>
json = null
try
json = JSON.parse(data)
catch e
# ignored
(if json?.type is "message" then @log else @debug) @CM("Received via websocket:"),data
if json?
if @should_ignore json
@debug "Ignoring:",json
else
switch json.type
when "hello"
@emit "rtm/hello", json, flags
when "goodbye"
@emit "rtm/goodbye", json, flags
when "pong"
@emit "rtm/pong", json, flags
when "message"
@emit "rtm/message", json, flags
when "user_typing"
@emit "rtm/user_typing", json, flags
when "note"
@emit "rtm/note", json, flags
when "rest/response"
@emit "rtm/rest/response", json, flags
# Invoked (via `@on_ws_message`) when a `message` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_message:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `note` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_note:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `user_type` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_user_typing:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `rest/response` payload is delivered.
on_rtm_rest_response:(json,flags)=>
if json.reply_to is @put_presence_id
@put_presence_id = null
@debug """
Presence set to #{@config.presence_value}. \
Round-trip latency #{@_format_duration(@put_presence_sent)}. \
Repeating in #{@_format_duration(0,@config.presence_wait_millis)}.
"""
# Invoked (via `@on_ws_message`) when the `hello` payload is delivered.
on_rtm_hello:(json,flags)=>
@log @CG "RTM session started."
if @config.fetch_screen_name
@fetch_screen_name()
if @config.ping_wait_millis
@send_ping()
if @config.presence_wait_millis
@put_presence()
setInterval(@put_presence,@config.presence_wait_millis)
# Invoked (via `@on_ws_message`) when the `pong` payload is delivered.
# Logs the event then sets a timer to send the next `ping`
on_rtm_pong:(json,flags)=>
if @config.ping_wait_millis
if json?.sent?
latency_str = " Round-trip latency #{@_format_duration(json.sent)}."
@debug """
Got pong response.#{latency_str} \
Repeating in #{@_format_duration(0,@config.ping_wait_millis)}.
"""
setTimeout((()=>@send_ping()),@config.ping_wait_millis)
# Invoked (via `@on_ws_message`) when the `goodbye` payload is delivered.
on_rtm_goodbye:(json,flags)=>
@log @CR "The server said \"goodbye\" so I'm shutting down."
try
@ws?.close?()
@ws = null
catch e
# ignored
process.exit 0
# Updates my presence status by invoking a REST method thru the web socket.
# TODO consider doing this via @rest_client instead?
put_presence:()=>
if @ws?
payload = {
type: "rest/request"
method: "PUT"
path: @config.presence_path
body: {"presence":@config.presence_value}
id: Util.uuid(null,true)
}
@put_presence_id = payload.id
@put_presence_sent = Date.now()
try
@send_payload payload
catch err
@error "while posting presence:", payload, err
# send a chat message containing `message` to a workspace or chat.
# - `reply_to` - the original payload we are responding to
# - `message` - the text of the message to send
# - `options` - an optional map of options.
# recognized options include:
# - `@mention` - auto (default), true, false (also recognized as `at_mention`)
reply:(reply_to, message, options)=>
reply_to ?= {}
options ?= {}
message ?= ""
if reply_to.screen_name?
if Util.truthy_string( options["@mention"] ? options["at_mention"] )
message = "@#{reply_to.screen_name} #{message}"
else if Util.falsey_string( options["@mention"] ? options["at_mention"] )
message = message
else unless reply_to.workspace_1on1
message = "@#{reply_to.screen_name} #{message}"
payload = {
type : "message"
org_id : reply_to.org_id
workspace_id : reply_to.workspace_id
text : message
}
@send_payload payload
send_typing:(org_id, workspace_id)=>
# allow `org_id` to be a payload-like object
if not workspace_id? and org_id?.org_id? and org_id?.workspace_id?
workspace_id = org_id.workspace_id
org_id = org_id.org_id
payload = {
type: "typing"
org_id: org_id
workspace_id: workspace_id
}
@send_payload(payload)
# publish the given payload object to the web socket (then log it)
send_payload:(payload)=>
log = (if payload?.type is "message" then @log else @debug)
if payload? and typeof payload isnt "string"
payload = JSON.stringify(payload)
log(@CB("Sending RTM payload via websocket:"), payload)
@ws.send payload
# Assuming @my_screen_name is populated, searches @my_screen_name
# in `text` and replaces it with `replace_with` (defaults to `" "`).
# when `replace_globally` is `true` (the default) all instances of
# the screen name are replaced, otherwise only the first instance
# is replaced.
#
# See `fetch_screen_name` and the `fetch_screen_name` configuration
# parameter for more details.
replace_my_screen_name:(text, replace_with=" ", replace_globally=true)=>
replace_with ?= " "
if text?
if replace_globally and @my_screen_name_re_g?
text = text.replace(@my_screen_name_re_g, replace_with)
else if @my_screen_name_re
text = text.replace(@my_screen_name_re, replace_with)
return text
# Use the (non-tunnelled) REST client to fetch the specified
# user's profile.
# - `id` - optional identifier for the user to fetch, which can be user_id,
# email address or the string `-`, indicating that the profile of
# the _current_ (bot) user should be fetched; defualts to `-`.
# - `callback` - callback method with the signature `(err, json)`
# (where `json` contains the user info).
#
get_user:(id,callback)=>
if typeof id is 'function' and not callback?
callback = id
id = null
id ?= "-"
if callback? # don't bother to make the call if the caller is not going to accept the data
@debug "Using REST client to call GET /user/#{id}"
@rest_client.get_user "-", (err, json, response, body)=>
@debug "REST client to call to GET /user/#{id} yielded",err, response?.statusCode, JSON.stringify(json)
if err?
@error "Error during rest_client.get_user", err
callback(err, json, response, body)
else
@warn "get_user call ignored because no callback method was provided."
fetch_screen_name:(callback)=>
@get_user "-", (err, json, response, body)=>
if err?
if callback?
callback err
else
@warn "get_user yielded an error in fetch_screen_name but no callback was provided.", err
else unless json?.screen_name?
@warn "fetch_screen_name failed to return an object with a 'screen_name' attribute."
callback? null, null
else
@my_user_id = json.user_id
@my_screen_name = json.screen_name
@my_screen_name_re = new RegExp("@#{@my_screen_name} ?")
@my_screen_name_re_g = new RegExp("@#{@my_screen_name} ?","g")
callback? null, @my_screen_name
# posts a `ping` payload to the websocket
send_ping:()=>
@send_payload {
n:@ping_count++
sent: Date.now()
type:"ping"
}
# log the given message unless QUIET is set
log:(message...)=>
unless @config.quiet
# LogUtil.tplog("\x1b[0;37m#{@botname}\x1b[1;37m",message...,"\x1b[0m")
LogUtil.tplog("#{@botname}",message...)
# log the given message if DEBUG is set
debug:(message...)=>
if @config.debug
LogUtil.tplog("#{@botname}",message...)
# log the given message to STDERR
error:(message...)=>
LogUtil.tperr("#{@botname}",@CR("ERROR"),message...)
# log the given message to STDERR
warn:(message...)=>
LogUtil.tperr("#{@botname}",@CY("WARNNIG"),message...)
# utility method for formatting a duration in millliseconds as seconds
_format_duration:(millis,now)=>
now ?= Date.now()
if millis?
val = "#{Math.round((now-millis)/100)/10}"
unless /\./.test val
val = "#{val}.0s"
else
val = "#{val}s"
return val
else
return null
_maybe_register_sigint_handler:(options)=>
options ?= {}
unless Util.falsey_string(options.sigint)
process.on 'SIGINT', ()=>
if @ws?
try
@log @Cr "Got interrupt signal (Ctrl-C). Sending goodbye payload."
@send_payload({type:"goodbye"})
setTimeout((()->process.exit()),6000)
catch err
# ignored
process.exit(1)
else
process.exit()
_register_internal_listeners:()=>
for event in ["open","error","close","message"]
@on "ws/#{event}", @["on_ws_#{event}"]
for event in ["message","user_typing","note","rest/response","hello","pong","goodbye"]
@on "rtm/#{event}", @["on_rtm_#{event.replace /\//g,'_'}"]
_configure_logging:(options)=>
options ?= {}
if options.botname?
@botname = "[#{options.botname}]"
else
@botname = ""
unless Util.truthy_string(options.log_pid)
LogUtil.tplog = LogUtil.tlog
LogUtil.tperr = LogUtil.terr
if Util.falsey_string(options.log_ts)
LogUtil.tplog = console.log
LogUtil.tperr = console.error
# if use-color is set, the create color-wrapping methods
if @config.use_color
@Cg = (str)->"\x1b[0;32m#{str}\x1b[0m"
@CG = (str)->"\x1b[1;32m#{str}\x1b[0m"
@Cr = (str)->"\x1b[0;31m#{str}\x1b[0m"
@CR = (str)->"\x1b[1;31m#{str}\x1b[0m"
@Cb = (str)->"\x1b[0;34m#{str}\x1b[0m"
@CB = (str)->"\x1b[1;34m#{str}\x1b[0m"
@Cm = (str)->"\x1b[0;35m#{str}\x1b[0m"
@CM = (str)->"\x1b[1;35m#{str}\x1b[0m"
@Cy = (str)->"\x1b[0;33m#{str}\x1b[0m"
@CY = (str)->"\x1b[1;33m#{str}\x1b[0m"
else # else declare the equivalent methods as no-ops==
for f in [ "Cg", "CG", "Cr", "CR", "Cb", "CB", "Cm", "CM", "Cy", "CY" ]
@[f] = (x)->x
_configure:(overrides, defaults)=>
return @configure( require('inote-util').config.init( defaults, overrides ) )
configure:(config)=>
c = {}
#-------------------------------------------------------------------------------
# Compose the base REST method used to launch RTM session.
# Other than changing `START_HOST` to point to a specific regional data-center
# you probably don't need to modify any of these values.
#-------------------------------------------------------------------------------
c.start_protocol = config.get("rtm:start:protocol") ? "https"
c.start_host = config.get("rtm:start:host") ? "app.us.team-one.com"
c.start_port = Util.to_int(config.get("rtm:start:port"))
unless c.start_port?
if c.start_protocol is 'https'
c.start_port ?= 443
else
c.start_port ?= 80
c.start_path = config.get("rtm:start:path") ? "/rest/v2/rtms/start"
#-------------------------------------------------------------------------------
# Configure ping frequency (if any). Defaults to around 30 seconds (but the
# exact value is "fuzzed" to avoid unnecessary sychronization when launching
# several bots simaltaneously). Set `PING_WAIT_MILLIS` to `0` or `false` to
# disable the ping entirely.
#-------------------------------------------------------------------------------
c.ping_wait_millis = config.get("rtm:ping:wait-time-millis") ? config.get("ping_wait_millis")
if c.ping_wait_millis? and Util.falsey_string(c.ping_wait_millis)
c.ping_wait_millis = false
else
c.ping_wait_millis = Util.to_int(c.ping_wait_millis)
c.ping_wait_millis ?= 30*1000
if c.ping_wait_millis
c.ping_wait_millis = c.ping_wait_millis - (3*1000) + (Math.random()*6*1000) # fuzz +/- 3 seconds
#-------------------------------------------------------------------------------
# Configure presence update frequency (if any). Defaults to around 12 minutes
# (but the exact value is "fuzzed" to avoid unnecessary sychronization when
# launching several bots simaltaneously). Set `PRESENCE_WAIT_MILLIS` to `0` or
# `false` to disable the ping entirely.
#-------------------------------------------------------------------------------
c.presence_wait_millis = config.get("rtm:presence:wait-time-millis") ? config.get("presence_wait_millis")
if c.presence_wait_millis? and Util.falsey_string(c.presence_wait_millis)
c.presence_wait_millis = false
else
c.presence_wait_millis = Util.to_int(c.presence_wait_millis)
c.presence_wait_millis ?= 12*60*1000
c.presence_value = config.get("rtm:presence:status") ? "ONLINE"
c.presence_path = config.get("rtm:presence:path") ? "/user/-/presence"
if c.presence_wait_millis
c.presence_wait_millis = c.presence_wait_millis - (30*1000) + (Math.random()*60*1000) # fuzz +/- 30 seconds
c.fetch_screen_name = Util.truthy_string(config.get("rtm:fetch-screen-name") ? config.get("rtm:fetch_screen_name") ? config.get("fetch-screen-name") ? config.get("fetch_screen_name") ? false)
#-------------------------------------------------------------------------------
# Configure log level. Note that `QUIET` is laconic but not totally silent.
#-------------------------------------------------------------------------------
c.quiet = Util.truthy_string(config.get("quiet") ? config.get("QUIET") ? false)
c.debug = Util.truthy_string(config.get("debug") ? config.get("DEBUG") ? (/(^|,|;)Team-?one(-?(Base-?)?Bots?)?($|,|;)/i.test(process.env.NODE_DEBUG)) )
#-------------------------------------------------------------------------------
c.sigint = Util.truthy_string(config.get("sigint-handler") ? config.get("sigint_handler") ? config.get("sigint") ? true)
c.botname = config.get("botname") ? config.get("name")
c.log_pid = Util.truthy_string(config.get("log:pid") ? config.get("log-pid") ? config.get("log_pid") ? false)
c.log_ts = Util.truthy_string(config.get("log:ts") ? config.get("log-ts") ? config.get("log_ts") ? true)
c.use_color = @_should_use_color(config)
c.default_ignore_duration_seconds = Util.to_int(config.get("ignore-duration-seconds")) ? 60
#-------------------------------------------------------------------------------
return c
# inspect:
# - inote-util.config object
# - process.argv
# - process.env
# - process.stdout
# to determine whether or not color output is appropriate
_should_use_color:(config = null, argv = process.argv, env = process.env, stdout = process.stdout)=>
positive_value = config.get("log:use-color") ? config.get("log:use_color") ? config.get("log:usecolor") ? config.get("log:color") ? config.get("use-color") ? config.get("use_color") ? config.get("color") ? config.get("USE-COLOR") ? config.get("USE_COLOR") ? config.get("COLOR")
negative_value = config.get("log:no-color") ? config.get("log:no_color") ? config.get("log:nocolor") ? config.get("no-color") ? config.get("no_color") ? config.get("nocolor") ? config.get("NO-COLOR") ? config.get("NO_COLOR") ? config.get("NOCOLOR")
if Util.truthy_string(positive_value) or positive_value is "always"
return true
else if Util.falsey_string(negative_value) or negative_value is "never"
return false
else if ("--no-color" in argv) or ("--color=false" in argv) or ("--color=0" in argv)
return false
else if ("--color" in argv) or ("--color=true" in argv) or ("--color=always" in argv) or ("--color=1" in argv)
return true
else if stdout? and not stdout.isTTY
return false
else if "COLORTERM" in env
return true
else if env.TERM is "dumb"
return false
else if /(^screen)|(^xterm)|(^vt100)|(color)|(ansi)|(cygwin)|(linux)/i.test env.TERM
return true
else
return false
exports.BaseBot = BaseBot
| 36306 | #-------------------------------------------------------------------------------
# Base Imports
#-------------------------------------------------------------------------------
LogUtil = require('inote-util').LogUtil
Util = require('inote-util').Util
WebSocket = require 'ws'
EventEmitter = require 'events'
IntellinoteClient = require("intellinote-client").IntellinoteClient
https = require 'https'
#-------------------------------------------------------------------------------
# "Abstract" base class to extend when creating Team-One bots.
#
# Provides convenience methods to simplify bot creation and some default
# behaviors like heartbeat (ping) and set-presence-to-online timers.
#
# Subclasses should implement `on_rtm_message`, probably invoking
# `reply` or `send_payload` at some point within it.
#
# Subclasses may hook into other methods to handle additional message types
# or provide other specialized behavior. See comments below.
#
# Note that `log`, `debug` and `error` methods are provided for
# configuration-aware logging. Subclasses should typically use that rather
# than `console.log` or `console.error` for most logging purposes.
#
# See `./basic/basic-bot.coffee` for a tiny example of extending this class
# to implement a bot.
#
# See the [README file](../README.md) for a long-winded description of how to
# extend this class.
#
class BaseBot extends EventEmitter
constructor:(options)->
@config = @_configure(options)
@_register_internal_listeners()
@_maybe_register_sigint_handler(@config)
@_configure_logging(@config)
@ignoring = {}
@ping_count = 0
if @config.start_protocol is "http"
https = require 'http'
# ignore the specified user within the specified workspace for
# duration seconds.
ignore:(workspace_id, user_id, duration_in_seconds)=>
duration_in_seconds ?= @config.default_ignore_duration_seconds
duration = duration_in_seconds*1000
key = <KEY>
ignore_until = Date.now()+duration
@ignoring[key] = ignore_until
stop_ignoring = ()=>
if @ignoring[key] is ignore_until
delete @ignoring[key]
setTimeout(stop,duration)
# stop ignoring the specified user within the specified
# workspace, even if the previously defined duration has
# not elapsed.
stop_ignoring:(workspace_id, user_id)=>
key = <KEY>
delete @ignoring[key]
# returns `true` if we should ignore the specified payload,
# `false` otherwise.
should_ignore:(payload)=>
if payload.type in ["message","user_typing"]
key = <KEY>
else if payload.type is "note"
key = <KEY>payload.note?.creator?.user_id ? payload.previous_note?.creator?.user_<KEY>
if key?
ignore_until = @ignoring[key]
if ignore_until?
if ignore_until >= Date.now()
return true
else
delete @ignoring[key]
return false
else
return false
else
return false
# The REST client (`rest_client`) is automatically initialized in `launch_bot`,
# but you can use this method to exert more control over the initialization
# or to init and use the REST client before `launch_bot` is called.
init_rest_client:(api_key,base_url,debug)=>
# if a config map is passed as the first parameter rather than an api key,
# use that instaed
if api_key? and typeof api_key is "object" and (api_key.access_token? or api_key.api_key?) and not base_url? and not debug?
config = api_key
if config.api_key and not config.access_token
config.access_token = config.api_key
delete config.api_key
else
client_config = {
access_token: api_key
base_url: base_url ? "#{@config.start_protocol}://#{@config.start_host}:#{@config.start_port}/rest/v2"
debug: debug ? false
}
@rest_client = new IntellinoteClient(client_config)
# Connect to the RTM API with the given `api_key` (string) and
# `filters` (string or array of strings). Once launched the
# `@on_rtm_message` method will be invoked every time a
# `message` payload is received from the RTM API.
launch_bot:(api_key, filters)=>
@log @Cg "Launching bot."
@debug "Fetching WSS URL."
unless @rest_client?
@init_rest_client(api_key)
@get_wss_url api_key, filters, (err, url)=>
if err?
@error "while fetching WSS URL:", err
@error "can't establish WSS connection. Exiting"
process.exit(2)
else
@debug "Fetched WSS URL:", url
@debug @Cg "Opening websocket."
@ws = new WebSocket(url)
@ws.on "open", ()=>
@emit "ws/open"
@ws.on "close", (code, reason)=>
@emit "ws/status", code, reason
@ws.on "error", (err)=>
@emit "ws/error", err
@ws.on "message", (data, flags)=>
@emit "ws/message", data,flags
# Hits the `/rest/v2/rtms/start` endpoint to obtain a WSS URL
# that can be used to initiate an RTM session.
get_wss_url:(api_key,filters,callback)=>
filters ?= []
if typeof filters is 'string'
filters = [filters]
filters.push("event_type=message_added")
filters.push("from_me=false")
full_path = "#{@config.start_path}?#{filters.join('&')}"
options = {
method: "GET"
host: @config.start_host
path: full_path
port: @config.start_port
headers: {
Authorization: "Bearer #{api_key}"
}
}
handler = (response)->
unless /^2[0-9]{2}$/.test "#{response?.statusCode}"
callback new Error("Expected 2xx-series status code but found #{response?.statusCode}.")
else
body = ""
response.on "data", (chunk)->
body += chunk
response.on "end", ()->
try
json = JSON.parse(body)
callback(null, json.href)
catch e
callback e
https.request(options, handler).end()
# Invoked (via `@launch_bot`) when the websocket is first connected.
on_ws_open:()=>
@log @Cg "Websocket connection established."
# Invoked (via `@launch_bot`) when the websocket is closed.
on_ws_close:(code,reason)=>
process.nextTick ()=> # allow other event listeners to run
@log "Websocket connection closed (code=#{code},reason=#{reason}). exiting."
@ws = null
process.exit 0
# Invoked (via `@launch_bot`) when an websocket error is encountered.
on_ws_error:(err)=>
@error "from websocket:",err
# Invoked (via `@launch_bot`) when an websocket message is receieved.
# Invokes `@on_hello`, `@on_ping`, @on_rtm_message`, etc. based on the
# contents of the message.
on_ws_message:(data,flags)=>
json = null
try
json = JSON.parse(data)
catch e
# ignored
(if json?.type is "message" then @log else @debug) @CM("Received via websocket:"),data
if json?
if @should_ignore json
@debug "Ignoring:",json
else
switch json.type
when "hello"
@emit "rtm/hello", json, flags
when "goodbye"
@emit "rtm/goodbye", json, flags
when "pong"
@emit "rtm/pong", json, flags
when "message"
@emit "rtm/message", json, flags
when "user_typing"
@emit "rtm/user_typing", json, flags
when "note"
@emit "rtm/note", json, flags
when "rest/response"
@emit "rtm/rest/response", json, flags
# Invoked (via `@on_ws_message`) when a `message` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_message:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `note` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_note:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `user_type` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_user_typing:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `rest/response` payload is delivered.
on_rtm_rest_response:(json,flags)=>
if json.reply_to is @put_presence_id
@put_presence_id = null
@debug """
Presence set to #{@config.presence_value}. \
Round-trip latency #{@_format_duration(@put_presence_sent)}. \
Repeating in #{@_format_duration(0,@config.presence_wait_millis)}.
"""
# Invoked (via `@on_ws_message`) when the `hello` payload is delivered.
on_rtm_hello:(json,flags)=>
@log @CG "RTM session started."
if @config.fetch_screen_name
@fetch_screen_name()
if @config.ping_wait_millis
@send_ping()
if @config.presence_wait_millis
@put_presence()
setInterval(@put_presence,@config.presence_wait_millis)
# Invoked (via `@on_ws_message`) when the `pong` payload is delivered.
# Logs the event then sets a timer to send the next `ping`
on_rtm_pong:(json,flags)=>
if @config.ping_wait_millis
if json?.sent?
latency_str = " Round-trip latency #{@_format_duration(json.sent)}."
@debug """
Got pong response.#{latency_str} \
Repeating in #{@_format_duration(0,@config.ping_wait_millis)}.
"""
setTimeout((()=>@send_ping()),@config.ping_wait_millis)
# Invoked (via `@on_ws_message`) when the `goodbye` payload is delivered.
on_rtm_goodbye:(json,flags)=>
@log @CR "The server said \"goodbye\" so I'm shutting down."
try
@ws?.close?()
@ws = null
catch e
# ignored
process.exit 0
# Updates my presence status by invoking a REST method thru the web socket.
# TODO consider doing this via @rest_client instead?
put_presence:()=>
if @ws?
payload = {
type: "rest/request"
method: "PUT"
path: @config.presence_path
body: {"presence":@config.presence_value}
id: Util.uuid(null,true)
}
@put_presence_id = payload.id
@put_presence_sent = Date.now()
try
@send_payload payload
catch err
@error "while posting presence:", payload, err
# send a chat message containing `message` to a workspace or chat.
# - `reply_to` - the original payload we are responding to
# - `message` - the text of the message to send
# - `options` - an optional map of options.
# recognized options include:
# - `@mention` - auto (default), true, false (also recognized as `at_mention`)
reply:(reply_to, message, options)=>
reply_to ?= {}
options ?= {}
message ?= ""
if reply_to.screen_name?
if Util.truthy_string( options["@mention"] ? options["at_mention"] )
message = "@#{reply_to.screen_name} #{message}"
else if Util.falsey_string( options["@mention"] ? options["at_mention"] )
message = message
else unless reply_to.workspace_1on1
message = "@#{reply_to.screen_name} #{message}"
payload = {
type : "message"
org_id : reply_to.org_id
workspace_id : reply_to.workspace_id
text : message
}
@send_payload payload
send_typing:(org_id, workspace_id)=>
# allow `org_id` to be a payload-like object
if not workspace_id? and org_id?.org_id? and org_id?.workspace_id?
workspace_id = org_id.workspace_id
org_id = org_id.org_id
payload = {
type: "typing"
org_id: org_id
workspace_id: workspace_id
}
@send_payload(payload)
# publish the given payload object to the web socket (then log it)
send_payload:(payload)=>
log = (if payload?.type is "message" then @log else @debug)
if payload? and typeof payload isnt "string"
payload = JSON.stringify(payload)
log(@CB("Sending RTM payload via websocket:"), payload)
@ws.send payload
# Assuming @my_screen_name is populated, searches @my_screen_name
# in `text` and replaces it with `replace_with` (defaults to `" "`).
# when `replace_globally` is `true` (the default) all instances of
# the screen name are replaced, otherwise only the first instance
# is replaced.
#
# See `fetch_screen_name` and the `fetch_screen_name` configuration
# parameter for more details.
replace_my_screen_name:(text, replace_with=" ", replace_globally=true)=>
replace_with ?= " "
if text?
if replace_globally and @my_screen_name_re_g?
text = text.replace(@my_screen_name_re_g, replace_with)
else if @my_screen_name_re
text = text.replace(@my_screen_name_re, replace_with)
return text
# Use the (non-tunnelled) REST client to fetch the specified
# user's profile.
# - `id` - optional identifier for the user to fetch, which can be user_id,
# email address or the string `-`, indicating that the profile of
# the _current_ (bot) user should be fetched; defualts to `-`.
# - `callback` - callback method with the signature `(err, json)`
# (where `json` contains the user info).
#
get_user:(id,callback)=>
if typeof id is 'function' and not callback?
callback = id
id = null
id ?= "-"
if callback? # don't bother to make the call if the caller is not going to accept the data
@debug "Using REST client to call GET /user/#{id}"
@rest_client.get_user "-", (err, json, response, body)=>
@debug "REST client to call to GET /user/#{id} yielded",err, response?.statusCode, JSON.stringify(json)
if err?
@error "Error during rest_client.get_user", err
callback(err, json, response, body)
else
@warn "get_user call ignored because no callback method was provided."
fetch_screen_name:(callback)=>
@get_user "-", (err, json, response, body)=>
if err?
if callback?
callback err
else
@warn "get_user yielded an error in fetch_screen_name but no callback was provided.", err
else unless json?.screen_name?
@warn "fetch_screen_name failed to return an object with a 'screen_name' attribute."
callback? null, null
else
@my_user_id = json.user_id
@my_screen_name = json.screen_name
@my_screen_name_re = new RegExp("@#{@my_screen_name} ?")
@my_screen_name_re_g = new RegExp("@#{@my_screen_name} ?","g")
callback? null, @my_screen_name
# posts a `ping` payload to the websocket
send_ping:()=>
@send_payload {
n:@ping_count++
sent: Date.now()
type:"ping"
}
# log the given message unless QUIET is set
log:(message...)=>
unless @config.quiet
# LogUtil.tplog("\x1b[0;37m#{@botname}\x1b[1;37m",message...,"\x1b[0m")
LogUtil.tplog("#{@botname}",message...)
# log the given message if DEBUG is set
debug:(message...)=>
if @config.debug
LogUtil.tplog("#{@botname}",message...)
# log the given message to STDERR
error:(message...)=>
LogUtil.tperr("#{@botname}",@CR("ERROR"),message...)
# log the given message to STDERR
warn:(message...)=>
LogUtil.tperr("#{@botname}",@CY("WARNNIG"),message...)
# utility method for formatting a duration in millliseconds as seconds
_format_duration:(millis,now)=>
now ?= Date.now()
if millis?
val = "#{Math.round((now-millis)/100)/10}"
unless /\./.test val
val = "#{val}.0s"
else
val = "#{val}s"
return val
else
return null
_maybe_register_sigint_handler:(options)=>
options ?= {}
unless Util.falsey_string(options.sigint)
process.on 'SIGINT', ()=>
if @ws?
try
@log @Cr "Got interrupt signal (Ctrl-C). Sending goodbye payload."
@send_payload({type:"goodbye"})
setTimeout((()->process.exit()),6000)
catch err
# ignored
process.exit(1)
else
process.exit()
_register_internal_listeners:()=>
for event in ["open","error","close","message"]
@on "ws/#{event}", @["on_ws_#{event}"]
for event in ["message","user_typing","note","rest/response","hello","pong","goodbye"]
@on "rtm/#{event}", @["on_rtm_#{event.replace /\//g,'_'}"]
_configure_logging:(options)=>
options ?= {}
if options.botname?
@botname = "[#{options.botname}]"
else
@botname = ""
unless Util.truthy_string(options.log_pid)
LogUtil.tplog = LogUtil.tlog
LogUtil.tperr = LogUtil.terr
if Util.falsey_string(options.log_ts)
LogUtil.tplog = console.log
LogUtil.tperr = console.error
# if use-color is set, the create color-wrapping methods
if @config.use_color
@Cg = (str)->"\x1b[0;32m#{str}\x1b[0m"
@CG = (str)->"\x1b[1;32m#{str}\x1b[0m"
@Cr = (str)->"\x1b[0;31m#{str}\x1b[0m"
@CR = (str)->"\x1b[1;31m#{str}\x1b[0m"
@Cb = (str)->"\x1b[0;34m#{str}\x1b[0m"
@CB = (str)->"\x1b[1;34m#{str}\x1b[0m"
@Cm = (str)->"\x1b[0;35m#{str}\x1b[0m"
@CM = (str)->"\x1b[1;35m#{str}\x1b[0m"
@Cy = (str)->"\x1b[0;33m#{str}\x1b[0m"
@CY = (str)->"\x1b[1;33m#{str}\x1b[0m"
else # else declare the equivalent methods as no-ops==
for f in [ "Cg", "CG", "Cr", "CR", "Cb", "CB", "Cm", "CM", "Cy", "CY" ]
@[f] = (x)->x
_configure:(overrides, defaults)=>
return @configure( require('inote-util').config.init( defaults, overrides ) )
configure:(config)=>
c = {}
#-------------------------------------------------------------------------------
# Compose the base REST method used to launch RTM session.
# Other than changing `START_HOST` to point to a specific regional data-center
# you probably don't need to modify any of these values.
#-------------------------------------------------------------------------------
c.start_protocol = config.get("rtm:start:protocol") ? "https"
c.start_host = config.get("rtm:start:host") ? "app.us.team-one.com"
c.start_port = Util.to_int(config.get("rtm:start:port"))
unless c.start_port?
if c.start_protocol is 'https'
c.start_port ?= 443
else
c.start_port ?= 80
c.start_path = config.get("rtm:start:path") ? "/rest/v2/rtms/start"
#-------------------------------------------------------------------------------
# Configure ping frequency (if any). Defaults to around 30 seconds (but the
# exact value is "fuzzed" to avoid unnecessary sychronization when launching
# several bots simaltaneously). Set `PING_WAIT_MILLIS` to `0` or `false` to
# disable the ping entirely.
#-------------------------------------------------------------------------------
c.ping_wait_millis = config.get("rtm:ping:wait-time-millis") ? config.get("ping_wait_millis")
if c.ping_wait_millis? and Util.falsey_string(c.ping_wait_millis)
c.ping_wait_millis = false
else
c.ping_wait_millis = Util.to_int(c.ping_wait_millis)
c.ping_wait_millis ?= 30*1000
if c.ping_wait_millis
c.ping_wait_millis = c.ping_wait_millis - (3*1000) + (Math.random()*6*1000) # fuzz +/- 3 seconds
#-------------------------------------------------------------------------------
# Configure presence update frequency (if any). Defaults to around 12 minutes
# (but the exact value is "fuzzed" to avoid unnecessary sychronization when
# launching several bots simaltaneously). Set `PRESENCE_WAIT_MILLIS` to `0` or
# `false` to disable the ping entirely.
#-------------------------------------------------------------------------------
c.presence_wait_millis = config.get("rtm:presence:wait-time-millis") ? config.get("presence_wait_millis")
if c.presence_wait_millis? and Util.falsey_string(c.presence_wait_millis)
c.presence_wait_millis = false
else
c.presence_wait_millis = Util.to_int(c.presence_wait_millis)
c.presence_wait_millis ?= 12*60*1000
c.presence_value = config.get("rtm:presence:status") ? "ONLINE"
c.presence_path = config.get("rtm:presence:path") ? "/user/-/presence"
if c.presence_wait_millis
c.presence_wait_millis = c.presence_wait_millis - (30*1000) + (Math.random()*60*1000) # fuzz +/- 30 seconds
c.fetch_screen_name = Util.truthy_string(config.get("rtm:fetch-screen-name") ? config.get("rtm:fetch_screen_name") ? config.get("fetch-screen-name") ? config.get("fetch_screen_name") ? false)
#-------------------------------------------------------------------------------
# Configure log level. Note that `QUIET` is laconic but not totally silent.
#-------------------------------------------------------------------------------
c.quiet = Util.truthy_string(config.get("quiet") ? config.get("QUIET") ? false)
c.debug = Util.truthy_string(config.get("debug") ? config.get("DEBUG") ? (/(^|,|;)Team-?one(-?(Base-?)?Bots?)?($|,|;)/i.test(process.env.NODE_DEBUG)) )
#-------------------------------------------------------------------------------
c.sigint = Util.truthy_string(config.get("sigint-handler") ? config.get("sigint_handler") ? config.get("sigint") ? true)
c.botname = config.get("botname") ? config.get("name")
c.log_pid = Util.truthy_string(config.get("log:pid") ? config.get("log-pid") ? config.get("log_pid") ? false)
c.log_ts = Util.truthy_string(config.get("log:ts") ? config.get("log-ts") ? config.get("log_ts") ? true)
c.use_color = @_should_use_color(config)
c.default_ignore_duration_seconds = Util.to_int(config.get("ignore-duration-seconds")) ? 60
#-------------------------------------------------------------------------------
return c
# inspect:
# - inote-util.config object
# - process.argv
# - process.env
# - process.stdout
# to determine whether or not color output is appropriate
_should_use_color:(config = null, argv = process.argv, env = process.env, stdout = process.stdout)=>
positive_value = config.get("log:use-color") ? config.get("log:use_color") ? config.get("log:usecolor") ? config.get("log:color") ? config.get("use-color") ? config.get("use_color") ? config.get("color") ? config.get("USE-COLOR") ? config.get("USE_COLOR") ? config.get("COLOR")
negative_value = config.get("log:no-color") ? config.get("log:no_color") ? config.get("log:nocolor") ? config.get("no-color") ? config.get("no_color") ? config.get("nocolor") ? config.get("NO-COLOR") ? config.get("NO_COLOR") ? config.get("NOCOLOR")
if Util.truthy_string(positive_value) or positive_value is "always"
return true
else if Util.falsey_string(negative_value) or negative_value is "never"
return false
else if ("--no-color" in argv) or ("--color=false" in argv) or ("--color=0" in argv)
return false
else if ("--color" in argv) or ("--color=true" in argv) or ("--color=always" in argv) or ("--color=1" in argv)
return true
else if stdout? and not stdout.isTTY
return false
else if "COLORTERM" in env
return true
else if env.TERM is "dumb"
return false
else if /(^screen)|(^xterm)|(^vt100)|(color)|(ansi)|(cygwin)|(linux)/i.test env.TERM
return true
else
return false
exports.BaseBot = BaseBot
| true | #-------------------------------------------------------------------------------
# Base Imports
#-------------------------------------------------------------------------------
LogUtil = require('inote-util').LogUtil
Util = require('inote-util').Util
WebSocket = require 'ws'
EventEmitter = require 'events'
IntellinoteClient = require("intellinote-client").IntellinoteClient
https = require 'https'
#-------------------------------------------------------------------------------
# "Abstract" base class to extend when creating Team-One bots.
#
# Provides convenience methods to simplify bot creation and some default
# behaviors like heartbeat (ping) and set-presence-to-online timers.
#
# Subclasses should implement `on_rtm_message`, probably invoking
# `reply` or `send_payload` at some point within it.
#
# Subclasses may hook into other methods to handle additional message types
# or provide other specialized behavior. See comments below.
#
# Note that `log`, `debug` and `error` methods are provided for
# configuration-aware logging. Subclasses should typically use that rather
# than `console.log` or `console.error` for most logging purposes.
#
# See `./basic/basic-bot.coffee` for a tiny example of extending this class
# to implement a bot.
#
# See the [README file](../README.md) for a long-winded description of how to
# extend this class.
#
class BaseBot extends EventEmitter
constructor:(options)->
@config = @_configure(options)
@_register_internal_listeners()
@_maybe_register_sigint_handler(@config)
@_configure_logging(@config)
@ignoring = {}
@ping_count = 0
if @config.start_protocol is "http"
https = require 'http'
# ignore the specified user within the specified workspace for
# duration seconds.
ignore:(workspace_id, user_id, duration_in_seconds)=>
duration_in_seconds ?= @config.default_ignore_duration_seconds
duration = duration_in_seconds*1000
key = PI:KEY:<KEY>END_PI
ignore_until = Date.now()+duration
@ignoring[key] = ignore_until
stop_ignoring = ()=>
if @ignoring[key] is ignore_until
delete @ignoring[key]
setTimeout(stop,duration)
# stop ignoring the specified user within the specified
# workspace, even if the previously defined duration has
# not elapsed.
stop_ignoring:(workspace_id, user_id)=>
key = PI:KEY:<KEY>END_PI
delete @ignoring[key]
# returns `true` if we should ignore the specified payload,
# `false` otherwise.
should_ignore:(payload)=>
if payload.type in ["message","user_typing"]
key = PI:KEY:<KEY>END_PI
else if payload.type is "note"
key = PI:KEY:<KEY>END_PIpayload.note?.creator?.user_id ? payload.previous_note?.creator?.user_PI:KEY:<KEY>END_PI
if key?
ignore_until = @ignoring[key]
if ignore_until?
if ignore_until >= Date.now()
return true
else
delete @ignoring[key]
return false
else
return false
else
return false
# The REST client (`rest_client`) is automatically initialized in `launch_bot`,
# but you can use this method to exert more control over the initialization
# or to init and use the REST client before `launch_bot` is called.
init_rest_client:(api_key,base_url,debug)=>
# if a config map is passed as the first parameter rather than an api key,
# use that instaed
if api_key? and typeof api_key is "object" and (api_key.access_token? or api_key.api_key?) and not base_url? and not debug?
config = api_key
if config.api_key and not config.access_token
config.access_token = config.api_key
delete config.api_key
else
client_config = {
access_token: api_key
base_url: base_url ? "#{@config.start_protocol}://#{@config.start_host}:#{@config.start_port}/rest/v2"
debug: debug ? false
}
@rest_client = new IntellinoteClient(client_config)
# Connect to the RTM API with the given `api_key` (string) and
# `filters` (string or array of strings). Once launched the
# `@on_rtm_message` method will be invoked every time a
# `message` payload is received from the RTM API.
launch_bot:(api_key, filters)=>
@log @Cg "Launching bot."
@debug "Fetching WSS URL."
unless @rest_client?
@init_rest_client(api_key)
@get_wss_url api_key, filters, (err, url)=>
if err?
@error "while fetching WSS URL:", err
@error "can't establish WSS connection. Exiting"
process.exit(2)
else
@debug "Fetched WSS URL:", url
@debug @Cg "Opening websocket."
@ws = new WebSocket(url)
@ws.on "open", ()=>
@emit "ws/open"
@ws.on "close", (code, reason)=>
@emit "ws/status", code, reason
@ws.on "error", (err)=>
@emit "ws/error", err
@ws.on "message", (data, flags)=>
@emit "ws/message", data,flags
# Hits the `/rest/v2/rtms/start` endpoint to obtain a WSS URL
# that can be used to initiate an RTM session.
get_wss_url:(api_key,filters,callback)=>
filters ?= []
if typeof filters is 'string'
filters = [filters]
filters.push("event_type=message_added")
filters.push("from_me=false")
full_path = "#{@config.start_path}?#{filters.join('&')}"
options = {
method: "GET"
host: @config.start_host
path: full_path
port: @config.start_port
headers: {
Authorization: "Bearer #{api_key}"
}
}
handler = (response)->
unless /^2[0-9]{2}$/.test "#{response?.statusCode}"
callback new Error("Expected 2xx-series status code but found #{response?.statusCode}.")
else
body = ""
response.on "data", (chunk)->
body += chunk
response.on "end", ()->
try
json = JSON.parse(body)
callback(null, json.href)
catch e
callback e
https.request(options, handler).end()
# Invoked (via `@launch_bot`) when the websocket is first connected.
on_ws_open:()=>
@log @Cg "Websocket connection established."
# Invoked (via `@launch_bot`) when the websocket is closed.
on_ws_close:(code,reason)=>
process.nextTick ()=> # allow other event listeners to run
@log "Websocket connection closed (code=#{code},reason=#{reason}). exiting."
@ws = null
process.exit 0
# Invoked (via `@launch_bot`) when an websocket error is encountered.
on_ws_error:(err)=>
@error "from websocket:",err
# Invoked (via `@launch_bot`) when an websocket message is receieved.
# Invokes `@on_hello`, `@on_ping`, @on_rtm_message`, etc. based on the
# contents of the message.
on_ws_message:(data,flags)=>
json = null
try
json = JSON.parse(data)
catch e
# ignored
(if json?.type is "message" then @log else @debug) @CM("Received via websocket:"),data
if json?
if @should_ignore json
@debug "Ignoring:",json
else
switch json.type
when "hello"
@emit "rtm/hello", json, flags
when "goodbye"
@emit "rtm/goodbye", json, flags
when "pong"
@emit "rtm/pong", json, flags
when "message"
@emit "rtm/message", json, flags
when "user_typing"
@emit "rtm/user_typing", json, flags
when "note"
@emit "rtm/note", json, flags
when "rest/response"
@emit "rtm/rest/response", json, flags
# Invoked (via `@on_ws_message`) when a `message` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_message:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `note` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_note:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `user_type` payload is delivered.
# `json` will contain the JSON payload that was receieved (in object, not string form).
on_rtm_user_typing:(json,flags)=>
undefined
# Invoked (via `@on_ws_message`) when a `rest/response` payload is delivered.
on_rtm_rest_response:(json,flags)=>
if json.reply_to is @put_presence_id
@put_presence_id = null
@debug """
Presence set to #{@config.presence_value}. \
Round-trip latency #{@_format_duration(@put_presence_sent)}. \
Repeating in #{@_format_duration(0,@config.presence_wait_millis)}.
"""
# Invoked (via `@on_ws_message`) when the `hello` payload is delivered.
on_rtm_hello:(json,flags)=>
@log @CG "RTM session started."
if @config.fetch_screen_name
@fetch_screen_name()
if @config.ping_wait_millis
@send_ping()
if @config.presence_wait_millis
@put_presence()
setInterval(@put_presence,@config.presence_wait_millis)
# Invoked (via `@on_ws_message`) when the `pong` payload is delivered.
# Logs the event then sets a timer to send the next `ping`
on_rtm_pong:(json,flags)=>
if @config.ping_wait_millis
if json?.sent?
latency_str = " Round-trip latency #{@_format_duration(json.sent)}."
@debug """
Got pong response.#{latency_str} \
Repeating in #{@_format_duration(0,@config.ping_wait_millis)}.
"""
setTimeout((()=>@send_ping()),@config.ping_wait_millis)
# Invoked (via `@on_ws_message`) when the `goodbye` payload is delivered.
on_rtm_goodbye:(json,flags)=>
@log @CR "The server said \"goodbye\" so I'm shutting down."
try
@ws?.close?()
@ws = null
catch e
# ignored
process.exit 0
# Updates my presence status by invoking a REST method thru the web socket.
# TODO consider doing this via @rest_client instead?
put_presence:()=>
if @ws?
payload = {
type: "rest/request"
method: "PUT"
path: @config.presence_path
body: {"presence":@config.presence_value}
id: Util.uuid(null,true)
}
@put_presence_id = payload.id
@put_presence_sent = Date.now()
try
@send_payload payload
catch err
@error "while posting presence:", payload, err
# send a chat message containing `message` to a workspace or chat.
# - `reply_to` - the original payload we are responding to
# - `message` - the text of the message to send
# - `options` - an optional map of options.
# recognized options include:
# - `@mention` - auto (default), true, false (also recognized as `at_mention`)
reply:(reply_to, message, options)=>
reply_to ?= {}
options ?= {}
message ?= ""
if reply_to.screen_name?
if Util.truthy_string( options["@mention"] ? options["at_mention"] )
message = "@#{reply_to.screen_name} #{message}"
else if Util.falsey_string( options["@mention"] ? options["at_mention"] )
message = message
else unless reply_to.workspace_1on1
message = "@#{reply_to.screen_name} #{message}"
payload = {
type : "message"
org_id : reply_to.org_id
workspace_id : reply_to.workspace_id
text : message
}
@send_payload payload
send_typing:(org_id, workspace_id)=>
# allow `org_id` to be a payload-like object
if not workspace_id? and org_id?.org_id? and org_id?.workspace_id?
workspace_id = org_id.workspace_id
org_id = org_id.org_id
payload = {
type: "typing"
org_id: org_id
workspace_id: workspace_id
}
@send_payload(payload)
# publish the given payload object to the web socket (then log it)
send_payload:(payload)=>
log = (if payload?.type is "message" then @log else @debug)
if payload? and typeof payload isnt "string"
payload = JSON.stringify(payload)
log(@CB("Sending RTM payload via websocket:"), payload)
@ws.send payload
# Assuming @my_screen_name is populated, searches @my_screen_name
# in `text` and replaces it with `replace_with` (defaults to `" "`).
# when `replace_globally` is `true` (the default) all instances of
# the screen name are replaced, otherwise only the first instance
# is replaced.
#
# See `fetch_screen_name` and the `fetch_screen_name` configuration
# parameter for more details.
replace_my_screen_name:(text, replace_with=" ", replace_globally=true)=>
replace_with ?= " "
if text?
if replace_globally and @my_screen_name_re_g?
text = text.replace(@my_screen_name_re_g, replace_with)
else if @my_screen_name_re
text = text.replace(@my_screen_name_re, replace_with)
return text
# Use the (non-tunnelled) REST client to fetch the specified
# user's profile.
# - `id` - optional identifier for the user to fetch, which can be user_id,
# email address or the string `-`, indicating that the profile of
# the _current_ (bot) user should be fetched; defualts to `-`.
# - `callback` - callback method with the signature `(err, json)`
# (where `json` contains the user info).
#
get_user:(id,callback)=>
if typeof id is 'function' and not callback?
callback = id
id = null
id ?= "-"
if callback? # don't bother to make the call if the caller is not going to accept the data
@debug "Using REST client to call GET /user/#{id}"
@rest_client.get_user "-", (err, json, response, body)=>
@debug "REST client to call to GET /user/#{id} yielded",err, response?.statusCode, JSON.stringify(json)
if err?
@error "Error during rest_client.get_user", err
callback(err, json, response, body)
else
@warn "get_user call ignored because no callback method was provided."
fetch_screen_name:(callback)=>
@get_user "-", (err, json, response, body)=>
if err?
if callback?
callback err
else
@warn "get_user yielded an error in fetch_screen_name but no callback was provided.", err
else unless json?.screen_name?
@warn "fetch_screen_name failed to return an object with a 'screen_name' attribute."
callback? null, null
else
@my_user_id = json.user_id
@my_screen_name = json.screen_name
@my_screen_name_re = new RegExp("@#{@my_screen_name} ?")
@my_screen_name_re_g = new RegExp("@#{@my_screen_name} ?","g")
callback? null, @my_screen_name
# posts a `ping` payload to the websocket
send_ping:()=>
@send_payload {
n:@ping_count++
sent: Date.now()
type:"ping"
}
# log the given message unless QUIET is set
log:(message...)=>
unless @config.quiet
# LogUtil.tplog("\x1b[0;37m#{@botname}\x1b[1;37m",message...,"\x1b[0m")
LogUtil.tplog("#{@botname}",message...)
# log the given message if DEBUG is set
debug:(message...)=>
if @config.debug
LogUtil.tplog("#{@botname}",message...)
# log the given message to STDERR
error:(message...)=>
LogUtil.tperr("#{@botname}",@CR("ERROR"),message...)
# log the given message to STDERR
warn:(message...)=>
LogUtil.tperr("#{@botname}",@CY("WARNNIG"),message...)
# utility method for formatting a duration in millliseconds as seconds
_format_duration:(millis,now)=>
now ?= Date.now()
if millis?
val = "#{Math.round((now-millis)/100)/10}"
unless /\./.test val
val = "#{val}.0s"
else
val = "#{val}s"
return val
else
return null
_maybe_register_sigint_handler:(options)=>
options ?= {}
unless Util.falsey_string(options.sigint)
process.on 'SIGINT', ()=>
if @ws?
try
@log @Cr "Got interrupt signal (Ctrl-C). Sending goodbye payload."
@send_payload({type:"goodbye"})
setTimeout((()->process.exit()),6000)
catch err
# ignored
process.exit(1)
else
process.exit()
_register_internal_listeners:()=>
for event in ["open","error","close","message"]
@on "ws/#{event}", @["on_ws_#{event}"]
for event in ["message","user_typing","note","rest/response","hello","pong","goodbye"]
@on "rtm/#{event}", @["on_rtm_#{event.replace /\//g,'_'}"]
_configure_logging:(options)=>
options ?= {}
if options.botname?
@botname = "[#{options.botname}]"
else
@botname = ""
unless Util.truthy_string(options.log_pid)
LogUtil.tplog = LogUtil.tlog
LogUtil.tperr = LogUtil.terr
if Util.falsey_string(options.log_ts)
LogUtil.tplog = console.log
LogUtil.tperr = console.error
# if use-color is set, the create color-wrapping methods
if @config.use_color
@Cg = (str)->"\x1b[0;32m#{str}\x1b[0m"
@CG = (str)->"\x1b[1;32m#{str}\x1b[0m"
@Cr = (str)->"\x1b[0;31m#{str}\x1b[0m"
@CR = (str)->"\x1b[1;31m#{str}\x1b[0m"
@Cb = (str)->"\x1b[0;34m#{str}\x1b[0m"
@CB = (str)->"\x1b[1;34m#{str}\x1b[0m"
@Cm = (str)->"\x1b[0;35m#{str}\x1b[0m"
@CM = (str)->"\x1b[1;35m#{str}\x1b[0m"
@Cy = (str)->"\x1b[0;33m#{str}\x1b[0m"
@CY = (str)->"\x1b[1;33m#{str}\x1b[0m"
else # else declare the equivalent methods as no-ops==
for f in [ "Cg", "CG", "Cr", "CR", "Cb", "CB", "Cm", "CM", "Cy", "CY" ]
@[f] = (x)->x
_configure:(overrides, defaults)=>
return @configure( require('inote-util').config.init( defaults, overrides ) )
configure:(config)=>
c = {}
#-------------------------------------------------------------------------------
# Compose the base REST method used to launch RTM session.
# Other than changing `START_HOST` to point to a specific regional data-center
# you probably don't need to modify any of these values.
#-------------------------------------------------------------------------------
c.start_protocol = config.get("rtm:start:protocol") ? "https"
c.start_host = config.get("rtm:start:host") ? "app.us.team-one.com"
c.start_port = Util.to_int(config.get("rtm:start:port"))
unless c.start_port?
if c.start_protocol is 'https'
c.start_port ?= 443
else
c.start_port ?= 80
c.start_path = config.get("rtm:start:path") ? "/rest/v2/rtms/start"
#-------------------------------------------------------------------------------
# Configure ping frequency (if any). Defaults to around 30 seconds (but the
# exact value is "fuzzed" to avoid unnecessary sychronization when launching
# several bots simaltaneously). Set `PING_WAIT_MILLIS` to `0` or `false` to
# disable the ping entirely.
#-------------------------------------------------------------------------------
c.ping_wait_millis = config.get("rtm:ping:wait-time-millis") ? config.get("ping_wait_millis")
if c.ping_wait_millis? and Util.falsey_string(c.ping_wait_millis)
c.ping_wait_millis = false
else
c.ping_wait_millis = Util.to_int(c.ping_wait_millis)
c.ping_wait_millis ?= 30*1000
if c.ping_wait_millis
c.ping_wait_millis = c.ping_wait_millis - (3*1000) + (Math.random()*6*1000) # fuzz +/- 3 seconds
#-------------------------------------------------------------------------------
# Configure presence update frequency (if any). Defaults to around 12 minutes
# (but the exact value is "fuzzed" to avoid unnecessary sychronization when
# launching several bots simaltaneously). Set `PRESENCE_WAIT_MILLIS` to `0` or
# `false` to disable the ping entirely.
#-------------------------------------------------------------------------------
c.presence_wait_millis = config.get("rtm:presence:wait-time-millis") ? config.get("presence_wait_millis")
if c.presence_wait_millis? and Util.falsey_string(c.presence_wait_millis)
c.presence_wait_millis = false
else
c.presence_wait_millis = Util.to_int(c.presence_wait_millis)
c.presence_wait_millis ?= 12*60*1000
c.presence_value = config.get("rtm:presence:status") ? "ONLINE"
c.presence_path = config.get("rtm:presence:path") ? "/user/-/presence"
if c.presence_wait_millis
c.presence_wait_millis = c.presence_wait_millis - (30*1000) + (Math.random()*60*1000) # fuzz +/- 30 seconds
c.fetch_screen_name = Util.truthy_string(config.get("rtm:fetch-screen-name") ? config.get("rtm:fetch_screen_name") ? config.get("fetch-screen-name") ? config.get("fetch_screen_name") ? false)
#-------------------------------------------------------------------------------
# Configure log level. Note that `QUIET` is laconic but not totally silent.
#-------------------------------------------------------------------------------
c.quiet = Util.truthy_string(config.get("quiet") ? config.get("QUIET") ? false)
c.debug = Util.truthy_string(config.get("debug") ? config.get("DEBUG") ? (/(^|,|;)Team-?one(-?(Base-?)?Bots?)?($|,|;)/i.test(process.env.NODE_DEBUG)) )
#-------------------------------------------------------------------------------
c.sigint = Util.truthy_string(config.get("sigint-handler") ? config.get("sigint_handler") ? config.get("sigint") ? true)
c.botname = config.get("botname") ? config.get("name")
c.log_pid = Util.truthy_string(config.get("log:pid") ? config.get("log-pid") ? config.get("log_pid") ? false)
c.log_ts = Util.truthy_string(config.get("log:ts") ? config.get("log-ts") ? config.get("log_ts") ? true)
c.use_color = @_should_use_color(config)
c.default_ignore_duration_seconds = Util.to_int(config.get("ignore-duration-seconds")) ? 60
#-------------------------------------------------------------------------------
return c
# inspect:
# - inote-util.config object
# - process.argv
# - process.env
# - process.stdout
# to determine whether or not color output is appropriate
_should_use_color:(config = null, argv = process.argv, env = process.env, stdout = process.stdout)=>
positive_value = config.get("log:use-color") ? config.get("log:use_color") ? config.get("log:usecolor") ? config.get("log:color") ? config.get("use-color") ? config.get("use_color") ? config.get("color") ? config.get("USE-COLOR") ? config.get("USE_COLOR") ? config.get("COLOR")
negative_value = config.get("log:no-color") ? config.get("log:no_color") ? config.get("log:nocolor") ? config.get("no-color") ? config.get("no_color") ? config.get("nocolor") ? config.get("NO-COLOR") ? config.get("NO_COLOR") ? config.get("NOCOLOR")
if Util.truthy_string(positive_value) or positive_value is "always"
return true
else if Util.falsey_string(negative_value) or negative_value is "never"
return false
else if ("--no-color" in argv) or ("--color=false" in argv) or ("--color=0" in argv)
return false
else if ("--color" in argv) or ("--color=true" in argv) or ("--color=always" in argv) or ("--color=1" in argv)
return true
else if stdout? and not stdout.isTTY
return false
else if "COLORTERM" in env
return true
else if env.TERM is "dumb"
return false
else if /(^screen)|(^xterm)|(^vt100)|(color)|(ansi)|(cygwin)|(linux)/i.test env.TERM
return true
else
return false
exports.BaseBot = BaseBot
|
[
{
"context": ": appendRules\n expect(praiseSinger.givePraise 'John' ).toBe(FILL_ME_IN)\n\n praiseSinger.givePraise ",
"end": 1868,
"score": 0.9987109899520874,
"start": 1864,
"tag": "NAME",
"value": "John"
},
{
"context": "ndDoubleRules\n expect(praiseSinger.givePraise 'Mary... | koans/AboutFunctions.coffee | gaslight/coffeescript-koans | 1 | describe 'About Functions', ->
it 'should declare functions', ->
# In Coffeescript, the value of the last expression is the return value of the function
add = (a, b) -> a + b
expect(add(1, 2)).toBe(FILL_ME_IN)
it 'should know internal variables override outer variables', ->
message = 'Outer'
getMessage = -> message
overrideMessage = -> message = 'Inner'
expect(getMessage()).toBe(FILL_ME_IN)
expect(overrideMessage()).toBe(FILL_ME_IN)
expect(message).toBe(FILL_ME_IN) # Side effect
it 'should have lexical scoping', ->
variable = 'top-level'
parentfunction = ->
variable = 'local'
childfunction = -> variable
expect(parentfunction()()).toBe(FILL_ME_IN)
it 'should use lexical scoping to synthesise functions', ->
makeIncreaseByFunction = (increaseByAmount) ->
(numberToIncrease) -> numberToIncrease + increaseByAmount
increaseBy3 = makeIncreaseByFunction 3
increaseBy5 = makeIncreaseByFunction 5
expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN)
it 'should allow extra function arguments', ->
returnFirstArg = (firstArg) -> firstArg
expect(returnFirstArg('first', 'second', 'third')).toBe(FILL_ME_IN)
returnSecondArg = (firstArg, secondArg) -> secondArg
expect(returnSecondArg('only give first arg')).toBe(FILL_ME_IN)
# Coffeescript supports splats
returnAllArgs = (allargs...) -> allargs
expect(returnAllArgs('first', 'second', 'third')).toEqual(FILL_ME_IN)
returnAllButFirst = (firstArg, rest...) -> rest
expect(returnAllButFirst('first', 'second', 'third')).toEqual(FILL_ME_IN)
it 'should pass functions as values', ->
appendRules = (name) -> name + ' rules!'
appendDoubleRules = (name) -> name + ' totally rules!'
praiseSinger = givePraise: appendRules
expect(praiseSinger.givePraise 'John' ).toBe(FILL_ME_IN)
praiseSinger.givePraise = appendDoubleRules
expect(praiseSinger.givePraise 'Mary' ).toBe(FILL_ME_IN)
it 'should understand destructuring assignment', ->
weatherReport = (location) -> [location, 22, 'Mostly sunny']
[city, temperature, forecast] = weatherReport 'London'
expect(city).toBe(FILL_ME_IN)
expect(temperature).toBe(FILL_ME_IN)
it 'should understand destructuring works with splats', ->
phrase = 'Now is the time for all good men to come to the aid of the Party'
[start, middle..., end] = phrase.split ' '
expect(start).toBe(FILL_ME_IN)
expect(end).toBe(FILL_ME_IN)
| 60544 | describe 'About Functions', ->
it 'should declare functions', ->
# In Coffeescript, the value of the last expression is the return value of the function
add = (a, b) -> a + b
expect(add(1, 2)).toBe(FILL_ME_IN)
it 'should know internal variables override outer variables', ->
message = 'Outer'
getMessage = -> message
overrideMessage = -> message = 'Inner'
expect(getMessage()).toBe(FILL_ME_IN)
expect(overrideMessage()).toBe(FILL_ME_IN)
expect(message).toBe(FILL_ME_IN) # Side effect
it 'should have lexical scoping', ->
variable = 'top-level'
parentfunction = ->
variable = 'local'
childfunction = -> variable
expect(parentfunction()()).toBe(FILL_ME_IN)
it 'should use lexical scoping to synthesise functions', ->
makeIncreaseByFunction = (increaseByAmount) ->
(numberToIncrease) -> numberToIncrease + increaseByAmount
increaseBy3 = makeIncreaseByFunction 3
increaseBy5 = makeIncreaseByFunction 5
expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN)
it 'should allow extra function arguments', ->
returnFirstArg = (firstArg) -> firstArg
expect(returnFirstArg('first', 'second', 'third')).toBe(FILL_ME_IN)
returnSecondArg = (firstArg, secondArg) -> secondArg
expect(returnSecondArg('only give first arg')).toBe(FILL_ME_IN)
# Coffeescript supports splats
returnAllArgs = (allargs...) -> allargs
expect(returnAllArgs('first', 'second', 'third')).toEqual(FILL_ME_IN)
returnAllButFirst = (firstArg, rest...) -> rest
expect(returnAllButFirst('first', 'second', 'third')).toEqual(FILL_ME_IN)
it 'should pass functions as values', ->
appendRules = (name) -> name + ' rules!'
appendDoubleRules = (name) -> name + ' totally rules!'
praiseSinger = givePraise: appendRules
expect(praiseSinger.givePraise '<NAME>' ).toBe(FILL_ME_IN)
praiseSinger.givePraise = appendDoubleRules
expect(praiseSinger.givePraise '<NAME>' ).toBe(FILL_ME_IN)
it 'should understand destructuring assignment', ->
weatherReport = (location) -> [location, 22, 'Mostly sunny']
[city, temperature, forecast] = weatherReport 'London'
expect(city).toBe(FILL_ME_IN)
expect(temperature).toBe(FILL_ME_IN)
it 'should understand destructuring works with splats', ->
phrase = 'Now is the time for all good men to come to the aid of the Party'
[start, middle..., end] = phrase.split ' '
expect(start).toBe(FILL_ME_IN)
expect(end).toBe(FILL_ME_IN)
| true | describe 'About Functions', ->
it 'should declare functions', ->
# In Coffeescript, the value of the last expression is the return value of the function
add = (a, b) -> a + b
expect(add(1, 2)).toBe(FILL_ME_IN)
it 'should know internal variables override outer variables', ->
message = 'Outer'
getMessage = -> message
overrideMessage = -> message = 'Inner'
expect(getMessage()).toBe(FILL_ME_IN)
expect(overrideMessage()).toBe(FILL_ME_IN)
expect(message).toBe(FILL_ME_IN) # Side effect
it 'should have lexical scoping', ->
variable = 'top-level'
parentfunction = ->
variable = 'local'
childfunction = -> variable
expect(parentfunction()()).toBe(FILL_ME_IN)
it 'should use lexical scoping to synthesise functions', ->
makeIncreaseByFunction = (increaseByAmount) ->
(numberToIncrease) -> numberToIncrease + increaseByAmount
increaseBy3 = makeIncreaseByFunction 3
increaseBy5 = makeIncreaseByFunction 5
expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN)
it 'should allow extra function arguments', ->
returnFirstArg = (firstArg) -> firstArg
expect(returnFirstArg('first', 'second', 'third')).toBe(FILL_ME_IN)
returnSecondArg = (firstArg, secondArg) -> secondArg
expect(returnSecondArg('only give first arg')).toBe(FILL_ME_IN)
# Coffeescript supports splats
returnAllArgs = (allargs...) -> allargs
expect(returnAllArgs('first', 'second', 'third')).toEqual(FILL_ME_IN)
returnAllButFirst = (firstArg, rest...) -> rest
expect(returnAllButFirst('first', 'second', 'third')).toEqual(FILL_ME_IN)
it 'should pass functions as values', ->
appendRules = (name) -> name + ' rules!'
appendDoubleRules = (name) -> name + ' totally rules!'
praiseSinger = givePraise: appendRules
expect(praiseSinger.givePraise 'PI:NAME:<NAME>END_PI' ).toBe(FILL_ME_IN)
praiseSinger.givePraise = appendDoubleRules
expect(praiseSinger.givePraise 'PI:NAME:<NAME>END_PI' ).toBe(FILL_ME_IN)
it 'should understand destructuring assignment', ->
weatherReport = (location) -> [location, 22, 'Mostly sunny']
[city, temperature, forecast] = weatherReport 'London'
expect(city).toBe(FILL_ME_IN)
expect(temperature).toBe(FILL_ME_IN)
it 'should understand destructuring works with splats', ->
phrase = 'Now is the time for all good men to come to the aid of the Party'
[start, middle..., end] = phrase.split ' '
expect(start).toBe(FILL_ME_IN)
expect(end).toBe(FILL_ME_IN)
|
[
{
"context": "STS = true\n\n# Helpers\n\ngetNock = (host = 'http://127.0.0.1:4001') ->\n nock host\n\n# Tests for utility functi",
"end": 202,
"score": 0.5802416801452637,
"start": 194,
"tag": "IP_ADDRESS",
"value": "27.0.0.1"
},
{
"context": "low 307 redirects', (done) ->\n (n... | node_modules/node-etcd/test/index.coffee | bugsysBugs/cote-workshop-secured | 0 | should = require 'should'
nock = require 'nock'
Etcd = require '../src/index.coffee'
# Set env var to skip timeouts
process.env.RUNNING_UNIT_TESTS = true
# Helpers
getNock = (host = 'http://127.0.0.1:4001') ->
nock host
# Tests for utility functions
describe 'Utility', ->
etcd = new Etcd
describe '#_stripSlashPrefix()', ->
it 'should strip prefix-/ from key', ->
etcd._stripSlashPrefix("/key/").should.equal("key/")
etcd._stripSlashPrefix("key/").should.equal("key/")
describe '#_prepareOpts()', ->
it 'should return default request options', ->
etcd._prepareOpts('keypath/key').should.containEql {
json: true
path: '/v2/keypath/key'
}
describe 'Basic functions', ->
etcd = new Etcd
checkVal = (done) ->
(err, val) ->
val.should.containEql { value: "value" }
done err, val
describe '#get()', ->
it 'should return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.get('/v2/keys/key?recursive=true')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', { recursive: true }, checkVal done
it 'should callback with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
etcd.get 'key', (err, val) ->
err.should.be.instanceOf Error
err.error.errorCode.should.equal 100
err.message.should.equal "Key not found"
done()
describe '#getSync()', ->
it 'should synchronously return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
val = etcd.getSync 'key'
doneCheck = checkVal done
doneCheck val.err, val.body
it 'should synchronously return with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
val = etcd.getSync 'key'
val.err.should.be.instanceOf Error
val.err.error.errorCode.should.equal 100
val.err.message.should.equal "Key not found"
done()
describe '#set()', ->
it 'should put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
etcd.set 'key', 'value', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.set 'key', 'value', { prevValue: "oldvalue" }, checkVal done
it 'should follow 307 redirects', (done) ->
(nock 'http://127.0.0.1:4002')
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
(nock 'http://127.0.0.1:4001')
.put('/v2/keys/key', { value: "value" })
.reply(307, "", { location: "http://127.0.0.1:4002/v2/keys/key" })
etcd.set 'key', 'value', checkVal done
describe '#setSync()', ->
it 'should synchronously put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
val = etcd.setSync 'key', 'value'
doneCheck = checkVal done
doneCheck val.err, val.body
describe '#create()', ->
it 'should post value to dir', (done) ->
getNock()
.post('/v2/keys/dir', { value: "value" })
.reply(200, '{"action":"create", "node":{"key":"/dir/2"}}')
etcd.create 'dir', 'value', (err, val) ->
val.should.containEql { action: "create" }
done err, val
describe '#post()', ->
it 'should post value to key', (done) ->
getNock().post('/v2/keys/key', { value: "value" }).reply(200)
etcd.post 'key', 'value', done
describe '#compareAndSwap()', ->
it 'should set using prevValue', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.compareAndSwap 'key', 'value', 'oldvalue', checkVal done
it 'has alias testAndSet', ->
etcd.testAndSet.should.equal etcd.testAndSet
describe '#compareAndDelete', ->
it 'should delete using prevValue', (done) ->
getNock().delete('/v2/keys/key?prevValue=oldvalue').reply(200)
etcd.compareAndDelete 'key', 'oldvalue', done
it 'has alias testAndDelete', ->
etcd.compareAndDelete.should.equal etcd.testAndDelete
describe '#mkdir()', ->
it 'should create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
etcd.mkdir 'key', (err, val) ->
val.should.containEql {action: "create"}
val.node.should.containEql {key: "/key"}
val.node.should.containEql {dir: true}
done()
describe '#mkdirSync()', ->
it 'should synchronously create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
val = etcd.mkdirSync 'key'
val.body.should.containEql {action: "create"}
val.body.node.should.containEql {key: "/key"}
val.body.node.should.containEql {dir: true}
done()
describe '#rmdir()', ->
it 'should remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true').reply(200)
etcd.rmdir 'key', done
describe '#rmdirSync()', ->
it 'should synchronously remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true')
.reply(200, '{"action":"delete","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":3}}')
val = etcd.rmdirSync 'key'
val.body.should.containEql {action: "delete"}
val.body.node.should.containEql {dir: true}
done()
describe '#del()', ->
it 'should delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key').reply(200)
etcd.del 'key', done
describe '#delSync()', ->
it 'should synchronously delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key2').reply(200, '{"action":"delete"}')
val = etcd.delSync 'key2'
val.body.should.containEql {action: "delete"}
done()
describe '#watch()', ->
it 'should do a get with wait=true', (done) ->
getNock()
.get('/v2/keys/key?wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watch 'key', checkVal done
describe '#watchIndex()', ->
it 'should do a get with wait=true and waitIndex=x', (done) ->
getNock()
.get('/v2/keys/key?waitIndex=1&wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watchIndex 'key', 1, checkVal done
describe '#raw()', ->
it 'should use provided method', (done) ->
getNock().patch('/key').reply(200, 'ok')
etcd.raw 'PATCH', 'key', null, {}, done
it 'should send provided value', (done) ->
getNock().post('/key', { value: "value" }).reply(200, 'ok')
etcd.raw 'POST', 'key', "value", {}, done
it 'should call cb on value from etcd', (done) ->
getNock().get('/key').reply(200, 'value')
etcd.raw 'GET', 'key', null, {}, (err, val) ->
val.should.equal 'value'
done err, val
describe '#machines()', ->
it 'should ask etcd for connected machines', (done) ->
getNock().get('/v2/keys/_etcd/machines').reply(200, '{"value":"value"}')
etcd.machines checkVal done
describe '#leader()', ->
it 'should ask etcd for leader', (done) ->
getNock().get('/v2/leader').reply(200, '{"value":"value"}')
etcd.leader checkVal done
describe '#leaderStats()', ->
it 'should ask etcd for statistics for leader', (done) ->
getNock().get('/v2/stats/leader').reply(200, '{"value":"value"}')
etcd.leaderStats checkVal done
describe '#selfStats()', ->
it 'should ask etcd for statistics for connected server', (done) ->
getNock().get('/v2/stats/self').reply(200, '{"value":"value"}')
etcd.selfStats checkVal done
describe '#version()', ->
it 'should ask etcd for version', (done) ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd.version (err, val) ->
val.should.equal 'etcd v0.1.0-8-gaad1626'
done err, val
describe 'SSL support', ->
it 'should use https url if sslopts is given', ->
etcdssl = new Etcd 'localhost', '4001', {}
opt = etcdssl._prepareOpts 'path'
opt.serverprotocol.should.equal "https"
it 'should set ca if ca is given', ->
etcdsslca = new Etcd 'localhost', '4001', {ca: ['ca']}
opt = etcdsslca._prepareOpts 'path'
should.exist opt.agentOptions
should.exist opt.agentOptions.ca
opt.agentOptions.ca.should.eql ['ca']
it 'should connect to https if sslopts is given', (done) ->
getNock('https://localhost:4001')
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcdssl = new Etcd ['localhost:4001'], {ca: ['ca']}
etcdssl.get 'key', done
describe 'Cancellation Token', ->
beforeEach () ->
nock.cleanAll()
it 'should return token on request', ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd = new Etcd
token = etcd.version()
token.abort.should.be.a.function
token.isAborted().should.be.false
it 'should stop execution on abort', (done) ->
http = getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd = new Etcd '127.0.0.1', 4001
token = etcd.version () -> throw new Error "Version call should have been aborted"
token.abort()
etcd.get 'key', () ->
http.isDone().should.be.true
done()
describe 'Multiserver/Cluster support', ->
beforeEach () ->
nock.cleanAll()
it 'should accept list of servers in constructor', ->
etcd = new Etcd ['localhost:4001', 'localhost:4002']
etcd.getHosts().should.eql ['localhost:4001', 'localhost:4002']
it 'should accept host and port in constructor', ->
etcd = new Etcd 'localhost', 4001
etcd.getHosts().should.eql ['localhost:4001']
it 'should try next server in list on http error', (done) ->
path = '/v2/keys/foo'
response = '{"action":"GET","key":"/key","value":"value","index":1}'
handler = (uri) ->
nock.cleanAll()
getNock('http://s1').get(path).reply(200, response)
getNock('http://s2').get(path).reply(200, response)
return {}
getNock('http://s1').get(path).reply(500, handler)
getNock('http://s2').get(path).reply(500, handler)
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
res.value.should.eql 'value'
done()
it 'should callback error if all servers failed', (done) ->
path = '/v2/keys/foo'
getNock('http://s1').get(path).reply(500, {})
getNock('http://s2').get(path).reply(500, {})
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
err.should.be.an.instanceOf Error
err.errors.should.have.lengthOf 2
done()
describe 'when cluster is doing leader elect', () ->
it 'should retry on connection refused', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', (err) ->
err.errors.length.should.be.exactly 12
token.errors.length.should.be.exactly 12
token.retries.should.be.exactly 3
done()
it 'should allow maxRetries to control number of retries', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', { maxRetries: 1 }, (err) ->
err.errors.length.should.be.exactly 6
token.retries.should.be.exactly 1
done()
| 193695 | should = require 'should'
nock = require 'nock'
Etcd = require '../src/index.coffee'
# Set env var to skip timeouts
process.env.RUNNING_UNIT_TESTS = true
# Helpers
getNock = (host = 'http://1192.168.127.12:4001') ->
nock host
# Tests for utility functions
describe 'Utility', ->
etcd = new Etcd
describe '#_stripSlashPrefix()', ->
it 'should strip prefix-/ from key', ->
etcd._stripSlashPrefix("/key/").should.equal("key/")
etcd._stripSlashPrefix("key/").should.equal("key/")
describe '#_prepareOpts()', ->
it 'should return default request options', ->
etcd._prepareOpts('keypath/key').should.containEql {
json: true
path: '/v2/keypath/key'
}
describe 'Basic functions', ->
etcd = new Etcd
checkVal = (done) ->
(err, val) ->
val.should.containEql { value: "value" }
done err, val
describe '#get()', ->
it 'should return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.get('/v2/keys/key?recursive=true')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', { recursive: true }, checkVal done
it 'should callback with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
etcd.get 'key', (err, val) ->
err.should.be.instanceOf Error
err.error.errorCode.should.equal 100
err.message.should.equal "Key not found"
done()
describe '#getSync()', ->
it 'should synchronously return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
val = etcd.getSync 'key'
doneCheck = checkVal done
doneCheck val.err, val.body
it 'should synchronously return with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
val = etcd.getSync 'key'
val.err.should.be.instanceOf Error
val.err.error.errorCode.should.equal 100
val.err.message.should.equal "Key not found"
done()
describe '#set()', ->
it 'should put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
etcd.set 'key', 'value', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.set 'key', 'value', { prevValue: "oldvalue" }, checkVal done
it 'should follow 307 redirects', (done) ->
(nock 'http://127.0.0.1:4002')
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
(nock 'http://127.0.0.1:4001')
.put('/v2/keys/key', { value: "value" })
.reply(307, "", { location: "http://127.0.0.1:4002/v2/keys/key" })
etcd.set 'key', 'value', checkVal done
describe '#setSync()', ->
it 'should synchronously put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
val = etcd.setSync 'key', 'value'
doneCheck = checkVal done
doneCheck val.err, val.body
describe '#create()', ->
it 'should post value to dir', (done) ->
getNock()
.post('/v2/keys/dir', { value: "value" })
.reply(200, '{"action":"create", "node":{"key":"/dir/2"}}')
etcd.create 'dir', 'value', (err, val) ->
val.should.containEql { action: "create" }
done err, val
describe '#post()', ->
it 'should post value to key', (done) ->
getNock().post('/v2/keys/key', { value: "value" }).reply(200)
etcd.post 'key', 'value', done
describe '#compareAndSwap()', ->
it 'should set using prevValue', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.compareAndSwap 'key', 'value', 'oldvalue', checkVal done
it 'has alias testAndSet', ->
etcd.testAndSet.should.equal etcd.testAndSet
describe '#compareAndDelete', ->
it 'should delete using prevValue', (done) ->
getNock().delete('/v2/keys/key?prevValue=oldvalue').reply(200)
etcd.compareAndDelete 'key', 'oldvalue', done
it 'has alias testAndDelete', ->
etcd.compareAndDelete.should.equal etcd.testAndDelete
describe '#mkdir()', ->
it 'should create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
etcd.mkdir 'key', (err, val) ->
val.should.containEql {action: "create"}
val.node.should.containEql {key: "/key"}
val.node.should.containEql {dir: true}
done()
describe '#mkdirSync()', ->
it 'should synchronously create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
val = etcd.mkdirSync 'key'
val.body.should.containEql {action: "create"}
val.body.node.should.containEql {key: "/key"}
val.body.node.should.containEql {dir: true}
done()
describe '#rmdir()', ->
it 'should remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true').reply(200)
etcd.rmdir 'key', done
describe '#rmdirSync()', ->
it 'should synchronously remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true')
.reply(200, '{"action":"delete","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":3}}')
val = etcd.rmdirSync 'key'
val.body.should.containEql {action: "delete"}
val.body.node.should.containEql {dir: true}
done()
describe '#del()', ->
it 'should delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key').reply(200)
etcd.del 'key', done
describe '#delSync()', ->
it 'should synchronously delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key2').reply(200, '{"action":"delete"}')
val = etcd.delSync 'key2'
val.body.should.containEql {action: "delete"}
done()
describe '#watch()', ->
it 'should do a get with wait=true', (done) ->
getNock()
.get('/v2/keys/key?wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watch 'key', checkVal done
describe '#watchIndex()', ->
it 'should do a get with wait=true and waitIndex=x', (done) ->
getNock()
.get('/v2/keys/key?waitIndex=1&wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watchIndex 'key', 1, checkVal done
describe '#raw()', ->
it 'should use provided method', (done) ->
getNock().patch('/key').reply(200, 'ok')
etcd.raw 'PATCH', 'key', null, {}, done
it 'should send provided value', (done) ->
getNock().post('/key', { value: "value" }).reply(200, 'ok')
etcd.raw 'POST', 'key', "value", {}, done
it 'should call cb on value from etcd', (done) ->
getNock().get('/key').reply(200, 'value')
etcd.raw 'GET', 'key', null, {}, (err, val) ->
val.should.equal 'value'
done err, val
describe '#machines()', ->
it 'should ask etcd for connected machines', (done) ->
getNock().get('/v2/keys/_etcd/machines').reply(200, '{"value":"value"}')
etcd.machines checkVal done
describe '#leader()', ->
it 'should ask etcd for leader', (done) ->
getNock().get('/v2/leader').reply(200, '{"value":"value"}')
etcd.leader checkVal done
describe '#leaderStats()', ->
it 'should ask etcd for statistics for leader', (done) ->
getNock().get('/v2/stats/leader').reply(200, '{"value":"value"}')
etcd.leaderStats checkVal done
describe '#selfStats()', ->
it 'should ask etcd for statistics for connected server', (done) ->
getNock().get('/v2/stats/self').reply(200, '{"value":"value"}')
etcd.selfStats checkVal done
describe '#version()', ->
it 'should ask etcd for version', (done) ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd.version (err, val) ->
val.should.equal 'etcd v0.1.0-8-gaad1626'
done err, val
describe 'SSL support', ->
it 'should use https url if sslopts is given', ->
etcdssl = new Etcd 'localhost', '4001', {}
opt = etcdssl._prepareOpts 'path'
opt.serverprotocol.should.equal "https"
it 'should set ca if ca is given', ->
etcdsslca = new Etcd 'localhost', '4001', {ca: ['ca']}
opt = etcdsslca._prepareOpts 'path'
should.exist opt.agentOptions
should.exist opt.agentOptions.ca
opt.agentOptions.ca.should.eql ['ca']
it 'should connect to https if sslopts is given', (done) ->
getNock('https://localhost:4001')
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcdssl = new Etcd ['localhost:4001'], {ca: ['ca']}
etcdssl.get 'key', done
describe 'Cancellation Token', ->
beforeEach () ->
nock.cleanAll()
it 'should return token on request', ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd = new Etcd
token = etcd.version()
token.abort.should.be.a.function
token.isAborted().should.be.false
it 'should stop execution on abort', (done) ->
http = getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd = new Etcd '127.0.0.1', 4001
token = etcd.version () -> throw new Error "Version call should have been aborted"
token.abort()
etcd.get 'key', () ->
http.isDone().should.be.true
done()
describe 'Multiserver/Cluster support', ->
beforeEach () ->
nock.cleanAll()
it 'should accept list of servers in constructor', ->
etcd = new Etcd ['localhost:4001', 'localhost:4002']
etcd.getHosts().should.eql ['localhost:4001', 'localhost:4002']
it 'should accept host and port in constructor', ->
etcd = new Etcd 'localhost', 4001
etcd.getHosts().should.eql ['localhost:4001']
it 'should try next server in list on http error', (done) ->
path = '/v2/keys/foo'
response = '{"action":"GET","key":"/key","value":"value","index":1}'
handler = (uri) ->
nock.cleanAll()
getNock('http://s1').get(path).reply(200, response)
getNock('http://s2').get(path).reply(200, response)
return {}
getNock('http://s1').get(path).reply(500, handler)
getNock('http://s2').get(path).reply(500, handler)
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
res.value.should.eql 'value'
done()
it 'should callback error if all servers failed', (done) ->
path = '/v2/keys/foo'
getNock('http://s1').get(path).reply(500, {})
getNock('http://s2').get(path).reply(500, {})
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
err.should.be.an.instanceOf Error
err.errors.should.have.lengthOf 2
done()
describe 'when cluster is doing leader elect', () ->
it 'should retry on connection refused', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', (err) ->
err.errors.length.should.be.exactly 12
token.errors.length.should.be.exactly 12
token.retries.should.be.exactly 3
done()
it 'should allow maxRetries to control number of retries', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', { maxRetries: 1 }, (err) ->
err.errors.length.should.be.exactly 6
token.retries.should.be.exactly 1
done()
| true | should = require 'should'
nock = require 'nock'
Etcd = require '../src/index.coffee'
# Set env var to skip timeouts
process.env.RUNNING_UNIT_TESTS = true
# Helpers
getNock = (host = 'http://1PI:IP_ADDRESS:192.168.127.12END_PI:4001') ->
nock host
# Tests for utility functions
describe 'Utility', ->
etcd = new Etcd
describe '#_stripSlashPrefix()', ->
it 'should strip prefix-/ from key', ->
etcd._stripSlashPrefix("/key/").should.equal("key/")
etcd._stripSlashPrefix("key/").should.equal("key/")
describe '#_prepareOpts()', ->
it 'should return default request options', ->
etcd._prepareOpts('keypath/key').should.containEql {
json: true
path: '/v2/keypath/key'
}
describe 'Basic functions', ->
etcd = new Etcd
checkVal = (done) ->
(err, val) ->
val.should.containEql { value: "value" }
done err, val
describe '#get()', ->
it 'should return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.get('/v2/keys/key?recursive=true')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', { recursive: true }, checkVal done
it 'should callback with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
etcd.get 'key', (err, val) ->
err.should.be.instanceOf Error
err.error.errorCode.should.equal 100
err.message.should.equal "Key not found"
done()
describe '#getSync()', ->
it 'should synchronously return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
val = etcd.getSync 'key'
doneCheck = checkVal done
doneCheck val.err, val.body
it 'should synchronously return with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
val = etcd.getSync 'key'
val.err.should.be.instanceOf Error
val.err.error.errorCode.should.equal 100
val.err.message.should.equal "Key not found"
done()
describe '#set()', ->
it 'should put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
etcd.set 'key', 'value', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.set 'key', 'value', { prevValue: "oldvalue" }, checkVal done
it 'should follow 307 redirects', (done) ->
(nock 'http://127.0.0.1:4002')
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
(nock 'http://127.0.0.1:4001')
.put('/v2/keys/key', { value: "value" })
.reply(307, "", { location: "http://127.0.0.1:4002/v2/keys/key" })
etcd.set 'key', 'value', checkVal done
describe '#setSync()', ->
it 'should synchronously put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
val = etcd.setSync 'key', 'value'
doneCheck = checkVal done
doneCheck val.err, val.body
describe '#create()', ->
it 'should post value to dir', (done) ->
getNock()
.post('/v2/keys/dir', { value: "value" })
.reply(200, '{"action":"create", "node":{"key":"/dir/2"}}')
etcd.create 'dir', 'value', (err, val) ->
val.should.containEql { action: "create" }
done err, val
describe '#post()', ->
it 'should post value to key', (done) ->
getNock().post('/v2/keys/key', { value: "value" }).reply(200)
etcd.post 'key', 'value', done
describe '#compareAndSwap()', ->
it 'should set using prevValue', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.compareAndSwap 'key', 'value', 'oldvalue', checkVal done
it 'has alias testAndSet', ->
etcd.testAndSet.should.equal etcd.testAndSet
describe '#compareAndDelete', ->
it 'should delete using prevValue', (done) ->
getNock().delete('/v2/keys/key?prevValue=oldvalue').reply(200)
etcd.compareAndDelete 'key', 'oldvalue', done
it 'has alias testAndDelete', ->
etcd.compareAndDelete.should.equal etcd.testAndDelete
describe '#mkdir()', ->
it 'should create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
etcd.mkdir 'key', (err, val) ->
val.should.containEql {action: "create"}
val.node.should.containEql {key: "/key"}
val.node.should.containEql {dir: true}
done()
describe '#mkdirSync()', ->
it 'should synchronously create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
val = etcd.mkdirSync 'key'
val.body.should.containEql {action: "create"}
val.body.node.should.containEql {key: "/key"}
val.body.node.should.containEql {dir: true}
done()
describe '#rmdir()', ->
it 'should remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true').reply(200)
etcd.rmdir 'key', done
describe '#rmdirSync()', ->
it 'should synchronously remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true')
.reply(200, '{"action":"delete","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":3}}')
val = etcd.rmdirSync 'key'
val.body.should.containEql {action: "delete"}
val.body.node.should.containEql {dir: true}
done()
describe '#del()', ->
it 'should delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key').reply(200)
etcd.del 'key', done
describe '#delSync()', ->
it 'should synchronously delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key2').reply(200, '{"action":"delete"}')
val = etcd.delSync 'key2'
val.body.should.containEql {action: "delete"}
done()
describe '#watch()', ->
it 'should do a get with wait=true', (done) ->
getNock()
.get('/v2/keys/key?wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watch 'key', checkVal done
describe '#watchIndex()', ->
it 'should do a get with wait=true and waitIndex=x', (done) ->
getNock()
.get('/v2/keys/key?waitIndex=1&wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watchIndex 'key', 1, checkVal done
describe '#raw()', ->
it 'should use provided method', (done) ->
getNock().patch('/key').reply(200, 'ok')
etcd.raw 'PATCH', 'key', null, {}, done
it 'should send provided value', (done) ->
getNock().post('/key', { value: "value" }).reply(200, 'ok')
etcd.raw 'POST', 'key', "value", {}, done
it 'should call cb on value from etcd', (done) ->
getNock().get('/key').reply(200, 'value')
etcd.raw 'GET', 'key', null, {}, (err, val) ->
val.should.equal 'value'
done err, val
describe '#machines()', ->
it 'should ask etcd for connected machines', (done) ->
getNock().get('/v2/keys/_etcd/machines').reply(200, '{"value":"value"}')
etcd.machines checkVal done
describe '#leader()', ->
it 'should ask etcd for leader', (done) ->
getNock().get('/v2/leader').reply(200, '{"value":"value"}')
etcd.leader checkVal done
describe '#leaderStats()', ->
it 'should ask etcd for statistics for leader', (done) ->
getNock().get('/v2/stats/leader').reply(200, '{"value":"value"}')
etcd.leaderStats checkVal done
describe '#selfStats()', ->
it 'should ask etcd for statistics for connected server', (done) ->
getNock().get('/v2/stats/self').reply(200, '{"value":"value"}')
etcd.selfStats checkVal done
describe '#version()', ->
it 'should ask etcd for version', (done) ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd.version (err, val) ->
val.should.equal 'etcd v0.1.0-8-gaad1626'
done err, val
describe 'SSL support', ->
it 'should use https url if sslopts is given', ->
etcdssl = new Etcd 'localhost', '4001', {}
opt = etcdssl._prepareOpts 'path'
opt.serverprotocol.should.equal "https"
it 'should set ca if ca is given', ->
etcdsslca = new Etcd 'localhost', '4001', {ca: ['ca']}
opt = etcdsslca._prepareOpts 'path'
should.exist opt.agentOptions
should.exist opt.agentOptions.ca
opt.agentOptions.ca.should.eql ['ca']
it 'should connect to https if sslopts is given', (done) ->
getNock('https://localhost:4001')
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcdssl = new Etcd ['localhost:4001'], {ca: ['ca']}
etcdssl.get 'key', done
describe 'Cancellation Token', ->
beforeEach () ->
nock.cleanAll()
it 'should return token on request', ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd = new Etcd
token = etcd.version()
token.abort.should.be.a.function
token.isAborted().should.be.false
it 'should stop execution on abort', (done) ->
http = getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd = new Etcd '127.0.0.1', 4001
token = etcd.version () -> throw new Error "Version call should have been aborted"
token.abort()
etcd.get 'key', () ->
http.isDone().should.be.true
done()
describe 'Multiserver/Cluster support', ->
beforeEach () ->
nock.cleanAll()
it 'should accept list of servers in constructor', ->
etcd = new Etcd ['localhost:4001', 'localhost:4002']
etcd.getHosts().should.eql ['localhost:4001', 'localhost:4002']
it 'should accept host and port in constructor', ->
etcd = new Etcd 'localhost', 4001
etcd.getHosts().should.eql ['localhost:4001']
it 'should try next server in list on http error', (done) ->
path = '/v2/keys/foo'
response = '{"action":"GET","key":"/key","value":"value","index":1}'
handler = (uri) ->
nock.cleanAll()
getNock('http://s1').get(path).reply(200, response)
getNock('http://s2').get(path).reply(200, response)
return {}
getNock('http://s1').get(path).reply(500, handler)
getNock('http://s2').get(path).reply(500, handler)
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
res.value.should.eql 'value'
done()
it 'should callback error if all servers failed', (done) ->
path = '/v2/keys/foo'
getNock('http://s1').get(path).reply(500, {})
getNock('http://s2').get(path).reply(500, {})
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
err.should.be.an.instanceOf Error
err.errors.should.have.lengthOf 2
done()
describe 'when cluster is doing leader elect', () ->
it 'should retry on connection refused', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', (err) ->
err.errors.length.should.be.exactly 12
token.errors.length.should.be.exactly 12
token.retries.should.be.exactly 3
done()
it 'should allow maxRetries to control number of retries', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', { maxRetries: 1 }, (err) ->
err.errors.length.should.be.exactly 6
token.retries.should.be.exactly 1
done()
|
[
{
"context": "dminConfig =\n name: Config.name\n adminEmails: ['ghlndsl@126.com', 'sivagao@126.com']\n collections:\n Posts:\n ",
"end": 67,
"score": 0.9999264478683472,
"start": 52,
"tag": "EMAIL",
"value": "ghlndsl@126.com"
},
{
"context": ": Config.name\n adminEmails: ['gh... | lib/_config/admin_config.coffee | gaohailang/plaza-quiz | 0 | @AdminConfig =
name: Config.name
adminEmails: ['ghlndsl@126.com', 'sivagao@126.com']
collections:
Posts:
color: 'red'
icon: 'pencil'
extraFields: ['owner']
tableColumns: [
{ label: 'Title', name: 'title' }
{ label: 'User', name: 'author()', template: 'adminUserCell' }
]
Comments:
color: 'green'
icon: 'comments'
tableColumns: [
{ label: 'Content', name: 'content' }
{ label: 'Post', name: 'docTitle()', template: 'adminPostCell' }
{ label: 'User', name: 'author()', template: 'adminUserCell' }
]
extraFields: ['doc', 'owner']
children: [
{
find: (comment) ->
Posts.find comment.doc, limit: 1
}
{
find: (comment) ->
Meteor.users.find comment.owner, limit: 1
}
]
VvQuizs:
color: 'yellow'
icon: 'pencil'
tableColumns: [
{label: 'Title', name: 'quiz.title'},
{label: 'Type', name: 'quiz.type'}
]
templates:
edit:
name: "VonVonEdit"
data:
doc: Meteor.isClient && Session.get('admin_doc')
fields: ["quiz", "questions", "choices"]
dashboard:
homeUrl: '/dashboard'
autoForm:
omitFields: ['createdAt', 'updatedAt']
| 176187 | @AdminConfig =
name: Config.name
adminEmails: ['<EMAIL>', '<EMAIL>']
collections:
Posts:
color: 'red'
icon: 'pencil'
extraFields: ['owner']
tableColumns: [
{ label: 'Title', name: 'title' }
{ label: 'User', name: 'author()', template: 'adminUserCell' }
]
Comments:
color: 'green'
icon: 'comments'
tableColumns: [
{ label: 'Content', name: 'content' }
{ label: 'Post', name: 'docTitle()', template: 'adminPostCell' }
{ label: 'User', name: 'author()', template: 'adminUserCell' }
]
extraFields: ['doc', 'owner']
children: [
{
find: (comment) ->
Posts.find comment.doc, limit: 1
}
{
find: (comment) ->
Meteor.users.find comment.owner, limit: 1
}
]
VvQuizs:
color: 'yellow'
icon: 'pencil'
tableColumns: [
{label: 'Title', name: 'quiz.title'},
{label: 'Type', name: 'quiz.type'}
]
templates:
edit:
name: "VonVonEdit"
data:
doc: Meteor.isClient && Session.get('admin_doc')
fields: ["quiz", "questions", "choices"]
dashboard:
homeUrl: '/dashboard'
autoForm:
omitFields: ['createdAt', 'updatedAt']
| true | @AdminConfig =
name: Config.name
adminEmails: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI']
collections:
Posts:
color: 'red'
icon: 'pencil'
extraFields: ['owner']
tableColumns: [
{ label: 'Title', name: 'title' }
{ label: 'User', name: 'author()', template: 'adminUserCell' }
]
Comments:
color: 'green'
icon: 'comments'
tableColumns: [
{ label: 'Content', name: 'content' }
{ label: 'Post', name: 'docTitle()', template: 'adminPostCell' }
{ label: 'User', name: 'author()', template: 'adminUserCell' }
]
extraFields: ['doc', 'owner']
children: [
{
find: (comment) ->
Posts.find comment.doc, limit: 1
}
{
find: (comment) ->
Meteor.users.find comment.owner, limit: 1
}
]
VvQuizs:
color: 'yellow'
icon: 'pencil'
tableColumns: [
{label: 'Title', name: 'quiz.title'},
{label: 'Type', name: 'quiz.type'}
]
templates:
edit:
name: "VonVonEdit"
data:
doc: Meteor.isClient && Session.get('admin_doc')
fields: ["quiz", "questions", "choices"]
dashboard:
homeUrl: '/dashboard'
autoForm:
omitFields: ['createdAt', 'updatedAt']
|
[
{
"context": "scription: Display 5 latest google tasks\n# Author: Ryuei Sasaki\n# Github: https://github.com/louixs/\n\n# Dependenc",
"end": 247,
"score": 0.9998798370361328,
"start": 235,
"tag": "NAME",
"value": "Ryuei Sasaki"
},
{
"context": "Author: Ryuei Sasaki\n# Github: https:/... | tasks.widget/tasks.coffee | louixs/ubersicht_tasks | 2 | # Todo
# toggle between different mode
# latest x tasks based on updated date - done
# tasks from certain list based on list names
# Name: Google Tasks for Übersicht using oauth2
# Description: Display 5 latest google tasks
# Author: Ryuei Sasaki
# Github: https://github.com/louixs/
# Dependencies. Best to leave them alone.
_ = require('./assets/lib/underscore.js');
GOOGLE_APP:"tasks"
command: """
if [ ! -d assets ]; then
cd "$PWD"/tasks.widget
"$PWD"/assets/run.sh
else
assets/run.sh
fi
"""
#==== Google API Credentials ====
# Fill in your Google API cleint id and client secret
# Save this file and a browser should launch asking you to allow widget to access google calendar
# Once you allow, you will be presented with your Authorization code. Please fill it in and save the file.
# Your calendar events should now show. If not try refreshing Übersicht.
# If you don't have your client id and/or client secret, please follow the steps in the Setup section in README.md.
CLIENT_ID:""
CLIENT_SECRET:""
AUTHORIZATION_CODE:""
# Enter the number of tasks you want to display
TASK_COUNT:"7"
TASKS_TITLE: "-- To do --"
refreshFrequency: "30m" #30 min.
#Other permitted formats: '2 days', '1d', '10h', '2.5 hrs', '2h', '1m', or '5s'
render: (output) -> """
<div class="container"></div>
"""
update: (output,domEl)->
# @run """
# if [ ! -e getTasks.sh ]; then
# "$PWD/tasks.widget/getTasks.sh"
# else
# "$PWD/getTasks.sh"
# fi
# """, (err, output)->
titleToAdd= @TASKS_TITLE
# Clear DOM upon every update to avoid duplicated display
$(domEl).find(".container").empty()
show=(item)->
console.log(item)
tasksArr=output.split(",")
cleanArr=(arr)-> _.map(arr, (item)-> item.trim())
cleanedTasksArr=cleanArr(tasksArr)
makeHTMLTitle=(title)->
return titleToAdd="<div class=title>#{title}</div>"
addArrToDom = (title,arr)->
titleToAdd=makeHTMLTitle(title)
$(domEl).find(".container").append(titleToAdd)
for element,index in arr
itemToAdd="<div class=item> • #{arr[index]}</div>"
$(domEl).find(".container").append(itemToAdd)
addArrToDomFilterZero=(title, arr)->
arrSize=_.size(arr)
if arrSize is 0
addToDom(title, "No task")
else
addArrToDom(title, arr)
makeDomClassP=(text)->
"<div class=p>#{text}</p>"
addTasksToDom=()->
addArrToDomFilterZero(titleToAdd, cleanedTasksArr)
addTasksToDom()
# the CSS style for this widget, written using Stylus
# (http://learnboost.github.io/stylus/)
style: """
//-webkit-backdrop-filter: blur(20px)
@font-face
font-family: 'hack'
src: url('assets/lib/hack.ttf')
font-family: hack, Andale Mono, Melno, Monaco, Courier, Helvetica Neue, Osaka
color: #df740c //#6fc3df
font-family: hack
font-weight: 100
font-size: 11px
top: 40%
left: 2%
line-height: 1.5
//margin-left: -40px
//padding: 120px 20px 20px
.title
color: #ffe64d //#6fc3df
text-shadow: 0 0 1px rgba(#000, 0.5)
"""
| 2199 | # Todo
# toggle between different mode
# latest x tasks based on updated date - done
# tasks from certain list based on list names
# Name: Google Tasks for Übersicht using oauth2
# Description: Display 5 latest google tasks
# Author: <NAME>
# Github: https://github.com/louixs/
# Dependencies. Best to leave them alone.
_ = require('./assets/lib/underscore.js');
GOOGLE_APP:"tasks"
command: """
if [ ! -d assets ]; then
cd "$PWD"/tasks.widget
"$PWD"/assets/run.sh
else
assets/run.sh
fi
"""
#==== Google API Credentials ====
# Fill in your Google API cleint id and client secret
# Save this file and a browser should launch asking you to allow widget to access google calendar
# Once you allow, you will be presented with your Authorization code. Please fill it in and save the file.
# Your calendar events should now show. If not try refreshing Übersicht.
# If you don't have your client id and/or client secret, please follow the steps in the Setup section in README.md.
CLIENT_ID:""
CLIENT_SECRET:""
AUTHORIZATION_CODE:""
# Enter the number of tasks you want to display
TASK_COUNT:"7"
TASKS_TITLE: "-- To do --"
refreshFrequency: "30m" #30 min.
#Other permitted formats: '2 days', '1d', '10h', '2.5 hrs', '2h', '1m', or '5s'
render: (output) -> """
<div class="container"></div>
"""
update: (output,domEl)->
# @run """
# if [ ! -e getTasks.sh ]; then
# "$PWD/tasks.widget/getTasks.sh"
# else
# "$PWD/getTasks.sh"
# fi
# """, (err, output)->
titleToAdd= @TASKS_TITLE
# Clear DOM upon every update to avoid duplicated display
$(domEl).find(".container").empty()
show=(item)->
console.log(item)
tasksArr=output.split(",")
cleanArr=(arr)-> _.map(arr, (item)-> item.trim())
cleanedTasksArr=cleanArr(tasksArr)
makeHTMLTitle=(title)->
return titleToAdd="<div class=title>#{title}</div>"
addArrToDom = (title,arr)->
titleToAdd=makeHTMLTitle(title)
$(domEl).find(".container").append(titleToAdd)
for element,index in arr
itemToAdd="<div class=item> • #{arr[index]}</div>"
$(domEl).find(".container").append(itemToAdd)
addArrToDomFilterZero=(title, arr)->
arrSize=_.size(arr)
if arrSize is 0
addToDom(title, "No task")
else
addArrToDom(title, arr)
makeDomClassP=(text)->
"<div class=p>#{text}</p>"
addTasksToDom=()->
addArrToDomFilterZero(titleToAdd, cleanedTasksArr)
addTasksToDom()
# the CSS style for this widget, written using Stylus
# (http://learnboost.github.io/stylus/)
style: """
//-webkit-backdrop-filter: blur(20px)
@font-face
font-family: 'hack'
src: url('assets/lib/hack.ttf')
font-family: hack, Andale Mono, Melno, Monaco, Courier, Helvetica Neue, Osaka
color: #df740c //#6fc3df
font-family: hack
font-weight: 100
font-size: 11px
top: 40%
left: 2%
line-height: 1.5
//margin-left: -40px
//padding: 120px 20px 20px
.title
color: #ffe64d //#6fc3df
text-shadow: 0 0 1px rgba(#000, 0.5)
"""
| true | # Todo
# toggle between different mode
# latest x tasks based on updated date - done
# tasks from certain list based on list names
# Name: Google Tasks for Übersicht using oauth2
# Description: Display 5 latest google tasks
# Author: PI:NAME:<NAME>END_PI
# Github: https://github.com/louixs/
# Dependencies. Best to leave them alone.
_ = require('./assets/lib/underscore.js');
GOOGLE_APP:"tasks"
command: """
if [ ! -d assets ]; then
cd "$PWD"/tasks.widget
"$PWD"/assets/run.sh
else
assets/run.sh
fi
"""
#==== Google API Credentials ====
# Fill in your Google API cleint id and client secret
# Save this file and a browser should launch asking you to allow widget to access google calendar
# Once you allow, you will be presented with your Authorization code. Please fill it in and save the file.
# Your calendar events should now show. If not try refreshing Übersicht.
# If you don't have your client id and/or client secret, please follow the steps in the Setup section in README.md.
CLIENT_ID:""
CLIENT_SECRET:""
AUTHORIZATION_CODE:""
# Enter the number of tasks you want to display
TASK_COUNT:"7"
TASKS_TITLE: "-- To do --"
refreshFrequency: "30m" #30 min.
#Other permitted formats: '2 days', '1d', '10h', '2.5 hrs', '2h', '1m', or '5s'
render: (output) -> """
<div class="container"></div>
"""
update: (output,domEl)->
# @run """
# if [ ! -e getTasks.sh ]; then
# "$PWD/tasks.widget/getTasks.sh"
# else
# "$PWD/getTasks.sh"
# fi
# """, (err, output)->
titleToAdd= @TASKS_TITLE
# Clear DOM upon every update to avoid duplicated display
$(domEl).find(".container").empty()
show=(item)->
console.log(item)
tasksArr=output.split(",")
cleanArr=(arr)-> _.map(arr, (item)-> item.trim())
cleanedTasksArr=cleanArr(tasksArr)
makeHTMLTitle=(title)->
return titleToAdd="<div class=title>#{title}</div>"
addArrToDom = (title,arr)->
titleToAdd=makeHTMLTitle(title)
$(domEl).find(".container").append(titleToAdd)
for element,index in arr
itemToAdd="<div class=item> • #{arr[index]}</div>"
$(domEl).find(".container").append(itemToAdd)
addArrToDomFilterZero=(title, arr)->
arrSize=_.size(arr)
if arrSize is 0
addToDom(title, "No task")
else
addArrToDom(title, arr)
makeDomClassP=(text)->
"<div class=p>#{text}</p>"
addTasksToDom=()->
addArrToDomFilterZero(titleToAdd, cleanedTasksArr)
addTasksToDom()
# the CSS style for this widget, written using Stylus
# (http://learnboost.github.io/stylus/)
style: """
//-webkit-backdrop-filter: blur(20px)
@font-face
font-family: 'hack'
src: url('assets/lib/hack.ttf')
font-family: hack, Andale Mono, Melno, Monaco, Courier, Helvetica Neue, Osaka
color: #df740c //#6fc3df
font-family: hack
font-weight: 100
font-size: 11px
top: 40%
left: 2%
line-height: 1.5
//margin-left: -40px
//padding: 120px 20px 20px
.title
color: #ffe64d //#6fc3df
text-shadow: 0 0 1px rgba(#000, 0.5)
"""
|
[
{
"context": " target = 'published'\n key = 'viewInstance'\n\n if widget.isPreview\n target = ",
"end": 754,
"score": 0.9888869524002075,
"start": 742,
"tag": "KEY",
"value": "viewInstance"
},
{
"context": "\n target = 'preview'\n ... | client/app/lib/widgetcontroller.coffee | ezgikaysi/koding | 1 | htmlencode = require 'htmlencode'
kookies = require 'kookies'
remote = require('./remote').getInstance()
kd = require 'kd'
KDController = kd.Controller
module.exports = class WidgetController extends KDController
constructor: (options = {}, data) ->
super options, data
@placeholders = {}
@widgets =
preview : {}
published : {}
@registerPlaceholders()
@fetchWidgets()
fetchWidgets: ->
query =
partialType : 'WIDGET'
'$or' : [
{ isActive: yes }
{ isPreview: yes }
]
remote.api.JCustomPartials.some query, {}, (err, widgets) =>
return unless widgets or err
for widget in widgets
target = 'published'
key = 'viewInstance'
if widget.isPreview
target = 'preview'
key = 'previewInstance'
@widgets[target][widget[key]] = widget
registerPlaceholders: ->
@placeholders.ActivityTop = { title: 'Activity Top', key: 'ActivityTop' }
@placeholders.ActivityLeft = { title: 'Activity Left', key: 'ActivityLeft' }
getPlaceholders: ->
return @placeholders
showWidgets: (widgets) ->
isPreviewMode = kookies.get 'custom-partials-preview-mode'
targetKey = if isPreviewMode then 'preview' else 'published'
for widget in widgets
{ view, key } = widget
widgetData = @widgets[targetKey][key]
hasPlaceholder = @placeholders[key]
if view and key and widgetData and hasPlaceholder
try
{ css, js } = widgetData.partial
@evalJS view, js if js
@appendCSS css, key if css
catch
kd.warn "#{key} widget failed to load"
evalJS: (view, js) ->
jsCode = "viewId = '#{view.getId()}'; #{js}"
eval htmlencode.htmlDecode jsCode
appendCSS: (css, key) ->
domId = "#{key}WidgetStyle"
oldElement = global.document.getElementById domId
global.document.head.removeChild oldElement if oldElement
tag = global.document.createElement 'style'
tag.id = domId
tag.innerHTML = htmlencode.htmlDecode css
global.document.head.appendChild tag
| 207481 | htmlencode = require 'htmlencode'
kookies = require 'kookies'
remote = require('./remote').getInstance()
kd = require 'kd'
KDController = kd.Controller
module.exports = class WidgetController extends KDController
constructor: (options = {}, data) ->
super options, data
@placeholders = {}
@widgets =
preview : {}
published : {}
@registerPlaceholders()
@fetchWidgets()
fetchWidgets: ->
query =
partialType : 'WIDGET'
'$or' : [
{ isActive: yes }
{ isPreview: yes }
]
remote.api.JCustomPartials.some query, {}, (err, widgets) =>
return unless widgets or err
for widget in widgets
target = 'published'
key = '<KEY>'
if widget.isPreview
target = 'preview'
key = '<KEY>'
@widgets[target][widget[key]] = widget
registerPlaceholders: ->
@placeholders.ActivityTop = { title: 'Activity Top', key: '<KEY>Top' }
@placeholders.ActivityLeft = { title: 'Activity Left', key: 'ActivityLeft' }
getPlaceholders: ->
return @placeholders
showWidgets: (widgets) ->
isPreviewMode = kookies.get 'custom-partials-preview-mode'
targetKey = if isPreviewMode then 'preview' else 'published'
for widget in widgets
{ view, key } = widget
widgetData = @widgets[targetKey][key]
hasPlaceholder = @placeholders[key]
if view and key and widgetData and hasPlaceholder
try
{ css, js } = widgetData.partial
@evalJS view, js if js
@appendCSS css, key if css
catch
kd.warn "#{key} widget failed to load"
evalJS: (view, js) ->
jsCode = "viewId = '#{view.getId()}'; #{js}"
eval htmlencode.htmlDecode jsCode
appendCSS: (css, key) ->
domId = "#{key}WidgetStyle"
oldElement = global.document.getElementById domId
global.document.head.removeChild oldElement if oldElement
tag = global.document.createElement 'style'
tag.id = domId
tag.innerHTML = htmlencode.htmlDecode css
global.document.head.appendChild tag
| true | htmlencode = require 'htmlencode'
kookies = require 'kookies'
remote = require('./remote').getInstance()
kd = require 'kd'
KDController = kd.Controller
module.exports = class WidgetController extends KDController
constructor: (options = {}, data) ->
super options, data
@placeholders = {}
@widgets =
preview : {}
published : {}
@registerPlaceholders()
@fetchWidgets()
fetchWidgets: ->
query =
partialType : 'WIDGET'
'$or' : [
{ isActive: yes }
{ isPreview: yes }
]
remote.api.JCustomPartials.some query, {}, (err, widgets) =>
return unless widgets or err
for widget in widgets
target = 'published'
key = 'PI:KEY:<KEY>END_PI'
if widget.isPreview
target = 'preview'
key = 'PI:KEY:<KEY>END_PI'
@widgets[target][widget[key]] = widget
registerPlaceholders: ->
@placeholders.ActivityTop = { title: 'Activity Top', key: 'PI:KEY:<KEY>END_PITop' }
@placeholders.ActivityLeft = { title: 'Activity Left', key: 'ActivityLeft' }
getPlaceholders: ->
return @placeholders
showWidgets: (widgets) ->
isPreviewMode = kookies.get 'custom-partials-preview-mode'
targetKey = if isPreviewMode then 'preview' else 'published'
for widget in widgets
{ view, key } = widget
widgetData = @widgets[targetKey][key]
hasPlaceholder = @placeholders[key]
if view and key and widgetData and hasPlaceholder
try
{ css, js } = widgetData.partial
@evalJS view, js if js
@appendCSS css, key if css
catch
kd.warn "#{key} widget failed to load"
evalJS: (view, js) ->
jsCode = "viewId = '#{view.getId()}'; #{js}"
eval htmlencode.htmlDecode jsCode
appendCSS: (css, key) ->
domId = "#{key}WidgetStyle"
oldElement = global.document.getElementById domId
global.document.head.removeChild oldElement if oldElement
tag = global.document.createElement 'style'
tag.id = domId
tag.innerHTML = htmlencode.htmlDecode css
global.document.head.appendChild tag
|
[
{
"context": "operty('url').\n to.equal \"#{api_url}?key=blahblah\"\n\n describe '#call', ->\n linkshrink = new Lin",
"end": 1109,
"score": 0.7796754240989685,
"start": 1105,
"tag": "KEY",
"value": "blah"
}
] | test/linkshrink_test.coffee | jonahoffline/node-linkshrink | 0 | {LinkShrink} = require '../index'
expect = require('chai').expect
describe 'LinkShrink', ->
it '#new', ->
linkshrink = new LinkShrink('something')
expect(linkshrink).to.have.property('api_key').to.equal 'something'
it '#defaults', ->
linkshrink = new LinkShrink
expect(linkshrink).to.have.property('params').to.be.a('Object')
expect(linkshrink).to.have.property('api_key').to.be.a('String')
expect(linkshrink).to.have.property('api_key').to.not.be.empty
describe '#shrinkUrl', ->
linkshrink = new LinkShrink
long_url = 'http://www.google.com'
body_params = '{"longUrl":"http://www.google.com"}'
it 'adds longUrl to the body request', ->
linkshrink.shrinkUrl(long_url)
expect(linkshrink).to.have.property('params').property('body').
to.equal body_params
describe '#configureApi', ->
linkshrink = new LinkShrink('blahblah')
api_url = 'https://www.googleapis.com/urlshortener/v1/url/'
it 'overrides default api url', ->
expect(linkshrink).to.have.property('params').property('url').
to.equal "#{api_url}?key=blahblah"
describe '#call', ->
linkshrink = new LinkShrink
long_url = 'http://www.google.com'
res = {
"kind": "urlshortener#url",
"id": "http://goo.gl/rjHP",
"longUrl": "http://www.google.com/"
}
it 'sends post request to API', ->
res = linkshrink.shrinkUrl(long_url)
expect(res).to.equal res
| 142354 | {LinkShrink} = require '../index'
expect = require('chai').expect
describe 'LinkShrink', ->
it '#new', ->
linkshrink = new LinkShrink('something')
expect(linkshrink).to.have.property('api_key').to.equal 'something'
it '#defaults', ->
linkshrink = new LinkShrink
expect(linkshrink).to.have.property('params').to.be.a('Object')
expect(linkshrink).to.have.property('api_key').to.be.a('String')
expect(linkshrink).to.have.property('api_key').to.not.be.empty
describe '#shrinkUrl', ->
linkshrink = new LinkShrink
long_url = 'http://www.google.com'
body_params = '{"longUrl":"http://www.google.com"}'
it 'adds longUrl to the body request', ->
linkshrink.shrinkUrl(long_url)
expect(linkshrink).to.have.property('params').property('body').
to.equal body_params
describe '#configureApi', ->
linkshrink = new LinkShrink('blahblah')
api_url = 'https://www.googleapis.com/urlshortener/v1/url/'
it 'overrides default api url', ->
expect(linkshrink).to.have.property('params').property('url').
to.equal "#{api_url}?key=blah<KEY>"
describe '#call', ->
linkshrink = new LinkShrink
long_url = 'http://www.google.com'
res = {
"kind": "urlshortener#url",
"id": "http://goo.gl/rjHP",
"longUrl": "http://www.google.com/"
}
it 'sends post request to API', ->
res = linkshrink.shrinkUrl(long_url)
expect(res).to.equal res
| true | {LinkShrink} = require '../index'
expect = require('chai').expect
describe 'LinkShrink', ->
it '#new', ->
linkshrink = new LinkShrink('something')
expect(linkshrink).to.have.property('api_key').to.equal 'something'
it '#defaults', ->
linkshrink = new LinkShrink
expect(linkshrink).to.have.property('params').to.be.a('Object')
expect(linkshrink).to.have.property('api_key').to.be.a('String')
expect(linkshrink).to.have.property('api_key').to.not.be.empty
describe '#shrinkUrl', ->
linkshrink = new LinkShrink
long_url = 'http://www.google.com'
body_params = '{"longUrl":"http://www.google.com"}'
it 'adds longUrl to the body request', ->
linkshrink.shrinkUrl(long_url)
expect(linkshrink).to.have.property('params').property('body').
to.equal body_params
describe '#configureApi', ->
linkshrink = new LinkShrink('blahblah')
api_url = 'https://www.googleapis.com/urlshortener/v1/url/'
it 'overrides default api url', ->
expect(linkshrink).to.have.property('params').property('url').
to.equal "#{api_url}?key=blahPI:KEY:<KEY>END_PI"
describe '#call', ->
linkshrink = new LinkShrink
long_url = 'http://www.google.com'
res = {
"kind": "urlshortener#url",
"id": "http://goo.gl/rjHP",
"longUrl": "http://www.google.com/"
}
it 'sends post request to API', ->
res = linkshrink.shrinkUrl(long_url)
expect(res).to.equal res
|
[
{
"context": "--------------------\\n\\n'\n res.write \"The name is Bond...hey, no, it is #{req.post['name'] or 'unknown'}",
"end": 1459,
"score": 0.9191706776618958,
"start": 1455,
"tag": "NAME",
"value": "Bond"
},
{
"context": "1], 'base64').toString().split ':'\n if usr is 'sa... | images/Postman.app/Contents/Resources/app/node_modules/node-simple-router/test/common/test_router.coffee | longjo/longjo.github.io | 7 | #!/usr/bin/env coffee
Router = require '../../lib/router'
http = require 'http'
router = Router(list_dir: true)
###
Example routes
###
#router.get "/", (req, res) ->
# res.end "Home"
router.get "/hello", (req, res) ->
res.end "Hello, World!, Hola, Mundo!"
router.get "/users", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end "<h1 style='color: navy; text-align: center;'>Active members registry</h1>"
router.post "/users", (req, res) ->
router.log "\n\nBody of request is: #{req.body.toString()}\nRequest content type is: #{req.headers['content-type']}"
router.log "\nRequest Headers"
router.log "#{key} = #{val}" for key, val of req.headers
router.log "\nRequest body object properties"
res.write "\nRequest body object properties\n"
try
router.log "#{key}: #{val}" for key, val of req.body
catch e
res.write "Looks like you did something dumb: #{e.toString()}\n"
for key, val of req.body
res.write "#{key} = #{val}\n"
res.end()
router.get "/users/:id", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end "<h1>User No: <span style='color: red;'>#{req.params.id}</span></h1>"
router.get "/crashit", (req, res) ->
throw new Error("Crashed on purpose...")
router.post "/showrequest", (req, res) ->
res.writeHead(200, {'Content-type': 'text/plain'})
res.write '-----------------------------------------------------------\n\n'
res.write "The name is Bond...hey, no, it is #{req.post['name'] or 'unknown'}\n"
res.write "And the age is #{req.post['age']}\n\n";
#res.write("And that is all, folks...")
for key, val of req
try
stri = "Request #{key} = #{JSON.stringify(val)}\n"
router.log stri unless not router.logging
res.write stri
catch e
res.write "NASTY ERROR: #{e.message}\n"
res.end()
router.get "/formrequest", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end """
<title>Request vars discovery</title>
<form action="/showrequest" method="post" enctype="application/x-www-form-urlencoded">
<p>Name:<input type="text" required="required" size="40" name="name" /></p>
<p>Age: <input type="number" required="required" size="4" name="age" /></p>
<p><input type="submit" value="Submit to /showrequest" /><input type="reset" value="Reset" /></p>
</form>
"""
# Proxy pass
router.get "/google", (req, res) ->
router.proxy_pass "http://www.google.com.ar", res
router.get "/testing", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org/", res
router.get "/testing/:route", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org/#{req.params.route}/", res
router.get "/shell", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org:10001", res
# End of proxy pass
#Auth
router.get "/login", (req, res) ->
require_credentials = ->
res.setHeader "WWW-Authenticate", 'Basic realm="node-simple-router"'
res.writeHead 401, 'Access denied', 'Content-type': 'text/html'
res.end()
console.log req.headers
console.log "----------------------------------------------------------------"
if not req.headers['authorization']
require_credentials()
else
console.log "req.headers['authorization'] = #{req.headers['authorization']}"
auth = req.headers['authorization'].split /\s+/
console.log "AUTH: #{auth[0] + ' - ' + auth[1]}"
[usr, pwd] = new Buffer(auth[1], 'base64').toString().split ':'
if usr is 'sandy' and pwd is 'ygnas'
res.writeHead 200, 'Content-type': 'text/plain'
res.write "usr: #{usr}\n"
res.write "pwd: #{pwd}\n"
res.end()
else
require_credentials()
#End of Auth
#SCGI
router.get "/scgi", (req, res) ->
router.scgi_pass '/tmp/node_scgi.sk', req, res
get_scgi = (req, res) ->
router.scgi_pass 26000, req, res
router.get "/scgiform", (req, res) ->
res.writeHead 200, 'Content-type': 'text/html'
res.end """
<title>SCGI Form</title>
<h3 style="text-align: center; color: #220088;">SCGI Form</h3><hr/>
<form action="/uwsgi" method="post">
<table>
<tr>
<td>Name</td>
<td style="text-align: right;"><input type="text" size="40" name="name" required="required" /></td>
<tr>
<tr>
<td>Age</td>
<td style="text-align: right;"><input type="number" size="4" name="age" /></td>
<tr>
<tr>
<td><input type="submit" value="Send data" /></td>
<td><input type="reset" value="Reset" /></td>
<tr>
</table>
</form>
"""
router.get "/uwsgi", get_scgi
router.post "/uwsgi", get_scgi
#End of SCGI
###
End of example routes
###
#Ok, just start the server!
argv = process.argv.slice 2
server = http.createServer router
server.on 'listening', ->
addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}
router.log "Serving web content at #{addr.address}:#{addr.port}"
process.on "SIGINT", ->
server.close()
router.log "\n Server shutting up...\n"
process.exit 0
server.listen if argv[0]? and not isNaN(parseInt(argv[0])) then parseInt(argv[0]) else 8000
| 46174 | #!/usr/bin/env coffee
Router = require '../../lib/router'
http = require 'http'
router = Router(list_dir: true)
###
Example routes
###
#router.get "/", (req, res) ->
# res.end "Home"
router.get "/hello", (req, res) ->
res.end "Hello, World!, Hola, Mundo!"
router.get "/users", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end "<h1 style='color: navy; text-align: center;'>Active members registry</h1>"
router.post "/users", (req, res) ->
router.log "\n\nBody of request is: #{req.body.toString()}\nRequest content type is: #{req.headers['content-type']}"
router.log "\nRequest Headers"
router.log "#{key} = #{val}" for key, val of req.headers
router.log "\nRequest body object properties"
res.write "\nRequest body object properties\n"
try
router.log "#{key}: #{val}" for key, val of req.body
catch e
res.write "Looks like you did something dumb: #{e.toString()}\n"
for key, val of req.body
res.write "#{key} = #{val}\n"
res.end()
router.get "/users/:id", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end "<h1>User No: <span style='color: red;'>#{req.params.id}</span></h1>"
router.get "/crashit", (req, res) ->
throw new Error("Crashed on purpose...")
router.post "/showrequest", (req, res) ->
res.writeHead(200, {'Content-type': 'text/plain'})
res.write '-----------------------------------------------------------\n\n'
res.write "The name is <NAME>...hey, no, it is #{req.post['name'] or 'unknown'}\n"
res.write "And the age is #{req.post['age']}\n\n";
#res.write("And that is all, folks...")
for key, val of req
try
stri = "Request #{key} = #{JSON.stringify(val)}\n"
router.log stri unless not router.logging
res.write stri
catch e
res.write "NASTY ERROR: #{e.message}\n"
res.end()
router.get "/formrequest", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end """
<title>Request vars discovery</title>
<form action="/showrequest" method="post" enctype="application/x-www-form-urlencoded">
<p>Name:<input type="text" required="required" size="40" name="name" /></p>
<p>Age: <input type="number" required="required" size="4" name="age" /></p>
<p><input type="submit" value="Submit to /showrequest" /><input type="reset" value="Reset" /></p>
</form>
"""
# Proxy pass
router.get "/google", (req, res) ->
router.proxy_pass "http://www.google.com.ar", res
router.get "/testing", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org/", res
router.get "/testing/:route", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org/#{req.params.route}/", res
router.get "/shell", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org:10001", res
# End of proxy pass
#Auth
router.get "/login", (req, res) ->
require_credentials = ->
res.setHeader "WWW-Authenticate", 'Basic realm="node-simple-router"'
res.writeHead 401, 'Access denied', 'Content-type': 'text/html'
res.end()
console.log req.headers
console.log "----------------------------------------------------------------"
if not req.headers['authorization']
require_credentials()
else
console.log "req.headers['authorization'] = #{req.headers['authorization']}"
auth = req.headers['authorization'].split /\s+/
console.log "AUTH: #{auth[0] + ' - ' + auth[1]}"
[usr, pwd] = new Buffer(auth[1], 'base64').toString().split ':'
if usr is 'sandy' and pwd is '<PASSWORD>'
res.writeHead 200, 'Content-type': 'text/plain'
res.write "usr: #{usr}\n"
res.write "pwd: #{pwd}\n"
res.end()
else
require_credentials()
#End of Auth
#SCGI
router.get "/scgi", (req, res) ->
router.scgi_pass '/tmp/node_scgi.sk', req, res
get_scgi = (req, res) ->
router.scgi_pass 26000, req, res
router.get "/scgiform", (req, res) ->
res.writeHead 200, 'Content-type': 'text/html'
res.end """
<title>SCGI Form</title>
<h3 style="text-align: center; color: #220088;">SCGI Form</h3><hr/>
<form action="/uwsgi" method="post">
<table>
<tr>
<td>Name</td>
<td style="text-align: right;"><input type="text" size="40" name="name" required="required" /></td>
<tr>
<tr>
<td>Age</td>
<td style="text-align: right;"><input type="number" size="4" name="age" /></td>
<tr>
<tr>
<td><input type="submit" value="Send data" /></td>
<td><input type="reset" value="Reset" /></td>
<tr>
</table>
</form>
"""
router.get "/uwsgi", get_scgi
router.post "/uwsgi", get_scgi
#End of SCGI
###
End of example routes
###
#Ok, just start the server!
argv = process.argv.slice 2
server = http.createServer router
server.on 'listening', ->
addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}
router.log "Serving web content at #{addr.address}:#{addr.port}"
process.on "SIGINT", ->
server.close()
router.log "\n Server shutting up...\n"
process.exit 0
server.listen if argv[0]? and not isNaN(parseInt(argv[0])) then parseInt(argv[0]) else 8000
| true | #!/usr/bin/env coffee
Router = require '../../lib/router'
http = require 'http'
router = Router(list_dir: true)
###
Example routes
###
#router.get "/", (req, res) ->
# res.end "Home"
router.get "/hello", (req, res) ->
res.end "Hello, World!, Hola, Mundo!"
router.get "/users", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end "<h1 style='color: navy; text-align: center;'>Active members registry</h1>"
router.post "/users", (req, res) ->
router.log "\n\nBody of request is: #{req.body.toString()}\nRequest content type is: #{req.headers['content-type']}"
router.log "\nRequest Headers"
router.log "#{key} = #{val}" for key, val of req.headers
router.log "\nRequest body object properties"
res.write "\nRequest body object properties\n"
try
router.log "#{key}: #{val}" for key, val of req.body
catch e
res.write "Looks like you did something dumb: #{e.toString()}\n"
for key, val of req.body
res.write "#{key} = #{val}\n"
res.end()
router.get "/users/:id", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end "<h1>User No: <span style='color: red;'>#{req.params.id}</span></h1>"
router.get "/crashit", (req, res) ->
throw new Error("Crashed on purpose...")
router.post "/showrequest", (req, res) ->
res.writeHead(200, {'Content-type': 'text/plain'})
res.write '-----------------------------------------------------------\n\n'
res.write "The name is PI:NAME:<NAME>END_PI...hey, no, it is #{req.post['name'] or 'unknown'}\n"
res.write "And the age is #{req.post['age']}\n\n";
#res.write("And that is all, folks...")
for key, val of req
try
stri = "Request #{key} = #{JSON.stringify(val)}\n"
router.log stri unless not router.logging
res.write stri
catch e
res.write "NASTY ERROR: #{e.message}\n"
res.end()
router.get "/formrequest", (req, res) ->
res.writeHead(200, {'Content-type': 'text/html'})
res.end """
<title>Request vars discovery</title>
<form action="/showrequest" method="post" enctype="application/x-www-form-urlencoded">
<p>Name:<input type="text" required="required" size="40" name="name" /></p>
<p>Age: <input type="number" required="required" size="4" name="age" /></p>
<p><input type="submit" value="Submit to /showrequest" /><input type="reset" value="Reset" /></p>
</form>
"""
# Proxy pass
router.get "/google", (req, res) ->
router.proxy_pass "http://www.google.com.ar", res
router.get "/testing", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org/", res
router.get "/testing/:route", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org/#{req.params.route}/", res
router.get "/shell", (req, res) ->
router.proxy_pass "http://testing.savos.ods.org:10001", res
# End of proxy pass
#Auth
router.get "/login", (req, res) ->
require_credentials = ->
res.setHeader "WWW-Authenticate", 'Basic realm="node-simple-router"'
res.writeHead 401, 'Access denied', 'Content-type': 'text/html'
res.end()
console.log req.headers
console.log "----------------------------------------------------------------"
if not req.headers['authorization']
require_credentials()
else
console.log "req.headers['authorization'] = #{req.headers['authorization']}"
auth = req.headers['authorization'].split /\s+/
console.log "AUTH: #{auth[0] + ' - ' + auth[1]}"
[usr, pwd] = new Buffer(auth[1], 'base64').toString().split ':'
if usr is 'sandy' and pwd is 'PI:PASSWORD:<PASSWORD>END_PI'
res.writeHead 200, 'Content-type': 'text/plain'
res.write "usr: #{usr}\n"
res.write "pwd: #{pwd}\n"
res.end()
else
require_credentials()
#End of Auth
#SCGI
router.get "/scgi", (req, res) ->
router.scgi_pass '/tmp/node_scgi.sk', req, res
get_scgi = (req, res) ->
router.scgi_pass 26000, req, res
router.get "/scgiform", (req, res) ->
res.writeHead 200, 'Content-type': 'text/html'
res.end """
<title>SCGI Form</title>
<h3 style="text-align: center; color: #220088;">SCGI Form</h3><hr/>
<form action="/uwsgi" method="post">
<table>
<tr>
<td>Name</td>
<td style="text-align: right;"><input type="text" size="40" name="name" required="required" /></td>
<tr>
<tr>
<td>Age</td>
<td style="text-align: right;"><input type="number" size="4" name="age" /></td>
<tr>
<tr>
<td><input type="submit" value="Send data" /></td>
<td><input type="reset" value="Reset" /></td>
<tr>
</table>
</form>
"""
router.get "/uwsgi", get_scgi
router.post "/uwsgi", get_scgi
#End of SCGI
###
End of example routes
###
#Ok, just start the server!
argv = process.argv.slice 2
server = http.createServer router
server.on 'listening', ->
addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}
router.log "Serving web content at #{addr.address}:#{addr.port}"
process.on "SIGINT", ->
server.close()
router.log "\n Server shutting up...\n"
process.exit 0
server.listen if argv[0]? and not isNaN(parseInt(argv[0])) then parseInt(argv[0]) else 8000
|
[
{
"context": "tyEmail.options = \n\t\ttwitter: 'http://twitter.com/Royal_Arse'\n\t\twebsite: 'http://cacheflow.ca'\n\n\t\tsiteName: 'J",
"end": 84,
"score": 0.9995740652084351,
"start": 74,
"tag": "USERNAME",
"value": "Royal_Arse"
},
{
"context": "e'\n\t\twebsite: 'http://cacheflow.c... | both/_config/emails.coffee | DeBraid/jetfile | 0 | if Meteor.isServer
PrettyEmail.options =
twitter: 'http://twitter.com/Royal_Arse'
website: 'http://cacheflow.ca'
siteName: 'Jetfile'
companyAddress: 'Toronto, ON'
companyName: 'Jetfile'
companyUrl: 'http://jetfile.meteor.com' | 26685 | if Meteor.isServer
PrettyEmail.options =
twitter: 'http://twitter.com/Royal_Arse'
website: 'http://cacheflow.ca'
siteName: '<NAME>file'
companyAddress: 'Toronto, ON'
companyName: '<NAME>'
companyUrl: 'http://jetfile.meteor.com' | true | if Meteor.isServer
PrettyEmail.options =
twitter: 'http://twitter.com/Royal_Arse'
website: 'http://cacheflow.ca'
siteName: 'PI:NAME:<NAME>END_PIfile'
companyAddress: 'Toronto, ON'
companyName: 'PI:NAME:<NAME>END_PI'
companyUrl: 'http://jetfile.meteor.com' |
[
{
"context": "escapes html-like text\", ->\n renderer.message 'joe', '<a \"evil.jpg\"/>'\n expect(renderer._addMessa",
"end": 818,
"score": 0.9695072174072266,
"start": 815,
"tag": "NAME",
"value": "joe"
}
] | test/window_message_renderer_test.coffee | nornagon/ircv | 20 | describe "A window message renderer", ->
surface = renderer = undefined
message = (num) ->
msg = $ $('.message', surface)[num]
{ source: $(msg.children()[0]), content: $(msg.children()[1]) }
beforeEach ->
mocks.dom.setUp()
surface = $ '<div>'
win = {
$messages: surface
isScrolledDown: ->
scrollToBottom: ->
getContext: -> {}
emit: ->
isFocused: -> true
}
renderer = new chat.window.MessageRenderer win
spyOn(renderer, '_addMessage').andCallThrough()
afterEach ->
mocks.dom.tearDown()
surface.remove()
it "displays messages to the user", ->
renderer.message 'bob', 'hi'
expect(message(0).source).toHaveText 'bob'
expect(message(0).content).toHaveText 'hi'
it "escapes html-like text", ->
renderer.message 'joe', '<a "evil.jpg"/>'
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<a "evil.jpg"/>', ''
it "doesn't collapse multiple spaces", ->
renderer.message 'bill', 'hi there'
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'hi there', ''
it "auto-links urls", ->
renderer.message '*', 'check www.youtube.com out'
expect(renderer._addMessage).toHaveBeenCalledWith '*',
'check <a target="_blank" href="http://www.youtube.com">' +
'www.youtube.com</a> out', ''
it "allows long words to break", ->
word = 'thisisareallyreallyreallyreallyreallyreallyreallylongword'
renderer.message 'bill', word
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'<span class="longword">' + word + '</span>', ''
it "allows multiple long words to break", ->
word1 = 'thisisareallyreallyreallyreallyreallyreallyreallylongword'
word2 = 'andthisisalsoareallylongword!!!!!!!!!!!!!!!!!'
renderer.message 'joe', word1 + ' ' + word2
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<span class="longword">' + word1 + '</span> ' +
'<span class="longword">' + word2 + '</span>', ''
it "allows the same long word to be used twice", ->
word = 'andthisisalsoareallylongwordddddddddddddd'
renderer.message 'joe', word + ' ' + word
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<span class="longword">' + word + '</span> ' +
'<span class="longword">' + word + '</span>', ''
it "allows long words to break even when they contain HTML", ->
word = 'thisisareallyreallyrea"<>&><"lyreallyreallyreallylongword'
renderer.message 'bill', word
escapedWord = word[..21] + '"<>&><"' + word[29..]
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'<span class="longword">' + escapedWord + '</span>', ''
it "doesn't allow short words that seem long due to HTML escaping to break", ->
renderer.message 'joe', '<a href="evil.jpg"/>'
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<a href="evil.jpg"/>', '' | 168128 | describe "A window message renderer", ->
surface = renderer = undefined
message = (num) ->
msg = $ $('.message', surface)[num]
{ source: $(msg.children()[0]), content: $(msg.children()[1]) }
beforeEach ->
mocks.dom.setUp()
surface = $ '<div>'
win = {
$messages: surface
isScrolledDown: ->
scrollToBottom: ->
getContext: -> {}
emit: ->
isFocused: -> true
}
renderer = new chat.window.MessageRenderer win
spyOn(renderer, '_addMessage').andCallThrough()
afterEach ->
mocks.dom.tearDown()
surface.remove()
it "displays messages to the user", ->
renderer.message 'bob', 'hi'
expect(message(0).source).toHaveText 'bob'
expect(message(0).content).toHaveText 'hi'
it "escapes html-like text", ->
renderer.message '<NAME>', '<a "evil.jpg"/>'
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<a "evil.jpg"/>', ''
it "doesn't collapse multiple spaces", ->
renderer.message 'bill', 'hi there'
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'hi there', ''
it "auto-links urls", ->
renderer.message '*', 'check www.youtube.com out'
expect(renderer._addMessage).toHaveBeenCalledWith '*',
'check <a target="_blank" href="http://www.youtube.com">' +
'www.youtube.com</a> out', ''
it "allows long words to break", ->
word = 'thisisareallyreallyreallyreallyreallyreallyreallylongword'
renderer.message 'bill', word
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'<span class="longword">' + word + '</span>', ''
it "allows multiple long words to break", ->
word1 = 'thisisareallyreallyreallyreallyreallyreallyreallylongword'
word2 = 'andthisisalsoareallylongword!!!!!!!!!!!!!!!!!'
renderer.message 'joe', word1 + ' ' + word2
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<span class="longword">' + word1 + '</span> ' +
'<span class="longword">' + word2 + '</span>', ''
it "allows the same long word to be used twice", ->
word = 'andthisisalsoareallylongwordddddddddddddd'
renderer.message 'joe', word + ' ' + word
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<span class="longword">' + word + '</span> ' +
'<span class="longword">' + word + '</span>', ''
it "allows long words to break even when they contain HTML", ->
word = 'thisisareallyreallyrea"<>&><"lyreallyreallyreallylongword'
renderer.message 'bill', word
escapedWord = word[..21] + '"<>&><"' + word[29..]
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'<span class="longword">' + escapedWord + '</span>', ''
it "doesn't allow short words that seem long due to HTML escaping to break", ->
renderer.message 'joe', '<a href="evil.jpg"/>'
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<a href="evil.jpg"/>', '' | true | describe "A window message renderer", ->
surface = renderer = undefined
message = (num) ->
msg = $ $('.message', surface)[num]
{ source: $(msg.children()[0]), content: $(msg.children()[1]) }
beforeEach ->
mocks.dom.setUp()
surface = $ '<div>'
win = {
$messages: surface
isScrolledDown: ->
scrollToBottom: ->
getContext: -> {}
emit: ->
isFocused: -> true
}
renderer = new chat.window.MessageRenderer win
spyOn(renderer, '_addMessage').andCallThrough()
afterEach ->
mocks.dom.tearDown()
surface.remove()
it "displays messages to the user", ->
renderer.message 'bob', 'hi'
expect(message(0).source).toHaveText 'bob'
expect(message(0).content).toHaveText 'hi'
it "escapes html-like text", ->
renderer.message 'PI:NAME:<NAME>END_PI', '<a "evil.jpg"/>'
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<a "evil.jpg"/>', ''
it "doesn't collapse multiple spaces", ->
renderer.message 'bill', 'hi there'
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'hi there', ''
it "auto-links urls", ->
renderer.message '*', 'check www.youtube.com out'
expect(renderer._addMessage).toHaveBeenCalledWith '*',
'check <a target="_blank" href="http://www.youtube.com">' +
'www.youtube.com</a> out', ''
it "allows long words to break", ->
word = 'thisisareallyreallyreallyreallyreallyreallyreallylongword'
renderer.message 'bill', word
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'<span class="longword">' + word + '</span>', ''
it "allows multiple long words to break", ->
word1 = 'thisisareallyreallyreallyreallyreallyreallyreallylongword'
word2 = 'andthisisalsoareallylongword!!!!!!!!!!!!!!!!!'
renderer.message 'joe', word1 + ' ' + word2
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<span class="longword">' + word1 + '</span> ' +
'<span class="longword">' + word2 + '</span>', ''
it "allows the same long word to be used twice", ->
word = 'andthisisalsoareallylongwordddddddddddddd'
renderer.message 'joe', word + ' ' + word
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<span class="longword">' + word + '</span> ' +
'<span class="longword">' + word + '</span>', ''
it "allows long words to break even when they contain HTML", ->
word = 'thisisareallyreallyrea"<>&><"lyreallyreallyreallylongword'
renderer.message 'bill', word
escapedWord = word[..21] + '"<>&><"' + word[29..]
expect(renderer._addMessage).toHaveBeenCalledWith 'bill',
'<span class="longword">' + escapedWord + '</span>', ''
it "doesn't allow short words that seem long due to HTML escaping to break", ->
renderer.message 'joe', '<a href="evil.jpg"/>'
expect(renderer._addMessage).toHaveBeenCalledWith 'joe',
'<a href="evil.jpg"/>', '' |
[
{
"context": "#\n# grunt-amdify\n# https://github.com/ePages-de/grunt-amdify\n#\n# Copyright (c) 2014 Erik Müller\n#",
"end": 47,
"score": 0.9992435574531555,
"start": 38,
"tag": "USERNAME",
"value": "ePages-de"
},
{
"context": ".com/ePages-de/grunt-amdify\n#\n# Copyright (c) 2014 Er... | tasks/amdify.coffee | ePages-de/grunt-amdify | 2 | #
# grunt-amdify
# https://github.com/ePages-de/grunt-amdify
#
# Copyright (c) 2014 Erik Müller
# Licensed under the MIT license.
#
module.exports = (grunt) ->
# Please see the Grunt documentation for more information regarding task
# creation: http://gruntjs.com/creating-tasks
amdify = require('audit').wrap
colors = require 'chalk'
grunt.task.registerMultiTask('amdify', 'use audit to wrap commonjs modules to AMD', ->
options = @options()
@files.forEach (file) ->
grunt.log.writeln colors.magenta('[amdify] ') + colors.cyan(file.src[0]) + ' => ' + colors.cyan(file.dest)
grunt.file.write file.dest, amdify(grunt.file.read(file.src[0]), options)
)
| 120194 | #
# grunt-amdify
# https://github.com/ePages-de/grunt-amdify
#
# Copyright (c) 2014 <NAME>
# Licensed under the MIT license.
#
module.exports = (grunt) ->
# Please see the Grunt documentation for more information regarding task
# creation: http://gruntjs.com/creating-tasks
amdify = require('audit').wrap
colors = require 'chalk'
grunt.task.registerMultiTask('amdify', 'use audit to wrap commonjs modules to AMD', ->
options = @options()
@files.forEach (file) ->
grunt.log.writeln colors.magenta('[amdify] ') + colors.cyan(file.src[0]) + ' => ' + colors.cyan(file.dest)
grunt.file.write file.dest, amdify(grunt.file.read(file.src[0]), options)
)
| true | #
# grunt-amdify
# https://github.com/ePages-de/grunt-amdify
#
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
#
module.exports = (grunt) ->
# Please see the Grunt documentation for more information regarding task
# creation: http://gruntjs.com/creating-tasks
amdify = require('audit').wrap
colors = require 'chalk'
grunt.task.registerMultiTask('amdify', 'use audit to wrap commonjs modules to AMD', ->
options = @options()
@files.forEach (file) ->
grunt.log.writeln colors.magenta('[amdify] ') + colors.cyan(file.src[0]) + ' => ' + colors.cyan(file.dest)
grunt.file.write file.dest, amdify(grunt.file.read(file.src[0]), options)
)
|
[
{
"context": "rent]\n\n console.log '\\n\\n\\nGIFSTORM.biz\\nby CHARLTON ROBERTS\\nhttp://charlton.io\\n@charltoons\\n\\n\\n'\n\n ",
"end": 536,
"score": 0.9998392462730408,
"start": 520,
"tag": "NAME",
"value": "CHARLTON ROBERTS"
}
] | src/coffee/gifstorm.coffee | charltoons/gifstorm | 1 | gifs = require('../../gifs.json')
class GIFSTORM
constructor: (@gifs)->
@body = document.body
@gif_path = './gifs/'
@exhibit = document.getElementById 'exhibit'
@title = document.getElementById 'title'
@artist = document.getElementById 'artist'
@source = document.getElementById 'source'
@next = document.getElementById 'next'
@current = 0
@next.onclick = @on_next
@load @gifs[@current]
console.log '\n\n\nGIFSTORM.biz\nby CHARLTON ROBERTS\nhttp://charlton.io\n@charltoons\n\n\n'
window.analytics.track 'Initial Load'
hooks('GIFSTORM.biz', 'Somebody loaded the page', '1yjvfcdngK')
load: (gif)->
@img = new Image
path = @get_path gif.file
# set callback for when the gif loads
@img.onload = =>
@is_loading false
@body.style.backgroundImage = 'url(' + path + ')'
@is_loading true
# load the image in a dummy html <img> so we know when its loaded
# setTimeout (=> # used to test the loading screen
@img.src = path
# ), 5000
# set the exhibit info
@title.innerText = gif.title
@artist.innerText = 'by ' + gif.artist
@source.setAttribute 'href', gif.source
# fired with the "NEXT" button is pressed
on_next: =>
# if we're at the end, go back around
if ++@current >= @gifs.length then @current = 0
# load the next gif
@load @gifs[@current]
window.analytics.track 'Next'
hooks('GIFSTORM.biz', 'Somebody clicked next', '1yjvfcdngK')
is_loading: (is_currently_loading)->
if is_currently_loading
@body.classList.add('is-loading')
else
@body.classList.remove('is-loading')
get_path: (filename)-> @gif_path + filename
document.onreadystatechange = ->
if document.readyState == "complete"
GIFSTORM = new GIFSTORM gifs
| 144046 | gifs = require('../../gifs.json')
class GIFSTORM
constructor: (@gifs)->
@body = document.body
@gif_path = './gifs/'
@exhibit = document.getElementById 'exhibit'
@title = document.getElementById 'title'
@artist = document.getElementById 'artist'
@source = document.getElementById 'source'
@next = document.getElementById 'next'
@current = 0
@next.onclick = @on_next
@load @gifs[@current]
console.log '\n\n\nGIFSTORM.biz\nby <NAME>\nhttp://charlton.io\n@charltoons\n\n\n'
window.analytics.track 'Initial Load'
hooks('GIFSTORM.biz', 'Somebody loaded the page', '1yjvfcdngK')
load: (gif)->
@img = new Image
path = @get_path gif.file
# set callback for when the gif loads
@img.onload = =>
@is_loading false
@body.style.backgroundImage = 'url(' + path + ')'
@is_loading true
# load the image in a dummy html <img> so we know when its loaded
# setTimeout (=> # used to test the loading screen
@img.src = path
# ), 5000
# set the exhibit info
@title.innerText = gif.title
@artist.innerText = 'by ' + gif.artist
@source.setAttribute 'href', gif.source
# fired with the "NEXT" button is pressed
on_next: =>
# if we're at the end, go back around
if ++@current >= @gifs.length then @current = 0
# load the next gif
@load @gifs[@current]
window.analytics.track 'Next'
hooks('GIFSTORM.biz', 'Somebody clicked next', '1yjvfcdngK')
is_loading: (is_currently_loading)->
if is_currently_loading
@body.classList.add('is-loading')
else
@body.classList.remove('is-loading')
get_path: (filename)-> @gif_path + filename
document.onreadystatechange = ->
if document.readyState == "complete"
GIFSTORM = new GIFSTORM gifs
| true | gifs = require('../../gifs.json')
class GIFSTORM
constructor: (@gifs)->
@body = document.body
@gif_path = './gifs/'
@exhibit = document.getElementById 'exhibit'
@title = document.getElementById 'title'
@artist = document.getElementById 'artist'
@source = document.getElementById 'source'
@next = document.getElementById 'next'
@current = 0
@next.onclick = @on_next
@load @gifs[@current]
console.log '\n\n\nGIFSTORM.biz\nby PI:NAME:<NAME>END_PI\nhttp://charlton.io\n@charltoons\n\n\n'
window.analytics.track 'Initial Load'
hooks('GIFSTORM.biz', 'Somebody loaded the page', '1yjvfcdngK')
load: (gif)->
@img = new Image
path = @get_path gif.file
# set callback for when the gif loads
@img.onload = =>
@is_loading false
@body.style.backgroundImage = 'url(' + path + ')'
@is_loading true
# load the image in a dummy html <img> so we know when its loaded
# setTimeout (=> # used to test the loading screen
@img.src = path
# ), 5000
# set the exhibit info
@title.innerText = gif.title
@artist.innerText = 'by ' + gif.artist
@source.setAttribute 'href', gif.source
# fired with the "NEXT" button is pressed
on_next: =>
# if we're at the end, go back around
if ++@current >= @gifs.length then @current = 0
# load the next gif
@load @gifs[@current]
window.analytics.track 'Next'
hooks('GIFSTORM.biz', 'Somebody clicked next', '1yjvfcdngK')
is_loading: (is_currently_loading)->
if is_currently_loading
@body.classList.add('is-loading')
else
@body.classList.remove('is-loading')
get_path: (filename)-> @gif_path + filename
document.onreadystatechange = ->
if document.readyState == "complete"
GIFSTORM = new GIFSTORM gifs
|
[
{
"context": "Email: (browser) ->\n\n user =\n email : 'kodingtester@gmail.com'\n username : 'kodingqa'\n password : 'pa",
"end": 321,
"score": 0.9999158978462219,
"start": 299,
"tag": "EMAIL",
"value": "kodingtester@gmail.com"
},
{
"context": "l : 'kodingtest... | client/test/lib/register/register.coffee | ezgikaysi/koding | 1 | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
expectValidationError = (browser) ->
browser
.waitForElementVisible '.validation-error', 20000 # Assertion
.end()
module.exports =
registerWithGravatarEmail: (browser) ->
user =
email : 'kodingtester@gmail.com'
username : 'kodingqa'
password : 'passwordfortestuser' # gmail and gravatar pass is the same
gravatar : yes
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
browser
.pause 5000
.element 'css selector', '[testpath=main-sidebar]', (result) ->
if result.status is 0
browser.end()
else
helpers.attemptEnterUsernameOnRegister(browser, user)
browser
.waitForElementVisible '[testpath=AvatarAreaIconLink]', 50000 # Assertion
.end()
registerWithoutGravatarEmail: (browser) ->
helpers.doRegister(browser)
browser.end()
tryRegisterWithInvalidUsername: (browser) ->
user = utils.getUser(yes)
user.username = '{r2d2}'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
helpers.attemptEnterUsernameOnRegister(browser, user)
expectValidationError(browser)
tryRegisterWithInvalidEmail: (browser) ->
user = utils.getUser(yes)
user.email = 'r2d2.kd.io'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
expectValidationError(browser)
tryRegisterWithInvalidPassword: (browser) ->
user = utils.getUser(yes)
user.password = '123456'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
expectValidationError(browser)
# forgotPasswordWwithEmailConfirmation: (browser) -> #yarim kaldi
# user = helpers.doRegister(browser)
# email = user.email
# browser.execute 'KD.isTesting = true;'
# browser
# .waitForElementVisible '[testpath=main-header]', 50000
# .click 'nav:not(.mobile-menu) [testpath=login-link]'
# .waitForElementVisible '.forgot-link', 50000
# .click '.forgot-link'
# .waitForElementVisible '.login-input-view', 20000
# .setValue '.login-input-view', email
# .click '.login-form button'
# .end()
| 50890 | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
expectValidationError = (browser) ->
browser
.waitForElementVisible '.validation-error', 20000 # Assertion
.end()
module.exports =
registerWithGravatarEmail: (browser) ->
user =
email : '<EMAIL>'
username : 'kodingqa'
password : '<PASSWORD>' # gmail and gravatar pass is the same
gravatar : yes
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
browser
.pause 5000
.element 'css selector', '[testpath=main-sidebar]', (result) ->
if result.status is 0
browser.end()
else
helpers.attemptEnterUsernameOnRegister(browser, user)
browser
.waitForElementVisible '[testpath=AvatarAreaIconLink]', 50000 # Assertion
.end()
registerWithoutGravatarEmail: (browser) ->
helpers.doRegister(browser)
browser.end()
tryRegisterWithInvalidUsername: (browser) ->
user = utils.getUser(yes)
user.username = '{r2d2}'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
helpers.attemptEnterUsernameOnRegister(browser, user)
expectValidationError(browser)
tryRegisterWithInvalidEmail: (browser) ->
user = utils.getUser(yes)
user.email = 'r2d2.kd.io'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
expectValidationError(browser)
tryRegisterWithInvalidPassword: (browser) ->
user = utils.getUser(yes)
user.password = '<PASSWORD>'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
expectValidationError(browser)
# forgotPasswordWwithEmailConfirmation: (browser) -> #yarim kaldi
# user = helpers.doRegister(browser)
# email = user.email
# browser.execute 'KD.isTesting = true;'
# browser
# .waitForElementVisible '[testpath=main-header]', 50000
# .click 'nav:not(.mobile-menu) [testpath=login-link]'
# .waitForElementVisible '.forgot-link', 50000
# .click '.forgot-link'
# .waitForElementVisible '.login-input-view', 20000
# .setValue '.login-input-view', email
# .click '.login-form button'
# .end()
| true | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
expectValidationError = (browser) ->
browser
.waitForElementVisible '.validation-error', 20000 # Assertion
.end()
module.exports =
registerWithGravatarEmail: (browser) ->
user =
email : 'PI:EMAIL:<EMAIL>END_PI'
username : 'kodingqa'
password : 'PI:PASSWORD:<PASSWORD>END_PI' # gmail and gravatar pass is the same
gravatar : yes
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
browser
.pause 5000
.element 'css selector', '[testpath=main-sidebar]', (result) ->
if result.status is 0
browser.end()
else
helpers.attemptEnterUsernameOnRegister(browser, user)
browser
.waitForElementVisible '[testpath=AvatarAreaIconLink]', 50000 # Assertion
.end()
registerWithoutGravatarEmail: (browser) ->
helpers.doRegister(browser)
browser.end()
tryRegisterWithInvalidUsername: (browser) ->
user = utils.getUser(yes)
user.username = '{r2d2}'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
helpers.attemptEnterUsernameOnRegister(browser, user)
expectValidationError(browser)
tryRegisterWithInvalidEmail: (browser) ->
user = utils.getUser(yes)
user.email = 'r2d2.kd.io'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
expectValidationError(browser)
tryRegisterWithInvalidPassword: (browser) ->
user = utils.getUser(yes)
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
helpers.attemptEnterEmailAndPasswordOnRegister(browser, user)
expectValidationError(browser)
# forgotPasswordWwithEmailConfirmation: (browser) -> #yarim kaldi
# user = helpers.doRegister(browser)
# email = user.email
# browser.execute 'KD.isTesting = true;'
# browser
# .waitForElementVisible '[testpath=main-header]', 50000
# .click 'nav:not(.mobile-menu) [testpath=login-link]'
# .waitForElementVisible '.forgot-link', 50000
# .click '.forgot-link'
# .waitForElementVisible '.login-input-view', 20000
# .setValue '.login-input-view', email
# .click '.login-form button'
# .end()
|
[
{
"context": "ice_obj : -> { name : @service_name(), username : @user.remote }\n is_remote_proof : () -> true\n\n @single_occup",
"end": 1624,
"score": 0.9835731387138367,
"start": 1612,
"tag": "USERNAME",
"value": "@user.remote"
},
{
"context": ".remote}\"\n\n to_key_value_pair ... | src/web_service.iced | tarsbase/proofs | 0 | {cieq,Base} = require './base'
{constants} = require './constants'
urlmod = require 'url'
#==========================================================================
class WebServiceBinding extends Base
#------
_v_customize_json : (ret) ->
ret.body.service = o if (o = @service_obj())?
#---------------
_service_obj_check : (x) -> return not(x?)
#---------------
# service has to be optional because some legacy sigchains
# use this type to prove ownership of a new key with no
# service section
_optional_sections : () -> super().concat(["revoke", "service"])
#---------------
# For Twitter, Github, etc, this will be empty. For non-signle-occupants,
# it will be the unique id for the resource, like https://keybase.io/ for
# Web services.
resource_id : () -> ""
#---------------
_type : () -> constants.sig_types.web_service_binding
#---------------
_type_v2 : (revoke_flag) ->
if @revoke? or revoke_flag then constants.sig_types_v2.web_service_binding_with_revoke
else constants.sig_types_v2.web_service_binding
#---------------
_v_check : ({json}, cb) ->
await super { json }, defer err
if not(err?) and not(@_service_obj_check(json?.body?.service))
err = new Error "Bad service object found"
cb err
#==========================================================================
class SocialNetworkBinding extends WebServiceBinding
_service_obj_check : (x) ->
so = @service_obj()
return (x? and cieq(so.username, x.username) and cieq(so.name, x.name))
service_obj : -> { name : @service_name(), username : @user.remote }
is_remote_proof : () -> true
@single_occupancy : () -> true
single_occupancy : () -> SocialNetworkBinding.single_occupancy()
@normalize_name : (n) ->
n = n.toLowerCase()
if n[0] is '@' then n[1...] else n
normalize_name : (n) ->
n or= @user.remote
if @check_name(n) then SocialNetworkBinding.normalize_name n
else null
check_inputs : () ->
if (@check_name(@user.remote)) then null
else new Error "Bad remote_username given: #{@user.remote}"
to_key_value_pair : () ->
{ key : @service_name(), value : @normalize_name() }
#==========================================================================
# A last-minute sanity check of the URL module
has_non_ascii = (s) ->
buf = Buffer.from s, 'utf8'
for i in [0...buf.length]
if buf.readUInt8(i) >= 128
return true
return false
#----------
class GenericWebSiteBinding extends WebServiceBinding
constructor : (args) ->
@remote_host = @parse args.remote_host
super args
@parse : (h, opts = {}) ->
ret = null
if h? and (h = h.toLowerCase())? and (o = urlmod.parse(h))? and
o.hostname? and (not(o.path?) or (o.path is '/')) and not(o.port?)
protocol = o.protocol or opts.protocol
if protocol?
ret = { protocol, hostname : o.hostname }
n = GenericWebSiteBinding.to_string(ret)
if has_non_ascii(n)
console.error "Bug in urlmod found: found non-ascii in URL: #{n}"
ret = null
return ret
parse : (h) -> GenericWebSiteBinding.parse h
to_key_value_pair : () -> {
key : @remote_host.protocol[0...-1]
value : @remote_host.hostname
}
@to_string : (o) ->
([ o.protocol, o.hostname ].join '//').toLowerCase()
@normalize_name : (s) ->
if (o = GenericWebSiteBinding.parse(s))? then GenericWebSiteBinding.to_string(o) else null
@check_name : (h) -> GenericWebSiteBinding.parse(h)?
check_name : (n) -> @parse(n)?
@single_occupancy : () -> false
single_occupancy : () -> GenericWebSiteBinding.single_occupancy()
resource_id : () -> @to_string()
to_string : () -> GenericWebSiteBinding.to_string @remote_host
_service_obj_check : (x) ->
so = @service_obj()
return x? and so? and cieq(so.protocol, x.protocol) and cieq(so.hostname, x.hostname)
service_obj : () -> @remote_host
is_remote_proof : () -> true
proof_type : () -> constants.proof_types.generic_web_site
@name_hint : () -> "a valid hostname, like `my.site.com`"
check_inputs : () ->
if @remote_host? then null
else new Error "Bad remote_host given"
check_existing : (proofs) ->
if (v = proofs.generic_web_site)?
for {check_data_json} in v
if cieq(GenericWebSiteBinding.to_string(check_data_json), @to_string())
return new Error "A live proof for #{@to_string()} already exists"
return null
#==========================================================================
class DnsBinding extends WebServiceBinding
constructor : (args) ->
@domain = @parse args.remote_host
super args
@parse : (h, opts = {}) ->
ret = null
if h?
h = "dns://#{h}" if h.indexOf("dns://") isnt 0
if h? and (h = h.toLowerCase())? and (o = urlmod.parse(h))? and
o.hostname? and (not(o.path?) or (o.path is '/')) and not(o.port?)
ret = o.hostname
if has_non_ascii(ret)
console.error "Bug in urlmod found: non-ASCII in done name: #{ret}"
ret = null
return ret
to_key_value_pair : () -> { key : "dns", value : @domain }
parse : (h) -> DnsBinding.parse(h)
@to_string : (o) -> o.domain
to_string : () -> @domain
normalize_name : (s) -> DnsBinding.parse(s)
@single_occupancy : () -> false
single_occupancy : () -> DnsBinding.single_occupancy()
resource_id : () -> @to_string()
_service_obj_check : (x) ->
so = @service_obj()
return x? and so? and cieq(so.protocol, x.protocol) and cieq(so.domain, x.domain)
@service_name : -> "dns"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.dns
@check_name : (n) -> DnsBinding.parse(n)?
check_name : (n) -> DnsBinding.check_name(n)
service_obj : () -> { protocol : "dns", @domain }
is_remote_proof : () -> true
check_inputs : () -> if @domain then null else new Error "Bad domain given"
@name_hint : () -> "A DNS domain name, like maxk.org"
check_existing : (proofs) ->
if (v = proofs.dns?)
for {check_data_json} in v
if cieq(GenericWebSiteBinding.to_string(check_data_json), @to_string())
return new Error "A live proof for #{@to_string()} already exists"
return null
#==========================================================================
class TwitterBinding extends SocialNetworkBinding
@service_name : -> "twitter"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.twitter
is_short : -> true
@check_name : (n) ->
ret = if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_]{1,20}$/ then true
else false
return ret
check_name : (n) -> TwitterBinding.check_name(n)
@name_hint : () -> "alphanumerics, between 1 and 15 characters long"
#==========================================================================
class FacebookBinding extends SocialNetworkBinding
@service_name : -> "facebook"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.facebook
is_short : -> true
@check_name : (n) ->
# Technically Facebook doesn't count dots in the character count, and also
# prohibits leading/trailing/consecutive dots.
ret = if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9.]{1,50}$/ then true
else false
return ret
check_name : (n) -> FacebookBinding.check_name(n)
@name_hint : () -> "alphanumerics and dots, between 1 and 50 characters long"
#==========================================================================
class KeybaseBinding extends WebServiceBinding
_service_obj_check : (x) -> not x?
@service_name : -> "keybase"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.keybase
service_obj : -> null
#==========================================================================
class GithubBinding extends SocialNetworkBinding
@service_name : -> "github"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.github
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9][a-z0-9-]{0,38}$/ then true
else false
@name_hint : () -> "alphanumerics, between 1 and 39 characters long"
check_name : (n) -> GithubBinding.check_name(n)
#==========================================================================
class BitbucketBinding extends SocialNetworkBinding
@service_name : -> "bitbucket"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.bitbucket
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-zA-Z0-9_\-]{0,31}/ then true
else false
@name_hint : () -> "alphanumerics, between 1 and 30 characters long"
check_name : (n) -> BitbucketBinding.check_name(n)
#==========================================================================
class RedditBinding extends SocialNetworkBinding
@service_name : -> "reddit"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.reddit
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_-]{3,20}$/ then true
else false
@name_hint : () -> "alphanumerics, between 3 and 20 characters long"
check_name : (n) -> RedditBinding.check_name(n)
#==========================================================================
class CoinbaseBinding extends SocialNetworkBinding
@service_name : -> "coinbase"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.coinbase
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_]{2,16}$/ then true
else false
@name_hint : () -> "alphanumerics, between 2 and 16 characters long"
check_name : (n) -> CoinbaseBinding.check_name(n)
#==========================================================================
class HackerNewsBinding extends SocialNetworkBinding
@service_name : -> "hackernews"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.hackernews
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_-]{2,15}$/ then true
else false
@name_hint : () -> "alphanumerics, between 2 and 15 characters long"
check_name : (n) -> HackerNewsBinding.check_name(n)
# HN names are case-sensitive
@normalize_name : (n) ->
if n[0] is '@' then n[1...] else n
normalize_name : (n) ->
n or= @user.remote
if @check_name(n) then HackerNewsBinding.normalize_name n
else null
_service_obj_check : (x) ->
so = @service_obj()
return (x? and (so.username is x.username) and cieq(so.name, x.name))
#==========================================================================
class GenericSocialBinding extends SocialNetworkBinding
constructor : (args) ->
@remote_service = args.remote_service
if (r = args.name_regexp)? then try @name_regexp = new RegExp(r)
super args
@single_occupancy : () -> false
single_occupancy : () -> GenericSocialBinding.single_occupancy()
service_name : -> @remote_service
proof_type : -> constants.proof_types.generic_social
check_name : (n) ->
unless n? and (n is n.toLowerCase()) then false
else if n.match @name_regexp then true
else false
@name_hint : () -> "valid username"
@_check_remote_service : (n) ->
unless n? and (n is n.toLowerCase()) then false
else if n.match /^([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,15}?$/ then true
else false
_check_remote_service : (n) -> GenericSocialBinding._check_remote_service(n)
check_inputs : () ->
if err = super() then return err
else if not(@remote_service?) then return new Error "No remote_service given"
else if not(@_check_remote_service(@remote_service)) then return new Error "invalid remote_service"
else if not(@name_regexp?) then return new Error "No name_regexp given"
else return null
resource_id : () -> @remote_service
exports.TwitterBinding = TwitterBinding
exports.FacebookBinding = FacebookBinding
exports.RedditBinding = RedditBinding
exports.KeybaseBinding = KeybaseBinding
exports.GithubBinding = GithubBinding
exports.GenericWebSiteBinding = GenericWebSiteBinding
exports.CoinbaseBinding = CoinbaseBinding
exports.DnsBinding = DnsBinding
exports.HackerNewsBinding = HackerNewsBinding
exports.SocialNetworkBinding = SocialNetworkBinding
exports.BitbucketBinding = BitbucketBinding
exports.GenericSocialBinding = GenericSocialBinding
#==========================================================================
| 79139 | {cieq,Base} = require './base'
{constants} = require './constants'
urlmod = require 'url'
#==========================================================================
class WebServiceBinding extends Base
#------
_v_customize_json : (ret) ->
ret.body.service = o if (o = @service_obj())?
#---------------
_service_obj_check : (x) -> return not(x?)
#---------------
# service has to be optional because some legacy sigchains
# use this type to prove ownership of a new key with no
# service section
_optional_sections : () -> super().concat(["revoke", "service"])
#---------------
# For Twitter, Github, etc, this will be empty. For non-signle-occupants,
# it will be the unique id for the resource, like https://keybase.io/ for
# Web services.
resource_id : () -> ""
#---------------
_type : () -> constants.sig_types.web_service_binding
#---------------
_type_v2 : (revoke_flag) ->
if @revoke? or revoke_flag then constants.sig_types_v2.web_service_binding_with_revoke
else constants.sig_types_v2.web_service_binding
#---------------
_v_check : ({json}, cb) ->
await super { json }, defer err
if not(err?) and not(@_service_obj_check(json?.body?.service))
err = new Error "Bad service object found"
cb err
#==========================================================================
class SocialNetworkBinding extends WebServiceBinding
_service_obj_check : (x) ->
so = @service_obj()
return (x? and cieq(so.username, x.username) and cieq(so.name, x.name))
service_obj : -> { name : @service_name(), username : @user.remote }
is_remote_proof : () -> true
@single_occupancy : () -> true
single_occupancy : () -> SocialNetworkBinding.single_occupancy()
@normalize_name : (n) ->
n = n.toLowerCase()
if n[0] is '@' then n[1...] else n
normalize_name : (n) ->
n or= @user.remote
if @check_name(n) then SocialNetworkBinding.normalize_name n
else null
check_inputs : () ->
if (@check_name(@user.remote)) then null
else new Error "Bad remote_username given: #{@user.remote}"
to_key_value_pair : () ->
{ key : <KEY>(), value : @normalize_name() }
#==========================================================================
# A last-minute sanity check of the URL module
has_non_ascii = (s) ->
buf = Buffer.from s, 'utf8'
for i in [0...buf.length]
if buf.readUInt8(i) >= 128
return true
return false
#----------
class GenericWebSiteBinding extends WebServiceBinding
constructor : (args) ->
@remote_host = @parse args.remote_host
super args
@parse : (h, opts = {}) ->
ret = null
if h? and (h = h.toLowerCase())? and (o = urlmod.parse(h))? and
o.hostname? and (not(o.path?) or (o.path is '/')) and not(o.port?)
protocol = o.protocol or opts.protocol
if protocol?
ret = { protocol, hostname : o.hostname }
n = GenericWebSiteBinding.to_string(ret)
if has_non_ascii(n)
console.error "Bug in urlmod found: found non-ascii in URL: #{n}"
ret = null
return ret
parse : (h) -> GenericWebSiteBinding.parse h
to_key_value_pair : () -> {
key : <KEY>_<KEY>
value : @remote_host.hostname
}
@to_string : (o) ->
([ o.protocol, o.hostname ].join '//').toLowerCase()
@normalize_name : (s) ->
if (o = GenericWebSiteBinding.parse(s))? then GenericWebSiteBinding.to_string(o) else null
@check_name : (h) -> GenericWebSiteBinding.parse(h)?
check_name : (n) -> @parse(n)?
@single_occupancy : () -> false
single_occupancy : () -> GenericWebSiteBinding.single_occupancy()
resource_id : () -> @to_string()
to_string : () -> GenericWebSiteBinding.to_string @remote_host
_service_obj_check : (x) ->
so = @service_obj()
return x? and so? and cieq(so.protocol, x.protocol) and cieq(so.hostname, x.hostname)
service_obj : () -> @remote_host
is_remote_proof : () -> true
proof_type : () -> constants.proof_types.generic_web_site
@name_hint : () -> "a valid hostname, like `my.site.com`"
check_inputs : () ->
if @remote_host? then null
else new Error "Bad remote_host given"
check_existing : (proofs) ->
if (v = proofs.generic_web_site)?
for {check_data_json} in v
if cieq(GenericWebSiteBinding.to_string(check_data_json), @to_string())
return new Error "A live proof for #{@to_string()} already exists"
return null
#==========================================================================
class DnsBinding extends WebServiceBinding
constructor : (args) ->
@domain = @parse args.remote_host
super args
@parse : (h, opts = {}) ->
ret = null
if h?
h = "dns://#{h}" if h.indexOf("dns://") isnt 0
if h? and (h = h.toLowerCase())? and (o = urlmod.parse(h))? and
o.hostname? and (not(o.path?) or (o.path is '/')) and not(o.port?)
ret = o.hostname
if has_non_ascii(ret)
console.error "Bug in urlmod found: non-ASCII in done name: #{ret}"
ret = null
return ret
to_key_value_pair : () -> { key : "dns", value : @domain }
parse : (h) -> DnsBinding.parse(h)
@to_string : (o) -> o.domain
to_string : () -> @domain
normalize_name : (s) -> DnsBinding.parse(s)
@single_occupancy : () -> false
single_occupancy : () -> DnsBinding.single_occupancy()
resource_id : () -> @to_string()
_service_obj_check : (x) ->
so = @service_obj()
return x? and so? and cieq(so.protocol, x.protocol) and cieq(so.domain, x.domain)
@service_name : -> "dns"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.dns
@check_name : (n) -> DnsBinding.parse(n)?
check_name : (n) -> DnsBinding.check_name(n)
service_obj : () -> { protocol : "dns", @domain }
is_remote_proof : () -> true
check_inputs : () -> if @domain then null else new Error "Bad domain given"
@name_hint : () -> "A DNS domain name, like maxk.org"
check_existing : (proofs) ->
if (v = proofs.dns?)
for {check_data_json} in v
if cieq(GenericWebSiteBinding.to_string(check_data_json), @to_string())
return new Error "A live proof for #{@to_string()} already exists"
return null
#==========================================================================
class TwitterBinding extends SocialNetworkBinding
@service_name : -> "twitter"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.twitter
is_short : -> true
@check_name : (n) ->
ret = if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_]{1,20}$/ then true
else false
return ret
check_name : (n) -> TwitterBinding.check_name(n)
@name_hint : () -> "alphanumerics, between 1 and 15 characters long"
#==========================================================================
class FacebookBinding extends SocialNetworkBinding
@service_name : -> "facebook"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.facebook
is_short : -> true
@check_name : (n) ->
# Technically Facebook doesn't count dots in the character count, and also
# prohibits leading/trailing/consecutive dots.
ret = if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9.]{1,50}$/ then true
else false
return ret
check_name : (n) -> FacebookBinding.check_name(n)
@name_hint : () -> "alphanumerics and dots, between 1 and 50 characters long"
#==========================================================================
class KeybaseBinding extends WebServiceBinding
_service_obj_check : (x) -> not x?
@service_name : -> "keybase"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.keybase
service_obj : -> null
#==========================================================================
class GithubBinding extends SocialNetworkBinding
@service_name : -> "github"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.github
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9][a-z0-9-]{0,38}$/ then true
else false
@name_hint : () -> "alphanumerics, between 1 and 39 characters long"
check_name : (n) -> GithubBinding.check_name(n)
#==========================================================================
class BitbucketBinding extends SocialNetworkBinding
@service_name : -> "bitbucket"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.bitbucket
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-zA-Z0-9_\-]{0,31}/ then true
else false
@name_hint : () -> "alphanumerics, between 1 and 30 characters long"
check_name : (n) -> BitbucketBinding.check_name(n)
#==========================================================================
class RedditBinding extends SocialNetworkBinding
@service_name : -> "reddit"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.reddit
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_-]{3,20}$/ then true
else false
@name_hint : () -> "alphanumerics, between 3 and 20 characters long"
check_name : (n) -> RedditBinding.check_name(n)
#==========================================================================
class CoinbaseBinding extends SocialNetworkBinding
@service_name : -> "coinbase"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.coinbase
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_]{2,16}$/ then true
else false
@name_hint : () -> "alphanumerics, between 2 and 16 characters long"
check_name : (n) -> CoinbaseBinding.check_name(n)
#==========================================================================
class HackerNewsBinding extends SocialNetworkBinding
@service_name : -> "hackernews"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.hackernews
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_-]{2,15}$/ then true
else false
@name_hint : () -> "alphanumerics, between 2 and 15 characters long"
check_name : (n) -> HackerNewsBinding.check_name(n)
# HN names are case-sensitive
@normalize_name : (n) ->
if n[0] is '@' then n[1...] else n
normalize_name : (n) ->
n or= @user.remote
if @check_name(n) then HackerNewsBinding.normalize_name n
else null
_service_obj_check : (x) ->
so = @service_obj()
return (x? and (so.username is x.username) and cieq(so.name, x.name))
#==========================================================================
class GenericSocialBinding extends SocialNetworkBinding
constructor : (args) ->
@remote_service = args.remote_service
if (r = args.name_regexp)? then try @name_regexp = new RegExp(r)
super args
@single_occupancy : () -> false
single_occupancy : () -> GenericSocialBinding.single_occupancy()
service_name : -> @remote_service
proof_type : -> constants.proof_types.generic_social
check_name : (n) ->
unless n? and (n is n.toLowerCase()) then false
else if n.match @name_regexp then true
else false
@name_hint : () -> "valid username"
@_check_remote_service : (n) ->
unless n? and (n is n.toLowerCase()) then false
else if n.match /^([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,15}?$/ then true
else false
_check_remote_service : (n) -> GenericSocialBinding._check_remote_service(n)
check_inputs : () ->
if err = super() then return err
else if not(@remote_service?) then return new Error "No remote_service given"
else if not(@_check_remote_service(@remote_service)) then return new Error "invalid remote_service"
else if not(@name_regexp?) then return new Error "No name_regexp given"
else return null
resource_id : () -> @remote_service
exports.TwitterBinding = TwitterBinding
exports.FacebookBinding = FacebookBinding
exports.RedditBinding = RedditBinding
exports.KeybaseBinding = KeybaseBinding
exports.GithubBinding = GithubBinding
exports.GenericWebSiteBinding = GenericWebSiteBinding
exports.CoinbaseBinding = CoinbaseBinding
exports.DnsBinding = DnsBinding
exports.HackerNewsBinding = HackerNewsBinding
exports.SocialNetworkBinding = SocialNetworkBinding
exports.BitbucketBinding = BitbucketBinding
exports.GenericSocialBinding = GenericSocialBinding
#==========================================================================
| true | {cieq,Base} = require './base'
{constants} = require './constants'
urlmod = require 'url'
#==========================================================================
class WebServiceBinding extends Base
#------
_v_customize_json : (ret) ->
ret.body.service = o if (o = @service_obj())?
#---------------
_service_obj_check : (x) -> return not(x?)
#---------------
# service has to be optional because some legacy sigchains
# use this type to prove ownership of a new key with no
# service section
_optional_sections : () -> super().concat(["revoke", "service"])
#---------------
# For Twitter, Github, etc, this will be empty. For non-signle-occupants,
# it will be the unique id for the resource, like https://keybase.io/ for
# Web services.
resource_id : () -> ""
#---------------
_type : () -> constants.sig_types.web_service_binding
#---------------
_type_v2 : (revoke_flag) ->
if @revoke? or revoke_flag then constants.sig_types_v2.web_service_binding_with_revoke
else constants.sig_types_v2.web_service_binding
#---------------
_v_check : ({json}, cb) ->
await super { json }, defer err
if not(err?) and not(@_service_obj_check(json?.body?.service))
err = new Error "Bad service object found"
cb err
#==========================================================================
class SocialNetworkBinding extends WebServiceBinding
_service_obj_check : (x) ->
so = @service_obj()
return (x? and cieq(so.username, x.username) and cieq(so.name, x.name))
service_obj : -> { name : @service_name(), username : @user.remote }
is_remote_proof : () -> true
@single_occupancy : () -> true
single_occupancy : () -> SocialNetworkBinding.single_occupancy()
@normalize_name : (n) ->
n = n.toLowerCase()
if n[0] is '@' then n[1...] else n
normalize_name : (n) ->
n or= @user.remote
if @check_name(n) then SocialNetworkBinding.normalize_name n
else null
check_inputs : () ->
if (@check_name(@user.remote)) then null
else new Error "Bad remote_username given: #{@user.remote}"
to_key_value_pair : () ->
{ key : PI:KEY:<KEY>END_PI(), value : @normalize_name() }
#==========================================================================
# A last-minute sanity check of the URL module
has_non_ascii = (s) ->
buf = Buffer.from s, 'utf8'
for i in [0...buf.length]
if buf.readUInt8(i) >= 128
return true
return false
#----------
class GenericWebSiteBinding extends WebServiceBinding
constructor : (args) ->
@remote_host = @parse args.remote_host
super args
@parse : (h, opts = {}) ->
ret = null
if h? and (h = h.toLowerCase())? and (o = urlmod.parse(h))? and
o.hostname? and (not(o.path?) or (o.path is '/')) and not(o.port?)
protocol = o.protocol or opts.protocol
if protocol?
ret = { protocol, hostname : o.hostname }
n = GenericWebSiteBinding.to_string(ret)
if has_non_ascii(n)
console.error "Bug in urlmod found: found non-ascii in URL: #{n}"
ret = null
return ret
parse : (h) -> GenericWebSiteBinding.parse h
to_key_value_pair : () -> {
key : PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI
value : @remote_host.hostname
}
@to_string : (o) ->
([ o.protocol, o.hostname ].join '//').toLowerCase()
@normalize_name : (s) ->
if (o = GenericWebSiteBinding.parse(s))? then GenericWebSiteBinding.to_string(o) else null
@check_name : (h) -> GenericWebSiteBinding.parse(h)?
check_name : (n) -> @parse(n)?
@single_occupancy : () -> false
single_occupancy : () -> GenericWebSiteBinding.single_occupancy()
resource_id : () -> @to_string()
to_string : () -> GenericWebSiteBinding.to_string @remote_host
_service_obj_check : (x) ->
so = @service_obj()
return x? and so? and cieq(so.protocol, x.protocol) and cieq(so.hostname, x.hostname)
service_obj : () -> @remote_host
is_remote_proof : () -> true
proof_type : () -> constants.proof_types.generic_web_site
@name_hint : () -> "a valid hostname, like `my.site.com`"
check_inputs : () ->
if @remote_host? then null
else new Error "Bad remote_host given"
check_existing : (proofs) ->
if (v = proofs.generic_web_site)?
for {check_data_json} in v
if cieq(GenericWebSiteBinding.to_string(check_data_json), @to_string())
return new Error "A live proof for #{@to_string()} already exists"
return null
#==========================================================================
class DnsBinding extends WebServiceBinding
constructor : (args) ->
@domain = @parse args.remote_host
super args
@parse : (h, opts = {}) ->
ret = null
if h?
h = "dns://#{h}" if h.indexOf("dns://") isnt 0
if h? and (h = h.toLowerCase())? and (o = urlmod.parse(h))? and
o.hostname? and (not(o.path?) or (o.path is '/')) and not(o.port?)
ret = o.hostname
if has_non_ascii(ret)
console.error "Bug in urlmod found: non-ASCII in done name: #{ret}"
ret = null
return ret
to_key_value_pair : () -> { key : "dns", value : @domain }
parse : (h) -> DnsBinding.parse(h)
@to_string : (o) -> o.domain
to_string : () -> @domain
normalize_name : (s) -> DnsBinding.parse(s)
@single_occupancy : () -> false
single_occupancy : () -> DnsBinding.single_occupancy()
resource_id : () -> @to_string()
_service_obj_check : (x) ->
so = @service_obj()
return x? and so? and cieq(so.protocol, x.protocol) and cieq(so.domain, x.domain)
@service_name : -> "dns"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.dns
@check_name : (n) -> DnsBinding.parse(n)?
check_name : (n) -> DnsBinding.check_name(n)
service_obj : () -> { protocol : "dns", @domain }
is_remote_proof : () -> true
check_inputs : () -> if @domain then null else new Error "Bad domain given"
@name_hint : () -> "A DNS domain name, like maxk.org"
check_existing : (proofs) ->
if (v = proofs.dns?)
for {check_data_json} in v
if cieq(GenericWebSiteBinding.to_string(check_data_json), @to_string())
return new Error "A live proof for #{@to_string()} already exists"
return null
#==========================================================================
class TwitterBinding extends SocialNetworkBinding
@service_name : -> "twitter"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.twitter
is_short : -> true
@check_name : (n) ->
ret = if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_]{1,20}$/ then true
else false
return ret
check_name : (n) -> TwitterBinding.check_name(n)
@name_hint : () -> "alphanumerics, between 1 and 15 characters long"
#==========================================================================
class FacebookBinding extends SocialNetworkBinding
@service_name : -> "facebook"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.facebook
is_short : -> true
@check_name : (n) ->
# Technically Facebook doesn't count dots in the character count, and also
# prohibits leading/trailing/consecutive dots.
ret = if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9.]{1,50}$/ then true
else false
return ret
check_name : (n) -> FacebookBinding.check_name(n)
@name_hint : () -> "alphanumerics and dots, between 1 and 50 characters long"
#==========================================================================
class KeybaseBinding extends WebServiceBinding
_service_obj_check : (x) -> not x?
@service_name : -> "keybase"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.keybase
service_obj : -> null
#==========================================================================
class GithubBinding extends SocialNetworkBinding
@service_name : -> "github"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.github
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9][a-z0-9-]{0,38}$/ then true
else false
@name_hint : () -> "alphanumerics, between 1 and 39 characters long"
check_name : (n) -> GithubBinding.check_name(n)
#==========================================================================
class BitbucketBinding extends SocialNetworkBinding
@service_name : -> "bitbucket"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.bitbucket
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-zA-Z0-9_\-]{0,31}/ then true
else false
@name_hint : () -> "alphanumerics, between 1 and 30 characters long"
check_name : (n) -> BitbucketBinding.check_name(n)
#==========================================================================
class RedditBinding extends SocialNetworkBinding
@service_name : -> "reddit"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.reddit
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_-]{3,20}$/ then true
else false
@name_hint : () -> "alphanumerics, between 3 and 20 characters long"
check_name : (n) -> RedditBinding.check_name(n)
#==========================================================================
class CoinbaseBinding extends SocialNetworkBinding
@service_name : -> "coinbase"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.coinbase
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_]{2,16}$/ then true
else false
@name_hint : () -> "alphanumerics, between 2 and 16 characters long"
check_name : (n) -> CoinbaseBinding.check_name(n)
#==========================================================================
class HackerNewsBinding extends SocialNetworkBinding
@service_name : -> "hackernews"
service_name : -> @constructor.service_name()
proof_type : -> constants.proof_types.hackernews
@check_name : (n) ->
if not n? or not (n = n.toLowerCase())? then false
else if n.match /^[a-z0-9_-]{2,15}$/ then true
else false
@name_hint : () -> "alphanumerics, between 2 and 15 characters long"
check_name : (n) -> HackerNewsBinding.check_name(n)
# HN names are case-sensitive
@normalize_name : (n) ->
if n[0] is '@' then n[1...] else n
normalize_name : (n) ->
n or= @user.remote
if @check_name(n) then HackerNewsBinding.normalize_name n
else null
_service_obj_check : (x) ->
so = @service_obj()
return (x? and (so.username is x.username) and cieq(so.name, x.name))
#==========================================================================
class GenericSocialBinding extends SocialNetworkBinding
constructor : (args) ->
@remote_service = args.remote_service
if (r = args.name_regexp)? then try @name_regexp = new RegExp(r)
super args
@single_occupancy : () -> false
single_occupancy : () -> GenericSocialBinding.single_occupancy()
service_name : -> @remote_service
proof_type : -> constants.proof_types.generic_social
check_name : (n) ->
unless n? and (n is n.toLowerCase()) then false
else if n.match @name_regexp then true
else false
@name_hint : () -> "valid username"
@_check_remote_service : (n) ->
unless n? and (n is n.toLowerCase()) then false
else if n.match /^([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,15}?$/ then true
else false
_check_remote_service : (n) -> GenericSocialBinding._check_remote_service(n)
check_inputs : () ->
if err = super() then return err
else if not(@remote_service?) then return new Error "No remote_service given"
else if not(@_check_remote_service(@remote_service)) then return new Error "invalid remote_service"
else if not(@name_regexp?) then return new Error "No name_regexp given"
else return null
resource_id : () -> @remote_service
exports.TwitterBinding = TwitterBinding
exports.FacebookBinding = FacebookBinding
exports.RedditBinding = RedditBinding
exports.KeybaseBinding = KeybaseBinding
exports.GithubBinding = GithubBinding
exports.GenericWebSiteBinding = GenericWebSiteBinding
exports.CoinbaseBinding = CoinbaseBinding
exports.DnsBinding = DnsBinding
exports.HackerNewsBinding = HackerNewsBinding
exports.SocialNetworkBinding = SocialNetworkBinding
exports.BitbucketBinding = BitbucketBinding
exports.GenericSocialBinding = GenericSocialBinding
#==========================================================================
|
[
{
"context": " actually works on node.js\r\n * https://github.com/Meettya/whet.extend\r\n *\r\n * Copyright 2012, Dmitrii Karpi",
"end": 125,
"score": 0.9996122121810913,
"start": 118,
"tag": "USERNAME",
"value": "Meettya"
},
{
"context": "ub.com/Meettya/whet.extend\r\n *\r\n * Copyr... | node_modules/whet.extend/src/whet.extend.coffee | firojkabir/lsg | 0 | ###
* whet.extend v0.9.7
* Standalone port of jQuery.extend that actually works on node.js
* https://github.com/Meettya/whet.extend
*
* Copyright 2012, Dmitrii Karpich
* Released under the MIT License
###
module.exports = extend = (deep, target, args...) ->
unless _isClass deep, 'Boolean'
args.unshift target
[ target, deep ] = [ deep or {}, false ]
#Handle case when target is a string or something (possible in deep copy)
target = {} if _isPrimitiveType target
for options in args when options?
for name, copy of options
target[name] = _findValue deep, copy, target[name]
target
###
Internal methods from now
###
_isClass = (obj, str) ->
"[object #{str}]" is Object::toString.call obj
_isOwnProp = (obj, prop) ->
Object::hasOwnProperty.call obj, prop
_isTypeOf = (obj, str) ->
str is typeof obj
_isPlainObj = (obj) ->
return false unless obj
return false if obj.nodeType or obj.setInterval or not _isClass obj, 'Object'
# Not own constructor property must be Object
return false if obj.constructor and
not _isOwnProp(obj, 'constructor') and
not _isOwnProp(obj.constructor::, 'isPrototypeOf')
# Own properties are enumerated firstly, so to speed up,
# if last one is own, then all properties are own.
key for key of obj
key is undefined or _isOwnProp obj, key
_isPrimitiveType = (obj) ->
not ( _isTypeOf(obj, 'object') or _isTypeOf(obj, 'function') )
_prepareClone = (copy, src) ->
if _isClass copy, 'Array'
if _isClass src, 'Array' then src else []
else
if _isPlainObj src then src else {}
_findValue = (deep, copy, src) ->
# if we're merging plain objects or arrays
if deep and ( _isClass(copy, 'Array') or _isPlainObj copy )
clone = _prepareClone copy, src
extend deep, clone, copy
else
copy
| 69131 | ###
* whet.extend v0.9.7
* Standalone port of jQuery.extend that actually works on node.js
* https://github.com/Meettya/whet.extend
*
* Copyright 2012, <NAME>
* Released under the MIT License
###
module.exports = extend = (deep, target, args...) ->
unless _isClass deep, 'Boolean'
args.unshift target
[ target, deep ] = [ deep or {}, false ]
#Handle case when target is a string or something (possible in deep copy)
target = {} if _isPrimitiveType target
for options in args when options?
for name, copy of options
target[name] = _findValue deep, copy, target[name]
target
###
Internal methods from now
###
_isClass = (obj, str) ->
"[object #{str}]" is Object::toString.call obj
_isOwnProp = (obj, prop) ->
Object::hasOwnProperty.call obj, prop
_isTypeOf = (obj, str) ->
str is typeof obj
_isPlainObj = (obj) ->
return false unless obj
return false if obj.nodeType or obj.setInterval or not _isClass obj, 'Object'
# Not own constructor property must be Object
return false if obj.constructor and
not _isOwnProp(obj, 'constructor') and
not _isOwnProp(obj.constructor::, 'isPrototypeOf')
# Own properties are enumerated firstly, so to speed up,
# if last one is own, then all properties are own.
key for key of obj
key is undefined or _isOwnProp obj, key
_isPrimitiveType = (obj) ->
not ( _isTypeOf(obj, 'object') or _isTypeOf(obj, 'function') )
_prepareClone = (copy, src) ->
if _isClass copy, 'Array'
if _isClass src, 'Array' then src else []
else
if _isPlainObj src then src else {}
_findValue = (deep, copy, src) ->
# if we're merging plain objects or arrays
if deep and ( _isClass(copy, 'Array') or _isPlainObj copy )
clone = _prepareClone copy, src
extend deep, clone, copy
else
copy
| true | ###
* whet.extend v0.9.7
* Standalone port of jQuery.extend that actually works on node.js
* https://github.com/Meettya/whet.extend
*
* Copyright 2012, PI:NAME:<NAME>END_PI
* Released under the MIT License
###
module.exports = extend = (deep, target, args...) ->
unless _isClass deep, 'Boolean'
args.unshift target
[ target, deep ] = [ deep or {}, false ]
#Handle case when target is a string or something (possible in deep copy)
target = {} if _isPrimitiveType target
for options in args when options?
for name, copy of options
target[name] = _findValue deep, copy, target[name]
target
###
Internal methods from now
###
_isClass = (obj, str) ->
"[object #{str}]" is Object::toString.call obj
_isOwnProp = (obj, prop) ->
Object::hasOwnProperty.call obj, prop
_isTypeOf = (obj, str) ->
str is typeof obj
_isPlainObj = (obj) ->
return false unless obj
return false if obj.nodeType or obj.setInterval or not _isClass obj, 'Object'
# Not own constructor property must be Object
return false if obj.constructor and
not _isOwnProp(obj, 'constructor') and
not _isOwnProp(obj.constructor::, 'isPrototypeOf')
# Own properties are enumerated firstly, so to speed up,
# if last one is own, then all properties are own.
key for key of obj
key is undefined or _isOwnProp obj, key
_isPrimitiveType = (obj) ->
not ( _isTypeOf(obj, 'object') or _isTypeOf(obj, 'function') )
_prepareClone = (copy, src) ->
if _isClass copy, 'Array'
if _isClass src, 'Array' then src else []
else
if _isPlainObj src then src else {}
_findValue = (deep, copy, src) ->
# if we're merging plain objects or arrays
if deep and ( _isClass(copy, 'Array') or _isPlainObj copy )
clone = _prepareClone copy, src
extend deep, clone, copy
else
copy
|
[
{
"context": "an input field does not satisfy a rule\n # @author Daniel Bartholomae\n class NotValidatorRule extends ValidatorRule\n ",
"end": 381,
"score": 0.9998905658721924,
"start": 363,
"tag": "NAME",
"value": "Daniel Bartholomae"
}
] | src/rules/Not.coffee | dbartholomae/node-validation-codes | 0 | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( ['./Rule'], (ValidatorRule) ->
# A rule to validate that an input field does not satisfy a rule
# @author Daniel Bartholomae
class NotValidatorRule extends ValidatorRule
# Create a new NotValidatorRule
#
# @param [ValidatorRule] rule The rule that should be negated
# @param [Object] (options) An optional list of options
constructor: (@rule, options) ->
super options
# Set the options for this and all its child rules
#
# @param [Object] (options) The options to be set
setOptions: (options) ->
@rule.setOptions options
super
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> 'Not' + violationCode for violationCode in @rule.getViolationCodes()
# Validate that a value does not satisfy a rule
#
# @param [Object] value The value to validate
# @return [Array<String>] [] if the value is valid, 'Not' + the violation codes of the negated rule if it isn't
validate: (value) -> if @rule.isValid(value) then @getViolationCodes() else []
) | 197466 | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( ['./Rule'], (ValidatorRule) ->
# A rule to validate that an input field does not satisfy a rule
# @author <NAME>
class NotValidatorRule extends ValidatorRule
# Create a new NotValidatorRule
#
# @param [ValidatorRule] rule The rule that should be negated
# @param [Object] (options) An optional list of options
constructor: (@rule, options) ->
super options
# Set the options for this and all its child rules
#
# @param [Object] (options) The options to be set
setOptions: (options) ->
@rule.setOptions options
super
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> 'Not' + violationCode for violationCode in @rule.getViolationCodes()
# Validate that a value does not satisfy a rule
#
# @param [Object] value The value to validate
# @return [Array<String>] [] if the value is valid, 'Not' + the violation codes of the negated rule if it isn't
validate: (value) -> if @rule.isValid(value) then @getViolationCodes() else []
) | true | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( ['./Rule'], (ValidatorRule) ->
# A rule to validate that an input field does not satisfy a rule
# @author PI:NAME:<NAME>END_PI
class NotValidatorRule extends ValidatorRule
# Create a new NotValidatorRule
#
# @param [ValidatorRule] rule The rule that should be negated
# @param [Object] (options) An optional list of options
constructor: (@rule, options) ->
super options
# Set the options for this and all its child rules
#
# @param [Object] (options) The options to be set
setOptions: (options) ->
@rule.setOptions options
super
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> 'Not' + violationCode for violationCode in @rule.getViolationCodes()
# Validate that a value does not satisfy a rule
#
# @param [Object] value The value to validate
# @return [Array<String>] [] if the value is valid, 'Not' + the violation codes of the negated rule if it isn't
validate: (value) -> if @rule.isValid(value) then @getViolationCodes() else []
) |
[
{
"context": "\"\n\t\t\n\t\t# define details\n\t\tdetails = {\n\t\t\tAuthor: 'Chris Tate <chris@autocode.run>'\n\t\t\tLicense: 'Apache-2.0'\n\t\t",
"end": 956,
"score": 0.9998643398284912,
"start": 946,
"tag": "NAME",
"value": "Chris Tate"
},
{
"context": "ine details\n\t\tdetails = ... | cli/src/help.coffee | crystal/autocode-js | 92 | module.exports = (commands) ->
# load packages
pad = require 'pad'
getCommands = () ->
# define output
output = "Commands:\n\n"
# get longest command
command_max = 0
for command_name of commands
command = commands[command_name]
command_length = (command_name + (if command.opts then ' ' + command.opts else '')).length
if command_length > command_max
command_max = command_length
command_max++
command_max++
# add each command to output
for command_name of commands
command = commands[command_name]
output += ' '
output += pad(command_name + (if command.opts then ' ' + command.opts else ''), command_max, ' ')
output += "#{command.desc}\n"
return output
getCopyright = () ->
# define output
output = "Copyright (c) 2014-2016 Autocode. All Rights Reserved.\n"
getInfo = () ->
# add info to output
output = "\nInfo:\n\n"
# define details
details = {
Author: 'Chris Tate <chris@autocode.run>'
License: 'Apache-2.0'
Website: 'https://autocode.run'
Repository: 'https://github.com/ctate/autocode'
}
# get longest detail
detail_max = 0
for detail_name of details
detail = details[detail_name]
detail_length = detail_name.length
if detail_length > detail_max
detail_max = detail_length
detail_max++
detail_max++
# add each detail to output
for detail_name of details
detail = details[detail_name]
detail_name += ':'
output += ' ' + pad(detail_name, detail_max, ' ')
output += "#{detail}\n"
output += "\n"
getUsage = () ->
# define output
output = "Usage:\n\n"
output += "autocode [command]\n\n"
# define output
output = getUsage()
output += getCommands()
output += getInfo()
output += getCopyright()
| 94861 | module.exports = (commands) ->
# load packages
pad = require 'pad'
getCommands = () ->
# define output
output = "Commands:\n\n"
# get longest command
command_max = 0
for command_name of commands
command = commands[command_name]
command_length = (command_name + (if command.opts then ' ' + command.opts else '')).length
if command_length > command_max
command_max = command_length
command_max++
command_max++
# add each command to output
for command_name of commands
command = commands[command_name]
output += ' '
output += pad(command_name + (if command.opts then ' ' + command.opts else ''), command_max, ' ')
output += "#{command.desc}\n"
return output
getCopyright = () ->
# define output
output = "Copyright (c) 2014-2016 Autocode. All Rights Reserved.\n"
getInfo = () ->
# add info to output
output = "\nInfo:\n\n"
# define details
details = {
Author: '<NAME> <<EMAIL>>'
License: 'Apache-2.0'
Website: 'https://autocode.run'
Repository: 'https://github.com/ctate/autocode'
}
# get longest detail
detail_max = 0
for detail_name of details
detail = details[detail_name]
detail_length = detail_name.length
if detail_length > detail_max
detail_max = detail_length
detail_max++
detail_max++
# add each detail to output
for detail_name of details
detail = details[detail_name]
detail_name += ':'
output += ' ' + pad(detail_name, detail_max, ' ')
output += "#{detail}\n"
output += "\n"
getUsage = () ->
# define output
output = "Usage:\n\n"
output += "autocode [command]\n\n"
# define output
output = getUsage()
output += getCommands()
output += getInfo()
output += getCopyright()
| true | module.exports = (commands) ->
# load packages
pad = require 'pad'
getCommands = () ->
# define output
output = "Commands:\n\n"
# get longest command
command_max = 0
for command_name of commands
command = commands[command_name]
command_length = (command_name + (if command.opts then ' ' + command.opts else '')).length
if command_length > command_max
command_max = command_length
command_max++
command_max++
# add each command to output
for command_name of commands
command = commands[command_name]
output += ' '
output += pad(command_name + (if command.opts then ' ' + command.opts else ''), command_max, ' ')
output += "#{command.desc}\n"
return output
getCopyright = () ->
# define output
output = "Copyright (c) 2014-2016 Autocode. All Rights Reserved.\n"
getInfo = () ->
# add info to output
output = "\nInfo:\n\n"
# define details
details = {
Author: 'PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>'
License: 'Apache-2.0'
Website: 'https://autocode.run'
Repository: 'https://github.com/ctate/autocode'
}
# get longest detail
detail_max = 0
for detail_name of details
detail = details[detail_name]
detail_length = detail_name.length
if detail_length > detail_max
detail_max = detail_length
detail_max++
detail_max++
# add each detail to output
for detail_name of details
detail = details[detail_name]
detail_name += ':'
output += ' ' + pad(detail_name, detail_max, ' ')
output += "#{detail}\n"
output += "\n"
getUsage = () ->
# define output
output = "Usage:\n\n"
output += "autocode [command]\n\n"
# define output
output = getUsage()
output += getCommands()
output += getInfo()
output += getCopyright()
|
[
{
"context": "eoverview Tests for no-else-return rule.\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------",
"end": 81,
"score": 0.9996768832206726,
"start": 62,
"tag": "NAME",
"value": "Ian Christian Myers"
}
] | src/tests/rules/no-else-return.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-else-return rule.
# @author Ian Christian Myers
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-else-return'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-else-return', rule,
valid: [
'''
foo = ->
if yes
if no
return x
else
return y
'''
'''
->
if yes
return x
return y
'''
'''
->
if yes
loop
return x
else
return y
'''
'''
->
x = yes
if x
return x
else if x is no
return no
'''
'''
->
if yes
notAReturn()
else
return y
'''
'''
->
if x
notAReturn()
else if y
return true
else
notAReturn()
'''
'''
->
if x
return true
else if y
notAReturn()
else
notAReturn()
'''
'''
if 0
if 0
;
else
;
else
;
'''
,
code: '''
->
if true
return x
else if false
return y
'''
options: [allowElseIf: yes]
,
code: '''
->
if (x)
return true
else if (y)
notAReturn()
else
notAReturn()
'''
options: [allowElseIf: yes]
,
code: '''
->
x = true
if (x)
return x
else if (x is false)
return false
'''
options: [allowElseIf: yes]
]
invalid: [
code: '''
->
if (true)
return x
else
return y
'''
# output: 'function foo1() { if (true) { return x; } return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
x = bar
return x
else
y = baz
return y
'''
# output:
# 'function foo2() { if (true) { var x = bar; return x; } var y = baz; return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true) then return x else return y
'''
# output: 'function foo3() { if (true) return x; return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
return x
else
return y
else
return z
'''
# output:
# 'function foo4() { if (true) { if (false) return x; return y; } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
w = y
else
w = x
else
return z
'''
# output:
# 'function foo5() { if (true) { if (false) { if (true) return x; w = y; } else { w = x; } } else { return z; } }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
else
return z
'''
# output:
# 'function foo6() { if (true) { if (false) { if (true) return x; return y; } } else { return z; } }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
return w
else
return z
'''
# output:
# 'function foo7() { if (true) { if (false) { if (true) return x; return y; } return w; } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
else
w = x
else
return z
'''
# output:
# 'function foo8() { if (true) { if (false) { if (true) return x; return y; } else { w = x; } } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (x)
return true
else if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9() {if (x) { return true; } else if (y) { return true; } notAReturn(); }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (x)
return true
else if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9a() {if (x) { return true; } if (y) { return true; } else { notAReturn(); } }'
options: [allowElseIf: no]
errors: [
messageId: 'unexpected'
type: 'IfStatement'
,
messageId: 'unexpected'
type: 'BlockStatement'
]
,
code: '''
->
if (x)
return true
if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9b() {if (x) { return true; } if (y) { return true; } notAReturn(); }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (foo)
return bar
else
(foo).bar()
'''
# output: 'function foo10() { if (foo) return bar; (foo).bar(); }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (foo) then return bar else [1, 2, 3].map(foo)
'''
# output: null
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
return x
else if (false)
return y
'''
# output:
# 'function foo19() { if (true) { return x; } if (false) { return y; } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
if (x)
return true
else if (y)
notAReturn()
else
notAReturn()
'''
# output:
# 'function foo20() {if (x) { return true; } if (y) { notAReturn() } else { notAReturn(); } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
x = true
if (x)
return x
else if x is false
return false
'''
# output:
# 'function foo21() { var x = true; if (x) { return x; } if (x === false) { return false; } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
while foo
if bar
return
else
baz
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if foo
if bar
return
else
baz
else
qux
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if foo
return
else
if bar
no
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
]
| 123472 | ###*
# @fileoverview Tests for no-else-return rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-else-return'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-else-return', rule,
valid: [
'''
foo = ->
if yes
if no
return x
else
return y
'''
'''
->
if yes
return x
return y
'''
'''
->
if yes
loop
return x
else
return y
'''
'''
->
x = yes
if x
return x
else if x is no
return no
'''
'''
->
if yes
notAReturn()
else
return y
'''
'''
->
if x
notAReturn()
else if y
return true
else
notAReturn()
'''
'''
->
if x
return true
else if y
notAReturn()
else
notAReturn()
'''
'''
if 0
if 0
;
else
;
else
;
'''
,
code: '''
->
if true
return x
else if false
return y
'''
options: [allowElseIf: yes]
,
code: '''
->
if (x)
return true
else if (y)
notAReturn()
else
notAReturn()
'''
options: [allowElseIf: yes]
,
code: '''
->
x = true
if (x)
return x
else if (x is false)
return false
'''
options: [allowElseIf: yes]
]
invalid: [
code: '''
->
if (true)
return x
else
return y
'''
# output: 'function foo1() { if (true) { return x; } return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
x = bar
return x
else
y = baz
return y
'''
# output:
# 'function foo2() { if (true) { var x = bar; return x; } var y = baz; return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true) then return x else return y
'''
# output: 'function foo3() { if (true) return x; return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
return x
else
return y
else
return z
'''
# output:
# 'function foo4() { if (true) { if (false) return x; return y; } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
w = y
else
w = x
else
return z
'''
# output:
# 'function foo5() { if (true) { if (false) { if (true) return x; w = y; } else { w = x; } } else { return z; } }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
else
return z
'''
# output:
# 'function foo6() { if (true) { if (false) { if (true) return x; return y; } } else { return z; } }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
return w
else
return z
'''
# output:
# 'function foo7() { if (true) { if (false) { if (true) return x; return y; } return w; } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
else
w = x
else
return z
'''
# output:
# 'function foo8() { if (true) { if (false) { if (true) return x; return y; } else { w = x; } } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (x)
return true
else if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9() {if (x) { return true; } else if (y) { return true; } notAReturn(); }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (x)
return true
else if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9a() {if (x) { return true; } if (y) { return true; } else { notAReturn(); } }'
options: [allowElseIf: no]
errors: [
messageId: 'unexpected'
type: 'IfStatement'
,
messageId: 'unexpected'
type: 'BlockStatement'
]
,
code: '''
->
if (x)
return true
if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9b() {if (x) { return true; } if (y) { return true; } notAReturn(); }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (foo)
return bar
else
(foo).bar()
'''
# output: 'function foo10() { if (foo) return bar; (foo).bar(); }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (foo) then return bar else [1, 2, 3].map(foo)
'''
# output: null
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
return x
else if (false)
return y
'''
# output:
# 'function foo19() { if (true) { return x; } if (false) { return y; } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
if (x)
return true
else if (y)
notAReturn()
else
notAReturn()
'''
# output:
# 'function foo20() {if (x) { return true; } if (y) { notAReturn() } else { notAReturn(); } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
x = true
if (x)
return x
else if x is false
return false
'''
# output:
# 'function foo21() { var x = true; if (x) { return x; } if (x === false) { return false; } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
while foo
if bar
return
else
baz
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if foo
if bar
return
else
baz
else
qux
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if foo
return
else
if bar
no
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
]
| true | ###*
# @fileoverview Tests for no-else-return rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-else-return'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-else-return', rule,
valid: [
'''
foo = ->
if yes
if no
return x
else
return y
'''
'''
->
if yes
return x
return y
'''
'''
->
if yes
loop
return x
else
return y
'''
'''
->
x = yes
if x
return x
else if x is no
return no
'''
'''
->
if yes
notAReturn()
else
return y
'''
'''
->
if x
notAReturn()
else if y
return true
else
notAReturn()
'''
'''
->
if x
return true
else if y
notAReturn()
else
notAReturn()
'''
'''
if 0
if 0
;
else
;
else
;
'''
,
code: '''
->
if true
return x
else if false
return y
'''
options: [allowElseIf: yes]
,
code: '''
->
if (x)
return true
else if (y)
notAReturn()
else
notAReturn()
'''
options: [allowElseIf: yes]
,
code: '''
->
x = true
if (x)
return x
else if (x is false)
return false
'''
options: [allowElseIf: yes]
]
invalid: [
code: '''
->
if (true)
return x
else
return y
'''
# output: 'function foo1() { if (true) { return x; } return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
x = bar
return x
else
y = baz
return y
'''
# output:
# 'function foo2() { if (true) { var x = bar; return x; } var y = baz; return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true) then return x else return y
'''
# output: 'function foo3() { if (true) return x; return y; }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
return x
else
return y
else
return z
'''
# output:
# 'function foo4() { if (true) { if (false) return x; return y; } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
w = y
else
w = x
else
return z
'''
# output:
# 'function foo5() { if (true) { if (false) { if (true) return x; w = y; } else { w = x; } } else { return z; } }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
else
return z
'''
# output:
# 'function foo6() { if (true) { if (false) { if (true) return x; return y; } } else { return z; } }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
return w
else
return z
'''
# output:
# 'function foo7() { if (true) { if (false) { if (true) return x; return y; } return w; } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (true)
if (false)
if (true)
return x
else
return y
else
w = x
else
return z
'''
# output:
# 'function foo8() { if (true) { if (false) { if (true) return x; return y; } else { w = x; } } else { return z; } }' # Other case is fixed in the second pass.
errors: [
messageId: 'unexpected', type: 'BlockStatement'
,
messageId: 'unexpected', type: 'BlockStatement'
]
,
code: '''
->
if (x)
return true
else if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9() {if (x) { return true; } else if (y) { return true; } notAReturn(); }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (x)
return true
else if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9a() {if (x) { return true; } if (y) { return true; } else { notAReturn(); } }'
options: [allowElseIf: no]
errors: [
messageId: 'unexpected'
type: 'IfStatement'
,
messageId: 'unexpected'
type: 'BlockStatement'
]
,
code: '''
->
if (x)
return true
if (y)
return true
else
notAReturn()
'''
# output:
# 'function foo9b() {if (x) { return true; } if (y) { return true; } notAReturn(); }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (foo)
return bar
else
(foo).bar()
'''
# output: 'function foo10() { if (foo) return bar; (foo).bar(); }'
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (foo) then return bar else [1, 2, 3].map(foo)
'''
# output: null
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if (true)
return x
else if (false)
return y
'''
# output:
# 'function foo19() { if (true) { return x; } if (false) { return y; } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
if (x)
return true
else if (y)
notAReturn()
else
notAReturn()
'''
# output:
# 'function foo20() {if (x) { return true; } if (y) { notAReturn() } else { notAReturn(); } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
x = true
if (x)
return x
else if x is false
return false
'''
# output:
# 'function foo21() { var x = true; if (x) { return x; } if (x === false) { return false; } }'
options: [allowElseIf: no]
errors: [messageId: 'unexpected', type: 'IfStatement']
,
code: '''
->
while foo
if bar
return
else
baz
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if foo
if bar
return
else
baz
else
qux
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
,
code: '''
->
if foo
return
else
if bar
no
'''
errors: [messageId: 'unexpected', type: 'BlockStatement']
]
|
[
{
"context": "\nnikita = require '@nikitajs/core/lib'\n{tags, config} = require '../../test'\nt",
"end": 28,
"score": 0.8413353562355042,
"start": 23,
"tag": "USERNAME",
"value": "itajs"
},
{
"context": "ed.conf\"\n content:\n FallbackDNS: \"1.1.1.1\"\n reload:... | packages/file/test/types/systemd/resolved.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'file.types.systemd.resolved', ->
they 'servers as a string', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
FallbackDNS: "1.1.1.1"
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1
"""
trim: true
they 'servers as an array', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
FallbackDNS: ["1.1.1.1", "9.9.9.10", "8.8.8.8", "2606:4700:4700::1111"]
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1 9.9.9.10 8.8.8.8 2606:4700:4700::1111
"""
trim: true
they 'merge values', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
DNS: "ns0.fdn.fr"
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
"""
trim: true
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
ReadEtcHosts: "true"
merge: true
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
ReadEtcHosts=true
"""
trim: true
| 24086 |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'file.types.systemd.resolved', ->
they 'servers as a string', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
FallbackDNS: "1.1.1.1"
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1
"""
trim: true
they 'servers as an array', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
FallbackDNS: ["1.1.1.1", "192.168.3.11", "8.8.8.8", "fdf8:f53e:61e4::18"]
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1 192.168.3.11 8.8.8.8 2606:fc00:db20:35b:7399::5
"""
trim: true
they 'merge values', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
DNS: "ns0.fdn.fr"
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
"""
trim: true
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
ReadEtcHosts: "true"
merge: true
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
ReadEtcHosts=true
"""
trim: true
| true |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'file.types.systemd.resolved', ->
they 'servers as a string', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
FallbackDNS: "1.1.1.1"
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1
"""
trim: true
they 'servers as an array', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
FallbackDNS: ["1.1.1.1", "PI:IP_ADDRESS:192.168.3.11END_PI", "8.8.8.8", "PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI"]
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1 PI:IP_ADDRESS:192.168.3.11END_PI 8.8.8.8 2606:PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI
"""
trim: true
they 'merge values', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
DNS: "ns0.fdn.fr"
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
"""
trim: true
@file.types.systemd.resolved
target: "#{tmpdir}/resolved.conf"
content:
ReadEtcHosts: "true"
merge: true
reload: false
@fs.assert
target: "#{tmpdir}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
ReadEtcHosts=true
"""
trim: true
|
[
{
"context": "given artwork', ->\n @user.set 'id': 'current-user'\n @user.savedArtwork('bitty', success: (save",
"end": 3385,
"score": 0.5433845520019531,
"start": 3381,
"tag": "USERNAME",
"value": "user"
},
{
"context": "'follows an artist', ->\n @user.followArtist 'a... | src/test/lib/current_user.coffee | kierangillen/force | 1 | Q = require 'bluebird-q'
_ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../lib/current_user'
describe 'CurrentUser', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@user = new CurrentUser fabricate 'user'
afterEach ->
Backbone.sync.restore()
describe '#sync', ->
it 'does the right thing for fetch/save', ->
@user.save()
_.isUndefined(Backbone.sync.args[0][2].data).should.be.true()
@user.fetch()
_.keys(Backbone.sync.args[1][2].data).should.containEql 'access_token'
describe '#registeredForAuction', ->
describe 'when a user is not registered', ->
it 'returns false', (done) ->
@user.registeredForAuction 'foobar-auction', success: (boolean) ->
boolean.should.be.false()
done()
Backbone.sync.args[0][2].data.sale_id.should.equal 'foobar-auction'
Backbone.sync.args[0][2].success []
describe 'when a user is registered', ->
it 'returns true', (done) ->
@user.registeredForAuction 'foobar-auction-registered', success: (boolean) ->
boolean.should.be.true()
done()
Backbone.sync.args[0][2].data.sale_id.should.equal 'foobar-auction-registered'
Backbone.sync.args[0][2].success [{ id: 'existy' }]
it 'when given a user is logged out error soaks it up and returns false', (done) ->
@user.registeredForAuction 'foobar', success: (registered) ->
registered.should.equal false
done()
Backbone.sync.args[0][2].error { responseText: "A user is required" }
describe '#fetchQualifiedBidder', ->
describe 'when a user has no bidders', ->
it 'returns false', (done) ->
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success []
describe 'when a user has no bidders for the auction', ->
it 'returns false', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: true
sale: {
id: 'nothing'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success [bidder]
describe 'when a user is qualified', ->
it 'returns true', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: true
sale: {
id: 'foobar-auction'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.true()
done()
Backbone.sync.args[0][2].success [bidder]
describe 'when a user is not qualified', ->
it 'returns false', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: false
sale: {
id: 'foobar-auction'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success [bidder]
describe '#placeBid', ->
it 'creates a new bid position given the right params'
describe '#savedArtwork', ->
it 'passess true to success cb if the user has saved the given artwork', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty', success: (saved) ->
saved.should.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].success [ fabricate 'artwork' ]
it 'passes false to success cb if the user has not saved the given work', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
success: (saved) ->
saved.should.not.be.ok()
error: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].success [ ]
it 'when the collection is not found, false is passed to the success cb', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
success: (saved) ->
saved.should.not.be.ok()
error: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].error { responseText: "Collection not found" }
it 'calls the error cb for other errors', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
error: (msg) ->
msg.should.be.ok()
success: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].error { responseText: 'Unauthorized' }
describe '#followingArtists', ->
it 'makes the correct API call to retreive a list of artists the user is following', ->
@user.followingArtists()
Backbone.sync.args[0][0].should.equal 'read'
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/follow/artists'
describe 'CurrentUser', ->
beforeEach ->
@sd = require('sharify').data
@sd.SESSION_ID = 'cool-session-id'
@user = new CurrentUser fabricate 'user'
sinon.stub(Backbone, 'sync')
afterEach ->
Backbone.sync.restore()
describe '#defaultArtworkCollection', ->
it 'throws a sensible error when you forget to initialize artwork collections', ->
(=> @user.defaultArtworkCollection()).should.throw /Must call/
describe '#saveArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.saveArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'create'
describe '#removeArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.removeArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'delete'
describe '#fetchSuggestedHomepageArtworks', ->
it 'fetches homepages artworks', ->
@user.fetchSuggestedHomepageArtworks({})
Backbone.sync.args[0][2].url.should.containEql 'suggested/artworks/homepage'
describe '#followArtist', ->
it 'follows an artist', ->
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[1].url().should.containEql 'me/follow/artist'
it 'injects the access token', ->
@user.set accessToken: 'xfoobar'
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[2].access_token.should.equal 'xfoobar'
describe '#checkRegisteredForAuction', ->
it 'makes the correct API call, accepts normal options', (done) ->
@user.checkRegisteredForAuction
saleId: 'an-auction'
success: (status) ->
status.should.be.true()
done()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/bidders'
Backbone.sync.args[0][2].data.sale_id.should.equal 'an-auction'
Backbone.sync.args[0][2].success ['existy']
describe '#fetchNotifications', ->
it 'makes the correct API call and has default size of 10', ->
@user.fetchNotificationBundles
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications/feed'
Backbone.sync.args[0][2].data.size.should.equal 10
describe '#fetchAndMarkNotifications', ->
it 'makes the correct API call and has defaults', ->
@user.fetchAndMarkNotifications
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications'
Backbone.sync.args[0][2].data.type.should.equal 'ArtworkPublished'
Backbone.sync.args[0][2].data.unread.should.be.true()
Backbone.sync.args[0][2].data.size.should.equal 100
describe '#prepareForInquiry', ->
beforeEach ->
Backbone.sync.restore()
@user = new CurrentUser
sinon.stub Backbone, 'sync'
.returns Q.resolve()
it 'creates or persists everything needed to make an inquiry', ->
@user.prepareForInquiry().then ->
Backbone.sync.callCount.should.equal 2
Backbone.sync.args[0][1].url()
.should.containEql '/api/v1/me'
Backbone.sync.args[1][1].url
.should.containEql '/api/v1/me/collector_profile'
describe '#isChecked', ->
it 'translates a boolean attribute to on or off', ->
@user.set weekly_email: false, follow_email: true, offer_emails: false
_.isUndefined(@user.isChecked('weekly_email')).should.be.true()
_.isUndefined(@user.isChecked('offer_emails')).should.be.true()
@user.isChecked('follow_email').should.be.true()
describe 'authentications', ->
beforeEach ->
@authentications = [
{ id: '1', uid: '123456789', provider: 'twitter' }
{ id: '2', uid: '987654321', provider: 'facebook' }
]
describe 'relation', ->
it 'should inject initial authentications', ->
user = new CurrentUser authentications: @authentications
user.isLinkedTo('twitter').should.be.true()
user.isLinkedTo('facebook').should.be.true()
describe '#isLinkedTo', ->
it 'determines if an account is linked to an app provider', ->
@user.isLinkedTo 'twitter'
.should.be.false()
@user.related().authentications.reset @authentications
@user.isLinkedTo 'twitter'
.should.be.true()
@user.isLinkedTo 'facebook'
.should.be.true()
| 121940 | Q = require 'bluebird-q'
_ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../lib/current_user'
describe 'CurrentUser', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@user = new CurrentUser fabricate 'user'
afterEach ->
Backbone.sync.restore()
describe '#sync', ->
it 'does the right thing for fetch/save', ->
@user.save()
_.isUndefined(Backbone.sync.args[0][2].data).should.be.true()
@user.fetch()
_.keys(Backbone.sync.args[1][2].data).should.containEql 'access_token'
describe '#registeredForAuction', ->
describe 'when a user is not registered', ->
it 'returns false', (done) ->
@user.registeredForAuction 'foobar-auction', success: (boolean) ->
boolean.should.be.false()
done()
Backbone.sync.args[0][2].data.sale_id.should.equal 'foobar-auction'
Backbone.sync.args[0][2].success []
describe 'when a user is registered', ->
it 'returns true', (done) ->
@user.registeredForAuction 'foobar-auction-registered', success: (boolean) ->
boolean.should.be.true()
done()
Backbone.sync.args[0][2].data.sale_id.should.equal 'foobar-auction-registered'
Backbone.sync.args[0][2].success [{ id: 'existy' }]
it 'when given a user is logged out error soaks it up and returns false', (done) ->
@user.registeredForAuction 'foobar', success: (registered) ->
registered.should.equal false
done()
Backbone.sync.args[0][2].error { responseText: "A user is required" }
describe '#fetchQualifiedBidder', ->
describe 'when a user has no bidders', ->
it 'returns false', (done) ->
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success []
describe 'when a user has no bidders for the auction', ->
it 'returns false', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: true
sale: {
id: 'nothing'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success [bidder]
describe 'when a user is qualified', ->
it 'returns true', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: true
sale: {
id: 'foobar-auction'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.true()
done()
Backbone.sync.args[0][2].success [bidder]
describe 'when a user is not qualified', ->
it 'returns false', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: false
sale: {
id: 'foobar-auction'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success [bidder]
describe '#placeBid', ->
it 'creates a new bid position given the right params'
describe '#savedArtwork', ->
it 'passess true to success cb if the user has saved the given artwork', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty', success: (saved) ->
saved.should.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].success [ fabricate 'artwork' ]
it 'passes false to success cb if the user has not saved the given work', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
success: (saved) ->
saved.should.not.be.ok()
error: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].success [ ]
it 'when the collection is not found, false is passed to the success cb', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
success: (saved) ->
saved.should.not.be.ok()
error: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].error { responseText: "Collection not found" }
it 'calls the error cb for other errors', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
error: (msg) ->
msg.should.be.ok()
success: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].error { responseText: 'Unauthorized' }
describe '#followingArtists', ->
it 'makes the correct API call to retreive a list of artists the user is following', ->
@user.followingArtists()
Backbone.sync.args[0][0].should.equal 'read'
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/follow/artists'
describe 'CurrentUser', ->
beforeEach ->
@sd = require('sharify').data
@sd.SESSION_ID = 'cool-session-id'
@user = new CurrentUser fabricate 'user'
sinon.stub(Backbone, 'sync')
afterEach ->
Backbone.sync.restore()
describe '#defaultArtworkCollection', ->
it 'throws a sensible error when you forget to initialize artwork collections', ->
(=> @user.defaultArtworkCollection()).should.throw /Must call/
describe '#saveArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.saveArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'create'
describe '#removeArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.removeArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'delete'
describe '#fetchSuggestedHomepageArtworks', ->
it 'fetches homepages artworks', ->
@user.fetchSuggestedHomepageArtworks({})
Backbone.sync.args[0][2].url.should.containEql 'suggested/artworks/homepage'
describe '#followArtist', ->
it 'follows an artist', ->
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[1].url().should.containEql 'me/follow/artist'
it 'injects the access token', ->
@user.set accessToken: '<KEY>'
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[2].access_token.should.equal 'x<KEY>'
describe '#checkRegisteredForAuction', ->
it 'makes the correct API call, accepts normal options', (done) ->
@user.checkRegisteredForAuction
saleId: 'an-auction'
success: (status) ->
status.should.be.true()
done()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/bidders'
Backbone.sync.args[0][2].data.sale_id.should.equal 'an-auction'
Backbone.sync.args[0][2].success ['existy']
describe '#fetchNotifications', ->
it 'makes the correct API call and has default size of 10', ->
@user.fetchNotificationBundles
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications/feed'
Backbone.sync.args[0][2].data.size.should.equal 10
describe '#fetchAndMarkNotifications', ->
it 'makes the correct API call and has defaults', ->
@user.fetchAndMarkNotifications
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications'
Backbone.sync.args[0][2].data.type.should.equal 'ArtworkPublished'
Backbone.sync.args[0][2].data.unread.should.be.true()
Backbone.sync.args[0][2].data.size.should.equal 100
describe '#prepareForInquiry', ->
beforeEach ->
Backbone.sync.restore()
@user = new CurrentUser
sinon.stub Backbone, 'sync'
.returns Q.resolve()
it 'creates or persists everything needed to make an inquiry', ->
@user.prepareForInquiry().then ->
Backbone.sync.callCount.should.equal 2
Backbone.sync.args[0][1].url()
.should.containEql '/api/v1/me'
Backbone.sync.args[1][1].url
.should.containEql '/api/v1/me/collector_profile'
describe '#isChecked', ->
it 'translates a boolean attribute to on or off', ->
@user.set weekly_email: false, follow_email: true, offer_emails: false
_.isUndefined(@user.isChecked('weekly_email')).should.be.true()
_.isUndefined(@user.isChecked('offer_emails')).should.be.true()
@user.isChecked('follow_email').should.be.true()
describe 'authentications', ->
beforeEach ->
@authentications = [
{ id: '1', uid: '123456789', provider: 'twitter' }
{ id: '2', uid: '987654321', provider: 'facebook' }
]
describe 'relation', ->
it 'should inject initial authentications', ->
user = new CurrentUser authentications: @authentications
user.isLinkedTo('twitter').should.be.true()
user.isLinkedTo('facebook').should.be.true()
describe '#isLinkedTo', ->
it 'determines if an account is linked to an app provider', ->
@user.isLinkedTo 'twitter'
.should.be.false()
@user.related().authentications.reset @authentications
@user.isLinkedTo 'twitter'
.should.be.true()
@user.isLinkedTo 'facebook'
.should.be.true()
| true | Q = require 'bluebird-q'
_ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../lib/current_user'
describe 'CurrentUser', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@user = new CurrentUser fabricate 'user'
afterEach ->
Backbone.sync.restore()
describe '#sync', ->
it 'does the right thing for fetch/save', ->
@user.save()
_.isUndefined(Backbone.sync.args[0][2].data).should.be.true()
@user.fetch()
_.keys(Backbone.sync.args[1][2].data).should.containEql 'access_token'
describe '#registeredForAuction', ->
describe 'when a user is not registered', ->
it 'returns false', (done) ->
@user.registeredForAuction 'foobar-auction', success: (boolean) ->
boolean.should.be.false()
done()
Backbone.sync.args[0][2].data.sale_id.should.equal 'foobar-auction'
Backbone.sync.args[0][2].success []
describe 'when a user is registered', ->
it 'returns true', (done) ->
@user.registeredForAuction 'foobar-auction-registered', success: (boolean) ->
boolean.should.be.true()
done()
Backbone.sync.args[0][2].data.sale_id.should.equal 'foobar-auction-registered'
Backbone.sync.args[0][2].success [{ id: 'existy' }]
it 'when given a user is logged out error soaks it up and returns false', (done) ->
@user.registeredForAuction 'foobar', success: (registered) ->
registered.should.equal false
done()
Backbone.sync.args[0][2].error { responseText: "A user is required" }
describe '#fetchQualifiedBidder', ->
describe 'when a user has no bidders', ->
it 'returns false', (done) ->
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success []
describe 'when a user has no bidders for the auction', ->
it 'returns false', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: true
sale: {
id: 'nothing'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success [bidder]
describe 'when a user is qualified', ->
it 'returns true', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: true
sale: {
id: 'foobar-auction'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.true()
done()
Backbone.sync.args[0][2].success [bidder]
describe 'when a user is not qualified', ->
it 'returns false', (done) ->
bidder = {
id: 'me',
qualified_for_bidding: false
sale: {
id: 'foobar-auction'
}
}
@user.fetchQualifiedBidder 'foobar-auction', success: (bool) ->
bool.should.be.false()
done()
Backbone.sync.args[0][2].success [bidder]
describe '#placeBid', ->
it 'creates a new bid position given the right params'
describe '#savedArtwork', ->
it 'passess true to success cb if the user has saved the given artwork', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty', success: (saved) ->
saved.should.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].success [ fabricate 'artwork' ]
it 'passes false to success cb if the user has not saved the given work', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
success: (saved) ->
saved.should.not.be.ok()
error: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].success [ ]
it 'when the collection is not found, false is passed to the success cb', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
success: (saved) ->
saved.should.not.be.ok()
error: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].error { responseText: "Collection not found" }
it 'calls the error cb for other errors', ->
@user.set 'id': 'current-user'
@user.savedArtwork('bitty',
error: (msg) ->
msg.should.be.ok()
success: (msg) ->
msg.should.not.be.ok()
)
Backbone.sync.args[0][2].url.should.containEql '/api/v1/collection/saved-artwork/artworks?artworks[]=bitty&private=true&user_id=current-user'
Backbone.sync.args[0][2].error { responseText: 'Unauthorized' }
describe '#followingArtists', ->
it 'makes the correct API call to retreive a list of artists the user is following', ->
@user.followingArtists()
Backbone.sync.args[0][0].should.equal 'read'
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/follow/artists'
describe 'CurrentUser', ->
beforeEach ->
@sd = require('sharify').data
@sd.SESSION_ID = 'cool-session-id'
@user = new CurrentUser fabricate 'user'
sinon.stub(Backbone, 'sync')
afterEach ->
Backbone.sync.restore()
describe '#defaultArtworkCollection', ->
it 'throws a sensible error when you forget to initialize artwork collections', ->
(=> @user.defaultArtworkCollection()).should.throw /Must call/
describe '#saveArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.saveArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'create'
describe '#removeArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.removeArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'delete'
describe '#fetchSuggestedHomepageArtworks', ->
it 'fetches homepages artworks', ->
@user.fetchSuggestedHomepageArtworks({})
Backbone.sync.args[0][2].url.should.containEql 'suggested/artworks/homepage'
describe '#followArtist', ->
it 'follows an artist', ->
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[1].url().should.containEql 'me/follow/artist'
it 'injects the access token', ->
@user.set accessToken: 'PI:KEY:<KEY>END_PI'
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[2].access_token.should.equal 'xPI:KEY:<KEY>END_PI'
describe '#checkRegisteredForAuction', ->
it 'makes the correct API call, accepts normal options', (done) ->
@user.checkRegisteredForAuction
saleId: 'an-auction'
success: (status) ->
status.should.be.true()
done()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/bidders'
Backbone.sync.args[0][2].data.sale_id.should.equal 'an-auction'
Backbone.sync.args[0][2].success ['existy']
describe '#fetchNotifications', ->
it 'makes the correct API call and has default size of 10', ->
@user.fetchNotificationBundles
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications/feed'
Backbone.sync.args[0][2].data.size.should.equal 10
describe '#fetchAndMarkNotifications', ->
it 'makes the correct API call and has defaults', ->
@user.fetchAndMarkNotifications
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications'
Backbone.sync.args[0][2].data.type.should.equal 'ArtworkPublished'
Backbone.sync.args[0][2].data.unread.should.be.true()
Backbone.sync.args[0][2].data.size.should.equal 100
describe '#prepareForInquiry', ->
beforeEach ->
Backbone.sync.restore()
@user = new CurrentUser
sinon.stub Backbone, 'sync'
.returns Q.resolve()
it 'creates or persists everything needed to make an inquiry', ->
@user.prepareForInquiry().then ->
Backbone.sync.callCount.should.equal 2
Backbone.sync.args[0][1].url()
.should.containEql '/api/v1/me'
Backbone.sync.args[1][1].url
.should.containEql '/api/v1/me/collector_profile'
describe '#isChecked', ->
it 'translates a boolean attribute to on or off', ->
@user.set weekly_email: false, follow_email: true, offer_emails: false
_.isUndefined(@user.isChecked('weekly_email')).should.be.true()
_.isUndefined(@user.isChecked('offer_emails')).should.be.true()
@user.isChecked('follow_email').should.be.true()
describe 'authentications', ->
beforeEach ->
@authentications = [
{ id: '1', uid: '123456789', provider: 'twitter' }
{ id: '2', uid: '987654321', provider: 'facebook' }
]
describe 'relation', ->
it 'should inject initial authentications', ->
user = new CurrentUser authentications: @authentications
user.isLinkedTo('twitter').should.be.true()
user.isLinkedTo('facebook').should.be.true()
describe '#isLinkedTo', ->
it 'determines if an account is linked to an app provider', ->
@user.isLinkedTo 'twitter'
.should.be.false()
@user.related().authentications.reset @authentications
@user.isLinkedTo 'twitter'
.should.be.true()
@user.isLinkedTo 'facebook'
.should.be.true()
|
[
{
"context": "iew Tests for max-nested-callbacks rule.\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------",
"end": 87,
"score": 0.9996574521064758,
"start": 68,
"tag": "NAME",
"value": "Ian Christian Myers"
}
] | src/tests/rules/max-nested-callbacks.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for max-nested-callbacks rule.
# @author Ian Christian Myers
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/max-nested-callbacks'
{RuleTester} = require 'eslint'
path = require 'path'
OPENING = 'foo(-> '
CLOSING = ')'
###*
# Generates a code string with the specified number of nested callbacks.
# @param {int} times The number of times to nest the callbacks.
# @returns {string} Code with the specified number of nested callbacks
# @private
###
nestFunctions = (times) ->
openings = ''
closings = ''
i = 0
while i < times
openings += OPENING
closings += CLOSING
i++
openings + closings
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'max-nested-callbacks', rule,
valid: [
code: 'foo -> bar thing, (data) ->', options: [3]
,
code: '''
foo = ->
bar ->
baz ->
qux foo
'''
options: [2]
,
code: 'fn ->, ->, ->', options: [2]
,
nestFunctions 10
,
# object property options
code: 'foo -> bar thing, (data) ->'
options: [max: 3]
]
invalid: [
code:
'foo -> bar thing, (data) -> baz ->'
options: [2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
,
code:
'foo -> if isTrue then bar (data) -> baz ->'
options: [2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
,
code: nestFunctions 11
errors: [
message: 'Too many nested callbacks (11). Maximum allowed is 10.'
type: 'FunctionExpression'
]
,
# object property options
code:
'foo -> bar thing, (data) -> baz ->'
options: [max: 2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
]
| 225185 | ###*
# @fileoverview Tests for max-nested-callbacks rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/max-nested-callbacks'
{RuleTester} = require 'eslint'
path = require 'path'
OPENING = 'foo(-> '
CLOSING = ')'
###*
# Generates a code string with the specified number of nested callbacks.
# @param {int} times The number of times to nest the callbacks.
# @returns {string} Code with the specified number of nested callbacks
# @private
###
nestFunctions = (times) ->
openings = ''
closings = ''
i = 0
while i < times
openings += OPENING
closings += CLOSING
i++
openings + closings
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'max-nested-callbacks', rule,
valid: [
code: 'foo -> bar thing, (data) ->', options: [3]
,
code: '''
foo = ->
bar ->
baz ->
qux foo
'''
options: [2]
,
code: 'fn ->, ->, ->', options: [2]
,
nestFunctions 10
,
# object property options
code: 'foo -> bar thing, (data) ->'
options: [max: 3]
]
invalid: [
code:
'foo -> bar thing, (data) -> baz ->'
options: [2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
,
code:
'foo -> if isTrue then bar (data) -> baz ->'
options: [2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
,
code: nestFunctions 11
errors: [
message: 'Too many nested callbacks (11). Maximum allowed is 10.'
type: 'FunctionExpression'
]
,
# object property options
code:
'foo -> bar thing, (data) -> baz ->'
options: [max: 2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
]
| true | ###*
# @fileoverview Tests for max-nested-callbacks rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/max-nested-callbacks'
{RuleTester} = require 'eslint'
path = require 'path'
OPENING = 'foo(-> '
CLOSING = ')'
###*
# Generates a code string with the specified number of nested callbacks.
# @param {int} times The number of times to nest the callbacks.
# @returns {string} Code with the specified number of nested callbacks
# @private
###
nestFunctions = (times) ->
openings = ''
closings = ''
i = 0
while i < times
openings += OPENING
closings += CLOSING
i++
openings + closings
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'max-nested-callbacks', rule,
valid: [
code: 'foo -> bar thing, (data) ->', options: [3]
,
code: '''
foo = ->
bar ->
baz ->
qux foo
'''
options: [2]
,
code: 'fn ->, ->, ->', options: [2]
,
nestFunctions 10
,
# object property options
code: 'foo -> bar thing, (data) ->'
options: [max: 3]
]
invalid: [
code:
'foo -> bar thing, (data) -> baz ->'
options: [2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
,
code:
'foo -> if isTrue then bar (data) -> baz ->'
options: [2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
,
code: nestFunctions 11
errors: [
message: 'Too many nested callbacks (11). Maximum allowed is 10.'
type: 'FunctionExpression'
]
,
# object property options
code:
'foo -> bar thing, (data) -> baz ->'
options: [max: 2]
errors: [
message: 'Too many nested callbacks (3). Maximum allowed is 2.'
type: 'FunctionExpression'
]
]
|
[
{
"context": "extends TypeTool\n @shouldParse: (key) -> key is 'tySh'\n\n constructor: (layer, length) ->\n super(lay",
"end": 153,
"score": 0.9845390319824219,
"start": 149,
"tag": "KEY",
"value": "tySh"
}
] | lib/psd/layer_info/legacy_typetool.coffee | LoginovIlya/psd.js | 2,218 | _ = require 'lodash'
TypeTool = require './typetool.coffee'
module.exports = class LegacyTypeTool extends TypeTool
@shouldParse: (key) -> key is 'tySh'
constructor: (layer, length) ->
super(layer, length)
@transform = {}
@faces = []
@styles = []
@lines = []
@type = 0
@scalingFactor = 0
@characterCount = 0
@horzPlace = 0
@vertPlace = 0
@selectStart = 0
@selectEnd = 0
@color = null
@antialias = null
parse: ->
@file.seek 2, true # Version
@parseTransformInfo()
# Font information
@file.seek 2, true
facesCount = @file.readShort()
for i in [0...facesCount]
@faces.push _({}).tap (face) =>
face.mark = @file.readShort()
face.fontType = @file.readInt()
face.fontName = @file.readString()
face.fontFamilyName = @file.readString()
face.fontStyleName = @file.readString()
face.script = @file.readShort()
face.numberAxesVector = @file.readInt()
face.vector = []
for j in [0...face.numberAxesVector]
face.vector.push @file.readInt()
stylesCount = @file.readShort()
for i in [0...stylesCount]
@styles.push _({}).tap (style) =>
style.mark = @file.readShort()
style.faceMark = @file.readShort()
style.size = @file.readInt()
style.tracking = @file.readInt()
style.kerning = @file.readInt()
style.leading = @file.readInt()
style.baseShift = @file.readInt()
style.autoKern = @file.readBoolean()
@file.seek 1, true
style.rotate = @file.readBoolean()
@type = @file.readShort()
@scalingFactor = @file.readInt()
@characterCount = @file.readInt()
@horzPlace = @file.readInt()
@vertPlace = @file.readInt()
@selectStart = @file.readInt()
@selectEnd = @file.readInt()
linesCount = @file.readShort()
for i in [0...linesCount]
@lines.push _({}).tap (line) ->
line.charCount = @file.readInt()
line.orientation = @file.readShort()
line.alignment = @file.readShort()
line.actualChar = @file.readShort()
line.style = @file.readShort()
@color = @file.readSpaceColor()
@antialias = @file.readBoolean()
| 148884 | _ = require 'lodash'
TypeTool = require './typetool.coffee'
module.exports = class LegacyTypeTool extends TypeTool
@shouldParse: (key) -> key is '<KEY>'
constructor: (layer, length) ->
super(layer, length)
@transform = {}
@faces = []
@styles = []
@lines = []
@type = 0
@scalingFactor = 0
@characterCount = 0
@horzPlace = 0
@vertPlace = 0
@selectStart = 0
@selectEnd = 0
@color = null
@antialias = null
parse: ->
@file.seek 2, true # Version
@parseTransformInfo()
# Font information
@file.seek 2, true
facesCount = @file.readShort()
for i in [0...facesCount]
@faces.push _({}).tap (face) =>
face.mark = @file.readShort()
face.fontType = @file.readInt()
face.fontName = @file.readString()
face.fontFamilyName = @file.readString()
face.fontStyleName = @file.readString()
face.script = @file.readShort()
face.numberAxesVector = @file.readInt()
face.vector = []
for j in [0...face.numberAxesVector]
face.vector.push @file.readInt()
stylesCount = @file.readShort()
for i in [0...stylesCount]
@styles.push _({}).tap (style) =>
style.mark = @file.readShort()
style.faceMark = @file.readShort()
style.size = @file.readInt()
style.tracking = @file.readInt()
style.kerning = @file.readInt()
style.leading = @file.readInt()
style.baseShift = @file.readInt()
style.autoKern = @file.readBoolean()
@file.seek 1, true
style.rotate = @file.readBoolean()
@type = @file.readShort()
@scalingFactor = @file.readInt()
@characterCount = @file.readInt()
@horzPlace = @file.readInt()
@vertPlace = @file.readInt()
@selectStart = @file.readInt()
@selectEnd = @file.readInt()
linesCount = @file.readShort()
for i in [0...linesCount]
@lines.push _({}).tap (line) ->
line.charCount = @file.readInt()
line.orientation = @file.readShort()
line.alignment = @file.readShort()
line.actualChar = @file.readShort()
line.style = @file.readShort()
@color = @file.readSpaceColor()
@antialias = @file.readBoolean()
| true | _ = require 'lodash'
TypeTool = require './typetool.coffee'
module.exports = class LegacyTypeTool extends TypeTool
@shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI'
constructor: (layer, length) ->
super(layer, length)
@transform = {}
@faces = []
@styles = []
@lines = []
@type = 0
@scalingFactor = 0
@characterCount = 0
@horzPlace = 0
@vertPlace = 0
@selectStart = 0
@selectEnd = 0
@color = null
@antialias = null
parse: ->
@file.seek 2, true # Version
@parseTransformInfo()
# Font information
@file.seek 2, true
facesCount = @file.readShort()
for i in [0...facesCount]
@faces.push _({}).tap (face) =>
face.mark = @file.readShort()
face.fontType = @file.readInt()
face.fontName = @file.readString()
face.fontFamilyName = @file.readString()
face.fontStyleName = @file.readString()
face.script = @file.readShort()
face.numberAxesVector = @file.readInt()
face.vector = []
for j in [0...face.numberAxesVector]
face.vector.push @file.readInt()
stylesCount = @file.readShort()
for i in [0...stylesCount]
@styles.push _({}).tap (style) =>
style.mark = @file.readShort()
style.faceMark = @file.readShort()
style.size = @file.readInt()
style.tracking = @file.readInt()
style.kerning = @file.readInt()
style.leading = @file.readInt()
style.baseShift = @file.readInt()
style.autoKern = @file.readBoolean()
@file.seek 1, true
style.rotate = @file.readBoolean()
@type = @file.readShort()
@scalingFactor = @file.readInt()
@characterCount = @file.readInt()
@horzPlace = @file.readInt()
@vertPlace = @file.readInt()
@selectStart = @file.readInt()
@selectEnd = @file.readInt()
linesCount = @file.readShort()
for i in [0...linesCount]
@lines.push _({}).tap (line) ->
line.charCount = @file.readInt()
line.orientation = @file.readShort()
line.alignment = @file.readShort()
line.actualChar = @file.readShort()
line.style = @file.readShort()
@color = @file.readSpaceColor()
@antialias = @file.readBoolean()
|
[
{
"context": "ne or two tight twists.\n '''\n\n scientificName: 'Taurotragus oryx'\n mainImage: 'assets/fieldguide-content/mammals/",
"end": 507,
"score": 0.9920796751976013,
"start": 491,
"tag": "NAME",
"value": "Taurotragus oryx"
}
] | app/lib/field-guide-content/eland.coffee | zooniverse/wildcam-gorongosa-facebook | 7 | module.exports =
label: 'Common Eland'
description: '''
The common eland is the world’s largest antelope. It has a cowlike body with a massive neck and large shoulders. Common elands have a smooth coat that is yellowish-brown or tan in color and may h ave white vertical stripes running along the body. They have a long, thin tail that ends in a black tuft. Their ears are small and narrow and their horns are nearly straight, with one or two tight twists.
'''
scientificName: 'Taurotragus oryx'
mainImage: 'assets/fieldguide-content/mammals/eland/eland-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '2-3.4 m'
}, {
label: 'Height'
value: '1.25-1.83 m'
}, {
label: 'Weight'
value: '317-942 kg'
}, {
label: 'Lifespan'
value: '15-20 years'
}, {
label: 'Gestation'
value: '9 months'
}, {
label: 'Avg. number of offspring'
value: '1'
}]
sections: [{
title: 'Habitat'
content: 'Common elands are found in grasslands, mountains, subdeserts, acacia savanna, and miombo woodland areas. They avoid deserts, forests, and swamps.'
}, {
title: 'Diet'
content: 'The common eland is a mixed feeder. They feed on grass and other vegetation near the ground during the rainy season and on leaves, shoots, or fruits of taller vegetation during the dry season.'
}, {
title: 'Predators'
content: 'Lions, spotted hyenas'
}, {
title: 'Behavior'
content: '''
The common eland is one of the most nomadic antelopes; females have home ranges of up to 500 square km. The social organization of the eland is somewhat different from that of other antelopes. The older the males, the more solitary they become, while younger animals may form small groups.
'''
}, {
title: 'Breeding'
content: '''
The common eland breeds year-round. After a gestation period of nine months, females will give birth to a single calf. Females with young calves come together in nursery groups. After the young are weaned at about three months, the mothers rejoin the female herds, and the calves remain together in the nursery group. Juveniles usually remain in the nursery group until they are almost two years old.
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The common eland is the world’s largest antelope species as well as the slowest. It tops out at a speed of 40 km/h (or 25 mph) and quickly tires.</li>
<li>The common eland is an accomplished high jumper, easily clearing 2 m.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/eland/eland-map.jpg"/>'
}]
| 161903 | module.exports =
label: 'Common Eland'
description: '''
The common eland is the world’s largest antelope. It has a cowlike body with a massive neck and large shoulders. Common elands have a smooth coat that is yellowish-brown or tan in color and may h ave white vertical stripes running along the body. They have a long, thin tail that ends in a black tuft. Their ears are small and narrow and their horns are nearly straight, with one or two tight twists.
'''
scientificName: '<NAME>'
mainImage: 'assets/fieldguide-content/mammals/eland/eland-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '2-3.4 m'
}, {
label: 'Height'
value: '1.25-1.83 m'
}, {
label: 'Weight'
value: '317-942 kg'
}, {
label: 'Lifespan'
value: '15-20 years'
}, {
label: 'Gestation'
value: '9 months'
}, {
label: 'Avg. number of offspring'
value: '1'
}]
sections: [{
title: 'Habitat'
content: 'Common elands are found in grasslands, mountains, subdeserts, acacia savanna, and miombo woodland areas. They avoid deserts, forests, and swamps.'
}, {
title: 'Diet'
content: 'The common eland is a mixed feeder. They feed on grass and other vegetation near the ground during the rainy season and on leaves, shoots, or fruits of taller vegetation during the dry season.'
}, {
title: 'Predators'
content: 'Lions, spotted hyenas'
}, {
title: 'Behavior'
content: '''
The common eland is one of the most nomadic antelopes; females have home ranges of up to 500 square km. The social organization of the eland is somewhat different from that of other antelopes. The older the males, the more solitary they become, while younger animals may form small groups.
'''
}, {
title: 'Breeding'
content: '''
The common eland breeds year-round. After a gestation period of nine months, females will give birth to a single calf. Females with young calves come together in nursery groups. After the young are weaned at about three months, the mothers rejoin the female herds, and the calves remain together in the nursery group. Juveniles usually remain in the nursery group until they are almost two years old.
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The common eland is the world’s largest antelope species as well as the slowest. It tops out at a speed of 40 km/h (or 25 mph) and quickly tires.</li>
<li>The common eland is an accomplished high jumper, easily clearing 2 m.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/eland/eland-map.jpg"/>'
}]
| true | module.exports =
label: 'Common Eland'
description: '''
The common eland is the world’s largest antelope. It has a cowlike body with a massive neck and large shoulders. Common elands have a smooth coat that is yellowish-brown or tan in color and may h ave white vertical stripes running along the body. They have a long, thin tail that ends in a black tuft. Their ears are small and narrow and their horns are nearly straight, with one or two tight twists.
'''
scientificName: 'PI:NAME:<NAME>END_PI'
mainImage: 'assets/fieldguide-content/mammals/eland/eland-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '2-3.4 m'
}, {
label: 'Height'
value: '1.25-1.83 m'
}, {
label: 'Weight'
value: '317-942 kg'
}, {
label: 'Lifespan'
value: '15-20 years'
}, {
label: 'Gestation'
value: '9 months'
}, {
label: 'Avg. number of offspring'
value: '1'
}]
sections: [{
title: 'Habitat'
content: 'Common elands are found in grasslands, mountains, subdeserts, acacia savanna, and miombo woodland areas. They avoid deserts, forests, and swamps.'
}, {
title: 'Diet'
content: 'The common eland is a mixed feeder. They feed on grass and other vegetation near the ground during the rainy season and on leaves, shoots, or fruits of taller vegetation during the dry season.'
}, {
title: 'Predators'
content: 'Lions, spotted hyenas'
}, {
title: 'Behavior'
content: '''
The common eland is one of the most nomadic antelopes; females have home ranges of up to 500 square km. The social organization of the eland is somewhat different from that of other antelopes. The older the males, the more solitary they become, while younger animals may form small groups.
'''
}, {
title: 'Breeding'
content: '''
The common eland breeds year-round. After a gestation period of nine months, females will give birth to a single calf. Females with young calves come together in nursery groups. After the young are weaned at about three months, the mothers rejoin the female herds, and the calves remain together in the nursery group. Juveniles usually remain in the nursery group until they are almost two years old.
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The common eland is the world’s largest antelope species as well as the slowest. It tops out at a speed of 40 km/h (or 25 mph) and quickly tires.</li>
<li>The common eland is an accomplished high jumper, easily clearing 2 m.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/eland/eland-map.jpg"/>'
}]
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.999916672706604,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/store-cart.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.
# Cart-specific script should go here.
class @StoreCart
@setEnabled: (flag) ->
$('.js-store-add-to-cart').prop 'disabled', !flag
$('#product-form').data 'disabled', !flag
| 79629 | # 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.
# Cart-specific script should go here.
class @StoreCart
@setEnabled: (flag) ->
$('.js-store-add-to-cart').prop 'disabled', !flag
$('#product-form').data 'disabled', !flag
| 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.
# Cart-specific script should go here.
class @StoreCart
@setEnabled: (flag) ->
$('.js-store-add-to-cart').prop 'disabled', !flag
$('#product-form').data 'disabled', !flag
|
[
{
"context": "# Copyright (c) 2014 sobataro <sobatarooo@gmail.com>\n# Released under the MIT l",
"end": 29,
"score": 0.6938810348510742,
"start": 21,
"tag": "USERNAME",
"value": "sobataro"
},
{
"context": "# Copyright (c) 2014 sobataro <sobatarooo@gmail.com>\n# Released under the MIT... | src/pull_request_checker.coffee | sobataro/robotaro | 2 | # Copyright (c) 2014 sobataro <sobatarooo@gmail.com>
# Released under the MIT license
# http://opensource.org/licenses/mit-license.php
Q = require("q")
config = require("config")
PullRequestTuple = require("./pull_request_tuple")
githubot = require("githubot")(
logger: # dummy robot only has error logger
error: (e) ->
console.error e
, config.get("github"))
class PullRequestChecker
@makePullRequestTuples: () ->
console.log "fetching pull requests from github (it may take a while)"
url = "orgs/#{config.get("github.orgName")}/issues?filter=all&state=open&per_page=100"
d = Q.defer()
githubot.get url, (issues) =>
issuesWithPR = (issue for issue in issues when issue.pull_request? and issue.comments > 0)
tuples = (new PullRequestTuple(i, githubot) for i in issuesWithPR)
tuples = (t.fetch() for t in tuples)
Q.allSettled(tuples).then (promises) =>
console.log ''
d.resolve (p.value for p in promises)
d.promise
@_makeMessage: (ignoredList, title, pullRequestFormatter) ->
message = []
if ignoredList.length > 0
message.push title
for t in ignoredList
message.push pullRequestFormatter t
message.push '' # section separator
message
@checkIssuesCommentsPullRequests: (pullRequestTuples) ->
console.log "checking ignored pull requests"
ignored = (t for t in pullRequestTuples when t.isNotCommented())
unmerged = (t for t in pullRequestTuples when t.isUnmergedLGTM())
halfway = (t for t in pullRequestTuples when t.isHalfwayReviewedAndForgotten())
conflict = (t for t in pullRequestTuples when t.isConflicting())
message = []
message = message.concat @_makeMessage(ignored,
"*誰もレビューしていないプルリクが #{ignored.length} 件ある、誰かレビューしてくだち* @channel",
(t) -> t.makeDescriptionText())
message = message.concat @_makeMessage(unmerged,
"*LGTMなのにマージされていないプルリクが #{unmerged.length} 件あるっぽい*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterCommenterText()}")
message = message.concat @_makeMessage(halfway,
"*レビューの途中で放置されているプルリクが #{halfway.length} 件あるかも?*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterCommenterText()}")
message = message.concat @_makeMessage(conflict,
"*コンフリクトしているプルリクが #{conflict.length} 件あるぽ*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterText()}")
if message.length == 0
message.push "放置されてそうなプルリクはない٩(๑❛ᴗ❛๑)۶"
else if message.length > 20
message.push "ワオ!大漁大漁!"
else
message.pop()
console.log "done."
message.join("\n")
@check: (sendMessage) ->
Q.when()
.then @makePullRequestTuples
.done (pullRequests) =>
(t.makeIndicators() for t in pullRequests)
sendMessage @checkIssuesCommentsPullRequests(pullRequests)
module.exports = PullRequestChecker
| 204243 | # Copyright (c) 2014 sobataro <<EMAIL>>
# Released under the MIT license
# http://opensource.org/licenses/mit-license.php
Q = require("q")
config = require("config")
PullRequestTuple = require("./pull_request_tuple")
githubot = require("githubot")(
logger: # dummy robot only has error logger
error: (e) ->
console.error e
, config.get("github"))
class PullRequestChecker
@makePullRequestTuples: () ->
console.log "fetching pull requests from github (it may take a while)"
url = "orgs/#{config.get("github.orgName")}/issues?filter=all&state=open&per_page=100"
d = Q.defer()
githubot.get url, (issues) =>
issuesWithPR = (issue for issue in issues when issue.pull_request? and issue.comments > 0)
tuples = (new PullRequestTuple(i, githubot) for i in issuesWithPR)
tuples = (t.fetch() for t in tuples)
Q.allSettled(tuples).then (promises) =>
console.log ''
d.resolve (p.value for p in promises)
d.promise
@_makeMessage: (ignoredList, title, pullRequestFormatter) ->
message = []
if ignoredList.length > 0
message.push title
for t in ignoredList
message.push pullRequestFormatter t
message.push '' # section separator
message
@checkIssuesCommentsPullRequests: (pullRequestTuples) ->
console.log "checking ignored pull requests"
ignored = (t for t in pullRequestTuples when t.isNotCommented())
unmerged = (t for t in pullRequestTuples when t.isUnmergedLGTM())
halfway = (t for t in pullRequestTuples when t.isHalfwayReviewedAndForgotten())
conflict = (t for t in pullRequestTuples when t.isConflicting())
message = []
message = message.concat @_makeMessage(ignored,
"*誰もレビューしていないプルリクが #{ignored.length} 件ある、誰かレビューしてくだち* @channel",
(t) -> t.makeDescriptionText())
message = message.concat @_makeMessage(unmerged,
"*LGTMなのにマージされていないプルリクが #{unmerged.length} 件あるっぽい*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterCommenterText()}")
message = message.concat @_makeMessage(halfway,
"*レビューの途中で放置されているプルリクが #{halfway.length} 件あるかも?*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterCommenterText()}")
message = message.concat @_makeMessage(conflict,
"*コンフリクトしているプルリクが #{conflict.length} 件あるぽ*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterText()}")
if message.length == 0
message.push "放置されてそうなプルリクはない٩(๑❛ᴗ❛๑)۶"
else if message.length > 20
message.push "ワオ!大漁大漁!"
else
message.pop()
console.log "done."
message.join("\n")
@check: (sendMessage) ->
Q.when()
.then @makePullRequestTuples
.done (pullRequests) =>
(t.makeIndicators() for t in pullRequests)
sendMessage @checkIssuesCommentsPullRequests(pullRequests)
module.exports = PullRequestChecker
| true | # Copyright (c) 2014 sobataro <PI:EMAIL:<EMAIL>END_PI>
# Released under the MIT license
# http://opensource.org/licenses/mit-license.php
Q = require("q")
config = require("config")
PullRequestTuple = require("./pull_request_tuple")
githubot = require("githubot")(
logger: # dummy robot only has error logger
error: (e) ->
console.error e
, config.get("github"))
class PullRequestChecker
@makePullRequestTuples: () ->
console.log "fetching pull requests from github (it may take a while)"
url = "orgs/#{config.get("github.orgName")}/issues?filter=all&state=open&per_page=100"
d = Q.defer()
githubot.get url, (issues) =>
issuesWithPR = (issue for issue in issues when issue.pull_request? and issue.comments > 0)
tuples = (new PullRequestTuple(i, githubot) for i in issuesWithPR)
tuples = (t.fetch() for t in tuples)
Q.allSettled(tuples).then (promises) =>
console.log ''
d.resolve (p.value for p in promises)
d.promise
@_makeMessage: (ignoredList, title, pullRequestFormatter) ->
message = []
if ignoredList.length > 0
message.push title
for t in ignoredList
message.push pullRequestFormatter t
message.push '' # section separator
message
@checkIssuesCommentsPullRequests: (pullRequestTuples) ->
console.log "checking ignored pull requests"
ignored = (t for t in pullRequestTuples when t.isNotCommented())
unmerged = (t for t in pullRequestTuples when t.isUnmergedLGTM())
halfway = (t for t in pullRequestTuples when t.isHalfwayReviewedAndForgotten())
conflict = (t for t in pullRequestTuples when t.isConflicting())
message = []
message = message.concat @_makeMessage(ignored,
"*誰もレビューしていないプルリクが #{ignored.length} 件ある、誰かレビューしてくだち* @channel",
(t) -> t.makeDescriptionText())
message = message.concat @_makeMessage(unmerged,
"*LGTMなのにマージされていないプルリクが #{unmerged.length} 件あるっぽい*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterCommenterText()}")
message = message.concat @_makeMessage(halfway,
"*レビューの途中で放置されているプルリクが #{halfway.length} 件あるかも?*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterCommenterText()}")
message = message.concat @_makeMessage(conflict,
"*コンフリクトしているプルリクが #{conflict.length} 件あるぽ*",
(t) -> "#{t.makeDescriptionText()} #{t.makeReplyToPRCreaterText()}")
if message.length == 0
message.push "放置されてそうなプルリクはない٩(๑❛ᴗ❛๑)۶"
else if message.length > 20
message.push "ワオ!大漁大漁!"
else
message.pop()
console.log "done."
message.join("\n")
@check: (sendMessage) ->
Q.when()
.then @makePullRequestTuples
.done (pullRequests) =>
(t.makeIndicators() for t in pullRequests)
sendMessage @checkIssuesCommentsPullRequests(pullRequests)
module.exports = PullRequestChecker
|
[
{
"context": "uire('moves/gaff.coffee')])\n )\n\n # LEVEL 2 - Huminski\n game.addScreen(new Battle(game, requir",
"end": 1502,
"score": 0.5603129267692566,
"start": 1501,
"tag": "NAME",
"value": "H"
},
{
"context": "ee'),\n 'Hello! T-bone Huminsk... | src/js/main.coffee | Huntrr/Battle-Resolution | 0 | # coffeelint: disable=max_line_length
$ = require './lib/jquery.js'
$ ->
Game = require './game.coffee'
game = new Game()
testConf = require './testmode-conf.coffee'
if testConf.enabled
Test = require './testmode.coffee'
test = new Test(game)
test.run()
else
# set up starter moves
game.addMove require 'moves/flourish.coffee'
game.addMove require 'moves/clash.coffee'
game.addMove require 'moves/cross.coffee'
# set up screen order
Menu = require './screens/menu.coffee'
game.addScreen(new Menu(game))
Oak = require './screens/oak.coffee'
game.addScreen(new Oak(game))
# Battle screens
Battle = require './battle.coffee'
# LEVEL 1 - Novice
game.addScreen(new Battle(game, require('debaters/novice.coffee'),
'This is my first debate! I hope I can
convince you of the merits of COMMUNISM...
But first... How long is my speech?',
'Wow. You\'re really good. I think I\'m
going to go home and read up on Keynes...',
'And THAT\'S why we must affirm the resolution
that... I mean we must NEGATE the resolution that
resolved... this house would... we are...
COMMUNISM!',
[require('moves/gaff.coffee')])
)
# LEVEL 2 - Huminski
game.addScreen(new Battle(game, require('debaters/huminski.coffee'),
'Hello! T-bone Huminski here! Fear my
sandals, and prepare to die!',
'Oh... I lost... This is like the Integrity
Basketball game all over again... Oh well...
At least I still have my sandals',
'Hah! That\'s right! I just GATSBY\'d you
so hard! ... Yea that makes sense, why
wouldn\'t it!?',
[require('moves/ramble.coffee'), require('moves/sandal.coffee')])
)
# LEVEL 3 - Really aggressive novice
game.addScreen(new Battle(game, require('debaters/aggressive-novice.coffee'),
'FREE THOUGHT is dumb! SMITH only teaches you
stock arguments anyway...',
'I still refuse to change my way of thinking.
The JUDGE was the wrong one here.',
'Ha ha! I told you FREE THOUGHT was super dumb',
#require('moves/gaff.coffee'), add back in later
[require('moves/shout.coffee')])
)
# LEVEL 4 - Sophmore Slumper
game.addScreen(new Battle(game, require('debaters/sophmore-slumper.coffee'),
'ugh, why even bother with this...? woo COMMUNISM',
'whatever CAPITALISM is fine too I guess',
'what? gee dude, you sure you\'re a varsity worthy debater?',
[require('moves/half-assed-case.coffee')]))
# LEVEL 5 - The Complexity Rubric (secretly a communist plot)
game.addScreen(new Battle(game, require('debaters/complexity-rubric.coffee'),
'WE WILL NOT STOP UNTIL THE ENTIRE WORLD HAS SUCCUMBED TO STANDARDS AND QUOTAS.',
'TOO...MUCH...RISK TAKING...',
'YOU ARE A DEVELOPING DEBATER. LONG LIVE THE COMMON CORE!',
[require('moves/star.coffee')])
)
# LEVEL 6 - THE CAPTAIN (boss #1, picture of McMoran)
# (start dialogue with 'This is your captain speaking. Today, I discovered communism')
game.addScreen(new Battle(game, require('debaters/captain.coffee'),
'This is your captain speaking. Today, I have discovered COMMUNISM.
And I\'m here to share with you the good word... You may have beaten
my right-hand-man (The Complexity Rubric), but you aren\'t going to
beat me, no matter how AMBIGUOUS you are!',
'Oh... I guess I\'m wrong after all... You\'ve embraced more AMBIGUITY
than I ever have. Oh, teach me more about this INVISIBLE HAND! CAPITALISM
reminds me a lot of my Complexity Rubric.',
'That\'s right! Embrace AMBIGUITY? Psh, yeah right! More like, embrace
the fact that OWNERSHIP is a LIE and the CLASS-HIERARCHY must die!',
[require('moves/philosophize.coffee'), require('moves/announce.coffee')])
)
# LEVEL 20 - CDA Parent Judge
game.addScreen(new Battle(game, require('debaters/parent-judge.coffee'),
'WAIT JUST ONE FREE THINKING MOMENT!! You\'ve been
advocating for CAPITALISM?! How\'d you win so much when I\'ve been judging you?
Either way... You\'ll have to beat ME now! ',
'Wait who\'s judging? Huh... well you win this time! I guess there\'s a reason
you\'ve been winning ',
'pffft guess I\'ll have to look out twice for dirty CAPPY\'S like yourself',
[require 'moves/mess-up-flow.coffee']))
# LEVEL 22 - Sam Aldershof
#
# LEVEL 25 - Nicolo Marzaro
#
# LEVEL 27 - Alyssa Bilinski
# Special move: Talk about Grandma's cookies (the Judge was thoroughly Pathos'd)
game.addScreen(new Battle(game, require('debaters/alyssa.coffee'),
'If YALE (together with XI JINPING) taught me anything,
it\'s that I can save the world, and that the path to
saving the world is paved with COMMUNISM. And FRESH BAKED
COOKIES. Here are my THREE CONTENTIONS. You\'re about to be
BILINSKI\'d!',
'What? I lost!? The last time I LOST a debate was in <ERROR: 404,
YEAR NOT FOUND>! Well I guess you\'re right after all then...',
'And THAT is why you must AFFIRM. Thank you for your time and I now
stand open to kicking this CAPPY\'s BUTT'
[require('moves/bake-cookies.coffee'), require('moves/save-world.coffee')]))
# LEVEL 28 - Ron Paul (thinks he is at Libertarian National Convention)
game.addScreen(new Battle(game, require('./debaters/ron-paul.coffee'),
'Is this the Libertarian National Convention??
... ... ...whaaaaaat? Invisible hands?
Radical freedom?',
'Blasted! Well I guess I\'ll run again next year',
'HA! ...Wait I won something? It wasn\'t the pesidency was it?
....... didn\'t think so',
[require 'moves/run-for-pres.coffee']))
# LEVEL 29 - Xi Jinping
# PLOT TWIST: LOSE MESSAGE: Reveal EVAN IS A COMMY (You can see your friend now, but I have a surprise for you...)
game.addScreen(new Battle(game, require('debaters/xi.coffee'),
'Has the little money-grabbing punk come to rescue his little friend? I knew I couldn\'t trust those CORRUPT officials to do my dirty work. Now it is time for me to end this.',
'...I now realize the error of the dream of reviving WORLDWIDE COMMUNISM. You can see your friend now, but we have created a monster that even I cannot contain...',
'Should have sent Kissinger.',
[require('moves/communism.coffee')]))
# LEVEL "30" - Evan streams
# OPENER: I WAS THE COMMUNIST ALL ALONG
# Need a super lengthy explanation...
game.addScreen(new Battle(game, require('debaters/evan.coffee'),
'SURPRISE! I was the DIRTY COMMY the whole time! You see, like everyone
in CHINA, I quickly realized the merits of COMMUNISM and shed all traces of
my CAPITALIST past! Then, using my superior DEBATE ABILITIES, I convinced the
rest of the CDA to join me. If it hadn\'t been for you MEDDLING DEBATER(S), I would
have succeeded in my goal of TAKING OVER THE WORLD! But wait... There might be one
last hope. If I can convince you to join me--and embrace the COMMY CAUSE--we might,
together, have enough debate power to destroy CAPITALISM once and for all! That\'s
it! RESOLVED: You are going to help me take over the world! I have three major
CONTENTIONS!',
'What. What? You mean... You\'re right! There IS no society on the PLANET ideal enough
for COMMUNISM to be successful! I never thought about it like that... I guess... I guess...
I guess I\'ll just have to settle for CAPITALISM. Thank you, young stranger, for saving
me from my own destruction... I owe you. The world owes you. AMERICA owes you! And for
that reason, Mr. Judge, I urge you to negate the aforementioned resolution. Good job KID,
you won.',
'And that is why, Mr. Speaker, you MUST affirm the resolution! Take that you CAPITALIST
PIG! Now, join me, and together we will take over the world!',
[])
)
# Closing screen for winning, show Evan back to good side
# start the game
game.start()
| 110271 | # coffeelint: disable=max_line_length
$ = require './lib/jquery.js'
$ ->
Game = require './game.coffee'
game = new Game()
testConf = require './testmode-conf.coffee'
if testConf.enabled
Test = require './testmode.coffee'
test = new Test(game)
test.run()
else
# set up starter moves
game.addMove require 'moves/flourish.coffee'
game.addMove require 'moves/clash.coffee'
game.addMove require 'moves/cross.coffee'
# set up screen order
Menu = require './screens/menu.coffee'
game.addScreen(new Menu(game))
Oak = require './screens/oak.coffee'
game.addScreen(new Oak(game))
# Battle screens
Battle = require './battle.coffee'
# LEVEL 1 - Novice
game.addScreen(new Battle(game, require('debaters/novice.coffee'),
'This is my first debate! I hope I can
convince you of the merits of COMMUNISM...
But first... How long is my speech?',
'Wow. You\'re really good. I think I\'m
going to go home and read up on Keynes...',
'And THAT\'S why we must affirm the resolution
that... I mean we must NEGATE the resolution that
resolved... this house would... we are...
COMMUNISM!',
[require('moves/gaff.coffee')])
)
# LEVEL 2 - <NAME>uminski
game.addScreen(new Battle(game, require('debaters/huminski.coffee'),
'Hello! T-bone <NAME>ski here! Fear my
sandals, and prepare to die!',
'Oh... I lost... This is like the Integrity
Basketball game all over again... Oh well...
At least I still have my sandals',
'Hah! That\'s right! I just GATSBY\'d you
so hard! ... Yea that makes sense, why
wouldn\'t it!?',
[require('moves/ramble.coffee'), require('moves/sandal.coffee')])
)
# LEVEL 3 - Really aggressive novice
game.addScreen(new Battle(game, require('debaters/aggressive-novice.coffee'),
'FREE THOUGHT is dumb! SMITH only teaches you
stock arguments anyway...',
'I still refuse to change my way of thinking.
The JUDGE was the wrong one here.',
'Ha ha! I told you FREE THOUGHT was super dumb',
#require('moves/gaff.coffee'), add back in later
[require('moves/shout.coffee')])
)
# LEVEL 4 - Sophmore Slumper
game.addScreen(new Battle(game, require('debaters/sophmore-slumper.coffee'),
'ugh, why even bother with this...? woo COMMUNISM',
'whatever CAPITALISM is fine too I guess',
'what? gee dude, you sure you\'re a varsity worthy debater?',
[require('moves/half-assed-case.coffee')]))
# LEVEL 5 - The Complexity Rubric (secretly a communist plot)
game.addScreen(new Battle(game, require('debaters/complexity-rubric.coffee'),
'WE WILL NOT STOP UNTIL THE ENTIRE WORLD HAS SUCCUMBED TO STANDARDS AND QUOTAS.',
'TOO...MUCH...RISK TAKING...',
'YOU ARE A DEVELOPING DEBATER. LONG LIVE THE COMMON CORE!',
[require('moves/star.coffee')])
)
# LEVEL 6 - THE CAPTAIN (boss #1, picture of McMoran)
# (start dialogue with 'This is your captain speaking. Today, I discovered communism')
game.addScreen(new Battle(game, require('debaters/captain.coffee'),
'This is your captain speaking. Today, I have discovered COMMUNISM.
And I\'m here to share with you the good word... You may have beaten
my right-hand-man (The Complexity Rubric), but you aren\'t going to
beat me, no matter how AMBIGUOUS you are!',
'Oh... I guess I\'m wrong after all... You\'ve embraced more AMBIGUITY
than I ever have. Oh, teach me more about this INVISIBLE HAND! CAPITALISM
reminds me a lot of my Complexity Rubric.',
'That\'s right! Embrace AMBIGUITY? Psh, yeah right! More like, embrace
the fact that OWNERSHIP is a LIE and the CLASS-HIERARCHY must die!',
[require('moves/philosophize.coffee'), require('moves/announce.coffee')])
)
# LEVEL 20 - CDA Parent Judge
game.addScreen(new Battle(game, require('debaters/parent-judge.coffee'),
'WAIT JUST ONE FREE THINKING MOMENT!! You\'ve been
advocating for CAPITALISM?! How\'d you win so much when I\'ve been judging you?
Either way... You\'ll have to beat ME now! ',
'Wait who\'s judging? Huh... well you win this time! I guess there\'s a reason
you\'ve been winning ',
'pffft guess I\'ll have to look out twice for dirty CAPPY\'S like yourself',
[require 'moves/mess-up-flow.coffee']))
# LEVEL 22 - <NAME>
#
# LEVEL 25 - <NAME>
#
# LEVEL 27 - <NAME>
# Special move: Talk about Grandma's cookies (the Judge was thoroughly Pathos'd)
game.addScreen(new Battle(game, require('debaters/alyssa.coffee'),
'If YALE (together with XI JINPING) taught me anything,
it\'s that I can save the world, and that the path to
saving the world is paved with COMMUNISM. And FRESH BAKED
COOKIES. Here are my THREE CONTENTIONS. You\'re about to be
BILINSKI\'d!',
'What? I lost!? The last time I LOST a debate was in <ERROR: 404,
YEAR NOT FOUND>! Well I guess you\'re right after all then...',
'And THAT is why you must AFFIRM. Thank you for your time and I now
stand open to kicking this CAPPY\'s BUTT'
[require('moves/bake-cookies.coffee'), require('moves/save-world.coffee')]))
# LEVEL 28 - <NAME> (thinks he is at Libertarian National Convention)
game.addScreen(new Battle(game, require('./debaters/ron-paul.coffee'),
'Is this the Libertarian National Convention??
... ... ...whaaaaaat? Invisible hands?
Radical freedom?',
'Blasted! Well I guess I\'ll run again next year',
'HA! ...Wait I won something? It wasn\'t the pesidency was it?
....... didn\'t think so',
[require 'moves/run-for-pres.coffee']))
# LEVEL 29 - <NAME>
# PLOT TWIST: LOSE MESSAGE: Reveal EVAN IS A COMMY (You can see your friend now, but I have a surprise for you...)
game.addScreen(new Battle(game, require('debaters/xi.coffee'),
'Has the little money-grabbing punk come to rescue his little friend? I knew I couldn\'t trust those CORRUPT officials to do my dirty work. Now it is time for me to end this.',
'...I now realize the error of the dream of reviving WORLDWIDE COMMUNISM. You can see your friend now, but we have created a monster that even I cannot contain...',
'Should have sent Kissinger.',
[require('moves/communism.coffee')]))
# LEVEL "30" - Evan streams
# OPENER: I WAS THE COMMUNIST ALL ALONG
# Need a super lengthy explanation...
game.addScreen(new Battle(game, require('debaters/evan.coffee'),
'SURPRISE! I was the DIRTY COMMY the whole time! You see, like everyone
in CHINA, I quickly realized the merits of COMMUNISM and shed all traces of
my CAPITALIST past! Then, using my superior DEBATE ABILITIES, I convinced the
rest of the CDA to join me. If it hadn\'t been for you MEDDLING DEBATER(S), I would
have succeeded in my goal of TAKING OVER THE WORLD! But wait... There might be one
last hope. If I can convince you to join me--and embrace the COMMY CAUSE--we might,
together, have enough debate power to destroy CAPITALISM once and for all! That\'s
it! RESOLVED: You are going to help me take over the world! I have three major
CONTENTIONS!',
'What. What? You mean... You\'re right! There IS no society on the PLANET ideal enough
for COMMUNISM to be successful! I never thought about it like that... I guess... I guess...
I guess I\'ll just have to settle for CAPITALISM. Thank you, young stranger, for saving
me from my own destruction... I owe you. The world owes you. AMERICA owes you! And for
that reason, Mr. <NAME>udge, I urge you to negate the aforementioned resolution. Good job KID,
you won.',
'And that is why, Mr. Speaker, you MUST affirm the resolution! Take that you CAPITALIST
PIG! Now, join me, and together we will take over the world!',
[])
)
# Closing screen for winning, show Evan back to good side
# start the game
game.start()
| true | # coffeelint: disable=max_line_length
$ = require './lib/jquery.js'
$ ->
Game = require './game.coffee'
game = new Game()
testConf = require './testmode-conf.coffee'
if testConf.enabled
Test = require './testmode.coffee'
test = new Test(game)
test.run()
else
# set up starter moves
game.addMove require 'moves/flourish.coffee'
game.addMove require 'moves/clash.coffee'
game.addMove require 'moves/cross.coffee'
# set up screen order
Menu = require './screens/menu.coffee'
game.addScreen(new Menu(game))
Oak = require './screens/oak.coffee'
game.addScreen(new Oak(game))
# Battle screens
Battle = require './battle.coffee'
# LEVEL 1 - Novice
game.addScreen(new Battle(game, require('debaters/novice.coffee'),
'This is my first debate! I hope I can
convince you of the merits of COMMUNISM...
But first... How long is my speech?',
'Wow. You\'re really good. I think I\'m
going to go home and read up on Keynes...',
'And THAT\'S why we must affirm the resolution
that... I mean we must NEGATE the resolution that
resolved... this house would... we are...
COMMUNISM!',
[require('moves/gaff.coffee')])
)
# LEVEL 2 - PI:NAME:<NAME>END_PIuminski
game.addScreen(new Battle(game, require('debaters/huminski.coffee'),
'Hello! T-bone PI:NAME:<NAME>END_PIski here! Fear my
sandals, and prepare to die!',
'Oh... I lost... This is like the Integrity
Basketball game all over again... Oh well...
At least I still have my sandals',
'Hah! That\'s right! I just GATSBY\'d you
so hard! ... Yea that makes sense, why
wouldn\'t it!?',
[require('moves/ramble.coffee'), require('moves/sandal.coffee')])
)
# LEVEL 3 - Really aggressive novice
game.addScreen(new Battle(game, require('debaters/aggressive-novice.coffee'),
'FREE THOUGHT is dumb! SMITH only teaches you
stock arguments anyway...',
'I still refuse to change my way of thinking.
The JUDGE was the wrong one here.',
'Ha ha! I told you FREE THOUGHT was super dumb',
#require('moves/gaff.coffee'), add back in later
[require('moves/shout.coffee')])
)
# LEVEL 4 - Sophmore Slumper
game.addScreen(new Battle(game, require('debaters/sophmore-slumper.coffee'),
'ugh, why even bother with this...? woo COMMUNISM',
'whatever CAPITALISM is fine too I guess',
'what? gee dude, you sure you\'re a varsity worthy debater?',
[require('moves/half-assed-case.coffee')]))
# LEVEL 5 - The Complexity Rubric (secretly a communist plot)
game.addScreen(new Battle(game, require('debaters/complexity-rubric.coffee'),
'WE WILL NOT STOP UNTIL THE ENTIRE WORLD HAS SUCCUMBED TO STANDARDS AND QUOTAS.',
'TOO...MUCH...RISK TAKING...',
'YOU ARE A DEVELOPING DEBATER. LONG LIVE THE COMMON CORE!',
[require('moves/star.coffee')])
)
# LEVEL 6 - THE CAPTAIN (boss #1, picture of McMoran)
# (start dialogue with 'This is your captain speaking. Today, I discovered communism')
game.addScreen(new Battle(game, require('debaters/captain.coffee'),
'This is your captain speaking. Today, I have discovered COMMUNISM.
And I\'m here to share with you the good word... You may have beaten
my right-hand-man (The Complexity Rubric), but you aren\'t going to
beat me, no matter how AMBIGUOUS you are!',
'Oh... I guess I\'m wrong after all... You\'ve embraced more AMBIGUITY
than I ever have. Oh, teach me more about this INVISIBLE HAND! CAPITALISM
reminds me a lot of my Complexity Rubric.',
'That\'s right! Embrace AMBIGUITY? Psh, yeah right! More like, embrace
the fact that OWNERSHIP is a LIE and the CLASS-HIERARCHY must die!',
[require('moves/philosophize.coffee'), require('moves/announce.coffee')])
)
# LEVEL 20 - CDA Parent Judge
game.addScreen(new Battle(game, require('debaters/parent-judge.coffee'),
'WAIT JUST ONE FREE THINKING MOMENT!! You\'ve been
advocating for CAPITALISM?! How\'d you win so much when I\'ve been judging you?
Either way... You\'ll have to beat ME now! ',
'Wait who\'s judging? Huh... well you win this time! I guess there\'s a reason
you\'ve been winning ',
'pffft guess I\'ll have to look out twice for dirty CAPPY\'S like yourself',
[require 'moves/mess-up-flow.coffee']))
# LEVEL 22 - PI:NAME:<NAME>END_PI
#
# LEVEL 25 - PI:NAME:<NAME>END_PI
#
# LEVEL 27 - PI:NAME:<NAME>END_PI
# Special move: Talk about Grandma's cookies (the Judge was thoroughly Pathos'd)
game.addScreen(new Battle(game, require('debaters/alyssa.coffee'),
'If YALE (together with XI JINPING) taught me anything,
it\'s that I can save the world, and that the path to
saving the world is paved with COMMUNISM. And FRESH BAKED
COOKIES. Here are my THREE CONTENTIONS. You\'re about to be
BILINSKI\'d!',
'What? I lost!? The last time I LOST a debate was in <ERROR: 404,
YEAR NOT FOUND>! Well I guess you\'re right after all then...',
'And THAT is why you must AFFIRM. Thank you for your time and I now
stand open to kicking this CAPPY\'s BUTT'
[require('moves/bake-cookies.coffee'), require('moves/save-world.coffee')]))
# LEVEL 28 - PI:NAME:<NAME>END_PI (thinks he is at Libertarian National Convention)
game.addScreen(new Battle(game, require('./debaters/ron-paul.coffee'),
'Is this the Libertarian National Convention??
... ... ...whaaaaaat? Invisible hands?
Radical freedom?',
'Blasted! Well I guess I\'ll run again next year',
'HA! ...Wait I won something? It wasn\'t the pesidency was it?
....... didn\'t think so',
[require 'moves/run-for-pres.coffee']))
# LEVEL 29 - PI:NAME:<NAME>END_PI
# PLOT TWIST: LOSE MESSAGE: Reveal EVAN IS A COMMY (You can see your friend now, but I have a surprise for you...)
game.addScreen(new Battle(game, require('debaters/xi.coffee'),
'Has the little money-grabbing punk come to rescue his little friend? I knew I couldn\'t trust those CORRUPT officials to do my dirty work. Now it is time for me to end this.',
'...I now realize the error of the dream of reviving WORLDWIDE COMMUNISM. You can see your friend now, but we have created a monster that even I cannot contain...',
'Should have sent Kissinger.',
[require('moves/communism.coffee')]))
# LEVEL "30" - Evan streams
# OPENER: I WAS THE COMMUNIST ALL ALONG
# Need a super lengthy explanation...
game.addScreen(new Battle(game, require('debaters/evan.coffee'),
'SURPRISE! I was the DIRTY COMMY the whole time! You see, like everyone
in CHINA, I quickly realized the merits of COMMUNISM and shed all traces of
my CAPITALIST past! Then, using my superior DEBATE ABILITIES, I convinced the
rest of the CDA to join me. If it hadn\'t been for you MEDDLING DEBATER(S), I would
have succeeded in my goal of TAKING OVER THE WORLD! But wait... There might be one
last hope. If I can convince you to join me--and embrace the COMMY CAUSE--we might,
together, have enough debate power to destroy CAPITALISM once and for all! That\'s
it! RESOLVED: You are going to help me take over the world! I have three major
CONTENTIONS!',
'What. What? You mean... You\'re right! There IS no society on the PLANET ideal enough
for COMMUNISM to be successful! I never thought about it like that... I guess... I guess...
I guess I\'ll just have to settle for CAPITALISM. Thank you, young stranger, for saving
me from my own destruction... I owe you. The world owes you. AMERICA owes you! And for
that reason, Mr. PI:NAME:<NAME>END_PIudge, I urge you to negate the aforementioned resolution. Good job KID,
you won.',
'And that is why, Mr. Speaker, you MUST affirm the resolution! Take that you CAPITALIST
PIG! Now, join me, and together we will take over the world!',
[])
)
# Closing screen for winning, show Evan back to good side
# start the game
game.start()
|
[
{
"context": "critic = require '../'\n\n###\ncritic.create \"affleck\", (err, gen) ->\n return console.log err if err?\n",
"end": 50,
"score": 0.504750669002533,
"start": 48,
"tag": "NAME",
"value": "ck"
},
{
"context": "mments.length} loaded\"\n console.log gen.respond \"ben affle... | examples/test.coffee | wearefractal/critic | 1 | critic = require '../'
###
critic.create "affleck", (err, gen) ->
return console.log err if err?
console.log "#{gen.comments.length} loaded"
console.log gen.respond "ben affleck"
###
critic.create "walking dead", (err, gen) ->
return console.log err if err?
console.log "#{gen.comments.length} loaded"
console.log gen.respond "finale" | 192903 | critic = require '../'
###
critic.create "affle<NAME>", (err, gen) ->
return console.log err if err?
console.log "#{gen.comments.length} loaded"
console.log gen.respond "<NAME>"
###
critic.create "walking dead", (err, gen) ->
return console.log err if err?
console.log "#{gen.comments.length} loaded"
console.log gen.respond "finale" | true | critic = require '../'
###
critic.create "afflePI:NAME:<NAME>END_PI", (err, gen) ->
return console.log err if err?
console.log "#{gen.comments.length} loaded"
console.log gen.respond "PI:NAME:<NAME>END_PI"
###
critic.create "walking dead", (err, gen) ->
return console.log err if err?
console.log "#{gen.comments.length} loaded"
console.log gen.respond "finale" |
[
{
"context": "'Car 6']\n [current.lat+.002, current.lng-.01, 'Perry Donham']\n ]\n carLocation = new (google.maps.LatLng)(ca",
"end": 2987,
"score": 0.9997996091842651,
"start": 2975,
"tag": "NAME",
"value": "Perry Donham"
}
] | app/assets/javascripts/map.coffee | RyanTKing/CarePax | 0 | window.initMap = ->
mapStyle = new (google.maps.StyledMapType)([
{
'featureType': 'administrative'
'elementType': 'labels.text.fill'
'stylers': [ { 'color': '#444444' } ]
}
{
'featureType': 'landscape'
'elementType': 'all'
'stylers': [ { 'color': '#f2f2f2' } ]
}
{
'featureType': 'poi'
'elementType': 'all'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'road'
'elementType': 'all'
'stylers': [
{ 'saturation': -100 }
{ 'lightness': 45 }
]
}
{
'featureType': 'road.highway'
'elementType': 'all'
'stylers': [ { 'visibility': 'simplified' } ]
}
{
'featureType': 'road.arterial'
'elementType': 'labels.icon'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'transit'
'elementType': 'all'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'water'
'elementType': 'all'
'stylers': [
{ 'color': '#3498DB' }
{ 'visibility': 'on' }
]
}
], name: 'Blue Water')
mapStyleId = 'blue_water'
map = new (google.maps.Map)(document.getElementById('map'),
center:
lat: 42.350
lng: -71.108
zoom: 16
disableDefaultUI: true
mapTypeControlOptions: mapTypeIds: [
google.maps.MapTypeId.ROADMAP
mapStyleId
])
map.mapTypes.set mapStyleId, mapStyle
map.setMapTypeId mapStyleId
blueDot = new google.maps.MarkerImage(
'http://plebeosaur.us/etc/map/bluedot_retina.png'
null,
null,
new google.maps.Point( 8, 8 )
new google.maps.Size( 17, 17 )
)
car = new google.maps.MarkerImage(
'http://cliparts.co/cliparts/6ip/o6X/6ipo6XBMT.png'
null,
null,
new google.maps.Point( 8, 8 )
new google.maps.Size( 30, 30 )
)
userMarker = new (google.maps.Marker)(
flat: true
icon: blueDot
optimized: false
visible: true
position:
lat: 42.350
lng: -71.108
map: map
title: 'Your location'
)
current =
lat: 42.350
lng: -71.108
if navigator.geolocation
navigator.geolocation.getCurrentPosition ((position) ->
current.lat = position.coords.latitude
current.lng = position.coords.longitude
pos =
lat: position.coords.latitude
lng: position.coords.longitude
map.setCenter pos
userMarker.setPosition(pos)
return
), ->
handleLocationError true
return
else
handleLocationError false
return
window.pickupMarker = new (google.maps.Marker)(
map: null
position: null
draggable: true
)
carMarkers = [
[current.lat+.015, current.lng+.001, 'Car 1']
[current.lat-.01, current.lng+.003, 'Car 2']
[current.lat-.005, current.lng-.003, 'Car 3']
[current.lat+.0005, current.lng+.005, 'Car 4']
[current.lat+.003, current.lng+.003, 'Car 6']
[current.lat+.002, current.lng-.01, 'Perry Donham']
]
carLocation = new (google.maps.LatLng)(carMarkers[5][0], carMarkers[5][1])
carMarker = new (google.maps.Marker)(
map: map
icon: car
visible: true
optimized: false
position: new (google.maps.LatLng)(carMarkers[5][0], carMarkers[5][1])
title: carMarkers[5][2]
)
i = 0
while i < 5
marker = new (google.maps.Marker)(
map: map
icon: car
visible: true
optimized: false
position: new (google.maps.LatLng)(carMarkers[i][0], carMarkers[5][1])
title: carMarkers[i][2]
)
i++
geocoder = new (google.maps.Geocoder)
map.addListener 'click', (e) ->
pickupMarker.setMap(map)
geocodeLatLng geocoder, map, e.latLng, pickupMarker
return
pickupMarker.addListener 'dragend', (e) ->
geocodeLatLng geocoder, map, e.latLng, pickupMarker
return
userMarker.addListener 'click', (e) ->
pickupMarker.setMap(map)
geocodeLatLng geocoder, map, e.latLng, pickupMarker
carMarker.addListener 'click', (e) ->
$('#order-form').show()
$('#order-form div.order-close a').click ->
$('#order-form').hide()
$('button.order').click ->
directionsService = new (google.maps.DirectionsService)
directionsDisplay = new (google.maps.DirectionsRenderer)(
preserveViewport: true
suppressMarkers: true
)
directionsDisplay.setMap(map);
polyline = new (google.maps.Polyline)(
path: []
strokeColor: '#3498DB'
strokeWeight: 3)
poly2 = new (google.maps.Polyline)(
path: []
strokeColor: '#3498DB'
strokeWeight: 3)
steps = []
request =
origin: carLocation
destination: pickupMarker.position
travelMode: google.maps.TravelMode.DRIVING
directionsService.route request, (response, status) ->
if status == google.maps.DirectionsStatus.OK
directionsDisplay.setDirections(response);
pathCoords = response.routes[0].overview_path
route = new (google.maps.Polyline)(
path: []
geodesic: true
strokeColor: '#FF0000'
strokeOpacity: 0
strokeWeight: 2
editable: false
map: map)
i = 0
while i < pathCoords.length
setTimeout ((coords) ->
route.getPath().push coords
carMarker.setPosition coords
return
), 2000 * i, pathCoords[i]
i++
return
return
input = document.getElementById('pac-input')
searchBox = new (google.maps.places.SearchBox)(input)
map.controls[google.maps.ControlPosition.TOP_CENTER].push input
map.addListener 'bounds_changed', ->
searchBox.setBounds map.getBounds()
return
searchBox.addListener 'places_changed', ->
places = searchBox.getPlaces()
if places.length == 0
return
pickupLoc = places[0]
pickupMarker.setMap map
pickupMarker.setPosition pickupLoc.geometry.location
pickupMarker.setTitle pickupLoc.name
map.setCenter pickupLoc.geometry.location
return
handleLocationError = (browserHasGeolocation) ->
if browserHasGeolocation
console.log('Error: The Geolocation service failed.')
else
console.log('Error: Your browser doesn\'t support geolocation')
return
geocodeLatLng = (geocoder, map, latlng, marker) ->
geocoder.geocode { 'location': latlng }, (results, status) ->
if status == google.maps.GeocoderStatus.OK
if results[1]
marker.setPosition latlng
marker.setTitle results[1].formatted_address
else
window.alert 'No results found'
else
window.alert 'Geocoder failed due to: ' + status
return
return
| 70509 | window.initMap = ->
mapStyle = new (google.maps.StyledMapType)([
{
'featureType': 'administrative'
'elementType': 'labels.text.fill'
'stylers': [ { 'color': '#444444' } ]
}
{
'featureType': 'landscape'
'elementType': 'all'
'stylers': [ { 'color': '#f2f2f2' } ]
}
{
'featureType': 'poi'
'elementType': 'all'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'road'
'elementType': 'all'
'stylers': [
{ 'saturation': -100 }
{ 'lightness': 45 }
]
}
{
'featureType': 'road.highway'
'elementType': 'all'
'stylers': [ { 'visibility': 'simplified' } ]
}
{
'featureType': 'road.arterial'
'elementType': 'labels.icon'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'transit'
'elementType': 'all'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'water'
'elementType': 'all'
'stylers': [
{ 'color': '#3498DB' }
{ 'visibility': 'on' }
]
}
], name: 'Blue Water')
mapStyleId = 'blue_water'
map = new (google.maps.Map)(document.getElementById('map'),
center:
lat: 42.350
lng: -71.108
zoom: 16
disableDefaultUI: true
mapTypeControlOptions: mapTypeIds: [
google.maps.MapTypeId.ROADMAP
mapStyleId
])
map.mapTypes.set mapStyleId, mapStyle
map.setMapTypeId mapStyleId
blueDot = new google.maps.MarkerImage(
'http://plebeosaur.us/etc/map/bluedot_retina.png'
null,
null,
new google.maps.Point( 8, 8 )
new google.maps.Size( 17, 17 )
)
car = new google.maps.MarkerImage(
'http://cliparts.co/cliparts/6ip/o6X/6ipo6XBMT.png'
null,
null,
new google.maps.Point( 8, 8 )
new google.maps.Size( 30, 30 )
)
userMarker = new (google.maps.Marker)(
flat: true
icon: blueDot
optimized: false
visible: true
position:
lat: 42.350
lng: -71.108
map: map
title: 'Your location'
)
current =
lat: 42.350
lng: -71.108
if navigator.geolocation
navigator.geolocation.getCurrentPosition ((position) ->
current.lat = position.coords.latitude
current.lng = position.coords.longitude
pos =
lat: position.coords.latitude
lng: position.coords.longitude
map.setCenter pos
userMarker.setPosition(pos)
return
), ->
handleLocationError true
return
else
handleLocationError false
return
window.pickupMarker = new (google.maps.Marker)(
map: null
position: null
draggable: true
)
carMarkers = [
[current.lat+.015, current.lng+.001, 'Car 1']
[current.lat-.01, current.lng+.003, 'Car 2']
[current.lat-.005, current.lng-.003, 'Car 3']
[current.lat+.0005, current.lng+.005, 'Car 4']
[current.lat+.003, current.lng+.003, 'Car 6']
[current.lat+.002, current.lng-.01, '<NAME>']
]
carLocation = new (google.maps.LatLng)(carMarkers[5][0], carMarkers[5][1])
carMarker = new (google.maps.Marker)(
map: map
icon: car
visible: true
optimized: false
position: new (google.maps.LatLng)(carMarkers[5][0], carMarkers[5][1])
title: carMarkers[5][2]
)
i = 0
while i < 5
marker = new (google.maps.Marker)(
map: map
icon: car
visible: true
optimized: false
position: new (google.maps.LatLng)(carMarkers[i][0], carMarkers[5][1])
title: carMarkers[i][2]
)
i++
geocoder = new (google.maps.Geocoder)
map.addListener 'click', (e) ->
pickupMarker.setMap(map)
geocodeLatLng geocoder, map, e.latLng, pickupMarker
return
pickupMarker.addListener 'dragend', (e) ->
geocodeLatLng geocoder, map, e.latLng, pickupMarker
return
userMarker.addListener 'click', (e) ->
pickupMarker.setMap(map)
geocodeLatLng geocoder, map, e.latLng, pickupMarker
carMarker.addListener 'click', (e) ->
$('#order-form').show()
$('#order-form div.order-close a').click ->
$('#order-form').hide()
$('button.order').click ->
directionsService = new (google.maps.DirectionsService)
directionsDisplay = new (google.maps.DirectionsRenderer)(
preserveViewport: true
suppressMarkers: true
)
directionsDisplay.setMap(map);
polyline = new (google.maps.Polyline)(
path: []
strokeColor: '#3498DB'
strokeWeight: 3)
poly2 = new (google.maps.Polyline)(
path: []
strokeColor: '#3498DB'
strokeWeight: 3)
steps = []
request =
origin: carLocation
destination: pickupMarker.position
travelMode: google.maps.TravelMode.DRIVING
directionsService.route request, (response, status) ->
if status == google.maps.DirectionsStatus.OK
directionsDisplay.setDirections(response);
pathCoords = response.routes[0].overview_path
route = new (google.maps.Polyline)(
path: []
geodesic: true
strokeColor: '#FF0000'
strokeOpacity: 0
strokeWeight: 2
editable: false
map: map)
i = 0
while i < pathCoords.length
setTimeout ((coords) ->
route.getPath().push coords
carMarker.setPosition coords
return
), 2000 * i, pathCoords[i]
i++
return
return
input = document.getElementById('pac-input')
searchBox = new (google.maps.places.SearchBox)(input)
map.controls[google.maps.ControlPosition.TOP_CENTER].push input
map.addListener 'bounds_changed', ->
searchBox.setBounds map.getBounds()
return
searchBox.addListener 'places_changed', ->
places = searchBox.getPlaces()
if places.length == 0
return
pickupLoc = places[0]
pickupMarker.setMap map
pickupMarker.setPosition pickupLoc.geometry.location
pickupMarker.setTitle pickupLoc.name
map.setCenter pickupLoc.geometry.location
return
handleLocationError = (browserHasGeolocation) ->
if browserHasGeolocation
console.log('Error: The Geolocation service failed.')
else
console.log('Error: Your browser doesn\'t support geolocation')
return
geocodeLatLng = (geocoder, map, latlng, marker) ->
geocoder.geocode { 'location': latlng }, (results, status) ->
if status == google.maps.GeocoderStatus.OK
if results[1]
marker.setPosition latlng
marker.setTitle results[1].formatted_address
else
window.alert 'No results found'
else
window.alert 'Geocoder failed due to: ' + status
return
return
| true | window.initMap = ->
mapStyle = new (google.maps.StyledMapType)([
{
'featureType': 'administrative'
'elementType': 'labels.text.fill'
'stylers': [ { 'color': '#444444' } ]
}
{
'featureType': 'landscape'
'elementType': 'all'
'stylers': [ { 'color': '#f2f2f2' } ]
}
{
'featureType': 'poi'
'elementType': 'all'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'road'
'elementType': 'all'
'stylers': [
{ 'saturation': -100 }
{ 'lightness': 45 }
]
}
{
'featureType': 'road.highway'
'elementType': 'all'
'stylers': [ { 'visibility': 'simplified' } ]
}
{
'featureType': 'road.arterial'
'elementType': 'labels.icon'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'transit'
'elementType': 'all'
'stylers': [ { 'visibility': 'off' } ]
}
{
'featureType': 'water'
'elementType': 'all'
'stylers': [
{ 'color': '#3498DB' }
{ 'visibility': 'on' }
]
}
], name: 'Blue Water')
mapStyleId = 'blue_water'
map = new (google.maps.Map)(document.getElementById('map'),
center:
lat: 42.350
lng: -71.108
zoom: 16
disableDefaultUI: true
mapTypeControlOptions: mapTypeIds: [
google.maps.MapTypeId.ROADMAP
mapStyleId
])
map.mapTypes.set mapStyleId, mapStyle
map.setMapTypeId mapStyleId
blueDot = new google.maps.MarkerImage(
'http://plebeosaur.us/etc/map/bluedot_retina.png'
null,
null,
new google.maps.Point( 8, 8 )
new google.maps.Size( 17, 17 )
)
car = new google.maps.MarkerImage(
'http://cliparts.co/cliparts/6ip/o6X/6ipo6XBMT.png'
null,
null,
new google.maps.Point( 8, 8 )
new google.maps.Size( 30, 30 )
)
userMarker = new (google.maps.Marker)(
flat: true
icon: blueDot
optimized: false
visible: true
position:
lat: 42.350
lng: -71.108
map: map
title: 'Your location'
)
current =
lat: 42.350
lng: -71.108
if navigator.geolocation
navigator.geolocation.getCurrentPosition ((position) ->
current.lat = position.coords.latitude
current.lng = position.coords.longitude
pos =
lat: position.coords.latitude
lng: position.coords.longitude
map.setCenter pos
userMarker.setPosition(pos)
return
), ->
handleLocationError true
return
else
handleLocationError false
return
window.pickupMarker = new (google.maps.Marker)(
map: null
position: null
draggable: true
)
carMarkers = [
[current.lat+.015, current.lng+.001, 'Car 1']
[current.lat-.01, current.lng+.003, 'Car 2']
[current.lat-.005, current.lng-.003, 'Car 3']
[current.lat+.0005, current.lng+.005, 'Car 4']
[current.lat+.003, current.lng+.003, 'Car 6']
[current.lat+.002, current.lng-.01, 'PI:NAME:<NAME>END_PI']
]
carLocation = new (google.maps.LatLng)(carMarkers[5][0], carMarkers[5][1])
carMarker = new (google.maps.Marker)(
map: map
icon: car
visible: true
optimized: false
position: new (google.maps.LatLng)(carMarkers[5][0], carMarkers[5][1])
title: carMarkers[5][2]
)
i = 0
while i < 5
marker = new (google.maps.Marker)(
map: map
icon: car
visible: true
optimized: false
position: new (google.maps.LatLng)(carMarkers[i][0], carMarkers[5][1])
title: carMarkers[i][2]
)
i++
geocoder = new (google.maps.Geocoder)
map.addListener 'click', (e) ->
pickupMarker.setMap(map)
geocodeLatLng geocoder, map, e.latLng, pickupMarker
return
pickupMarker.addListener 'dragend', (e) ->
geocodeLatLng geocoder, map, e.latLng, pickupMarker
return
userMarker.addListener 'click', (e) ->
pickupMarker.setMap(map)
geocodeLatLng geocoder, map, e.latLng, pickupMarker
carMarker.addListener 'click', (e) ->
$('#order-form').show()
$('#order-form div.order-close a').click ->
$('#order-form').hide()
$('button.order').click ->
directionsService = new (google.maps.DirectionsService)
directionsDisplay = new (google.maps.DirectionsRenderer)(
preserveViewport: true
suppressMarkers: true
)
directionsDisplay.setMap(map);
polyline = new (google.maps.Polyline)(
path: []
strokeColor: '#3498DB'
strokeWeight: 3)
poly2 = new (google.maps.Polyline)(
path: []
strokeColor: '#3498DB'
strokeWeight: 3)
steps = []
request =
origin: carLocation
destination: pickupMarker.position
travelMode: google.maps.TravelMode.DRIVING
directionsService.route request, (response, status) ->
if status == google.maps.DirectionsStatus.OK
directionsDisplay.setDirections(response);
pathCoords = response.routes[0].overview_path
route = new (google.maps.Polyline)(
path: []
geodesic: true
strokeColor: '#FF0000'
strokeOpacity: 0
strokeWeight: 2
editable: false
map: map)
i = 0
while i < pathCoords.length
setTimeout ((coords) ->
route.getPath().push coords
carMarker.setPosition coords
return
), 2000 * i, pathCoords[i]
i++
return
return
input = document.getElementById('pac-input')
searchBox = new (google.maps.places.SearchBox)(input)
map.controls[google.maps.ControlPosition.TOP_CENTER].push input
map.addListener 'bounds_changed', ->
searchBox.setBounds map.getBounds()
return
searchBox.addListener 'places_changed', ->
places = searchBox.getPlaces()
if places.length == 0
return
pickupLoc = places[0]
pickupMarker.setMap map
pickupMarker.setPosition pickupLoc.geometry.location
pickupMarker.setTitle pickupLoc.name
map.setCenter pickupLoc.geometry.location
return
handleLocationError = (browserHasGeolocation) ->
if browserHasGeolocation
console.log('Error: The Geolocation service failed.')
else
console.log('Error: Your browser doesn\'t support geolocation')
return
geocodeLatLng = (geocoder, map, latlng, marker) ->
geocoder.geocode { 'location': latlng }, (results, status) ->
if status == google.maps.GeocoderStatus.OK
if results[1]
marker.setPosition latlng
marker.setTitle results[1].formatted_address
else
window.alert 'No results found'
else
window.alert 'Geocoder failed due to: ' + status
return
return
|
[
{
"context": "', 'link')\n selected: new Batman.Object(name: 'crono')\n helpers.render '<select data-bind=\"selected.n",
"end": 4897,
"score": 0.9374864101409912,
"start": 4892,
"tag": "NAME",
"value": "crono"
},
{
"context": " ->\n context = new Batman.Object\n something: 'c... | tests/batman/view/simple_rendering_test.coffee | nickjs/batman | 1 | helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper'
QUnit.module 'Batman.View simple rendering'
hte = (actual, expected) ->
equal actual.innerHTML.toLowerCase().replace(/\n|\r/g, ""),
expected.toLowerCase().replace(/\n|\r/g, "")
test 'it should render simple nodes', ->
hte helpers.render("<div></div>", false), "<div></div>"
test 'it should render many parent nodes', ->
hte helpers.render("<div></div><p></p>", false), "<div></div><p></p>"
asyncTest 'it should allow the inner value to be bound', 1, ->
helpers.render '<div data-bind="foo"></div>',
foo: 'bar'
, (node) =>
equals node.html(), "bar"
QUnit.start()
asyncTest 'it should bind undefined values as empty strings', 1, ->
helpers.render '<div data-bind="foo"></div>',
foo: undefined
, (node) =>
equals node.html(), ""
QUnit.start()
asyncTest 'it should ignore empty bindings', 1, ->
helpers.render '<div data-bind=""></div>', Batman(), (node) =>
equals node.html(), ""
QUnit.start()
asyncTest 'it should allow a class to be bound', 6, ->
source = '<div data-addclass-one="foo" data-removeclass-two="bar" class="zero"></div>'
helpers.render source,
foo: true
bar: true
, (node) ->
ok node.hasClass('zero')
ok node.hasClass('one')
ok !node.hasClass('two')
helpers.render source,
foo: false
bar: false
, (node) ->
ok node.hasClass('zero')
ok !node.hasClass('one')
ok node.hasClass('two')
QUnit.start()
asyncTest 'it should allow visibility to be bound on block elements', 2, ->
testDiv = $('<div/>')
testDiv.appendTo($('body'))
blockDefaultDisplay = testDiv.css('display')
testDiv.remove()
source = '<div data-showif="foo"></div>'
helpers.render source,
foo: true
, (node) ->
# Must put the node in the DOM for the style to be calculated properly.
helpers.withNodeInDom node, ->
equal node.css('display'), blockDefaultDisplay
helpers.render source,
foo: false
, (node) ->
helpers.withNodeInDom node, ->
equal node.css('display'), 'none'
QUnit.start()
asyncTest 'it should allow visibility to be bound on inline elements', 2, ->
testSpan = $('<span/>')
testSpan.appendTo($('body'))
inlineDefaultDisplay = testSpan.css('display')
testSpan.remove()
source = '<span data-showif="foo"></span>'
helpers.render source,
foo: true
, (node) ->
# Must put the node in the DOM for the style to be calculated properly.
helpers.withNodeInDom node, ->
equal node.css('display'), inlineDefaultDisplay
helpers.render source,
foo: false
, (node) ->
helpers.withNodeInDom node, ->
equal node.css('display'), 'none'
QUnit.start()
asyncTest 'it should allow arbitrary attributes to be bound', 2, ->
source = '<div data-bind-foo="one" data-bind-bar="two" foo="before"></div>'
helpers.render source,
one: "baz"
two: "qux"
, (node) ->
equal $(node[0]).attr('foo'), "baz"
equal $(node[0]).attr('bar'), "qux"
QUnit.start()
asyncTest 'it should allow multiple class names to be bound and updated', ->
source = '<div data-bind-class="classes"></div>'
context = new Batman.Object classes: 'foo bar'
helpers.render source, context, (node) ->
equal node[0].className, 'foo bar'
context.set 'classes', 'bar baz'
delay =>
equal node[0].className, 'bar baz'
asyncTest 'it should allow input values to be bound', 1, ->
helpers.render '<input data-bind="one" type="text" />',
one: "qux"
, (node) ->
equal $(node[0]).val(), 'qux'
QUnit.start()
asyncTest 'it should bind the input value and update the input when it changes', 2, ->
context = new Batman.Object
one: "qux"
helpers.render '<input data-bind="one" type="text" />', context, (node) ->
equal $(node[0]).val(), 'qux'
context.set('one', "bar")
delay =>
equal $(node[0]).val(), 'bar'
asyncTest 'it should bind the input value of checkboxes and update the value when the object changes', 2, ->
context = new Batman.Object
one: true
helpers.render '<input type="checkbox" data-bind="one" />', context, (node) ->
equal node[0].checked, true
context.set('one', false)
delay =>
equal node[0].checked, false
asyncTest 'it should bind the input value of checkboxes and update the object when the value changes', 1, ->
context = new Batman.Object
one: true
helpers.render '<input type="checkbox" data-bind="one" />', context, (node) ->
node[0].checked = false
helpers.triggerChange(node[0])
delay =>
equal context.get('one'), false
asyncTest 'it should bind the value of a select box and update when the value changes', 2, ->
context = new Batman.Object
heros: new Batman.Set('mario', 'crono', 'link')
selected: new Batman.Object(name: 'crono')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equals node[0].value, 'crono'
context.set 'selected.name', 'link'
delay =>
equal node[0].value, 'link'
asyncTest 'it binds the options of a select box and updates when the select\'s value changes', ->
context = new Batman.Object
something: 'crono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select data-bind="something"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equal node[0].value, 'crono'
equal context.get('crono.selected'), true
equal context.get('mario.selected'), false
node[0].value = 'mario'
helpers.triggerChange node[0]
delay =>
equal context.get('mario.selected'), true
equal context.get('crono.selected'), false
asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', ->
context = new Batman.Object
heros: new Batman.Set('mario', 'crono', 'link', 'kirby')
selected: new Batman.Object(name: ['crono', 'link'])
helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
selections = (c.selected for c in node[0].children)
deepEqual selections, [no, yes, yes, no]
context.set 'selected.name', ['mario', 'kirby']
delay =>
selections = (c.selected for c in node[0].children)
deepEqual selections, [yes, no, no, yes]
asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', ->
context = new Batman.Object
selected: 'crono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select multiple="multiple" data-bind="selected"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equal node[0].value, 'crono', 'node value is crono'
equal context.get('selected'), 'crono', 'selected is crono'
equal context.get('crono.selected'), true, 'crono is selected'
equal context.get('mario.selected'), false, 'mario is not selected'
context.set 'mario.selected', true
delay =>
equal context.get('mario.selected'), true, 'mario is selected'
equal context.get('crono.selected'), true, 'crono is still selected'
deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding'
for opt in node[0].children
ok opt.selected, "#{opt.value} option is selected"
asyncTest 'it should bind the input value and update the object when it changes', 1, ->
context = new Batman.Object
one: "qux"
helpers.render '<input data-bind="one" type="text" />', context, (node) ->
$(node[0]).val('bar')
# Use DOM level 2 event dispatch, $().trigger doesn't seem to work
helpers.triggerChange(node[0])
delay =>
equal context.get('one'), 'bar'
asyncTest 'it should bind the value of textareas', 2, ->
context = new Batman.Object
one: "qux"
helpers.render '<textarea data-bind="one"></textarea>', context, (node) ->
equal node.val(), 'qux'
context.set('one', "bar")
delay =>
equal node.val(), 'bar'
asyncTest 'it should bind the value of textareas and inputs simulatenously', ->
context = new Batman.Object
one: "qux"
helpers.render '<textarea data-bind="one"></textarea><input data-bind="one" type="text"/>', context, (node) ->
f = (v) =>
equal $(node[0]).val(), v
equal $(node[1]).val(), v
f('qux')
$(node[1]).val('bar')
helpers.triggerChange(node[1])
delay =>
f('bar')
$(node[0]).val('baz')
helpers.triggerChange(node[0])
delay =>
f('baz')
$(node[1]).val('foo')
helpers.triggerChange(node[1])
delay =>
f('foo')
asyncTest 'it should allow events to be bound and execute them in the context as specified on a multi key keypath', 1, ->
context = Batman
foo: Batman
bar: Batman
doSomething: spy = createSpy()
source = '<button data-event-click="foo.bar.doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
equal spy.lastCallContext, context.get('foo.bar')
asyncTest 'it should allow events to be bound and execute them in the context as specified on terminal keypath', 1, ->
context = Batman
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
equal spy.lastCallContext, context
asyncTest 'it should allow click events to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow double click events to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<button data-event-doubleclick="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerDoubleClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow event handlers to update', 2, ->
context = Batman
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
context.set('doSomething', newSpy = createSpy())
helpers.triggerClick(node[0])
delay ->
ok newSpy.called
asyncTest 'it should allow change events on checkboxes to be bound', 1, ->
context = new Batman.Object
one: true
doSomething: createSpy()
helpers.render '<input type="checkbox" data-bind="one" data-event-change="doSomething"/>', context, (node) ->
node[0].checked = false
helpers.triggerChange(node[0])
delay =>
ok context.doSomething.called
asyncTest 'it should allow submit events on inputs to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<form><input data-event-submit="doSomething" /></form>'
helpers.render source, context, (node) ->
helpers.triggerKey(node[0].childNodes[0], 13)
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0].childNodes[0]
asyncTest 'it should allow form submit events to be bound', 1, ->
context =
doSomething: spy = createSpy()
source = '<form data-event-submit="doSomething"><input type="submit" id="submit" /></form>'
helpers.render source, context, (node) ->
helpers.triggerSubmit(node[0])
delay =>
ok spy.called
asyncTest 'allows data-event-click attributes to reference native model properties directly', ->
spy = createSpy()
class Foo extends Batman.Model
handleClick: spy
source = '<button data-event-click="foo.handleClick"></button>'
helpers.render source, {foo: new Foo()}, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow mixins to be applied', 1, ->
Batman.mixins.set 'test',
foo: 'bar'
source = '<div data-mixin="test"></div>'
helpers.render source, false, (node) ->
delay ->
equals Batman.data(node.firstChild, 'foo'), 'bar'
delete Batman.mixins.test
asyncTest 'it should allow contexts to be entered', 2, ->
context = Batman
namespace: Batman
foo: 'bar'
source = '<div data-context="namespace"><span id="test" data-bind="foo"></span></div>'
helpers.render source, context, (node) ->
equal $('#test', node).html(), 'bar'
context.set('namespace', Batman(foo: 'baz'))
delay ->
equal $("#test", node).html(), 'baz', 'if the context changes the bindings should update'
asyncTest 'it should allow contexts to be specified using filters', 2, ->
context = Batman
namespace: Batman
foo: Batman
bar: 'baz'
keyName: 'foo'
source = '<div data-context="namespace | get keyName"><span id="test" data-bind="bar"></span></div>'
helpers.render source, context, (node) ->
equal $('#test', node).html(), 'baz'
context.set('namespace', Batman(foo: Batman(bar: 'qux')))
delay ->
equal $("#test", node).html(), 'qux', 'if the context changes the bindings should update'
asyncTest 'should bind radio buttons to a value', ->
source = '<input id="fixed" type="radio" data-bind="ad.sale_type" name="sale_type" value="fixed"/>
<input id="free" type="radio" data-bind="ad.sale_type" name="sale_type" value="free"/>
<input id="trade" type="radio" data-bind="ad.sale_type" name="sale_type" value="trade"/>'
context = Batman
ad: Batman
sale_type: 'free'
helpers.render source, context, (node) ->
fixed = node[0]
free = node[1]
trade = node[2]
ok (!fixed.checked and free.checked and !trade.checked)
context.set 'ad.sale_type', 'trade'
delay =>
ok (!fixed.checked and !free.checked and trade.checked)
asyncTest 'should bind to the value of radio buttons', ->
source = '<input id="fixed" type="radio" data-bind="ad.sale_type" name="sale_type" value="fixed"/>
<input id="free" type="radio" data-bind="ad.sale_type" name="sale_type" value="free"/>
<input id="trade" type="radio" data-bind="ad.sale_type" name="sale_type" value="trade" checked/>'
context = Batman
ad: Batman
helpers.render source, context, (node) ->
fixed = node[0]
free = node[1]
trade = node[2]
ok (!fixed.checked and !free.checked and trade.checked)
equal context.get('ad.sale_type'), 'trade', 'checked attribute binds'
helpers.triggerChange(fixed)
delay =>
equal context.get('ad.sale_type'), 'fixed'
| 129760 | helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper'
QUnit.module 'Batman.View simple rendering'
hte = (actual, expected) ->
equal actual.innerHTML.toLowerCase().replace(/\n|\r/g, ""),
expected.toLowerCase().replace(/\n|\r/g, "")
test 'it should render simple nodes', ->
hte helpers.render("<div></div>", false), "<div></div>"
test 'it should render many parent nodes', ->
hte helpers.render("<div></div><p></p>", false), "<div></div><p></p>"
asyncTest 'it should allow the inner value to be bound', 1, ->
helpers.render '<div data-bind="foo"></div>',
foo: 'bar'
, (node) =>
equals node.html(), "bar"
QUnit.start()
asyncTest 'it should bind undefined values as empty strings', 1, ->
helpers.render '<div data-bind="foo"></div>',
foo: undefined
, (node) =>
equals node.html(), ""
QUnit.start()
asyncTest 'it should ignore empty bindings', 1, ->
helpers.render '<div data-bind=""></div>', Batman(), (node) =>
equals node.html(), ""
QUnit.start()
asyncTest 'it should allow a class to be bound', 6, ->
source = '<div data-addclass-one="foo" data-removeclass-two="bar" class="zero"></div>'
helpers.render source,
foo: true
bar: true
, (node) ->
ok node.hasClass('zero')
ok node.hasClass('one')
ok !node.hasClass('two')
helpers.render source,
foo: false
bar: false
, (node) ->
ok node.hasClass('zero')
ok !node.hasClass('one')
ok node.hasClass('two')
QUnit.start()
asyncTest 'it should allow visibility to be bound on block elements', 2, ->
testDiv = $('<div/>')
testDiv.appendTo($('body'))
blockDefaultDisplay = testDiv.css('display')
testDiv.remove()
source = '<div data-showif="foo"></div>'
helpers.render source,
foo: true
, (node) ->
# Must put the node in the DOM for the style to be calculated properly.
helpers.withNodeInDom node, ->
equal node.css('display'), blockDefaultDisplay
helpers.render source,
foo: false
, (node) ->
helpers.withNodeInDom node, ->
equal node.css('display'), 'none'
QUnit.start()
asyncTest 'it should allow visibility to be bound on inline elements', 2, ->
testSpan = $('<span/>')
testSpan.appendTo($('body'))
inlineDefaultDisplay = testSpan.css('display')
testSpan.remove()
source = '<span data-showif="foo"></span>'
helpers.render source,
foo: true
, (node) ->
# Must put the node in the DOM for the style to be calculated properly.
helpers.withNodeInDom node, ->
equal node.css('display'), inlineDefaultDisplay
helpers.render source,
foo: false
, (node) ->
helpers.withNodeInDom node, ->
equal node.css('display'), 'none'
QUnit.start()
asyncTest 'it should allow arbitrary attributes to be bound', 2, ->
source = '<div data-bind-foo="one" data-bind-bar="two" foo="before"></div>'
helpers.render source,
one: "baz"
two: "qux"
, (node) ->
equal $(node[0]).attr('foo'), "baz"
equal $(node[0]).attr('bar'), "qux"
QUnit.start()
asyncTest 'it should allow multiple class names to be bound and updated', ->
source = '<div data-bind-class="classes"></div>'
context = new Batman.Object classes: 'foo bar'
helpers.render source, context, (node) ->
equal node[0].className, 'foo bar'
context.set 'classes', 'bar baz'
delay =>
equal node[0].className, 'bar baz'
asyncTest 'it should allow input values to be bound', 1, ->
helpers.render '<input data-bind="one" type="text" />',
one: "qux"
, (node) ->
equal $(node[0]).val(), 'qux'
QUnit.start()
asyncTest 'it should bind the input value and update the input when it changes', 2, ->
context = new Batman.Object
one: "qux"
helpers.render '<input data-bind="one" type="text" />', context, (node) ->
equal $(node[0]).val(), 'qux'
context.set('one', "bar")
delay =>
equal $(node[0]).val(), 'bar'
asyncTest 'it should bind the input value of checkboxes and update the value when the object changes', 2, ->
context = new Batman.Object
one: true
helpers.render '<input type="checkbox" data-bind="one" />', context, (node) ->
equal node[0].checked, true
context.set('one', false)
delay =>
equal node[0].checked, false
asyncTest 'it should bind the input value of checkboxes and update the object when the value changes', 1, ->
context = new Batman.Object
one: true
helpers.render '<input type="checkbox" data-bind="one" />', context, (node) ->
node[0].checked = false
helpers.triggerChange(node[0])
delay =>
equal context.get('one'), false
asyncTest 'it should bind the value of a select box and update when the value changes', 2, ->
context = new Batman.Object
heros: new Batman.Set('mario', 'crono', 'link')
selected: new Batman.Object(name: '<NAME>')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equals node[0].value, 'crono'
context.set 'selected.name', 'link'
delay =>
equal node[0].value, 'link'
asyncTest 'it binds the options of a select box and updates when the select\'s value changes', ->
context = new Batman.Object
something: '<NAME>'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select data-bind="something"><option value="<NAME>" data-bind-selected="mario.selected"></option><option value="<NAME>" data-bind-selected="crono.selected"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equal node[0].value, '<NAME>'
equal context.get('crono.selected'), true
equal context.get('mario.selected'), false
node[0].value = '<NAME>'
helpers.triggerChange node[0]
delay =>
equal context.get('mario.selected'), true
equal context.get('crono.selected'), false
asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', ->
context = new Batman.Object
heros: new Batman.Set('<NAME>', '<NAME>', 'link', '<NAME>')
selected: new Batman.Object(name: ['<NAME>', '<NAME>'])
helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
selections = (c.selected for c in node[0].children)
deepEqual selections, [no, yes, yes, no]
context.set 'selected.name', ['<NAME>', '<NAME>']
delay =>
selections = (c.selected for c in node[0].children)
deepEqual selections, [yes, no, no, yes]
asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', ->
context = new Batman.Object
selected: '<NAME>ono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select multiple="multiple" data-bind="selected"><option value="mario" data-bind-selected="mario.selected"></option><option value="<NAME>ono" data-bind-selected="crono.selected"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equal node[0].value, 'crono', 'node value is crono'
equal context.get('selected'), 'crono', 'selected is crono'
equal context.get('crono.selected'), true, 'crono is selected'
equal context.get('mario.selected'), false, 'mario is not selected'
context.set 'mario.selected', true
delay =>
equal context.get('mario.selected'), true, 'mario is selected'
equal context.get('crono.selected'), true, 'crono is still selected'
deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding'
for opt in node[0].children
ok opt.selected, "#{opt.value} option is selected"
asyncTest 'it should bind the input value and update the object when it changes', 1, ->
context = new Batman.Object
one: "qux"
helpers.render '<input data-bind="one" type="text" />', context, (node) ->
$(node[0]).val('bar')
# Use DOM level 2 event dispatch, $().trigger doesn't seem to work
helpers.triggerChange(node[0])
delay =>
equal context.get('one'), 'bar'
asyncTest 'it should bind the value of textareas', 2, ->
context = new Batman.Object
one: "qux"
helpers.render '<textarea data-bind="one"></textarea>', context, (node) ->
equal node.val(), 'qux'
context.set('one', "bar")
delay =>
equal node.val(), 'bar'
asyncTest 'it should bind the value of textareas and inputs simulatenously', ->
context = new Batman.Object
one: "qux"
helpers.render '<textarea data-bind="one"></textarea><input data-bind="one" type="text"/>', context, (node) ->
f = (v) =>
equal $(node[0]).val(), v
equal $(node[1]).val(), v
f('qux')
$(node[1]).val('bar')
helpers.triggerChange(node[1])
delay =>
f('bar')
$(node[0]).val('baz')
helpers.triggerChange(node[0])
delay =>
f('baz')
$(node[1]).val('foo')
helpers.triggerChange(node[1])
delay =>
f('foo')
asyncTest 'it should allow events to be bound and execute them in the context as specified on a multi key keypath', 1, ->
context = Batman
foo: Batman
bar: Batman
doSomething: spy = createSpy()
source = '<button data-event-click="foo.bar.doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
equal spy.lastCallContext, context.get('foo.bar')
asyncTest 'it should allow events to be bound and execute them in the context as specified on terminal keypath', 1, ->
context = Batman
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
equal spy.lastCallContext, context
asyncTest 'it should allow click events to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow double click events to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<button data-event-doubleclick="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerDoubleClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow event handlers to update', 2, ->
context = Batman
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
context.set('doSomething', newSpy = createSpy())
helpers.triggerClick(node[0])
delay ->
ok newSpy.called
asyncTest 'it should allow change events on checkboxes to be bound', 1, ->
context = new Batman.Object
one: true
doSomething: createSpy()
helpers.render '<input type="checkbox" data-bind="one" data-event-change="doSomething"/>', context, (node) ->
node[0].checked = false
helpers.triggerChange(node[0])
delay =>
ok context.doSomething.called
asyncTest 'it should allow submit events on inputs to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<form><input data-event-submit="doSomething" /></form>'
helpers.render source, context, (node) ->
helpers.triggerKey(node[0].childNodes[0], 13)
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0].childNodes[0]
asyncTest 'it should allow form submit events to be bound', 1, ->
context =
doSomething: spy = createSpy()
source = '<form data-event-submit="doSomething"><input type="submit" id="submit" /></form>'
helpers.render source, context, (node) ->
helpers.triggerSubmit(node[0])
delay =>
ok spy.called
asyncTest 'allows data-event-click attributes to reference native model properties directly', ->
spy = createSpy()
class Foo extends Batman.Model
handleClick: spy
source = '<button data-event-click="foo.handleClick"></button>'
helpers.render source, {foo: new Foo()}, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow mixins to be applied', 1, ->
Batman.mixins.set 'test',
foo: 'bar'
source = '<div data-mixin="test"></div>'
helpers.render source, false, (node) ->
delay ->
equals Batman.data(node.firstChild, 'foo'), 'bar'
delete Batman.mixins.test
asyncTest 'it should allow contexts to be entered', 2, ->
context = Batman
namespace: Batman
foo: 'bar'
source = '<div data-context="namespace"><span id="test" data-bind="foo"></span></div>'
helpers.render source, context, (node) ->
equal $('#test', node).html(), 'bar'
context.set('namespace', Batman(foo: 'baz'))
delay ->
equal $("#test", node).html(), 'baz', 'if the context changes the bindings should update'
asyncTest 'it should allow contexts to be specified using filters', 2, ->
context = Batman
namespace: Batman
foo: Batman
bar: 'baz'
keyName: 'foo'
source = '<div data-context="namespace | get keyName"><span id="test" data-bind="bar"></span></div>'
helpers.render source, context, (node) ->
equal $('#test', node).html(), 'baz'
context.set('namespace', Batman(foo: Batman(bar: 'qux')))
delay ->
equal $("#test", node).html(), 'qux', 'if the context changes the bindings should update'
asyncTest 'should bind radio buttons to a value', ->
source = '<input id="fixed" type="radio" data-bind="ad.sale_type" name="sale_type" value="fixed"/>
<input id="free" type="radio" data-bind="ad.sale_type" name="sale_type" value="free"/>
<input id="trade" type="radio" data-bind="ad.sale_type" name="sale_type" value="trade"/>'
context = Batman
ad: Batman
sale_type: 'free'
helpers.render source, context, (node) ->
fixed = node[0]
free = node[1]
trade = node[2]
ok (!fixed.checked and free.checked and !trade.checked)
context.set 'ad.sale_type', 'trade'
delay =>
ok (!fixed.checked and !free.checked and trade.checked)
asyncTest 'should bind to the value of radio buttons', ->
source = '<input id="fixed" type="radio" data-bind="ad.sale_type" name="sale_type" value="fixed"/>
<input id="free" type="radio" data-bind="ad.sale_type" name="sale_type" value="free"/>
<input id="trade" type="radio" data-bind="ad.sale_type" name="sale_type" value="trade" checked/>'
context = Batman
ad: Batman
helpers.render source, context, (node) ->
fixed = node[0]
free = node[1]
trade = node[2]
ok (!fixed.checked and !free.checked and trade.checked)
equal context.get('ad.sale_type'), 'trade', 'checked attribute binds'
helpers.triggerChange(fixed)
delay =>
equal context.get('ad.sale_type'), 'fixed'
| true | helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper'
QUnit.module 'Batman.View simple rendering'
hte = (actual, expected) ->
equal actual.innerHTML.toLowerCase().replace(/\n|\r/g, ""),
expected.toLowerCase().replace(/\n|\r/g, "")
test 'it should render simple nodes', ->
hte helpers.render("<div></div>", false), "<div></div>"
test 'it should render many parent nodes', ->
hte helpers.render("<div></div><p></p>", false), "<div></div><p></p>"
asyncTest 'it should allow the inner value to be bound', 1, ->
helpers.render '<div data-bind="foo"></div>',
foo: 'bar'
, (node) =>
equals node.html(), "bar"
QUnit.start()
asyncTest 'it should bind undefined values as empty strings', 1, ->
helpers.render '<div data-bind="foo"></div>',
foo: undefined
, (node) =>
equals node.html(), ""
QUnit.start()
asyncTest 'it should ignore empty bindings', 1, ->
helpers.render '<div data-bind=""></div>', Batman(), (node) =>
equals node.html(), ""
QUnit.start()
asyncTest 'it should allow a class to be bound', 6, ->
source = '<div data-addclass-one="foo" data-removeclass-two="bar" class="zero"></div>'
helpers.render source,
foo: true
bar: true
, (node) ->
ok node.hasClass('zero')
ok node.hasClass('one')
ok !node.hasClass('two')
helpers.render source,
foo: false
bar: false
, (node) ->
ok node.hasClass('zero')
ok !node.hasClass('one')
ok node.hasClass('two')
QUnit.start()
asyncTest 'it should allow visibility to be bound on block elements', 2, ->
testDiv = $('<div/>')
testDiv.appendTo($('body'))
blockDefaultDisplay = testDiv.css('display')
testDiv.remove()
source = '<div data-showif="foo"></div>'
helpers.render source,
foo: true
, (node) ->
# Must put the node in the DOM for the style to be calculated properly.
helpers.withNodeInDom node, ->
equal node.css('display'), blockDefaultDisplay
helpers.render source,
foo: false
, (node) ->
helpers.withNodeInDom node, ->
equal node.css('display'), 'none'
QUnit.start()
asyncTest 'it should allow visibility to be bound on inline elements', 2, ->
testSpan = $('<span/>')
testSpan.appendTo($('body'))
inlineDefaultDisplay = testSpan.css('display')
testSpan.remove()
source = '<span data-showif="foo"></span>'
helpers.render source,
foo: true
, (node) ->
# Must put the node in the DOM for the style to be calculated properly.
helpers.withNodeInDom node, ->
equal node.css('display'), inlineDefaultDisplay
helpers.render source,
foo: false
, (node) ->
helpers.withNodeInDom node, ->
equal node.css('display'), 'none'
QUnit.start()
asyncTest 'it should allow arbitrary attributes to be bound', 2, ->
source = '<div data-bind-foo="one" data-bind-bar="two" foo="before"></div>'
helpers.render source,
one: "baz"
two: "qux"
, (node) ->
equal $(node[0]).attr('foo'), "baz"
equal $(node[0]).attr('bar'), "qux"
QUnit.start()
asyncTest 'it should allow multiple class names to be bound and updated', ->
source = '<div data-bind-class="classes"></div>'
context = new Batman.Object classes: 'foo bar'
helpers.render source, context, (node) ->
equal node[0].className, 'foo bar'
context.set 'classes', 'bar baz'
delay =>
equal node[0].className, 'bar baz'
asyncTest 'it should allow input values to be bound', 1, ->
helpers.render '<input data-bind="one" type="text" />',
one: "qux"
, (node) ->
equal $(node[0]).val(), 'qux'
QUnit.start()
asyncTest 'it should bind the input value and update the input when it changes', 2, ->
context = new Batman.Object
one: "qux"
helpers.render '<input data-bind="one" type="text" />', context, (node) ->
equal $(node[0]).val(), 'qux'
context.set('one', "bar")
delay =>
equal $(node[0]).val(), 'bar'
asyncTest 'it should bind the input value of checkboxes and update the value when the object changes', 2, ->
context = new Batman.Object
one: true
helpers.render '<input type="checkbox" data-bind="one" />', context, (node) ->
equal node[0].checked, true
context.set('one', false)
delay =>
equal node[0].checked, false
asyncTest 'it should bind the input value of checkboxes and update the object when the value changes', 1, ->
context = new Batman.Object
one: true
helpers.render '<input type="checkbox" data-bind="one" />', context, (node) ->
node[0].checked = false
helpers.triggerChange(node[0])
delay =>
equal context.get('one'), false
asyncTest 'it should bind the value of a select box and update when the value changes', 2, ->
context = new Batman.Object
heros: new Batman.Set('mario', 'crono', 'link')
selected: new Batman.Object(name: 'PI:NAME:<NAME>END_PI')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equals node[0].value, 'crono'
context.set 'selected.name', 'link'
delay =>
equal node[0].value, 'link'
asyncTest 'it binds the options of a select box and updates when the select\'s value changes', ->
context = new Batman.Object
something: 'PI:NAME:<NAME>END_PI'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select data-bind="something"><option value="PI:NAME:<NAME>END_PI" data-bind-selected="mario.selected"></option><option value="PI:NAME:<NAME>END_PI" data-bind-selected="crono.selected"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equal node[0].value, 'PI:NAME:<NAME>END_PI'
equal context.get('crono.selected'), true
equal context.get('mario.selected'), false
node[0].value = 'PI:NAME:<NAME>END_PI'
helpers.triggerChange node[0]
delay =>
equal context.get('mario.selected'), true
equal context.get('crono.selected'), false
asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', ->
context = new Batman.Object
heros: new Batman.Set('PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'link', 'PI:NAME:<NAME>END_PI')
selected: new Batman.Object(name: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'])
helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
selections = (c.selected for c in node[0].children)
deepEqual selections, [no, yes, yes, no]
context.set 'selected.name', ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
delay =>
selections = (c.selected for c in node[0].children)
deepEqual selections, [yes, no, no, yes]
asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', ->
context = new Batman.Object
selected: 'PI:NAME:<NAME>END_PIono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select multiple="multiple" data-bind="selected"><option value="mario" data-bind-selected="mario.selected"></option><option value="PI:NAME:<NAME>END_PIono" data-bind-selected="crono.selected"></option></select>', context, (node) ->
delay => # wait for select's data-bind listener to receive the rendered event
equal node[0].value, 'crono', 'node value is crono'
equal context.get('selected'), 'crono', 'selected is crono'
equal context.get('crono.selected'), true, 'crono is selected'
equal context.get('mario.selected'), false, 'mario is not selected'
context.set 'mario.selected', true
delay =>
equal context.get('mario.selected'), true, 'mario is selected'
equal context.get('crono.selected'), true, 'crono is still selected'
deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding'
for opt in node[0].children
ok opt.selected, "#{opt.value} option is selected"
asyncTest 'it should bind the input value and update the object when it changes', 1, ->
context = new Batman.Object
one: "qux"
helpers.render '<input data-bind="one" type="text" />', context, (node) ->
$(node[0]).val('bar')
# Use DOM level 2 event dispatch, $().trigger doesn't seem to work
helpers.triggerChange(node[0])
delay =>
equal context.get('one'), 'bar'
asyncTest 'it should bind the value of textareas', 2, ->
context = new Batman.Object
one: "qux"
helpers.render '<textarea data-bind="one"></textarea>', context, (node) ->
equal node.val(), 'qux'
context.set('one', "bar")
delay =>
equal node.val(), 'bar'
asyncTest 'it should bind the value of textareas and inputs simulatenously', ->
context = new Batman.Object
one: "qux"
helpers.render '<textarea data-bind="one"></textarea><input data-bind="one" type="text"/>', context, (node) ->
f = (v) =>
equal $(node[0]).val(), v
equal $(node[1]).val(), v
f('qux')
$(node[1]).val('bar')
helpers.triggerChange(node[1])
delay =>
f('bar')
$(node[0]).val('baz')
helpers.triggerChange(node[0])
delay =>
f('baz')
$(node[1]).val('foo')
helpers.triggerChange(node[1])
delay =>
f('foo')
asyncTest 'it should allow events to be bound and execute them in the context as specified on a multi key keypath', 1, ->
context = Batman
foo: Batman
bar: Batman
doSomething: spy = createSpy()
source = '<button data-event-click="foo.bar.doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
equal spy.lastCallContext, context.get('foo.bar')
asyncTest 'it should allow events to be bound and execute them in the context as specified on terminal keypath', 1, ->
context = Batman
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
equal spy.lastCallContext, context
asyncTest 'it should allow click events to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow double click events to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<button data-event-doubleclick="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerDoubleClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow event handlers to update', 2, ->
context = Batman
doSomething: spy = createSpy()
source = '<button data-event-click="doSomething"></button>'
helpers.render source, context, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
context.set('doSomething', newSpy = createSpy())
helpers.triggerClick(node[0])
delay ->
ok newSpy.called
asyncTest 'it should allow change events on checkboxes to be bound', 1, ->
context = new Batman.Object
one: true
doSomething: createSpy()
helpers.render '<input type="checkbox" data-bind="one" data-event-change="doSomething"/>', context, (node) ->
node[0].checked = false
helpers.triggerChange(node[0])
delay =>
ok context.doSomething.called
asyncTest 'it should allow submit events on inputs to be bound', 2, ->
context =
doSomething: spy = createSpy()
source = '<form><input data-event-submit="doSomething" /></form>'
helpers.render source, context, (node) ->
helpers.triggerKey(node[0].childNodes[0], 13)
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0].childNodes[0]
asyncTest 'it should allow form submit events to be bound', 1, ->
context =
doSomething: spy = createSpy()
source = '<form data-event-submit="doSomething"><input type="submit" id="submit" /></form>'
helpers.render source, context, (node) ->
helpers.triggerSubmit(node[0])
delay =>
ok spy.called
asyncTest 'allows data-event-click attributes to reference native model properties directly', ->
spy = createSpy()
class Foo extends Batman.Model
handleClick: spy
source = '<button data-event-click="foo.handleClick"></button>'
helpers.render source, {foo: new Foo()}, (node) ->
helpers.triggerClick(node[0])
delay ->
ok spy.called
equal spy.lastCallArguments[0], node[0]
asyncTest 'it should allow mixins to be applied', 1, ->
Batman.mixins.set 'test',
foo: 'bar'
source = '<div data-mixin="test"></div>'
helpers.render source, false, (node) ->
delay ->
equals Batman.data(node.firstChild, 'foo'), 'bar'
delete Batman.mixins.test
asyncTest 'it should allow contexts to be entered', 2, ->
context = Batman
namespace: Batman
foo: 'bar'
source = '<div data-context="namespace"><span id="test" data-bind="foo"></span></div>'
helpers.render source, context, (node) ->
equal $('#test', node).html(), 'bar'
context.set('namespace', Batman(foo: 'baz'))
delay ->
equal $("#test", node).html(), 'baz', 'if the context changes the bindings should update'
asyncTest 'it should allow contexts to be specified using filters', 2, ->
context = Batman
namespace: Batman
foo: Batman
bar: 'baz'
keyName: 'foo'
source = '<div data-context="namespace | get keyName"><span id="test" data-bind="bar"></span></div>'
helpers.render source, context, (node) ->
equal $('#test', node).html(), 'baz'
context.set('namespace', Batman(foo: Batman(bar: 'qux')))
delay ->
equal $("#test", node).html(), 'qux', 'if the context changes the bindings should update'
asyncTest 'should bind radio buttons to a value', ->
source = '<input id="fixed" type="radio" data-bind="ad.sale_type" name="sale_type" value="fixed"/>
<input id="free" type="radio" data-bind="ad.sale_type" name="sale_type" value="free"/>
<input id="trade" type="radio" data-bind="ad.sale_type" name="sale_type" value="trade"/>'
context = Batman
ad: Batman
sale_type: 'free'
helpers.render source, context, (node) ->
fixed = node[0]
free = node[1]
trade = node[2]
ok (!fixed.checked and free.checked and !trade.checked)
context.set 'ad.sale_type', 'trade'
delay =>
ok (!fixed.checked and !free.checked and trade.checked)
asyncTest 'should bind to the value of radio buttons', ->
source = '<input id="fixed" type="radio" data-bind="ad.sale_type" name="sale_type" value="fixed"/>
<input id="free" type="radio" data-bind="ad.sale_type" name="sale_type" value="free"/>
<input id="trade" type="radio" data-bind="ad.sale_type" name="sale_type" value="trade" checked/>'
context = Batman
ad: Batman
helpers.render source, context, (node) ->
fixed = node[0]
free = node[1]
trade = node[2]
ok (!fixed.checked and !free.checked and trade.checked)
equal context.get('ad.sale_type'), 'trade', 'checked attribute binds'
helpers.triggerChange(fixed)
delay =>
equal context.get('ad.sale_type'), 'fixed'
|
[
{
"context": "\n# ngrok.connect\n# authtoken : 'CMY-UsZMWdx586A3tA0U'\n# subdomain : subdomain\n# po",
"end": 2018,
"score": 0.9986413717269897,
"start": 1998,
"tag": "PASSWORD",
"value": "CMY-UsZMWdx586A3tA0U"
}
] | app/templates/server/server.coffee | koding/generator-kd | 0 | cookieParser = require 'cookie-parser'
fs = require 'fs'
log = console.log
PeerServer = require('./peerjs-server').PeerServer
coffee = require 'coffee-script'
ngrok = require 'ngrok'
restify = require('./peerjs-server/node_modules/restify')
# fs.writeFileSync "./static/main.js",coffee.compile(fs.readFileSync("./app/client/main.coffee","utf8"))
maps =
c2p : {}
p2c : {}
peers = {}
index = fs.readFileSync "./static/index.html"
indexLen = Buffer.byteLength(index+"")
defaultRoute = (req, res, next) ->
# res.cookie "peerid", peerid
# res.cookie "peers", peerList(channel)
# log "sending peers:",peerList(channel)
console.log req.params
res.writeHead 200,
"Content-Length" : indexLen
'Content-Type' : 'text/html'
res.write index
res.end()
next()
path = require 'path'
ps = new PeerServer
port : 3000
path : '/-/ps'
static:
path : /\/static\/?.*/
directory : path.join __dirname, "/.."
default : 'index.html'
routes :
[
{
type : "get"
path : "/peers"
fn : (req,res,next)->
# res.writeHead 200,
# 'Content-Type' : 'application/json'
res.send 200, peers
},
{
type : "get"
path : "/:all"
fn : defaultRoute
},
{
type : "get"
path : "/"
fn : defaultRoute
}
]
ps.on "connection",(peerid)->
log "connected:",peerid
peers[peerid] = ""
ps.on "disconnect",(peerid)->
log "disconnected:",peerid
delete peers[peerid]
setInterval ->
log peers
,2500
# setTimeout ->
# [{name:"p2p", port: 3000}].forEach (kite)->
# id = process.env.USER
# subdomain = "#{kite.name}-#{id}"
# console.log "--------------------> creating public website #{subdomain}"
# ngrok.connect
# authtoken : 'CMY-UsZMWdx586A3tA0U'
# subdomain : subdomain
# port : kite.port
# , (err, url)->
# if err
# console.log "Failed to create #{kite.name} tunnel: ", err
# else
# console.log "0.0.0.0:#{kite.port} for #{subdomain} is now tunneling with: ", url
# ,10000
| 117122 | cookieParser = require 'cookie-parser'
fs = require 'fs'
log = console.log
PeerServer = require('./peerjs-server').PeerServer
coffee = require 'coffee-script'
ngrok = require 'ngrok'
restify = require('./peerjs-server/node_modules/restify')
# fs.writeFileSync "./static/main.js",coffee.compile(fs.readFileSync("./app/client/main.coffee","utf8"))
maps =
c2p : {}
p2c : {}
peers = {}
index = fs.readFileSync "./static/index.html"
indexLen = Buffer.byteLength(index+"")
defaultRoute = (req, res, next) ->
# res.cookie "peerid", peerid
# res.cookie "peers", peerList(channel)
# log "sending peers:",peerList(channel)
console.log req.params
res.writeHead 200,
"Content-Length" : indexLen
'Content-Type' : 'text/html'
res.write index
res.end()
next()
path = require 'path'
ps = new PeerServer
port : 3000
path : '/-/ps'
static:
path : /\/static\/?.*/
directory : path.join __dirname, "/.."
default : 'index.html'
routes :
[
{
type : "get"
path : "/peers"
fn : (req,res,next)->
# res.writeHead 200,
# 'Content-Type' : 'application/json'
res.send 200, peers
},
{
type : "get"
path : "/:all"
fn : defaultRoute
},
{
type : "get"
path : "/"
fn : defaultRoute
}
]
ps.on "connection",(peerid)->
log "connected:",peerid
peers[peerid] = ""
ps.on "disconnect",(peerid)->
log "disconnected:",peerid
delete peers[peerid]
setInterval ->
log peers
,2500
# setTimeout ->
# [{name:"p2p", port: 3000}].forEach (kite)->
# id = process.env.USER
# subdomain = "#{kite.name}-#{id}"
# console.log "--------------------> creating public website #{subdomain}"
# ngrok.connect
# authtoken : '<PASSWORD>'
# subdomain : subdomain
# port : kite.port
# , (err, url)->
# if err
# console.log "Failed to create #{kite.name} tunnel: ", err
# else
# console.log "0.0.0.0:#{kite.port} for #{subdomain} is now tunneling with: ", url
# ,10000
| true | cookieParser = require 'cookie-parser'
fs = require 'fs'
log = console.log
PeerServer = require('./peerjs-server').PeerServer
coffee = require 'coffee-script'
ngrok = require 'ngrok'
restify = require('./peerjs-server/node_modules/restify')
# fs.writeFileSync "./static/main.js",coffee.compile(fs.readFileSync("./app/client/main.coffee","utf8"))
maps =
c2p : {}
p2c : {}
peers = {}
index = fs.readFileSync "./static/index.html"
indexLen = Buffer.byteLength(index+"")
defaultRoute = (req, res, next) ->
# res.cookie "peerid", peerid
# res.cookie "peers", peerList(channel)
# log "sending peers:",peerList(channel)
console.log req.params
res.writeHead 200,
"Content-Length" : indexLen
'Content-Type' : 'text/html'
res.write index
res.end()
next()
path = require 'path'
ps = new PeerServer
port : 3000
path : '/-/ps'
static:
path : /\/static\/?.*/
directory : path.join __dirname, "/.."
default : 'index.html'
routes :
[
{
type : "get"
path : "/peers"
fn : (req,res,next)->
# res.writeHead 200,
# 'Content-Type' : 'application/json'
res.send 200, peers
},
{
type : "get"
path : "/:all"
fn : defaultRoute
},
{
type : "get"
path : "/"
fn : defaultRoute
}
]
ps.on "connection",(peerid)->
log "connected:",peerid
peers[peerid] = ""
ps.on "disconnect",(peerid)->
log "disconnected:",peerid
delete peers[peerid]
setInterval ->
log peers
,2500
# setTimeout ->
# [{name:"p2p", port: 3000}].forEach (kite)->
# id = process.env.USER
# subdomain = "#{kite.name}-#{id}"
# console.log "--------------------> creating public website #{subdomain}"
# ngrok.connect
# authtoken : 'PI:PASSWORD:<PASSWORD>END_PI'
# subdomain : subdomain
# port : kite.port
# , (err, url)->
# if err
# console.log "Failed to create #{kite.name} tunnel: ", err
# else
# console.log "0.0.0.0:#{kite.port} for #{subdomain} is now tunneling with: ", url
# ,10000
|
[
{
"context": " \"localhost\"\n\t\t\tuser: config.username\n\t\t\tpassword: config.password\n\t\t\tdatabase: config.database\n\t\t\tcharset: config.c",
"end": 354,
"score": 0.9992130398750305,
"start": 339,
"tag": "PASSWORD",
"value": "config.password"
}
] | lib/fancyshelf/index.coffee | rallias/pdfy2 | 0 | bookshelf = require("bookshelf")
knex = require("knex")
util = require "util"
module.exports = (config) ->
conn = config.knex ? knex({
client: switch config.engine
when "pg", "postgres", "postgresql" then "pg"
else (config.engine ? "mysql2")
connection:
host: config.host ? "localhost"
user: config.username
password: config.password
database: config.database
charset: config.charset ? "utf8"
debug: config.debug ? false
})
shelf = bookshelf(conn)
shelf.connection = conn
shelf.plugin("registry") # We use the original model registry plugin, no point in reproducing a wheel.
shelf.plugin("virtuals") # We need the virtuals plugin as well.
shelf.plugin(require.resolve("./aliases"))
shelf.plugin(require.resolve("./better-fetch"))
shelf.plugin(require.resolve("./find-method"))
shelf.plugin(require.resolve("./retrieve-each"))
shelf.plugin(require.resolve("./save-changes"))
shelf.express = (req, res, next) ->
req.db = shelf
req.model = shelf.model.bind(shelf)
req.modelQuery = shelf.modelQuery.bind(shelf)
next()
return shelf
| 106455 | bookshelf = require("bookshelf")
knex = require("knex")
util = require "util"
module.exports = (config) ->
conn = config.knex ? knex({
client: switch config.engine
when "pg", "postgres", "postgresql" then "pg"
else (config.engine ? "mysql2")
connection:
host: config.host ? "localhost"
user: config.username
password: <PASSWORD>
database: config.database
charset: config.charset ? "utf8"
debug: config.debug ? false
})
shelf = bookshelf(conn)
shelf.connection = conn
shelf.plugin("registry") # We use the original model registry plugin, no point in reproducing a wheel.
shelf.plugin("virtuals") # We need the virtuals plugin as well.
shelf.plugin(require.resolve("./aliases"))
shelf.plugin(require.resolve("./better-fetch"))
shelf.plugin(require.resolve("./find-method"))
shelf.plugin(require.resolve("./retrieve-each"))
shelf.plugin(require.resolve("./save-changes"))
shelf.express = (req, res, next) ->
req.db = shelf
req.model = shelf.model.bind(shelf)
req.modelQuery = shelf.modelQuery.bind(shelf)
next()
return shelf
| true | bookshelf = require("bookshelf")
knex = require("knex")
util = require "util"
module.exports = (config) ->
conn = config.knex ? knex({
client: switch config.engine
when "pg", "postgres", "postgresql" then "pg"
else (config.engine ? "mysql2")
connection:
host: config.host ? "localhost"
user: config.username
password: PI:PASSWORD:<PASSWORD>END_PI
database: config.database
charset: config.charset ? "utf8"
debug: config.debug ? false
})
shelf = bookshelf(conn)
shelf.connection = conn
shelf.plugin("registry") # We use the original model registry plugin, no point in reproducing a wheel.
shelf.plugin("virtuals") # We need the virtuals plugin as well.
shelf.plugin(require.resolve("./aliases"))
shelf.plugin(require.resolve("./better-fetch"))
shelf.plugin(require.resolve("./find-method"))
shelf.plugin(require.resolve("./retrieve-each"))
shelf.plugin(require.resolve("./save-changes"))
shelf.express = (req, res, next) ->
req.db = shelf
req.model = shelf.model.bind(shelf)
req.modelQuery = shelf.modelQuery.bind(shelf)
next()
return shelf
|
[
{
"context": "al = (a, b, opts) ->\n # This code is adapted from Anders Kaseorg's post at\n # http://stackoverflow.com/a/32794387/6",
"end": 507,
"score": 0.9904873967170715,
"start": 491,
"tag": "NAME",
"value": "Anders Kaseorg's"
},
{
"context": " should not be used unless\n # h... | src/Util/DeepEquality.coffee | cdglabs/apparatus | 1,060 | _ = require "underscore"
module.exports = DeepEquality = {}
# cyclicDeepEqual compares two Javascript values. It is comfortable with values
# which have cyclic references between their parts. In this case, it will ensure
# that the two values have isomorphic reference graphs.
# Opts:
# checkPrototypes (default: true) -- whether equality of prototypes should
# be included in the checking process
DeepEquality.cyclicDeepEqual = (a, b, opts) ->
# This code is adapted from Anders Kaseorg's post at
# http://stackoverflow.com/a/32794387/668144.
# Note that deep-equal-ident should not be used unless
# https://github.com/fkling/deep-equal-ident/issues/3
# is fixed.
opts ?= {}
_.defaults(opts, {
checkPrototypes: true,
})
left = []
right = []
has = Object.prototype.hasOwnProperty
visit = (a, b) ->
if typeof a != 'object' || typeof b != 'object' || a == null || b == null
return a == b
for i in [0...left.length]
if (a == left[i])
return b == right[i]
if (b == right[i])
return a == left[i]
for own k of a
return false if !has.call(b, k)
for own k of b
return false if !has.call(a, k)
left.push(a)
right.push(b)
for own k of a
return false if !visit(a[k], b[k])
if opts.checkPrototypes
# NOTE: This is changed from StackOverflow version, to allow prototypes to
# be part of the maybe-isomorphic reference graphs rather than strictly
# equal to one another.
return false if !visit(Object.getPrototypeOf(a), Object.getPrototypeOf(b))
return true
return visit(a, b)
| 77177 | _ = require "underscore"
module.exports = DeepEquality = {}
# cyclicDeepEqual compares two Javascript values. It is comfortable with values
# which have cyclic references between their parts. In this case, it will ensure
# that the two values have isomorphic reference graphs.
# Opts:
# checkPrototypes (default: true) -- whether equality of prototypes should
# be included in the checking process
DeepEquality.cyclicDeepEqual = (a, b, opts) ->
# This code is adapted from <NAME> post at
# http://stackoverflow.com/a/32794387/668144.
# Note that deep-equal-ident should not be used unless
# https://github.com/fkling/deep-equal-ident/issues/3
# is fixed.
opts ?= {}
_.defaults(opts, {
checkPrototypes: true,
})
left = []
right = []
has = Object.prototype.hasOwnProperty
visit = (a, b) ->
if typeof a != 'object' || typeof b != 'object' || a == null || b == null
return a == b
for i in [0...left.length]
if (a == left[i])
return b == right[i]
if (b == right[i])
return a == left[i]
for own k of a
return false if !has.call(b, k)
for own k of b
return false if !has.call(a, k)
left.push(a)
right.push(b)
for own k of a
return false if !visit(a[k], b[k])
if opts.checkPrototypes
# NOTE: This is changed from StackOverflow version, to allow prototypes to
# be part of the maybe-isomorphic reference graphs rather than strictly
# equal to one another.
return false if !visit(Object.getPrototypeOf(a), Object.getPrototypeOf(b))
return true
return visit(a, b)
| true | _ = require "underscore"
module.exports = DeepEquality = {}
# cyclicDeepEqual compares two Javascript values. It is comfortable with values
# which have cyclic references between their parts. In this case, it will ensure
# that the two values have isomorphic reference graphs.
# Opts:
# checkPrototypes (default: true) -- whether equality of prototypes should
# be included in the checking process
DeepEquality.cyclicDeepEqual = (a, b, opts) ->
# This code is adapted from PI:NAME:<NAME>END_PI post at
# http://stackoverflow.com/a/32794387/668144.
# Note that deep-equal-ident should not be used unless
# https://github.com/fkling/deep-equal-ident/issues/3
# is fixed.
opts ?= {}
_.defaults(opts, {
checkPrototypes: true,
})
left = []
right = []
has = Object.prototype.hasOwnProperty
visit = (a, b) ->
if typeof a != 'object' || typeof b != 'object' || a == null || b == null
return a == b
for i in [0...left.length]
if (a == left[i])
return b == right[i]
if (b == right[i])
return a == left[i]
for own k of a
return false if !has.call(b, k)
for own k of b
return false if !has.call(a, k)
left.push(a)
right.push(b)
for own k of a
return false if !visit(a[k], b[k])
if opts.checkPrototypes
# NOTE: This is changed from StackOverflow version, to allow prototypes to
# be part of the maybe-isomorphic reference graphs rather than strictly
# equal to one another.
return false if !visit(Object.getPrototypeOf(a), Object.getPrototypeOf(b))
return true
return visit(a, b)
|
[
{
"context": "nt from specified DSN correctly', ->\n key = '1234567890abcdef'\n secret = 'fedcba0987654321'\n project_",
"end": 636,
"score": 0.9996853470802307,
"start": 620,
"tag": "KEY",
"value": "1234567890abcdef"
},
{
"context": "->\n key = '1234567890abcdef'... | test/sentry.coffee | DanielsNoJack/sentry-node | 4 | _ = require 'underscore'
assert = require 'assert'
os = require 'os'
nock = require 'nock'
sinon = require 'sinon'
Promise = require 'bluebird'
Sentry = require("#{__dirname}/../lib/sentry")
{_handle_http_load_errors} = require("#{__dirname}/../lib/sentry")._private
sentry_settings = require("#{__dirname}/credentials").sentry
describe 'Sentry', ->
beforeEach ->
@sentry = new Sentry sentry_settings
describe 'constructor', ->
it 'should create an instance of Sentry', ->
assert.equal @sentry.constructor.name, 'Sentry'
it 'setup sentry client from specified DSN correctly', ->
key = '1234567890abcdef'
secret = 'fedcba0987654321'
project_id = '12345'
# mock sentry dsn with random uuid as public_key and secret_key
dsn = "https://#{key}:#{secret}@app.getsentry.com/#{project_id}"
_sentry = new Sentry dsn
assert.equal _sentry.key, key
assert.equal _sentry.secret, secret
assert.equal _sentry.project_id, project_id
assert.equal _sentry.hostname, os.hostname()
assert.equal _sentry.enabled, true
it 'setup sentry client from object correctly', ->
assert.equal @sentry.key, sentry_settings.key
assert.equal @sentry.secret, sentry_settings.secret
assert.equal @sentry.project_id, sentry_settings.project_id
assert.equal @sentry.hostname, os.hostname()
assert.equal @sentry.enabled, true
it 'refuses to enable the sentry with incomplete credentials', ->
_sentry = new Sentry _.omit sentry_settings, 'secret'
assert.equal _sentry.hostname, os.hostname()
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
it 'empty or missing DSN should disable the client', ->
_sentry = new Sentry ""
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
_sentry = new Sentry()
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Sentry client expected String or Object as argument. You passed: undefined."
it 'invalid DSN should disable the client', ->
_sentry = new Sentry "https://app.getsentry.com/12345"
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
describe '#error', ->
beforeEach ->
sinon.stub @sentry, '_send'
it 'emits warning if passed an error that isnt an instance of Error', (done) ->
@sentry.on 'warning', (err) ->
assert err instanceof Error
assert err.message.match /^WARNING: err not passed as Error!/
done()
@sentry.error 'not an Error', 'path/to/logger', 'culprit'
it 'uses _send to send error', ->
[err_message, logger, culprit] = ['Error message', '/path/to/logger', 'culprit']
@sentry.error new Error(err_message), logger, culprit
assert @sentry._send.calledOnce
send_data = @sentry._send.getCall(0).args[0]
assert.equal err_message, send_data.message, "Unexpected message. Expected '#{err_message}', Received '#{send_data.message}'"
assert.equal logger, send_data.logger, "Unexpected logger. Expected '#{logger}', Received '#{send_data.logger}'"
assert !_.isUndefined send_data.server_name, "Expected a value to be set for server_name, undefined given"
assert.equal culprit, send_data.culprit, "Unexpected culprit. Expected '#{culprit}', Received '#{send_data.culprit}'"
assert.equal 'node', send_data.platform, "Unexpected platform. Expected 'node', Received '#{send_data.platform}'"
assert.equal 'error', send_data.level, "Unexpected level. Expected 'error', Received '#{send_data.level}'"
it 'will send error correctly when culprit is null', ->
@sentry.error new Error('Error message'), '/path/to/logger', null
send_data = @sentry._send.getCall(0).args[0]
assert _.isUndefined(send_data.culprit)
describe '#message', ->
beforeEach ->
sinon.stub @sentry, '_send'
it 'send message correctly via _send', ->
@sentry.message 'message', '/path/to/logger'
assert @sentry._send.calledOnce
send_data = @sentry._send.getCall(0).args[0]
assert.equal 'message', send_data.message, "Unexpected message. Expected 'message', Received '#{send_data.message}'"
assert.equal '/path/to/logger', send_data.logger, "Unexpected logger. Expected '/path/to/logger', Received '#{send_data.logger}'"
assert.equal 'info', send_data.level, "Unexpected level. Expected 'info', Received '#{send_data.level}'"
describe '#_send', ->
beforeEach ->
# Mute errors, they should be tested for and expected
sinon.stub console , 'error'
afterEach ->
console.error.restore()
it 'emit error event when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', (err) ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'calls callback when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', ->
@sentry.message "hey!", "/", {}, (err) ->
assert.equal err.message, "status code: 500"
scope.done()
done()
it 'emits done event when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', ->
@sentry.once 'done', ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'calls callback when successfully made an api call', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.message "hey!", "/", {}, (err) ->
assert.ifError err
scope.done()
done()
it 'emits done event successfully made an api call', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.once 'done', ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'emits logged event when successfully made an api call', (done) ->
@scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.on 'logged', ->
done()
@sentry._send get_mock_data()
it 'emits a warning if you pass a non string logger', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
logger = key: '/path/to/logger'
@sentry.once 'warning', (err) ->
assert.equal err.message, "WARNING: logger not passed as string! #{JSON.stringify(logger)}"
done()
data = get_mock_data()
data.logger = logger
@sentry._send data
it 'emits a logged event once logged', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
logger = key: '/path/to/logger'
@sentry.once 'logged', ->
scope.done()
done()
data = get_mock_data()
data.logger = logger
@sentry._send data
it 'emits a warning if there are circular references in "extra", before sending', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
extra = {foo: 'bar'}
extra = _.extend extra, {circular: extra}
@sentry.once 'warning', (err) ->
assert.equal err.message, "WARNING: extra not parseable to JSON!"
assert !_.isEmpty(scope.pendingMocks())
done()
@sentry.error new Error('Error message'), '/path/to/logger', 'culprit', extra
it 'emits logged even if there are circular referances in "extra"', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
extra = {foo: 'bar'}
extra = _.extend extra, {circular: extra}
@sentry.once 'logged', ->
scope.done()
done()
@sentry.error new Error('Error message'), '/path/to/logger', 'culprit', extra
describe 'private function _handle_http_load_errors', ->
it 'exists as a function', ->
assert _.isFunction _handle_http_load_errors, 'Expected Sentry to have fn _handle_http_load_errors'
it 'should emit a warning when invoked with error', (done) ->
my_error = new Error 'Testing error'
@sentry.once 'warning', (err) ->
assert.equal err, my_error
done()
_handle_http_load_errors @sentry, my_error
describe 'wrapper with sentry disabled', ->
beforeEach ->
sinon.spy @sentry, 'error'
@sentry.enabled = false
it 'calls the given fn normally if sentry is disabled', (done) ->
wrapper = @sentry.wrapper 'logger'
args = [1, 'two', [3]]
expected = [null, {'4'}, 5, 'six']
fn = sinon.stub().yields expected...
wrapper.wrap(fn) args..., (results...) =>
assert not @sentry.error.called, 'Expected sentry.error to not be called'
assert.deepEqual results, expected
assert fn.calledOnce, 'Expected fn to be called exactly once'
assert.deepEqual fn.firstCall.args[...-1], args # strip off callback
done()
describe 'wrapper with sentry enabled', ->
beforeEach ->
sinon.spy @sentry, 'error'
@scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
it 'calls the given fn with its args and passes through the results', (done) ->
wrapper = @sentry.wrapper 'logger'
args = [1, 'two', [3]]
expected = [null, {'4'}, 5, 'six']
fn = sinon.stub().yields expected...
wrapper.wrap(fn) args..., (results...) ->
assert.deepEqual results, expected
assert fn.calledOnce, 'Expected fn to be called exactly once'
assert.deepEqual fn.firstCall.args[...-1], args # strip off callback
done()
it 'sends to Sentry if the given function produces an error', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error 'oops'
expected_args = [1, 'two', [3]]
wrapper.wrap((args..., cb) -> setImmediate -> cb expected_err) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
done()
return
it 'doesnt send to Sentry if the given function produces no error', (done) ->
wrapper = @sentry.wrapper 'logger'
wrapper.wrap((cb) -> setImmediate -> cb null) (err) =>
assert.deepEqual err, null
assert not @sentry.error.called, 'Expected sentry.error to not be called'
done()
return
it 'sends to Sentry if the given function produces an error and globals has value', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error('oops')
expected_args = [1, 'two', [3]]
wrapper.wrap((args..., cb) -> setImmediate ->
wrapper.globals.hello = 'world'
cb expected_err
) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
assert.deepEqual @sentry.error.firstCall.args[3].hello, 'world'
done()
it 'only calls the cb with no error once sentry-node emits a "logged" event', (done) ->
wrapper = @sentry.wrapper 'logger'
cb = sinon.spy()
wrapper.wrap((cb) -> cb new Error 'oops') cb
assert not cb.called, 'Expected cb to not be called before event'
@sentry.once 'logged', ->
assert cb.calledOnce, 'Expected cb to be called after logged event'
done()
@sentry.emit 'logged'
it 'calls the cb with an error if sentry-node emits an "error" event', (done) ->
wrapper = @sentry.wrapper 'logger'
cb = sinon.spy()
original_error = new Error 'oops'
sentry_error = new Error 'sentry failed'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before event'
@sentry.once 'error', ->
assert cb.calledOnce, 'Expected cb to be called after error event'
assert.deepEqual cb.firstCall.args, [_.extend sentry_error, {original_error}]
done()
@sentry.emit 'error', sentry_error
describe 'wrapper with timeout set', ->
beforeEach ->
sinon.stub @sentry, 'error'
TIMEOUT = 10
it 'calls the cb with an error if sentry-node doesnt emit any event', (done) ->
wrapper = @sentry.wrapper 'logger', TIMEOUT
cb = sinon.spy()
original_error = new Error 'oops'
timeout_error = new Error 'Sentry timed out'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before timeout'
setTimeout ->
assert cb.calledOnce, 'Expected cb to be called after timeout'
assert.deepEqual cb.firstCall.args, [_.extend timeout_error, {original_error}]
done()
, TIMEOUT + 1
it 'calls the cb with an error if sentry-node doesnt emit an event quickly enough', (done) ->
wrapper = @sentry.wrapper 'logger', TIMEOUT
cb = sinon.spy()
original_error = new Error 'oops'
timeout_error = new Error 'Sentry timed out'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before timeout'
setTimeout (=> @sentry.emit 'logged'), TIMEOUT + 1
setTimeout ->
assert cb.calledOnce, 'Expected cb to be called exactly once after timeout'
assert.deepEqual cb.firstCall.args, [_.extend timeout_error, {original_error}]
done()
, TIMEOUT + 2
describe 'wrapper with sentry enabled using promises', ->
beforeEach ->
sinon.spy @sentry, 'error'
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
it 'sends to Sentry if the given function produces an error', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error 'oops'
expected_args = [1, 'two', [3]]
wrapper.wrap((args...) -> new Promise (resolve, reject) -> setImmediate -> reject(expected_err)) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
done()
return
it 'doesnt send to Sentry if the given function produces no error', (done) ->
wrapper = @sentry.wrapper 'logger'
wrapper.wrap(-> new Promise (resolve, reject) -> setImmediate -> resolve(null)) (err) =>
assert.deepEqual err, null
assert not @sentry.error.called, 'Expected sentry.error to not be called'
done()
return
get_mock_data = ->
err = new Error 'Testing sentry'
message: err.message # smaller text that appears right under culprit (and shows up in HipChat)
logger: '/path/to/logger'
server_name: 'apple'
platform: 'node'
level: 'error'
extra: err.stack
culprit: 'Too many tests... jk'
| 203056 | _ = require 'underscore'
assert = require 'assert'
os = require 'os'
nock = require 'nock'
sinon = require 'sinon'
Promise = require 'bluebird'
Sentry = require("#{__dirname}/../lib/sentry")
{_handle_http_load_errors} = require("#{__dirname}/../lib/sentry")._private
sentry_settings = require("#{__dirname}/credentials").sentry
describe 'Sentry', ->
beforeEach ->
@sentry = new Sentry sentry_settings
describe 'constructor', ->
it 'should create an instance of Sentry', ->
assert.equal @sentry.constructor.name, 'Sentry'
it 'setup sentry client from specified DSN correctly', ->
key = '<KEY>'
secret = '<KEY>'
project_id = '12345'
# mock sentry dsn with random uuid as public_key and secret_key
dsn = "https://#{key}:#{secret}@app.getsentry.com/#{project_id}"
_sentry = new Sentry dsn
assert.equal _sentry.key, key
assert.equal _sentry.secret, secret
assert.equal _sentry.project_id, project_id
assert.equal _sentry.hostname, os.hostname()
assert.equal _sentry.enabled, true
it 'setup sentry client from object correctly', ->
assert.equal @sentry.key, sentry_settings.key
assert.equal @sentry.secret, sentry_settings.secret
assert.equal @sentry.project_id, sentry_settings.project_id
assert.equal @sentry.hostname, os.hostname()
assert.equal @sentry.enabled, true
it 'refuses to enable the sentry with incomplete credentials', ->
_sentry = new Sentry _.omit sentry_settings, 'secret'
assert.equal _sentry.hostname, os.hostname()
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
it 'empty or missing DSN should disable the client', ->
_sentry = new Sentry ""
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
_sentry = new Sentry()
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Sentry client expected String or Object as argument. You passed: undefined."
it 'invalid DSN should disable the client', ->
_sentry = new Sentry "https://app.getsentry.com/12345"
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
describe '#error', ->
beforeEach ->
sinon.stub @sentry, '_send'
it 'emits warning if passed an error that isnt an instance of Error', (done) ->
@sentry.on 'warning', (err) ->
assert err instanceof Error
assert err.message.match /^WARNING: err not passed as Error!/
done()
@sentry.error 'not an Error', 'path/to/logger', 'culprit'
it 'uses _send to send error', ->
[err_message, logger, culprit] = ['Error message', '/path/to/logger', 'culprit']
@sentry.error new Error(err_message), logger, culprit
assert @sentry._send.calledOnce
send_data = @sentry._send.getCall(0).args[0]
assert.equal err_message, send_data.message, "Unexpected message. Expected '#{err_message}', Received '#{send_data.message}'"
assert.equal logger, send_data.logger, "Unexpected logger. Expected '#{logger}', Received '#{send_data.logger}'"
assert !_.isUndefined send_data.server_name, "Expected a value to be set for server_name, undefined given"
assert.equal culprit, send_data.culprit, "Unexpected culprit. Expected '#{culprit}', Received '#{send_data.culprit}'"
assert.equal 'node', send_data.platform, "Unexpected platform. Expected 'node', Received '#{send_data.platform}'"
assert.equal 'error', send_data.level, "Unexpected level. Expected 'error', Received '#{send_data.level}'"
it 'will send error correctly when culprit is null', ->
@sentry.error new Error('Error message'), '/path/to/logger', null
send_data = @sentry._send.getCall(0).args[0]
assert _.isUndefined(send_data.culprit)
describe '#message', ->
beforeEach ->
sinon.stub @sentry, '_send'
it 'send message correctly via _send', ->
@sentry.message 'message', '/path/to/logger'
assert @sentry._send.calledOnce
send_data = @sentry._send.getCall(0).args[0]
assert.equal 'message', send_data.message, "Unexpected message. Expected 'message', Received '#{send_data.message}'"
assert.equal '/path/to/logger', send_data.logger, "Unexpected logger. Expected '/path/to/logger', Received '#{send_data.logger}'"
assert.equal 'info', send_data.level, "Unexpected level. Expected 'info', Received '#{send_data.level}'"
describe '#_send', ->
beforeEach ->
# Mute errors, they should be tested for and expected
sinon.stub console , 'error'
afterEach ->
console.error.restore()
it 'emit error event when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', (err) ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'calls callback when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', ->
@sentry.message "hey!", "/", {}, (err) ->
assert.equal err.message, "status code: 500"
scope.done()
done()
it 'emits done event when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', ->
@sentry.once 'done', ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'calls callback when successfully made an api call', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.message "hey!", "/", {}, (err) ->
assert.ifError err
scope.done()
done()
it 'emits done event successfully made an api call', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.once 'done', ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'emits logged event when successfully made an api call', (done) ->
@scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.on 'logged', ->
done()
@sentry._send get_mock_data()
it 'emits a warning if you pass a non string logger', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
logger = key: '/path/to/logger'
@sentry.once 'warning', (err) ->
assert.equal err.message, "WARNING: logger not passed as string! #{JSON.stringify(logger)}"
done()
data = get_mock_data()
data.logger = logger
@sentry._send data
it 'emits a logged event once logged', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
logger = key: <KEY>'
@sentry.once 'logged', ->
scope.done()
done()
data = get_mock_data()
data.logger = logger
@sentry._send data
it 'emits a warning if there are circular references in "extra", before sending', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
extra = {foo: 'bar'}
extra = _.extend extra, {circular: extra}
@sentry.once 'warning', (err) ->
assert.equal err.message, "WARNING: extra not parseable to JSON!"
assert !_.isEmpty(scope.pendingMocks())
done()
@sentry.error new Error('Error message'), '/path/to/logger', 'culprit', extra
it 'emits logged even if there are circular referances in "extra"', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
extra = {foo: 'bar'}
extra = _.extend extra, {circular: extra}
@sentry.once 'logged', ->
scope.done()
done()
@sentry.error new Error('Error message'), '/path/to/logger', 'culprit', extra
describe 'private function _handle_http_load_errors', ->
it 'exists as a function', ->
assert _.isFunction _handle_http_load_errors, 'Expected Sentry to have fn _handle_http_load_errors'
it 'should emit a warning when invoked with error', (done) ->
my_error = new Error 'Testing error'
@sentry.once 'warning', (err) ->
assert.equal err, my_error
done()
_handle_http_load_errors @sentry, my_error
describe 'wrapper with sentry disabled', ->
beforeEach ->
sinon.spy @sentry, 'error'
@sentry.enabled = false
it 'calls the given fn normally if sentry is disabled', (done) ->
wrapper = @sentry.wrapper 'logger'
args = [1, 'two', [3]]
expected = [null, {'4'}, 5, 'six']
fn = sinon.stub().yields expected...
wrapper.wrap(fn) args..., (results...) =>
assert not @sentry.error.called, 'Expected sentry.error to not be called'
assert.deepEqual results, expected
assert fn.calledOnce, 'Expected fn to be called exactly once'
assert.deepEqual fn.firstCall.args[...-1], args # strip off callback
done()
describe 'wrapper with sentry enabled', ->
beforeEach ->
sinon.spy @sentry, 'error'
@scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
it 'calls the given fn with its args and passes through the results', (done) ->
wrapper = @sentry.wrapper 'logger'
args = [1, 'two', [3]]
expected = [null, {'4'}, 5, 'six']
fn = sinon.stub().yields expected...
wrapper.wrap(fn) args..., (results...) ->
assert.deepEqual results, expected
assert fn.calledOnce, 'Expected fn to be called exactly once'
assert.deepEqual fn.firstCall.args[...-1], args # strip off callback
done()
it 'sends to Sentry if the given function produces an error', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error 'oops'
expected_args = [1, 'two', [3]]
wrapper.wrap((args..., cb) -> setImmediate -> cb expected_err) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
done()
return
it 'doesnt send to Sentry if the given function produces no error', (done) ->
wrapper = @sentry.wrapper 'logger'
wrapper.wrap((cb) -> setImmediate -> cb null) (err) =>
assert.deepEqual err, null
assert not @sentry.error.called, 'Expected sentry.error to not be called'
done()
return
it 'sends to Sentry if the given function produces an error and globals has value', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error('oops')
expected_args = [1, 'two', [3]]
wrapper.wrap((args..., cb) -> setImmediate ->
wrapper.globals.hello = 'world'
cb expected_err
) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
assert.deepEqual @sentry.error.firstCall.args[3].hello, 'world'
done()
it 'only calls the cb with no error once sentry-node emits a "logged" event', (done) ->
wrapper = @sentry.wrapper 'logger'
cb = sinon.spy()
wrapper.wrap((cb) -> cb new Error 'oops') cb
assert not cb.called, 'Expected cb to not be called before event'
@sentry.once 'logged', ->
assert cb.calledOnce, 'Expected cb to be called after logged event'
done()
@sentry.emit 'logged'
it 'calls the cb with an error if sentry-node emits an "error" event', (done) ->
wrapper = @sentry.wrapper 'logger'
cb = sinon.spy()
original_error = new Error 'oops'
sentry_error = new Error 'sentry failed'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before event'
@sentry.once 'error', ->
assert cb.calledOnce, 'Expected cb to be called after error event'
assert.deepEqual cb.firstCall.args, [_.extend sentry_error, {original_error}]
done()
@sentry.emit 'error', sentry_error
describe 'wrapper with timeout set', ->
beforeEach ->
sinon.stub @sentry, 'error'
TIMEOUT = 10
it 'calls the cb with an error if sentry-node doesnt emit any event', (done) ->
wrapper = @sentry.wrapper 'logger', TIMEOUT
cb = sinon.spy()
original_error = new Error 'oops'
timeout_error = new Error 'Sentry timed out'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before timeout'
setTimeout ->
assert cb.calledOnce, 'Expected cb to be called after timeout'
assert.deepEqual cb.firstCall.args, [_.extend timeout_error, {original_error}]
done()
, TIMEOUT + 1
it 'calls the cb with an error if sentry-node doesnt emit an event quickly enough', (done) ->
wrapper = @sentry.wrapper 'logger', TIMEOUT
cb = sinon.spy()
original_error = new Error 'oops'
timeout_error = new Error 'Sentry timed out'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before timeout'
setTimeout (=> @sentry.emit 'logged'), TIMEOUT + 1
setTimeout ->
assert cb.calledOnce, 'Expected cb to be called exactly once after timeout'
assert.deepEqual cb.firstCall.args, [_.extend timeout_error, {original_error}]
done()
, TIMEOUT + 2
describe 'wrapper with sentry enabled using promises', ->
beforeEach ->
sinon.spy @sentry, 'error'
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
it 'sends to Sentry if the given function produces an error', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error 'oops'
expected_args = [1, 'two', [3]]
wrapper.wrap((args...) -> new Promise (resolve, reject) -> setImmediate -> reject(expected_err)) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
done()
return
it 'doesnt send to Sentry if the given function produces no error', (done) ->
wrapper = @sentry.wrapper 'logger'
wrapper.wrap(-> new Promise (resolve, reject) -> setImmediate -> resolve(null)) (err) =>
assert.deepEqual err, null
assert not @sentry.error.called, 'Expected sentry.error to not be called'
done()
return
get_mock_data = ->
err = new Error 'Testing sentry'
message: err.message # smaller text that appears right under culprit (and shows up in HipChat)
logger: '/path/to/logger'
server_name: 'apple'
platform: 'node'
level: 'error'
extra: err.stack
culprit: 'Too many tests... jk'
| true | _ = require 'underscore'
assert = require 'assert'
os = require 'os'
nock = require 'nock'
sinon = require 'sinon'
Promise = require 'bluebird'
Sentry = require("#{__dirname}/../lib/sentry")
{_handle_http_load_errors} = require("#{__dirname}/../lib/sentry")._private
sentry_settings = require("#{__dirname}/credentials").sentry
describe 'Sentry', ->
beforeEach ->
@sentry = new Sentry sentry_settings
describe 'constructor', ->
it 'should create an instance of Sentry', ->
assert.equal @sentry.constructor.name, 'Sentry'
it 'setup sentry client from specified DSN correctly', ->
key = 'PI:KEY:<KEY>END_PI'
secret = 'PI:KEY:<KEY>END_PI'
project_id = '12345'
# mock sentry dsn with random uuid as public_key and secret_key
dsn = "https://#{key}:#{secret}@app.getsentry.com/#{project_id}"
_sentry = new Sentry dsn
assert.equal _sentry.key, key
assert.equal _sentry.secret, secret
assert.equal _sentry.project_id, project_id
assert.equal _sentry.hostname, os.hostname()
assert.equal _sentry.enabled, true
it 'setup sentry client from object correctly', ->
assert.equal @sentry.key, sentry_settings.key
assert.equal @sentry.secret, sentry_settings.secret
assert.equal @sentry.project_id, sentry_settings.project_id
assert.equal @sentry.hostname, os.hostname()
assert.equal @sentry.enabled, true
it 'refuses to enable the sentry with incomplete credentials', ->
_sentry = new Sentry _.omit sentry_settings, 'secret'
assert.equal _sentry.hostname, os.hostname()
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
it 'empty or missing DSN should disable the client', ->
_sentry = new Sentry ""
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
_sentry = new Sentry()
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Sentry client expected String or Object as argument. You passed: undefined."
it 'invalid DSN should disable the client', ->
_sentry = new Sentry "https://app.getsentry.com/12345"
assert.equal _sentry.enabled, false
assert.equal _sentry.disable_message, "Credentials you passed in aren't complete."
describe '#error', ->
beforeEach ->
sinon.stub @sentry, '_send'
it 'emits warning if passed an error that isnt an instance of Error', (done) ->
@sentry.on 'warning', (err) ->
assert err instanceof Error
assert err.message.match /^WARNING: err not passed as Error!/
done()
@sentry.error 'not an Error', 'path/to/logger', 'culprit'
it 'uses _send to send error', ->
[err_message, logger, culprit] = ['Error message', '/path/to/logger', 'culprit']
@sentry.error new Error(err_message), logger, culprit
assert @sentry._send.calledOnce
send_data = @sentry._send.getCall(0).args[0]
assert.equal err_message, send_data.message, "Unexpected message. Expected '#{err_message}', Received '#{send_data.message}'"
assert.equal logger, send_data.logger, "Unexpected logger. Expected '#{logger}', Received '#{send_data.logger}'"
assert !_.isUndefined send_data.server_name, "Expected a value to be set for server_name, undefined given"
assert.equal culprit, send_data.culprit, "Unexpected culprit. Expected '#{culprit}', Received '#{send_data.culprit}'"
assert.equal 'node', send_data.platform, "Unexpected platform. Expected 'node', Received '#{send_data.platform}'"
assert.equal 'error', send_data.level, "Unexpected level. Expected 'error', Received '#{send_data.level}'"
it 'will send error correctly when culprit is null', ->
@sentry.error new Error('Error message'), '/path/to/logger', null
send_data = @sentry._send.getCall(0).args[0]
assert _.isUndefined(send_data.culprit)
describe '#message', ->
beforeEach ->
sinon.stub @sentry, '_send'
it 'send message correctly via _send', ->
@sentry.message 'message', '/path/to/logger'
assert @sentry._send.calledOnce
send_data = @sentry._send.getCall(0).args[0]
assert.equal 'message', send_data.message, "Unexpected message. Expected 'message', Received '#{send_data.message}'"
assert.equal '/path/to/logger', send_data.logger, "Unexpected logger. Expected '/path/to/logger', Received '#{send_data.logger}'"
assert.equal 'info', send_data.level, "Unexpected level. Expected 'info', Received '#{send_data.level}'"
describe '#_send', ->
beforeEach ->
# Mute errors, they should be tested for and expected
sinon.stub console , 'error'
afterEach ->
console.error.restore()
it 'emit error event when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', (err) ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'calls callback when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', ->
@sentry.message "hey!", "/", {}, (err) ->
assert.equal err.message, "status code: 500"
scope.done()
done()
it 'emits done event when the api call returned an error', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(500, 'Oops!', {'x-sentry-error': 'Oops!'})
@sentry.once 'error', ->
@sentry.once 'done', ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'calls callback when successfully made an api call', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.message "hey!", "/", {}, (err) ->
assert.ifError err
scope.done()
done()
it 'emits done event successfully made an api call', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.once 'done', ->
scope.done()
done()
@sentry.message "hey!", "/"
it 'emits logged event when successfully made an api call', (done) ->
@scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
@sentry.on 'logged', ->
done()
@sentry._send get_mock_data()
it 'emits a warning if you pass a non string logger', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
logger = key: '/path/to/logger'
@sentry.once 'warning', (err) ->
assert.equal err.message, "WARNING: logger not passed as string! #{JSON.stringify(logger)}"
done()
data = get_mock_data()
data.logger = logger
@sentry._send data
it 'emits a logged event once logged', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
logger = key: PI:KEY:<KEY>END_PI'
@sentry.once 'logged', ->
scope.done()
done()
data = get_mock_data()
data.logger = logger
@sentry._send data
it 'emits a warning if there are circular references in "extra", before sending', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
extra = {foo: 'bar'}
extra = _.extend extra, {circular: extra}
@sentry.once 'warning', (err) ->
assert.equal err.message, "WARNING: extra not parseable to JSON!"
assert !_.isEmpty(scope.pendingMocks())
done()
@sentry.error new Error('Error message'), '/path/to/logger', 'culprit', extra
it 'emits logged even if there are circular referances in "extra"', (done) ->
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
extra = {foo: 'bar'}
extra = _.extend extra, {circular: extra}
@sentry.once 'logged', ->
scope.done()
done()
@sentry.error new Error('Error message'), '/path/to/logger', 'culprit', extra
describe 'private function _handle_http_load_errors', ->
it 'exists as a function', ->
assert _.isFunction _handle_http_load_errors, 'Expected Sentry to have fn _handle_http_load_errors'
it 'should emit a warning when invoked with error', (done) ->
my_error = new Error 'Testing error'
@sentry.once 'warning', (err) ->
assert.equal err, my_error
done()
_handle_http_load_errors @sentry, my_error
describe 'wrapper with sentry disabled', ->
beforeEach ->
sinon.spy @sentry, 'error'
@sentry.enabled = false
it 'calls the given fn normally if sentry is disabled', (done) ->
wrapper = @sentry.wrapper 'logger'
args = [1, 'two', [3]]
expected = [null, {'4'}, 5, 'six']
fn = sinon.stub().yields expected...
wrapper.wrap(fn) args..., (results...) =>
assert not @sentry.error.called, 'Expected sentry.error to not be called'
assert.deepEqual results, expected
assert fn.calledOnce, 'Expected fn to be called exactly once'
assert.deepEqual fn.firstCall.args[...-1], args # strip off callback
done()
describe 'wrapper with sentry enabled', ->
beforeEach ->
sinon.spy @sentry, 'error'
@scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
it 'calls the given fn with its args and passes through the results', (done) ->
wrapper = @sentry.wrapper 'logger'
args = [1, 'two', [3]]
expected = [null, {'4'}, 5, 'six']
fn = sinon.stub().yields expected...
wrapper.wrap(fn) args..., (results...) ->
assert.deepEqual results, expected
assert fn.calledOnce, 'Expected fn to be called exactly once'
assert.deepEqual fn.firstCall.args[...-1], args # strip off callback
done()
it 'sends to Sentry if the given function produces an error', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error 'oops'
expected_args = [1, 'two', [3]]
wrapper.wrap((args..., cb) -> setImmediate -> cb expected_err) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
done()
return
it 'doesnt send to Sentry if the given function produces no error', (done) ->
wrapper = @sentry.wrapper 'logger'
wrapper.wrap((cb) -> setImmediate -> cb null) (err) =>
assert.deepEqual err, null
assert not @sentry.error.called, 'Expected sentry.error to not be called'
done()
return
it 'sends to Sentry if the given function produces an error and globals has value', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error('oops')
expected_args = [1, 'two', [3]]
wrapper.wrap((args..., cb) -> setImmediate ->
wrapper.globals.hello = 'world'
cb expected_err
) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
assert.deepEqual @sentry.error.firstCall.args[3].hello, 'world'
done()
it 'only calls the cb with no error once sentry-node emits a "logged" event', (done) ->
wrapper = @sentry.wrapper 'logger'
cb = sinon.spy()
wrapper.wrap((cb) -> cb new Error 'oops') cb
assert not cb.called, 'Expected cb to not be called before event'
@sentry.once 'logged', ->
assert cb.calledOnce, 'Expected cb to be called after logged event'
done()
@sentry.emit 'logged'
it 'calls the cb with an error if sentry-node emits an "error" event', (done) ->
wrapper = @sentry.wrapper 'logger'
cb = sinon.spy()
original_error = new Error 'oops'
sentry_error = new Error 'sentry failed'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before event'
@sentry.once 'error', ->
assert cb.calledOnce, 'Expected cb to be called after error event'
assert.deepEqual cb.firstCall.args, [_.extend sentry_error, {original_error}]
done()
@sentry.emit 'error', sentry_error
describe 'wrapper with timeout set', ->
beforeEach ->
sinon.stub @sentry, 'error'
TIMEOUT = 10
it 'calls the cb with an error if sentry-node doesnt emit any event', (done) ->
wrapper = @sentry.wrapper 'logger', TIMEOUT
cb = sinon.spy()
original_error = new Error 'oops'
timeout_error = new Error 'Sentry timed out'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before timeout'
setTimeout ->
assert cb.calledOnce, 'Expected cb to be called after timeout'
assert.deepEqual cb.firstCall.args, [_.extend timeout_error, {original_error}]
done()
, TIMEOUT + 1
it 'calls the cb with an error if sentry-node doesnt emit an event quickly enough', (done) ->
wrapper = @sentry.wrapper 'logger', TIMEOUT
cb = sinon.spy()
original_error = new Error 'oops'
timeout_error = new Error 'Sentry timed out'
wrapper.wrap((cb) -> cb original_error) cb
assert not cb.called, 'Expected cb to not be called before timeout'
setTimeout (=> @sentry.emit 'logged'), TIMEOUT + 1
setTimeout ->
assert cb.calledOnce, 'Expected cb to be called exactly once after timeout'
assert.deepEqual cb.firstCall.args, [_.extend timeout_error, {original_error}]
done()
, TIMEOUT + 2
describe 'wrapper with sentry enabled using promises', ->
beforeEach ->
sinon.spy @sentry, 'error'
scope = nock('https://app.getsentry.com')
.filteringRequestBody(/.*/, '*')
.post("/api/#{sentry_settings.project_id}/store/", '*')
.reply(200, 'OK')
it 'sends to Sentry if the given function produces an error', (done) ->
wrapper = @sentry.wrapper 'logger'
expected_err = new Error 'oops'
expected_args = [1, 'two', [3]]
wrapper.wrap((args...) -> new Promise (resolve, reject) -> setImmediate -> reject(expected_err)) expected_args..., (err) =>
assert.deepEqual err, expected_err
assert @sentry.error.calledOnce, 'Expected sentry.error to be called exactly once'
assert.deepEqual @sentry.error.firstCall.args[0..2],
[expected_err, 'logger', null]
# The 'extra' param should have the args the function was called with
assert.deepEqual @sentry.error.firstCall.args[3].args, expected_args
done()
return
it 'doesnt send to Sentry if the given function produces no error', (done) ->
wrapper = @sentry.wrapper 'logger'
wrapper.wrap(-> new Promise (resolve, reject) -> setImmediate -> resolve(null)) (err) =>
assert.deepEqual err, null
assert not @sentry.error.called, 'Expected sentry.error to not be called'
done()
return
get_mock_data = ->
err = new Error 'Testing sentry'
message: err.message # smaller text that appears right under culprit (and shows up in HipChat)
logger: '/path/to/logger'
server_name: 'apple'
platform: 'node'
level: 'error'
extra: err.stack
culprit: 'Too many tests... jk'
|
[
{
"context": "s turtles.\"\n }\n {\n id: 3\n title: \"Sharks\"\n description: \"An advanced pet. Needs milli",
"end": 632,
"score": 0.653390645980835,
"start": 626,
"tag": "NAME",
"value": "Sharks"
}
] | app/js/features/pets/pet_service.coffee | Light2288/Prova_IonicCordovaCoffeeJade | 0 | ###
A simple example service that returns some data.
###
angular.module("ionicstarter")
.factory "PetService", ->
# Might use a resource here that returns a JSON array
# Some fake testing data
pets = [
{
id: 0
title: "Cats"
description: "Furry little creatures. Obsessed with plotting assassination, but never following through on it."
}
{
id: 1
title: "Dogs"
description: "Lovable. Loyal almost to a fault. Smarter than they let on."
}
{
id: 2
title: "Turtles"
description: "Everyone likes turtles."
}
{
id: 3
title: "Sharks"
description: "An advanced pet. Needs millions of gallons of salt water. Will happily eat you."
}
]
all: ->
pets
get: (petId) ->
# Simple index lookup
pets[petId]
| 19424 | ###
A simple example service that returns some data.
###
angular.module("ionicstarter")
.factory "PetService", ->
# Might use a resource here that returns a JSON array
# Some fake testing data
pets = [
{
id: 0
title: "Cats"
description: "Furry little creatures. Obsessed with plotting assassination, but never following through on it."
}
{
id: 1
title: "Dogs"
description: "Lovable. Loyal almost to a fault. Smarter than they let on."
}
{
id: 2
title: "Turtles"
description: "Everyone likes turtles."
}
{
id: 3
title: "<NAME>"
description: "An advanced pet. Needs millions of gallons of salt water. Will happily eat you."
}
]
all: ->
pets
get: (petId) ->
# Simple index lookup
pets[petId]
| true | ###
A simple example service that returns some data.
###
angular.module("ionicstarter")
.factory "PetService", ->
# Might use a resource here that returns a JSON array
# Some fake testing data
pets = [
{
id: 0
title: "Cats"
description: "Furry little creatures. Obsessed with plotting assassination, but never following through on it."
}
{
id: 1
title: "Dogs"
description: "Lovable. Loyal almost to a fault. Smarter than they let on."
}
{
id: 2
title: "Turtles"
description: "Everyone likes turtles."
}
{
id: 3
title: "PI:NAME:<NAME>END_PI"
description: "An advanced pet. Needs millions of gallons of salt water. Will happily eat you."
}
]
all: ->
pets
get: (petId) ->
# Simple index lookup
pets[petId]
|
[
{
"context": "/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Jonah\"]\r\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book",
"end": 14911,
"score": 0.8500025868415833,
"start": 14909,
"tag": "NAME",
"value": "ah"
},
{
"context": "[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\r... | src/es/regexps.coffee | phillipb/Bible-Passage-Reference-Parser | 149 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| (?:subt[íi]tulo|t[íi]tulo|tít) (?! [a-z] ) #could be followed by a number
| y#{bcv_parser::regexps.space}+siguientes | y(?!#{bcv_parser::regexps.space}+sig) | y#{bcv_parser::regexps.space}+sig | vers[íi]culos | cap[íi]tulos | vers[íi]culo | cap[íi]tulo | caps | vers | cap | ver | vss | vs | vv | á | v
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* (?:subt[íi]tulo|t[íi]tulo|tít)
| \d \W* (?:y#{bcv_parser::regexps.space}+siguientes|y#{bcv_parser::regexps.space}+sig) (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:1\.?[ºo]|1|I|Primero?)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:2\.?[ºo]|2|II|Segundo)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:3\.?[ºo]|3|III|Tercero?)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|y(?!#{bcv_parser::regexps.space}+sig)|á)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|á)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:[e\xE9](?:n(?:esis)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[E\xC9]x(?:o(?:do?)?|d)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*y[\s\xa0]*el[\s\xa0]*(?:Drag[o\xF3]n|Serpiente))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:ev(?:[i\xED]tico)?|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:[u\xFA](?:m(?:eros)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Si(?:r(?:[a\xE1]cides|[a\xE1]cida)|r(?:[a\xE1]c)?)?|Ec(?:lesi[a\xE1]stico|clus))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ab(?:idur[i\xED]a)?|b)|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:a(?:m(?:[ei]ntaciones?)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Carta[\s\xa0]*Jerem[i\xED]as|(?:Carta[\s\xa0]*|Ep)Jer|Carta[\s\xa0]*de[\s\xa0]*Jerem[i\xED]as|La[\s\xa0]*Carta[\s\xa0]*de[\s\xa0]*Jerem[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Apocalipsis)|(?:El[\s\xa0]*Apocalipsis|Apoc|Rev|Ap)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Manas[e\xE9]s|(?:Or\.?[\s\xa0]*|Pr)Man|La[\s\xa0]*Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Manas[e\xE9]s)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:eu(?:t(?:[eo]rono?mio|rono?mio)?)?|ueteronomio|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:u[e\xE9]|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:u(?:e(?:c(?:es)?)?|dg)|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:u(?:th?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Esdras)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Esdras|1(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Esdras|Primero?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Esdras)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Esdras|2(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Esdras|Segundo[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:a(?:[i\xED]as)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*S(?:amuel|m))|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Samuel|2(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Samuel|Segundo[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*S(?:amuel|m))|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Samuel|1(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Samuel|Primero?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*R(?:(?:e(?:ye?|e)?|ye?)?s|e(?:ye?|e)?|ye?)?|Kgs)|(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Reyes|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Reyes|Segundo[\s\xa0]*Reyes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*R(?:(?:e(?:ye?|e)?|ye?)?s|e(?:ye?|e)?|ye?)?|Kgs)|(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Reyes|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Reyes|Primero?[\s\xa0]*Reyes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Cr[o\xF3]nicas)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Cr[o\xF3]nicas|2(?:[\s\xa0]*Cr[o\xF3]n|Chr|[\s\xa0]*Cr[o\xF3]?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Cr[o\xF3]nicas|Segundo[\s\xa0]*Cr[o\xF3]nicas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Cr[o\xF3]nicas)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Cr[o\xF3]nicas|1(?:[\s\xa0]*Cr[o\xF3]n|Chr|[\s\xa0]*Cr[o\xF3]?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Cr[o\xF3]nicas|Primer(?:o[\s\xa0]*Cr[o\xF3]|[\s\xa0]*Cr[o\xF3])nicas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sd(?:r(?:as)?)?|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ne(?:h(?:em[i\xED]as)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er[\s\xa0]*(?:\([Gg]riego\)|[Gg]riego)|[\s\xa0]*Gr)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Es(?:t(?:er|h)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:al(?:m(?:os?)?)?|lm?)|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Or[\s\xa0]*|Pr)Azar|Or[\s\xa0]*Az|Azar[i\xED]as|Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Azar[i\xED]as|C[a\xE1]ntico[\s\xa0]*de[\s\xa0]*Azar[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Prvbos)|(?:Prover?bios)|(?:P(?:r(?:v(?:erbios|b[os])|everbios|verbio|vb?|everbio|o(?:bv?erbios|verbio|v)?)?|or?verbios|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ec(?:c(?:l(?:es(?:i(?:a(?:st(?:i(?:c[e\xE9]|[e\xE9])s|[e\xE9]s|[e\xE9])|t(?:[e\xE9]s|[e\xE9]))|i(?:s?t[e\xE9]s|s?t[e\xE9]))|(?:s[ai][ai]|a[ai])s?t[e\xE9]s|(?:s[ai][ai]|a[ai])s?t[e\xE9])?)?)?|l(?:es(?:i(?:a(?:st(?:i(?:c[e\xE9]|[e\xE9])s|[e\xE9]s|[e\xE9])|t(?:[e\xE9]s|[e\xE9]))|i(?:s?t[e\xE9]s|s?t[e\xE9]))|(?:s[ai][ai]|a[ai])s?t[e\xE9]s|(?:s[ai][ai]|a[ai])s?t[e\xE9])?)?)?|Qo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:El[\s\xa0]*(?:Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre))|Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)))os|Ct[\s\xa0]*3[\s\xa0]*J[o\xF3]|SgThree)|(?:Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*Jud[i\xED]os)|(?:(?:Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre))o|Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)o|Tres[\s\xa0]*J[o\xF3]vene))s)|(?:(?:(?:Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*)?3[\s\xa0]*J[o\xF3]|Tres[\s\xa0]*J[o\xF3]|Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]|3[\s\xa0]*J[o\xF3]))venes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Cantare?[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Cantares)|(?:Cantares)|(?:El[\s\xa0]*Cantar[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Cantares|C(?:an|n)?t|Song|Can)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:er(?:e(?:m[i\xED]as?)?)?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:qu(?:i[ae]|e)l|qu?|k|[ei]qui?el)?|i[ei]qui?el|iqui?el|q)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:a(?:n(?:iel)?)?|[ln]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Os(?:eas)?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:oel?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:[o\xF3]s?|s)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:d(?:[i\xED]as)?)?|Obad)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:on(?:a[hs]|\xE1s)?|ns))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:i(?:q(?:ueas)?|c)?|q))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:a(?:h(?:[u\xFA]m?)?)?|h))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:ac[au]c|c|bac[au]c)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:o(?:f(?:on[i\xED]as)?)?|f)|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:H(?:ag(?:geo|eo)?|g)|Ag(?:eo)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:c(?:ar(?:[i\xED]as)?)?)?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:al(?:a(?:qu(?:[i\xED]as)?)?)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mateo)|(?:E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Mateo|M(?:at|a)?t|San[\s\xa0]*Mateo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Mc)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|2(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Segundo[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Mc)|(?:(?:3(?:\.[o\xBA]?|[o\xBA])|III)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|3(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:3(?:\.[o\xBA]|[o\xBA])|III)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Tercer(?:o[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Mc)|(?:(?:4(?:\.[o\xBA]?|[o\xBA])|IV)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|4(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:4(?:\.[o\xBA]|[o\xBA])|IV)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Cuarto[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Mc)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|1(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Primer(?:o[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar(?:cos|k)|rcos))|(?:M(?:(?:ar|r)?c|a?r)|San[\s\xa0]*Marcos|E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Marcos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Lucas)|(?:L(?:u(?:ke|c)|c|u)|San[\s\xa0]*Lucas|E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Lucas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|1(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Primer(?:o[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|2(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Segundo[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au]))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:3(?:\.[o\xBA]?|[o\xBA])|III)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|3(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:3(?:\.[o\xBA]|[o\xBA])|III)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Tercer(?:o[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:El[\s\xa0]*Evangelio[\s\xa0]*de[\s\xa0]*J[au][au]|San[\s\xa0]*Jua|Joh|J|J[au][au])n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hch)|(?:Hechos(?:[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Ap[o\xF3]stoles)?|H(?:ech?|c)|Acts|Los[\s\xa0]*Hechos(?:[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Ap[o\xF3]stoles)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:o(?:m(?:anos?|s)?|s)?|m(?:ns?|s)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Corin(?:tios|i))|(?:2[\s\xa0]*Corinti)|(?:2[\s\xa0]*Corint)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Corintios|2(?:[\s\xa0]*Corin|Cor|[\s\xa0]*Cor?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Corintios|Segundo[\s\xa0]*Corintios)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Corin(?:tios|i))|(?:1[\s\xa0]*Corinti)|(?:1[\s\xa0]*Corint)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Corintios|1(?:[\s\xa0]*Corin|Cor|[\s\xa0]*Cor?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Corintios|Primero?[\s\xa0]*Corintios)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G[a\xE1](?:l(?:at(?:as)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:f(?:es(?:ios)?)?|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:il(?:i(?:p(?:enses)?)?)?|lp)|Phil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Col(?:os(?:enses)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Tesaloni[cs]enses?)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Tesaloni[cs]enses?|2(?:[\s\xa0]*T(?:hes|e)?|Thes)s|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Tesaloni[cs]enses?|Segundo[\s\xa0]*Tesaloni[cs]enses?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Tesaloni[cs]enses?)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Tesaloni[cs]enses?|1(?:[\s\xa0]*T(?:hes|e)?|Thes)s|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Tesaloni[cs]enses?|Primer(?:o[\s\xa0]*Tesaloni[cs]enses?|[\s\xa0]*Tesaloni[cs]enses?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Timoteo)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Timoteo|2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Timoteo|Segundo[\s\xa0]*Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Timoteo)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Timoteo|1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Timoteo|Primero?[\s\xa0]*Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:i(?:t(?:us|o)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:ilem(?:[o\xF3]n)?|lmn?|mn)|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hebr(?:[or][eor]|[or]|e[er])s)|(?:He(?:b(?:[eo](?:[eor][eor]?)?s|r(?:eo?)?s|r(?:eo)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ant(?:iago)?|tg?)|Jas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*P(?:edro|d)|Pet))|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*(?:San[\s\xa0]*)?Pedro|2[\s\xa0]*(?:P(?:ed|e)?|San[\s\xa0]*Pedro)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*(?:San[\s\xa0]*)?Pedro|Segundo[\s\xa0]*(?:San[\s\xa0]*)?Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*P(?:edro|d)|Pet))|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*(?:San[\s\xa0]*)?Pedro|1[\s\xa0]*(?:P(?:ed|e)?|San[\s\xa0]*Pedro)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*(?:San[\s\xa0]*)?Pedro|Primer(?:o[\s\xa0]*(?:San[\s\xa0]*)?|[\s\xa0]*(?:San[\s\xa0]*)?)Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ud(?:as|e)|das))|(?:San[\s\xa0]*Judas|Ju?d)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:it?|t)?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udi?|di?)t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ba(?:r(?:uc)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sus(?:ana)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab", "Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ha)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb", "Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah", "Job", "Josh", "Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude", "Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt", "Mark", "Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ma)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil", "Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Fil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| 115921 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| (?:subt[íi]tulo|t[íi]tulo|tít) (?! [a-z] ) #could be followed by a number
| y#{bcv_parser::regexps.space}+siguientes | y(?!#{bcv_parser::regexps.space}+sig) | y#{bcv_parser::regexps.space}+sig | vers[íi]culos | cap[íi]tulos | vers[íi]culo | cap[íi]tulo | caps | vers | cap | ver | vss | vs | vv | á | v
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* (?:subt[íi]tulo|t[íi]tulo|tít)
| \d \W* (?:y#{bcv_parser::regexps.space}+siguientes|y#{bcv_parser::regexps.space}+sig) (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:1\.?[ºo]|1|I|Primero?)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:2\.?[ºo]|2|II|Segundo)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:3\.?[ºo]|3|III|Tercero?)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|y(?!#{bcv_parser::regexps.space}+sig)|á)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|á)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:[e\xE9](?:n(?:esis)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[E\xC9]x(?:o(?:do?)?|d)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*y[\s\xa0]*el[\s\xa0]*(?:Drag[o\xF3]n|Serpiente))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:ev(?:[i\xED]tico)?|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:[u\xFA](?:m(?:eros)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Si(?:r(?:[a\xE1]cides|[a\xE1]cida)|r(?:[a\xE1]c)?)?|Ec(?:lesi[a\xE1]stico|clus))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ab(?:idur[i\xED]a)?|b)|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:a(?:m(?:[ei]ntaciones?)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Carta[\s\xa0]*Jerem[i\xED]as|(?:Carta[\s\xa0]*|Ep)Jer|Carta[\s\xa0]*de[\s\xa0]*Jerem[i\xED]as|La[\s\xa0]*Carta[\s\xa0]*de[\s\xa0]*Jerem[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Apocalipsis)|(?:El[\s\xa0]*Apocalipsis|Apoc|Rev|Ap)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Manas[e\xE9]s|(?:Or\.?[\s\xa0]*|Pr)Man|La[\s\xa0]*Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Manas[e\xE9]s)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:eu(?:t(?:[eo]rono?mio|rono?mio)?)?|ueteronomio|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:u[e\xE9]|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:u(?:e(?:c(?:es)?)?|dg)|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:u(?:th?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Esdras)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Esdras|1(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Esdras|Primero?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Esdras)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Esdras|2(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Esdras|Segundo[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:a(?:[i\xED]as)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*S(?:amuel|m))|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Samuel|2(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Samuel|Segundo[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*S(?:amuel|m))|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Samuel|1(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Samuel|Primero?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*R(?:(?:e(?:ye?|e)?|ye?)?s|e(?:ye?|e)?|ye?)?|Kgs)|(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Reyes|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Reyes|Segundo[\s\xa0]*Reyes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*R(?:(?:e(?:ye?|e)?|ye?)?s|e(?:ye?|e)?|ye?)?|Kgs)|(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Reyes|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Reyes|Primero?[\s\xa0]*Reyes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Cr[o\xF3]nicas)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Cr[o\xF3]nicas|2(?:[\s\xa0]*Cr[o\xF3]n|Chr|[\s\xa0]*Cr[o\xF3]?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Cr[o\xF3]nicas|Segundo[\s\xa0]*Cr[o\xF3]nicas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Cr[o\xF3]nicas)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Cr[o\xF3]nicas|1(?:[\s\xa0]*Cr[o\xF3]n|Chr|[\s\xa0]*Cr[o\xF3]?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Cr[o\xF3]nicas|Primer(?:o[\s\xa0]*Cr[o\xF3]|[\s\xa0]*Cr[o\xF3])nicas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sd(?:r(?:as)?)?|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ne(?:h(?:em[i\xED]as)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er[\s\xa0]*(?:\([Gg]riego\)|[Gg]riego)|[\s\xa0]*Gr)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Es(?:t(?:er|h)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:al(?:m(?:os?)?)?|lm?)|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Or[\s\xa0]*|Pr)Azar|Or[\s\xa0]*Az|Azar[i\xED]as|Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Azar[i\xED]as|C[a\xE1]ntico[\s\xa0]*de[\s\xa0]*Azar[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Prvbos)|(?:Prover?bios)|(?:P(?:r(?:v(?:erbios|b[os])|everbios|verbio|vb?|everbio|o(?:bv?erbios|verbio|v)?)?|or?verbios|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ec(?:c(?:l(?:es(?:i(?:a(?:st(?:i(?:c[e\xE9]|[e\xE9])s|[e\xE9]s|[e\xE9])|t(?:[e\xE9]s|[e\xE9]))|i(?:s?t[e\xE9]s|s?t[e\xE9]))|(?:s[ai][ai]|a[ai])s?t[e\xE9]s|(?:s[ai][ai]|a[ai])s?t[e\xE9])?)?)?|l(?:es(?:i(?:a(?:st(?:i(?:c[e\xE9]|[e\xE9])s|[e\xE9]s|[e\xE9])|t(?:[e\xE9]s|[e\xE9]))|i(?:s?t[e\xE9]s|s?t[e\xE9]))|(?:s[ai][ai]|a[ai])s?t[e\xE9]s|(?:s[ai][ai]|a[ai])s?t[e\xE9])?)?)?|Qo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:El[\s\xa0]*(?:Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre))|Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)))os|Ct[\s\xa0]*3[\s\xa0]*J[o\xF3]|SgThree)|(?:Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*Jud[i\xED]os)|(?:(?:Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre))o|Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)o|Tres[\s\xa0]*J[o\xF3]vene))s)|(?:(?:(?:Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*)?3[\s\xa0]*J[o\xF3]|Tres[\s\xa0]*J[o\xF3]|Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]|3[\s\xa0]*J[o\xF3]))venes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Cantare?[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Cantares)|(?:Cantares)|(?:El[\s\xa0]*Cantar[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Cantares|C(?:an|n)?t|Song|Can)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:er(?:e(?:m[i\xED]as?)?)?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:qu(?:i[ae]|e)l|qu?|k|[ei]qui?el)?|i[ei]qui?el|iqui?el|q)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:a(?:n(?:iel)?)?|[ln]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Os(?:eas)?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:oel?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:[o\xF3]s?|s)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:d(?:[i\xED]as)?)?|Obad)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jon<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:on(?:a[hs]|\xE1s)?|ns))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:i(?:q(?:ueas)?|c)?|q))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:a(?:h(?:[u\xFA]m?)?)?|h))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:ac[au]c|c|bac[au]c)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:o(?:f(?:on[i\xED]as)?)?|f)|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:H(?:ag(?:geo|eo)?|g)|Ag(?:eo)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:c(?:ar(?:[i\xED]as)?)?)?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:al(?:a(?:qu(?:[i\xED]as)?)?)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mateo)|(?:E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Mateo|M(?:at|a)?t|San[\s\xa0]*Mateo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Mc)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|2(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Segundo[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Mc)|(?:(?:3(?:\.[o\xBA]?|[o\xBA])|III)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|3(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:3(?:\.[o\xBA]|[o\xBA])|III)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Tercer(?:o[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Mc)|(?:(?:4(?:\.[o\xBA]?|[o\xBA])|IV)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|4(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:4(?:\.[o\xBA]|[o\xBA])|IV)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Cuarto[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Mc)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|1(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Primer(?:o[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar(?:cos|k)|rcos))|(?:M(?:(?:ar|r)?c|a?r)|San[\s\xa0]*Marcos|E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Marcos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Lucas)|(?:L(?:u(?:ke|c)|c|u)|San[\s\xa0]*Lucas|E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Lucas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|1(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Primer(?:o[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|2(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Segundo[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au]))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:3(?:\.[o\xBA]?|[o\xBA])|III)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|3(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:3(?:\.[o\xBA]|[o\xBA])|III)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Tercer(?:o[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:El[\s\xa0]*Evangelio[\s\xa0]*de[\s\xa0]*J[au][au]|San[\s\xa0]*Jua|Joh|J|J[au][au])n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hch)|(?:Hechos(?:[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Ap[o\xF3]stoles)?|H(?:ech?|c)|Acts|Los[\s\xa0]*Hechos(?:[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Ap[o\xF3]stoles)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:o(?:m(?:anos?|s)?|s)?|m(?:ns?|s)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Corin(?:tios|i))|(?:2[\s\xa0]*Corinti)|(?:2[\s\xa0]*Corint)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Corintios|2(?:[\s\xa0]*Corin|Cor|[\s\xa0]*Cor?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Corintios|Segundo[\s\xa0]*Corintios)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Corin(?:tios|i))|(?:1[\s\xa0]*Corinti)|(?:1[\s\xa0]*Corint)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Corintios|1(?:[\s\xa0]*Corin|Cor|[\s\xa0]*Cor?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Corintios|Primero?[\s\xa0]*Corintios)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G[a\xE1](?:l(?:at(?:as)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:f(?:es(?:ios)?)?|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:il(?:i(?:p(?:enses)?)?)?|lp)|Phil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Col(?:os(?:enses)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Tesaloni[cs]enses?)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Tesaloni[cs]enses?|2(?:[\s\xa0]*T(?:hes|e)?|Thes)s|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Tesaloni[cs]enses?|Segundo[\s\xa0]*Tesaloni[cs]enses?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Tesaloni[cs]enses?)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Tesaloni[cs]enses?|1(?:[\s\xa0]*T(?:hes|e)?|Thes)s|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Tesaloni[cs]enses?|Primer(?:o[\s\xa0]*Tesaloni[cs]enses?|[\s\xa0]*Tesaloni[cs]enses?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Timoteo)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Timoteo|2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Timoteo|Segundo[\s\xa0]*Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Timoteo)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Timoteo|1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Timoteo|Primero?[\s\xa0]*Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:i(?:t(?:us|o)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:ilem(?:[o\xF3]n)?|lmn?|mn)|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hebr(?:[or][eor]|[or]|e[er])s)|(?:He(?:b(?:[eo](?:[eor][eor]?)?s|r(?:eo?)?s|r(?:eo)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ant(?:iago)?|tg?)|Jas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*P(?:edro|d)|Pet))|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*(?:San[\s\xa0]*)?Pedro|2[\s\xa0]*(?:P(?:ed|e)?|San[\s\xa0]*Pedro)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*(?:San[\s\xa0]*)?Pedro|Segundo[\s\xa0]*(?:San[\s\xa0]*)?Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*P(?:edro|d)|Pet))|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*(?:San[\s\xa0]*)?Pedro|1[\s\xa0]*(?:P(?:ed|e)?|San[\s\xa0]*Pedro)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*(?:San[\s\xa0]*)?Pedro|Primer(?:o[\s\xa0]*(?:San[\s\xa0]*)?|[\s\xa0]*(?:San[\s\xa0]*)?)Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ud(?:as|e)|das))|(?:San[\s\xa0]*Judas|Ju?d)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:it?|t)?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udi?|di?)t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ba(?:r(?:uc)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sus(?:ana)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab", "Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ha)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb", "Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>", "<NAME>", "<NAME>", "<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>", "<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>", "<NAME>", "<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ma)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil", "Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Fil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| true | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| (?:subt[íi]tulo|t[íi]tulo|tít) (?! [a-z] ) #could be followed by a number
| y#{bcv_parser::regexps.space}+siguientes | y(?!#{bcv_parser::regexps.space}+sig) | y#{bcv_parser::regexps.space}+sig | vers[íi]culos | cap[íi]tulos | vers[íi]culo | cap[íi]tulo | caps | vers | cap | ver | vss | vs | vv | á | v
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* (?:subt[íi]tulo|t[íi]tulo|tít)
| \d \W* (?:y#{bcv_parser::regexps.space}+siguientes|y#{bcv_parser::regexps.space}+sig) (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:1\.?[ºo]|1|I|Primero?)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:2\.?[ºo]|2|II|Segundo)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:3\.?[ºo]|3|III|Tercero?)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|y(?!#{bcv_parser::regexps.space}+sig)|á)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|á)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:[e\xE9](?:n(?:esis)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[E\xC9]x(?:o(?:do?)?|d)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*y[\s\xa0]*el[\s\xa0]*(?:Drag[o\xF3]n|Serpiente))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:ev(?:[i\xED]tico)?|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:[u\xFA](?:m(?:eros)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Si(?:r(?:[a\xE1]cides|[a\xE1]cida)|r(?:[a\xE1]c)?)?|Ec(?:lesi[a\xE1]stico|clus))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ab(?:idur[i\xED]a)?|b)|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:a(?:m(?:[ei]ntaciones?)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Carta[\s\xa0]*Jerem[i\xED]as|(?:Carta[\s\xa0]*|Ep)Jer|Carta[\s\xa0]*de[\s\xa0]*Jerem[i\xED]as|La[\s\xa0]*Carta[\s\xa0]*de[\s\xa0]*Jerem[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Apocalipsis)|(?:El[\s\xa0]*Apocalipsis|Apoc|Rev|Ap)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Manas[e\xE9]s|(?:Or\.?[\s\xa0]*|Pr)Man|La[\s\xa0]*Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Manas[e\xE9]s)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:eu(?:t(?:[eo]rono?mio|rono?mio)?)?|ueteronomio|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:u[e\xE9]|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:u(?:e(?:c(?:es)?)?|dg)|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:u(?:th?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Esdras)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Esdras|1(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Esdras|Primero?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Esdras)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Esdras|2(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Esdras|Segundo[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:a(?:[i\xED]as)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*S(?:amuel|m))|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Samuel|2(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Samuel|Segundo[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*S(?:amuel|m))|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Samuel|1(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Samuel|Primero?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*R(?:(?:e(?:ye?|e)?|ye?)?s|e(?:ye?|e)?|ye?)?|Kgs)|(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Reyes|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Reyes|Segundo[\s\xa0]*Reyes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*R(?:(?:e(?:ye?|e)?|ye?)?s|e(?:ye?|e)?|ye?)?|Kgs)|(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Reyes|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Reyes|Primero?[\s\xa0]*Reyes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Cr[o\xF3]nicas)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Cr[o\xF3]nicas|2(?:[\s\xa0]*Cr[o\xF3]n|Chr|[\s\xa0]*Cr[o\xF3]?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Cr[o\xF3]nicas|Segundo[\s\xa0]*Cr[o\xF3]nicas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Cr[o\xF3]nicas)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Cr[o\xF3]nicas|1(?:[\s\xa0]*Cr[o\xF3]n|Chr|[\s\xa0]*Cr[o\xF3]?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Cr[o\xF3]nicas|Primer(?:o[\s\xa0]*Cr[o\xF3]|[\s\xa0]*Cr[o\xF3])nicas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sd(?:r(?:as)?)?|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ne(?:h(?:em[i\xED]as)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er[\s\xa0]*(?:\([Gg]riego\)|[Gg]riego)|[\s\xa0]*Gr)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Es(?:t(?:er|h)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:al(?:m(?:os?)?)?|lm?)|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Or[\s\xa0]*|Pr)Azar|Or[\s\xa0]*Az|Azar[i\xED]as|Oraci[o\xF3]n[\s\xa0]*de[\s\xa0]*Azar[i\xED]as|C[a\xE1]ntico[\s\xa0]*de[\s\xa0]*Azar[i\xED]as)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Prvbos)|(?:Prover?bios)|(?:P(?:r(?:v(?:erbios|b[os])|everbios|verbio|vb?|everbio|o(?:bv?erbios|verbio|v)?)?|or?verbios|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ec(?:c(?:l(?:es(?:i(?:a(?:st(?:i(?:c[e\xE9]|[e\xE9])s|[e\xE9]s|[e\xE9])|t(?:[e\xE9]s|[e\xE9]))|i(?:s?t[e\xE9]s|s?t[e\xE9]))|(?:s[ai][ai]|a[ai])s?t[e\xE9]s|(?:s[ai][ai]|a[ai])s?t[e\xE9])?)?)?|l(?:es(?:i(?:a(?:st(?:i(?:c[e\xE9]|[e\xE9])s|[e\xE9]s|[e\xE9])|t(?:[e\xE9]s|[e\xE9]))|i(?:s?t[e\xE9]s|s?t[e\xE9]))|(?:s[ai][ai]|a[ai])s?t[e\xE9]s|(?:s[ai][ai]|a[ai])s?t[e\xE9])?)?)?|Qo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:El[\s\xa0]*(?:Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre))|Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)))os|Ct[\s\xa0]*3[\s\xa0]*J[o\xF3]|SgThree)|(?:Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*Jud[i\xED]os)|(?:(?:Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)|3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre))o|Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:3[\s\xa0]*J[o\xF3]venes[\s\xa0]*(?:Jud[i\xED]|Hebre)o|Tres[\s\xa0]*J[o\xF3]vene))s)|(?:(?:(?:Himno[\s\xa0]*de[\s\xa0]*los[\s\xa0]*)?3[\s\xa0]*J[o\xF3]|Tres[\s\xa0]*J[o\xF3]|Canto[\s\xa0]*de[\s\xa0]*los[\s\xa0]*(?:Tres[\s\xa0]*J[o\xF3]|3[\s\xa0]*J[o\xF3]))venes)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Cantare?[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Cantares)|(?:Cantares)|(?:El[\s\xa0]*Cantar[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Cantares|C(?:an|n)?t|Song|Can)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:er(?:e(?:m[i\xED]as?)?)?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:qu(?:i[ae]|e)l|qu?|k|[ei]qui?el)?|i[ei]qui?el|iqui?el|q)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:a(?:n(?:iel)?)?|[ln]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Os(?:eas)?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:oel?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:[o\xF3]s?|s)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:d(?:[i\xED]as)?)?|Obad)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["JonPI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:on(?:a[hs]|\xE1s)?|ns))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:i(?:q(?:ueas)?|c)?|q))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:a(?:h(?:[u\xFA]m?)?)?|h))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:ac[au]c|c|bac[au]c)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:o(?:f(?:on[i\xED]as)?)?|f)|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:H(?:ag(?:geo|eo)?|g)|Ag(?:eo)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:c(?:ar(?:[i\xED]as)?)?)?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:al(?:a(?:qu(?:[i\xED]as)?)?)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mateo)|(?:E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Mateo|M(?:at|a)?t|San[\s\xa0]*Mateo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Mc)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|2(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Segundo[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Mc)|(?:(?:3(?:\.[o\xBA]?|[o\xBA])|III)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|3(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:3(?:\.[o\xBA]|[o\xBA])|III)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Tercer(?:o[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Mc)|(?:(?:4(?:\.[o\xBA]?|[o\xBA])|IV)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|4(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:4(?:\.[o\xBA]|[o\xBA])|IV)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Cuarto[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Mc)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|1(?:[\s\xa0]*Macc?ab(?:be(?:eos?|os?)|e(?:eos?|os?))|[\s\xa0]*M(?:acc?)?|Macc)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|Primer(?:o[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))|[\s\xa0]*Mac(?:cab(?:be(?:eos?|os?)|e(?:eos?|os?))|ab(?:be(?:eos?|os?)|e(?:eos?|os?)))))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar(?:cos|k)|rcos))|(?:M(?:(?:ar|r)?c|a?r)|San[\s\xa0]*Marcos|E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Marcos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Lucas)|(?:L(?:u(?:ke|c)|c|u)|San[\s\xa0]*Lucas|E(?:l[\s\xa0]*E)?vangelio[\s\xa0]*de[\s\xa0]*Lucas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|1(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Primer(?:o[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|2(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Segundo[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au]))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:3(?:\.[o\xBA]?|[o\xBA])|III)[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|3(?:[\s\xa0]*J[au][au]|Joh|[\s\xa0]*J|[\s\xa0]*San[\s\xa0]*J[au][au])|(?:3(?:\.[o\xBA]|[o\xBA])|III)\.[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|Tercer(?:o[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])|[\s\xa0]*(?:San[\s\xa0]*J[au][au]|J[au][au])))n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:El[\s\xa0]*Evangelio[\s\xa0]*de[\s\xa0]*J[au][au]|San[\s\xa0]*Jua|Joh|J|J[au][au])n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hch)|(?:Hechos(?:[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Ap[o\xF3]stoles)?|H(?:ech?|c)|Acts|Los[\s\xa0]*Hechos(?:[\s\xa0]*de[\s\xa0]*los[\s\xa0]*Ap[o\xF3]stoles)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:o(?:m(?:anos?|s)?|s)?|m(?:ns?|s)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Corin(?:tios|i))|(?:2[\s\xa0]*Corinti)|(?:2[\s\xa0]*Corint)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Corintios|2(?:[\s\xa0]*Corin|Cor|[\s\xa0]*Cor?)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Corintios|Segundo[\s\xa0]*Corintios)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Corin(?:tios|i))|(?:1[\s\xa0]*Corinti)|(?:1[\s\xa0]*Corint)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Corintios|1(?:[\s\xa0]*Corin|Cor|[\s\xa0]*Cor?)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Corintios|Primero?[\s\xa0]*Corintios)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G[a\xE1](?:l(?:at(?:as)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:f(?:es(?:ios)?)?|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:il(?:i(?:p(?:enses)?)?)?|lp)|Phil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Col(?:os(?:enses)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Tesaloni[cs]enses?)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Tesaloni[cs]enses?|2(?:[\s\xa0]*T(?:hes|e)?|Thes)s|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Tesaloni[cs]enses?|Segundo[\s\xa0]*Tesaloni[cs]enses?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Tesaloni[cs]enses?)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Tesaloni[cs]enses?|1(?:[\s\xa0]*T(?:hes|e)?|Thes)s|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Tesaloni[cs]enses?|Primer(?:o[\s\xa0]*Tesaloni[cs]enses?|[\s\xa0]*Tesaloni[cs]enses?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Timoteo)|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*Timoteo|2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*Timoteo|Segundo[\s\xa0]*Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Timoteo)|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*Timoteo|1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*Timoteo|Primero?[\s\xa0]*Timoteo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:i(?:t(?:us|o)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:ilem(?:[o\xF3]n)?|lmn?|mn)|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hebr(?:[or][eor]|[or]|e[er])s)|(?:He(?:b(?:[eo](?:[eor][eor]?)?s|r(?:eo?)?s|r(?:eo)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ant(?:iago)?|tg?)|Jas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*P(?:edro|d)|Pet))|(?:(?:2(?:\.[o\xBA]?|[o\xBA])|II)[\s\xa0]*(?:San[\s\xa0]*)?Pedro|2[\s\xa0]*(?:P(?:ed|e)?|San[\s\xa0]*Pedro)|(?:2(?:\.[o\xBA]|[o\xBA])|II)\.[\s\xa0]*(?:San[\s\xa0]*)?Pedro|Segundo[\s\xa0]*(?:San[\s\xa0]*)?Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*P(?:edro|d)|Pet))|(?:(?:1(?:\.[o\xBA]?|[o\xBA])|I)[\s\xa0]*(?:San[\s\xa0]*)?Pedro|1[\s\xa0]*(?:P(?:ed|e)?|San[\s\xa0]*Pedro)|(?:1(?:\.[o\xBA]|[o\xBA])|I)\.[\s\xa0]*(?:San[\s\xa0]*)?Pedro|Primer(?:o[\s\xa0]*(?:San[\s\xa0]*)?|[\s\xa0]*(?:San[\s\xa0]*)?)Pedro)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ud(?:as|e)|das))|(?:San[\s\xa0]*Judas|Ju?d)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:it?|t)?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udi?|di?)t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ba(?:r(?:uc)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sus(?:ana)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab", "Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ha)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb", "Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ma)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil", "Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Fil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
|
[
{
"context": "m',\n version: '49.0.2609.0',\n path: '/Users/bmann/Downloads/chrome-mac/Chromium.app/Contents/MacOS/",
"end": 2148,
"score": 0.9988757371902466,
"start": 2143,
"tag": "USERNAME",
"value": "bmann"
},
{
"context": ", ->\n Promise.all([\n user.set({name:... | packages/server/test/integration/cypress_spec.coffee | Manduro/cypress | 0 | require("../spec_helper")
_ = require("lodash")
os = require("os")
cp = require("child_process")
path = require("path")
EE = require("events")
http = require("http")
Promise = require("bluebird")
electron = require("electron")
commitInfo = require("@cypress/commit-info")
isForkPr = require("is-fork-pr")
Fixtures = require("../support/helpers/fixtures")
pkg = require("@packages/root")
launcher = require("@packages/launcher")
extension = require("@packages/extension")
fs = require("#{root}lib/util/fs")
connect = require("#{root}lib/util/connect")
ciProvider = require("#{root}lib/util/ci_provider")
settings = require("#{root}lib/util/settings")
Events = require("#{root}lib/gui/events")
Windows = require("#{root}lib/gui/windows")
record = require("#{root}lib/modes/record")
interactiveMode = require("#{root}lib/modes/interactive")
runMode = require("#{root}lib/modes/run")
api = require("#{root}lib/api")
cwd = require("#{root}lib/cwd")
user = require("#{root}lib/user")
config = require("#{root}lib/config")
cache = require("#{root}lib/cache")
errors = require("#{root}lib/errors")
plugins = require("#{root}lib/plugins")
cypress = require("#{root}lib/cypress")
Project = require("#{root}lib/project")
Server = require("#{root}lib/server")
Reporter = require("#{root}lib/reporter")
Watchers = require("#{root}lib/watchers")
browsers = require("#{root}lib/browsers")
videoCapture = require("#{root}lib/video_capture")
browserUtils = require("#{root}lib/browsers/utils")
openProject = require("#{root}lib/open_project")
env = require("#{root}lib/util/env")
appData = require("#{root}lib/util/app_data")
formStatePath = require("#{root}lib/util/saved_state").formStatePath
TYPICAL_BROWSERS = [
{
name: 'chrome',
displayName: 'Chrome',
version: '60.0.3112.101',
path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
majorVersion: '60'
}, {
name: 'chromium',
displayName: 'Chromium',
version: '49.0.2609.0',
path: '/Users/bmann/Downloads/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
majorVersion: '49'
}, {
name: 'canary',
displayName: 'Canary',
version: '62.0.3197.0',
path: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
majorVersion: '62'
}, {
name: 'electron',
version: '',
path: '',
majorVersion: '',
info: 'Electron is the default browser that comes with Cypress. This is the browser that runs in headless mode. Selecting this browser is useful when debugging. The version number indicates the underlying Chromium version that Electron uses.'
}
]
describe "lib/cypress", ->
require("mocha-banner").register()
beforeEach ->
@timeout(5000)
cache.__removeSync()
Fixtures.scaffold()
@todosPath = Fixtures.projectPath("todos")
@pristinePath = Fixtures.projectPath("pristine")
@noScaffolding = Fixtures.projectPath("no-scaffolding")
@recordPath = Fixtures.projectPath("record")
@pluginConfig = Fixtures.projectPath("plugin-config")
@pluginBrowser = Fixtures.projectPath("plugin-browser")
@idsPath = Fixtures.projectPath("ids")
## force cypress to call directly into main without
## spawning a separate process
sinon.stub(videoCapture, "start").resolves({})
sinon.stub(plugins, "init").resolves(undefined)
sinon.stub(cypress, "isCurrentlyRunningElectron").returns(true)
sinon.stub(extension, "setHostAndPath").resolves()
sinon.stub(launcher, "detect").resolves(TYPICAL_BROWSERS)
sinon.stub(process, "exit")
sinon.stub(Server.prototype, "reset")
sinon.spy(errors, "log")
sinon.spy(errors, "warning")
sinon.spy(console, "log")
@expectExitWith = (code) =>
expect(process.exit).to.be.calledWith(code)
@expectExitWithErr = (type, msg) ->
expect(errors.log).to.be.calledWithMatch({type: type})
expect(process.exit).to.be.calledWith(1)
if msg
err = errors.log.getCall(0).args[0]
expect(err.message).to.include(msg)
afterEach ->
Fixtures.remove()
## make sure every project
## we spawn is closed down
openProject.close()
context "--get-key", ->
it "writes out key and exits on success", ->
Promise.all([
user.set({name: "brian", authToken: "auth-token-123"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
expect(console.log).to.be.calledWith("new-key-123")
@expectExitWith(0)
it "logs error and exits when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("NOT_LOGGED_IN")
it "logs error and exits when project does not have an id", ->
user.set({authToken: "auth-token-123"})
.then =>
cypress.start(["--get-key", "--project=#{@pristinePath}"])
.then =>
@expectExitWithErr("NO_PROJECT_ID", @pristinePath)
it "logs error and exits when project could not be found at the path", ->
user.set({authToken: "auth-token-123"})
.then =>
cypress.start(["--get-key", "--project=path/to/no/project"])
.then =>
@expectExitWithErr("NO_PROJECT_FOUND_AT_PROJECT_ROOT", "path/to/no/project")
it "logs error and exits when project token cannot be fetched", ->
Promise.all([
user.set({authToken: "auth-token-123"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_FETCH_PROJECT_TOKEN")
context "--new-key", ->
it "writes out key and exits on success", ->
Promise.all([
user.set({name: "brian", authToken: "auth-token-123"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
expect(console.log).to.be.calledWith("new-key-123")
@expectExitWith(0)
it "logs error and exits when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("NOT_LOGGED_IN")
it "logs error and exits when project does not have an id", ->
user.set({authToken: "auth-token-123"})
.then =>
cypress.start(["--new-key", "--project=#{@pristinePath}"])
.then =>
@expectExitWithErr("NO_PROJECT_ID", @pristinePath)
it "logs error and exits when project could not be found at the path", ->
user.set({authToken: "auth-token-123"})
.then =>
cypress.start(["--new-key", "--project=path/to/no/project"])
.then =>
@expectExitWithErr("NO_PROJECT_FOUND_AT_PROJECT_ROOT", "path/to/no/project")
it "logs error and exits when project token cannot be fetched", ->
Promise.all([
user.set({authToken: "auth-token-123"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_CREATE_PROJECT_TOKEN")
context "--run-project", ->
beforeEach ->
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(runMode, "waitForSocketConnection")
sinon.stub(runMode, "listenForProjectEnd").resolves({stats: {failures: 0} })
sinon.stub(browsers, "open")
sinon.stub(commitInfo, "getRemoteOrigin").resolves("remoteOrigin")
it "runs project headlessly and exits with exit code 0", ->
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron")
@expectExitWith(0)
it "runs project headlessly and exits with exit code 10", ->
sinon.stub(runMode, "runSpecs").resolves({ totalFailed: 10 })
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWith(10)
it "does not generate a project id even if missing one", ->
sinon.stub(api, "createProject")
user.set({authToken: "auth-token-123"})
.then =>
cypress.start(["--run-project=#{@noScaffolding}"])
.then =>
@expectExitWith(0)
.then =>
expect(api.createProject).not.to.be.called
Project(@noScaffolding).getProjectId()
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("NO_PROJECT_ID")
it "does not add project to the global cache", ->
cache.getProjectRoots()
.then (projects) =>
## no projects in the cache
expect(projects.length).to.eq(0)
cypress.start(["--run-project=#{@todosPath}"])
.then ->
cache.getProjectRoots()
.then (projects) ->
## still not projects
expect(projects.length).to.eq(0)
it "runs project by relative spec and exits with status 0", ->
relativePath = path.relative(cwd(), @todosPath)
cypress.start([
"--run-project=#{@todosPath}",
"--spec=#{relativePath}/tests/test2.coffee"
])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {
url: "http://localhost:8888/__/#/tests/integration/test2.coffee"
})
@expectExitWith(0)
it "runs project by specific spec with default configuration", ->
cypress.start(["--run-project=#{@idsPath}", "--spec=#{@idsPath}/cypress/integration/bar.js", "--config", "port=2020"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {url: "http://localhost:2020/__/#/tests/integration/bar.js"})
@expectExitWith(0)
it "runs project by specific absolute spec and exits with status 0", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=#{@todosPath}/tests/test2.coffee"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {url: "http://localhost:8888/__/#/tests/integration/test2.coffee"})
@expectExitWith(0)
it "scaffolds out integration and example specs if they do not exist when not runMode", ->
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(cfg.integrationFolder)
.then ->
throw new Error("integrationFolder should not exist!")
.catch =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(cfg.integrationFolder)
.then =>
Promise.join(
fs.statAsync(path.join(cfg.integrationFolder, "examples", "actions.spec.js")),
fs.statAsync(path.join(cfg.integrationFolder, "examples", "files.spec.js")),
fs.statAsync(path.join(cfg.integrationFolder, "examples", "viewport.spec.js"))
)
it "does not scaffold when headless and exits with error when no existing project", ->
ensureDoesNotExist = (inspection, index) ->
if not inspection.isRejected()
throw new Error("File or folder was scaffolded at index: #{index}")
expect(inspection.reason()).to.have.property("code", "ENOENT")
Promise.all([
fs.statAsync(path.join(@pristinePath, "cypress")).reflect()
fs.statAsync(path.join(@pristinePath, "cypress.json")).reflect()
])
.each(ensureDoesNotExist)
.then =>
cypress.start(["--run-project=#{@pristinePath}"])
.then =>
Promise.all([
fs.statAsync(path.join(@pristinePath, "cypress")).reflect()
fs.statAsync(path.join(@pristinePath, "cypress.json")).reflect()
])
.each(ensureDoesNotExist)
.then =>
@expectExitWithErr("PROJECT_DOES_NOT_EXIST", @pristinePath)
it "does not scaffold integration or example specs when runMode", ->
settings.write(@pristinePath, {})
.then =>
cypress.start(["--run-project=#{@pristinePath}"])
.then =>
fs.statAsync(path.join(@pristinePath, "cypress", "integration"))
.then =>
throw new Error("integration folder should not exist!")
.catch {code: "ENOENT"}, =>
it "scaffolds out fixtures + files if they do not exist", ->
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(cfg.fixturesFolder)
.then ->
throw new Error("fixturesFolder should not exist!")
.catch =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(cfg.fixturesFolder)
.then =>
fs.statAsync path.join(cfg.fixturesFolder, "example.json")
it "scaffolds out support + files if they do not exist", ->
supportFolder = path.join(@pristinePath, "cypress/support")
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(supportFolder)
.then ->
throw new Error("supportFolder should not exist!")
.catch {code: "ENOENT"}, =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(supportFolder)
.then =>
fs.statAsync path.join(supportFolder, "index.js")
.then =>
fs.statAsync path.join(supportFolder, "commands.js")
it "removes fixtures when they exist and fixturesFolder is false", (done) ->
config.get(@idsPath)
.then (@cfg) =>
fs.statAsync(@cfg.fixturesFolder)
.then =>
settings.read(@idsPath)
.then (json) =>
json.fixturesFolder = false
settings.write(@idsPath, json)
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
fs.statAsync(@cfg.fixturesFolder)
.then ->
throw new Error("fixturesFolder should not exist!")
.catch -> done()
it "runs project headlessly and displays gui", ->
cypress.start(["--run-project=#{@todosPath}", "--headed"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {
proxyServer: "http://localhost:8888"
show: true
})
@expectExitWith(0)
it "turns on reporting", ->
sinon.spy(Reporter, "create")
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(Reporter.create).to.be.calledWith("spec")
@expectExitWith(0)
it "can change the reporter to nyan", ->
sinon.spy(Reporter, "create")
cypress.start(["--run-project=#{@todosPath}", "--reporter=nyan"])
.then =>
expect(Reporter.create).to.be.calledWith("nyan")
@expectExitWith(0)
it "can change the reporter with cypress.json", ->
sinon.spy(Reporter, "create")
config.get(@idsPath)
.then (@cfg) =>
settings.read(@idsPath)
.then (json) =>
json.reporter = "dot"
settings.write(@idsPath, json)
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
expect(Reporter.create).to.be.calledWith("dot")
@expectExitWith(0)
it "runs tests even when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWith(0)
it "logs warning when projectId and key but no record option", ->
cypress.start(["--run-project=#{@todosPath}", "--key=asdf"])
.then =>
expect(errors.warning).to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).to.be.calledWithMatch("You also provided your Record Key, but you did not pass the --record flag.")
expect(console.log).to.be.calledWithMatch("cypress run --record")
expect(console.log).to.be.calledWithMatch("https://on.cypress.io/recording-project-runs")
it "does not log warning when no projectId", ->
cypress.start(["--run-project=#{@pristinePath}", "--key=asdf"])
.then =>
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).not.to.be.calledWithMatch("cypress run --key <record_key>")
it "does not log warning when projectId but --record false", ->
cypress.start(["--run-project=#{@todosPath}", "--key=asdf", "--record=false"])
.then =>
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).not.to.be.calledWithMatch("cypress run --key <record_key>")
it "logs error when supportFile doesn't exist", ->
settings.write(@idsPath, {supportFile: "/does/not/exist"})
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
@expectExitWithErr("SUPPORT_FILE_NOT_FOUND", "Your supportFile is set to '/does/not/exist',")
it "logs error when browser cannot be found", ->
browsers.open.restore()
cypress.start(["--run-project=#{@idsPath}", "--browser=foo"])
.then =>
@expectExitWithErr("BROWSER_NOT_FOUND")
## get all the error args
argsSet = errors.log.args
found1 = _.find argsSet, (args) ->
_.find args, (arg) ->
arg.message and arg.message.includes(
"Browser: 'foo' was not found on your system."
)
expect(found1, "foo should not be found").to.be.ok
found2 = _.find argsSet, (args) ->
_.find args, (arg) ->
arg.message and arg.message.includes(
"Available browsers found are: chrome, chromium, canary, electron"
)
expect(found2, "browser names should be listed").to.be.ok
it "logs error and exits when spec file was specified and does not exist", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=path/to/spec"])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "path/to/spec")
@expectExitWithErr("NO_SPECS_FOUND", "We searched for any files matching this glob pattern:")
it "logs error and exits when spec absolute file was specified and does not exist", ->
cypress.start([
"--run-project=#{@todosPath}",
"--spec=#{@todosPath}/tests/path/to/spec"
])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "tests/path/to/spec")
it "logs error and exits when no specs were found at all", ->
cypress.start([
"--run-project=#{@todosPath}",
"--config=integrationFolder=cypress/specs"
])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "We searched for any files inside of this folder:")
@expectExitWithErr("NO_SPECS_FOUND", "cypress/specs")
it "logs error and exits when project has cypress.json syntax error", ->
fs.writeFileAsync(@todosPath + "/cypress.json", "{'foo': 'bar}")
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("ERROR_READING_FILE", @todosPath)
it "logs error and exits when project has cypress.env.json syntax error", ->
fs.writeFileAsync(@todosPath + "/cypress.env.json", "{'foo': 'bar}")
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("ERROR_READING_FILE", @todosPath)
it "logs error and exits when project has invalid cypress.json values", ->
settings.write(@todosPath, {baseUrl: "localhost:9999"})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("SETTINGS_VALIDATION_ERROR", "cypress.json")
it "logs error and exits when project has invalid config values from the CLI", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=baseUrl=localhost:9999"
])
.then =>
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "localhost:9999")
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "We found an invalid configuration value")
it "logs error and exits when project has invalid config values from env vars", ->
process.env.CYPRESS_BASE_URL = "localhost:9999"
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "localhost:9999")
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "We found an invalid configuration value")
it "logs error and exits when using an old configuration option: trashAssetsBeforeHeadlessRuns", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=trashAssetsBeforeHeadlessRuns=false"
])
.then =>
@expectExitWithErr("RENAMED_CONFIG_OPTION", "trashAssetsBeforeHeadlessRuns")
@expectExitWithErr("RENAMED_CONFIG_OPTION", "trashAssetsBeforeRuns")
it "logs error and exits when using an old configuration option: videoRecording", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=videoRecording=false"
])
.then =>
@expectExitWithErr("RENAMED_CONFIG_OPTION", "videoRecording")
@expectExitWithErr("RENAMED_CONFIG_OPTION", "video")
it "logs error and exits when using screenshotOnHeadlessFailure", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=screenshotOnHeadlessFailure=false"
])
.then =>
@expectExitWithErr("SCREENSHOT_ON_HEADLESS_FAILURE_REMOVED", "screenshotOnHeadlessFailure")
@expectExitWithErr("SCREENSHOT_ON_HEADLESS_FAILURE_REMOVED", "You now configure this behavior in your test code")
it "logs error and exits when baseUrl cannot be verified", ->
settings.write(@todosPath, {baseUrl: "http://localhost:90874"})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_CONNECT_BASE_URL", "http://localhost:90874")
## TODO: make sure we have integration tests around this
## for headed projects!
## also make sure we test the rest of the integration functionality
## for headed errors! <-- not unit tests, but integration tests!
it "logs error and exits when project folder has read permissions only and cannot write cypress.json", ->
if process.env.CI
## Gleb: disabling this because Node 8 docker image runs as root
## which makes accessing everything possible.
return
permissionsPath = path.resolve("./permissions")
cypressJson = path.join(permissionsPath, "cypress.json")
fs.outputFileAsync(cypressJson, "{}")
.then =>
## read only
fs.chmodAsync(permissionsPath, "555")
.then =>
cypress.start(["--run-project=#{permissionsPath}"])
.then =>
fs.chmodAsync(permissionsPath, "777")
.then =>
fs.removeAsync(permissionsPath)
.then =>
@expectExitWithErr("ERROR_READING_FILE", path.join(permissionsPath, "cypress.json"))
it "logs error and exits when reporter does not exist", ->
cypress.start(["--run-project=#{@todosPath}", "--reporter", "foobarbaz"])
.then =>
@expectExitWithErr("INVALID_REPORTER_NAME", "foobarbaz")
describe "state", ->
statePath = null
beforeEach ->
formStatePath(@todosPath)
.then (statePathStart) ->
statePath = appData.projectsPath(statePathStart)
fs.pathExists(statePath)
.then (found) ->
if found
fs.unlink(statePath)
afterEach ->
fs.unlink(statePath)
it "saves project state", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=#{@todosPath}/tests/test2.coffee"])
.then =>
@expectExitWith(0)
.then ->
openProject.getProject().saveState()
.then () ->
fs.pathExists(statePath)
.then (found) ->
expect(found, "Finds saved stage file #{statePath}").to.be.true
describe "morgan", ->
it "sets morgan to false", ->
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(openProject.getProject().cfg.morgan).to.be.false
@expectExitWith(0)
describe "config overrides", ->
it "can override default values", ->
cypress.start(["--run-project=#{@todosPath}", "--config=requestTimeout=1234,videoCompression=false"])
.then =>
cfg = openProject.getProject().cfg
expect(cfg.videoCompression).to.be.false
expect(cfg.requestTimeout).to.eq(1234)
expect(cfg.resolved.videoCompression).to.deep.eq({
value: false
from: "cli"
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234
from: "cli"
})
@expectExitWith(0)
it "can override values in plugins", ->
plugins.init.restore()
cypress.start([
"--run-project=#{@pluginConfig}", "--config=requestTimeout=1234,videoCompression=false"
"--env=foo=foo,bar=bar"
])
.then =>
cfg = openProject.getProject().cfg
expect(cfg.videoCompression).to.eq(20)
expect(cfg.defaultCommandTimeout).to.eq(500)
expect(cfg.env).to.deep.eq({
foo: "bar"
bar: "bar"
})
expect(cfg.resolved.videoCompression).to.deep.eq({
value: 20
from: "plugin"
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234
from: "cli"
})
expect(cfg.resolved.env.foo).to.deep.eq({
value: "bar"
from: "plugin"
})
expect(cfg.resolved.env.bar).to.deep.eq({
value: "bar"
from: "cli"
})
@expectExitWith(0)
describe "plugins", ->
beforeEach ->
plugins.init.restore()
browsers.open.restore()
ee = new EE()
ee.kill = ->
ee.emit("exit")
ee.close = ->
ee.emit("closed")
ee.isDestroyed = -> false
ee.loadURL = ->
ee.webContents = {
session: {
clearCache: sinon.stub().yieldsAsync()
}
}
sinon.stub(browserUtils, "launch").resolves(ee)
sinon.stub(Windows, "create").returns(ee)
sinon.stub(Windows, "automation")
context "before:browser:launch", ->
it "chrome", ->
cypress.start([
"--run-project=#{@pluginBrowser}"
"--browser=chrome"
])
.then =>
args = browserUtils.launch.firstCall.args
expect(args[0]).to.eq("chrome")
browserArgs = args[2]
expect(browserArgs).to.have.length(7)
expect(browserArgs.slice(0, 4)).to.deep.eq([
"chrome", "foo", "bar", "baz"
])
@expectExitWith(0)
it "electron", ->
cypress.start([
"--run-project=#{@pluginBrowser}"
"--browser=electron"
])
.then =>
expect(Windows.create).to.be.calledWith(@pluginBrowser, {
browser: "electron"
foo: "bar"
})
@expectExitWith(0)
describe "--port", ->
beforeEach ->
runMode.listenForProjectEnd.resolves({stats: {failures: 0} })
it "can change the default port to 5555", ->
listen = sinon.spy(http.Server.prototype, "listen")
open = sinon.spy(Server.prototype, "open")
cypress.start(["--run-project=#{@todosPath}", "--port=5555"])
.then =>
expect(openProject.getProject().cfg.port).to.eq(5555)
expect(listen).to.be.calledWith(5555)
expect(open).to.be.calledWithMatch({port: 5555})
@expectExitWith(0)
## TODO: handle PORT_IN_USE short integration test
it "logs error and exits when port is in use", ->
server = http.createServer()
server = Promise.promisifyAll(server)
server.listenAsync(5555)
.then =>
cypress.start(["--run-project=#{@todosPath}", "--port=5555"])
.then =>
@expectExitWithErr("PORT_IN_USE_LONG", "5555")
describe "--env", ->
beforeEach ->
process.env = _.omit(process.env, "CYPRESS_DEBUG")
runMode.listenForProjectEnd.resolves({stats: {failures: 0} })
it "can set specific environment variables", ->
cypress.start([
"--run-project=#{@todosPath}",
"--video=false"
"--env",
"version=0.12.1,foo=bar,host=http://localhost:8888,baz=quux=dolor"
])
.then =>
expect(openProject.getProject().cfg.env).to.deep.eq({
version: "0.12.1"
foo: "bar"
host: "http://localhost:8888"
baz: "quux=dolor"
})
@expectExitWith(0)
## most record mode logic is covered in e2e tests.
## we only need to cover the edge cases / warnings
context "--record or --ci", ->
beforeEach ->
sinon.stub(api, "createRun").resolves()
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(browsers, "open")
sinon.stub(runMode, "waitForSocketConnection")
sinon.stub(runMode, "waitForTestsToFinishRunning").resolves({
stats: {
tests: 1
passes: 2
failures: 3
pending: 4
skipped: 5
wallClockDuration: 6
}
tests: []
hooks: []
video: "path/to/video"
shouldUploadVideo: true
screenshots: []
config: {}
spec: {}
})
Promise.all([
## make sure we have no user object
user.set({})
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
it "uses process.env.CYPRESS_PROJECT_ID", ->
sinon.stub(env, "get").withArgs("CYPRESS_PROJECT_ID").returns(@projectId)
cypress.start([
"--run-project=#{@noScaffolding}",
"--record",
"--key=token-123"
])
.then =>
expect(api.createRun).to.be.calledWithMatch({projectId: @projectId})
expect(errors.warning).not.to.be.called
@expectExitWith(3)
it "uses process.env.CYPRESS_RECORD_KEY", ->
sinon.stub(env, "get")
.withArgs("CYPRESS_PROJECT_ID").returns("foo-project-123")
.withArgs("CYPRESS_RECORD_KEY").returns("token")
cypress.start([
"--run-project=#{@noScaffolding}",
"--record"
])
.then =>
expect(api.createRun).to.be.calledWithMatch({
projectId: "foo-project-123"
recordKey: "token"
})
expect(errors.warning).not.to.be.called
@expectExitWith(3)
it "logs warning when using deprecated --ci arg and no env var", ->
cypress.start([
"--run-project=#{@recordPath}",
"--key=token-123",
"--ci"
])
.then =>
expect(errors.warning).to.be.calledWith("CYPRESS_CI_DEPRECATED")
expect(console.log).to.be.calledWithMatch("You are using the deprecated command:")
expect(console.log).to.be.calledWithMatch("cypress run --record --key <record_key>")
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION")
@expectExitWith(3)
it "logs warning when using deprecated --ci arg and env var", ->
sinon.stub(env, "get")
.withArgs("CYPRESS_CI_KEY")
.returns("asdf123foobarbaz")
cypress.start([
"--run-project=#{@recordPath}",
"--key=token-123",
"--ci"
])
.then =>
expect(errors.warning).to.be.calledWith("CYPRESS_CI_DEPRECATED_ENV_VAR")
expect(console.log).to.be.calledWithMatch("You are using the deprecated command:")
expect(console.log).to.be.calledWithMatch("cypress ci")
expect(console.log).to.be.calledWithMatch("cypress run --record")
@expectExitWith(3)
context "--return-pkg", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs package.json and exits", ->
cypress.start(["--return-pkg"])
.then =>
expect(console.log).to.be.calledWithMatch('{"name":"cypress"')
@expectExitWith(0)
context "--version", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs version and exits", ->
cypress.start(["--version"])
.then =>
expect(console.log).to.be.calledWith(pkg.version)
@expectExitWith(0)
context "--smoke-test", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs pong value and exits", ->
cypress.start(["--smoke-test", "--ping=abc123"])
.then =>
expect(console.log).to.be.calledWith("abc123")
@expectExitWith(0)
context "interactive", ->
beforeEach ->
@win = {
on: sinon.stub()
webContents: {
on: sinon.stub()
}
}
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(Windows, "open").resolves(@win)
sinon.stub(Server.prototype, "startWebsockets")
sinon.spy(Events, "start")
sinon.stub(electron.ipcMain, "on")
it "passes options to interactiveMode.ready", ->
sinon.stub(interactiveMode, "ready")
cypress.start(["--updating", "--port=2121", "--config=pageLoadTimeout=1000"])
.then ->
expect(interactiveMode.ready).to.be.calledWithMatch({
updating: true
config: {
port: 2121
pageLoadTimeout: 1000
}
})
it "passes options to Events.start", ->
cypress.start(["--port=2121", "--config=pageLoadTimeout=1000"])
.then ->
expect(Events.start).to.be.calledWithMatch({
port: 2121,
config: {
pageLoadTimeout: 1000
port: 2121
}
})
it "passes filtered options to Project#open and sets cli config", ->
getConfig = sinon.spy(Project.prototype, "getConfig")
open = sinon.stub(Server.prototype, "open").resolves([])
process.env.CYPRESS_FILE_SERVER_FOLDER = "foo"
process.env.CYPRESS_BASE_URL = "http://localhost"
process.env.CYPRESS_port = "2222"
process.env.CYPRESS_responseTimeout = "5555"
process.env.CYPRESS_watch_for_file_changes = "false"
user.set({name: "brian", authToken: "auth-token-123"})
.then =>
settings.read(@todosPath)
.then (json) =>
## this should be overriden by the env argument
json.baseUrl = "http://localhost:8080"
settings.write(@todosPath, json)
.then =>
cypress.start([
"--port=2121",
"--config",
"pageLoadTimeout=1000",
"--foo=bar",
"--env=baz=baz"
])
.then =>
options = Events.start.firstCall.args[0]
Events.handleEvent(options, {}, {}, 123, "open:project", @todosPath)
.then =>
expect(getConfig).to.be.calledWithMatch({
port: 2121
pageLoadTimeout: 1000
report: false
env: { baz: "baz" }
})
expect(open).to.be.called
cfg = open.getCall(0).args[0]
expect(cfg.fileServerFolder).to.eq(path.join(@todosPath, "foo"))
expect(cfg.pageLoadTimeout).to.eq(1000)
expect(cfg.port).to.eq(2121)
expect(cfg.baseUrl).to.eq("http://localhost")
expect(cfg.watchForFileChanges).to.be.false
expect(cfg.responseTimeout).to.eq(5555)
expect(cfg.env.baz).to.eq("baz")
expect(cfg.env).not.to.have.property("fileServerFolder")
expect(cfg.env).not.to.have.property("port")
expect(cfg.env).not.to.have.property("BASE_URL")
expect(cfg.env).not.to.have.property("watchForFileChanges")
expect(cfg.env).not.to.have.property("responseTimeout")
expect(cfg.resolved.fileServerFolder).to.deep.eq({
value: "foo"
from: "env"
})
expect(cfg.resolved.pageLoadTimeout).to.deep.eq({
value: 1000
from: "cli"
})
expect(cfg.resolved.port).to.deep.eq({
value: 2121
from: "cli"
})
expect(cfg.resolved.baseUrl).to.deep.eq({
value: "http://localhost"
from: "env"
})
expect(cfg.resolved.watchForFileChanges).to.deep.eq({
value: false
from: "env"
})
expect(cfg.resolved.responseTimeout).to.deep.eq({
value: 5555
from: "env"
})
expect(cfg.resolved.env.baz).to.deep.eq({
value: "baz"
from: "cli"
})
it "sends warning when baseUrl cannot be verified", ->
bus = new EE()
event = { sender: { send: sinon.stub() } }
warning = { message: "Blah blah baseUrl blah blah" }
open = sinon.stub(Server.prototype, "open").resolves([2121, warning])
cypress.start(["--port=2121", "--config", "pageLoadTimeout=1000", "--foo=bar", "--env=baz=baz"])
.then =>
options = Events.start.firstCall.args[0]
Events.handleEvent(options, bus, event, 123, "on:project:warning")
Events.handleEvent(options, bus, event, 123, "open:project", @todosPath)
.then ->
expect(event.sender.send.withArgs("response").firstCall.args[1].data).to.eql(warning)
context "no args", ->
beforeEach ->
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(interactiveMode, "ready").resolves()
it "runs interactiveMode and does not exit", ->
cypress.start().then ->
expect(interactiveMode.ready).to.be.calledOnce
| 28389 | require("../spec_helper")
_ = require("lodash")
os = require("os")
cp = require("child_process")
path = require("path")
EE = require("events")
http = require("http")
Promise = require("bluebird")
electron = require("electron")
commitInfo = require("@cypress/commit-info")
isForkPr = require("is-fork-pr")
Fixtures = require("../support/helpers/fixtures")
pkg = require("@packages/root")
launcher = require("@packages/launcher")
extension = require("@packages/extension")
fs = require("#{root}lib/util/fs")
connect = require("#{root}lib/util/connect")
ciProvider = require("#{root}lib/util/ci_provider")
settings = require("#{root}lib/util/settings")
Events = require("#{root}lib/gui/events")
Windows = require("#{root}lib/gui/windows")
record = require("#{root}lib/modes/record")
interactiveMode = require("#{root}lib/modes/interactive")
runMode = require("#{root}lib/modes/run")
api = require("#{root}lib/api")
cwd = require("#{root}lib/cwd")
user = require("#{root}lib/user")
config = require("#{root}lib/config")
cache = require("#{root}lib/cache")
errors = require("#{root}lib/errors")
plugins = require("#{root}lib/plugins")
cypress = require("#{root}lib/cypress")
Project = require("#{root}lib/project")
Server = require("#{root}lib/server")
Reporter = require("#{root}lib/reporter")
Watchers = require("#{root}lib/watchers")
browsers = require("#{root}lib/browsers")
videoCapture = require("#{root}lib/video_capture")
browserUtils = require("#{root}lib/browsers/utils")
openProject = require("#{root}lib/open_project")
env = require("#{root}lib/util/env")
appData = require("#{root}lib/util/app_data")
formStatePath = require("#{root}lib/util/saved_state").formStatePath
TYPICAL_BROWSERS = [
{
name: 'chrome',
displayName: 'Chrome',
version: '60.0.3112.101',
path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
majorVersion: '60'
}, {
name: 'chromium',
displayName: 'Chromium',
version: '49.0.2609.0',
path: '/Users/bmann/Downloads/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
majorVersion: '49'
}, {
name: 'canary',
displayName: 'Canary',
version: '62.0.3197.0',
path: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
majorVersion: '62'
}, {
name: 'electron',
version: '',
path: '',
majorVersion: '',
info: 'Electron is the default browser that comes with Cypress. This is the browser that runs in headless mode. Selecting this browser is useful when debugging. The version number indicates the underlying Chromium version that Electron uses.'
}
]
describe "lib/cypress", ->
require("mocha-banner").register()
beforeEach ->
@timeout(5000)
cache.__removeSync()
Fixtures.scaffold()
@todosPath = Fixtures.projectPath("todos")
@pristinePath = Fixtures.projectPath("pristine")
@noScaffolding = Fixtures.projectPath("no-scaffolding")
@recordPath = Fixtures.projectPath("record")
@pluginConfig = Fixtures.projectPath("plugin-config")
@pluginBrowser = Fixtures.projectPath("plugin-browser")
@idsPath = Fixtures.projectPath("ids")
## force cypress to call directly into main without
## spawning a separate process
sinon.stub(videoCapture, "start").resolves({})
sinon.stub(plugins, "init").resolves(undefined)
sinon.stub(cypress, "isCurrentlyRunningElectron").returns(true)
sinon.stub(extension, "setHostAndPath").resolves()
sinon.stub(launcher, "detect").resolves(TYPICAL_BROWSERS)
sinon.stub(process, "exit")
sinon.stub(Server.prototype, "reset")
sinon.spy(errors, "log")
sinon.spy(errors, "warning")
sinon.spy(console, "log")
@expectExitWith = (code) =>
expect(process.exit).to.be.calledWith(code)
@expectExitWithErr = (type, msg) ->
expect(errors.log).to.be.calledWithMatch({type: type})
expect(process.exit).to.be.calledWith(1)
if msg
err = errors.log.getCall(0).args[0]
expect(err.message).to.include(msg)
afterEach ->
Fixtures.remove()
## make sure every project
## we spawn is closed down
openProject.close()
context "--get-key", ->
it "writes out key and exits on success", ->
Promise.all([
user.set({name: "brian", authToken: "<PASSWORD>"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
expect(console.log).to.be.calledWith("new-key-123")
@expectExitWith(0)
it "logs error and exits when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("NOT_LOGGED_IN")
it "logs error and exits when project does not have an id", ->
user.set({authToken: "<PASSWORD>"})
.then =>
cypress.start(["--get-key", "--project=#{@pristinePath}"])
.then =>
@expectExitWithErr("NO_PROJECT_ID", @pristinePath)
it "logs error and exits when project could not be found at the path", ->
user.set({authToken: "<PASSWORD>"})
.then =>
cypress.start(["--get-key", "--project=path/to/no/project"])
.then =>
@expectExitWithErr("NO_PROJECT_FOUND_AT_PROJECT_ROOT", "path/to/no/project")
it "logs error and exits when project token cannot be fetched", ->
Promise.all([
user.set({authToken: "<PASSWORD>"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_FETCH_PROJECT_TOKEN")
context "--new-key", ->
it "writes out key and exits on success", ->
Promise.all([
user.set({name: "brian", authToken: "<PASSWORD>"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
expect(console.log).to.be.calledWith("new-key-123")
@expectExitWith(0)
it "logs error and exits when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("NOT_LOGGED_IN")
it "logs error and exits when project does not have an id", ->
user.set({authToken: "<PASSWORD>"})
.then =>
cypress.start(["--new-key", "--project=#{@pristinePath}"])
.then =>
@expectExitWithErr("NO_PROJECT_ID", @pristinePath)
it "logs error and exits when project could not be found at the path", ->
user.set({authToken: "<PASSWORD>"})
.then =>
cypress.start(["--new-key", "--project=path/to/no/project"])
.then =>
@expectExitWithErr("NO_PROJECT_FOUND_AT_PROJECT_ROOT", "path/to/no/project")
it "logs error and exits when project token cannot be fetched", ->
Promise.all([
user.set({authToken: "<PASSWORD>"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-<PASSWORD>")
.rejects(new Error())
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_CREATE_PROJECT_TOKEN")
context "--run-project", ->
beforeEach ->
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(runMode, "waitForSocketConnection")
sinon.stub(runMode, "listenForProjectEnd").resolves({stats: {failures: 0} })
sinon.stub(browsers, "open")
sinon.stub(commitInfo, "getRemoteOrigin").resolves("remoteOrigin")
it "runs project headlessly and exits with exit code 0", ->
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron")
@expectExitWith(0)
it "runs project headlessly and exits with exit code 10", ->
sinon.stub(runMode, "runSpecs").resolves({ totalFailed: 10 })
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWith(10)
it "does not generate a project id even if missing one", ->
sinon.stub(api, "createProject")
user.set({authToken: "<PASSWORD>"})
.then =>
cypress.start(["--run-project=#{@noScaffolding}"])
.then =>
@expectExitWith(0)
.then =>
expect(api.createProject).not.to.be.called
Project(@noScaffolding).getProjectId()
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("NO_PROJECT_ID")
it "does not add project to the global cache", ->
cache.getProjectRoots()
.then (projects) =>
## no projects in the cache
expect(projects.length).to.eq(0)
cypress.start(["--run-project=#{@todosPath}"])
.then ->
cache.getProjectRoots()
.then (projects) ->
## still not projects
expect(projects.length).to.eq(0)
it "runs project by relative spec and exits with status 0", ->
relativePath = path.relative(cwd(), @todosPath)
cypress.start([
"--run-project=#{@todosPath}",
"--spec=#{relativePath}/tests/test2.coffee"
])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {
url: "http://localhost:8888/__/#/tests/integration/test2.coffee"
})
@expectExitWith(0)
it "runs project by specific spec with default configuration", ->
cypress.start(["--run-project=#{@idsPath}", "--spec=#{@idsPath}/cypress/integration/bar.js", "--config", "port=2020"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {url: "http://localhost:2020/__/#/tests/integration/bar.js"})
@expectExitWith(0)
it "runs project by specific absolute spec and exits with status 0", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=#{@todosPath}/tests/test2.coffee"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {url: "http://localhost:8888/__/#/tests/integration/test2.coffee"})
@expectExitWith(0)
it "scaffolds out integration and example specs if they do not exist when not runMode", ->
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(cfg.integrationFolder)
.then ->
throw new Error("integrationFolder should not exist!")
.catch =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(cfg.integrationFolder)
.then =>
Promise.join(
fs.statAsync(path.join(cfg.integrationFolder, "examples", "actions.spec.js")),
fs.statAsync(path.join(cfg.integrationFolder, "examples", "files.spec.js")),
fs.statAsync(path.join(cfg.integrationFolder, "examples", "viewport.spec.js"))
)
it "does not scaffold when headless and exits with error when no existing project", ->
ensureDoesNotExist = (inspection, index) ->
if not inspection.isRejected()
throw new Error("File or folder was scaffolded at index: #{index}")
expect(inspection.reason()).to.have.property("code", "ENOENT")
Promise.all([
fs.statAsync(path.join(@pristinePath, "cypress")).reflect()
fs.statAsync(path.join(@pristinePath, "cypress.json")).reflect()
])
.each(ensureDoesNotExist)
.then =>
cypress.start(["--run-project=#{@pristinePath}"])
.then =>
Promise.all([
fs.statAsync(path.join(@pristinePath, "cypress")).reflect()
fs.statAsync(path.join(@pristinePath, "cypress.json")).reflect()
])
.each(ensureDoesNotExist)
.then =>
@expectExitWithErr("PROJECT_DOES_NOT_EXIST", @pristinePath)
it "does not scaffold integration or example specs when runMode", ->
settings.write(@pristinePath, {})
.then =>
cypress.start(["--run-project=#{@pristinePath}"])
.then =>
fs.statAsync(path.join(@pristinePath, "cypress", "integration"))
.then =>
throw new Error("integration folder should not exist!")
.catch {code: "ENOENT"}, =>
it "scaffolds out fixtures + files if they do not exist", ->
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(cfg.fixturesFolder)
.then ->
throw new Error("fixturesFolder should not exist!")
.catch =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(cfg.fixturesFolder)
.then =>
fs.statAsync path.join(cfg.fixturesFolder, "example.json")
it "scaffolds out support + files if they do not exist", ->
supportFolder = path.join(@pristinePath, "cypress/support")
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(supportFolder)
.then ->
throw new Error("supportFolder should not exist!")
.catch {code: "ENOENT"}, =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(supportFolder)
.then =>
fs.statAsync path.join(supportFolder, "index.js")
.then =>
fs.statAsync path.join(supportFolder, "commands.js")
it "removes fixtures when they exist and fixturesFolder is false", (done) ->
config.get(@idsPath)
.then (@cfg) =>
fs.statAsync(@cfg.fixturesFolder)
.then =>
settings.read(@idsPath)
.then (json) =>
json.fixturesFolder = false
settings.write(@idsPath, json)
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
fs.statAsync(@cfg.fixturesFolder)
.then ->
throw new Error("fixturesFolder should not exist!")
.catch -> done()
it "runs project headlessly and displays gui", ->
cypress.start(["--run-project=#{@todosPath}", "--headed"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {
proxyServer: "http://localhost:8888"
show: true
})
@expectExitWith(0)
it "turns on reporting", ->
sinon.spy(Reporter, "create")
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(Reporter.create).to.be.calledWith("spec")
@expectExitWith(0)
it "can change the reporter to nyan", ->
sinon.spy(Reporter, "create")
cypress.start(["--run-project=#{@todosPath}", "--reporter=nyan"])
.then =>
expect(Reporter.create).to.be.calledWith("nyan")
@expectExitWith(0)
it "can change the reporter with cypress.json", ->
sinon.spy(Reporter, "create")
config.get(@idsPath)
.then (@cfg) =>
settings.read(@idsPath)
.then (json) =>
json.reporter = "dot"
settings.write(@idsPath, json)
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
expect(Reporter.create).to.be.calledWith("dot")
@expectExitWith(0)
it "runs tests even when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWith(0)
it "logs warning when projectId and key but no record option", ->
cypress.start(["--run-project=#{@todosPath}", "--key=asdf"])
.then =>
expect(errors.warning).to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).to.be.calledWithMatch("You also provided your Record Key, but you did not pass the --record flag.")
expect(console.log).to.be.calledWithMatch("cypress run --record")
expect(console.log).to.be.calledWithMatch("https://on.cypress.io/recording-project-runs")
it "does not log warning when no projectId", ->
cypress.start(["--run-project=#{@pristinePath}", "--key=<KEY>"])
.then =>
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).not.to.be.calledWithMatch("cypress run --key <record_key>")
it "does not log warning when projectId but --record false", ->
cypress.start(["--run-project=#{@todosPath}", "--key=<KEY>", "--record=false"])
.then =>
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).not.to.be.calledWithMatch("cypress run --key <record_key>")
it "logs error when supportFile doesn't exist", ->
settings.write(@idsPath, {supportFile: "/does/not/exist"})
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
@expectExitWithErr("SUPPORT_FILE_NOT_FOUND", "Your supportFile is set to '/does/not/exist',")
it "logs error when browser cannot be found", ->
browsers.open.restore()
cypress.start(["--run-project=#{@idsPath}", "--browser=foo"])
.then =>
@expectExitWithErr("BROWSER_NOT_FOUND")
## get all the error args
argsSet = errors.log.args
found1 = _.find argsSet, (args) ->
_.find args, (arg) ->
arg.message and arg.message.includes(
"Browser: 'foo' was not found on your system."
)
expect(found1, "foo should not be found").to.be.ok
found2 = _.find argsSet, (args) ->
_.find args, (arg) ->
arg.message and arg.message.includes(
"Available browsers found are: chrome, chromium, canary, electron"
)
expect(found2, "browser names should be listed").to.be.ok
it "logs error and exits when spec file was specified and does not exist", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=path/to/spec"])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "path/to/spec")
@expectExitWithErr("NO_SPECS_FOUND", "We searched for any files matching this glob pattern:")
it "logs error and exits when spec absolute file was specified and does not exist", ->
cypress.start([
"--run-project=#{@todosPath}",
"--spec=#{@todosPath}/tests/path/to/spec"
])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "tests/path/to/spec")
it "logs error and exits when no specs were found at all", ->
cypress.start([
"--run-project=#{@todosPath}",
"--config=integrationFolder=cypress/specs"
])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "We searched for any files inside of this folder:")
@expectExitWithErr("NO_SPECS_FOUND", "cypress/specs")
it "logs error and exits when project has cypress.json syntax error", ->
fs.writeFileAsync(@todosPath + "/cypress.json", "{'foo': 'bar}")
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("ERROR_READING_FILE", @todosPath)
it "logs error and exits when project has cypress.env.json syntax error", ->
fs.writeFileAsync(@todosPath + "/cypress.env.json", "{'foo': 'bar}")
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("ERROR_READING_FILE", @todosPath)
it "logs error and exits when project has invalid cypress.json values", ->
settings.write(@todosPath, {baseUrl: "localhost:9999"})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("SETTINGS_VALIDATION_ERROR", "cypress.json")
it "logs error and exits when project has invalid config values from the CLI", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=baseUrl=localhost:9999"
])
.then =>
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "localhost:9999")
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "We found an invalid configuration value")
it "logs error and exits when project has invalid config values from env vars", ->
process.env.CYPRESS_BASE_URL = "localhost:9999"
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "localhost:9999")
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "We found an invalid configuration value")
it "logs error and exits when using an old configuration option: trashAssetsBeforeHeadlessRuns", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=trashAssetsBeforeHeadlessRuns=false"
])
.then =>
@expectExitWithErr("RENAMED_CONFIG_OPTION", "trashAssetsBeforeHeadlessRuns")
@expectExitWithErr("RENAMED_CONFIG_OPTION", "trashAssetsBeforeRuns")
it "logs error and exits when using an old configuration option: videoRecording", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=videoRecording=false"
])
.then =>
@expectExitWithErr("RENAMED_CONFIG_OPTION", "videoRecording")
@expectExitWithErr("RENAMED_CONFIG_OPTION", "video")
it "logs error and exits when using screenshotOnHeadlessFailure", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=screenshotOnHeadlessFailure=false"
])
.then =>
@expectExitWithErr("SCREENSHOT_ON_HEADLESS_FAILURE_REMOVED", "screenshotOnHeadlessFailure")
@expectExitWithErr("SCREENSHOT_ON_HEADLESS_FAILURE_REMOVED", "You now configure this behavior in your test code")
it "logs error and exits when baseUrl cannot be verified", ->
settings.write(@todosPath, {baseUrl: "http://localhost:90874"})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_CONNECT_BASE_URL", "http://localhost:90874")
## TODO: make sure we have integration tests around this
## for headed projects!
## also make sure we test the rest of the integration functionality
## for headed errors! <-- not unit tests, but integration tests!
it "logs error and exits when project folder has read permissions only and cannot write cypress.json", ->
if process.env.CI
## Gleb: disabling this because Node 8 docker image runs as root
## which makes accessing everything possible.
return
permissionsPath = path.resolve("./permissions")
cypressJson = path.join(permissionsPath, "cypress.json")
fs.outputFileAsync(cypressJson, "{}")
.then =>
## read only
fs.chmodAsync(permissionsPath, "555")
.then =>
cypress.start(["--run-project=#{permissionsPath}"])
.then =>
fs.chmodAsync(permissionsPath, "777")
.then =>
fs.removeAsync(permissionsPath)
.then =>
@expectExitWithErr("ERROR_READING_FILE", path.join(permissionsPath, "cypress.json"))
it "logs error and exits when reporter does not exist", ->
cypress.start(["--run-project=#{@todosPath}", "--reporter", "foobarbaz"])
.then =>
@expectExitWithErr("INVALID_REPORTER_NAME", "foobarbaz")
describe "state", ->
statePath = null
beforeEach ->
formStatePath(@todosPath)
.then (statePathStart) ->
statePath = appData.projectsPath(statePathStart)
fs.pathExists(statePath)
.then (found) ->
if found
fs.unlink(statePath)
afterEach ->
fs.unlink(statePath)
it "saves project state", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=#{@todosPath}/tests/test2.coffee"])
.then =>
@expectExitWith(0)
.then ->
openProject.getProject().saveState()
.then () ->
fs.pathExists(statePath)
.then (found) ->
expect(found, "Finds saved stage file #{statePath}").to.be.true
describe "morgan", ->
it "sets morgan to false", ->
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(openProject.getProject().cfg.morgan).to.be.false
@expectExitWith(0)
describe "config overrides", ->
it "can override default values", ->
cypress.start(["--run-project=#{@todosPath}", "--config=requestTimeout=1234,videoCompression=false"])
.then =>
cfg = openProject.getProject().cfg
expect(cfg.videoCompression).to.be.false
expect(cfg.requestTimeout).to.eq(1234)
expect(cfg.resolved.videoCompression).to.deep.eq({
value: false
from: "cli"
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234
from: "cli"
})
@expectExitWith(0)
it "can override values in plugins", ->
plugins.init.restore()
cypress.start([
"--run-project=#{@pluginConfig}", "--config=requestTimeout=1234,videoCompression=false"
"--env=foo=foo,bar=bar"
])
.then =>
cfg = openProject.getProject().cfg
expect(cfg.videoCompression).to.eq(20)
expect(cfg.defaultCommandTimeout).to.eq(500)
expect(cfg.env).to.deep.eq({
foo: "bar"
bar: "bar"
})
expect(cfg.resolved.videoCompression).to.deep.eq({
value: 20
from: "plugin"
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234
from: "cli"
})
expect(cfg.resolved.env.foo).to.deep.eq({
value: "bar"
from: "plugin"
})
expect(cfg.resolved.env.bar).to.deep.eq({
value: "bar"
from: "cli"
})
@expectExitWith(0)
describe "plugins", ->
beforeEach ->
plugins.init.restore()
browsers.open.restore()
ee = new EE()
ee.kill = ->
ee.emit("exit")
ee.close = ->
ee.emit("closed")
ee.isDestroyed = -> false
ee.loadURL = ->
ee.webContents = {
session: {
clearCache: sinon.stub().yieldsAsync()
}
}
sinon.stub(browserUtils, "launch").resolves(ee)
sinon.stub(Windows, "create").returns(ee)
sinon.stub(Windows, "automation")
context "before:browser:launch", ->
it "chrome", ->
cypress.start([
"--run-project=#{@pluginBrowser}"
"--browser=chrome"
])
.then =>
args = browserUtils.launch.firstCall.args
expect(args[0]).to.eq("chrome")
browserArgs = args[2]
expect(browserArgs).to.have.length(7)
expect(browserArgs.slice(0, 4)).to.deep.eq([
"chrome", "foo", "bar", "baz"
])
@expectExitWith(0)
it "electron", ->
cypress.start([
"--run-project=#{@pluginBrowser}"
"--browser=electron"
])
.then =>
expect(Windows.create).to.be.calledWith(@pluginBrowser, {
browser: "electron"
foo: "bar"
})
@expectExitWith(0)
describe "--port", ->
beforeEach ->
runMode.listenForProjectEnd.resolves({stats: {failures: 0} })
it "can change the default port to 5555", ->
listen = sinon.spy(http.Server.prototype, "listen")
open = sinon.spy(Server.prototype, "open")
cypress.start(["--run-project=#{@todosPath}", "--port=5555"])
.then =>
expect(openProject.getProject().cfg.port).to.eq(5555)
expect(listen).to.be.calledWith(5555)
expect(open).to.be.calledWithMatch({port: 5555})
@expectExitWith(0)
## TODO: handle PORT_IN_USE short integration test
it "logs error and exits when port is in use", ->
server = http.createServer()
server = Promise.promisifyAll(server)
server.listenAsync(5555)
.then =>
cypress.start(["--run-project=#{@todosPath}", "--port=5555"])
.then =>
@expectExitWithErr("PORT_IN_USE_LONG", "5555")
describe "--env", ->
beforeEach ->
process.env = _.omit(process.env, "CYPRESS_DEBUG")
runMode.listenForProjectEnd.resolves({stats: {failures: 0} })
it "can set specific environment variables", ->
cypress.start([
"--run-project=#{@todosPath}",
"--video=false"
"--env",
"version=0.12.1,foo=bar,host=http://localhost:8888,baz=quux=dolor"
])
.then =>
expect(openProject.getProject().cfg.env).to.deep.eq({
version: "0.12.1"
foo: "bar"
host: "http://localhost:8888"
baz: "quux=dolor"
})
@expectExitWith(0)
## most record mode logic is covered in e2e tests.
## we only need to cover the edge cases / warnings
context "--record or --ci", ->
beforeEach ->
sinon.stub(api, "createRun").resolves()
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(browsers, "open")
sinon.stub(runMode, "waitForSocketConnection")
sinon.stub(runMode, "waitForTestsToFinishRunning").resolves({
stats: {
tests: 1
passes: 2
failures: 3
pending: 4
skipped: 5
wallClockDuration: 6
}
tests: []
hooks: []
video: "path/to/video"
shouldUploadVideo: true
screenshots: []
config: {}
spec: {}
})
Promise.all([
## make sure we have no user object
user.set({})
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
it "uses process.env.CYPRESS_PROJECT_ID", ->
sinon.stub(env, "get").withArgs("CYPRESS_PROJECT_ID").returns(@projectId)
cypress.start([
"--run-project=#{@noScaffolding}",
"--record",
"--key=<PASSWORD>"
])
.then =>
expect(api.createRun).to.be.calledWithMatch({projectId: @projectId})
expect(errors.warning).not.to.be.called
@expectExitWith(3)
it "uses process.env.CYPRESS_RECORD_KEY", ->
sinon.stub(env, "get")
.withArgs("CYPRESS_PROJECT_ID").returns("foo-project-123")
.withArgs("CYPRESS_RECORD_KEY").returns("token")
cypress.start([
"--run-project=#{@noScaffolding}",
"--record"
])
.then =>
expect(api.createRun).to.be.calledWithMatch({
projectId: "foo-project-123"
recordKey: "token"
})
expect(errors.warning).not.to.be.called
@expectExitWith(3)
it "logs warning when using deprecated --ci arg and no env var", ->
cypress.start([
"--run-project=#{@recordPath}",
"--key=token-123",
"--ci"
])
.then =>
expect(errors.warning).to.be.calledWith("CYPRESS_CI_DEPRECATED")
expect(console.log).to.be.calledWithMatch("You are using the deprecated command:")
expect(console.log).to.be.calledWithMatch("cypress run --record --key <record_key>")
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION")
@expectExitWith(3)
it "logs warning when using deprecated --ci arg and env var", ->
sinon.stub(env, "get")
.withArgs("CYPRESS_CI_KEY")
.returns("<KEY>")
cypress.start([
"--run-project=#{@recordPath}",
"--key=token-1<KEY>3",
"--ci"
])
.then =>
expect(errors.warning).to.be.calledWith("CYPRESS_CI_DEPRECATED_ENV_VAR")
expect(console.log).to.be.calledWithMatch("You are using the deprecated command:")
expect(console.log).to.be.calledWithMatch("cypress ci")
expect(console.log).to.be.calledWithMatch("cypress run --record")
@expectExitWith(3)
context "--return-pkg", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs package.json and exits", ->
cypress.start(["--return-pkg"])
.then =>
expect(console.log).to.be.calledWithMatch('{"name":"cypress"')
@expectExitWith(0)
context "--version", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs version and exits", ->
cypress.start(["--version"])
.then =>
expect(console.log).to.be.calledWith(pkg.version)
@expectExitWith(0)
context "--smoke-test", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs pong value and exits", ->
cypress.start(["--smoke-test", "--ping=abc123"])
.then =>
expect(console.log).to.be.calledWith("abc123")
@expectExitWith(0)
context "interactive", ->
beforeEach ->
@win = {
on: sinon.stub()
webContents: {
on: sinon.stub()
}
}
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(Windows, "open").resolves(@win)
sinon.stub(Server.prototype, "startWebsockets")
sinon.spy(Events, "start")
sinon.stub(electron.ipcMain, "on")
it "passes options to interactiveMode.ready", ->
sinon.stub(interactiveMode, "ready")
cypress.start(["--updating", "--port=2121", "--config=pageLoadTimeout=1000"])
.then ->
expect(interactiveMode.ready).to.be.calledWithMatch({
updating: true
config: {
port: 2121
pageLoadTimeout: 1000
}
})
it "passes options to Events.start", ->
cypress.start(["--port=2121", "--config=pageLoadTimeout=1000"])
.then ->
expect(Events.start).to.be.calledWithMatch({
port: 2121,
config: {
pageLoadTimeout: 1000
port: 2121
}
})
it "passes filtered options to Project#open and sets cli config", ->
getConfig = sinon.spy(Project.prototype, "getConfig")
open = sinon.stub(Server.prototype, "open").resolves([])
process.env.CYPRESS_FILE_SERVER_FOLDER = "foo"
process.env.CYPRESS_BASE_URL = "http://localhost"
process.env.CYPRESS_port = "2222"
process.env.CYPRESS_responseTimeout = "5555"
process.env.CYPRESS_watch_for_file_changes = "false"
user.set({name: "brian", authToken: "<PASSWORD>"})
.then =>
settings.read(@todosPath)
.then (json) =>
## this should be overriden by the env argument
json.baseUrl = "http://localhost:8080"
settings.write(@todosPath, json)
.then =>
cypress.start([
"--port=2121",
"--config",
"pageLoadTimeout=1000",
"--foo=bar",
"--env=baz=baz"
])
.then =>
options = Events.start.firstCall.args[0]
Events.handleEvent(options, {}, {}, 123, "open:project", @todosPath)
.then =>
expect(getConfig).to.be.calledWithMatch({
port: 2121
pageLoadTimeout: 1000
report: false
env: { baz: "baz" }
})
expect(open).to.be.called
cfg = open.getCall(0).args[0]
expect(cfg.fileServerFolder).to.eq(path.join(@todosPath, "foo"))
expect(cfg.pageLoadTimeout).to.eq(1000)
expect(cfg.port).to.eq(2121)
expect(cfg.baseUrl).to.eq("http://localhost")
expect(cfg.watchForFileChanges).to.be.false
expect(cfg.responseTimeout).to.eq(5555)
expect(cfg.env.baz).to.eq("baz")
expect(cfg.env).not.to.have.property("fileServerFolder")
expect(cfg.env).not.to.have.property("port")
expect(cfg.env).not.to.have.property("BASE_URL")
expect(cfg.env).not.to.have.property("watchForFileChanges")
expect(cfg.env).not.to.have.property("responseTimeout")
expect(cfg.resolved.fileServerFolder).to.deep.eq({
value: "foo"
from: "env"
})
expect(cfg.resolved.pageLoadTimeout).to.deep.eq({
value: 1000
from: "cli"
})
expect(cfg.resolved.port).to.deep.eq({
value: 2121
from: "cli"
})
expect(cfg.resolved.baseUrl).to.deep.eq({
value: "http://localhost"
from: "env"
})
expect(cfg.resolved.watchForFileChanges).to.deep.eq({
value: false
from: "env"
})
expect(cfg.resolved.responseTimeout).to.deep.eq({
value: 5555
from: "env"
})
expect(cfg.resolved.env.baz).to.deep.eq({
value: "baz"
from: "cli"
})
it "sends warning when baseUrl cannot be verified", ->
bus = new EE()
event = { sender: { send: sinon.stub() } }
warning = { message: "Blah blah baseUrl blah blah" }
open = sinon.stub(Server.prototype, "open").resolves([2121, warning])
cypress.start(["--port=2121", "--config", "pageLoadTimeout=1000", "--foo=bar", "--env=baz=baz"])
.then =>
options = Events.start.firstCall.args[0]
Events.handleEvent(options, bus, event, 123, "on:project:warning")
Events.handleEvent(options, bus, event, 123, "open:project", @todosPath)
.then ->
expect(event.sender.send.withArgs("response").firstCall.args[1].data).to.eql(warning)
context "no args", ->
beforeEach ->
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(interactiveMode, "ready").resolves()
it "runs interactiveMode and does not exit", ->
cypress.start().then ->
expect(interactiveMode.ready).to.be.calledOnce
| true | require("../spec_helper")
_ = require("lodash")
os = require("os")
cp = require("child_process")
path = require("path")
EE = require("events")
http = require("http")
Promise = require("bluebird")
electron = require("electron")
commitInfo = require("@cypress/commit-info")
isForkPr = require("is-fork-pr")
Fixtures = require("../support/helpers/fixtures")
pkg = require("@packages/root")
launcher = require("@packages/launcher")
extension = require("@packages/extension")
fs = require("#{root}lib/util/fs")
connect = require("#{root}lib/util/connect")
ciProvider = require("#{root}lib/util/ci_provider")
settings = require("#{root}lib/util/settings")
Events = require("#{root}lib/gui/events")
Windows = require("#{root}lib/gui/windows")
record = require("#{root}lib/modes/record")
interactiveMode = require("#{root}lib/modes/interactive")
runMode = require("#{root}lib/modes/run")
api = require("#{root}lib/api")
cwd = require("#{root}lib/cwd")
user = require("#{root}lib/user")
config = require("#{root}lib/config")
cache = require("#{root}lib/cache")
errors = require("#{root}lib/errors")
plugins = require("#{root}lib/plugins")
cypress = require("#{root}lib/cypress")
Project = require("#{root}lib/project")
Server = require("#{root}lib/server")
Reporter = require("#{root}lib/reporter")
Watchers = require("#{root}lib/watchers")
browsers = require("#{root}lib/browsers")
videoCapture = require("#{root}lib/video_capture")
browserUtils = require("#{root}lib/browsers/utils")
openProject = require("#{root}lib/open_project")
env = require("#{root}lib/util/env")
appData = require("#{root}lib/util/app_data")
formStatePath = require("#{root}lib/util/saved_state").formStatePath
TYPICAL_BROWSERS = [
{
name: 'chrome',
displayName: 'Chrome',
version: '60.0.3112.101',
path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
majorVersion: '60'
}, {
name: 'chromium',
displayName: 'Chromium',
version: '49.0.2609.0',
path: '/Users/bmann/Downloads/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
majorVersion: '49'
}, {
name: 'canary',
displayName: 'Canary',
version: '62.0.3197.0',
path: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
majorVersion: '62'
}, {
name: 'electron',
version: '',
path: '',
majorVersion: '',
info: 'Electron is the default browser that comes with Cypress. This is the browser that runs in headless mode. Selecting this browser is useful when debugging. The version number indicates the underlying Chromium version that Electron uses.'
}
]
describe "lib/cypress", ->
require("mocha-banner").register()
beforeEach ->
@timeout(5000)
cache.__removeSync()
Fixtures.scaffold()
@todosPath = Fixtures.projectPath("todos")
@pristinePath = Fixtures.projectPath("pristine")
@noScaffolding = Fixtures.projectPath("no-scaffolding")
@recordPath = Fixtures.projectPath("record")
@pluginConfig = Fixtures.projectPath("plugin-config")
@pluginBrowser = Fixtures.projectPath("plugin-browser")
@idsPath = Fixtures.projectPath("ids")
## force cypress to call directly into main without
## spawning a separate process
sinon.stub(videoCapture, "start").resolves({})
sinon.stub(plugins, "init").resolves(undefined)
sinon.stub(cypress, "isCurrentlyRunningElectron").returns(true)
sinon.stub(extension, "setHostAndPath").resolves()
sinon.stub(launcher, "detect").resolves(TYPICAL_BROWSERS)
sinon.stub(process, "exit")
sinon.stub(Server.prototype, "reset")
sinon.spy(errors, "log")
sinon.spy(errors, "warning")
sinon.spy(console, "log")
@expectExitWith = (code) =>
expect(process.exit).to.be.calledWith(code)
@expectExitWithErr = (type, msg) ->
expect(errors.log).to.be.calledWithMatch({type: type})
expect(process.exit).to.be.calledWith(1)
if msg
err = errors.log.getCall(0).args[0]
expect(err.message).to.include(msg)
afterEach ->
Fixtures.remove()
## make sure every project
## we spawn is closed down
openProject.close()
context "--get-key", ->
it "writes out key and exits on success", ->
Promise.all([
user.set({name: "brian", authToken: "PI:PASSWORD:<PASSWORD>END_PI"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
expect(console.log).to.be.calledWith("new-key-123")
@expectExitWith(0)
it "logs error and exits when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("NOT_LOGGED_IN")
it "logs error and exits when project does not have an id", ->
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"})
.then =>
cypress.start(["--get-key", "--project=#{@pristinePath}"])
.then =>
@expectExitWithErr("NO_PROJECT_ID", @pristinePath)
it "logs error and exits when project could not be found at the path", ->
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"})
.then =>
cypress.start(["--get-key", "--project=path/to/no/project"])
.then =>
@expectExitWithErr("NO_PROJECT_FOUND_AT_PROJECT_ROOT", "path/to/no/project")
it "logs error and exits when project token cannot be fetched", ->
Promise.all([
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "getProjectToken")
.withArgs(@projectId, "auth-token-123")
.rejects(new Error())
cypress.start(["--get-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_FETCH_PROJECT_TOKEN")
context "--new-key", ->
it "writes out key and exits on success", ->
Promise.all([
user.set({name: "brian", authToken: "PI:PASSWORD:<PASSWORD>END_PI"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-token-123")
.resolves("new-key-123")
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
expect(console.log).to.be.calledWith("new-key-123")
@expectExitWith(0)
it "logs error and exits when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("NOT_LOGGED_IN")
it "logs error and exits when project does not have an id", ->
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"})
.then =>
cypress.start(["--new-key", "--project=#{@pristinePath}"])
.then =>
@expectExitWithErr("NO_PROJECT_ID", @pristinePath)
it "logs error and exits when project could not be found at the path", ->
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"})
.then =>
cypress.start(["--new-key", "--project=path/to/no/project"])
.then =>
@expectExitWithErr("NO_PROJECT_FOUND_AT_PROJECT_ROOT", "path/to/no/project")
it "logs error and exits when project token cannot be fetched", ->
Promise.all([
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"}),
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
.then =>
sinon.stub(api, "updateProjectToken")
.withArgs(@projectId, "auth-PI:PASSWORD:<PASSWORD>END_PI")
.rejects(new Error())
cypress.start(["--new-key", "--project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_CREATE_PROJECT_TOKEN")
context "--run-project", ->
beforeEach ->
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(runMode, "waitForSocketConnection")
sinon.stub(runMode, "listenForProjectEnd").resolves({stats: {failures: 0} })
sinon.stub(browsers, "open")
sinon.stub(commitInfo, "getRemoteOrigin").resolves("remoteOrigin")
it "runs project headlessly and exits with exit code 0", ->
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron")
@expectExitWith(0)
it "runs project headlessly and exits with exit code 10", ->
sinon.stub(runMode, "runSpecs").resolves({ totalFailed: 10 })
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWith(10)
it "does not generate a project id even if missing one", ->
sinon.stub(api, "createProject")
user.set({authToken: "PI:PASSWORD:<PASSWORD>END_PI"})
.then =>
cypress.start(["--run-project=#{@noScaffolding}"])
.then =>
@expectExitWith(0)
.then =>
expect(api.createProject).not.to.be.called
Project(@noScaffolding).getProjectId()
.then ->
throw new Error("should have caught error but did not")
.catch (err) ->
expect(err.type).to.eq("NO_PROJECT_ID")
it "does not add project to the global cache", ->
cache.getProjectRoots()
.then (projects) =>
## no projects in the cache
expect(projects.length).to.eq(0)
cypress.start(["--run-project=#{@todosPath}"])
.then ->
cache.getProjectRoots()
.then (projects) ->
## still not projects
expect(projects.length).to.eq(0)
it "runs project by relative spec and exits with status 0", ->
relativePath = path.relative(cwd(), @todosPath)
cypress.start([
"--run-project=#{@todosPath}",
"--spec=#{relativePath}/tests/test2.coffee"
])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {
url: "http://localhost:8888/__/#/tests/integration/test2.coffee"
})
@expectExitWith(0)
it "runs project by specific spec with default configuration", ->
cypress.start(["--run-project=#{@idsPath}", "--spec=#{@idsPath}/cypress/integration/bar.js", "--config", "port=2020"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {url: "http://localhost:2020/__/#/tests/integration/bar.js"})
@expectExitWith(0)
it "runs project by specific absolute spec and exits with status 0", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=#{@todosPath}/tests/test2.coffee"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {url: "http://localhost:8888/__/#/tests/integration/test2.coffee"})
@expectExitWith(0)
it "scaffolds out integration and example specs if they do not exist when not runMode", ->
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(cfg.integrationFolder)
.then ->
throw new Error("integrationFolder should not exist!")
.catch =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(cfg.integrationFolder)
.then =>
Promise.join(
fs.statAsync(path.join(cfg.integrationFolder, "examples", "actions.spec.js")),
fs.statAsync(path.join(cfg.integrationFolder, "examples", "files.spec.js")),
fs.statAsync(path.join(cfg.integrationFolder, "examples", "viewport.spec.js"))
)
it "does not scaffold when headless and exits with error when no existing project", ->
ensureDoesNotExist = (inspection, index) ->
if not inspection.isRejected()
throw new Error("File or folder was scaffolded at index: #{index}")
expect(inspection.reason()).to.have.property("code", "ENOENT")
Promise.all([
fs.statAsync(path.join(@pristinePath, "cypress")).reflect()
fs.statAsync(path.join(@pristinePath, "cypress.json")).reflect()
])
.each(ensureDoesNotExist)
.then =>
cypress.start(["--run-project=#{@pristinePath}"])
.then =>
Promise.all([
fs.statAsync(path.join(@pristinePath, "cypress")).reflect()
fs.statAsync(path.join(@pristinePath, "cypress.json")).reflect()
])
.each(ensureDoesNotExist)
.then =>
@expectExitWithErr("PROJECT_DOES_NOT_EXIST", @pristinePath)
it "does not scaffold integration or example specs when runMode", ->
settings.write(@pristinePath, {})
.then =>
cypress.start(["--run-project=#{@pristinePath}"])
.then =>
fs.statAsync(path.join(@pristinePath, "cypress", "integration"))
.then =>
throw new Error("integration folder should not exist!")
.catch {code: "ENOENT"}, =>
it "scaffolds out fixtures + files if they do not exist", ->
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(cfg.fixturesFolder)
.then ->
throw new Error("fixturesFolder should not exist!")
.catch =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(cfg.fixturesFolder)
.then =>
fs.statAsync path.join(cfg.fixturesFolder, "example.json")
it "scaffolds out support + files if they do not exist", ->
supportFolder = path.join(@pristinePath, "cypress/support")
config.get(@pristinePath)
.then (cfg) =>
fs.statAsync(supportFolder)
.then ->
throw new Error("supportFolder should not exist!")
.catch {code: "ENOENT"}, =>
cypress.start(["--run-project=#{@pristinePath}", "--no-runMode"])
.then =>
fs.statAsync(supportFolder)
.then =>
fs.statAsync path.join(supportFolder, "index.js")
.then =>
fs.statAsync path.join(supportFolder, "commands.js")
it "removes fixtures when they exist and fixturesFolder is false", (done) ->
config.get(@idsPath)
.then (@cfg) =>
fs.statAsync(@cfg.fixturesFolder)
.then =>
settings.read(@idsPath)
.then (json) =>
json.fixturesFolder = false
settings.write(@idsPath, json)
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
fs.statAsync(@cfg.fixturesFolder)
.then ->
throw new Error("fixturesFolder should not exist!")
.catch -> done()
it "runs project headlessly and displays gui", ->
cypress.start(["--run-project=#{@todosPath}", "--headed"])
.then =>
expect(browsers.open).to.be.calledWithMatch("electron", {
proxyServer: "http://localhost:8888"
show: true
})
@expectExitWith(0)
it "turns on reporting", ->
sinon.spy(Reporter, "create")
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(Reporter.create).to.be.calledWith("spec")
@expectExitWith(0)
it "can change the reporter to nyan", ->
sinon.spy(Reporter, "create")
cypress.start(["--run-project=#{@todosPath}", "--reporter=nyan"])
.then =>
expect(Reporter.create).to.be.calledWith("nyan")
@expectExitWith(0)
it "can change the reporter with cypress.json", ->
sinon.spy(Reporter, "create")
config.get(@idsPath)
.then (@cfg) =>
settings.read(@idsPath)
.then (json) =>
json.reporter = "dot"
settings.write(@idsPath, json)
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
expect(Reporter.create).to.be.calledWith("dot")
@expectExitWith(0)
it "runs tests even when user isn't logged in", ->
user.set({})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWith(0)
it "logs warning when projectId and key but no record option", ->
cypress.start(["--run-project=#{@todosPath}", "--key=asdf"])
.then =>
expect(errors.warning).to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).to.be.calledWithMatch("You also provided your Record Key, but you did not pass the --record flag.")
expect(console.log).to.be.calledWithMatch("cypress run --record")
expect(console.log).to.be.calledWithMatch("https://on.cypress.io/recording-project-runs")
it "does not log warning when no projectId", ->
cypress.start(["--run-project=#{@pristinePath}", "--key=PI:KEY:<KEY>END_PI"])
.then =>
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).not.to.be.calledWithMatch("cypress run --key <record_key>")
it "does not log warning when projectId but --record false", ->
cypress.start(["--run-project=#{@todosPath}", "--key=PI:KEY:<KEY>END_PI", "--record=false"])
.then =>
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", "abc123")
expect(console.log).not.to.be.calledWithMatch("cypress run --key <record_key>")
it "logs error when supportFile doesn't exist", ->
settings.write(@idsPath, {supportFile: "/does/not/exist"})
.then =>
cypress.start(["--run-project=#{@idsPath}"])
.then =>
@expectExitWithErr("SUPPORT_FILE_NOT_FOUND", "Your supportFile is set to '/does/not/exist',")
it "logs error when browser cannot be found", ->
browsers.open.restore()
cypress.start(["--run-project=#{@idsPath}", "--browser=foo"])
.then =>
@expectExitWithErr("BROWSER_NOT_FOUND")
## get all the error args
argsSet = errors.log.args
found1 = _.find argsSet, (args) ->
_.find args, (arg) ->
arg.message and arg.message.includes(
"Browser: 'foo' was not found on your system."
)
expect(found1, "foo should not be found").to.be.ok
found2 = _.find argsSet, (args) ->
_.find args, (arg) ->
arg.message and arg.message.includes(
"Available browsers found are: chrome, chromium, canary, electron"
)
expect(found2, "browser names should be listed").to.be.ok
it "logs error and exits when spec file was specified and does not exist", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=path/to/spec"])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "path/to/spec")
@expectExitWithErr("NO_SPECS_FOUND", "We searched for any files matching this glob pattern:")
it "logs error and exits when spec absolute file was specified and does not exist", ->
cypress.start([
"--run-project=#{@todosPath}",
"--spec=#{@todosPath}/tests/path/to/spec"
])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "tests/path/to/spec")
it "logs error and exits when no specs were found at all", ->
cypress.start([
"--run-project=#{@todosPath}",
"--config=integrationFolder=cypress/specs"
])
.then =>
@expectExitWithErr("NO_SPECS_FOUND", "We searched for any files inside of this folder:")
@expectExitWithErr("NO_SPECS_FOUND", "cypress/specs")
it "logs error and exits when project has cypress.json syntax error", ->
fs.writeFileAsync(@todosPath + "/cypress.json", "{'foo': 'bar}")
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("ERROR_READING_FILE", @todosPath)
it "logs error and exits when project has cypress.env.json syntax error", ->
fs.writeFileAsync(@todosPath + "/cypress.env.json", "{'foo': 'bar}")
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("ERROR_READING_FILE", @todosPath)
it "logs error and exits when project has invalid cypress.json values", ->
settings.write(@todosPath, {baseUrl: "localhost:9999"})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("SETTINGS_VALIDATION_ERROR", "cypress.json")
it "logs error and exits when project has invalid config values from the CLI", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=baseUrl=localhost:9999"
])
.then =>
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "localhost:9999")
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "We found an invalid configuration value")
it "logs error and exits when project has invalid config values from env vars", ->
process.env.CYPRESS_BASE_URL = "localhost:9999"
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "localhost:9999")
@expectExitWithErr("CONFIG_VALIDATION_ERROR", "We found an invalid configuration value")
it "logs error and exits when using an old configuration option: trashAssetsBeforeHeadlessRuns", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=trashAssetsBeforeHeadlessRuns=false"
])
.then =>
@expectExitWithErr("RENAMED_CONFIG_OPTION", "trashAssetsBeforeHeadlessRuns")
@expectExitWithErr("RENAMED_CONFIG_OPTION", "trashAssetsBeforeRuns")
it "logs error and exits when using an old configuration option: videoRecording", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=videoRecording=false"
])
.then =>
@expectExitWithErr("RENAMED_CONFIG_OPTION", "videoRecording")
@expectExitWithErr("RENAMED_CONFIG_OPTION", "video")
it "logs error and exits when using screenshotOnHeadlessFailure", ->
cypress.start([
"--run-project=#{@todosPath}"
"--config=screenshotOnHeadlessFailure=false"
])
.then =>
@expectExitWithErr("SCREENSHOT_ON_HEADLESS_FAILURE_REMOVED", "screenshotOnHeadlessFailure")
@expectExitWithErr("SCREENSHOT_ON_HEADLESS_FAILURE_REMOVED", "You now configure this behavior in your test code")
it "logs error and exits when baseUrl cannot be verified", ->
settings.write(@todosPath, {baseUrl: "http://localhost:90874"})
.then =>
cypress.start(["--run-project=#{@todosPath}"])
.then =>
@expectExitWithErr("CANNOT_CONNECT_BASE_URL", "http://localhost:90874")
## TODO: make sure we have integration tests around this
## for headed projects!
## also make sure we test the rest of the integration functionality
## for headed errors! <-- not unit tests, but integration tests!
it "logs error and exits when project folder has read permissions only and cannot write cypress.json", ->
if process.env.CI
## Gleb: disabling this because Node 8 docker image runs as root
## which makes accessing everything possible.
return
permissionsPath = path.resolve("./permissions")
cypressJson = path.join(permissionsPath, "cypress.json")
fs.outputFileAsync(cypressJson, "{}")
.then =>
## read only
fs.chmodAsync(permissionsPath, "555")
.then =>
cypress.start(["--run-project=#{permissionsPath}"])
.then =>
fs.chmodAsync(permissionsPath, "777")
.then =>
fs.removeAsync(permissionsPath)
.then =>
@expectExitWithErr("ERROR_READING_FILE", path.join(permissionsPath, "cypress.json"))
it "logs error and exits when reporter does not exist", ->
cypress.start(["--run-project=#{@todosPath}", "--reporter", "foobarbaz"])
.then =>
@expectExitWithErr("INVALID_REPORTER_NAME", "foobarbaz")
describe "state", ->
statePath = null
beforeEach ->
formStatePath(@todosPath)
.then (statePathStart) ->
statePath = appData.projectsPath(statePathStart)
fs.pathExists(statePath)
.then (found) ->
if found
fs.unlink(statePath)
afterEach ->
fs.unlink(statePath)
it "saves project state", ->
cypress.start(["--run-project=#{@todosPath}", "--spec=#{@todosPath}/tests/test2.coffee"])
.then =>
@expectExitWith(0)
.then ->
openProject.getProject().saveState()
.then () ->
fs.pathExists(statePath)
.then (found) ->
expect(found, "Finds saved stage file #{statePath}").to.be.true
describe "morgan", ->
it "sets morgan to false", ->
cypress.start(["--run-project=#{@todosPath}"])
.then =>
expect(openProject.getProject().cfg.morgan).to.be.false
@expectExitWith(0)
describe "config overrides", ->
it "can override default values", ->
cypress.start(["--run-project=#{@todosPath}", "--config=requestTimeout=1234,videoCompression=false"])
.then =>
cfg = openProject.getProject().cfg
expect(cfg.videoCompression).to.be.false
expect(cfg.requestTimeout).to.eq(1234)
expect(cfg.resolved.videoCompression).to.deep.eq({
value: false
from: "cli"
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234
from: "cli"
})
@expectExitWith(0)
it "can override values in plugins", ->
plugins.init.restore()
cypress.start([
"--run-project=#{@pluginConfig}", "--config=requestTimeout=1234,videoCompression=false"
"--env=foo=foo,bar=bar"
])
.then =>
cfg = openProject.getProject().cfg
expect(cfg.videoCompression).to.eq(20)
expect(cfg.defaultCommandTimeout).to.eq(500)
expect(cfg.env).to.deep.eq({
foo: "bar"
bar: "bar"
})
expect(cfg.resolved.videoCompression).to.deep.eq({
value: 20
from: "plugin"
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234
from: "cli"
})
expect(cfg.resolved.env.foo).to.deep.eq({
value: "bar"
from: "plugin"
})
expect(cfg.resolved.env.bar).to.deep.eq({
value: "bar"
from: "cli"
})
@expectExitWith(0)
describe "plugins", ->
beforeEach ->
plugins.init.restore()
browsers.open.restore()
ee = new EE()
ee.kill = ->
ee.emit("exit")
ee.close = ->
ee.emit("closed")
ee.isDestroyed = -> false
ee.loadURL = ->
ee.webContents = {
session: {
clearCache: sinon.stub().yieldsAsync()
}
}
sinon.stub(browserUtils, "launch").resolves(ee)
sinon.stub(Windows, "create").returns(ee)
sinon.stub(Windows, "automation")
context "before:browser:launch", ->
it "chrome", ->
cypress.start([
"--run-project=#{@pluginBrowser}"
"--browser=chrome"
])
.then =>
args = browserUtils.launch.firstCall.args
expect(args[0]).to.eq("chrome")
browserArgs = args[2]
expect(browserArgs).to.have.length(7)
expect(browserArgs.slice(0, 4)).to.deep.eq([
"chrome", "foo", "bar", "baz"
])
@expectExitWith(0)
it "electron", ->
cypress.start([
"--run-project=#{@pluginBrowser}"
"--browser=electron"
])
.then =>
expect(Windows.create).to.be.calledWith(@pluginBrowser, {
browser: "electron"
foo: "bar"
})
@expectExitWith(0)
describe "--port", ->
beforeEach ->
runMode.listenForProjectEnd.resolves({stats: {failures: 0} })
it "can change the default port to 5555", ->
listen = sinon.spy(http.Server.prototype, "listen")
open = sinon.spy(Server.prototype, "open")
cypress.start(["--run-project=#{@todosPath}", "--port=5555"])
.then =>
expect(openProject.getProject().cfg.port).to.eq(5555)
expect(listen).to.be.calledWith(5555)
expect(open).to.be.calledWithMatch({port: 5555})
@expectExitWith(0)
## TODO: handle PORT_IN_USE short integration test
it "logs error and exits when port is in use", ->
server = http.createServer()
server = Promise.promisifyAll(server)
server.listenAsync(5555)
.then =>
cypress.start(["--run-project=#{@todosPath}", "--port=5555"])
.then =>
@expectExitWithErr("PORT_IN_USE_LONG", "5555")
describe "--env", ->
beforeEach ->
process.env = _.omit(process.env, "CYPRESS_DEBUG")
runMode.listenForProjectEnd.resolves({stats: {failures: 0} })
it "can set specific environment variables", ->
cypress.start([
"--run-project=#{@todosPath}",
"--video=false"
"--env",
"version=0.12.1,foo=bar,host=http://localhost:8888,baz=quux=dolor"
])
.then =>
expect(openProject.getProject().cfg.env).to.deep.eq({
version: "0.12.1"
foo: "bar"
host: "http://localhost:8888"
baz: "quux=dolor"
})
@expectExitWith(0)
## most record mode logic is covered in e2e tests.
## we only need to cover the edge cases / warnings
context "--record or --ci", ->
beforeEach ->
sinon.stub(api, "createRun").resolves()
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(browsers, "open")
sinon.stub(runMode, "waitForSocketConnection")
sinon.stub(runMode, "waitForTestsToFinishRunning").resolves({
stats: {
tests: 1
passes: 2
failures: 3
pending: 4
skipped: 5
wallClockDuration: 6
}
tests: []
hooks: []
video: "path/to/video"
shouldUploadVideo: true
screenshots: []
config: {}
spec: {}
})
Promise.all([
## make sure we have no user object
user.set({})
Project.id(@todosPath)
.then (id) =>
@projectId = id
])
it "uses process.env.CYPRESS_PROJECT_ID", ->
sinon.stub(env, "get").withArgs("CYPRESS_PROJECT_ID").returns(@projectId)
cypress.start([
"--run-project=#{@noScaffolding}",
"--record",
"--key=PI:KEY:<PASSWORD>END_PI"
])
.then =>
expect(api.createRun).to.be.calledWithMatch({projectId: @projectId})
expect(errors.warning).not.to.be.called
@expectExitWith(3)
it "uses process.env.CYPRESS_RECORD_KEY", ->
sinon.stub(env, "get")
.withArgs("CYPRESS_PROJECT_ID").returns("foo-project-123")
.withArgs("CYPRESS_RECORD_KEY").returns("token")
cypress.start([
"--run-project=#{@noScaffolding}",
"--record"
])
.then =>
expect(api.createRun).to.be.calledWithMatch({
projectId: "foo-project-123"
recordKey: "token"
})
expect(errors.warning).not.to.be.called
@expectExitWith(3)
it "logs warning when using deprecated --ci arg and no env var", ->
cypress.start([
"--run-project=#{@recordPath}",
"--key=token-123",
"--ci"
])
.then =>
expect(errors.warning).to.be.calledWith("CYPRESS_CI_DEPRECATED")
expect(console.log).to.be.calledWithMatch("You are using the deprecated command:")
expect(console.log).to.be.calledWithMatch("cypress run --record --key <record_key>")
expect(errors.warning).not.to.be.calledWith("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION")
@expectExitWith(3)
it "logs warning when using deprecated --ci arg and env var", ->
sinon.stub(env, "get")
.withArgs("CYPRESS_CI_KEY")
.returns("PI:KEY:<KEY>END_PI")
cypress.start([
"--run-project=#{@recordPath}",
"--key=token-1PI:KEY:<KEY>END_PI3",
"--ci"
])
.then =>
expect(errors.warning).to.be.calledWith("CYPRESS_CI_DEPRECATED_ENV_VAR")
expect(console.log).to.be.calledWithMatch("You are using the deprecated command:")
expect(console.log).to.be.calledWithMatch("cypress ci")
expect(console.log).to.be.calledWithMatch("cypress run --record")
@expectExitWith(3)
context "--return-pkg", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs package.json and exits", ->
cypress.start(["--return-pkg"])
.then =>
expect(console.log).to.be.calledWithMatch('{"name":"cypress"')
@expectExitWith(0)
context "--version", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs version and exits", ->
cypress.start(["--version"])
.then =>
expect(console.log).to.be.calledWith(pkg.version)
@expectExitWith(0)
context "--smoke-test", ->
beforeEach ->
console.log.restore()
sinon.stub(console, "log")
it "logs pong value and exits", ->
cypress.start(["--smoke-test", "--ping=abc123"])
.then =>
expect(console.log).to.be.calledWith("abc123")
@expectExitWith(0)
context "interactive", ->
beforeEach ->
@win = {
on: sinon.stub()
webContents: {
on: sinon.stub()
}
}
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(Windows, "open").resolves(@win)
sinon.stub(Server.prototype, "startWebsockets")
sinon.spy(Events, "start")
sinon.stub(electron.ipcMain, "on")
it "passes options to interactiveMode.ready", ->
sinon.stub(interactiveMode, "ready")
cypress.start(["--updating", "--port=2121", "--config=pageLoadTimeout=1000"])
.then ->
expect(interactiveMode.ready).to.be.calledWithMatch({
updating: true
config: {
port: 2121
pageLoadTimeout: 1000
}
})
it "passes options to Events.start", ->
cypress.start(["--port=2121", "--config=pageLoadTimeout=1000"])
.then ->
expect(Events.start).to.be.calledWithMatch({
port: 2121,
config: {
pageLoadTimeout: 1000
port: 2121
}
})
it "passes filtered options to Project#open and sets cli config", ->
getConfig = sinon.spy(Project.prototype, "getConfig")
open = sinon.stub(Server.prototype, "open").resolves([])
process.env.CYPRESS_FILE_SERVER_FOLDER = "foo"
process.env.CYPRESS_BASE_URL = "http://localhost"
process.env.CYPRESS_port = "2222"
process.env.CYPRESS_responseTimeout = "5555"
process.env.CYPRESS_watch_for_file_changes = "false"
user.set({name: "brian", authToken: "PI:PASSWORD:<PASSWORD>END_PI"})
.then =>
settings.read(@todosPath)
.then (json) =>
## this should be overriden by the env argument
json.baseUrl = "http://localhost:8080"
settings.write(@todosPath, json)
.then =>
cypress.start([
"--port=2121",
"--config",
"pageLoadTimeout=1000",
"--foo=bar",
"--env=baz=baz"
])
.then =>
options = Events.start.firstCall.args[0]
Events.handleEvent(options, {}, {}, 123, "open:project", @todosPath)
.then =>
expect(getConfig).to.be.calledWithMatch({
port: 2121
pageLoadTimeout: 1000
report: false
env: { baz: "baz" }
})
expect(open).to.be.called
cfg = open.getCall(0).args[0]
expect(cfg.fileServerFolder).to.eq(path.join(@todosPath, "foo"))
expect(cfg.pageLoadTimeout).to.eq(1000)
expect(cfg.port).to.eq(2121)
expect(cfg.baseUrl).to.eq("http://localhost")
expect(cfg.watchForFileChanges).to.be.false
expect(cfg.responseTimeout).to.eq(5555)
expect(cfg.env.baz).to.eq("baz")
expect(cfg.env).not.to.have.property("fileServerFolder")
expect(cfg.env).not.to.have.property("port")
expect(cfg.env).not.to.have.property("BASE_URL")
expect(cfg.env).not.to.have.property("watchForFileChanges")
expect(cfg.env).not.to.have.property("responseTimeout")
expect(cfg.resolved.fileServerFolder).to.deep.eq({
value: "foo"
from: "env"
})
expect(cfg.resolved.pageLoadTimeout).to.deep.eq({
value: 1000
from: "cli"
})
expect(cfg.resolved.port).to.deep.eq({
value: 2121
from: "cli"
})
expect(cfg.resolved.baseUrl).to.deep.eq({
value: "http://localhost"
from: "env"
})
expect(cfg.resolved.watchForFileChanges).to.deep.eq({
value: false
from: "env"
})
expect(cfg.resolved.responseTimeout).to.deep.eq({
value: 5555
from: "env"
})
expect(cfg.resolved.env.baz).to.deep.eq({
value: "baz"
from: "cli"
})
it "sends warning when baseUrl cannot be verified", ->
bus = new EE()
event = { sender: { send: sinon.stub() } }
warning = { message: "Blah blah baseUrl blah blah" }
open = sinon.stub(Server.prototype, "open").resolves([2121, warning])
cypress.start(["--port=2121", "--config", "pageLoadTimeout=1000", "--foo=bar", "--env=baz=baz"])
.then =>
options = Events.start.firstCall.args[0]
Events.handleEvent(options, bus, event, 123, "on:project:warning")
Events.handleEvent(options, bus, event, 123, "open:project", @todosPath)
.then ->
expect(event.sender.send.withArgs("response").firstCall.args[1].data).to.eql(warning)
context "no args", ->
beforeEach ->
sinon.stub(electron.app, "on").withArgs("ready").yieldsAsync()
sinon.stub(interactiveMode, "ready").resolves()
it "runs interactiveMode and does not exit", ->
cypress.start().then ->
expect(interactiveMode.ready).to.be.calledOnce
|
[
{
"context": "_user=process.env.HUBOT_JENKINS_USER\njenkins_pass=process.env.HUBOT_JENKINS_PASSWORD\njenkins_api=process.env.HUB",
"end": 1583,
"score": 0.9293644428253174,
"start": 1572,
"tag": "PASSWORD",
"value": "process.env"
},
{
"context": "s.env.HUBOT_JENKINS_USER\njenkins_pas... | scripts/jenkins/scripts-msteams/installPlugin.coffee | CognizantOneDevOps/OnBot | 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.
#-------------------------------------------------------------------------------
#Description:
#Description:
# installs the given plugins to jenkins
#
#Configuration:
# HUBOT_NAME
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
# install <plugin1> <plugin2>... in jenkins -> install the given plugins to jenkins
# Example~
# install ccm msbuild mstest in jenkins
# (The above command will install ccm, msbuld and mstest plugin in jenkins)
#
#Depencencies:
# "request":"2.81.0"
# "elasticSearch": "^0.9.2"
request = require('request')
index = require('./index')
readjson = require './readjson.js'
finaljson=" ";
generate_id = require('./mongoConnt');
crumb = require('./jenkinscrumb.js')
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=process.env.HUBOT_JENKINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
crumbvalue = ''
options = {
url: '',
auth: {
'user': jenkins_user,
'pass': jenkins_api
},
method: 'POST',
headers:{}};
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
console.log stdout
if(stdout)
crumbvalue=stdout
post = (recipient, data) ->
options = {method: "POST", url: recipient, json: data}
request.post options, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /install (.+) in jenkins/i, (msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
finaljson=stdout;
userplugin=[]
userplugin=msg.match[1].split(' ')
if stdout.install_plugin.workflowflag
generate_id.getNextSequence (err,id) ->
tckid=id
console.log(tckid);
console.log(msg.toString())
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.install_plugin.admin,podIp:process.env.MY_POD_IP,userplugin:userplugin,"callback_id":"installplugin",msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Requested to install the plugins in jenkins","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to install the following plugins in jenkins:\n'+payload.userplugin,"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approved","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.install_plugin.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.install_plugin.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
else
pluginString=[]
plugins=[]
flag=0
pluginString=msg.match[1].split(' ')
url=jenkins_url+"/pluginManager/installNecessaryPlugins"
pluginData="<jenkins>"
for i in [0...pluginString.length]
pluginData=pluginData+"<install plugin=\""+pluginString[i]+"@latest\" /></jenkins>"
options = {
auth: {
'user': jenkins_user,
'pass': jenkins_pass
},
method: 'POST',
url: url,
headers: {"Content-Type": "text/xml"},
body: pluginData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = jenkins_api
request.post options, (error, response, body) ->
if(response.statusCode!=302)
dt="Error in installing"
msg.send dt
setTimeout (->index.passData dt),1000
else
setTimeout ( -> getInstallations()),1000
pluginData="<jenkins>"
getInstallations = () ->
options.url=jenkins_url+"/pluginManager/api/json?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins"
options.headers={"Content-Type": "text/json"}
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = jenkins_api
request.post options, (error, response, body) ->
plugins=JSON.parse(body).plugins
setTimeout ( -> check plugins),2000
check = (plugins) ->
if(plugins.length!=0)
for i in [0...pluginString.length]
for j in [0...plugins.length]
console.log plugins[j].shortName
if(pluginString[i]==plugins[j].shortName)
dt=pluginString[i]+": Installed successfully"
msg.send dt
setTimeout (->index.passData dt),1000
message = msg.match[0]
actionmsg = "jenkins plugin installed"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
flag=1
break
if(flag==0)
dt=pluginString[i]+": Error in installation. Verify the pluginID and try again"
msg.send dt
setTimeout (->index.passData dt),1000
flag=0
#the following code handles the approval flow of the command
robot.router.post '/installplugin', (req, response) ->
console.log(' INSIDE installplugin')
recipientid=req.body.userid
dt = {"text":"","title":""}
if(req.body.action=='Approved')
dt.title=req.body.approver+" approved installation of plugins "+req.body.userplugin+", requested by "+req.body.username+"\n"
post recipientid, dt
index.passData dt
pluginString=[]
plugins=[]
flag=0
pluginString=req.body.userplugin
url=jenkins_url+"/pluginManager/installNecessaryPlugins"
pluginData="<jenkins>"
for i in [0...pluginString.length]
pluginData=pluginData+"<install plugin=\""+pluginString[i]+"@latest\" /></jenkins>"
options = {
auth: {
'user': jenkins_user,
'pass': jenkins_pass
},
method: 'POST',
url: url,
headers: {"Content-Type": "text/xml"},
body: pluginData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
request.post options, (error, response, body) ->
if(response.statusCode!=302)
dt.text="error in installing"
post recipientid, dt
setTimeout (->index.passData dt),1000
else
setTimeout ( -> getInstallations()),1000
pluginData="<jenkins>"
getInstallations = () ->
options.url=jenkins_url+"/pluginManager/api/json?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins"
options.headers={"Content-Type": "text/json"}
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
request.post options, (error, response, body) ->
plugins=JSON.parse(body).plugins
setTimeout ( -> check plugins),2000
check = (plugins) ->
if(plugins.length!=0)
for i in [0...pluginString.length]
for j in [0...plugins.length]
console.log plugins[j].shortName
if(pluginString[i]==plugins[j].shortName)
dt.text=pluginString[i]+": installed successfully"
post recipientid, dt
setTimeout (->index.passData dt),1000
message = "install "+pluginString+"in jenkins"
actionmsg = "jenkins plugin installed"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
flag=1
break
if(flag==0)
dt.text=pluginString[i]+": error in installation. verify the pluginid and try again"
post recipientid, dt
setTimeout (->index.passData dt),1000
flag=0
else
dt.title="the jenkins plugin installation request from "+req.body.username+" was rejected by "+req.body.approver
post recipientid, dt
setTimeout (->index.passData dt),1000
| 54184 | #-------------------------------------------------------------------------------
# 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.
#-------------------------------------------------------------------------------
#Description:
#Description:
# installs the given plugins to jenkins
#
#Configuration:
# HUBOT_NAME
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
# install <plugin1> <plugin2>... in jenkins -> install the given plugins to jenkins
# Example~
# install ccm msbuild mstest in jenkins
# (The above command will install ccm, msbuld and mstest plugin in jenkins)
#
#Depencencies:
# "request":"2.81.0"
# "elasticSearch": "^0.9.2"
request = require('request')
index = require('./index')
readjson = require './readjson.js'
finaljson=" ";
generate_id = require('./mongoConnt');
crumb = require('./jenkinscrumb.js')
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=<PASSWORD>.<PASSWORD>
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
crumbvalue = ''
options = {
url: '',
auth: {
'user': jenkins_user,
'pass': <PASSWORD>
},
method: 'POST',
headers:{}};
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
console.log stdout
if(stdout)
crumbvalue=stdout
post = (recipient, data) ->
options = {method: "POST", url: recipient, json: data}
request.post options, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /install (.+) in jenkins/i, (msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
finaljson=stdout;
userplugin=[]
userplugin=msg.match[1].split(' ')
if stdout.install_plugin.workflowflag
generate_id.getNextSequence (err,id) ->
tckid=id
console.log(tckid);
console.log(msg.toString())
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.install_plugin.admin,podIp:process.env.MY_POD_IP,userplugin:userplugin,"callback_id":"installplugin",msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Requested to install the plugins in jenkins","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to install the following plugins in jenkins:\n'+payload.userplugin,"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approved","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.install_plugin.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.install_plugin.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
else
pluginString=[]
plugins=[]
flag=0
pluginString=msg.match[1].split(' ')
url=jenkins_url+"/pluginManager/installNecessaryPlugins"
pluginData="<jenkins>"
for i in [0...pluginString.length]
pluginData=pluginData+"<install plugin=\""+pluginString[i]+"@latest\" /></jenkins>"
options = {
auth: {
'user': jenkins_user,
'pass': <PASSWORD>
},
method: 'POST',
url: url,
headers: {"Content-Type": "text/xml"},
body: pluginData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = <PASSWORD>
request.post options, (error, response, body) ->
if(response.statusCode!=302)
dt="Error in installing"
msg.send dt
setTimeout (->index.passData dt),1000
else
setTimeout ( -> getInstallations()),1000
pluginData="<jenkins>"
getInstallations = () ->
options.url=jenkins_url+"/pluginManager/api/json?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins"
options.headers={"Content-Type": "text/json"}
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = <PASSWORD>
request.post options, (error, response, body) ->
plugins=JSON.parse(body).plugins
setTimeout ( -> check plugins),2000
check = (plugins) ->
if(plugins.length!=0)
for i in [0...pluginString.length]
for j in [0...plugins.length]
console.log plugins[j].shortName
if(pluginString[i]==plugins[j].shortName)
dt=pluginString[i]+": Installed successfully"
msg.send dt
setTimeout (->index.passData dt),1000
message = msg.match[0]
actionmsg = "jenkins plugin installed"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
flag=1
break
if(flag==0)
dt=pluginString[i]+": Error in installation. Verify the pluginID and try again"
msg.send dt
setTimeout (->index.passData dt),1000
flag=0
#the following code handles the approval flow of the command
robot.router.post '/installplugin', (req, response) ->
console.log(' INSIDE installplugin')
recipientid=req.body.userid
dt = {"text":"","title":""}
if(req.body.action=='Approved')
dt.title=req.body.approver+" approved installation of plugins "+req.body.userplugin+", requested by "+req.body.username+"\n"
post recipientid, dt
index.passData dt
pluginString=[]
plugins=[]
flag=0
pluginString=req.body.userplugin
url=jenkins_url+"/pluginManager/installNecessaryPlugins"
pluginData="<jenkins>"
for i in [0...pluginString.length]
pluginData=pluginData+"<install plugin=\""+pluginString[i]+"@latest\" /></jenkins>"
options = {
auth: {
'user': jenkins_user,
'pass': <PASSWORD>
},
method: 'POST',
url: url,
headers: {"Content-Type": "text/xml"},
body: pluginData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
request.post options, (error, response, body) ->
if(response.statusCode!=302)
dt.text="error in installing"
post recipientid, dt
setTimeout (->index.passData dt),1000
else
setTimeout ( -> getInstallations()),1000
pluginData="<jenkins>"
getInstallations = () ->
options.url=jenkins_url+"/pluginManager/api/json?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins"
options.headers={"Content-Type": "text/json"}
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
request.post options, (error, response, body) ->
plugins=JSON.parse(body).plugins
setTimeout ( -> check plugins),2000
check = (plugins) ->
if(plugins.length!=0)
for i in [0...pluginString.length]
for j in [0...plugins.length]
console.log plugins[j].shortName
if(pluginString[i]==plugins[j].shortName)
dt.text=pluginString[i]+": installed successfully"
post recipientid, dt
setTimeout (->index.passData dt),1000
message = "install "+pluginString+"in jenkins"
actionmsg = "jenkins plugin installed"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
flag=1
break
if(flag==0)
dt.text=pluginString[i]+": error in installation. verify the pluginid and try again"
post recipientid, dt
setTimeout (->index.passData dt),1000
flag=0
else
dt.title="the jenkins plugin installation request from "+req.body.username+" was rejected by "+req.body.approver
post recipientid, dt
setTimeout (->index.passData dt),1000
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
#Description:
#Description:
# installs the given plugins to jenkins
#
#Configuration:
# HUBOT_NAME
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
# install <plugin1> <plugin2>... in jenkins -> install the given plugins to jenkins
# Example~
# install ccm msbuild mstest in jenkins
# (The above command will install ccm, msbuld and mstest plugin in jenkins)
#
#Depencencies:
# "request":"2.81.0"
# "elasticSearch": "^0.9.2"
request = require('request')
index = require('./index')
readjson = require './readjson.js'
finaljson=" ";
generate_id = require('./mongoConnt');
crumb = require('./jenkinscrumb.js')
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
crumbvalue = ''
options = {
url: '',
auth: {
'user': jenkins_user,
'pass': PI:PASSWORD:<PASSWORD>END_PI
},
method: 'POST',
headers:{}};
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
console.log stdout
if(stdout)
crumbvalue=stdout
post = (recipient, data) ->
options = {method: "POST", url: recipient, json: data}
request.post options, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /install (.+) in jenkins/i, (msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
finaljson=stdout;
userplugin=[]
userplugin=msg.match[1].split(' ')
if stdout.install_plugin.workflowflag
generate_id.getNextSequence (err,id) ->
tckid=id
console.log(tckid);
console.log(msg.toString())
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.install_plugin.admin,podIp:process.env.MY_POD_IP,userplugin:userplugin,"callback_id":"installplugin",msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Requested to install the plugins in jenkins","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to install the following plugins in jenkins:\n'+payload.userplugin,"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approved","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.install_plugin.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.install_plugin.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
else
pluginString=[]
plugins=[]
flag=0
pluginString=msg.match[1].split(' ')
url=jenkins_url+"/pluginManager/installNecessaryPlugins"
pluginData="<jenkins>"
for i in [0...pluginString.length]
pluginData=pluginData+"<install plugin=\""+pluginString[i]+"@latest\" /></jenkins>"
options = {
auth: {
'user': jenkins_user,
'pass': PI:PASSWORD:<PASSWORD>END_PI
},
method: 'POST',
url: url,
headers: {"Content-Type": "text/xml"},
body: pluginData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI
request.post options, (error, response, body) ->
if(response.statusCode!=302)
dt="Error in installing"
msg.send dt
setTimeout (->index.passData dt),1000
else
setTimeout ( -> getInstallations()),1000
pluginData="<jenkins>"
getInstallations = () ->
options.url=jenkins_url+"/pluginManager/api/json?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins"
options.headers={"Content-Type": "text/json"}
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI
request.post options, (error, response, body) ->
plugins=JSON.parse(body).plugins
setTimeout ( -> check plugins),2000
check = (plugins) ->
if(plugins.length!=0)
for i in [0...pluginString.length]
for j in [0...plugins.length]
console.log plugins[j].shortName
if(pluginString[i]==plugins[j].shortName)
dt=pluginString[i]+": Installed successfully"
msg.send dt
setTimeout (->index.passData dt),1000
message = msg.match[0]
actionmsg = "jenkins plugin installed"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
flag=1
break
if(flag==0)
dt=pluginString[i]+": Error in installation. Verify the pluginID and try again"
msg.send dt
setTimeout (->index.passData dt),1000
flag=0
#the following code handles the approval flow of the command
robot.router.post '/installplugin', (req, response) ->
console.log(' INSIDE installplugin')
recipientid=req.body.userid
dt = {"text":"","title":""}
if(req.body.action=='Approved')
dt.title=req.body.approver+" approved installation of plugins "+req.body.userplugin+", requested by "+req.body.username+"\n"
post recipientid, dt
index.passData dt
pluginString=[]
plugins=[]
flag=0
pluginString=req.body.userplugin
url=jenkins_url+"/pluginManager/installNecessaryPlugins"
pluginData="<jenkins>"
for i in [0...pluginString.length]
pluginData=pluginData+"<install plugin=\""+pluginString[i]+"@latest\" /></jenkins>"
options = {
auth: {
'user': jenkins_user,
'pass': PI:PASSWORD:<PASSWORD>END_PI
},
method: 'POST',
url: url,
headers: {"Content-Type": "text/xml"},
body: pluginData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
request.post options, (error, response, body) ->
if(response.statusCode!=302)
dt.text="error in installing"
post recipientid, dt
setTimeout (->index.passData dt),1000
else
setTimeout ( -> getInstallations()),1000
pluginData="<jenkins>"
getInstallations = () ->
options.url=jenkins_url+"/pluginManager/api/json?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins"
options.headers={"Content-Type": "text/json"}
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
request.post options, (error, response, body) ->
plugins=JSON.parse(body).plugins
setTimeout ( -> check plugins),2000
check = (plugins) ->
if(plugins.length!=0)
for i in [0...pluginString.length]
for j in [0...plugins.length]
console.log plugins[j].shortName
if(pluginString[i]==plugins[j].shortName)
dt.text=pluginString[i]+": installed successfully"
post recipientid, dt
setTimeout (->index.passData dt),1000
message = "install "+pluginString+"in jenkins"
actionmsg = "jenkins plugin installed"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
flag=1
break
if(flag==0)
dt.text=pluginString[i]+": error in installation. verify the pluginid and try again"
post recipientid, dt
setTimeout (->index.passData dt),1000
flag=0
else
dt.title="the jenkins plugin installation request from "+req.body.username+" was rejected by "+req.body.approver
post recipientid, dt
setTimeout (->index.passData dt),1000
|
[
{
"context": " current: 0\n songs: [\n { artist: 'Taylor Swift', title: 'Shake It Off' }\n { artist: 'Ta",
"end": 2510,
"score": 0.9990631937980652,
"start": 2498,
"tag": "NAME",
"value": "Taylor Swift"
},
{
"context": "ft', title: 'Shake It Off' }\n ... | test/spec/controllers/main.coffee | jviotti/musync-frontend | 2 | 'use strict'
describe 'Controller: MainCtrl', ->
beforeEach module 'MuSyncApp'
MainCtrl = {}
scope = {}
# Initialize the controller and a mock scope
beforeEach inject ($controller, $rootScope) ->
scope = $rootScope.$new()
MainCtrl = $controller 'MainCtrl', {
$scope: scope
}
describe '.playSong()', ->
beforeEach ->
scope.playlist =
current: 1
playStart: Date.now() - 100000
it 'should set playlist.current to the index', ->
expect(scope.playlist.current).toEqual(1)
scope.playSong(3)
expect(scope.playlist.current).toEqual(3)
it 'should set playlist.playStart to the current time', ->
expect(scope.playlist.playStart).not.toBeCloseTo(Date.now(), 5)
scope.playSong(3)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe '.stop()', ->
beforeEach ->
scope.playlist =
current: 1
playStart: Date.now()
it 'should set playlist.current to null', ->
expect(scope.playlist.current).not.toBeNull()
scope.stop()
expect(scope.playlist.current).toBeNull()
it 'should set playlist.playStart to null', ->
expect(scope.playlist.playStart).not.toBeNull()
scope.stop()
expect(scope.playlist.playStart).toBeNull()
describe '.isPlaying()', ->
it 'should return true if playlist.current is defined', ->
scope.playlist.current = 1
expect(scope.isPlaying()).toBe(true)
it 'should return false if playlist.current is not defined', ->
scope.playlist.current = null
expect(scope.isPlaying()).toBe(false)
describe '.play()', ->
it 'should set playlist.current to zero', ->
scope.play()
expect(scope.playlist.current).toEqual(0)
it 'should set playlist.playStart to the current time', ->
scope.play()
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe '.hasNextSong()', ->
it 'should return false if no songs array', ->
scope.playlist.songs = null
expect(scope.hasNextSong()).toBe(false)
it 'should return false if no current', ->
scope.playlist.current = null
expect(scope.hasNextSong()).toBe(false)
it 'should return false if no songs', ->
scope.playlist.songs = []
scope.playlist.current = 0
expect(scope.hasNextSong()).toBe(false)
it 'should return true if there is a next song', ->
scope.playlist =
current: 0
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
expect(scope.hasNextSong()).toBe(true)
it 'should return true if there is not a next song', ->
scope.playlist =
current: 1
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
expect(scope.hasNextSong()).toBe(false)
describe '.hasPreviousSong()', ->
it 'should return false if no songs array', ->
scope.playlist.songs = null
expect(scope.hasPreviousSong()).toBe(false)
it 'should return false if no current', ->
scope.playlist.current = null
expect(scope.hasPreviousSong()).toBe(false)
it 'should return false if no songs', ->
scope.playlist.songs = []
scope.playlist.current = 0
expect(scope.hasPreviousSong()).toBe(false)
it 'should return true if there is a previous song', ->
scope.playlist =
current: 1
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
expect(scope.hasPreviousSong()).toBe(true)
it 'should return true if there is not a previous song', ->
scope.playlist =
current: 0
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
expect(scope.hasPreviousSong()).toBe(false)
describe '.addSong()', ->
it 'should add a song at the end of the list', ->
scope.playlist.songs = [
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
scope.newSong = { artist: 'Taylor Swift', title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs).toEqual [
{ artist: 'Taylor Swift', title: 'Blank Space' }
{ artist: 'Taylor Swift', title: 'Shake It Off' }
]
it 'should erase newSong', ->
scope.newSong = { artist: 'Taylor Swift', title: 'Shake It Off' }
scope.addSong()
expect(scope.newSong).toEqual({})
it 'should not add anything if no artist', ->
scope.playlist.songs = []
scope.newSong = { title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if artist is an empty string', ->
scope.playlist.songs = []
scope.newSong = { artist: '', title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if no title', ->
scope.playlist.songs = []
scope.newSong = { artist: 'Taylor Swift' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if title is an empty string', ->
scope.playlist.songs = []
scope.newSong = { artist: 'Taylor Swift', title: '' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
describe '.remove()', ->
it 'should remove the song from the playlist', ->
scope.playlist =
current: 0
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.songs).toEqual [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
]
it 'should replay the current song', ->
scope.playlist =
current: 0
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
it 'should not restart playStart if no current', ->
scope.playlist =
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.current).toBeUndefined()
expect(scope.playlist.playStart).toBeUndefined()
describe '.previous()', ->
describe 'if has a previous song', ->
beforeEach ->
scope.playlist =
current: 1
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
it 'should play the previous song', ->
scope.previous()
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe 'if no previous song', ->
beforeEach ->
scope.playlist =
current: 0
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
it 'should do nothing', ->
scope.previous()
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeUndefined()
describe '.next()', ->
describe 'if has a next song', ->
beforeEach ->
scope.playlist =
current: 0
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
it 'should play the next song', ->
scope.next()
expect(scope.playlist.current).toEqual(1)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe 'if no next song', ->
beforeEach ->
scope.playlist =
current: 1
songs: [
{ artist: 'Taylor Swift', title: 'Shake It Off' }
{ artist: 'Taylor Swift', title: 'Blank Space' }
]
it 'should do nothing', ->
scope.next()
expect(scope.playlist.current).toEqual(1)
expect(scope.playlist.playStart).toBeUndefined()
| 144695 | 'use strict'
describe 'Controller: MainCtrl', ->
beforeEach module 'MuSyncApp'
MainCtrl = {}
scope = {}
# Initialize the controller and a mock scope
beforeEach inject ($controller, $rootScope) ->
scope = $rootScope.$new()
MainCtrl = $controller 'MainCtrl', {
$scope: scope
}
describe '.playSong()', ->
beforeEach ->
scope.playlist =
current: 1
playStart: Date.now() - 100000
it 'should set playlist.current to the index', ->
expect(scope.playlist.current).toEqual(1)
scope.playSong(3)
expect(scope.playlist.current).toEqual(3)
it 'should set playlist.playStart to the current time', ->
expect(scope.playlist.playStart).not.toBeCloseTo(Date.now(), 5)
scope.playSong(3)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe '.stop()', ->
beforeEach ->
scope.playlist =
current: 1
playStart: Date.now()
it 'should set playlist.current to null', ->
expect(scope.playlist.current).not.toBeNull()
scope.stop()
expect(scope.playlist.current).toBeNull()
it 'should set playlist.playStart to null', ->
expect(scope.playlist.playStart).not.toBeNull()
scope.stop()
expect(scope.playlist.playStart).toBeNull()
describe '.isPlaying()', ->
it 'should return true if playlist.current is defined', ->
scope.playlist.current = 1
expect(scope.isPlaying()).toBe(true)
it 'should return false if playlist.current is not defined', ->
scope.playlist.current = null
expect(scope.isPlaying()).toBe(false)
describe '.play()', ->
it 'should set playlist.current to zero', ->
scope.play()
expect(scope.playlist.current).toEqual(0)
it 'should set playlist.playStart to the current time', ->
scope.play()
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe '.hasNextSong()', ->
it 'should return false if no songs array', ->
scope.playlist.songs = null
expect(scope.hasNextSong()).toBe(false)
it 'should return false if no current', ->
scope.playlist.current = null
expect(scope.hasNextSong()).toBe(false)
it 'should return false if no songs', ->
scope.playlist.songs = []
scope.playlist.current = 0
expect(scope.hasNextSong()).toBe(false)
it 'should return true if there is a next song', ->
scope.playlist =
current: 0
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
expect(scope.hasNextSong()).toBe(true)
it 'should return true if there is not a next song', ->
scope.playlist =
current: 1
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
expect(scope.hasNextSong()).toBe(false)
describe '.hasPreviousSong()', ->
it 'should return false if no songs array', ->
scope.playlist.songs = null
expect(scope.hasPreviousSong()).toBe(false)
it 'should return false if no current', ->
scope.playlist.current = null
expect(scope.hasPreviousSong()).toBe(false)
it 'should return false if no songs', ->
scope.playlist.songs = []
scope.playlist.current = 0
expect(scope.hasPreviousSong()).toBe(false)
it 'should return true if there is a previous song', ->
scope.playlist =
current: 1
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
expect(scope.hasPreviousSong()).toBe(true)
it 'should return true if there is not a previous song', ->
scope.playlist =
current: 0
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
expect(scope.hasPreviousSong()).toBe(false)
describe '.addSong()', ->
it 'should add a song at the end of the list', ->
scope.playlist.songs = [
{ artist: '<NAME>', title: 'Blank Space' }
]
scope.newSong = { artist: '<NAME>', title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs).toEqual [
{ artist: '<NAME>', title: 'Blank Space' }
{ artist: '<NAME>', title: 'Shake It Off' }
]
it 'should erase newSong', ->
scope.newSong = { artist: '<NAME>', title: 'Shake It Off' }
scope.addSong()
expect(scope.newSong).toEqual({})
it 'should not add anything if no artist', ->
scope.playlist.songs = []
scope.newSong = { title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if artist is an empty string', ->
scope.playlist.songs = []
scope.newSong = { artist: '', title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if no title', ->
scope.playlist.songs = []
scope.newSong = { artist: '<NAME>' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if title is an empty string', ->
scope.playlist.songs = []
scope.newSong = { artist: '<NAME>', title: '' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
describe '.remove()', ->
it 'should remove the song from the playlist', ->
scope.playlist =
current: 0
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.songs).toEqual [
{ artist: '<NAME>', title: 'Shake It Off' }
]
it 'should replay the current song', ->
scope.playlist =
current: 0
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
it 'should not restart playStart if no current', ->
scope.playlist =
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.current).toBeUndefined()
expect(scope.playlist.playStart).toBeUndefined()
describe '.previous()', ->
describe 'if has a previous song', ->
beforeEach ->
scope.playlist =
current: 1
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
it 'should play the previous song', ->
scope.previous()
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe 'if no previous song', ->
beforeEach ->
scope.playlist =
current: 0
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
it 'should do nothing', ->
scope.previous()
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeUndefined()
describe '.next()', ->
describe 'if has a next song', ->
beforeEach ->
scope.playlist =
current: 0
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
it 'should play the next song', ->
scope.next()
expect(scope.playlist.current).toEqual(1)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe 'if no next song', ->
beforeEach ->
scope.playlist =
current: 1
songs: [
{ artist: '<NAME>', title: 'Shake It Off' }
{ artist: '<NAME>', title: 'Blank Space' }
]
it 'should do nothing', ->
scope.next()
expect(scope.playlist.current).toEqual(1)
expect(scope.playlist.playStart).toBeUndefined()
| true | 'use strict'
describe 'Controller: MainCtrl', ->
beforeEach module 'MuSyncApp'
MainCtrl = {}
scope = {}
# Initialize the controller and a mock scope
beforeEach inject ($controller, $rootScope) ->
scope = $rootScope.$new()
MainCtrl = $controller 'MainCtrl', {
$scope: scope
}
describe '.playSong()', ->
beforeEach ->
scope.playlist =
current: 1
playStart: Date.now() - 100000
it 'should set playlist.current to the index', ->
expect(scope.playlist.current).toEqual(1)
scope.playSong(3)
expect(scope.playlist.current).toEqual(3)
it 'should set playlist.playStart to the current time', ->
expect(scope.playlist.playStart).not.toBeCloseTo(Date.now(), 5)
scope.playSong(3)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe '.stop()', ->
beforeEach ->
scope.playlist =
current: 1
playStart: Date.now()
it 'should set playlist.current to null', ->
expect(scope.playlist.current).not.toBeNull()
scope.stop()
expect(scope.playlist.current).toBeNull()
it 'should set playlist.playStart to null', ->
expect(scope.playlist.playStart).not.toBeNull()
scope.stop()
expect(scope.playlist.playStart).toBeNull()
describe '.isPlaying()', ->
it 'should return true if playlist.current is defined', ->
scope.playlist.current = 1
expect(scope.isPlaying()).toBe(true)
it 'should return false if playlist.current is not defined', ->
scope.playlist.current = null
expect(scope.isPlaying()).toBe(false)
describe '.play()', ->
it 'should set playlist.current to zero', ->
scope.play()
expect(scope.playlist.current).toEqual(0)
it 'should set playlist.playStart to the current time', ->
scope.play()
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe '.hasNextSong()', ->
it 'should return false if no songs array', ->
scope.playlist.songs = null
expect(scope.hasNextSong()).toBe(false)
it 'should return false if no current', ->
scope.playlist.current = null
expect(scope.hasNextSong()).toBe(false)
it 'should return false if no songs', ->
scope.playlist.songs = []
scope.playlist.current = 0
expect(scope.hasNextSong()).toBe(false)
it 'should return true if there is a next song', ->
scope.playlist =
current: 0
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
expect(scope.hasNextSong()).toBe(true)
it 'should return true if there is not a next song', ->
scope.playlist =
current: 1
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
expect(scope.hasNextSong()).toBe(false)
describe '.hasPreviousSong()', ->
it 'should return false if no songs array', ->
scope.playlist.songs = null
expect(scope.hasPreviousSong()).toBe(false)
it 'should return false if no current', ->
scope.playlist.current = null
expect(scope.hasPreviousSong()).toBe(false)
it 'should return false if no songs', ->
scope.playlist.songs = []
scope.playlist.current = 0
expect(scope.hasPreviousSong()).toBe(false)
it 'should return true if there is a previous song', ->
scope.playlist =
current: 1
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
expect(scope.hasPreviousSong()).toBe(true)
it 'should return true if there is not a previous song', ->
scope.playlist =
current: 0
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
expect(scope.hasPreviousSong()).toBe(false)
describe '.addSong()', ->
it 'should add a song at the end of the list', ->
scope.playlist.songs = [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
scope.newSong = { artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs).toEqual [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
]
it 'should erase newSong', ->
scope.newSong = { artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
scope.addSong()
expect(scope.newSong).toEqual({})
it 'should not add anything if no artist', ->
scope.playlist.songs = []
scope.newSong = { title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if artist is an empty string', ->
scope.playlist.songs = []
scope.newSong = { artist: '', title: 'Shake It Off' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if no title', ->
scope.playlist.songs = []
scope.newSong = { artist: 'PI:NAME:<NAME>END_PI' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
it 'should not add anything if title is an empty string', ->
scope.playlist.songs = []
scope.newSong = { artist: 'PI:NAME:<NAME>END_PI', title: '' }
scope.addSong()
expect(scope.playlist.songs.length).toBe(0)
describe '.remove()', ->
it 'should remove the song from the playlist', ->
scope.playlist =
current: 0
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.songs).toEqual [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
]
it 'should replay the current song', ->
scope.playlist =
current: 0
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
it 'should not restart playStart if no current', ->
scope.playlist =
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
scope.remove(1)
expect(scope.playlist.current).toBeUndefined()
expect(scope.playlist.playStart).toBeUndefined()
describe '.previous()', ->
describe 'if has a previous song', ->
beforeEach ->
scope.playlist =
current: 1
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
it 'should play the previous song', ->
scope.previous()
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe 'if no previous song', ->
beforeEach ->
scope.playlist =
current: 0
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
it 'should do nothing', ->
scope.previous()
expect(scope.playlist.current).toEqual(0)
expect(scope.playlist.playStart).toBeUndefined()
describe '.next()', ->
describe 'if has a next song', ->
beforeEach ->
scope.playlist =
current: 0
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
it 'should play the next song', ->
scope.next()
expect(scope.playlist.current).toEqual(1)
expect(scope.playlist.playStart).toBeCloseTo(Date.now(), 5)
describe 'if no next song', ->
beforeEach ->
scope.playlist =
current: 1
songs: [
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' }
{ artist: 'PI:NAME:<NAME>END_PI', title: 'Blank Space' }
]
it 'should do nothing', ->
scope.next()
expect(scope.playlist.current).toEqual(1)
expect(scope.playlist.playStart).toBeUndefined()
|
[
{
"context": ") ->\n action.config.new_key = 'new value'\n handler.call action.context,",
"end": 619,
"score": 0.7437775135040283,
"start": 610,
"tag": "KEY",
"value": "new value"
},
{
"context": "ainEql\n key: 'value'\n new_key... | packages/core/test/session/plugins/session.action.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
{tags} = require '../../test'
nikita = require '../../../src'
session = require '../../../src/session'
# Test the construction of the session namespace stored in state
describe 'session.plugins.session.action', ->
return unless tags.api
describe 'runtime', ->
it 'alter action - async', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
setImmediate ->
resolve (action) ->
action.config.new_key = 'new value'
handler.call action.context, action
context.registry.register ['an', 'action'],
config: key: 'value'
handler: ({config}) -> config
context.an.action().should.be.finally.containEql
key: 'value'
new_key: 'new value'
$status: false
it 'plugin return a promise, ensure child is executed', ->
session ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
await new Promise (resolve) -> setImmediate resolve
handler
@call name: 'parent', ->
@call name: 'child', ->
'ok'
.should.be.resolvedWith 'ok'
describe 'errors', ->
it 'throw in current context', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
if action.metadata.namespace.join('.') is 'an.action'
then throw Error 'Catch me'
else handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'thrown parent session', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
if action.metadata.namespace.join('.') is 'an.action'
then throw Error 'Catch me'
else handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'promise in current context', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
if action.metadata.namespace.join('.') is 'an.action'
then reject Error 'Catch me'
else resolve handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'promise in parent session', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
if action.metadata.namespace.join('.') is 'an.action'
then reject Error 'Catch me'
else resolve handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
| 169841 |
{tags} = require '../../test'
nikita = require '../../../src'
session = require '../../../src/session'
# Test the construction of the session namespace stored in state
describe 'session.plugins.session.action', ->
return unless tags.api
describe 'runtime', ->
it 'alter action - async', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
setImmediate ->
resolve (action) ->
action.config.new_key = '<KEY>'
handler.call action.context, action
context.registry.register ['an', 'action'],
config: key: 'value'
handler: ({config}) -> config
context.an.action().should.be.finally.containEql
key: 'value'
new_key: '<KEY>'
$status: false
it 'plugin return a promise, ensure child is executed', ->
session ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
await new Promise (resolve) -> setImmediate resolve
handler
@call name: 'parent', ->
@call name: 'child', ->
'ok'
.should.be.resolvedWith 'ok'
describe 'errors', ->
it 'throw in current context', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
if action.metadata.namespace.join('.') is 'an.action'
then throw Error 'Catch me'
else handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'thrown parent session', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
if action.metadata.namespace.join('.') is 'an.action'
then throw Error 'Catch me'
else handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'promise in current context', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
if action.metadata.namespace.join('.') is 'an.action'
then reject Error 'Catch me'
else resolve handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'promise in parent session', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
if action.metadata.namespace.join('.') is 'an.action'
then reject Error 'Catch me'
else resolve handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
| true |
{tags} = require '../../test'
nikita = require '../../../src'
session = require '../../../src/session'
# Test the construction of the session namespace stored in state
describe 'session.plugins.session.action', ->
return unless tags.api
describe 'runtime', ->
it 'alter action - async', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
setImmediate ->
resolve (action) ->
action.config.new_key = 'PI:KEY:<KEY>END_PI'
handler.call action.context, action
context.registry.register ['an', 'action'],
config: key: 'value'
handler: ({config}) -> config
context.an.action().should.be.finally.containEql
key: 'value'
new_key: 'PI:KEY:<KEY>END_PI'
$status: false
it 'plugin return a promise, ensure child is executed', ->
session ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
await new Promise (resolve) -> setImmediate resolve
handler
@call name: 'parent', ->
@call name: 'child', ->
'ok'
.should.be.resolvedWith 'ok'
describe 'errors', ->
it 'throw in current context', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
if action.metadata.namespace.join('.') is 'an.action'
then throw Error 'Catch me'
else handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'thrown parent session', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
if action.metadata.namespace.join('.') is 'an.action'
then throw Error 'Catch me'
else handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'promise in current context', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
if action.metadata.namespace.join('.') is 'an.action'
then reject Error 'Catch me'
else resolve handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
it 'promise in parent session', ->
nikita ({context, plugins, registry}) ->
plugins.register
'hooks':
'nikita:action': (action, handler) ->
new Promise (resolve, reject) ->
if action.metadata.namespace.join('.') is 'an.action'
then reject Error 'Catch me'
else resolve handler
context.registry.register ['an', 'action'],
handler: -> throw Error 'You are not invited'
context
.an.action()
.should.be.rejectedWith 'Catch me'
|
[
{
"context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s",
"end": 61,
"score": 0.9998319745063782,
"start": 48,
"tag": "NAME",
"value": "Stephan Jorek"
}
] | src/grammar/jison.coffee | sjorek/goatee-rules.js | 0 | ### ^
BSD 3-Clause License
Copyright (c) 2017, Stephan Jorek
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
###
# # Grammar …
# -----------
#
# … this time it's jison.coffee !
###
module.exports = (yy, notator) ->
### Use the script's jison-grammar ###
grammar = (require 'goatee-script.js/lib/grammar/jison')(yy, notator)
r = notator.resolve
o = notator.operation
c = notator.conditional
### Actually this is not needed, but it looks nicer ;-) ###
$1 = $2 = $3 = $4 = $5 = $6 = $7 = $8 = null
###*
# -------------
# Use the default jison-lexer
# @type {Object}
# @property lex
# @static
###
grammar.lex = do ->
### Declare all rule-related lexer tokens … ###
rules = [
r ///
(
[_a-zA-Z] |
[-_][_a-zA-Z]
)
(
-?\w
)*
/// , -> 'KEY'
c ['rule'], /\s\!important\b/ , -> 'NONIMPORTANT'
r ':' , -> @begin 'rule' ; ':'
].concat grammar.lex.rules.map (v, k) ->
### … and inherit the other lexer tokens from ScriptGrammar ###
switch v[1]
# '\s+', '/* … */'
when 'return;'
[['*']].concat v
# ';', 'EOF'
when 'return \';\';', 'return \'EOF\';'
v[1] = 'this.popState();' + v[1]
[['*']].concat v
else [['rule']].concat v
{
startConditions :
### “rule” is implicit (1), not explicit (0) ###
rule : 1
rules : rules
}
###*
# -------------
# The **Rules** is the top-level node in the syntax tree.
# @type {String}
# @property startSymbol
# @static
###
grammar.startSymbol = 'Rules'
###
# # Syntax description …
# ----------------------
#
# To build a grammar, a syntax is needed …
#
###
###*
# -------------
# … which is inherited and notated here in Backus-Naur-Format.
# @type {Object}
# @property bnf
# @static
###
grammar.bnf = do ->
bnf =
###
Since we parse bottom-up, all parsing must end here.
###
Rules: [
# TODO use a precompiled “undefined” expression in Rules » End
r 'End' , -> yy.goatee.create 'scalar', [undefined]
r 'RuleMap End' , -> $1
r 'Seperator RuleMap End' , -> $2
]
RuleMap: [
o 'Map' , -> yy.goatee.create 'rules', $1
o 'RuleMap Seperator Map' , -> yy.goatee.addRule $1, $3
]
Map: [
o 'KEY : Rule' , -> [$1].concat $3
]
Rule: [
o 'List' , -> [$1, off]
o 'List NONIMPORTANT' , -> [$1, on]
]
###
Inherit all but “Script” and “Statements” operations from script-grammar
###
for own k,v of grammar.bnf when k isnt 'Script' and k isnt 'Statements'
if k isnt 'Operation'
bnf[k] = v
continue
###
Tweak “Operation” to include a hack to support “!important” as statement
expression without interfering the final “!important” declaration
###
ops = []
for rule in v
if rule[0] is '! Expression'
ops.push o 'NONIMPORTANT', ->
yy.goatee.create '!' , [
yy.goatee.create 'reference', ['important']
]
ops.push rule
bnf[k] = ops
bnf
grammar
| 136844 | ### ^
BSD 3-Clause License
Copyright (c) 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
###
# # Grammar …
# -----------
#
# … this time it's jison.coffee !
###
module.exports = (yy, notator) ->
### Use the script's jison-grammar ###
grammar = (require 'goatee-script.js/lib/grammar/jison')(yy, notator)
r = notator.resolve
o = notator.operation
c = notator.conditional
### Actually this is not needed, but it looks nicer ;-) ###
$1 = $2 = $3 = $4 = $5 = $6 = $7 = $8 = null
###*
# -------------
# Use the default jison-lexer
# @type {Object}
# @property lex
# @static
###
grammar.lex = do ->
### Declare all rule-related lexer tokens … ###
rules = [
r ///
(
[_a-zA-Z] |
[-_][_a-zA-Z]
)
(
-?\w
)*
/// , -> 'KEY'
c ['rule'], /\s\!important\b/ , -> 'NONIMPORTANT'
r ':' , -> @begin 'rule' ; ':'
].concat grammar.lex.rules.map (v, k) ->
### … and inherit the other lexer tokens from ScriptGrammar ###
switch v[1]
# '\s+', '/* … */'
when 'return;'
[['*']].concat v
# ';', 'EOF'
when 'return \';\';', 'return \'EOF\';'
v[1] = 'this.popState();' + v[1]
[['*']].concat v
else [['rule']].concat v
{
startConditions :
### “rule” is implicit (1), not explicit (0) ###
rule : 1
rules : rules
}
###*
# -------------
# The **Rules** is the top-level node in the syntax tree.
# @type {String}
# @property startSymbol
# @static
###
grammar.startSymbol = 'Rules'
###
# # Syntax description …
# ----------------------
#
# To build a grammar, a syntax is needed …
#
###
###*
# -------------
# … which is inherited and notated here in Backus-Naur-Format.
# @type {Object}
# @property bnf
# @static
###
grammar.bnf = do ->
bnf =
###
Since we parse bottom-up, all parsing must end here.
###
Rules: [
# TODO use a precompiled “undefined” expression in Rules » End
r 'End' , -> yy.goatee.create 'scalar', [undefined]
r 'RuleMap End' , -> $1
r 'Seperator RuleMap End' , -> $2
]
RuleMap: [
o 'Map' , -> yy.goatee.create 'rules', $1
o 'RuleMap Seperator Map' , -> yy.goatee.addRule $1, $3
]
Map: [
o 'KEY : Rule' , -> [$1].concat $3
]
Rule: [
o 'List' , -> [$1, off]
o 'List NONIMPORTANT' , -> [$1, on]
]
###
Inherit all but “Script” and “Statements” operations from script-grammar
###
for own k,v of grammar.bnf when k isnt 'Script' and k isnt 'Statements'
if k isnt 'Operation'
bnf[k] = v
continue
###
Tweak “Operation” to include a hack to support “!important” as statement
expression without interfering the final “!important” declaration
###
ops = []
for rule in v
if rule[0] is '! Expression'
ops.push o 'NONIMPORTANT', ->
yy.goatee.create '!' , [
yy.goatee.create 'reference', ['important']
]
ops.push rule
bnf[k] = ops
bnf
grammar
| true | ### ^
BSD 3-Clause License
Copyright (c) 2017, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
###
# # Grammar …
# -----------
#
# … this time it's jison.coffee !
###
module.exports = (yy, notator) ->
### Use the script's jison-grammar ###
grammar = (require 'goatee-script.js/lib/grammar/jison')(yy, notator)
r = notator.resolve
o = notator.operation
c = notator.conditional
### Actually this is not needed, but it looks nicer ;-) ###
$1 = $2 = $3 = $4 = $5 = $6 = $7 = $8 = null
###*
# -------------
# Use the default jison-lexer
# @type {Object}
# @property lex
# @static
###
grammar.lex = do ->
### Declare all rule-related lexer tokens … ###
rules = [
r ///
(
[_a-zA-Z] |
[-_][_a-zA-Z]
)
(
-?\w
)*
/// , -> 'KEY'
c ['rule'], /\s\!important\b/ , -> 'NONIMPORTANT'
r ':' , -> @begin 'rule' ; ':'
].concat grammar.lex.rules.map (v, k) ->
### … and inherit the other lexer tokens from ScriptGrammar ###
switch v[1]
# '\s+', '/* … */'
when 'return;'
[['*']].concat v
# ';', 'EOF'
when 'return \';\';', 'return \'EOF\';'
v[1] = 'this.popState();' + v[1]
[['*']].concat v
else [['rule']].concat v
{
startConditions :
### “rule” is implicit (1), not explicit (0) ###
rule : 1
rules : rules
}
###*
# -------------
# The **Rules** is the top-level node in the syntax tree.
# @type {String}
# @property startSymbol
# @static
###
grammar.startSymbol = 'Rules'
###
# # Syntax description …
# ----------------------
#
# To build a grammar, a syntax is needed …
#
###
###*
# -------------
# … which is inherited and notated here in Backus-Naur-Format.
# @type {Object}
# @property bnf
# @static
###
grammar.bnf = do ->
bnf =
###
Since we parse bottom-up, all parsing must end here.
###
Rules: [
# TODO use a precompiled “undefined” expression in Rules » End
r 'End' , -> yy.goatee.create 'scalar', [undefined]
r 'RuleMap End' , -> $1
r 'Seperator RuleMap End' , -> $2
]
RuleMap: [
o 'Map' , -> yy.goatee.create 'rules', $1
o 'RuleMap Seperator Map' , -> yy.goatee.addRule $1, $3
]
Map: [
o 'KEY : Rule' , -> [$1].concat $3
]
Rule: [
o 'List' , -> [$1, off]
o 'List NONIMPORTANT' , -> [$1, on]
]
###
Inherit all but “Script” and “Statements” operations from script-grammar
###
for own k,v of grammar.bnf when k isnt 'Script' and k isnt 'Statements'
if k isnt 'Operation'
bnf[k] = v
continue
###
Tweak “Operation” to include a hack to support “!important” as statement
expression without interfering the final “!important” declaration
###
ops = []
for rule in v
if rule[0] is '! Expression'
ops.push o 'NONIMPORTANT', ->
yy.goatee.create '!' , [
yy.goatee.create 'reference', ['important']
]
ops.push rule
bnf[k] = ops
bnf
grammar
|
[
{
"context": "ow, 0], bufferPosition])\n # https://github.com/atom/autocomplete-plus/blob/9506a5c5fafca29003c59566cf",
"end": 346,
"score": 0.9452731013298035,
"start": 342,
"tag": "USERNAME",
"value": "atom"
},
{
"context": " the first letter\", ->\n editor.setText('\\\\cite{H... | spec/cite-provider-spec.coffee | smparker/atom-autocomplete-latex-cite | 4 | path = require 'path'
describe "Latex Cite Autocompletions", ->
[editor, provider] = []
bibFile = path.join(__dirname,'lib.bib')
getCompletions = ->
cursor = editor.getLastCursor()
bufferPosition = cursor.getBufferPosition()
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
# https://github.com/atom/autocomplete-plus/blob/9506a5c5fafca29003c59566cfc2b3ac37080973/lib/autocomplete-manager.js#L57
prefix = /(\b|['"~`!@#$%^&*(){}[\]=+,/?>])((\w+[\w-]*)|([.:;[{(< ]+))$/.exec(line)?[2] ? ''
request =
editor: editor
bufferPosition: bufferPosition
scopeDescriptor: cursor.getScopeDescriptor()
prefix: prefix
provider.getSuggestions(request)
checkSuggestion = (text) ->
waitsForPromise ->
getCompletions().then (values) ->
expect(values.length).toBeGreaterThan 0
expect(values[0].text).toEqual text
beforeEach ->
atom.packages.triggerActivationHook('language-latex:grammar-used')
atom.packages.triggerDeferredActivationHooks()
atom.project.setPaths([__dirname])
waitsForPromise -> atom.packages.activatePackage('autocomplete-latex-cite')
waitsForPromise -> atom.workspace.open('test.tex')
runs ->
provider = atom.packages.getActivePackage('autocomplete-latex-cite').mainModule.provide()
editor = atom.workspace.getActiveTextEditor()
waitsFor -> Object.keys(provider.manager.database).length > 0
it "returns no completions when not at the start of a tag", ->
editor.setText('')
expect(getCompletions()).not.toBeDefined()
editor.setText('d')
editor.setCursorBufferPosition([0, 0])
expect(getCompletions()).not.toBeDefined()
editor.setCursorBufferPosition([0, 1])
expect(getCompletions()).not.toBeDefined()
it "has no completions for prefix without first letter", ->
editor.setText('\\cite{')
expect(getCompletions()).not.toBeDefined()
it "has completions for prefix starting with the first letter", ->
editor.setText('\\cite{Hess')
checkSuggestion('7856203')
it "supports multiple arguments", ->
editor.setText('\\cite{7286496,Hess')
checkSuggestion('7856203')
| 62405 | path = require 'path'
describe "Latex Cite Autocompletions", ->
[editor, provider] = []
bibFile = path.join(__dirname,'lib.bib')
getCompletions = ->
cursor = editor.getLastCursor()
bufferPosition = cursor.getBufferPosition()
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
# https://github.com/atom/autocomplete-plus/blob/9506a5c5fafca29003c59566cfc2b3ac37080973/lib/autocomplete-manager.js#L57
prefix = /(\b|['"~`!@#$%^&*(){}[\]=+,/?>])((\w+[\w-]*)|([.:;[{(< ]+))$/.exec(line)?[2] ? ''
request =
editor: editor
bufferPosition: bufferPosition
scopeDescriptor: cursor.getScopeDescriptor()
prefix: prefix
provider.getSuggestions(request)
checkSuggestion = (text) ->
waitsForPromise ->
getCompletions().then (values) ->
expect(values.length).toBeGreaterThan 0
expect(values[0].text).toEqual text
beforeEach ->
atom.packages.triggerActivationHook('language-latex:grammar-used')
atom.packages.triggerDeferredActivationHooks()
atom.project.setPaths([__dirname])
waitsForPromise -> atom.packages.activatePackage('autocomplete-latex-cite')
waitsForPromise -> atom.workspace.open('test.tex')
runs ->
provider = atom.packages.getActivePackage('autocomplete-latex-cite').mainModule.provide()
editor = atom.workspace.getActiveTextEditor()
waitsFor -> Object.keys(provider.manager.database).length > 0
it "returns no completions when not at the start of a tag", ->
editor.setText('')
expect(getCompletions()).not.toBeDefined()
editor.setText('d')
editor.setCursorBufferPosition([0, 0])
expect(getCompletions()).not.toBeDefined()
editor.setCursorBufferPosition([0, 1])
expect(getCompletions()).not.toBeDefined()
it "has no completions for prefix without first letter", ->
editor.setText('\\cite{')
expect(getCompletions()).not.toBeDefined()
it "has completions for prefix starting with the first letter", ->
editor.setText('\\cite{<NAME>')
checkSuggestion('7856203')
it "supports multiple arguments", ->
editor.setText('\\cite{7286496,<NAME>')
checkSuggestion('7856203')
| true | path = require 'path'
describe "Latex Cite Autocompletions", ->
[editor, provider] = []
bibFile = path.join(__dirname,'lib.bib')
getCompletions = ->
cursor = editor.getLastCursor()
bufferPosition = cursor.getBufferPosition()
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
# https://github.com/atom/autocomplete-plus/blob/9506a5c5fafca29003c59566cfc2b3ac37080973/lib/autocomplete-manager.js#L57
prefix = /(\b|['"~`!@#$%^&*(){}[\]=+,/?>])((\w+[\w-]*)|([.:;[{(< ]+))$/.exec(line)?[2] ? ''
request =
editor: editor
bufferPosition: bufferPosition
scopeDescriptor: cursor.getScopeDescriptor()
prefix: prefix
provider.getSuggestions(request)
checkSuggestion = (text) ->
waitsForPromise ->
getCompletions().then (values) ->
expect(values.length).toBeGreaterThan 0
expect(values[0].text).toEqual text
beforeEach ->
atom.packages.triggerActivationHook('language-latex:grammar-used')
atom.packages.triggerDeferredActivationHooks()
atom.project.setPaths([__dirname])
waitsForPromise -> atom.packages.activatePackage('autocomplete-latex-cite')
waitsForPromise -> atom.workspace.open('test.tex')
runs ->
provider = atom.packages.getActivePackage('autocomplete-latex-cite').mainModule.provide()
editor = atom.workspace.getActiveTextEditor()
waitsFor -> Object.keys(provider.manager.database).length > 0
it "returns no completions when not at the start of a tag", ->
editor.setText('')
expect(getCompletions()).not.toBeDefined()
editor.setText('d')
editor.setCursorBufferPosition([0, 0])
expect(getCompletions()).not.toBeDefined()
editor.setCursorBufferPosition([0, 1])
expect(getCompletions()).not.toBeDefined()
it "has no completions for prefix without first letter", ->
editor.setText('\\cite{')
expect(getCompletions()).not.toBeDefined()
it "has completions for prefix starting with the first letter", ->
editor.setText('\\cite{PI:NAME:<NAME>END_PI')
checkSuggestion('7856203')
it "supports multiple arguments", ->
editor.setText('\\cite{7286496,PI:NAME:<NAME>END_PI')
checkSuggestion('7856203')
|
[
{
"context": "NFIG).toXml())\n eventEl\n\n##\n# <message to='hamlet@denmark.lit' from='pubsub.shakespeare.lit' id='approve1'>\n# ",
"end": 2274,
"score": 0.9996390342712402,
"start": 2256,
"tag": "EMAIL",
"value": "hamlet@denmark.lit"
},
{
"context": " to='hamlet@denmark.lit'... | src/xmpp/pubsub_notifications.coffee | surevine/buddycloud-server | 0 | xmpp = require('node-xmpp')
NS = require('./ns')
forms = require('./forms')
##
# All notifications are per-node, so listeners can be fetched once
#
# TODO: enforce MAX_STANZA_LIMIT
class Notification
constructor: (@opts) ->
toStanza: (fromJid, toJid) ->
message = new xmpp.Element('message',
type: 'headline'
from: fromJid
to: toJid
)
if @opts.replay
# For the MAM case the stanza is packaged up into
# <forwarded/>
message.c('forwarded', xmlns: NS.FORWARD).
c('message',
type: 'headline'
from: fromJid
to: toJid
)
else
message
class EventNotification extends Notification
toStanza: (fromJid, toJid) ->
eventEl = super.c('event', xmlns: NS.PUBSUB_EVENT)
for update in @opts
switch update.type
when 'items'
itemsEl = eventEl.
c('items', node: update.node)
if update.items? then for item in update.items
itemsEl.c('item', id: item.id).
cnode(item.el)
if update.retract? then for item_id in update.retract
itemsEl.c('retract', id: item_id)
when 'subscription'
eventEl.
c('subscription',
jid: update.user
node: update.node
subscription: update.subscription
)
when 'affiliation'
eventEl.
c('affiliation',
jid: update.user
node: update.node
affiliation: update.affiliation
)
when 'config'
eventEl.
c('configuration',
node: update.node
).cnode(forms.configToForm(update.config, 'result', NS.PUBSUB_NODE_CONFIG).toXml())
eventEl
##
# <message to='hamlet@denmark.lit' from='pubsub.shakespeare.lit' id='approve1'>
# <x xmlns='jabber:x:data' type='form'>
# <title>PubSub subscriber request</title>
# <instructions>
# To approve this entity's subscription request,
# click the OK button. To deny the request, click the
# cancel button.
# </instructions>
# <field var='FORM_TYPE' type='hidden'>
# <value>http://jabber.org/protocol/pubsub#subscribe_authorization</value>
# </field>
# <field var='pubsub#subid' type='hidden'><value>123-abc</value></field>
# <field var='pubsub#node' type='text-single' label='Node ID'>
# <value>princely_musings</value>
# </field>
# <field var='pusub#subscriber_jid' type='jid-single' label='Subscriber Address'# >
# <value>horatio@denmark.lit</value>
# </field>
# <field var='pubsub#allow' type='boolean'
# label='Allow this JID to subscribe to this pubsub node?'>
# <value>false</value>
# </field>
# </x>
# </message>
class AuthorizationPromptNotification extends Notification
toStanza: (fromJid, toJid) ->
form = new forms.Form('form', NS.PUBSUB_SUBSCRIBE_AUTHORIZATION)
form.title = 'Confirm channel subscription'
form.instructions = "Allow #{@opts.user} to subscribe to node #{@opts.node}?"
form.addField 'pubsub#node', 'text-single',
'Node', @opts.node
form.addField 'pubsub#subscriber_jid', 'jid-single',
'Subscriber Address', @opts.user
form.addField 'pubsub#allow', 'boolean',
'Allow?', 'false'
super.cnode form.toXml()
exports.make = (opts) ->
switch opts.type
when 'authorizationPrompt'
new AuthorizationPromptNotification(opts)
else
new EventNotification(opts)
| 69685 | xmpp = require('node-xmpp')
NS = require('./ns')
forms = require('./forms')
##
# All notifications are per-node, so listeners can be fetched once
#
# TODO: enforce MAX_STANZA_LIMIT
class Notification
constructor: (@opts) ->
toStanza: (fromJid, toJid) ->
message = new xmpp.Element('message',
type: 'headline'
from: fromJid
to: toJid
)
if @opts.replay
# For the MAM case the stanza is packaged up into
# <forwarded/>
message.c('forwarded', xmlns: NS.FORWARD).
c('message',
type: 'headline'
from: fromJid
to: toJid
)
else
message
class EventNotification extends Notification
toStanza: (fromJid, toJid) ->
eventEl = super.c('event', xmlns: NS.PUBSUB_EVENT)
for update in @opts
switch update.type
when 'items'
itemsEl = eventEl.
c('items', node: update.node)
if update.items? then for item in update.items
itemsEl.c('item', id: item.id).
cnode(item.el)
if update.retract? then for item_id in update.retract
itemsEl.c('retract', id: item_id)
when 'subscription'
eventEl.
c('subscription',
jid: update.user
node: update.node
subscription: update.subscription
)
when 'affiliation'
eventEl.
c('affiliation',
jid: update.user
node: update.node
affiliation: update.affiliation
)
when 'config'
eventEl.
c('configuration',
node: update.node
).cnode(forms.configToForm(update.config, 'result', NS.PUBSUB_NODE_CONFIG).toXml())
eventEl
##
# <message to='<EMAIL>' from='pubsub.shakespeare.<EMAIL>' id='approve1'>
# <x xmlns='jabber:x:data' type='form'>
# <title>PubSub subscriber request</title>
# <instructions>
# To approve this entity's subscription request,
# click the OK button. To deny the request, click the
# cancel button.
# </instructions>
# <field var='FORM_TYPE' type='hidden'>
# <value>http://jabber.org/protocol/pubsub#subscribe_authorization</value>
# </field>
# <field var='pubsub#subid' type='hidden'><value>123-abc</value></field>
# <field var='pubsub#node' type='text-single' label='Node ID'>
# <value>princely_musings</value>
# </field>
# <field var='pusub#subscriber_jid' type='jid-single' label='Subscriber Address'# >
# <value><EMAIL></value>
# </field>
# <field var='pubsub#allow' type='boolean'
# label='Allow this JID to subscribe to this pubsub node?'>
# <value>false</value>
# </field>
# </x>
# </message>
class AuthorizationPromptNotification extends Notification
toStanza: (fromJid, toJid) ->
form = new forms.Form('form', NS.PUBSUB_SUBSCRIBE_AUTHORIZATION)
form.title = 'Confirm channel subscription'
form.instructions = "Allow #{@opts.user} to subscribe to node #{@opts.node}?"
form.addField 'pubsub#node', 'text-single',
'Node', @opts.node
form.addField 'pubsub#subscriber_jid', 'jid-single',
'Subscriber Address', @opts.user
form.addField 'pubsub#allow', 'boolean',
'Allow?', 'false'
super.cnode form.toXml()
exports.make = (opts) ->
switch opts.type
when 'authorizationPrompt'
new AuthorizationPromptNotification(opts)
else
new EventNotification(opts)
| true | xmpp = require('node-xmpp')
NS = require('./ns')
forms = require('./forms')
##
# All notifications are per-node, so listeners can be fetched once
#
# TODO: enforce MAX_STANZA_LIMIT
class Notification
constructor: (@opts) ->
toStanza: (fromJid, toJid) ->
message = new xmpp.Element('message',
type: 'headline'
from: fromJid
to: toJid
)
if @opts.replay
# For the MAM case the stanza is packaged up into
# <forwarded/>
message.c('forwarded', xmlns: NS.FORWARD).
c('message',
type: 'headline'
from: fromJid
to: toJid
)
else
message
class EventNotification extends Notification
toStanza: (fromJid, toJid) ->
eventEl = super.c('event', xmlns: NS.PUBSUB_EVENT)
for update in @opts
switch update.type
when 'items'
itemsEl = eventEl.
c('items', node: update.node)
if update.items? then for item in update.items
itemsEl.c('item', id: item.id).
cnode(item.el)
if update.retract? then for item_id in update.retract
itemsEl.c('retract', id: item_id)
when 'subscription'
eventEl.
c('subscription',
jid: update.user
node: update.node
subscription: update.subscription
)
when 'affiliation'
eventEl.
c('affiliation',
jid: update.user
node: update.node
affiliation: update.affiliation
)
when 'config'
eventEl.
c('configuration',
node: update.node
).cnode(forms.configToForm(update.config, 'result', NS.PUBSUB_NODE_CONFIG).toXml())
eventEl
##
# <message to='PI:EMAIL:<EMAIL>END_PI' from='pubsub.shakespeare.PI:EMAIL:<EMAIL>END_PI' id='approve1'>
# <x xmlns='jabber:x:data' type='form'>
# <title>PubSub subscriber request</title>
# <instructions>
# To approve this entity's subscription request,
# click the OK button. To deny the request, click the
# cancel button.
# </instructions>
# <field var='FORM_TYPE' type='hidden'>
# <value>http://jabber.org/protocol/pubsub#subscribe_authorization</value>
# </field>
# <field var='pubsub#subid' type='hidden'><value>123-abc</value></field>
# <field var='pubsub#node' type='text-single' label='Node ID'>
# <value>princely_musings</value>
# </field>
# <field var='pusub#subscriber_jid' type='jid-single' label='Subscriber Address'# >
# <value>PI:EMAIL:<EMAIL>END_PI</value>
# </field>
# <field var='pubsub#allow' type='boolean'
# label='Allow this JID to subscribe to this pubsub node?'>
# <value>false</value>
# </field>
# </x>
# </message>
class AuthorizationPromptNotification extends Notification
toStanza: (fromJid, toJid) ->
form = new forms.Form('form', NS.PUBSUB_SUBSCRIBE_AUTHORIZATION)
form.title = 'Confirm channel subscription'
form.instructions = "Allow #{@opts.user} to subscribe to node #{@opts.node}?"
form.addField 'pubsub#node', 'text-single',
'Node', @opts.node
form.addField 'pubsub#subscriber_jid', 'jid-single',
'Subscriber Address', @opts.user
form.addField 'pubsub#allow', 'boolean',
'Allow?', 'false'
super.cnode form.toXml()
exports.make = (opts) ->
switch opts.type
when 'authorizationPrompt'
new AuthorizationPromptNotification(opts)
else
new EventNotification(opts)
|
[
{
"context": "usAilment\n inflict: (pokemon, log) ->\n key = @constructor.name\n pokemon.conditions[key] = this\n this.whenI",
"end": 76,
"score": 0.6221681237220764,
"start": 60,
"tag": "KEY",
"value": "constructor.name"
},
{
"context": " isInflicted: (pokemon) ->\n key... | src/conditions/condition.coffee | egilmore533/pokemon-battle-mod | 44 | class StatusAilment
inflict: (pokemon, log) ->
key = @constructor.name
pokemon.conditions[key] = this
this.whenInflicted pokemon, log
isInflicted: (pokemon) ->
key = @constructor.name
return pokemon.conditions[key]?
heal: (pokemon) ->
key = @constructor.name
delete pokemon.conditions[key]
whenInflicted: (pokemon, log) ->
canAttack: (pokemon, log) -> true
endTurn: (pokemon, log) ->
buildMultiplier: (attacker, chance) -> 1
battleMultiplier: (attacker, defender, chance) -> 1
module.exports = StatusAilment | 39233 | class StatusAilment
inflict: (pokemon, log) ->
key = @<KEY>
pokemon.conditions[key] = this
this.whenInflicted pokemon, log
isInflicted: (pokemon) ->
key = @constructor.<KEY>
return pokemon.conditions[key]?
heal: (pokemon) ->
key = @constructor.<KEY>
delete pokemon.conditions[key]
whenInflicted: (pokemon, log) ->
canAttack: (pokemon, log) -> true
endTurn: (pokemon, log) ->
buildMultiplier: (attacker, chance) -> 1
battleMultiplier: (attacker, defender, chance) -> 1
module.exports = StatusAilment | true | class StatusAilment
inflict: (pokemon, log) ->
key = @PI:KEY:<KEY>END_PI
pokemon.conditions[key] = this
this.whenInflicted pokemon, log
isInflicted: (pokemon) ->
key = @constructor.PI:KEY:<KEY>END_PI
return pokemon.conditions[key]?
heal: (pokemon) ->
key = @constructor.PI:KEY:<KEY>END_PI
delete pokemon.conditions[key]
whenInflicted: (pokemon, log) ->
canAttack: (pokemon, log) -> true
endTurn: (pokemon, log) ->
buildMultiplier: (attacker, chance) -> 1
battleMultiplier: (attacker, defender, chance) -> 1
module.exports = StatusAilment |
[
{
"context": "id}'>${name}</button>\n\"\"\"\n\n\n\n#userNameMap = {\n# 'kranian' : '허여송'\n# 'callin' : '임창진'\n# 'BOK' : '복정규'\n# ",
"end": 1604,
"score": 0.999393880367279,
"start": 1597,
"tag": "USERNAME",
"value": "kranian"
},
{
"context": "</button>\n\"\"\"\n\n\n\n#userNameMap... | render.coffee | kranian/gitlabviewer | 0 | #// This file is required by the index.html file and will
#// be executed in the renderer process for that window.
#// All of the Node.js APIs are available in this process.
$ = require('jquery');
_ = require('lodash');
d3 = require('d3');
showdown = require('showdown')
api = require('./gitlabApi');
shell = require('electron').shell;
ipcRenderer = require('electron').ipcRenderer
$body = $('body')
issueTmpl = _.template """
<td><%=iss.prjName%></td>
<td><%=iss.milestone.title %></td>
<td><%=iss.project_id == 19 ? iss.client : iss.subjectLabel %></td>
<td><%=iss.assignee.realname%></td>
<td class='<%=iss.el_state%>' ><span class='<%=iss.el_state%>' data-url='http://elevisor.iptime.org:9937/elevisor/<%=iss.realprjName%>/issues/<%=iss.iid%>' data-projectid='<%=iss.project_id%>' data-issueid='<%=iss.id%>'><%=iss.title%></span></td>
<td><%=iss.important%></td>
<td><%=iss.urgent%></td>
<td align='right'><%=iss.budget%></td>
<td><%=iss.created_at.substr(0,10)%></td>
<td><%=iss.updated_at.substr(0,10)%></td>
<td><%=iss.beginDt%></td>
<td><%=iss.endDt%></td>
<td>#<%=iss.iid%></td>
<td><%=iss.client%></td>
<td></td>
<td><button></button></td>
"""
filterItemTmpl = _.template """
<span class="nav-group-item itm" data-id='${id}'>${name}</span>
"""
filterPrjItemTmpl = _.template """
<span class="nav-group-item itm" data-id='${id}'>${name}</span>
"""
filterBtnTmpl = _.template """
<button class="btn btn-default label" data-id='${id}'>${name}</button>
"""
#userNameMap = {
# 'kranian' : '허여송'
# 'callin' : '임창진'
# 'BOK' : '복정규'
# 'acacia' : '이석우'
# 'yujeong' : '최유정'
# '':''
#}
#projectNameMap =
# 2: '신제품 개발'
# 19: '기존제품'
# 14:'홈페이지'
# 20 : 'tasklist'
#
#realprojectNameMap =
# 2: 'server'
# 19: 'maintenance'
# 14 : 'homepage'
# 20 : 'tasklist'
allIssue = []
filter = {
project_id : '*'
milestone : '*'
label : '*'
user : '*'
progress : '*'
issueTitle : ''
}
allMilestone = []
allLabel = []
allProject = []
allUser = []
dateRegEx = ///
!DT\[(.*)\]
///
budgetRegEx = ///
!BG\[(.*)\]
///
$.when(api.getProjectList(), api.getAllIssueList()).done (prjects, rslt) ->
# allProject =
allProjectMapper = {}
_.each(prjects,(val)->
prjId = val.id
allProjectMapper[prjId] = {}
allProjectMapper[prjId].id = val.id;
allProjectMapper[prjId].name = val.name;
)
console.log('allProjectMapper',allProjectMapper)
allIssue = _.map(rslt, (iss)->
iss.subjectLabel = _(iss.labels)
.filter((l)-> l.indexOf('[') < 0 )
.filter((l)-> l.indexOf('진행') < 0 )
.filter((l)-> l.indexOf('긴급') < 0 )
.filter((l)-> l.indexOf('종료') < 0 )
.filter((l)-> l != '상' )
.filter((l)-> l != '중' )
.filter((l)-> l != '하' )
.filter((l)-> l.indexOf('확인') < 0 )
.filter((l)-> l.indexOf('TODO') < 0 )
.filter((l)-> l.indexOf('report') < 0 )
.filter((l)-> l.indexOf('_cl') < 0 )
.value()
iss.client = _(iss.labels)
.filter((l)-> l.indexOf('_cl') > 0 )
.map((l)->l.split('_')[0])
.value().join(',')
iss.urgent = _(iss.labels)
.filter((l)-> l.indexOf('긴급') >= 0 )
.map(->'O')
.value().join('')
iss.important = _(iss.labels)
.filter((l)-> l.indexOf('중요') >= 0 )
.map(->'O')
.value().join('')
iss.el_state = _(iss.labels)
.filter((l)-> l.indexOf('작업종료') >= 0 or l.indexOf('진행중') >= 0)
.map((l)-> switch l
when '작업종료' then 'done'
when '진행중' then 'inprogress'
else ''
)
.value().join('')
iss.milestone ?= {title:''}
iss.assignee ?= {name:''}
iss.assignee.realname = iss.assignee.name
iss.prjName = allProjectMapper[iss.project_id].name
iss.realprjName = allProjectMapper[iss.project_id].name
iss.beginDt = ''
iss.endDt = ''
r = dateRegEx.exec(iss.description)
if r != null
#console.log r
iss.beginDt = r[1].split('~')[0]
iss.endDt = r[1].split('~')[1]
budget = budgetRegEx.exec(iss.description)
iss.budget = ''
if budget != null
iss.budget = budget[1]
#---------------------------------------------------------------
iss
)
allMilestone = _(allIssue).map('milestone').filter((v)->v!=null).map('title').uniq().value()
allLabel = _(allIssue).map('labels').flatten().uniq().sort().value()
allProject = prjects
allUser = _(allIssue).map('assignee').filter((v)->v!=null).map('name').uniq().value()
allIssue.sort (a,b) ->
order = b.project_id - a.project_id
return order if order != 0
if a.milestone.title != b.milestone.title
return if a.milestone.title < b.milestone.title then 1 else -1
if a.subjectLabel.join(',') != b.subjectLabel.join(',')
return if a.subjectLabel.join(',') < b.subjectLabel.join(',') then 1 else -1
return if a.assignee.name < b.assignee.name then 1 else -1
rows = d3.select('.main tbody').selectAll('tr').data(allIssue,(d)->d.id)
rows.enter()
.append('tr')
.html((d)->
issueTmpl({iss:d})
)
# console.log '--------------------------'
#----------------------------------
# console.log 'allProject', allProject
_.each(allProject, (prj)->
$('nav.project').append(filterPrjItemTmpl(prj))
)
#-----------------------------
_.each(allLabel, (lbl)->
$('#labelBtnGrp').append(filterBtnTmpl({id:lbl, name:lbl}))
)
#-----------------------------
_.each(allMilestone, (m)->
$('nav.milestone').append(filterItemTmpl({id:m, name:m}))
)
#-----------------------------
_.each(allUser, (u)->
$('nav.user').append(filterItemTmpl({id:u, name:u}))
)
#--------------------------------------- event -----------------------
$('nav').on('mousedown', '.nav-group-item', (evt)->
$t = $(evt.target)
$nav = $t.parent()
category = $nav.data('ctype')
$nav.find('.nav-group-item').removeClass('active')
$(evt.target).addClass('active')
idVal = $t.data('id')
#console.log idVal, category
switch category
when 'progress' then filter.progress = idVal.split(',')
when 'project'
filter.project_id = (''+idVal)
filter.milestone = '*'
filter.label = '*'
filterReset('project')
when 'milestone'
filter.milestone = idVal
filter.label = '*'
filterReset('milestone')
when 'user' then filter.user = idVal
doFilter()
)
$('#labelBtnGrp').on('click', 'button.label', (evt)->
$(evt.target).toggleClass('active')
selectedLabels = $('#labelBtnGrp button.active').map(-> $(@).data('id')).get()
if selectedLabels.length == 0
filter.label = '*'
else
filter.label = selectedLabels
doFilter()
)
$('.tab-item').click (evt)->
$('.tab-item').removeClass('active')
$(@).addClass('active')
tabid = $(@).data('tabid')
$('.sidebar .pane').hide()
$('.sidebar .pane.'+tabid).show()
$('#clearBtn').click ->
$('#labelBtnGrp button').removeClass('active')
filter.label = '*'
doFilter()
$('#refreshBtn').click (evt)->
if evt.shiftKey
ipcRenderer.sendSync('resetToken')
else
window.location.reload()
$('tbody').on('click', 'td span', (evt)->
projectId = $(@).data('projectid')
issueId = $(@).data('issueid')
console.log('projectId =>',projectId,issueId)
cv = new showdown.Converter()
api.getIssue(projectId,issueId)
.then((issue) ->
document.querySelector('.contents').innerHTML = ''
$('.contents').append( cv.makeHtml(issue.description))
document.querySelector('#hello_issue').showModal()
)
)
$('#cancel').on('click',(evt) ->
document.querySelector('#hello_issue').close(false)
)
$('#save').on('click',(evt) ->
document.querySelector('#hello_issue').close(false)
)
# url = $(@).data('url')
# evt.preventDefault();
# shell.openExternal(url);
$('input:text').keyup (evt)->
#console.log $(evt.target)[0].value
filter.issueTitle = $(evt.target).val()
doFilter()
$('div.pane.scroll').scroll ->
wst = $('div.pane.scroll').scrollTop()
if wst > 75
$('table.main thead').addClass('fixHeader')
ths = $('table.main thead tr th')
tds = $('table.main tbody tr:eq(0) td')
for idx in [0..ths.length-1]
$(ths[idx]).width $(tds[idx]).width()
else
$('table.main thead').removeClass('fixHeader')
filterReset = (level)->
$('#labelBtnGrp button.label').remove()
switch level
when 'project'
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
allMilestone = filteredIssue
.map('milestone').filter((v)->v!=null).map('title').uniq().value()
allLabel = filteredIssue.map('labels').flatten().uniq().sort().value()
$('nav.milestone span.itm').remove()
_.each(allMilestone, (m)->
$('nav.milestone').append(filterItemTmpl({id:m, name:m}))
)
when 'milestone'
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
.filter((v)-> if filter.milestone == '*' then true else v.milestone?.title == filter.milestone)
allLabel = filteredIssue.map('labels').flatten().uniq().sort().value()
_.each(allLabel, (lbl)->
$('#labelBtnGrp').append(filterBtnTmpl({id:lbl, name:lbl}))
)
doFilter = ->
console.log 'filter', filter
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
.filter((v)-> if filter.milestone == '*' then true else v.milestone?.title == filter.milestone)
.filter((v)-> if filter.issueTitle == '' then true else v.title.indexOf(filter.issueTitle) >= 0)
.filter((v)-> if filter.label == '*' then true else _.intersection(v.labels, filter.label).length > 0 )
.filter((v)-> if filter.user == '*' then true else v.assignee?.name == filter.user)
.filter((v)-> if filter.progress[0] == '*' then true else _.intersection(v.labels, filter.progress).length > 0 )
.value()
console.log "filter.progress.length", filter.progress.length
if filter.progress.length == 2
filteredIssue.sort (a,b) ->
if b.el_state > a.el_state then 1 else -1
rows = d3.select('.main tbody').selectAll('tr').data(filteredIssue,(d)->d.id)
rows.enter().append('tr').html((d)-> issueTmpl({iss:d}))
rows.exit().remove()
| 174305 | #// This file is required by the index.html file and will
#// be executed in the renderer process for that window.
#// All of the Node.js APIs are available in this process.
$ = require('jquery');
_ = require('lodash');
d3 = require('d3');
showdown = require('showdown')
api = require('./gitlabApi');
shell = require('electron').shell;
ipcRenderer = require('electron').ipcRenderer
$body = $('body')
issueTmpl = _.template """
<td><%=iss.prjName%></td>
<td><%=iss.milestone.title %></td>
<td><%=iss.project_id == 19 ? iss.client : iss.subjectLabel %></td>
<td><%=iss.assignee.realname%></td>
<td class='<%=iss.el_state%>' ><span class='<%=iss.el_state%>' data-url='http://elevisor.iptime.org:9937/elevisor/<%=iss.realprjName%>/issues/<%=iss.iid%>' data-projectid='<%=iss.project_id%>' data-issueid='<%=iss.id%>'><%=iss.title%></span></td>
<td><%=iss.important%></td>
<td><%=iss.urgent%></td>
<td align='right'><%=iss.budget%></td>
<td><%=iss.created_at.substr(0,10)%></td>
<td><%=iss.updated_at.substr(0,10)%></td>
<td><%=iss.beginDt%></td>
<td><%=iss.endDt%></td>
<td>#<%=iss.iid%></td>
<td><%=iss.client%></td>
<td></td>
<td><button></button></td>
"""
filterItemTmpl = _.template """
<span class="nav-group-item itm" data-id='${id}'>${name}</span>
"""
filterPrjItemTmpl = _.template """
<span class="nav-group-item itm" data-id='${id}'>${name}</span>
"""
filterBtnTmpl = _.template """
<button class="btn btn-default label" data-id='${id}'>${name}</button>
"""
#userNameMap = {
# 'kranian' : '<NAME>'
# 'callin' : '<NAME>'
# 'BOK' : '복정규'
# 'acacia' : '이석우'
# 'yujeong' : '최유정'
# '':''
#}
#projectNameMap =
# 2: '신제품 개발'
# 19: '기존제품'
# 14:'홈페이지'
# 20 : 'tasklist'
#
#realprojectNameMap =
# 2: 'server'
# 19: 'maintenance'
# 14 : 'homepage'
# 20 : 'tasklist'
allIssue = []
filter = {
project_id : '*'
milestone : '*'
label : '*'
user : '*'
progress : '*'
issueTitle : ''
}
allMilestone = []
allLabel = []
allProject = []
allUser = []
dateRegEx = ///
!DT\[(.*)\]
///
budgetRegEx = ///
!BG\[(.*)\]
///
$.when(api.getProjectList(), api.getAllIssueList()).done (prjects, rslt) ->
# allProject =
allProjectMapper = {}
_.each(prjects,(val)->
prjId = val.id
allProjectMapper[prjId] = {}
allProjectMapper[prjId].id = val.id;
allProjectMapper[prjId].name = val.name;
)
console.log('allProjectMapper',allProjectMapper)
allIssue = _.map(rslt, (iss)->
iss.subjectLabel = _(iss.labels)
.filter((l)-> l.indexOf('[') < 0 )
.filter((l)-> l.indexOf('진행') < 0 )
.filter((l)-> l.indexOf('긴급') < 0 )
.filter((l)-> l.indexOf('종료') < 0 )
.filter((l)-> l != '상' )
.filter((l)-> l != '중' )
.filter((l)-> l != '하' )
.filter((l)-> l.indexOf('확인') < 0 )
.filter((l)-> l.indexOf('TODO') < 0 )
.filter((l)-> l.indexOf('report') < 0 )
.filter((l)-> l.indexOf('_cl') < 0 )
.value()
iss.client = _(iss.labels)
.filter((l)-> l.indexOf('_cl') > 0 )
.map((l)->l.split('_')[0])
.value().join(',')
iss.urgent = _(iss.labels)
.filter((l)-> l.indexOf('긴급') >= 0 )
.map(->'O')
.value().join('')
iss.important = _(iss.labels)
.filter((l)-> l.indexOf('중요') >= 0 )
.map(->'O')
.value().join('')
iss.el_state = _(iss.labels)
.filter((l)-> l.indexOf('작업종료') >= 0 or l.indexOf('진행중') >= 0)
.map((l)-> switch l
when '작업종료' then 'done'
when '진행중' then 'inprogress'
else ''
)
.value().join('')
iss.milestone ?= {title:''}
iss.assignee ?= {name:''}
iss.assignee.realname = iss.assignee.name
iss.prjName = allProjectMapper[iss.project_id].name
iss.realprjName = allProjectMapper[iss.project_id].name
iss.beginDt = ''
iss.endDt = ''
r = dateRegEx.exec(iss.description)
if r != null
#console.log r
iss.beginDt = r[1].split('~')[0]
iss.endDt = r[1].split('~')[1]
budget = budgetRegEx.exec(iss.description)
iss.budget = ''
if budget != null
iss.budget = budget[1]
#---------------------------------------------------------------
iss
)
allMilestone = _(allIssue).map('milestone').filter((v)->v!=null).map('title').uniq().value()
allLabel = _(allIssue).map('labels').flatten().uniq().sort().value()
allProject = prjects
allUser = _(allIssue).map('assignee').filter((v)->v!=null).map('name').uniq().value()
allIssue.sort (a,b) ->
order = b.project_id - a.project_id
return order if order != 0
if a.milestone.title != b.milestone.title
return if a.milestone.title < b.milestone.title then 1 else -1
if a.subjectLabel.join(',') != b.subjectLabel.join(',')
return if a.subjectLabel.join(',') < b.subjectLabel.join(',') then 1 else -1
return if a.assignee.name < b.assignee.name then 1 else -1
rows = d3.select('.main tbody').selectAll('tr').data(allIssue,(d)->d.id)
rows.enter()
.append('tr')
.html((d)->
issueTmpl({iss:d})
)
# console.log '--------------------------'
#----------------------------------
# console.log 'allProject', allProject
_.each(allProject, (prj)->
$('nav.project').append(filterPrjItemTmpl(prj))
)
#-----------------------------
_.each(allLabel, (lbl)->
$('#labelBtnGrp').append(filterBtnTmpl({id:lbl, name:lbl}))
)
#-----------------------------
_.each(allMilestone, (m)->
$('nav.milestone').append(filterItemTmpl({id:m, name:m}))
)
#-----------------------------
_.each(allUser, (u)->
$('nav.user').append(filterItemTmpl({id:u, name:u}))
)
#--------------------------------------- event -----------------------
$('nav').on('mousedown', '.nav-group-item', (evt)->
$t = $(evt.target)
$nav = $t.parent()
category = $nav.data('ctype')
$nav.find('.nav-group-item').removeClass('active')
$(evt.target).addClass('active')
idVal = $t.data('id')
#console.log idVal, category
switch category
when 'progress' then filter.progress = idVal.split(',')
when 'project'
filter.project_id = (''+idVal)
filter.milestone = '*'
filter.label = '*'
filterReset('project')
when 'milestone'
filter.milestone = idVal
filter.label = '*'
filterReset('milestone')
when 'user' then filter.user = idVal
doFilter()
)
$('#labelBtnGrp').on('click', 'button.label', (evt)->
$(evt.target).toggleClass('active')
selectedLabels = $('#labelBtnGrp button.active').map(-> $(@).data('id')).get()
if selectedLabels.length == 0
filter.label = '*'
else
filter.label = selectedLabels
doFilter()
)
$('.tab-item').click (evt)->
$('.tab-item').removeClass('active')
$(@).addClass('active')
tabid = $(@).data('tabid')
$('.sidebar .pane').hide()
$('.sidebar .pane.'+tabid).show()
$('#clearBtn').click ->
$('#labelBtnGrp button').removeClass('active')
filter.label = '*'
doFilter()
$('#refreshBtn').click (evt)->
if evt.shiftKey
ipcRenderer.sendSync('resetToken')
else
window.location.reload()
$('tbody').on('click', 'td span', (evt)->
projectId = $(@).data('projectid')
issueId = $(@).data('issueid')
console.log('projectId =>',projectId,issueId)
cv = new showdown.Converter()
api.getIssue(projectId,issueId)
.then((issue) ->
document.querySelector('.contents').innerHTML = ''
$('.contents').append( cv.makeHtml(issue.description))
document.querySelector('#hello_issue').showModal()
)
)
$('#cancel').on('click',(evt) ->
document.querySelector('#hello_issue').close(false)
)
$('#save').on('click',(evt) ->
document.querySelector('#hello_issue').close(false)
)
# url = $(@).data('url')
# evt.preventDefault();
# shell.openExternal(url);
$('input:text').keyup (evt)->
#console.log $(evt.target)[0].value
filter.issueTitle = $(evt.target).val()
doFilter()
$('div.pane.scroll').scroll ->
wst = $('div.pane.scroll').scrollTop()
if wst > 75
$('table.main thead').addClass('fixHeader')
ths = $('table.main thead tr th')
tds = $('table.main tbody tr:eq(0) td')
for idx in [0..ths.length-1]
$(ths[idx]).width $(tds[idx]).width()
else
$('table.main thead').removeClass('fixHeader')
filterReset = (level)->
$('#labelBtnGrp button.label').remove()
switch level
when 'project'
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
allMilestone = filteredIssue
.map('milestone').filter((v)->v!=null).map('title').uniq().value()
allLabel = filteredIssue.map('labels').flatten().uniq().sort().value()
$('nav.milestone span.itm').remove()
_.each(allMilestone, (m)->
$('nav.milestone').append(filterItemTmpl({id:m, name:m}))
)
when 'milestone'
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
.filter((v)-> if filter.milestone == '*' then true else v.milestone?.title == filter.milestone)
allLabel = filteredIssue.map('labels').flatten().uniq().sort().value()
_.each(allLabel, (lbl)->
$('#labelBtnGrp').append(filterBtnTmpl({id:lbl, name:lbl}))
)
doFilter = ->
console.log 'filter', filter
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
.filter((v)-> if filter.milestone == '*' then true else v.milestone?.title == filter.milestone)
.filter((v)-> if filter.issueTitle == '' then true else v.title.indexOf(filter.issueTitle) >= 0)
.filter((v)-> if filter.label == '*' then true else _.intersection(v.labels, filter.label).length > 0 )
.filter((v)-> if filter.user == '*' then true else v.assignee?.name == filter.user)
.filter((v)-> if filter.progress[0] == '*' then true else _.intersection(v.labels, filter.progress).length > 0 )
.value()
console.log "filter.progress.length", filter.progress.length
if filter.progress.length == 2
filteredIssue.sort (a,b) ->
if b.el_state > a.el_state then 1 else -1
rows = d3.select('.main tbody').selectAll('tr').data(filteredIssue,(d)->d.id)
rows.enter().append('tr').html((d)-> issueTmpl({iss:d}))
rows.exit().remove()
| true | #// This file is required by the index.html file and will
#// be executed in the renderer process for that window.
#// All of the Node.js APIs are available in this process.
$ = require('jquery');
_ = require('lodash');
d3 = require('d3');
showdown = require('showdown')
api = require('./gitlabApi');
shell = require('electron').shell;
ipcRenderer = require('electron').ipcRenderer
$body = $('body')
issueTmpl = _.template """
<td><%=iss.prjName%></td>
<td><%=iss.milestone.title %></td>
<td><%=iss.project_id == 19 ? iss.client : iss.subjectLabel %></td>
<td><%=iss.assignee.realname%></td>
<td class='<%=iss.el_state%>' ><span class='<%=iss.el_state%>' data-url='http://elevisor.iptime.org:9937/elevisor/<%=iss.realprjName%>/issues/<%=iss.iid%>' data-projectid='<%=iss.project_id%>' data-issueid='<%=iss.id%>'><%=iss.title%></span></td>
<td><%=iss.important%></td>
<td><%=iss.urgent%></td>
<td align='right'><%=iss.budget%></td>
<td><%=iss.created_at.substr(0,10)%></td>
<td><%=iss.updated_at.substr(0,10)%></td>
<td><%=iss.beginDt%></td>
<td><%=iss.endDt%></td>
<td>#<%=iss.iid%></td>
<td><%=iss.client%></td>
<td></td>
<td><button></button></td>
"""
filterItemTmpl = _.template """
<span class="nav-group-item itm" data-id='${id}'>${name}</span>
"""
filterPrjItemTmpl = _.template """
<span class="nav-group-item itm" data-id='${id}'>${name}</span>
"""
filterBtnTmpl = _.template """
<button class="btn btn-default label" data-id='${id}'>${name}</button>
"""
#userNameMap = {
# 'kranian' : 'PI:NAME:<NAME>END_PI'
# 'callin' : 'PI:NAME:<NAME>END_PI'
# 'BOK' : '복정규'
# 'acacia' : '이석우'
# 'yujeong' : '최유정'
# '':''
#}
#projectNameMap =
# 2: '신제품 개발'
# 19: '기존제품'
# 14:'홈페이지'
# 20 : 'tasklist'
#
#realprojectNameMap =
# 2: 'server'
# 19: 'maintenance'
# 14 : 'homepage'
# 20 : 'tasklist'
allIssue = []
filter = {
project_id : '*'
milestone : '*'
label : '*'
user : '*'
progress : '*'
issueTitle : ''
}
allMilestone = []
allLabel = []
allProject = []
allUser = []
dateRegEx = ///
!DT\[(.*)\]
///
budgetRegEx = ///
!BG\[(.*)\]
///
$.when(api.getProjectList(), api.getAllIssueList()).done (prjects, rslt) ->
# allProject =
allProjectMapper = {}
_.each(prjects,(val)->
prjId = val.id
allProjectMapper[prjId] = {}
allProjectMapper[prjId].id = val.id;
allProjectMapper[prjId].name = val.name;
)
console.log('allProjectMapper',allProjectMapper)
allIssue = _.map(rslt, (iss)->
iss.subjectLabel = _(iss.labels)
.filter((l)-> l.indexOf('[') < 0 )
.filter((l)-> l.indexOf('진행') < 0 )
.filter((l)-> l.indexOf('긴급') < 0 )
.filter((l)-> l.indexOf('종료') < 0 )
.filter((l)-> l != '상' )
.filter((l)-> l != '중' )
.filter((l)-> l != '하' )
.filter((l)-> l.indexOf('확인') < 0 )
.filter((l)-> l.indexOf('TODO') < 0 )
.filter((l)-> l.indexOf('report') < 0 )
.filter((l)-> l.indexOf('_cl') < 0 )
.value()
iss.client = _(iss.labels)
.filter((l)-> l.indexOf('_cl') > 0 )
.map((l)->l.split('_')[0])
.value().join(',')
iss.urgent = _(iss.labels)
.filter((l)-> l.indexOf('긴급') >= 0 )
.map(->'O')
.value().join('')
iss.important = _(iss.labels)
.filter((l)-> l.indexOf('중요') >= 0 )
.map(->'O')
.value().join('')
iss.el_state = _(iss.labels)
.filter((l)-> l.indexOf('작업종료') >= 0 or l.indexOf('진행중') >= 0)
.map((l)-> switch l
when '작업종료' then 'done'
when '진행중' then 'inprogress'
else ''
)
.value().join('')
iss.milestone ?= {title:''}
iss.assignee ?= {name:''}
iss.assignee.realname = iss.assignee.name
iss.prjName = allProjectMapper[iss.project_id].name
iss.realprjName = allProjectMapper[iss.project_id].name
iss.beginDt = ''
iss.endDt = ''
r = dateRegEx.exec(iss.description)
if r != null
#console.log r
iss.beginDt = r[1].split('~')[0]
iss.endDt = r[1].split('~')[1]
budget = budgetRegEx.exec(iss.description)
iss.budget = ''
if budget != null
iss.budget = budget[1]
#---------------------------------------------------------------
iss
)
allMilestone = _(allIssue).map('milestone').filter((v)->v!=null).map('title').uniq().value()
allLabel = _(allIssue).map('labels').flatten().uniq().sort().value()
allProject = prjects
allUser = _(allIssue).map('assignee').filter((v)->v!=null).map('name').uniq().value()
allIssue.sort (a,b) ->
order = b.project_id - a.project_id
return order if order != 0
if a.milestone.title != b.milestone.title
return if a.milestone.title < b.milestone.title then 1 else -1
if a.subjectLabel.join(',') != b.subjectLabel.join(',')
return if a.subjectLabel.join(',') < b.subjectLabel.join(',') then 1 else -1
return if a.assignee.name < b.assignee.name then 1 else -1
rows = d3.select('.main tbody').selectAll('tr').data(allIssue,(d)->d.id)
rows.enter()
.append('tr')
.html((d)->
issueTmpl({iss:d})
)
# console.log '--------------------------'
#----------------------------------
# console.log 'allProject', allProject
_.each(allProject, (prj)->
$('nav.project').append(filterPrjItemTmpl(prj))
)
#-----------------------------
_.each(allLabel, (lbl)->
$('#labelBtnGrp').append(filterBtnTmpl({id:lbl, name:lbl}))
)
#-----------------------------
_.each(allMilestone, (m)->
$('nav.milestone').append(filterItemTmpl({id:m, name:m}))
)
#-----------------------------
_.each(allUser, (u)->
$('nav.user').append(filterItemTmpl({id:u, name:u}))
)
#--------------------------------------- event -----------------------
$('nav').on('mousedown', '.nav-group-item', (evt)->
$t = $(evt.target)
$nav = $t.parent()
category = $nav.data('ctype')
$nav.find('.nav-group-item').removeClass('active')
$(evt.target).addClass('active')
idVal = $t.data('id')
#console.log idVal, category
switch category
when 'progress' then filter.progress = idVal.split(',')
when 'project'
filter.project_id = (''+idVal)
filter.milestone = '*'
filter.label = '*'
filterReset('project')
when 'milestone'
filter.milestone = idVal
filter.label = '*'
filterReset('milestone')
when 'user' then filter.user = idVal
doFilter()
)
$('#labelBtnGrp').on('click', 'button.label', (evt)->
$(evt.target).toggleClass('active')
selectedLabels = $('#labelBtnGrp button.active').map(-> $(@).data('id')).get()
if selectedLabels.length == 0
filter.label = '*'
else
filter.label = selectedLabels
doFilter()
)
$('.tab-item').click (evt)->
$('.tab-item').removeClass('active')
$(@).addClass('active')
tabid = $(@).data('tabid')
$('.sidebar .pane').hide()
$('.sidebar .pane.'+tabid).show()
$('#clearBtn').click ->
$('#labelBtnGrp button').removeClass('active')
filter.label = '*'
doFilter()
$('#refreshBtn').click (evt)->
if evt.shiftKey
ipcRenderer.sendSync('resetToken')
else
window.location.reload()
$('tbody').on('click', 'td span', (evt)->
projectId = $(@).data('projectid')
issueId = $(@).data('issueid')
console.log('projectId =>',projectId,issueId)
cv = new showdown.Converter()
api.getIssue(projectId,issueId)
.then((issue) ->
document.querySelector('.contents').innerHTML = ''
$('.contents').append( cv.makeHtml(issue.description))
document.querySelector('#hello_issue').showModal()
)
)
$('#cancel').on('click',(evt) ->
document.querySelector('#hello_issue').close(false)
)
$('#save').on('click',(evt) ->
document.querySelector('#hello_issue').close(false)
)
# url = $(@).data('url')
# evt.preventDefault();
# shell.openExternal(url);
$('input:text').keyup (evt)->
#console.log $(evt.target)[0].value
filter.issueTitle = $(evt.target).val()
doFilter()
$('div.pane.scroll').scroll ->
wst = $('div.pane.scroll').scrollTop()
if wst > 75
$('table.main thead').addClass('fixHeader')
ths = $('table.main thead tr th')
tds = $('table.main tbody tr:eq(0) td')
for idx in [0..ths.length-1]
$(ths[idx]).width $(tds[idx]).width()
else
$('table.main thead').removeClass('fixHeader')
filterReset = (level)->
$('#labelBtnGrp button.label').remove()
switch level
when 'project'
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
allMilestone = filteredIssue
.map('milestone').filter((v)->v!=null).map('title').uniq().value()
allLabel = filteredIssue.map('labels').flatten().uniq().sort().value()
$('nav.milestone span.itm').remove()
_.each(allMilestone, (m)->
$('nav.milestone').append(filterItemTmpl({id:m, name:m}))
)
when 'milestone'
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
.filter((v)-> if filter.milestone == '*' then true else v.milestone?.title == filter.milestone)
allLabel = filteredIssue.map('labels').flatten().uniq().sort().value()
_.each(allLabel, (lbl)->
$('#labelBtnGrp').append(filterBtnTmpl({id:lbl, name:lbl}))
)
doFilter = ->
console.log 'filter', filter
filteredIssue = _(allIssue)
.filter((v)-> if filter.project_id == '*' then true else (''+v.project_id) == filter.project_id)
.filter((v)-> if filter.milestone == '*' then true else v.milestone?.title == filter.milestone)
.filter((v)-> if filter.issueTitle == '' then true else v.title.indexOf(filter.issueTitle) >= 0)
.filter((v)-> if filter.label == '*' then true else _.intersection(v.labels, filter.label).length > 0 )
.filter((v)-> if filter.user == '*' then true else v.assignee?.name == filter.user)
.filter((v)-> if filter.progress[0] == '*' then true else _.intersection(v.labels, filter.progress).length > 0 )
.value()
console.log "filter.progress.length", filter.progress.length
if filter.progress.length == 2
filteredIssue.sort (a,b) ->
if b.el_state > a.el_state then 1 else -1
rows = d3.select('.main tbody').selectAll('tr').data(filteredIssue,(d)->d.id)
rows.enter().append('tr').html((d)-> issueTmpl({iss:d}))
rows.exit().remove()
|
[
{
"context": "rue\n\n try\n @_sock6.addMembership 'ff02::1', ip.address\n catch e\n\n onConnect()",
"end": 7800,
"score": 0.9996267557144165,
"start": 7793,
"tag": "IP_ADDRESS",
"value": "ff02::1"
}
] | src/dhcp/server.coffee | FrancYescO/tch-exploit | 58 | dgram = require 'dgram'
os = require 'os'
{ EventEmitter } = require 'events'
Lease = require './lease'
SeqBuffer = require './seqbuffer'
Options = require './options'
Protocol = require './protocol'
Tools = require './tools'
Ips = require '../ips'
{
DHCPDISCOVER, DHCPOFFER, DHCPREQUEST, DHCPDECLINE
DHCPACK, DHCPNAK, DHCPRELEASE, DHCPINFORM
SERVER_PORT, CLIENT_PORT
INADDR_ANY, INADDR_BROADCAST
BOOTREQUEST, BOOTREPLY, DHCPV6
} = require './constants'
class Server extends EventEmitter
@createServer: (opt) ->
new Server(opt)
constructor: (config) ->
super()
sock = dgram.createSocket
type: 'udp4'
reuseAddr: true
sock.on 'message', @ipv4Message.bind @
sock.on 'listening', =>
@emit 'listening', sock, ''
sock.on 'close', =>
@emit 'close'
sock6 = dgram.createSocket
type: 'udp6'
reuseAddr: true
sock6.on 'message', @ipv6Message.bind @
sock6.on 'listening', =>
@emit 'listening', sock6, 'v6'
sock6.on 'close', =>
@emit 'close'
@_sock6 = sock6
@_sock = sock
@_conf = config
@_state = {}
ipv4Message: (buf) ->
try
req = Protocol.parse(buf)
catch e
@emit 'error', e
return
@emit 'message', req
if req.op != BOOTREQUEST
@emit 'error', new Error('Malformed packet'), req
return
if not req.options[53]
return @handleRequest req
switch req.options[53]
when DHCPDISCOVER
@handleDiscover req
when DHCPREQUEST
@handleRequest req
ipv6Message: (buf, rinfo) ->
try
req = Protocol.parseIpv6(buf)
catch e
@emit 'error', e
return
@emit 'message', req
@emit DHCPV6.MESSAGETYPE[req.op], req, rinfo
config: (key) ->
optId = Options.conf[key]
if undefined != @_conf[key]
val = @_conf[key]
else if undefined != Options.opts[optId]
val = Options.opts[optId].default
if val == undefined
return 0
else
throw new Error 'Invalid option ' + key
if val instanceof Function
val = val.call @
values = Options.opts[optId]?.enum
if key not in [ 'range', 'static', 'randomIP' ] and values
for i, v of values when v is val
return parseInt i, 10
if values[val] is undefined
throw new Error 'Provided enum value for ' + key + ' is not valid'
else
val = parseInt val, 10
val
_getOptions: (pre, required, requested) ->
for req in required
if Options.opts[req] != undefined
pre[req] ?= @config(Options.opts[req].config)
if not pre[req]
throw new Error "Required option #{ Options.opts[req].config } does not have a value set"
else
@emit 'error', 'Unknown option ' + req
if requested
for req in requested
if Options.opts[req] isnt undefined and pre[req] is undefined
val = @config(Options.opts[req].config)
if val
pre[req] = val
else
@emit 'error', 'Unknown option ' + req
forceOptions = @_conf.forceOptions
if Array.isArray forceOptions
for option in forceOptions
if isNaN option
id = Options.conf[option]
else
id = option
if id? and pre[id] is undefined
pre[id] = @config(option)
pre
_selectAddress: (clientMAC, req) ->
if @_state[clientMAC]?.address
return @_state[clientMAC].address
_static = @config 'static'
if typeof _static is 'function'
staticResult = _static clientMAC, req
if staticResult
return staticResult
else if _static[clientMAC]
return _static[clientMAC]
randIP = @config 'randomIP'
_tmp = @config 'range'
firstIP = Tools.parseIp _tmp[0]
lastIP = Tools.parseIp _tmp[1]
ips = [ @config('server') ]
oldestMac = null
oldestTime = Infinity
leases = 0
for mac, v of @_state
if v.address
ips.push v.address
if v.leaseTime < oldestTime
oldestTime = v.leaseTime
oldestMac = mac
leases++
if oldestMac and lastIP - firstIP == leases
ip = @_state[oldestMac].address
delete @_state[oldestMac]
return ip
if randIP
loop
ip = Tools.formatIp(firstIP + Math.random() * (lastIP - firstIP) | 0)
if ips.indexOf(ip) == -1
return ip
i = firstIP
while i <= lastIP
ip = Tools.formatIp i
if ip not in ips
return ip
i++
handleDiscover: (req) ->
lease = @_state[req.chaddr] = @_state[req.chaddr] or new Lease
lease.address = @_selectAddress(req.chaddr, req)
lease.leasePeriod = @config 'leaseTime'
lease.server = @config 'server'
lease.state = 'OFFERED'
console.log '>>> DISCOVER', JSON.stringify lease
@sendOffer req
sendOffer: (req) ->
if req.options[97] and req.options[55].indexOf(97) == -1
req.options[55].push 97
if req.options[60] and req.options[60].indexOf('PXEClient') == 0
[ 66, 67 ].forEach (opt) ->
if req.options[55].indexOf(opt) is -1
req.options[55].push opt
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: INADDR_ANY
yiaddr: @_selectAddress req.chaddr
siaddr: @config 'server'
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: ''
options: @_getOptions { 53: DHCPOFFER }, [
1
3
51
54
6
], req.options[55]
console.log '<<< OFFER', JSON.stringify ans
@_send @config('broadcast'), ans
handleRequest: (req) ->
lease = @_state[req.chaddr] = @_state[req.chaddr] or new Lease
lease.address = @_selectAddress req.chaddr
lease.leasePeriod = @config 'leaseTime'
lease.server = @config 'server'
lease.state = 'BOUND'
lease.bindTime = new Date
lease.file = req.file
console.log '>>> REQUEST', JSON.stringify lease
@sendAck req
sendAck: (req) ->
if req.options[97] and req.options[55].indexOf(97) == -1
req.options[55].push 97
if req.options[60] and req.options[60].indexOf('PXEClient') == 0
[ 66, 67 ].forEach (opt) ->
if req.options[55].indexOf(opt) is -1
req.options[55].push opt
options = @_getOptions { 53: DHCPACK }, [
1
3
51
54
6
], req.options[55]
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: req.ciaddr
yiaddr: @_selectAddress req.chaddr
siaddr: @config 'server'
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: req.file
options: options
@_send @config('broadcast'), ans, =>
@emit 'bound', @_state, ans
sendNak: (req) ->
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: INADDR_ANY
yiaddr: INADDR_ANY
siaddr: INADDR_ANY
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: ''
options: @_getOptions { 53: DHCPNAK }, [ 54 ]
console.log '<<< NAK', JSON.stringify ans
@_send @config('broadcast'), ans
handleRelease: ->
handleRenew: ->
return
listen: (port, host, fn = ->) ->
ip = Ips().find ({ family }) -> family is 'IPv6'
connacks = Number not not ip
onConnect = ->
connacks++
if connacks is 2
process.nextTick fn
@_sock.bind port or SERVER_PORT, host or INADDR_ANY, =>
@_sock.setBroadcast true
onConnect()
if ip
@_sock6.bind 547, '::', =>
@_sock6.setBroadcast true
try
@_sock6.addMembership 'ff02::1', ip.address
catch e
onConnect()
@
close: (callback) ->
connacks = 0
onClose = ->
connacks++
if connacks is 2
callback()
@_sock.close onClose
@_sock6.close onClose
_send: (host, data, cb = ->) ->
sb = Protocol.format data
@_sock.send sb._data, 0, sb._w, CLIENT_PORT, host, (err, bytes) ->
if err
console.log err
cb err, bytes
module.exports = Server
| 166848 | dgram = require 'dgram'
os = require 'os'
{ EventEmitter } = require 'events'
Lease = require './lease'
SeqBuffer = require './seqbuffer'
Options = require './options'
Protocol = require './protocol'
Tools = require './tools'
Ips = require '../ips'
{
DHCPDISCOVER, DHCPOFFER, DHCPREQUEST, DHCPDECLINE
DHCPACK, DHCPNAK, DHCPRELEASE, DHCPINFORM
SERVER_PORT, CLIENT_PORT
INADDR_ANY, INADDR_BROADCAST
BOOTREQUEST, BOOTREPLY, DHCPV6
} = require './constants'
class Server extends EventEmitter
@createServer: (opt) ->
new Server(opt)
constructor: (config) ->
super()
sock = dgram.createSocket
type: 'udp4'
reuseAddr: true
sock.on 'message', @ipv4Message.bind @
sock.on 'listening', =>
@emit 'listening', sock, ''
sock.on 'close', =>
@emit 'close'
sock6 = dgram.createSocket
type: 'udp6'
reuseAddr: true
sock6.on 'message', @ipv6Message.bind @
sock6.on 'listening', =>
@emit 'listening', sock6, 'v6'
sock6.on 'close', =>
@emit 'close'
@_sock6 = sock6
@_sock = sock
@_conf = config
@_state = {}
ipv4Message: (buf) ->
try
req = Protocol.parse(buf)
catch e
@emit 'error', e
return
@emit 'message', req
if req.op != BOOTREQUEST
@emit 'error', new Error('Malformed packet'), req
return
if not req.options[53]
return @handleRequest req
switch req.options[53]
when DHCPDISCOVER
@handleDiscover req
when DHCPREQUEST
@handleRequest req
ipv6Message: (buf, rinfo) ->
try
req = Protocol.parseIpv6(buf)
catch e
@emit 'error', e
return
@emit 'message', req
@emit DHCPV6.MESSAGETYPE[req.op], req, rinfo
config: (key) ->
optId = Options.conf[key]
if undefined != @_conf[key]
val = @_conf[key]
else if undefined != Options.opts[optId]
val = Options.opts[optId].default
if val == undefined
return 0
else
throw new Error 'Invalid option ' + key
if val instanceof Function
val = val.call @
values = Options.opts[optId]?.enum
if key not in [ 'range', 'static', 'randomIP' ] and values
for i, v of values when v is val
return parseInt i, 10
if values[val] is undefined
throw new Error 'Provided enum value for ' + key + ' is not valid'
else
val = parseInt val, 10
val
_getOptions: (pre, required, requested) ->
for req in required
if Options.opts[req] != undefined
pre[req] ?= @config(Options.opts[req].config)
if not pre[req]
throw new Error "Required option #{ Options.opts[req].config } does not have a value set"
else
@emit 'error', 'Unknown option ' + req
if requested
for req in requested
if Options.opts[req] isnt undefined and pre[req] is undefined
val = @config(Options.opts[req].config)
if val
pre[req] = val
else
@emit 'error', 'Unknown option ' + req
forceOptions = @_conf.forceOptions
if Array.isArray forceOptions
for option in forceOptions
if isNaN option
id = Options.conf[option]
else
id = option
if id? and pre[id] is undefined
pre[id] = @config(option)
pre
_selectAddress: (clientMAC, req) ->
if @_state[clientMAC]?.address
return @_state[clientMAC].address
_static = @config 'static'
if typeof _static is 'function'
staticResult = _static clientMAC, req
if staticResult
return staticResult
else if _static[clientMAC]
return _static[clientMAC]
randIP = @config 'randomIP'
_tmp = @config 'range'
firstIP = Tools.parseIp _tmp[0]
lastIP = Tools.parseIp _tmp[1]
ips = [ @config('server') ]
oldestMac = null
oldestTime = Infinity
leases = 0
for mac, v of @_state
if v.address
ips.push v.address
if v.leaseTime < oldestTime
oldestTime = v.leaseTime
oldestMac = mac
leases++
if oldestMac and lastIP - firstIP == leases
ip = @_state[oldestMac].address
delete @_state[oldestMac]
return ip
if randIP
loop
ip = Tools.formatIp(firstIP + Math.random() * (lastIP - firstIP) | 0)
if ips.indexOf(ip) == -1
return ip
i = firstIP
while i <= lastIP
ip = Tools.formatIp i
if ip not in ips
return ip
i++
handleDiscover: (req) ->
lease = @_state[req.chaddr] = @_state[req.chaddr] or new Lease
lease.address = @_selectAddress(req.chaddr, req)
lease.leasePeriod = @config 'leaseTime'
lease.server = @config 'server'
lease.state = 'OFFERED'
console.log '>>> DISCOVER', JSON.stringify lease
@sendOffer req
sendOffer: (req) ->
if req.options[97] and req.options[55].indexOf(97) == -1
req.options[55].push 97
if req.options[60] and req.options[60].indexOf('PXEClient') == 0
[ 66, 67 ].forEach (opt) ->
if req.options[55].indexOf(opt) is -1
req.options[55].push opt
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: INADDR_ANY
yiaddr: @_selectAddress req.chaddr
siaddr: @config 'server'
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: ''
options: @_getOptions { 53: DHCPOFFER }, [
1
3
51
54
6
], req.options[55]
console.log '<<< OFFER', JSON.stringify ans
@_send @config('broadcast'), ans
handleRequest: (req) ->
lease = @_state[req.chaddr] = @_state[req.chaddr] or new Lease
lease.address = @_selectAddress req.chaddr
lease.leasePeriod = @config 'leaseTime'
lease.server = @config 'server'
lease.state = 'BOUND'
lease.bindTime = new Date
lease.file = req.file
console.log '>>> REQUEST', JSON.stringify lease
@sendAck req
sendAck: (req) ->
if req.options[97] and req.options[55].indexOf(97) == -1
req.options[55].push 97
if req.options[60] and req.options[60].indexOf('PXEClient') == 0
[ 66, 67 ].forEach (opt) ->
if req.options[55].indexOf(opt) is -1
req.options[55].push opt
options = @_getOptions { 53: DHCPACK }, [
1
3
51
54
6
], req.options[55]
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: req.ciaddr
yiaddr: @_selectAddress req.chaddr
siaddr: @config 'server'
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: req.file
options: options
@_send @config('broadcast'), ans, =>
@emit 'bound', @_state, ans
sendNak: (req) ->
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: INADDR_ANY
yiaddr: INADDR_ANY
siaddr: INADDR_ANY
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: ''
options: @_getOptions { 53: DHCPNAK }, [ 54 ]
console.log '<<< NAK', JSON.stringify ans
@_send @config('broadcast'), ans
handleRelease: ->
handleRenew: ->
return
listen: (port, host, fn = ->) ->
ip = Ips().find ({ family }) -> family is 'IPv6'
connacks = Number not not ip
onConnect = ->
connacks++
if connacks is 2
process.nextTick fn
@_sock.bind port or SERVER_PORT, host or INADDR_ANY, =>
@_sock.setBroadcast true
onConnect()
if ip
@_sock6.bind 547, '::', =>
@_sock6.setBroadcast true
try
@_sock6.addMembership 'fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', ip.address
catch e
onConnect()
@
close: (callback) ->
connacks = 0
onClose = ->
connacks++
if connacks is 2
callback()
@_sock.close onClose
@_sock6.close onClose
_send: (host, data, cb = ->) ->
sb = Protocol.format data
@_sock.send sb._data, 0, sb._w, CLIENT_PORT, host, (err, bytes) ->
if err
console.log err
cb err, bytes
module.exports = Server
| true | dgram = require 'dgram'
os = require 'os'
{ EventEmitter } = require 'events'
Lease = require './lease'
SeqBuffer = require './seqbuffer'
Options = require './options'
Protocol = require './protocol'
Tools = require './tools'
Ips = require '../ips'
{
DHCPDISCOVER, DHCPOFFER, DHCPREQUEST, DHCPDECLINE
DHCPACK, DHCPNAK, DHCPRELEASE, DHCPINFORM
SERVER_PORT, CLIENT_PORT
INADDR_ANY, INADDR_BROADCAST
BOOTREQUEST, BOOTREPLY, DHCPV6
} = require './constants'
class Server extends EventEmitter
@createServer: (opt) ->
new Server(opt)
constructor: (config) ->
super()
sock = dgram.createSocket
type: 'udp4'
reuseAddr: true
sock.on 'message', @ipv4Message.bind @
sock.on 'listening', =>
@emit 'listening', sock, ''
sock.on 'close', =>
@emit 'close'
sock6 = dgram.createSocket
type: 'udp6'
reuseAddr: true
sock6.on 'message', @ipv6Message.bind @
sock6.on 'listening', =>
@emit 'listening', sock6, 'v6'
sock6.on 'close', =>
@emit 'close'
@_sock6 = sock6
@_sock = sock
@_conf = config
@_state = {}
ipv4Message: (buf) ->
try
req = Protocol.parse(buf)
catch e
@emit 'error', e
return
@emit 'message', req
if req.op != BOOTREQUEST
@emit 'error', new Error('Malformed packet'), req
return
if not req.options[53]
return @handleRequest req
switch req.options[53]
when DHCPDISCOVER
@handleDiscover req
when DHCPREQUEST
@handleRequest req
ipv6Message: (buf, rinfo) ->
try
req = Protocol.parseIpv6(buf)
catch e
@emit 'error', e
return
@emit 'message', req
@emit DHCPV6.MESSAGETYPE[req.op], req, rinfo
config: (key) ->
optId = Options.conf[key]
if undefined != @_conf[key]
val = @_conf[key]
else if undefined != Options.opts[optId]
val = Options.opts[optId].default
if val == undefined
return 0
else
throw new Error 'Invalid option ' + key
if val instanceof Function
val = val.call @
values = Options.opts[optId]?.enum
if key not in [ 'range', 'static', 'randomIP' ] and values
for i, v of values when v is val
return parseInt i, 10
if values[val] is undefined
throw new Error 'Provided enum value for ' + key + ' is not valid'
else
val = parseInt val, 10
val
_getOptions: (pre, required, requested) ->
for req in required
if Options.opts[req] != undefined
pre[req] ?= @config(Options.opts[req].config)
if not pre[req]
throw new Error "Required option #{ Options.opts[req].config } does not have a value set"
else
@emit 'error', 'Unknown option ' + req
if requested
for req in requested
if Options.opts[req] isnt undefined and pre[req] is undefined
val = @config(Options.opts[req].config)
if val
pre[req] = val
else
@emit 'error', 'Unknown option ' + req
forceOptions = @_conf.forceOptions
if Array.isArray forceOptions
for option in forceOptions
if isNaN option
id = Options.conf[option]
else
id = option
if id? and pre[id] is undefined
pre[id] = @config(option)
pre
_selectAddress: (clientMAC, req) ->
if @_state[clientMAC]?.address
return @_state[clientMAC].address
_static = @config 'static'
if typeof _static is 'function'
staticResult = _static clientMAC, req
if staticResult
return staticResult
else if _static[clientMAC]
return _static[clientMAC]
randIP = @config 'randomIP'
_tmp = @config 'range'
firstIP = Tools.parseIp _tmp[0]
lastIP = Tools.parseIp _tmp[1]
ips = [ @config('server') ]
oldestMac = null
oldestTime = Infinity
leases = 0
for mac, v of @_state
if v.address
ips.push v.address
if v.leaseTime < oldestTime
oldestTime = v.leaseTime
oldestMac = mac
leases++
if oldestMac and lastIP - firstIP == leases
ip = @_state[oldestMac].address
delete @_state[oldestMac]
return ip
if randIP
loop
ip = Tools.formatIp(firstIP + Math.random() * (lastIP - firstIP) | 0)
if ips.indexOf(ip) == -1
return ip
i = firstIP
while i <= lastIP
ip = Tools.formatIp i
if ip not in ips
return ip
i++
handleDiscover: (req) ->
lease = @_state[req.chaddr] = @_state[req.chaddr] or new Lease
lease.address = @_selectAddress(req.chaddr, req)
lease.leasePeriod = @config 'leaseTime'
lease.server = @config 'server'
lease.state = 'OFFERED'
console.log '>>> DISCOVER', JSON.stringify lease
@sendOffer req
sendOffer: (req) ->
if req.options[97] and req.options[55].indexOf(97) == -1
req.options[55].push 97
if req.options[60] and req.options[60].indexOf('PXEClient') == 0
[ 66, 67 ].forEach (opt) ->
if req.options[55].indexOf(opt) is -1
req.options[55].push opt
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: INADDR_ANY
yiaddr: @_selectAddress req.chaddr
siaddr: @config 'server'
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: ''
options: @_getOptions { 53: DHCPOFFER }, [
1
3
51
54
6
], req.options[55]
console.log '<<< OFFER', JSON.stringify ans
@_send @config('broadcast'), ans
handleRequest: (req) ->
lease = @_state[req.chaddr] = @_state[req.chaddr] or new Lease
lease.address = @_selectAddress req.chaddr
lease.leasePeriod = @config 'leaseTime'
lease.server = @config 'server'
lease.state = 'BOUND'
lease.bindTime = new Date
lease.file = req.file
console.log '>>> REQUEST', JSON.stringify lease
@sendAck req
sendAck: (req) ->
if req.options[97] and req.options[55].indexOf(97) == -1
req.options[55].push 97
if req.options[60] and req.options[60].indexOf('PXEClient') == 0
[ 66, 67 ].forEach (opt) ->
if req.options[55].indexOf(opt) is -1
req.options[55].push opt
options = @_getOptions { 53: DHCPACK }, [
1
3
51
54
6
], req.options[55]
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: req.ciaddr
yiaddr: @_selectAddress req.chaddr
siaddr: @config 'server'
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: req.file
options: options
@_send @config('broadcast'), ans, =>
@emit 'bound', @_state, ans
sendNak: (req) ->
ans =
op: BOOTREPLY
htype: 1
hlen: 6
hops: 0
xid: req.xid
secs: 0
flags: req.flags
ciaddr: INADDR_ANY
yiaddr: INADDR_ANY
siaddr: INADDR_ANY
giaddr: req.giaddr
chaddr: req.chaddr
sname: ''
file: ''
options: @_getOptions { 53: DHCPNAK }, [ 54 ]
console.log '<<< NAK', JSON.stringify ans
@_send @config('broadcast'), ans
handleRelease: ->
handleRenew: ->
return
listen: (port, host, fn = ->) ->
ip = Ips().find ({ family }) -> family is 'IPv6'
connacks = Number not not ip
onConnect = ->
connacks++
if connacks is 2
process.nextTick fn
@_sock.bind port or SERVER_PORT, host or INADDR_ANY, =>
@_sock.setBroadcast true
onConnect()
if ip
@_sock6.bind 547, '::', =>
@_sock6.setBroadcast true
try
@_sock6.addMembership 'PI:IP_ADDRESS:fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3bEND_PI', ip.address
catch e
onConnect()
@
close: (callback) ->
connacks = 0
onClose = ->
connacks++
if connacks is 2
callback()
@_sock.close onClose
@_sock6.close onClose
_send: (host, data, cb = ->) ->
sb = Protocol.format data
@_sock.send sb._data, 0, sb._w, CLIENT_PORT, host, (err, bytes) ->
if err
console.log err
cb err, bytes
module.exports = Server
|
[
{
"context": "# GainText\n#\n# Martin Waitz <tali@admingilde.org>\n\nsut = require '../src/docu",
"end": 27,
"score": 0.9998314380645752,
"start": 15,
"tag": "NAME",
"value": "Martin Waitz"
},
{
"context": "# GainText\n#\n# Martin Waitz <tali@admingilde.org>\n\nsut = require '../src/... | test/document.coffee | gaintext/gaintext.js | 0 | # GainText
#
# Martin Waitz <tali@admingilde.org>
sut = require '../src/document'
mona = require 'mona-parser'
{expect} = require 'chai'
describe 'document', ->
it 'parses a single element', ->
text = "div:\n"
expect(mona.parse sut.document, text).to.eql [
name: 'div', title: '', content: []
]
it 'parses several elements', ->
text = "div:\npre:\n"
expect(mona.parse sut.document, text).to.eql [
{name: 'div', title: '', content: []}
{name: 'pre', title: '', content: []}
]
it 'parses a single paragraph', ->
text = "Hello World\n"
expect(mona.parse sut.document, text).to.eql [
[['Hello World']]
]
it 'parses a line which is similar to an element', ->
text = "Hello World:\n"
expect(mona.parse sut.document, text).to.eql [
[['Hello World:']]
]
it 'ignores leading blank lines', ->
text = "\n\nparagraph\n"
expect(mona.parse sut.document, text).to.eql [
[['paragraph']]
]
it 'ignores trailing blank lines', ->
text = "\nparagraph\n\n"
expect(mona.parse sut.document, text).to.eql [
[['paragraph']]]
it 'parses multiple paragraphs', ->
text = "first\nparagraph\n\nsecond\nparagraph\n"
expect(mona.parse sut.document, text).to.eql [
[['first'], ['paragraph']]
[['second'], ['paragraph']]
]
it 'parses hierarchy of block elements', ->
text =
"""
div: a simple document
Introduction text
for the example
pre:
text
"""
expect(mona.parse sut.document, text).to.eql [
name: 'div', title: 'a simple document', content: [
[['Introduction text'], ['for the example']]
name: 'pre', title: '', content: [[['text']]]
]
]
it 'parses embedded span element', ->
text = "[span title: [span inner]]\n"
expect(mona.parse sut.document, text).to.eql [
[[
name: 'span', title: 'title', content: [
name: 'span', title: 'inner', content: []
]
]]
]
it 'parses embedded span element with text', ->
text = "[span title: before[span inner]after]\n"
expect(mona.parse sut.document, text).to.eql [
[[
name: 'span', title: 'title', content: [
"before"
name: 'span', title: 'inner', content: []
"after"
]
]]
]
| 220462 | # GainText
#
# <NAME> <<EMAIL>>
sut = require '../src/document'
mona = require 'mona-parser'
{expect} = require 'chai'
describe 'document', ->
it 'parses a single element', ->
text = "div:\n"
expect(mona.parse sut.document, text).to.eql [
name: 'div', title: '', content: []
]
it 'parses several elements', ->
text = "div:\npre:\n"
expect(mona.parse sut.document, text).to.eql [
{name: 'div', title: '', content: []}
{name: 'pre', title: '', content: []}
]
it 'parses a single paragraph', ->
text = "Hello World\n"
expect(mona.parse sut.document, text).to.eql [
[['Hello World']]
]
it 'parses a line which is similar to an element', ->
text = "Hello World:\n"
expect(mona.parse sut.document, text).to.eql [
[['Hello World:']]
]
it 'ignores leading blank lines', ->
text = "\n\nparagraph\n"
expect(mona.parse sut.document, text).to.eql [
[['paragraph']]
]
it 'ignores trailing blank lines', ->
text = "\nparagraph\n\n"
expect(mona.parse sut.document, text).to.eql [
[['paragraph']]]
it 'parses multiple paragraphs', ->
text = "first\nparagraph\n\nsecond\nparagraph\n"
expect(mona.parse sut.document, text).to.eql [
[['first'], ['paragraph']]
[['second'], ['paragraph']]
]
it 'parses hierarchy of block elements', ->
text =
"""
div: a simple document
Introduction text
for the example
pre:
text
"""
expect(mona.parse sut.document, text).to.eql [
name: 'div', title: 'a simple document', content: [
[['Introduction text'], ['for the example']]
name: 'pre', title: '', content: [[['text']]]
]
]
it 'parses embedded span element', ->
text = "[span title: [span inner]]\n"
expect(mona.parse sut.document, text).to.eql [
[[
name: 'span', title: 'title', content: [
name: 'span', title: 'inner', content: []
]
]]
]
it 'parses embedded span element with text', ->
text = "[span title: before[span inner]after]\n"
expect(mona.parse sut.document, text).to.eql [
[[
name: 'span', title: 'title', content: [
"before"
name: 'span', title: 'inner', content: []
"after"
]
]]
]
| true | # GainText
#
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
sut = require '../src/document'
mona = require 'mona-parser'
{expect} = require 'chai'
describe 'document', ->
it 'parses a single element', ->
text = "div:\n"
expect(mona.parse sut.document, text).to.eql [
name: 'div', title: '', content: []
]
it 'parses several elements', ->
text = "div:\npre:\n"
expect(mona.parse sut.document, text).to.eql [
{name: 'div', title: '', content: []}
{name: 'pre', title: '', content: []}
]
it 'parses a single paragraph', ->
text = "Hello World\n"
expect(mona.parse sut.document, text).to.eql [
[['Hello World']]
]
it 'parses a line which is similar to an element', ->
text = "Hello World:\n"
expect(mona.parse sut.document, text).to.eql [
[['Hello World:']]
]
it 'ignores leading blank lines', ->
text = "\n\nparagraph\n"
expect(mona.parse sut.document, text).to.eql [
[['paragraph']]
]
it 'ignores trailing blank lines', ->
text = "\nparagraph\n\n"
expect(mona.parse sut.document, text).to.eql [
[['paragraph']]]
it 'parses multiple paragraphs', ->
text = "first\nparagraph\n\nsecond\nparagraph\n"
expect(mona.parse sut.document, text).to.eql [
[['first'], ['paragraph']]
[['second'], ['paragraph']]
]
it 'parses hierarchy of block elements', ->
text =
"""
div: a simple document
Introduction text
for the example
pre:
text
"""
expect(mona.parse sut.document, text).to.eql [
name: 'div', title: 'a simple document', content: [
[['Introduction text'], ['for the example']]
name: 'pre', title: '', content: [[['text']]]
]
]
it 'parses embedded span element', ->
text = "[span title: [span inner]]\n"
expect(mona.parse sut.document, text).to.eql [
[[
name: 'span', title: 'title', content: [
name: 'span', title: 'inner', content: []
]
]]
]
it 'parses embedded span element with text', ->
text = "[span title: before[span inner]after]\n"
expect(mona.parse sut.document, text).to.eql [
[[
name: 'span', title: 'title', content: [
"before"
name: 'span', title: 'inner', content: []
"after"
]
]]
]
|
[
{
"context": " it 'clears data', ->\n p = {data:{id:{name:'sam'}}}\n assert.equal null, ot.applyPresence p, ",
"end": 9763,
"score": 0.9299773573875427,
"start": 9760,
"tag": "NAME",
"value": "sam"
}
] | test/ot.coffee | kantele/k-livedb | 1 | # Unit tests for lib/ot.js
#
# This tests to make sure it does some of the right things WRT OT.
#
# Note that there's also OT code in other livedb files. This file does not
# contain any integration tests.
assert = require 'assert'
text = require('ot-text').type
ot = require '../lib/ot'
describe 'ot', ->
before ->
# apply and normalize put a creation / modification timestamp on snapshots
# & ops. We'll verify its correct by checking that its in the range of time
# from when the tests start running to 10 seconds after the tests start
# running. Hopefully the tests aren't slower than that.
before = Date.now()
after = before + 10 * 1000
checkMetaTs = (field) -> (data) ->
assert.ok data.m
assert.ok before <= data.m[field] < after
delete data.m[field]
data
@checkOpTs = checkMetaTs 'ts'
@checkDocCreate = checkMetaTs 'ctime'
@checkDocModified = checkMetaTs 'mtime'
@checkDocTs = (doc) =>
@checkDocCreate doc
@checkDocModified doc
doc
describe 'checkOpData', ->
it 'fails if opdata is not an object', ->
assert.ok ot.checkOpData 'hi'
assert.ok ot.checkOpData()
assert.ok ot.checkOpData 123
assert.ok ot.checkOpData []
it 'fails if op data is missing op, create and del', ->
assert.ok ot.checkOpData {v:5}
it 'fails if src/seq data is invalid', ->
assert.ok ot.checkOpData {del:true, v:5, src:'hi'}
assert.ok ot.checkOpData {del:true, v:5, seq:123}
assert.ok ot.checkOpData {del:true, v:5, src:'hi', seq:'there'}
it 'fails if a create operation is missing its type', ->
assert.ok ot.checkOpData {create:{}}
assert.ok ot.checkOpData {create:123}
it 'fails if the type is missing', ->
assert.ok ot.checkOpData {create:{type:"something that does not exist"}}
it 'accepts valid create operations', ->
assert.equal null, ot.checkOpData {create:{type:text.uri}}
assert.equal null, ot.checkOpData {create:{type:text.uri, data:'hi there'}}
it 'accepts valid delete operations', ->
assert.equal null, ot.checkOpData {del:true}
it 'accepts valid ops', ->
assert.equal null, ot.checkOpData {op:[1,2,3]}
describe 'normalize', ->
it 'expands type names in normalizeType', ->
assert.equal text.uri, ot.normalizeType 'text'
it 'expands type names in an op', ->
opData = create:type:'text'
ot.normalize opData
@checkOpTs opData
assert.deepEqual opData, {create:{type:text.uri}, m:{}, src:''}
describe 'apply', ->
it 'fails if the versions dont match', ->
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, create:{type:text.uri}}
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, del:true}
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, op:[]}
it 'allows the version field to be missing', ->
assert.equal null, ot.apply {v:5}, {create:{type:text.uri}}
assert.equal null, ot.apply {}, {v:6, create:{type:text.uri}}
describe 'create', ->
it 'fails if the document already exists', ->
doc = {v:6, create:{type:text.uri}}
assert.equal 'Document already exists', ot.apply {v:6, type:text.uri, data:'hi'}, doc
# The doc should be unmodified
assert.deepEqual doc, {v:6, create:{type:text.uri}}
it 'creates doc data correctly when no initial data is passed', ->
doc = {v:5}
assert.equal null, ot.apply doc, {v:5, create:{type:text.uri}}
@checkDocTs doc
assert.deepEqual doc, {v:6, type:text.uri, m:{}, data:''}
it 'creates doc data when it is given initial data', ->
doc = {v:5}
assert.equal null, ot.apply doc, {v:5, create:{type:text.uri, data:'Hi there'}}
@checkDocTs doc
assert.deepEqual doc, {v:6, type:text.uri, m:{}, data:'Hi there'}
it.skip 'runs pre and post validation functions'
describe 'del', ->
it 'deletes the document data', ->
doc = {v:6, type:text.uri, data:'Hi there'}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{}}
it 'still works if the document doesnt exist anyway', ->
doc = {v:6}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{}}
it 'keeps any metadata from op on the doc', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'hi'}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{ctime:1}}
describe 'op', ->
it 'fails if the document does not exist', ->
assert.equal 'Document does not exist', ot.apply {v:6}, {v:6, op:[1,2,3]}
it 'fails if the type is missing', ->
assert.equal 'Type not found', ot.apply {v:6, type:'some non existant type'}, {v:6, op:[1,2,3]}
it 'applies the operation to the document data', ->
doc = {v:6, type:text.uri, data:'Hi'}
assert.equal null, ot.apply doc, {v:6, op:[2, ' there']}
@checkDocModified doc
assert.deepEqual doc, {v:7, type:text.uri, m:{}, data:'Hi there'}
it 'updates mtime', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
assert.equal null, ot.apply doc, {v:6, op:[2, ' there']}
@checkDocModified doc
assert.deepEqual doc, {v:7, type:text.uri, m:{ctime:1}, data:'Hi there'}
it.skip 'shatters the operation if it can, and applies it incrementally'
describe 'noop', ->
it 'works on existing docs', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
assert.equal null, ot.apply doc, {v:6}
# same, but with v+1.
assert.deepEqual doc, {v:7, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
it 'works on nonexistant docs', ->
doc = {v:0}
assert.equal null, ot.apply doc, {v:0}
assert.deepEqual doc, {v:1}
describe 'transform', ->
it 'fails if the version is specified on both and does not match', ->
op1 = {v:5, op:[10, 'hi']}
op2 = {v:6, op:[5, 'abcde']}
assert.equal 'Version mismatch', ot.transform text.uri, op1, op2
assert.deepEqual op1, {v:5, op:[10, 'hi']}
# There's 9 cases here.
it 'create by create fails', ->
assert.equal 'Document created remotely', ot.transform null, {v:10, create:type:text.uri}, {v:10, create:type:text.uri}
it 'create by delete fails', ->
assert.ok ot.transform null, {create:type:text.uri}, {del:true}
it 'create by op fails', ->
assert.equal 'Document created remotely', ot.transform null, {v:10, create:type:text.uri}, {v:10, op:[15, 'hi']}
it 'create by noop ok', ->
op = {create:{type:text.uri}, v:6}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {create:{type:text.uri}, v:7}
it 'delete by create fails', ->
assert.ok ot.transform null, {del:true}, {create:type:text.uri}
it 'delete by delete ok', ->
op = del:true, v:6
assert.equal null, ot.transform text.uri, op, {del:true, v:6}
assert.deepEqual op, {del:true, v:7}
op = del:true # And with no version specified should work too.
assert.equal null, ot.transform text.uri, op, {del:true, v:6}
assert.deepEqual op, del:true
it 'delete by op ok', ->
op = del:true, v:8
assert.equal null, ot.transform text.uri, op, {op:[], v:8}
assert.deepEqual op, {del:true, v:9}
op = del:true # And with no version specified should work too.
assert.equal null, ot.transform text.uri, op, {op:[], v:8}
assert.deepEqual op, {del:true}
it 'delete by noop ok', ->
op = {del:true, v:6}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {del:true, v:7}
op = {del:true}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {del:true}
it 'op by create fails', ->
assert.ok ot.transform null, {op:{}}, {create:type:text.uri}
it 'op by delete fails', ->
assert.equal 'Document was deleted', ot.transform text.uri, {v:10, op:[]}, {v:10, del:true}
it 'op by op ok', ->
op1 = {v:6, op:[10, 'hi']}
op2 = {v:6, op:[5, 'abcde']}
assert.equal null, ot.transform text.uri, op1, op2
assert.deepEqual op1, {v:7, op:[15, 'hi']}
op1 = {op:[10, 'hi']} # No version specified
op2 = {v:6, op:[5, 'abcde']}
assert.equal null, ot.transform text.uri, op1, op2
assert.deepEqual op1, {op:[15, 'hi']}
it 'op by noop ok', ->
# I don't think this is ever used, but whatever.
op = {v:6, op:[10, 'hi']}
assert.equal null, ot.transform text.uri, op, {v:6}
assert.deepEqual op, {v:7, op:[10, 'hi']}
it 'noop by anything is ok', ->
op = {}
assert.equal null, ot.transform text.uri, op, {v:6, op:[10, 'hi']}
assert.deepEqual op, {}
assert.equal null, ot.transform text.uri, op, {del:true}
assert.deepEqual op, {}
assert.equal null, ot.transform null, op, {create:type:text.uri}
assert.deepEqual op, {}
assert.equal null, ot.transform null, op, {}
assert.deepEqual op, {}
# And op by op is tested in the first couple of tests.
describe 'applyPresence', ->
it 'sets', ->
p = {data:{}}
assert.equal null, ot.applyPresence p, {val:{id:{y:6}}}
assert.deepEqual p, data:{id:{y:6}}
assert.equal null, ot.applyPresence p, {p:['id'], val:{z:7}}
assert.deepEqual p, data:{id:{z:7}}
assert.equal null, ot.applyPresence p, {p:['id','z'], val:8}
assert.deepEqual p, data:{id:{z:8}}
it 'clears data', ->
p = {data:{id:{name:'sam'}}}
assert.equal null, ot.applyPresence p, {val:null}
assert.deepEqual p, data:{}
it "doesn't allow special keys other than _cursor", ->
p = {}
# assert.equal 'Cannot set reserved value', ot.applyPresence p, {val:{id:{_x:'hi'}}}
# assert.deepEqual p, {}
assert.equal 'Cannot set reserved value', ot.applyPresence p, {p:['id'], val:{_x:'hi'}}
assert.deepEqual p, {}
assert.equal 'Cannot set reserved value', ot.applyPresence p, {p:['id','_x'], val:'hi'}
assert.deepEqual p, {}
describe 'transformPresence', ->
it 'updates cursor positions', ->
| 170689 | # Unit tests for lib/ot.js
#
# This tests to make sure it does some of the right things WRT OT.
#
# Note that there's also OT code in other livedb files. This file does not
# contain any integration tests.
assert = require 'assert'
text = require('ot-text').type
ot = require '../lib/ot'
describe 'ot', ->
before ->
# apply and normalize put a creation / modification timestamp on snapshots
# & ops. We'll verify its correct by checking that its in the range of time
# from when the tests start running to 10 seconds after the tests start
# running. Hopefully the tests aren't slower than that.
before = Date.now()
after = before + 10 * 1000
checkMetaTs = (field) -> (data) ->
assert.ok data.m
assert.ok before <= data.m[field] < after
delete data.m[field]
data
@checkOpTs = checkMetaTs 'ts'
@checkDocCreate = checkMetaTs 'ctime'
@checkDocModified = checkMetaTs 'mtime'
@checkDocTs = (doc) =>
@checkDocCreate doc
@checkDocModified doc
doc
describe 'checkOpData', ->
it 'fails if opdata is not an object', ->
assert.ok ot.checkOpData 'hi'
assert.ok ot.checkOpData()
assert.ok ot.checkOpData 123
assert.ok ot.checkOpData []
it 'fails if op data is missing op, create and del', ->
assert.ok ot.checkOpData {v:5}
it 'fails if src/seq data is invalid', ->
assert.ok ot.checkOpData {del:true, v:5, src:'hi'}
assert.ok ot.checkOpData {del:true, v:5, seq:123}
assert.ok ot.checkOpData {del:true, v:5, src:'hi', seq:'there'}
it 'fails if a create operation is missing its type', ->
assert.ok ot.checkOpData {create:{}}
assert.ok ot.checkOpData {create:123}
it 'fails if the type is missing', ->
assert.ok ot.checkOpData {create:{type:"something that does not exist"}}
it 'accepts valid create operations', ->
assert.equal null, ot.checkOpData {create:{type:text.uri}}
assert.equal null, ot.checkOpData {create:{type:text.uri, data:'hi there'}}
it 'accepts valid delete operations', ->
assert.equal null, ot.checkOpData {del:true}
it 'accepts valid ops', ->
assert.equal null, ot.checkOpData {op:[1,2,3]}
describe 'normalize', ->
it 'expands type names in normalizeType', ->
assert.equal text.uri, ot.normalizeType 'text'
it 'expands type names in an op', ->
opData = create:type:'text'
ot.normalize opData
@checkOpTs opData
assert.deepEqual opData, {create:{type:text.uri}, m:{}, src:''}
describe 'apply', ->
it 'fails if the versions dont match', ->
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, create:{type:text.uri}}
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, del:true}
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, op:[]}
it 'allows the version field to be missing', ->
assert.equal null, ot.apply {v:5}, {create:{type:text.uri}}
assert.equal null, ot.apply {}, {v:6, create:{type:text.uri}}
describe 'create', ->
it 'fails if the document already exists', ->
doc = {v:6, create:{type:text.uri}}
assert.equal 'Document already exists', ot.apply {v:6, type:text.uri, data:'hi'}, doc
# The doc should be unmodified
assert.deepEqual doc, {v:6, create:{type:text.uri}}
it 'creates doc data correctly when no initial data is passed', ->
doc = {v:5}
assert.equal null, ot.apply doc, {v:5, create:{type:text.uri}}
@checkDocTs doc
assert.deepEqual doc, {v:6, type:text.uri, m:{}, data:''}
it 'creates doc data when it is given initial data', ->
doc = {v:5}
assert.equal null, ot.apply doc, {v:5, create:{type:text.uri, data:'Hi there'}}
@checkDocTs doc
assert.deepEqual doc, {v:6, type:text.uri, m:{}, data:'Hi there'}
it.skip 'runs pre and post validation functions'
describe 'del', ->
it 'deletes the document data', ->
doc = {v:6, type:text.uri, data:'Hi there'}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{}}
it 'still works if the document doesnt exist anyway', ->
doc = {v:6}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{}}
it 'keeps any metadata from op on the doc', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'hi'}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{ctime:1}}
describe 'op', ->
it 'fails if the document does not exist', ->
assert.equal 'Document does not exist', ot.apply {v:6}, {v:6, op:[1,2,3]}
it 'fails if the type is missing', ->
assert.equal 'Type not found', ot.apply {v:6, type:'some non existant type'}, {v:6, op:[1,2,3]}
it 'applies the operation to the document data', ->
doc = {v:6, type:text.uri, data:'Hi'}
assert.equal null, ot.apply doc, {v:6, op:[2, ' there']}
@checkDocModified doc
assert.deepEqual doc, {v:7, type:text.uri, m:{}, data:'Hi there'}
it 'updates mtime', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
assert.equal null, ot.apply doc, {v:6, op:[2, ' there']}
@checkDocModified doc
assert.deepEqual doc, {v:7, type:text.uri, m:{ctime:1}, data:'Hi there'}
it.skip 'shatters the operation if it can, and applies it incrementally'
describe 'noop', ->
it 'works on existing docs', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
assert.equal null, ot.apply doc, {v:6}
# same, but with v+1.
assert.deepEqual doc, {v:7, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
it 'works on nonexistant docs', ->
doc = {v:0}
assert.equal null, ot.apply doc, {v:0}
assert.deepEqual doc, {v:1}
describe 'transform', ->
it 'fails if the version is specified on both and does not match', ->
op1 = {v:5, op:[10, 'hi']}
op2 = {v:6, op:[5, 'abcde']}
assert.equal 'Version mismatch', ot.transform text.uri, op1, op2
assert.deepEqual op1, {v:5, op:[10, 'hi']}
# There's 9 cases here.
it 'create by create fails', ->
assert.equal 'Document created remotely', ot.transform null, {v:10, create:type:text.uri}, {v:10, create:type:text.uri}
it 'create by delete fails', ->
assert.ok ot.transform null, {create:type:text.uri}, {del:true}
it 'create by op fails', ->
assert.equal 'Document created remotely', ot.transform null, {v:10, create:type:text.uri}, {v:10, op:[15, 'hi']}
it 'create by noop ok', ->
op = {create:{type:text.uri}, v:6}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {create:{type:text.uri}, v:7}
it 'delete by create fails', ->
assert.ok ot.transform null, {del:true}, {create:type:text.uri}
it 'delete by delete ok', ->
op = del:true, v:6
assert.equal null, ot.transform text.uri, op, {del:true, v:6}
assert.deepEqual op, {del:true, v:7}
op = del:true # And with no version specified should work too.
assert.equal null, ot.transform text.uri, op, {del:true, v:6}
assert.deepEqual op, del:true
it 'delete by op ok', ->
op = del:true, v:8
assert.equal null, ot.transform text.uri, op, {op:[], v:8}
assert.deepEqual op, {del:true, v:9}
op = del:true # And with no version specified should work too.
assert.equal null, ot.transform text.uri, op, {op:[], v:8}
assert.deepEqual op, {del:true}
it 'delete by noop ok', ->
op = {del:true, v:6}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {del:true, v:7}
op = {del:true}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {del:true}
it 'op by create fails', ->
assert.ok ot.transform null, {op:{}}, {create:type:text.uri}
it 'op by delete fails', ->
assert.equal 'Document was deleted', ot.transform text.uri, {v:10, op:[]}, {v:10, del:true}
it 'op by op ok', ->
op1 = {v:6, op:[10, 'hi']}
op2 = {v:6, op:[5, 'abcde']}
assert.equal null, ot.transform text.uri, op1, op2
assert.deepEqual op1, {v:7, op:[15, 'hi']}
op1 = {op:[10, 'hi']} # No version specified
op2 = {v:6, op:[5, 'abcde']}
assert.equal null, ot.transform text.uri, op1, op2
assert.deepEqual op1, {op:[15, 'hi']}
it 'op by noop ok', ->
# I don't think this is ever used, but whatever.
op = {v:6, op:[10, 'hi']}
assert.equal null, ot.transform text.uri, op, {v:6}
assert.deepEqual op, {v:7, op:[10, 'hi']}
it 'noop by anything is ok', ->
op = {}
assert.equal null, ot.transform text.uri, op, {v:6, op:[10, 'hi']}
assert.deepEqual op, {}
assert.equal null, ot.transform text.uri, op, {del:true}
assert.deepEqual op, {}
assert.equal null, ot.transform null, op, {create:type:text.uri}
assert.deepEqual op, {}
assert.equal null, ot.transform null, op, {}
assert.deepEqual op, {}
# And op by op is tested in the first couple of tests.
describe 'applyPresence', ->
it 'sets', ->
p = {data:{}}
assert.equal null, ot.applyPresence p, {val:{id:{y:6}}}
assert.deepEqual p, data:{id:{y:6}}
assert.equal null, ot.applyPresence p, {p:['id'], val:{z:7}}
assert.deepEqual p, data:{id:{z:7}}
assert.equal null, ot.applyPresence p, {p:['id','z'], val:8}
assert.deepEqual p, data:{id:{z:8}}
it 'clears data', ->
p = {data:{id:{name:'<NAME>'}}}
assert.equal null, ot.applyPresence p, {val:null}
assert.deepEqual p, data:{}
it "doesn't allow special keys other than _cursor", ->
p = {}
# assert.equal 'Cannot set reserved value', ot.applyPresence p, {val:{id:{_x:'hi'}}}
# assert.deepEqual p, {}
assert.equal 'Cannot set reserved value', ot.applyPresence p, {p:['id'], val:{_x:'hi'}}
assert.deepEqual p, {}
assert.equal 'Cannot set reserved value', ot.applyPresence p, {p:['id','_x'], val:'hi'}
assert.deepEqual p, {}
describe 'transformPresence', ->
it 'updates cursor positions', ->
| true | # Unit tests for lib/ot.js
#
# This tests to make sure it does some of the right things WRT OT.
#
# Note that there's also OT code in other livedb files. This file does not
# contain any integration tests.
assert = require 'assert'
text = require('ot-text').type
ot = require '../lib/ot'
describe 'ot', ->
before ->
# apply and normalize put a creation / modification timestamp on snapshots
# & ops. We'll verify its correct by checking that its in the range of time
# from when the tests start running to 10 seconds after the tests start
# running. Hopefully the tests aren't slower than that.
before = Date.now()
after = before + 10 * 1000
checkMetaTs = (field) -> (data) ->
assert.ok data.m
assert.ok before <= data.m[field] < after
delete data.m[field]
data
@checkOpTs = checkMetaTs 'ts'
@checkDocCreate = checkMetaTs 'ctime'
@checkDocModified = checkMetaTs 'mtime'
@checkDocTs = (doc) =>
@checkDocCreate doc
@checkDocModified doc
doc
describe 'checkOpData', ->
it 'fails if opdata is not an object', ->
assert.ok ot.checkOpData 'hi'
assert.ok ot.checkOpData()
assert.ok ot.checkOpData 123
assert.ok ot.checkOpData []
it 'fails if op data is missing op, create and del', ->
assert.ok ot.checkOpData {v:5}
it 'fails if src/seq data is invalid', ->
assert.ok ot.checkOpData {del:true, v:5, src:'hi'}
assert.ok ot.checkOpData {del:true, v:5, seq:123}
assert.ok ot.checkOpData {del:true, v:5, src:'hi', seq:'there'}
it 'fails if a create operation is missing its type', ->
assert.ok ot.checkOpData {create:{}}
assert.ok ot.checkOpData {create:123}
it 'fails if the type is missing', ->
assert.ok ot.checkOpData {create:{type:"something that does not exist"}}
it 'accepts valid create operations', ->
assert.equal null, ot.checkOpData {create:{type:text.uri}}
assert.equal null, ot.checkOpData {create:{type:text.uri, data:'hi there'}}
it 'accepts valid delete operations', ->
assert.equal null, ot.checkOpData {del:true}
it 'accepts valid ops', ->
assert.equal null, ot.checkOpData {op:[1,2,3]}
describe 'normalize', ->
it 'expands type names in normalizeType', ->
assert.equal text.uri, ot.normalizeType 'text'
it 'expands type names in an op', ->
opData = create:type:'text'
ot.normalize opData
@checkOpTs opData
assert.deepEqual opData, {create:{type:text.uri}, m:{}, src:''}
describe 'apply', ->
it 'fails if the versions dont match', ->
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, create:{type:text.uri}}
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, del:true}
assert.equal 'Version mismatch', ot.apply {v:5}, {v:6, op:[]}
it 'allows the version field to be missing', ->
assert.equal null, ot.apply {v:5}, {create:{type:text.uri}}
assert.equal null, ot.apply {}, {v:6, create:{type:text.uri}}
describe 'create', ->
it 'fails if the document already exists', ->
doc = {v:6, create:{type:text.uri}}
assert.equal 'Document already exists', ot.apply {v:6, type:text.uri, data:'hi'}, doc
# The doc should be unmodified
assert.deepEqual doc, {v:6, create:{type:text.uri}}
it 'creates doc data correctly when no initial data is passed', ->
doc = {v:5}
assert.equal null, ot.apply doc, {v:5, create:{type:text.uri}}
@checkDocTs doc
assert.deepEqual doc, {v:6, type:text.uri, m:{}, data:''}
it 'creates doc data when it is given initial data', ->
doc = {v:5}
assert.equal null, ot.apply doc, {v:5, create:{type:text.uri, data:'Hi there'}}
@checkDocTs doc
assert.deepEqual doc, {v:6, type:text.uri, m:{}, data:'Hi there'}
it.skip 'runs pre and post validation functions'
describe 'del', ->
it 'deletes the document data', ->
doc = {v:6, type:text.uri, data:'Hi there'}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{}}
it 'still works if the document doesnt exist anyway', ->
doc = {v:6}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{}}
it 'keeps any metadata from op on the doc', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'hi'}
assert.equal null, ot.apply doc, {v:6, del:true}
delete doc.m.mtime
assert.deepEqual doc, {v:7, m:{ctime:1}}
describe 'op', ->
it 'fails if the document does not exist', ->
assert.equal 'Document does not exist', ot.apply {v:6}, {v:6, op:[1,2,3]}
it 'fails if the type is missing', ->
assert.equal 'Type not found', ot.apply {v:6, type:'some non existant type'}, {v:6, op:[1,2,3]}
it 'applies the operation to the document data', ->
doc = {v:6, type:text.uri, data:'Hi'}
assert.equal null, ot.apply doc, {v:6, op:[2, ' there']}
@checkDocModified doc
assert.deepEqual doc, {v:7, type:text.uri, m:{}, data:'Hi there'}
it 'updates mtime', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
assert.equal null, ot.apply doc, {v:6, op:[2, ' there']}
@checkDocModified doc
assert.deepEqual doc, {v:7, type:text.uri, m:{ctime:1}, data:'Hi there'}
it.skip 'shatters the operation if it can, and applies it incrementally'
describe 'noop', ->
it 'works on existing docs', ->
doc = {v:6, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
assert.equal null, ot.apply doc, {v:6}
# same, but with v+1.
assert.deepEqual doc, {v:7, type:text.uri, m:{ctime:1, mtime:2}, data:'Hi'}
it 'works on nonexistant docs', ->
doc = {v:0}
assert.equal null, ot.apply doc, {v:0}
assert.deepEqual doc, {v:1}
describe 'transform', ->
it 'fails if the version is specified on both and does not match', ->
op1 = {v:5, op:[10, 'hi']}
op2 = {v:6, op:[5, 'abcde']}
assert.equal 'Version mismatch', ot.transform text.uri, op1, op2
assert.deepEqual op1, {v:5, op:[10, 'hi']}
# There's 9 cases here.
it 'create by create fails', ->
assert.equal 'Document created remotely', ot.transform null, {v:10, create:type:text.uri}, {v:10, create:type:text.uri}
it 'create by delete fails', ->
assert.ok ot.transform null, {create:type:text.uri}, {del:true}
it 'create by op fails', ->
assert.equal 'Document created remotely', ot.transform null, {v:10, create:type:text.uri}, {v:10, op:[15, 'hi']}
it 'create by noop ok', ->
op = {create:{type:text.uri}, v:6}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {create:{type:text.uri}, v:7}
it 'delete by create fails', ->
assert.ok ot.transform null, {del:true}, {create:type:text.uri}
it 'delete by delete ok', ->
op = del:true, v:6
assert.equal null, ot.transform text.uri, op, {del:true, v:6}
assert.deepEqual op, {del:true, v:7}
op = del:true # And with no version specified should work too.
assert.equal null, ot.transform text.uri, op, {del:true, v:6}
assert.deepEqual op, del:true
it 'delete by op ok', ->
op = del:true, v:8
assert.equal null, ot.transform text.uri, op, {op:[], v:8}
assert.deepEqual op, {del:true, v:9}
op = del:true # And with no version specified should work too.
assert.equal null, ot.transform text.uri, op, {op:[], v:8}
assert.deepEqual op, {del:true}
it 'delete by noop ok', ->
op = {del:true, v:6}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {del:true, v:7}
op = {del:true}
assert.equal null, ot.transform null, op, {v:6}
assert.deepEqual op, {del:true}
it 'op by create fails', ->
assert.ok ot.transform null, {op:{}}, {create:type:text.uri}
it 'op by delete fails', ->
assert.equal 'Document was deleted', ot.transform text.uri, {v:10, op:[]}, {v:10, del:true}
it 'op by op ok', ->
op1 = {v:6, op:[10, 'hi']}
op2 = {v:6, op:[5, 'abcde']}
assert.equal null, ot.transform text.uri, op1, op2
assert.deepEqual op1, {v:7, op:[15, 'hi']}
op1 = {op:[10, 'hi']} # No version specified
op2 = {v:6, op:[5, 'abcde']}
assert.equal null, ot.transform text.uri, op1, op2
assert.deepEqual op1, {op:[15, 'hi']}
it 'op by noop ok', ->
# I don't think this is ever used, but whatever.
op = {v:6, op:[10, 'hi']}
assert.equal null, ot.transform text.uri, op, {v:6}
assert.deepEqual op, {v:7, op:[10, 'hi']}
it 'noop by anything is ok', ->
op = {}
assert.equal null, ot.transform text.uri, op, {v:6, op:[10, 'hi']}
assert.deepEqual op, {}
assert.equal null, ot.transform text.uri, op, {del:true}
assert.deepEqual op, {}
assert.equal null, ot.transform null, op, {create:type:text.uri}
assert.deepEqual op, {}
assert.equal null, ot.transform null, op, {}
assert.deepEqual op, {}
# And op by op is tested in the first couple of tests.
describe 'applyPresence', ->
it 'sets', ->
p = {data:{}}
assert.equal null, ot.applyPresence p, {val:{id:{y:6}}}
assert.deepEqual p, data:{id:{y:6}}
assert.equal null, ot.applyPresence p, {p:['id'], val:{z:7}}
assert.deepEqual p, data:{id:{z:7}}
assert.equal null, ot.applyPresence p, {p:['id','z'], val:8}
assert.deepEqual p, data:{id:{z:8}}
it 'clears data', ->
p = {data:{id:{name:'PI:NAME:<NAME>END_PI'}}}
assert.equal null, ot.applyPresence p, {val:null}
assert.deepEqual p, data:{}
it "doesn't allow special keys other than _cursor", ->
p = {}
# assert.equal 'Cannot set reserved value', ot.applyPresence p, {val:{id:{_x:'hi'}}}
# assert.deepEqual p, {}
assert.equal 'Cannot set reserved value', ot.applyPresence p, {p:['id'], val:{_x:'hi'}}
assert.deepEqual p, {}
assert.equal 'Cannot set reserved value', ot.applyPresence p, {p:['id','_x'], val:'hi'}
assert.deepEqual p, {}
describe 'transformPresence', ->
it 'updates cursor positions', ->
|
[
{
"context": "ame = require('os').hostname()\n\nbuildKey = (key)-> \"#{name}.#{hostname}.#{key}\"\nbuildGlobalKey = (key)-> \"#{name}.global.#{key}",
"end": 368,
"score": 0.9591077566146851,
"start": 342,
"tag": "KEY",
"value": "\"#{name}.#{hostname}.#{key"
},
{
"context": "name}.#{h... | metrics.coffee | das7pad/metrics-sharelatex | 0 | if process.env["USE_PROM_METRICS"] != "true"
return module.exports = require("./statsd/metrics")
else
console.log("using prometheus")
prom = require('prom-client')
Register = require('prom-client').register
collectDefaultMetrics = prom.collectDefaultMetrics
appname = "unknown"
hostname = require('os').hostname()
buildKey = (key)-> "#{name}.#{hostname}.#{key}"
buildGlobalKey = (key)-> "#{name}.global.#{key}"
promMetrics = {}
destructors = []
require "./uv_threadpool_size"
module.exports = Metrics =
register:Register
initialize: (_name) ->
appname = _name
collectDefaultMetrics({ timeout: 5000, prefix: Metrics.buildPromKey()})
console.log("ENABLE_TRACE_AGENT set to #{process.env['ENABLE_TRACE_AGENT']}")
if process.env['ENABLE_TRACE_AGENT'] == "true"
console.log("starting google trace agent")
traceAgent = require('@google-cloud/trace-agent')
traceOpts =
ignoreUrls: [/^\/status/, /^\/health_check/]
traceAgent.start(traceOpts)
console.log("ENABLE_DEBUG_AGENT set to #{process.env['ENABLE_DEBUG_AGENT']}")
if process.env['ENABLE_DEBUG_AGENT'] == "true"
console.log("starting google debug agent")
debugAgent = require('@google-cloud/debug-agent')
debugAgent.start({
allowExpressions: true,
serviceContext: {
service: appname,
version: process.env['BUILD_VERSION']
}
})
console.log("ENABLE_PROFILE_AGENT set to #{process.env['ENABLE_PROFILE_AGENT']}")
if process.env['ENABLE_PROFILE_AGENT'] == "true"
console.log("starting google profile agent")
profiler = require('@google-cloud/profiler')
profiler.start({
serviceContext: {
service: appname,
version: process.env['BUILD_VERSION']
}
})
Metrics.inc("process_startup")
registerDestructor: (func) ->
destructors.push func
injectMetricsRoute: (app) ->
app.get('/metrics', (req, res) ->
res.set('Content-Type', Register.contentType)
res.end(Register.metrics())
)
buildPromKey: (key = "")->
key.replace /[^a-zA-Z0-9]/g, "_"
sanitizeValue: (value) ->
parseFloat(value)
set : (key, value, sampleRate = 1)->
console.log("counts are not currently supported")
inc : (key, sampleRate = 1, opts = {})->
key = Metrics.buildPromKey(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Counter({
name: key,
help: key,
labelNames: ['app','host','status','method', 'path']
})
opts.app = appname
opts.host = hostname
promMetrics[key].inc(opts)
if process.env['DEBUG_METRICS']
console.log("doing inc", key, opts)
count : (key, count, sampleRate = 1)->
key = Metrics.buildPromKey(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Counter({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].inc({app: appname, host: hostname}, count)
if process.env['DEBUG_METRICS']
console.log("doing count/inc", key, opts)
timing: (key, timeSpan, sampleRate, opts = {})->
key = Metrics.buildPromKey("timer_" + key)
if !promMetrics[key]?
promMetrics[key] = new prom.Summary({
name: key,
help: key,
maxAgeSeconds: 600,
ageBuckets: 10,
labelNames: ['app', 'host', 'path', 'status_code', 'method', 'collection', 'query']
})
opts.app = appname
opts.host = hostname
promMetrics[key].observe(opts, timeSpan)
if process.env['DEBUG_METRICS']
console.log("doing timing", key, opts)
Timer : class
constructor :(key, sampleRate = 1, opts)->
this.start = new Date()
key = Metrics.buildPromKey(key)
this.key = key
this.sampleRate = sampleRate
this.opts = opts
done:->
timeSpan = new Date - this.start
Metrics.timing(this.key, timeSpan, this.sampleRate, this.opts)
return timeSpan
gauge : (key, value, sampleRate = 1)->
key = Metrics.buildPromKey(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Gauge({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].set({app: appname, host: hostname}, this.sanitizeValue(value))
if process.env['DEBUG_METRICS']
console.log("doing gauge", key, opts)
globalGauge: (key, value, sampleRate = 1)->
key = Metrics.buildPromKey(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Gauge({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].set({app: appname},this.sanitizeValue(value))
mongodb: require "./mongodb"
http: require "./http"
open_sockets: require "./open_sockets"
event_loop: require "./event_loop"
memory: require "./memory"
timeAsyncMethod: require('./timeAsyncMethod')
close: () ->
for func in destructors
func()
| 184923 | if process.env["USE_PROM_METRICS"] != "true"
return module.exports = require("./statsd/metrics")
else
console.log("using prometheus")
prom = require('prom-client')
Register = require('prom-client').register
collectDefaultMetrics = prom.collectDefaultMetrics
appname = "unknown"
hostname = require('os').hostname()
buildKey = (key)-> <KEY>}"
buildGlobalKey = (key)-> <KEY>}"
promMetrics = {}
destructors = []
require "./uv_threadpool_size"
module.exports = Metrics =
register:Register
initialize: (_name) ->
appname = _name
collectDefaultMetrics({ timeout: 5000, prefix: Metrics.buildPromKey()})
console.log("ENABLE_TRACE_AGENT set to #{process.env['ENABLE_TRACE_AGENT']}")
if process.env['ENABLE_TRACE_AGENT'] == "true"
console.log("starting google trace agent")
traceAgent = require('@google-cloud/trace-agent')
traceOpts =
ignoreUrls: [/^\/status/, /^\/health_check/]
traceAgent.start(traceOpts)
console.log("ENABLE_DEBUG_AGENT set to #{process.env['ENABLE_DEBUG_AGENT']}")
if process.env['ENABLE_DEBUG_AGENT'] == "true"
console.log("starting google debug agent")
debugAgent = require('@google-cloud/debug-agent')
debugAgent.start({
allowExpressions: true,
serviceContext: {
service: appname,
version: process.env['BUILD_VERSION']
}
})
console.log("ENABLE_PROFILE_AGENT set to #{process.env['ENABLE_PROFILE_AGENT']}")
if process.env['ENABLE_PROFILE_AGENT'] == "true"
console.log("starting google profile agent")
profiler = require('@google-cloud/profiler')
profiler.start({
serviceContext: {
service: appname,
version: process.env['BUILD_VERSION']
}
})
Metrics.inc("process_startup")
registerDestructor: (func) ->
destructors.push func
injectMetricsRoute: (app) ->
app.get('/metrics', (req, res) ->
res.set('Content-Type', Register.contentType)
res.end(Register.metrics())
)
buildPromKey: (key = "")->
key.replace /[^a-zA-Z0-9]/g, "_"
sanitizeValue: (value) ->
parseFloat(value)
set : (key, value, sampleRate = 1)->
console.log("counts are not currently supported")
inc : (key, sampleRate = 1, opts = {})->
key = <KEY>(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Counter({
name: key,
help: key,
labelNames: ['app','host','status','method', 'path']
})
opts.app = appname
opts.host = hostname
promMetrics[key].inc(opts)
if process.env['DEBUG_METRICS']
console.log("doing inc", key, opts)
count : (key, count, sampleRate = 1)->
key = <KEY>.<KEY>PromKey(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Counter({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].inc({app: appname, host: hostname}, count)
if process.env['DEBUG_METRICS']
console.log("doing count/inc", key, opts)
timing: (key, timeSpan, sampleRate, opts = {})->
key = <KEY>("<KEY>)
if !promMetrics[key]?
promMetrics[key] = new prom.Summary({
name: key,
help: key,
maxAgeSeconds: 600,
ageBuckets: 10,
labelNames: ['app', 'host', 'path', 'status_code', 'method', 'collection', 'query']
})
opts.app = appname
opts.host = hostname
promMetrics[key].observe(opts, timeSpan)
if process.env['DEBUG_METRICS']
console.log("doing timing", key, opts)
Timer : class
constructor :(key, sampleRate = 1, opts)->
this.start = new Date()
key = Metrics.<KEY>PromKey(key)
this.key = key
this.sampleRate = sampleRate
this.opts = opts
done:->
timeSpan = new Date - this.start
Metrics.timing(this.key, timeSpan, this.sampleRate, this.opts)
return timeSpan
gauge : (key, value, sampleRate = 1)->
key = <KEY>(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Gauge({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].set({app: appname, host: hostname}, this.sanitizeValue(value))
if process.env['DEBUG_METRICS']
console.log("doing gauge", key, opts)
globalGauge: (key, value, sampleRate = 1)->
key = <KEY>)
if !promMetrics[key]?
promMetrics[key] = new prom.Gauge({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].set({app: appname},this.sanitizeValue(value))
mongodb: require "./mongodb"
http: require "./http"
open_sockets: require "./open_sockets"
event_loop: require "./event_loop"
memory: require "./memory"
timeAsyncMethod: require('./timeAsyncMethod')
close: () ->
for func in destructors
func()
| true | if process.env["USE_PROM_METRICS"] != "true"
return module.exports = require("./statsd/metrics")
else
console.log("using prometheus")
prom = require('prom-client')
Register = require('prom-client').register
collectDefaultMetrics = prom.collectDefaultMetrics
appname = "unknown"
hostname = require('os').hostname()
buildKey = (key)-> PI:KEY:<KEY>END_PI}"
buildGlobalKey = (key)-> PI:KEY:<KEY>END_PI}"
promMetrics = {}
destructors = []
require "./uv_threadpool_size"
module.exports = Metrics =
register:Register
initialize: (_name) ->
appname = _name
collectDefaultMetrics({ timeout: 5000, prefix: Metrics.buildPromKey()})
console.log("ENABLE_TRACE_AGENT set to #{process.env['ENABLE_TRACE_AGENT']}")
if process.env['ENABLE_TRACE_AGENT'] == "true"
console.log("starting google trace agent")
traceAgent = require('@google-cloud/trace-agent')
traceOpts =
ignoreUrls: [/^\/status/, /^\/health_check/]
traceAgent.start(traceOpts)
console.log("ENABLE_DEBUG_AGENT set to #{process.env['ENABLE_DEBUG_AGENT']}")
if process.env['ENABLE_DEBUG_AGENT'] == "true"
console.log("starting google debug agent")
debugAgent = require('@google-cloud/debug-agent')
debugAgent.start({
allowExpressions: true,
serviceContext: {
service: appname,
version: process.env['BUILD_VERSION']
}
})
console.log("ENABLE_PROFILE_AGENT set to #{process.env['ENABLE_PROFILE_AGENT']}")
if process.env['ENABLE_PROFILE_AGENT'] == "true"
console.log("starting google profile agent")
profiler = require('@google-cloud/profiler')
profiler.start({
serviceContext: {
service: appname,
version: process.env['BUILD_VERSION']
}
})
Metrics.inc("process_startup")
registerDestructor: (func) ->
destructors.push func
injectMetricsRoute: (app) ->
app.get('/metrics', (req, res) ->
res.set('Content-Type', Register.contentType)
res.end(Register.metrics())
)
buildPromKey: (key = "")->
key.replace /[^a-zA-Z0-9]/g, "_"
sanitizeValue: (value) ->
parseFloat(value)
set : (key, value, sampleRate = 1)->
console.log("counts are not currently supported")
inc : (key, sampleRate = 1, opts = {})->
key = PI:KEY:<KEY>END_PI(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Counter({
name: key,
help: key,
labelNames: ['app','host','status','method', 'path']
})
opts.app = appname
opts.host = hostname
promMetrics[key].inc(opts)
if process.env['DEBUG_METRICS']
console.log("doing inc", key, opts)
count : (key, count, sampleRate = 1)->
key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PIPromKey(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Counter({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].inc({app: appname, host: hostname}, count)
if process.env['DEBUG_METRICS']
console.log("doing count/inc", key, opts)
timing: (key, timeSpan, sampleRate, opts = {})->
key = PI:KEY:<KEY>END_PI("PI:KEY:<KEY>END_PI)
if !promMetrics[key]?
promMetrics[key] = new prom.Summary({
name: key,
help: key,
maxAgeSeconds: 600,
ageBuckets: 10,
labelNames: ['app', 'host', 'path', 'status_code', 'method', 'collection', 'query']
})
opts.app = appname
opts.host = hostname
promMetrics[key].observe(opts, timeSpan)
if process.env['DEBUG_METRICS']
console.log("doing timing", key, opts)
Timer : class
constructor :(key, sampleRate = 1, opts)->
this.start = new Date()
key = Metrics.PI:KEY:<KEY>END_PIPromKey(key)
this.key = key
this.sampleRate = sampleRate
this.opts = opts
done:->
timeSpan = new Date - this.start
Metrics.timing(this.key, timeSpan, this.sampleRate, this.opts)
return timeSpan
gauge : (key, value, sampleRate = 1)->
key = PI:KEY:<KEY>END_PI(key)
if !promMetrics[key]?
promMetrics[key] = new prom.Gauge({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].set({app: appname, host: hostname}, this.sanitizeValue(value))
if process.env['DEBUG_METRICS']
console.log("doing gauge", key, opts)
globalGauge: (key, value, sampleRate = 1)->
key = PI:KEY:<KEY>END_PI)
if !promMetrics[key]?
promMetrics[key] = new prom.Gauge({
name: key,
help: key,
labelNames: ['app','host']
})
promMetrics[key].set({app: appname},this.sanitizeValue(value))
mongodb: require "./mongodb"
http: require "./http"
open_sockets: require "./open_sockets"
event_loop: require "./event_loop"
memory: require "./memory"
timeAsyncMethod: require('./timeAsyncMethod')
close: () ->
for func in destructors
func()
|
[
{
"context": "greyhound by asking \"@roobot add?\"\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail>\n\npath = require ",
"end": 227,
"score": 0.999875545501709,
"start": 216,
"tag": "NAME",
"value": "Zach Whaley"
},
{
"context": "sking \"@roobot add?\"\n#\n# Author:\n#... | scripts/arrivals.coffee | galtx-centex/roobot | 3 | # Description:
# Add a greyhound to the Available Hounds page
#
# Commands:
# hubot add - Show help text to add a greyhound
# arrivals - Find out how to add a greyhound by asking "@roobot add?"
#
# Author:
# Zach Whaley (zachwhaley) <zachbwhaley@gmail>
path = require 'path'
image = require 'imagemagick'
git = require '../lib/git'
site = require '../lib/site'
util = require '../lib/util'
arrival = (sitePath, greyhound, picUrl, info, callback) ->
fileName = site.newGreyhound sitePath, greyhound
picName = "#{fileName}#{path.extname(picUrl)}"
picPath = "#{sitePath}/img/#{picName}"
info.pic = picName
util.download picUrl, picPath, (err) ->
if err?
return callback "Download Error: #{err}"
# Make thumbnail
thmPath = "#{sitePath}/img/thm/#{picName}"
image.convert [picPath, '-thumbnail', '300x300^', '-gravity', 'center', '-extent', '300x300', thmPath], (err) ->
if err?
return callback "Thumbnail Error: #{err}"
site.dumpGreyhound sitePath, fileName, info, "", callback
addPic = (sitePath, greyhound, picUrl, callback) ->
site.loadGreyhound sitePath, greyhound, (info, bio) ->
if not info?
return callback "Sorry, couldn't find #{greyhound} 😕"
picNum = info.pics?.length ? 0
picName = "#{greyhound}_#{picNum + 1}#{path.extname(picUrl)}"
picPath = "#{sitePath}/img/#{picName}"
util.download picUrl, picPath, (err) ->
if err?
return callback "Download Error: #{err}"
info.pics = [picName] unless info.pics?.push picName
site.dumpGreyhound sitePath, greyhound, info, bio, callback
module.exports = (robot) ->
# arrival help text
robot.respond /add/i, (res) ->
res.reply "To add a greyhound, post a picture to #arrivals with a comment in the format below:\n" +
"\n`name = Name, sex = female/male, dob = m/d/yyyy, color = white and black, cats = yes/no`\n\n" +
"Notice the equals sign between each attribute and its value, and the commas separating each pair of attribute and value."
robot.listen(
(msg) ->
msg.room is 'C5F138J1K' and msg.message?.rawMessage?.files?.length > 0
(res) ->
message = res.message.message
file = message.rawMessage.files[0]
info = site.newInfo message.text
greyhound = util.slugify info.name
name = info.title
picUrl = file.thumb_1024 ? file.url_private
gitOpts =
branch: "arrival-#{greyhound}"
user:
name: message.user?.real_name
email: message.user?.email_address
gitOpts.message = "Add #{name}! 🌟"
res.reply "Adding #{name} to Available Hounds! 🌟\n" +
"Hang on a sec..."
git.review arrival, greyhound, picUrl, info, gitOpts, (update) ->
res.reply update
)
| 190985 | # Description:
# Add a greyhound to the Available Hounds page
#
# Commands:
# hubot add - Show help text to add a greyhound
# arrivals - Find out how to add a greyhound by asking "@roobot add?"
#
# Author:
# <NAME> (zachwhaley) <<EMAIL>>
path = require 'path'
image = require 'imagemagick'
git = require '../lib/git'
site = require '../lib/site'
util = require '../lib/util'
arrival = (sitePath, greyhound, picUrl, info, callback) ->
fileName = site.newGreyhound sitePath, greyhound
picName = "#{fileName}#{path.extname(picUrl)}"
picPath = "#{sitePath}/img/#{picName}"
info.pic = picName
util.download picUrl, picPath, (err) ->
if err?
return callback "Download Error: #{err}"
# Make thumbnail
thmPath = "#{sitePath}/img/thm/#{picName}"
image.convert [picPath, '-thumbnail', '300x300^', '-gravity', 'center', '-extent', '300x300', thmPath], (err) ->
if err?
return callback "Thumbnail Error: #{err}"
site.dumpGreyhound sitePath, fileName, info, "", callback
addPic = (sitePath, greyhound, picUrl, callback) ->
site.loadGreyhound sitePath, greyhound, (info, bio) ->
if not info?
return callback "Sorry, couldn't find #{greyhound} 😕"
picNum = info.pics?.length ? 0
picName = "#{greyhound}_#{picNum + 1}#{path.extname(picUrl)}"
picPath = "#{sitePath}/img/#{picName}"
util.download picUrl, picPath, (err) ->
if err?
return callback "Download Error: #{err}"
info.pics = [picName] unless info.pics?.push picName
site.dumpGreyhound sitePath, greyhound, info, bio, callback
module.exports = (robot) ->
# arrival help text
robot.respond /add/i, (res) ->
res.reply "To add a greyhound, post a picture to #arrivals with a comment in the format below:\n" +
"\n`name = <NAME>, sex = female/male, dob = m/d/yyyy, color = white and black, cats = yes/no`\n\n" +
"Notice the equals sign between each attribute and its value, and the commas separating each pair of attribute and value."
robot.listen(
(msg) ->
msg.room is 'C5F138J1K' and msg.message?.rawMessage?.files?.length > 0
(res) ->
message = res.message.message
file = message.rawMessage.files[0]
info = site.newInfo message.text
greyhound = util.slugify info.name
name = info.title
picUrl = file.thumb_1024 ? file.url_private
gitOpts =
branch: "arrival-#{greyhound}"
user:
name: message.user?.real_name
email: message.user?.email_address
gitOpts.message = "Add #{name}! 🌟"
res.reply "Adding #{name} to Available Hounds! 🌟\n" +
"Hang on a sec..."
git.review arrival, greyhound, picUrl, info, gitOpts, (update) ->
res.reply update
)
| true | # Description:
# Add a greyhound to the Available Hounds page
#
# Commands:
# hubot add - Show help text to add a greyhound
# arrivals - Find out how to add a greyhound by asking "@roobot add?"
#
# Author:
# PI:NAME:<NAME>END_PI (zachwhaley) <PI:EMAIL:<EMAIL>END_PI>
path = require 'path'
image = require 'imagemagick'
git = require '../lib/git'
site = require '../lib/site'
util = require '../lib/util'
arrival = (sitePath, greyhound, picUrl, info, callback) ->
fileName = site.newGreyhound sitePath, greyhound
picName = "#{fileName}#{path.extname(picUrl)}"
picPath = "#{sitePath}/img/#{picName}"
info.pic = picName
util.download picUrl, picPath, (err) ->
if err?
return callback "Download Error: #{err}"
# Make thumbnail
thmPath = "#{sitePath}/img/thm/#{picName}"
image.convert [picPath, '-thumbnail', '300x300^', '-gravity', 'center', '-extent', '300x300', thmPath], (err) ->
if err?
return callback "Thumbnail Error: #{err}"
site.dumpGreyhound sitePath, fileName, info, "", callback
addPic = (sitePath, greyhound, picUrl, callback) ->
site.loadGreyhound sitePath, greyhound, (info, bio) ->
if not info?
return callback "Sorry, couldn't find #{greyhound} 😕"
picNum = info.pics?.length ? 0
picName = "#{greyhound}_#{picNum + 1}#{path.extname(picUrl)}"
picPath = "#{sitePath}/img/#{picName}"
util.download picUrl, picPath, (err) ->
if err?
return callback "Download Error: #{err}"
info.pics = [picName] unless info.pics?.push picName
site.dumpGreyhound sitePath, greyhound, info, bio, callback
module.exports = (robot) ->
# arrival help text
robot.respond /add/i, (res) ->
res.reply "To add a greyhound, post a picture to #arrivals with a comment in the format below:\n" +
"\n`name = PI:NAME:<NAME>END_PI, sex = female/male, dob = m/d/yyyy, color = white and black, cats = yes/no`\n\n" +
"Notice the equals sign between each attribute and its value, and the commas separating each pair of attribute and value."
robot.listen(
(msg) ->
msg.room is 'C5F138J1K' and msg.message?.rawMessage?.files?.length > 0
(res) ->
message = res.message.message
file = message.rawMessage.files[0]
info = site.newInfo message.text
greyhound = util.slugify info.name
name = info.title
picUrl = file.thumb_1024 ? file.url_private
gitOpts =
branch: "arrival-#{greyhound}"
user:
name: message.user?.real_name
email: message.user?.email_address
gitOpts.message = "Add #{name}! 🌟"
res.reply "Adding #{name} to Available Hounds! 🌟\n" +
"Hang on a sec..."
git.review arrival, greyhound, picUrl, info, gitOpts, (update) ->
res.reply update
)
|
[
{
"context": "ema-ext'\n treemaExt.setup()\n filepicker.setKey('AvlkNoldcTOU4PvKi2Xm7z')\n\n # Set up Backbone.Mediator schemas\n setUpDe",
"end": 857,
"score": 0.9993826746940613,
"start": 835,
"tag": "KEY",
"value": "AvlkNoldcTOU4PvKi2Xm7z"
}
] | app/initialize.coffee | madawei2699/codecombat | 0 | app = require 'application'
channelSchemas =
'app': require './schemas/subscriptions/app'
'bus': require './schemas/subscriptions/bus'
'editor': require './schemas/subscriptions/editor'
'errors': require './schemas/subscriptions/errors'
'misc': require './schemas/subscriptions/misc'
'play': require './schemas/subscriptions/play'
'surface': require './schemas/subscriptions/surface'
'tome': require './schemas/subscriptions/tome'
'user': require './schemas/subscriptions/user'
'world': require './schemas/subscriptions/world'
definitionSchemas =
'bus': require './schemas/definitions/bus'
'misc': require './schemas/definitions/misc'
init = ->
app.initialize()
Backbone.history.start({ pushState: true })
handleNormalUrls()
treemaExt = require 'treema-ext'
treemaExt.setup()
filepicker.setKey('AvlkNoldcTOU4PvKi2Xm7z')
# Set up Backbone.Mediator schemas
setUpDefinitions()
setUpChannels()
$ -> init()
handleNormalUrls = ->
# http://artsy.github.com/blog/2012/06/25/replacing-hashbang-routes-with-pushstate/
$(document).on "click", "a[href^='/']", (event) ->
href = $(event.currentTarget).attr('href')
# chain 'or's for other black list routes
passThrough = href.indexOf('sign_out') >= 0
# Allow shift+click for new tabs, etc.
if !passThrough && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
event.preventDefault()
# Remove leading slashes and hash bangs (backward compatablility)
url = href.replace(/^\//,'').replace('\#\!\/','')
# Instruct Backbone to trigger routing events
app.router.navigate url, { trigger: true }
return false
setUpChannels = ->
for channel of channelSchemas
Backbone.Mediator.addChannelSchemas channelSchemas[channel]
setUpDefinitions = ->
for definition of definitionSchemas
Backbone.Mediator.addDefSchemas definitionSchemas[definition] | 16188 | app = require 'application'
channelSchemas =
'app': require './schemas/subscriptions/app'
'bus': require './schemas/subscriptions/bus'
'editor': require './schemas/subscriptions/editor'
'errors': require './schemas/subscriptions/errors'
'misc': require './schemas/subscriptions/misc'
'play': require './schemas/subscriptions/play'
'surface': require './schemas/subscriptions/surface'
'tome': require './schemas/subscriptions/tome'
'user': require './schemas/subscriptions/user'
'world': require './schemas/subscriptions/world'
definitionSchemas =
'bus': require './schemas/definitions/bus'
'misc': require './schemas/definitions/misc'
init = ->
app.initialize()
Backbone.history.start({ pushState: true })
handleNormalUrls()
treemaExt = require 'treema-ext'
treemaExt.setup()
filepicker.setKey('<KEY>')
# Set up Backbone.Mediator schemas
setUpDefinitions()
setUpChannels()
$ -> init()
handleNormalUrls = ->
# http://artsy.github.com/blog/2012/06/25/replacing-hashbang-routes-with-pushstate/
$(document).on "click", "a[href^='/']", (event) ->
href = $(event.currentTarget).attr('href')
# chain 'or's for other black list routes
passThrough = href.indexOf('sign_out') >= 0
# Allow shift+click for new tabs, etc.
if !passThrough && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
event.preventDefault()
# Remove leading slashes and hash bangs (backward compatablility)
url = href.replace(/^\//,'').replace('\#\!\/','')
# Instruct Backbone to trigger routing events
app.router.navigate url, { trigger: true }
return false
setUpChannels = ->
for channel of channelSchemas
Backbone.Mediator.addChannelSchemas channelSchemas[channel]
setUpDefinitions = ->
for definition of definitionSchemas
Backbone.Mediator.addDefSchemas definitionSchemas[definition] | true | app = require 'application'
channelSchemas =
'app': require './schemas/subscriptions/app'
'bus': require './schemas/subscriptions/bus'
'editor': require './schemas/subscriptions/editor'
'errors': require './schemas/subscriptions/errors'
'misc': require './schemas/subscriptions/misc'
'play': require './schemas/subscriptions/play'
'surface': require './schemas/subscriptions/surface'
'tome': require './schemas/subscriptions/tome'
'user': require './schemas/subscriptions/user'
'world': require './schemas/subscriptions/world'
definitionSchemas =
'bus': require './schemas/definitions/bus'
'misc': require './schemas/definitions/misc'
init = ->
app.initialize()
Backbone.history.start({ pushState: true })
handleNormalUrls()
treemaExt = require 'treema-ext'
treemaExt.setup()
filepicker.setKey('PI:KEY:<KEY>END_PI')
# Set up Backbone.Mediator schemas
setUpDefinitions()
setUpChannels()
$ -> init()
handleNormalUrls = ->
# http://artsy.github.com/blog/2012/06/25/replacing-hashbang-routes-with-pushstate/
$(document).on "click", "a[href^='/']", (event) ->
href = $(event.currentTarget).attr('href')
# chain 'or's for other black list routes
passThrough = href.indexOf('sign_out') >= 0
# Allow shift+click for new tabs, etc.
if !passThrough && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
event.preventDefault()
# Remove leading slashes and hash bangs (backward compatablility)
url = href.replace(/^\//,'').replace('\#\!\/','')
# Instruct Backbone to trigger routing events
app.router.navigate url, { trigger: true }
return false
setUpChannels = ->
for channel of channelSchemas
Backbone.Mediator.addChannelSchemas channelSchemas[channel]
setUpDefinitions = ->
for definition of definitionSchemas
Backbone.Mediator.addDefSchemas definitionSchemas[definition] |
[
{
"context": " ['one', 'two', 'three']\n person:\n name: 'Alexander Schilling'\n job: 'Developer'\n ref: 'test'\n secti",
"end": 539,
"score": 0.9998302459716797,
"start": 520,
"tag": "NAME",
"value": "Alexander Schilling"
},
{
"context": "eloper'\n ref: 'test'\... | test/mocha/properties.coffee | alinex/node-formatter | 0 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
fs = require 'fs'
debug = require('debug') 'test'
chalk = require 'chalk'
formatter = require '../../src/index'
describe "Properties", ->
file = __dirname + '/../data/format.properties'
format = 'properties'
example = fs.readFileSync file, 'UTF8'
data =
string: 'test'
other: 'text'
multiline: 'This text goes over multiple lines.'
integer: 15
float: -4.6
list: ['one', 'two', 'three']
person:
name: 'Alexander Schilling'
job: 'Developer'
ref: 'test'
section:
name: 'Alex'
same: 'Alex'
describe "parse preset file", ->
it "should get object", (cb) ->
formatter.parse example, format, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with autodetect", (cb) ->
formatter.parse example, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with filename", (cb) ->
formatter.parse example, file, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
describe "format and parse", ->
it "should reread object", (cb) ->
formatter.stringify data, format, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
| 14687 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
fs = require 'fs'
debug = require('debug') 'test'
chalk = require 'chalk'
formatter = require '../../src/index'
describe "Properties", ->
file = __dirname + '/../data/format.properties'
format = 'properties'
example = fs.readFileSync file, 'UTF8'
data =
string: 'test'
other: 'text'
multiline: 'This text goes over multiple lines.'
integer: 15
float: -4.6
list: ['one', 'two', 'three']
person:
name: '<NAME>'
job: 'Developer'
ref: 'test'
section:
name: '<NAME>'
same: '<NAME>'
describe "parse preset file", ->
it "should get object", (cb) ->
formatter.parse example, format, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with autodetect", (cb) ->
formatter.parse example, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with filename", (cb) ->
formatter.parse example, file, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
describe "format and parse", ->
it "should reread object", (cb) ->
formatter.stringify data, format, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
| true | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
fs = require 'fs'
debug = require('debug') 'test'
chalk = require 'chalk'
formatter = require '../../src/index'
describe "Properties", ->
file = __dirname + '/../data/format.properties'
format = 'properties'
example = fs.readFileSync file, 'UTF8'
data =
string: 'test'
other: 'text'
multiline: 'This text goes over multiple lines.'
integer: 15
float: -4.6
list: ['one', 'two', 'three']
person:
name: 'PI:NAME:<NAME>END_PI'
job: 'Developer'
ref: 'test'
section:
name: 'PI:NAME:<NAME>END_PI'
same: 'PI:NAME:<NAME>END_PI'
describe "parse preset file", ->
it "should get object", (cb) ->
formatter.parse example, format, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with autodetect", (cb) ->
formatter.parse example, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with filename", (cb) ->
formatter.parse example, file, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
describe "format and parse", ->
it "should reread object", (cb) ->
formatter.stringify data, format, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
|
[
{
"context": " # some names to play with\n first_names = [\"Alice\",\"Bob\",\"Charlie\",\"Chuck\",\"Dave\",\"Erin\",\"Eve\",\"Fai",
"end": 163,
"score": 0.9998202919960022,
"start": 158,
"tag": "NAME",
"value": "Alice"
},
{
"context": "me names to play with\n first_names = [... | src/dashboard.controller.coffee | vault12/zax-dash | 5 | class DashboardController
mailboxPrefix: "_mailbox"
constructor: (RelayService, $scope, $q, $timeout)->
# some names to play with
first_names = ["Alice","Bob","Charlie","Chuck","Dave","Erin","Eve","Faith",
"Frank","Mallory","Oscar","Peggy","Pat","Sam","Sally","Sybil",
"Trent","Trudy","Victor","Walter","Wendy"].sort ->
.5 - Math.random()
@names = []
for i in [1..20]
for name in first_names
if i == 1
@names.push "#{name}"
else
@names.push "#{name} #{i}"
$scope.relay_url = RelayService.relayUrl
$scope.editing_url = $scope.relay_url
$scope.updateRelay = ->
$scope.relay_url = $scope.editing_url
RelayService.changeRelay($scope.relay_url)
$scope.editing = false
$scope.refreshCounter()
# what mailboxes are we looking at?
$scope.mailboxes = RelayService.mailboxes
# mailbox commands
$scope.getMessages = (mailbox)->
RelayService.getMessages(mailbox).then (data)->
if !mailbox.messages
mailbox.messages = []
mailbox.messagesNonces = []
for msg in data
unless mailbox.messagesNonces.indexOf(msg.nonce) != -1
if msg.kind == 'file'
msg.data = '📎 uploadID: ' + JSON.parse(msg.data).uploadID
mailbox.messagesNonces.push msg.nonce
mailbox.messages.push msg
$scope.$apply()
$scope.deleteMessages = (mailbox, messagesToDelete = null)->
noncesToDelete = messagesToDelete or mailbox.messagesNonces or []
RelayService.deleteMessages(mailbox, noncesToDelete).then ->
if noncesToDelete.length == 0
mailbox.messages = []
mailbox.messagesNonces = []
else
for msg in noncesToDelete
index = mailbox.messagesNonces.indexOf(msg)
mailbox.messagesNonces.splice(index, 1)
mailbox.messages.splice(index, 1)
mailbox.messageCount = Object.keys(mailbox.messages).length
$scope.$apply()
$scope.sendMessage = (mailbox, outgoing)->
RelayService.sendToVia(outgoing.recipient, mailbox, outgoing.message).then (data)->
$scope.messageSent = true
$timeout(->
$scope.messageSent = false
$scope.$apply()
, 3000)
$scope.outgoing = {message: "", recipient: ""}
$scope.$apply()
$scope.deleteMailbox = (mailbox)=>
name = mailbox.identity
RelayService.destroyMailbox(mailbox).then =>
localStorage.removeItem "#{@mailboxPrefix}.#{name}"
$scope.activeMailbox = null
# show the active mailbox messages
$scope.selectMailbox = (mailbox)->
$scope.activeMailbox = mailbox
$scope.getMessages(mailbox)
# internals
$scope.addMailbox = (name, options)=>
RelayService.newMailbox(name, options).then (mailbox)=>
localStorage.setItem "#{@mailboxPrefix}.#{name}", mailbox.identity
$scope.refreshCounter()
$scope.addMailboxes = (quantityToAdd)=>
[1..quantityToAdd].reduce ((prev, i)=> prev.then => $scope.addMailbox @names.shift()), $q.all()
$scope.refreshCounter = ->
total = Object.keys $scope.mailboxes
if !total
return
$scope.showRefreshLoader = true
[0..total.length-1].reduce ((prev, i)=> prev.then => RelayService.messageCount $scope.mailboxes[total[i]]), $q.all()
.then ->
$scope.showRefreshLoader = false
$scope.addPublicKey = (mailbox, key)->
if mailbox.keyRing.addGuest key.name, key.key
$scope.keyAdded = true
$timeout(->
$scope.keyAdded = false
$scope.$apply()
, 3000)
$scope.pubKey = {name: "", key: ""}
$scope.$apply()
# add any mailbox stored in localStorage
next = $q.all()
for key in Object.keys localStorage
if key.indexOf(@mailboxPrefix) == 0
((key)->
next = next.then -> $scope.addMailbox(localStorage.getItem(key))
)(key)
next.then ->
$scope.refreshCounter()
angular
.module 'app'
.controller 'DashboardController', [
'RelayService'
'$scope'
'$q'
'$timeout'
DashboardController
]
| 198111 | class DashboardController
mailboxPrefix: "_mailbox"
constructor: (RelayService, $scope, $q, $timeout)->
# some names to play with
first_names = ["<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>",
"<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>",
"<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"].sort ->
.5 - Math.random()
@names = []
for i in [1..20]
for name in first_names
if i == 1
@names.push "#{name}"
else
@names.push "#{name} #{i}"
$scope.relay_url = RelayService.relayUrl
$scope.editing_url = $scope.relay_url
$scope.updateRelay = ->
$scope.relay_url = $scope.editing_url
RelayService.changeRelay($scope.relay_url)
$scope.editing = false
$scope.refreshCounter()
# what mailboxes are we looking at?
$scope.mailboxes = RelayService.mailboxes
# mailbox commands
$scope.getMessages = (mailbox)->
RelayService.getMessages(mailbox).then (data)->
if !mailbox.messages
mailbox.messages = []
mailbox.messagesNonces = []
for msg in data
unless mailbox.messagesNonces.indexOf(msg.nonce) != -1
if msg.kind == 'file'
msg.data = '📎 uploadID: ' + JSON.parse(msg.data).uploadID
mailbox.messagesNonces.push msg.nonce
mailbox.messages.push msg
$scope.$apply()
$scope.deleteMessages = (mailbox, messagesToDelete = null)->
noncesToDelete = messagesToDelete or mailbox.messagesNonces or []
RelayService.deleteMessages(mailbox, noncesToDelete).then ->
if noncesToDelete.length == 0
mailbox.messages = []
mailbox.messagesNonces = []
else
for msg in noncesToDelete
index = mailbox.messagesNonces.indexOf(msg)
mailbox.messagesNonces.splice(index, 1)
mailbox.messages.splice(index, 1)
mailbox.messageCount = Object.keys(mailbox.messages).length
$scope.$apply()
$scope.sendMessage = (mailbox, outgoing)->
RelayService.sendToVia(outgoing.recipient, mailbox, outgoing.message).then (data)->
$scope.messageSent = true
$timeout(->
$scope.messageSent = false
$scope.$apply()
, 3000)
$scope.outgoing = {message: "", recipient: ""}
$scope.$apply()
$scope.deleteMailbox = (mailbox)=>
name = mailbox.identity
RelayService.destroyMailbox(mailbox).then =>
localStorage.removeItem "#{@mailboxPrefix}.#{name}"
$scope.activeMailbox = null
# show the active mailbox messages
$scope.selectMailbox = (mailbox)->
$scope.activeMailbox = mailbox
$scope.getMessages(mailbox)
# internals
$scope.addMailbox = (name, options)=>
RelayService.newMailbox(name, options).then (mailbox)=>
localStorage.setItem "#{@mailboxPrefix}.#{name}", mailbox.identity
$scope.refreshCounter()
$scope.addMailboxes = (quantityToAdd)=>
[1..quantityToAdd].reduce ((prev, i)=> prev.then => $scope.addMailbox @names.shift()), $q.all()
$scope.refreshCounter = ->
total = Object.keys $scope.mailboxes
if !total
return
$scope.showRefreshLoader = true
[0..total.length-1].reduce ((prev, i)=> prev.then => RelayService.messageCount $scope.mailboxes[total[i]]), $q.all()
.then ->
$scope.showRefreshLoader = false
$scope.addPublicKey = (mailbox, key)->
if mailbox.keyRing.addGuest key.name, key.key
$scope.keyAdded = true
$timeout(->
$scope.keyAdded = false
$scope.$apply()
, 3000)
$scope.pubKey = {<KEY> key: <KEY>
$scope.$apply()
# add any mailbox stored in localStorage
next = $q.all()
for key in Object.keys localStorage
if key.indexOf(@mailboxPrefix) == 0
((key)->
next = next.then -> $scope.addMailbox(localStorage.getItem(key))
)(key)
next.then ->
$scope.refreshCounter()
angular
.module 'app'
.controller 'DashboardController', [
'RelayService'
'$scope'
'$q'
'$timeout'
DashboardController
]
| true | class DashboardController
mailboxPrefix: "_mailbox"
constructor: (RelayService, $scope, $q, $timeout)->
# some names to play with
first_names = ["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"].sort ->
.5 - Math.random()
@names = []
for i in [1..20]
for name in first_names
if i == 1
@names.push "#{name}"
else
@names.push "#{name} #{i}"
$scope.relay_url = RelayService.relayUrl
$scope.editing_url = $scope.relay_url
$scope.updateRelay = ->
$scope.relay_url = $scope.editing_url
RelayService.changeRelay($scope.relay_url)
$scope.editing = false
$scope.refreshCounter()
# what mailboxes are we looking at?
$scope.mailboxes = RelayService.mailboxes
# mailbox commands
$scope.getMessages = (mailbox)->
RelayService.getMessages(mailbox).then (data)->
if !mailbox.messages
mailbox.messages = []
mailbox.messagesNonces = []
for msg in data
unless mailbox.messagesNonces.indexOf(msg.nonce) != -1
if msg.kind == 'file'
msg.data = '📎 uploadID: ' + JSON.parse(msg.data).uploadID
mailbox.messagesNonces.push msg.nonce
mailbox.messages.push msg
$scope.$apply()
$scope.deleteMessages = (mailbox, messagesToDelete = null)->
noncesToDelete = messagesToDelete or mailbox.messagesNonces or []
RelayService.deleteMessages(mailbox, noncesToDelete).then ->
if noncesToDelete.length == 0
mailbox.messages = []
mailbox.messagesNonces = []
else
for msg in noncesToDelete
index = mailbox.messagesNonces.indexOf(msg)
mailbox.messagesNonces.splice(index, 1)
mailbox.messages.splice(index, 1)
mailbox.messageCount = Object.keys(mailbox.messages).length
$scope.$apply()
$scope.sendMessage = (mailbox, outgoing)->
RelayService.sendToVia(outgoing.recipient, mailbox, outgoing.message).then (data)->
$scope.messageSent = true
$timeout(->
$scope.messageSent = false
$scope.$apply()
, 3000)
$scope.outgoing = {message: "", recipient: ""}
$scope.$apply()
$scope.deleteMailbox = (mailbox)=>
name = mailbox.identity
RelayService.destroyMailbox(mailbox).then =>
localStorage.removeItem "#{@mailboxPrefix}.#{name}"
$scope.activeMailbox = null
# show the active mailbox messages
$scope.selectMailbox = (mailbox)->
$scope.activeMailbox = mailbox
$scope.getMessages(mailbox)
# internals
$scope.addMailbox = (name, options)=>
RelayService.newMailbox(name, options).then (mailbox)=>
localStorage.setItem "#{@mailboxPrefix}.#{name}", mailbox.identity
$scope.refreshCounter()
$scope.addMailboxes = (quantityToAdd)=>
[1..quantityToAdd].reduce ((prev, i)=> prev.then => $scope.addMailbox @names.shift()), $q.all()
$scope.refreshCounter = ->
total = Object.keys $scope.mailboxes
if !total
return
$scope.showRefreshLoader = true
[0..total.length-1].reduce ((prev, i)=> prev.then => RelayService.messageCount $scope.mailboxes[total[i]]), $q.all()
.then ->
$scope.showRefreshLoader = false
$scope.addPublicKey = (mailbox, key)->
if mailbox.keyRing.addGuest key.name, key.key
$scope.keyAdded = true
$timeout(->
$scope.keyAdded = false
$scope.$apply()
, 3000)
$scope.pubKey = {PI:KEY:<KEY>END_PI key: PI:KEY:<KEY>END_PI
$scope.$apply()
# add any mailbox stored in localStorage
next = $q.all()
for key in Object.keys localStorage
if key.indexOf(@mailboxPrefix) == 0
((key)->
next = next.then -> $scope.addMailbox(localStorage.getItem(key))
)(key)
next.then ->
$scope.refreshCounter()
angular
.module 'app'
.controller 'DashboardController', [
'RelayService'
'$scope'
'$q'
'$timeout'
DashboardController
]
|
[
{
"context": " Dictionary and returns definition\n#\n# Author:\n# Travis Jeffery (@travisjeffery)\n# Jamie Wilkinson (@jamiew)\n\nm",
"end": 231,
"score": 0.9998422861099243,
"start": 217,
"tag": "NAME",
"value": "Travis Jeffery"
},
{
"context": " returns definition\n#\n# Author:... | scripts/urban.coffee | jamiew/spacecat | 1 | # Description:
# Define terms via Urban Dictionary
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot define <term> - Searches Urban Dictionary and returns definition
#
# Author:
# Travis Jeffery (@travisjeffery)
# Jamie Wilkinson (@jamiew)
module.exports = (robot) ->
robot.respond /(define|urban)( me)? (.*)/i, (msg) ->
urbanDict msg, msg.match[3], (entry) ->
msg.send "#{entry.definition}. Example: \"#{entry.example}\""
urbanDict = (msg, query, callback) ->
msg.http("http://api.urbandictionary.com/v0/define?term=#{escape(query)}")
.get() (err, res, body) ->
# console.log body
callback(JSON.parse(body).list[0])
| 147927 | # Description:
# Define terms via Urban Dictionary
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot define <term> - Searches Urban Dictionary and returns definition
#
# Author:
# <NAME> (@travisjeffery)
# <NAME> (@jamiew)
module.exports = (robot) ->
robot.respond /(define|urban)( me)? (.*)/i, (msg) ->
urbanDict msg, msg.match[3], (entry) ->
msg.send "#{entry.definition}. Example: \"#{entry.example}\""
urbanDict = (msg, query, callback) ->
msg.http("http://api.urbandictionary.com/v0/define?term=#{escape(query)}")
.get() (err, res, body) ->
# console.log body
callback(JSON.parse(body).list[0])
| true | # Description:
# Define terms via Urban Dictionary
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot define <term> - Searches Urban Dictionary and returns definition
#
# Author:
# PI:NAME:<NAME>END_PI (@travisjeffery)
# PI:NAME:<NAME>END_PI (@jamiew)
module.exports = (robot) ->
robot.respond /(define|urban)( me)? (.*)/i, (msg) ->
urbanDict msg, msg.match[3], (entry) ->
msg.send "#{entry.definition}. Example: \"#{entry.example}\""
urbanDict = (msg, query, callback) ->
msg.http("http://api.urbandictionary.com/v0/define?term=#{escape(query)}")
.get() (err, res, body) ->
# console.log body
callback(JSON.parse(body).list[0])
|
[
{
"context": "##############################################\n#\n# Markus 1/23/2017\n#\n#####################################",
"end": 75,
"score": 0.9987979531288147,
"start": 69,
"tag": "NAME",
"value": "Markus"
}
] | server/methods/edu_cert.coffee | MooqitaSFH/worklearn | 0 | ################################################################
#
# Markus 1/23/2017
#
################################################################
###############################################
Meteor.methods
add_cert_template: () ->
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
return gen_cert_template user
add_recipients: (cert_template_id, recipients) ->
check recipients, String
check cert_template_id, String
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
cert_template = get_my_document EduCertTemplate, cert_template_id
for r in recipients.split ","
gen_cert_recipient(user, cert_template, r)
return true
bake_cert: (recipient_id) ->
user = Meteor.user()
recipient = get_my_document EduCertRecipients, recipient_id
return gen_cert_assertion recipient, user
| 112180 | ################################################################
#
# <NAME> 1/23/2017
#
################################################################
###############################################
Meteor.methods
add_cert_template: () ->
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
return gen_cert_template user
add_recipients: (cert_template_id, recipients) ->
check recipients, String
check cert_template_id, String
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
cert_template = get_my_document EduCertTemplate, cert_template_id
for r in recipients.split ","
gen_cert_recipient(user, cert_template, r)
return true
bake_cert: (recipient_id) ->
user = Meteor.user()
recipient = get_my_document EduCertRecipients, recipient_id
return gen_cert_assertion recipient, user
| true | ################################################################
#
# PI:NAME:<NAME>END_PI 1/23/2017
#
################################################################
###############################################
Meteor.methods
add_cert_template: () ->
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
return gen_cert_template user
add_recipients: (cert_template_id, recipients) ->
check recipients, String
check cert_template_id, String
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
cert_template = get_my_document EduCertTemplate, cert_template_id
for r in recipients.split ","
gen_cert_recipient(user, cert_template, r)
return true
bake_cert: (recipient_id) ->
user = Meteor.user()
recipient = get_my_document EduCertRecipients, recipient_id
return gen_cert_assertion recipient, user
|
[
{
"context": " Use postfix or prefix spread dots `...`\n# @author Julian Rosse\n###\n\n'use strict'\n\n# ----------------------------",
"end": 83,
"score": 0.9998425245285034,
"start": 71,
"tag": "NAME",
"value": "Julian Rosse"
}
] | src/tests/rules/spread-direction.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Use postfix or prefix spread dots `...`
# @author Julian Rosse
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/spread-direction'
{RuleTester} = require 'eslint'
path = require 'path'
USE_PREFIX = "Use the prefix form of '...'"
USE_POSTFIX = "Use the postfix form of '...'"
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'spread-direction', rule,
valid: [
'[...b]'
'[...b] = c'
'([...b]) ->'
'{...b}'
'{...b} = c'
'({...b}) ->'
'<div {...b} />'
,
code: '[...b]'
options: ['prefix']
,
code: '[b...]'
options: ['postfix']
,
code: '[b...] = c'
options: ['postfix']
,
code: '[a..., b] = c'
options: ['postfix']
,
code: '([b...]) ->'
options: ['postfix']
,
code: '{b...}'
options: ['postfix']
,
code: '{b...} = c'
options: ['postfix']
,
code: '({b...}) ->'
options: ['postfix']
,
code: '<div {b...} />'
options: ['postfix']
,
'[..., b] = c'
,
code: '[..., b] = c'
options: ['postfix']
]
invalid: [
code: '[...b]'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '[...b] = c'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '([...b]) ->'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '{...b}'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '{...b} = c'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '({...b}) ->'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '<div {...b} />'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '[b...]'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '[b...]'
errors: [USE_PREFIX]
,
code: '[b...] = c'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '([b...]) ->'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '{b...}'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '{b...} = c'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '({b...}) ->'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '<div {b...} />'
options: ['prefix']
errors: [USE_PREFIX]
]
| 36760 | ###*
# @fileoverview Use postfix or prefix spread dots `...`
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/spread-direction'
{RuleTester} = require 'eslint'
path = require 'path'
USE_PREFIX = "Use the prefix form of '...'"
USE_POSTFIX = "Use the postfix form of '...'"
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'spread-direction', rule,
valid: [
'[...b]'
'[...b] = c'
'([...b]) ->'
'{...b}'
'{...b} = c'
'({...b}) ->'
'<div {...b} />'
,
code: '[...b]'
options: ['prefix']
,
code: '[b...]'
options: ['postfix']
,
code: '[b...] = c'
options: ['postfix']
,
code: '[a..., b] = c'
options: ['postfix']
,
code: '([b...]) ->'
options: ['postfix']
,
code: '{b...}'
options: ['postfix']
,
code: '{b...} = c'
options: ['postfix']
,
code: '({b...}) ->'
options: ['postfix']
,
code: '<div {b...} />'
options: ['postfix']
,
'[..., b] = c'
,
code: '[..., b] = c'
options: ['postfix']
]
invalid: [
code: '[...b]'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '[...b] = c'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '([...b]) ->'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '{...b}'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '{...b} = c'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '({...b}) ->'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '<div {...b} />'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '[b...]'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '[b...]'
errors: [USE_PREFIX]
,
code: '[b...] = c'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '([b...]) ->'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '{b...}'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '{b...} = c'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '({b...}) ->'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '<div {b...} />'
options: ['prefix']
errors: [USE_PREFIX]
]
| true | ###*
# @fileoverview Use postfix or prefix spread dots `...`
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/spread-direction'
{RuleTester} = require 'eslint'
path = require 'path'
USE_PREFIX = "Use the prefix form of '...'"
USE_POSTFIX = "Use the postfix form of '...'"
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'spread-direction', rule,
valid: [
'[...b]'
'[...b] = c'
'([...b]) ->'
'{...b}'
'{...b} = c'
'({...b}) ->'
'<div {...b} />'
,
code: '[...b]'
options: ['prefix']
,
code: '[b...]'
options: ['postfix']
,
code: '[b...] = c'
options: ['postfix']
,
code: '[a..., b] = c'
options: ['postfix']
,
code: '([b...]) ->'
options: ['postfix']
,
code: '{b...}'
options: ['postfix']
,
code: '{b...} = c'
options: ['postfix']
,
code: '({b...}) ->'
options: ['postfix']
,
code: '<div {b...} />'
options: ['postfix']
,
'[..., b] = c'
,
code: '[..., b] = c'
options: ['postfix']
]
invalid: [
code: '[...b]'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '[...b] = c'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '([...b]) ->'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '{...b}'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '{...b} = c'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '({...b}) ->'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '<div {...b} />'
options: ['postfix']
errors: [USE_POSTFIX]
,
code: '[b...]'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '[b...]'
errors: [USE_PREFIX]
,
code: '[b...] = c'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '([b...]) ->'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '{b...}'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '{b...} = c'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '({b...}) ->'
options: ['prefix']
errors: [USE_PREFIX]
,
code: '<div {b...} />'
options: ['prefix']
errors: [USE_PREFIX]
]
|
[
{
"context": "###\n# node-make-sync\n# Copyright(c) 2012 Seb Vincent\n# MIT Licensed\n###\n\nFiber = require('fibers'); ",
"end": 52,
"score": 0.9998381733894348,
"start": 41,
"tag": "NAME",
"value": "Seb Vincent"
}
] | lib/make-sync.coffee | dnice-asana/node-make-sync | 0 | ###
# node-make-sync
# Copyright(c) 2012 Seb Vincent
# MIT Licensed
###
Fiber = require('fibers');
Future = require 'fibers/future'
wait = Future.wait
{Options} = require './options'
# use a Future to make the sync call and wait.
callSync = (f, resultBuilderFunc, args...) ->
# making sure the returns follow the
# usual callback rule
fWithErr = (callback) ->
f.apply this, [
args..., (res...) ->
callback null,res
]
wrappedf = Future.wrap fWithErr
rawRes = wrappedf.apply this
wait(rawRes)
rawRes = rawRes.get()
resultBuilderFunc.apply @, rawRes
# return a function wich:
# - uses fibers when the done callback is not detected.
# - otherwise calls the original function
makeFuncSync = (f, options, key) ->
mode = options.mode()
numOfParams = options.numOfParams key
[prepareCall] = []
switch mode[0]
when 'sync' then prepareCall = (args...) -> ['sync',args]
when 'async' then prepareCall = (args...) -> ['async',args]
when 'mixed'
switch mode[1]
when 'fibers' then prepareCall = (args...) ->
if Fiber.current? then ['sync',args] else ['async',args]
when 'args'
# move done to args when num of args too small, or if done is the
# wrong type
prepareCall = (args..., done) ->
if numOfParams? and done? and args.length < numOfParams
args.push done
done = undefined
if done? and typeof(done) isnt 'function'
args.push done
done = undefined
if done
['async',args.concat [done]]
else
['sync',args]
resultBuilderFunc = options.syncReturn( key )
(args...) ->
[callMode,args] = prepareCall args...
switch callMode
when 'sync'
callSync.apply this, [f, resultBuilderFunc, args...]
when 'async' then f.apply this, [args...]
# apply makesync on all the object functions
makeObjSync = (obj, options) ->
for k, v of obj when typeof v is 'function'
if options.isIncluded k
vSync = makeFuncSync v, options, k
obj[k] = vSync
obj
# call the approriate makeSync method depending on object type
makeSync = (target, _options) ->
options = new Options(_options)
switch typeof target
when 'function' then makeFuncSync target, options
when 'object' then makeObjSync target, options
# open a sync block
sync = (f) ->
fn = Fiber f
fn.run()
current = ->
Fiber.current
exports.Sync = sync
exports.MakeSync = makeSync
exports.MakeObjSync = makeObjSync
exports.MakeFuncSync = makeFuncSync
exports.Current = current
exports.sync = sync
exports.makeSync = makeSync
exports.makeObjSync = makeObjSync
exports.makeFuncSync = makeFuncSync
exports.current = current
| 113866 | ###
# node-make-sync
# Copyright(c) 2012 <NAME>
# MIT Licensed
###
Fiber = require('fibers');
Future = require 'fibers/future'
wait = Future.wait
{Options} = require './options'
# use a Future to make the sync call and wait.
callSync = (f, resultBuilderFunc, args...) ->
# making sure the returns follow the
# usual callback rule
fWithErr = (callback) ->
f.apply this, [
args..., (res...) ->
callback null,res
]
wrappedf = Future.wrap fWithErr
rawRes = wrappedf.apply this
wait(rawRes)
rawRes = rawRes.get()
resultBuilderFunc.apply @, rawRes
# return a function wich:
# - uses fibers when the done callback is not detected.
# - otherwise calls the original function
makeFuncSync = (f, options, key) ->
mode = options.mode()
numOfParams = options.numOfParams key
[prepareCall] = []
switch mode[0]
when 'sync' then prepareCall = (args...) -> ['sync',args]
when 'async' then prepareCall = (args...) -> ['async',args]
when 'mixed'
switch mode[1]
when 'fibers' then prepareCall = (args...) ->
if Fiber.current? then ['sync',args] else ['async',args]
when 'args'
# move done to args when num of args too small, or if done is the
# wrong type
prepareCall = (args..., done) ->
if numOfParams? and done? and args.length < numOfParams
args.push done
done = undefined
if done? and typeof(done) isnt 'function'
args.push done
done = undefined
if done
['async',args.concat [done]]
else
['sync',args]
resultBuilderFunc = options.syncReturn( key )
(args...) ->
[callMode,args] = prepareCall args...
switch callMode
when 'sync'
callSync.apply this, [f, resultBuilderFunc, args...]
when 'async' then f.apply this, [args...]
# apply makesync on all the object functions
makeObjSync = (obj, options) ->
for k, v of obj when typeof v is 'function'
if options.isIncluded k
vSync = makeFuncSync v, options, k
obj[k] = vSync
obj
# call the approriate makeSync method depending on object type
makeSync = (target, _options) ->
options = new Options(_options)
switch typeof target
when 'function' then makeFuncSync target, options
when 'object' then makeObjSync target, options
# open a sync block
sync = (f) ->
fn = Fiber f
fn.run()
current = ->
Fiber.current
exports.Sync = sync
exports.MakeSync = makeSync
exports.MakeObjSync = makeObjSync
exports.MakeFuncSync = makeFuncSync
exports.Current = current
exports.sync = sync
exports.makeSync = makeSync
exports.makeObjSync = makeObjSync
exports.makeFuncSync = makeFuncSync
exports.current = current
| true | ###
# node-make-sync
# Copyright(c) 2012 PI:NAME:<NAME>END_PI
# MIT Licensed
###
Fiber = require('fibers');
Future = require 'fibers/future'
wait = Future.wait
{Options} = require './options'
# use a Future to make the sync call and wait.
callSync = (f, resultBuilderFunc, args...) ->
# making sure the returns follow the
# usual callback rule
fWithErr = (callback) ->
f.apply this, [
args..., (res...) ->
callback null,res
]
wrappedf = Future.wrap fWithErr
rawRes = wrappedf.apply this
wait(rawRes)
rawRes = rawRes.get()
resultBuilderFunc.apply @, rawRes
# return a function wich:
# - uses fibers when the done callback is not detected.
# - otherwise calls the original function
makeFuncSync = (f, options, key) ->
mode = options.mode()
numOfParams = options.numOfParams key
[prepareCall] = []
switch mode[0]
when 'sync' then prepareCall = (args...) -> ['sync',args]
when 'async' then prepareCall = (args...) -> ['async',args]
when 'mixed'
switch mode[1]
when 'fibers' then prepareCall = (args...) ->
if Fiber.current? then ['sync',args] else ['async',args]
when 'args'
# move done to args when num of args too small, or if done is the
# wrong type
prepareCall = (args..., done) ->
if numOfParams? and done? and args.length < numOfParams
args.push done
done = undefined
if done? and typeof(done) isnt 'function'
args.push done
done = undefined
if done
['async',args.concat [done]]
else
['sync',args]
resultBuilderFunc = options.syncReturn( key )
(args...) ->
[callMode,args] = prepareCall args...
switch callMode
when 'sync'
callSync.apply this, [f, resultBuilderFunc, args...]
when 'async' then f.apply this, [args...]
# apply makesync on all the object functions
makeObjSync = (obj, options) ->
for k, v of obj when typeof v is 'function'
if options.isIncluded k
vSync = makeFuncSync v, options, k
obj[k] = vSync
obj
# call the approriate makeSync method depending on object type
makeSync = (target, _options) ->
options = new Options(_options)
switch typeof target
when 'function' then makeFuncSync target, options
when 'object' then makeObjSync target, options
# open a sync block
sync = (f) ->
fn = Fiber f
fn.run()
current = ->
Fiber.current
exports.Sync = sync
exports.MakeSync = makeSync
exports.MakeObjSync = makeObjSync
exports.MakeFuncSync = makeFuncSync
exports.Current = current
exports.sync = sync
exports.makeSync = makeSync
exports.makeObjSync = makeObjSync
exports.makeFuncSync = makeFuncSync
exports.current = current
|
[
{
"context": "\nclass Duck\n constructor: (name='Anonimous') ->\n @name = name\n quack: ->\n @",
"end": 45,
"score": 0.9993992447853088,
"start": 36,
"tag": "NAME",
"value": "Anonimous"
},
{
"context": " quack: ->\n @name + ' Duck: Quack-quack!'\n\ndonald =... | spec/fixtures/space_operators/invalid.coffee | dopustim/coffeelint-config | 0 |
class Duck
constructor: (name='Anonimous') ->
@name = name
quack: ->
@name + ' Duck: Quack-quack!'
donald = new duck 'Donald'
console.log donald.quack()
| 143408 |
class Duck
constructor: (name='<NAME>') ->
@name = name
quack: ->
@name + ' Duck: Quack-quack!'
<NAME> = new duck '<NAME>'
console.log donald.quack()
| true |
class Duck
constructor: (name='PI:NAME:<NAME>END_PI') ->
@name = name
quack: ->
@name + ' Duck: Quack-quack!'
PI:NAME:<NAME>END_PI = new duck 'PI:NAME:<NAME>END_PI'
console.log donald.quack()
|
[
{
"context": "5-AF4 Headhunter\"\"\"\n exportObj.renameShip \"\"\"M12-L Kimogila Fighter\"\"\", \"\"\"M12-L Kimogila Fighter\"",
"end": 9517,
"score": 0.6772056221961975,
"start": 9516,
"tag": "NAME",
"value": "2"
},
{
"context": "AF4 Headhunter\"\"\"\n exportObj.renameShip \"\... | coffeescripts/cards-hu.coffee | Dakkon426/xwing | 0 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.hu = 'Magyar'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Magyar =
slot:
"Astromech": "Astromech"
"Force": "Erő"
"Bomb": "Bomba"
"Cannon": "Ágyú"
"Crew": "Személyzet"
"Missile": "Rakéta"
"Sensor": "Szenzor"
"Torpedo": "Torpedó"
"Turret": "Lövegtorony"
"Hardpoint": "Fegyverfelfüggesztés"
"Illicit": "Tiltott"
"Configuration": "Konfiguráció"
"Talent": "Talentum"
"Modification": "Módosítás"
"Gunner": "Fegyverzet kezelő"
"Device": "Eszköz"
"Tech": "Tech"
"Title": "Nevesítés"
sources: # needed?
"Second Edition Core Set": "Second Edition Core Set"
"Rebel Alliance Conversion Kit": "Rebel Alliance Conversion Kit"
"Galactic Empire Conversion Kit": "Galactic Empire Conversion Kit"
"Scum and Villainy Conversion Kit": "Scum and Villainy Conversion Kit"
"T-65 X-Wing Expansion Pack": "T-65 X-Wing Expansion Pack"
"BTL-A4 Y-Wing Expansion Pack": "BTL-A4 Y-Wing Expansion Pack"
"TIE/ln Fighter Expansion Pack": "TIE/ln Fighter Expansion Pack"
"TIE Advanced x1 Expansion Pack": "TIE Advanced x1 Expansion Pack"
"Slave 1 Expansion Pack": "Slave 1 Expansion Pack"
"Fang Fighter Expansion Pack": "Fang Fighter Expansion Pack"
"Lando's Millennium Falcon Expansion Pack": "Lando's Millennium Falcon Expansion Pack"
"Saw's Renegades Expansion Pack": "Saw's Renegades Expansion Pack"
"TIE Reaper Expansion Pack": "TIE Reaper Expansion Pack"
ui:
shipSelectorPlaceholder: "Válassz egy hajót"
pilotSelectorPlaceholder: "Válassz egy pilótát"
upgradePlaceholder: (translator, language, slot) ->
"Nincs #{translator language, 'slot', slot} fejlesztés"
modificationPlaceholder: "Nincs módosítás"
titlePlaceholder: "Nincs nevesítés"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'slot', slot} fejlesztés"
unreleased: "kiadatlan"
epic: "epikus"
limited: "korlátozott"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'Ez a raj kiadatlan tartalmat használ!'
'.loading-failed-container .translated': 'It appears that you followed a broken link. No squad could be loaded!'
'.collection-invalid .translated': 'Ez a lista nem vihető pályára a készletedből!'
'.ship-number-invalid-container .translated': 'A tournament legal squad must contain 2-8 ships!'
# Type selector
'.game-type-selector option[value="standard"]': 'Kiterjesztett'
'.game-type-selector option[value="hyperspace"]': 'Hyperspace'
'.game-type-selector option[value="custom"]': 'Egyéni'
# Card browser
'.xwing-card-browser option[value="name"]': 'Név'
'.xwing-card-browser option[value="source"]': 'Forrás'
'.xwing-card-browser option[value="type-by-points"]': 'Típus (pont szerint)'
'.xwing-card-browser option[value="type-by-name"]': 'Típus (név szerint)'
'.xwing-card-browser .translate.select-a-card': 'Válassz a bal oldalon lévő kártyákból.'
'.xwing-card-browser .translate.sort-cards-by': 'Sort cards by'
# Info well
'.info-well .info-ship td.info-header': 'Hajó'
'.info-well .info-skill td.info-header': 'Kezdeményezés'
'.info-well .info-actions td.info-header': 'Akciók'
'.info-well .info-upgrades td.info-header': 'Fejlesztések'
'.info-well .info-range td.info-header': 'Távolság'
# Squadron edit buttons
'.clear-squad' : 'Új raj'
'.save-list' : '<i class="fa fa-floppy-o"></i> Mentés'
'.save-list-as' : '<i class="fa fa-files-o"></i> Mentés mint…'
'.delete-list' : '<i class="fa fa-trash-o"></i> Törlés'
'.backend-list-my-squads' : 'Raj betöltés'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Nyomtatás/Szövegnézet </span>'
'.randomize' : '<i class="fa fa-random"></i> Random!'
'.randomize-options' : 'Randomizer opciók…'
'.notes-container > span' : 'Jegyzetek'
# Print/View modal
'.bbcode-list' : 'Copy the BBCode below and paste it into your forum post.<textarea></textarea><button class="btn btn-copy">Másolás</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Másolás</button>'
'.vertical-space-checkbox' : """Hagyj helyet a sérülés és fejlesztéskártyáknak nyomtatáskor <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Színes nyomtatás <input type="checkbox" class="toggle-color-print" checked="checked" />"""
'.print-list' : '<i class="fa fa-print"></i> Nyomtatás'
# Randomizer options
'.do-randomize' : 'Randomize!'
# Top tab bar
'#browserTab' : 'Kártya tallózó'
'#aboutTab' : 'Rólunk'
# Obstacles
'.choose-obstacles' : 'Válassz akadályt'
'.choose-obstacles-description' : 'Choose up to three obstacles to include in the permalink for use in external programs. (This feature is in BETA; support for displaying which obstacles were selected in the printout is not yet supported.)'
'.coreasteroid0-select' : 'Core Asteroid 0'
'.coreasteroid1-select' : 'Core Asteroid 1'
'.coreasteroid2-select' : 'Core Asteroid 2'
'.coreasteroid3-select' : 'Core Asteroid 3'
'.coreasteroid4-select' : 'Core Asteroid 4'
'.coreasteroid5-select' : 'Core Asteroid 5'
'.yt2400debris0-select' : 'YT2400 Debris 0'
'.yt2400debris1-select' : 'YT2400 Debris 1'
'.yt2400debris2-select' : 'YT2400 Debris 2'
'.vt49decimatordebris0-select' : 'VT49 Debris 0'
'.vt49decimatordebris1-select' : 'VT49 Debris 1'
'.vt49decimatordebris2-select' : 'VT49 Debris 2'
'.core2asteroid0-select' : 'Force Awakens Asteroid 0'
'.core2asteroid1-select' : 'Force Awakens Asteroid 1'
'.core2asteroid2-select' : 'Force Awakens Asteroid 2'
'.core2asteroid3-select' : 'Force Awakens Asteroid 3'
'.core2asteroid4-select' : 'Force Awakens Asteroid 4'
'.core2asteroid5-select' : 'Force Awakens Asteroid 5'
# Collection
'.collection': '<i class="fa fa-folder-open hidden-phone hidden-tabler"></i> Gyűjteményed'
singular:
'pilots': 'Pilóta'
'modifications': 'Módosítás'
'titles': 'Nevesítés'
'ships' : 'Ship'
types:
'Pilot': 'Pilóta'
'Modification': 'Módosítás'
'Title': 'Nevesíés'
'Ship' : 'Ship'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Magyar = () ->
exportObj.cardLanguage = 'Magyar'
exportObj.renameShip """YT-1300""", """Modified YT-1300 Light Freighter"""
exportObj.renameShip """StarViper""", """StarViper-class Attack Platform"""
exportObj.renameShip """Scurrg H-6 Bomber""", """Scurrg H-6 Bomber"""
exportObj.renameShip """YT-2400""", """YT-2400 Light Freighter"""
exportObj.renameShip """Auzituck Gunship""", """Auzituck Gunship"""
exportObj.renameShip """Kihraxz Fighter""", """Kihraxz Fighter"""
exportObj.renameShip """Sheathipede-Class Shuttle""", """Sheathipede-class Shuttle"""
exportObj.renameShip """Quadjumper""", """Quadrijet Transfer Spacetug"""
exportObj.renameShip """Firespray-31""", """Firespray-class Patrol Craft"""
exportObj.renameShip """TIE Fighter""", """TIE/ln Fighter"""
exportObj.renameShip """Y-Wing""", """BTL-A4 Y-Wing"""
exportObj.renameShip """TIE Advanced""", """TIE Advanced x1"""
exportObj.renameShip """Alpha-Class Star Wing""", """Alpha-class Star Wing"""
exportObj.renameShip """U-Wing""", """UT-60D U-Wing"""
exportObj.renameShip """TIE Striker""", """TIE/sk Striker"""
exportObj.renameShip """B-Wing""", """A/SF-01 B-Wing"""
exportObj.renameShip """TIE Defender""", """TIE/D Defender"""
exportObj.renameShip """TIE Bomber""", """TIE/sa Bomber"""
exportObj.renameShip """TIE Punisher""", """TIE/ca Punisher"""
exportObj.renameShip """Aggressor""", """Aggressor Assault Fighter"""
exportObj.renameShip """G-1A Starfighter""", """G-1A Starfighter"""
exportObj.renameShip """VCX-100""", """VCX-100 Light Freighter"""
exportObj.renameShip """YV-666""", """YV-666 Light Freighter"""
exportObj.renameShip """TIE Advanced Prototype""", """TIE Advanced v1"""
exportObj.renameShip """Lambda-Class Shuttle""", """Lambda-class T-4a Shuttle"""
exportObj.renameShip """TIE Phantom""", """TIE/ph Phantom"""
exportObj.renameShip """VT-49 Decimator""", """VT-49 Decimator"""
exportObj.renameShip """TIE Aggressor""", """TIE/ag Aggressor"""
exportObj.renameShip """K-Wing""", """BTL-S8 K-Wing"""
exportObj.renameShip """ARC-170""", """ARC-170 Starfighter"""
exportObj.renameShip """Attack Shuttle""", """Attack Shuttle"""
exportObj.renameShip """X-Wing""", """T-65 X-Wing"""
exportObj.renameShip """HWK-290""", """HWK-290 Light Freighter"""
exportObj.renameShip """A-Wing""", """RZ-1 A-Wing"""
exportObj.renameShip """Fang Fighter""", """Fang Fighter"""
exportObj.renameShip """Z-95 Headhunter""", """Z-95-AF4 Headhunter"""
exportObj.renameShip """M12-L Kimogila Fighter""", """M12-L Kimogila Fighter"""
exportObj.renameShip """E-Wing""", """E-Wing"""
exportObj.renameShip """TIE Interceptor""", """TIE Interceptor"""
exportObj.renameShip """Lancer-Class Pursuit Craft""", """Lancer-class Pursuit Craft"""
exportObj.renameShip """TIE Reaper""", """TIE Reaper"""
exportObj.renameShip """JumpMaster 5000""", """JumpMaster 5000"""
exportObj.renameShip """M3-A Interceptor""", """M3-A Interceptor"""
exportObj.renameShip """Scavenged YT-1300""", """Scavenged YT-1300 Light Freighter"""
exportObj.renameShip """Escape Craft""", """Escape Craft"""
# Names don't need updating, but text needs to be set
pilot_translations =
"Academy Pilot":
display_name: """Academy Pilot"""
text: """ """
"Alpha Squadron Pilot":
display_name: """Alpha Squadron Pilot"""
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Bandit Squadron Pilot":
display_name: """Bandit Squadron Pilot"""
text: """ """
"Baron of the Empire":
display_name: """Baron of the Empire"""
text: """ """
"Binayre Pirate":
display_name: """Binayre Pirate"""
text: """ """
"Black Squadron Ace":
display_name: """Black Squadron Ace"""
text: """ """
"Black Squadron Scout":
display_name: """Black Squadron Scout"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Black Sun Ace":
display_name: """Black Sun Ace"""
text: """ """
"Black Sun Assassin":
display_name: """Black Sun Assassin"""
text: """<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Black Sun Enforcer":
display_name: """Black Sun Enforcer"""
text: """<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Black Sun Soldier":
display_name: """Black Sun Soldier"""
text: """ """
"Blade Squadron Veteran":
display_name: """Blade Squadron Veteran"""
text: """ """
"Blue Squadron Escort":
display_name: """Blue Squadron Escort"""
text: """ """
"Blue Squadron Pilot":
display_name: """Blue Squadron Pilot"""
text: """ """
"Blue Squadron Scout":
display_name: """Blue Squadron Scout"""
text: """ """
"Bounty Hunter":
display_name: """Bounty Hunter"""
text: """ """
"Cartel Executioner":
display_name: """Cartel Executioner"""
text: """<sasmall> <strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"Cartel Marauder":
display_name: """Cartel Marauder"""
text: """ """
"Cartel Spacer":
display_name: """Cartel Spacer"""
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Cavern Angels Zealot":
display_name: """Cavern Angels Zealot"""
text: """ """
"Contracted Scout":
display_name: """Contracted Scout"""
text: """ """
"Crymorah Goon":
display_name: """Crymorah Goon"""
text: """ """
"Cutlass Squadron Pilot":
display_name: """Cutlass Squadron Pilot"""
text: """ """
"Delta Squadron Pilot":
display_name: """Delta Squadron Pilot"""
text: """<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Freighter Captain":
display_name: """Freighter Captain"""
text: """"""
"Gamma Squadron Ace":
display_name: """Gamma Squadron Ace"""
text: """<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Gand Findsman":
display_name: """Gand Findsman"""
text: """ """
"Gold Squadron Veteran":
display_name: """Gold Squadron Veteran"""
text: """ """
"Gray Squadron Bomber":
display_name: """Gray Squadron Bomber"""
text: """ """
"Green Squadron Pilot":
display_name: """Green Squadron Pilot"""
text: """<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Hired Gun":
display_name: """Hired Gun"""
text: """ """
"Imdaar Test Pilot":
display_name: """Imdaar Test Pilot"""
text: """<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
"Inquisitor":
display_name: """Inquisitor"""
text: """ """
"Jakku Gunrunner":
display_name: """Jakku Gunrunner"""
text: """<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"Kashyyyk Defender":
display_name: """Kashyyyk Defender"""
text: """ """
"Knave Squadron Escort":
display_name: """Knave Squadron Escort"""
text: """<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Lok Revenant":
display_name: """Lok Revenant"""
text: """ """
"Lothal Rebel":
display_name: """Lothal Rebel"""
text: """<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"Nu Squadron Pilot":
display_name: """Nu Squadron Pilot"""
text: """ """
"Obsidian Squadron Pilot":
display_name: """Obsidian Squadron Pilot"""
text: """ """
"Omicron Group Pilot":
display_name: """Omicron Group Pilot"""
text: """ """
"Onyx Squadron Ace":
display_name: """Onyx Squadron Ace"""
text: """<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Onyx Squadron Scout":
display_name: """Onyx Squadron Scout"""
text: """ """
"Outer Rim Smuggler":
display_name: """Outer Rim Smuggler"""
text: """ """
"Partisan Renegade":
display_name: """Partisan Renegade"""
text: """ """
"Patrol Leader":
display_name: """Patrol Leader"""
text: """ """
"Phoenix Squadron Pilot":
display_name: """Phoenix Squadron Pilot"""
text: """<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Planetary Sentinel":
display_name: """Planetary Sentinel"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Rebel Scout":
display_name: """Rebel Scout"""
text: """ """
"Red Squadron Veteran":
display_name: """Red Squadron Veteran"""
text: """ """
"Rho Squadron Pilot":
display_name: """Rho Squadron Pilot"""
text: """ """
"Rogue Squadron Escort":
display_name: """Rogue Squadron Escort"""
text: """<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Saber Squadron Ace":
display_name: """Saber Squadron Ace"""
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Scarif Base Pilot":
display_name: """Scarif Base Pilot"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Scimitar Squadron Pilot":
display_name: """Scimitar Squadron Pilot"""
text: """<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Shadowport Hunter":
display_name: """Shadowport Hunter"""
text: """ """
"Sienar Specialist":
display_name: """Sienar Specialist"""
text: """ """
"Sigma Squadron Ace":
display_name: """Sigma Squadron Ace"""
text: """<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
"Skull Squadron Pilot":
display_name: """Skull Squadron Pilot"""
text: """<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Spice Runner":
display_name: """Spice Runner"""
text: """ """
"Storm Squadron Ace":
display_name: """Storm Squadron Ace"""
text: """<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Tala Squadron Pilot":
display_name: """Tala Squadron Pilot"""
text: """ """
"Tansarii Point Veteran":
display_name: """Tansarii Point Veteran"""
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Tempest Squadron Pilot":
display_name: """Tempest Squadron Pilot"""
text: """<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Trandoshan Slaver":
display_name: """Trandoshan Slaver"""
text: """ """
"Warden Squadron Pilot":
display_name: """Warden Squadron Pilot"""
text: """ """
"Wild Space Fringer":
display_name: """Wild Space Fringer"""
text: """<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
"Zealous Recruit":
display_name: """Zealous Recruit"""
text: """<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"4-LOM":
display_name: """4-LOM"""
text: """Miután teljesen végrehajtasz egy piros manővert, kapsz 1 kalkuláció jelzőt. A Vége fázis elején választhatsz 1 hajót 0-1-es távolságban. Ha így teszel, add át 1 stressz jelződ annak a hajónak."""
"Nashtah Pup":
display_name: """Nashtah Pup"""
text: """Csak vészhelyzet esetén válhatsz le az anyahajóról. Ebben az esetben megkapod a megsemmisült baráti Hound's Tooth pilóta nevet, kezdeményezést, pilóta képességet és hajó %CHARGE% jelzőt. %LINEBREAK% <strong>Escape Craft:</strong> <strong>Setup:</strong> <strong>Hound’s Tooth</strong> szükséges. A <strong>Hound’s Tooth</strong>-ra dokkolva <b>kell</b> kezdened a játékot."""
"AP-5":
display_name: """AP-5"""
text: """Amikor koordinálsz, ha a kiválasztott hajónak pontosan 1 stressz jelzője van, az végrehajthat akciókat.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"Airen Cracken":
display_name: """Airen Cracken"""
text: """Miután végrehajtasz egy támadást, választhatsz 1 baráti hajót 1-es távolságban. Az a hajó végrehajthat egy akciót, pirosként kezelve."""
"Arvel Crynyd":
display_name: """Arvel Crynyd"""
text: """Végrehajthatsz elsődleges támadást 0-ás távolságban. Ha egy %BOOST% akcióddal átfedésbe kerülsz egy másik hajóval, úgy hajtsd végre, mintha csak részleges manőver lett volna. %LINEBREAK% VECTORED THRUSTERS: Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% gyorsítás akciót."""
"Asajj Ventress":
display_name: """Asajj Ventress"""
text: """Az Ütközet fázis elején választhatsz 1 ellenséges hajót a %SINGLETURRETARC% tűzívedben 0-2-es távolságban és költs 1 %FORCE% jelzőt. Ha így teszel, az a hajó kap 1 stressz jelzőt, hacsak nem távolít el 1 zöld jelzőt."""
"Autopilot Drone":
display_name: """Autopilot Drone"""
text: """<strong>Rigged Energy Cells:</strong> A Rendszer fázis alatt, ha nem vagy dokkolva, elvesztesz 1 %CHARGE% jelzőt. Az aktivációs fázis végén, ha már nincs %CHARGE% jelződ, megsemmisülsz. Mielőtt levennéd a hajód minden 0-1-es távolságban lévő hajó elszenved 1 %CRIT% sérülést."""
"Benthic Two Tubes":
display_name: """Benthic Two Tubes"""
text: """Miután végrehajtasz egy %FOCUS% akciót, átrakhatod 1 fókusz jelződ egy baráti hajóra 1-2-es távolságban."""
"Biggs Darklighter":
display_name: """Biggs Darklighter"""
text: """Amikor baráti hajó védekezik tőled 0-1-es távolságban, az <strong>Eredmények semlegesítése</strong> lépés előtt, ha a támadó tűzívében vagy, elszenvedhetsz 1 %HIT% vagy %CRIT% találatot, hogy hatástalaníts 1 azzal egyező találatot."""
"Boba Fett":
display_name: """Boba Fett"""
text: """Amikor védekezel vagy végrehajtasz egy támadást, újradobhatsz 1 kockát, minden egyes 0-1-es távolságban lévő ellenséges hajó után."""
"Bodhi Rook":
display_name: """Bodhi Rook"""
text: """Baráti hajók bemérhetnek más baráti hajóktól 0-3-as távolságban lévő objektumokat."""
"Bossk":
display_name: """Bossk"""
text: """Amikor végrehajtasz egy elsődleges támadást, az <strong>Eredmények semlegesítése</strong> lépés után, elkölthetsz egy %CRIT% eredményt, hogy hozzáadj 2 %HIT% eredményt a dobásodhoz."""
"Braylen Stramm":
display_name: """Braylen Stramm"""
text: """Amikor védekezel vagy végrehajtasz egy támadást, ha stresszes vagy, újradobhatod legfeljebb 2 kockádat."""
"Captain Feroph":
display_name: """Captain Feroph"""
text: """Amikor védekezel, ha a támadónak nincs zöld jelzője, megváltoztathatod 1 üres vagy %FOCUS% dobásod %EVADE% eredményre.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Captain Jonus":
display_name: """Captain Jonus"""
text: """Amikor egy baráti hajó 0-1-es távolságban végrehajt egy %TORPEDO% vagy %MISSILE% támadást, az újradobhat legfeljebb 2 támadókockát.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Captain Jostero":
display_name: """Captain Jostero"""
text: """Miután egy ellenséges hajó sérülést szenved és nem védekezett, végrehajthatsz egy bónusz támadást ellene."""
"Captain Kagi":
display_name: """Captain Kagi"""
text: """Az Ütközet fázis elején választhatsz egy vagy több baráti hajót 0-3-es távolságban. Ha így teszel, tedd át az összes ellenséges bemérés jelzőt a kiválasztott hajókról magadra."""
"Captain Nym":
display_name: """Captain Nym"""
text: """Mielőtt egy baráti bomba vagy akna felrobbanna, elkölthetsz 1 %CHARGE% jelzőt, hogy megakadályozd a felrobbanását.%LINEBREAK%Mikor egy támadás ellen védekezel, amely akadályozott egy bomba vagy akna által, 1-gyel több védekezőkockával dobj."""
"Captain Oicunn":
display_name: """Captain Oicunn"""
text: """Végrehajthatsz elsődleges támadást 0-ás távolságban."""
"Captain Rex":
display_name: """Captain Rex"""
text: """Miután végrehajtasz egy támadást, jelöld meg a védekezőt a <strong>Suppressive Fire</strong> kondícióval."""
"Cassian Andor":
display_name: """Cassian Andor"""
text: """Az Aktivációs fázis elején választhatsz 1 baráti hajót 1-3-as távolságban. Ha így teszel, az a hajó eltávolít 1 stressz jelzőt."""
"Chewbacca":
display_name: """Chewbacca"""
text: """Mielőtt felfordított sebzéskártyát kapnál, elkölthetsz 1 %CHARGE%-et, hogy a lapot képpel lefelé húzd fel."""
"Colonel Jendon":
display_name: """Colonel Jendon"""
text: """Az Aktivációs fázis elején elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, amikor baráti hajók bemérés jelzőt tesznek fel ebben a körben, 3-as távolságon túl tehetik csak meg a 0-3-as távolság helyett."""
"Colonel Vessery":
display_name: """Colonel Vessery"""
text: """Amikor támadást hajtasz végre egy bemért hajó ellen, miután dobsz a kockákkal, feltehetsz egy bemérés jelzőt a védekezőre.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Constable Zuvio":
display_name: """Constable Zuvio"""
text: """Amikor kidobnál egy eszközt, helyette ki is lőheted egy [1 %STRAIGHT%] sablon használatával.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"Corran Horn":
display_name: """Corran Horn"""
text: """0-ás kezdeményezésnél végrehajthatsz egy bónusz elsődleges támadást egy ellenséges hajó ellen, aki a %BULLSEYEARC% tűzívedben van. Ha így teszel, a következő Tervezés fázisban kapsz 1 'inaktív fegyverzet' jelzőt.%LINEBREAK%<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Countess Ryad":
display_name: """Countess Ryad"""
text: """Amikor végrehajtanál egy %STRAIGHT% manővert, megnövelheted annak nehézségét. Ha így teszel, helyette végrehajthatod mint %KTURN% manőver.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Dace Bonearm":
display_name: """Dace Bonearm"""
text: """Miután egy ellenséges hajó 0-3-as távolságban kap legalább 1 ion jelzőt, elkölthetsz 3 %CHARGE% jelzőt. Ha így teszel, az a hajó kap 2 további ion jelzőt."""
"Dalan Oberos (StarViper)":
display_name: """Dalan Oberos"""
text: """Miután teljesen végrehajtasz egy manővert, kaphatsz 1 stressz jelzőt, hogy elforgasd a hajód 90 fokkal.%LINEBREAK% <sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Dalan Oberos":
display_name: """Dalan Oberos"""
text: """Az Ütközet fázis elején választhatsz 1 pajzzsal rendelkező hajót a %BULLSEYEARC% tűzívedben és elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó elveszít egy pajzsot, te pedig visszatöltesz 1 pajzsot.%LINEBREAK%<sasmall><strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"Darth Vader":
display_name: """Darth Vader"""
text: """Miután végrehajtasz egy akciót, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy akciót.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Dash Rendar":
display_name: """Dash Rendar"""
text: """Amikor mozogsz, hagyd figyelmen kívül az akadályokat.%LINEBREAK%<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
"Del Meeko":
display_name: """Del Meeko"""
text: """Amikor egy baráti 0-2 távolságban védekezik egy sérült támadó ellen, a védekező újradobhat 1 védekezőkockát."""
"Dengar":
display_name: """Dengar"""
text: """Miután védekeztél, ha a támadó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy bónusz támadást a támadó ellen."""
"Drea Renthal":
display_name: """Drea Renthal"""
text: """Amikor egy baráti nem-limitált hajó végrehajt egy támadást, ha a védekező benne van a tűzívedben, a támadó újradobhatja 1 támadókockáját."""
"Edrio Two Tubes":
display_name: """Edrio Two Tubes"""
text: """Mielőtt aktiválódnál és van fókuszod, végrehajthatsz egy akciót."""
"Emon Azzameen":
display_name: """Emon Azzameen"""
text: """Ha ki szeretnél dobni egy eszközt az [1 %STRAIGHT%] sablonnal, használhatod helyette a [3 %TURNLEFT%], [3 %STRAIGHT%], vagy [3 %TURNRIGHT%] sablont."""
"Esege Tuketu":
display_name: """Esege Tuketu"""
text: """Amikor egy 0-2-es távolságban lévő baráti hajó védekezik vagy támadást hajt végre, elköltheti a te fókusz jelzőidet, mintha a saját hajójáé lenne."""
"Evaan Verlaine":
display_name: """Evaan Verlaine"""
text: """Az Ütközet fázis elején elkölthetsz 1 fókusz jelzőt, hogy kiválassz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó a kör végéig minden védekezésénél 1-gyel több védekezőkockával dob."""
"Ezra Bridger":
display_name: """Ezra Bridger"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"Ezra Bridger (Sheathipede)":
display_name: """Ezra Bridger"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"Ezra Bridger (TIE Fighter)":
display_name: """Ezra Bridger"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts."""
"Fenn Rau (Sheathipede)":
display_name: """Fenn Rau"""
text: """Miután egy ellenséges hajó a tűzívedben sorra kerül az Ütközet fázisban, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt. Ha így teszel, az a hajó nem költhet el jelzőt, hogy módosítsa támadókockáit e fázis alatt.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"Fenn Rau":
display_name: """Fenn Rau"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha a támadás 1-es távolságban történik, 1-gyel több kockával dobhatsz.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Garven Dreis (X-Wing)":
display_name: """Garven Dreis"""
text: """Miután elköltesz egy fókusz jelzőt, választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó kap 1 fókusz jelzőt."""
"Garven Dreis":
display_name: """Garven Dreis"""
text: """Miután elköltesz egy fókusz jelzőt, választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó kap 1 fókusz jelzőt."""
"Gavin Darklighter":
display_name: """Gavin Darklighter"""
text: """Amikor egy baráti hajó végrehajt egy támadást, ha a védekező a %FRONTARC% tűzívedben van, a támadó 1 %HIT% eredményét %CRIT% eredményre módosíthatja.%LINEBREAK%<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Genesis Red":
display_name: """Genesis Red"""
text: """Miután feltettél egy bemérés jelzőt, le kell venned az összes fókusz és kitérés jelződet, aztán megkapsz annyi fókusz és kitérés jelzőt, ahány a bemért hajónak van.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Gideon Hask":
display_name: """Gideon Hask"""
text: """Amikor végrehajtasz egy támadást sérült védekező ellen, 1-gyel több támadókockával dobhatsz."""
"Grand Inquisitor":
display_name: """Grand Inquisitor"""
text: """Amikor 1-es távolságban védekezel, elkölthetsz 1 %FORCE% tokent, hogy megakadályozd az 1-es távolság bónuszt. Amikor támadást hajtasz végre 2-3-as távolságban lévő védekező ellen, elkölthetsz 1 %FORCE% jelzőt, hogy megkapd az 1-es távolság bónuszt."""
"Graz":
display_name: """Graz"""
text: """Amikor védekezel, ha a támadó mögött vagy, 1-gyel több védekezőkockával dobhatsz. Amikor végrehajtasz egy támadást, ha a védekező mögött vagy, 1-gyel több támadókockával dobhatsz."""
"Guri":
display_name: """Guri"""
text: """Az Ütközet fázis elején, ha legalább 1 ellenséges hajó van 0-1-es távolságban, kaphatsz egy fókusz jelzőt.%LINEBREAK% <sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Han Solo":
display_name: """Han Solo"""
text: """Miután dobtál, ha 0-1-es távolságban vagy akadálytól, újradobhatod az összes kockádat. Ez nem számít újradobásnak más hatások számára."""
"Han Solo (Scum)":
display_name: """Han Solo"""
text: """Amikor védekezel vagy elsődleges támadást hajtasz vége, ha a támadás akadály által akadályozott, 1-gyel több kockával dobhatsz."""
"Heff Tobber":
display_name: """Heff Tobber"""
text: """Miután egy ellenséges hajó végrehajt egy manővert, ha 0-ás távolságba kerül, végrehajthatsz egy akciót."""
"Hera Syndulla":
display_name: """Hera Syndulla"""
text: """Miután piros vagy kék manővert fedtél fel, átállíthatod manőversablonod egy másik, azonos nehézségű manőverre.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"Hera Syndulla (VCX-100)":
display_name: """Hera Syndulla"""
text: """Miután piros vagy kék manővert fedtél fel, átállíthatod manőversablonod egy másik, azonos nehézségű manőverre.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"Horton Salm":
display_name: """Horton Salm"""
text: """Amikor támadást hajtasz végre, a védekezőtől 0-1-es távolságban lévő minden más baráti hajó után újradobhatsz 1 támadókockát."""
"IG-88A":
display_name: """IG-88A"""
text: """Az Ütközet fázis elején kiválaszthatsz egy %CALCULATE% akcióval rendelkező baráti hajót 1-3-as távolságban. Ha így teszel, add át 1 kalkuláció jelződet neki.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88B":
display_name: """IG-88B"""
text: """Miután végrehajtasz egy támadást ami nem talált, végrehajthatsz egy bónusz %CANNON% támadást.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88C":
display_name: """IG-88C"""
text: """Miután végrehajtasz egy %BOOST% akciót, végrehajthatsz egy %EVADE% akciót.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88D":
display_name: """IG-88D"""
text: """Amikor végrehajtasz egy Segnor's Loop [%SLOOPLEFT% vagy %SLOOPRIGHT%] manővert, használhatsz ugyanazon sebességű másik sablont helyette: vagy megegyező irányú kanyar [%TURNLEFT% vagy %TURNRIGHT%] vagy előre egyenes [%STRAIGHT%] sablont.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"Ibtisam":
display_name: """Ibtisam"""
text: """Miután teljesen végrehajtasz egy manővert, ha stresszes vagy, dobhatsz 1 támadókockával. %HIT% vagy %CRIT% eredmény esetén távolíts el 1 stressz jelzőt."""
"Iden Versio":
display_name: """Iden Versio"""
text: """Mielőtt egy 0-1-es távolságban lévő baráti TIE/ln hajó elszenvedne 1 vagy több sérülést, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, megakadályozod a sérülést."""
"Inaldra":
display_name: """Inaldra"""
text: """Amikor védekezel vagy támadást hajtasz végre, elszenvedhetsz 1 %HIT% sérülést, hogy újradobj bármennyi kockát.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Jake Farrell":
display_name: """Jake Farrell"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, választhatsz egy baráti hajót 0-1-es távolságban. Az a hajó végrehajthat egy %FOCUS% akciót.%LINEBREAK%<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Jan Ors":
display_name: """Jan Ors"""
text: """Amikor egy tűzíveden belüli baráti hajó elsődleges támadást hajt végre, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt. Ha így teszel, az a hajó 1-gyel több támadókockával dobhat."""
"Jek Porkins":
display_name: """Jek Porkins"""
text: """Miután kapsz egy stressz jelzőt, dobhatsz 1 támadó kockával, hogy levedd. %HIT% eredmény esetén elszenvedsz 1 %HIT% sérülést."""
"Joy Rekkoff":
display_name: """Joy Rekkoff"""
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %CHARGE% jelzőt egy felszerelt %TORPEDO% fejlesztésről. Ha így teszel a védekező 1-gyel kevesebb védekezőkockával dob.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Kaa'to Leeachos":
display_name: """Kaa’to Leeachos"""
text: """Az Ütközet fázis elején kiválaszthatsz egy 0-2-es távolságban lévő baráti hajót. Ha így teszel, áttehetsz róla 1 fókusz vagy kitérés jelzőt a magadra."""
"Kad Solus":
display_name: """Kad Solus"""
text: """Miután teljesen végrehajtasz egy piros manővert, kapsz 2 fókusz jelzőt.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Kanan Jarrus":
display_name: """Kanan Jarrus"""
text: """Amikor egy tűzívedben lévő baráti hajó védekezik, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a támadó 1-gyel kevesebb támadókockával dob.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"Kath Scarlet":
display_name: """Kath Scarlet"""
text: """Amikor támadást hajtasz végre, ha legalább 1 nem-limitált baráti hajó van 0-ás távolságra a védekezőtől, dobj 1-gyel több támadókockával."""
"Kavil":
display_name: """Kavil"""
text: """Amikor egy nem-%FRONTARC% támadást hajtasz végre, dobj 1-gyel több támadókockával."""
"Ketsu Onyo":
display_name: """Ketsu Onyo"""
text: """Az Ütközet fázis elején választhatsz 1 hajót ami a %FRONTARC% és %SINGLETURRETARC% tűzívedben is benne van 0-1-es távolságban. Ha így teszel, az a hajó kap egy vonósugár jelzőt."""
"Koshka Frost":
display_name: """Koshka Frost"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó stresszes, újradobhatod 1 kockádat."""
"Krassis Trelix":
display_name: """Krassis Trelix"""
text: """Végrehajthatsz egy %FRONTARC% speciális támadást a %REARARC% tűzívedből. Amikor speciális támadást hajtasz végre, újradobhatsz egy támadókockát."""
"Kullbee Sperado":
display_name: """Kullbee Sperado"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, megfordíthatod a felszerelt %CONFIG% fejlesztés kártyád."""
"Kyle Katarn":
display_name: """Kyle Katarn"""
text: """Az Ütközet fázis elején átadhatod 1 fókusz jelződet egy tűzívedben lévő baráti hajónak."""
"L3-37":
display_name: """L3-37"""
text: """Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek."""
"L3-37 (Escape Craft)":
display_name: """L3-37"""
text: """Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"Laetin A'shera":
display_name: """Laetin A’shera"""
text: """Miután védekezel vagy támadást hajtasz végre, ha a támadás nem talált, kapsz 1 kitérés jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Lando Calrissian":
display_name: """Lando Calrissian"""
text: """Miután teljesen végrehajtasz egy kék manővert, választhatsz egy baráti hajót 0-3-as távolságban. Az a hajó végrehajthat egy akciót."""
"Lando Calrissian (Scum)":
display_name: """Lando Calrissian"""
text: """Miután dobsz a kockákkal, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy újradobhasd az összes üres eredményed."""
"Lando Calrissian (Scum) (Escape Craft)":
display_name: """Lando Calrissian"""
text: """Miután dobsz a kockákkal, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy újradobhasd az összes üres eredményed.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"Latts Razzi":
display_name: """Latts Razzi"""
text: """Az Ütközet fázis elején kiválaszthatsz egy hajót 1-es távolságban és elköltheted a rajta lévő bemérés jelződet. Ha így teszel, az a hajó kap egy vonósugár jelzőt."""
"Leevan Tenza":
display_name: """Leevan Tenza"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, végrehajthatsz egy piros %EVADE% akciót."""
"Lieutenant Blount":
display_name: """Lieutenant Blount"""
text: """Amikor elsődleges támadást hajtasz végre, ha legalább 1 másik baráti hajó van 0-1-es távolságban a védekezőtől, 1-gyel több támadókockával dobhatsz."""
"Lieutenant Karsabi":
display_name: """Lieutenant Karsabi"""
text: """Miután kapsz egy inaktív fegyverzet jelzőt, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy levegyél 1 inaktív fegyverzet jelzőt."""
"Lieutenant Kestal":
display_name: """Lieutenant Kestal"""
text: """Amikor támadást hajtasz végre, miután a védekező dob a kockáival, elkölthetsz 1 fókusz jelzőt, hogy semlegesítsd a védekező összes üres és fókusz eredményét."""
"Lieutenant Sai":
display_name: """Lieutenant Sai"""
text: """Miután végrehajtasz egy %COORDINATE% akciót, ha a koordinált hajó olyan akciót hajt végre, ami a te akciósávodon is rajta van, végrehajthatod azt az akciót."""
"Lowhhrick":
display_name: """Lowhhrick"""
text: """Miután egy 0-1-es távolságban lévő baráti hajó védekezővé válik, elkölthetsz 1 erősítés jelzőt. Ha így teszel, az a hajó kap 1 kitérés jelzőt."""
"Luke Skywalker":
display_name: """Luke Skywalker"""
text: """Miután védekező lettél (még a kockagurítás előtt), visszatölthetsz 1 %FORCE% jelzőt."""
"Maarek Stele":
display_name: """Maarek Stele"""
text: """Amikor támadást hajtasz végre, ha a védekező felfordított sérülés kártyát kapna, helyette húzz te 3 lapot, válassz egyet, a többit dobd el.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall> """
"Magva Yarro":
display_name: """Magva Yarro"""
text: """Amikor egy baráti hajó 0-2-es távolságban védekezik, a támadó maximum 1 kockáját dobhatja újra."""
"Major Rhymer":
display_name: """Major Rhymer"""
text: """Amikor végrhajtasz egy %TORPEDO% vagy %MISSILE% támadást, növelheted vagy csökkentheted a fegyver távolság követelményét 1-gyel, a 0-3 korláton belül.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Major Vermeil":
display_name: """Major Vermeil"""
text: """Amikor támadást hajtasz végre, ha a védekezőnek nincs egy zöld jelzője sem, megváltoztathatod 1 üres vagy %FOCUS% eredményedet %HIT% eredményre.%LINEBREAK% %LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Major Vynder":
display_name: """Major Vynder"""
text: """Amikor védekezel és van 'inaktív fegyverzet' jelződ, dobj 1-gyel több védekezőkockával."""
"Manaroo":
display_name: """Manaroo"""
text: """Az Ütközet fázis elején kiválaszthatsz egy 0-1-es távolságban lévő baráti hajót. Ha így teszel, add át neki az összes zöld jelződ."""
"Miranda Doni":
display_name: """Miranda Doni"""
text: """Amikor elsődleges támadást hajtasz végre, elkölthetsz 1 pajzsot, hogy 1-gyel több támadókockával dobj, vagy ha nincs pajzsod, dobhatsz 1-gyel kevesebb támadókockával, hogy visszatölts 1 pajzsot."""
"Moralo Eval":
display_name: """Moralo Eval"""
text: """Ha lerepülsz a pályáról, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, helyezd a hajód tartalékba. A következő Tervezési fázis elején helyezd el a hajót a pálya szélétől 1-es távolságban azon az oldalon, ahol lerepültél."""
"Norra Wexley (Y-Wing)":
display_name: """Norra Wexley"""
text: """Amikor védekezel, ha az ellenség 0-1-es távolságban van, adj 1 %EVADE% eredményt a dobásodhoz."""
"Norra Wexley":
display_name: """Norra Wexley"""
text: """Amikor védekezel, ha az ellenség 0-1-es távolságban van, adj 1 %EVADE% eredményt a dobásodhoz."""
"N'dru Suhlak":
display_name: """N’dru Suhlak"""
text: """Amikor elődleges támadást hajtasz végre, ha nincs baráti hajó 0-2 távolságban, dobj 1-gyel több támadókockával."""
"Old Teroch":
display_name: """Old Teroch"""
text: """Az Ütközet fázis elején, kiválaszthatsz 1 ellenséges hajót 1-es távolságban. Ha így teszel és benne vagy a %FRONTARC% tűzívében, leveheted az összes zöld jelzőjét.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Outer Rim Pioneer":
display_name: """Outer Rim Pioneer"""
text: """Baráti hajók 0-1-es távolságban végrehajthatnak támadást akadálytól 0 távolságra.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"Palob Godalhi":
display_name: """Palob Godalhi"""
text: """Az Ütközet fázis elején kiválaszthatsz 1 ellenséges hajót a tűzívedben 0-2 távolságban. Ha így teszel tedd át 1 fókusz vagy kitérés jelzőjét magadra."""
"Prince Xizor":
display_name: """Prince Xizor"""
text: """Amikor védekezel, az <strong>Eredmények semlegesítése</strong> lépés után, egy 0-1 távolságban lévő másik baráti hajó, aki benne van a támadó tűzívében, elszenvedhet 1 %HIT% vagy %CRIT% sérülést. Ha így tesz, hatástalaníts 1 ennek megfelelő eredményt.%LINEBREAK%<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Quinn Jast":
display_name: """Quinn Jast"""
text: """Az Ütközet fázis elején kaphatsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts 1 %CHARGE% jelzőt egy felszerelt fejlesztésen.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Rear Admiral Chiraneau":
display_name: """Rear Admiral Chiraneau"""
text: """Amikor támadást hajtasz végre, ha van 'reinforce' jelződ és a védekező a reinforce-nak megfelelő %FULLFRONTARC% vagy %FULLREARARC% tűzívedben van, megváltoztathatod 1 %FOCUS% eredményed %CRIT% eredményre."""
"Rexler Brath":
display_name: """Rexler Brath"""
text: """Miután végrehajtasz egy támadást, ami talál, ha van kitérés jelződ, fordítsd fel a védekező egy sérülés kártyáját.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Roark Garnet":
display_name: """Roark Garnet"""
text: """Az Ütközet fázis elején választhatsz 1 tűzívedben lévő hajót. Ha így teszel, a kezdeményezési értéke ebben a fázisban 7 lesz, függetlenül a nyomtatott értékétől."""
"Sabine Wren":
display_name: """Sabine Wren"""
text: """Mielőtt aktiválódsz, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"Sabine Wren (TIE Fighter)":
display_name: """Sabine Wren"""
text: """Mielőtt aktiválódsz, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót."""
"Sabine Wren (Scum)":
display_name: """Sabine Wren"""
text: """Amikor védekezel, ha a támadó benne van a %SINGLETURRETARC% tűzívedben 0-2-es távolságban, hozzáadhatsz 1 %FOCUS% eredményt a dobásodhoz."""
"Sarco Plank":
display_name: """Sarco Plank"""
text: """Amikor védekezel kezelheted a mozgékonyság értékedet úgy, hogy az megegyezzen az ebben a körben végrehajtott manővered sebességével.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"Saw Gerrera":
display_name: """Saw Gerrera"""
text: """Amikor egy sérült baráti hajó 0-3-as távolságban végrehajt egy támadást, újradobhat 1 támadókockát."""
"Serissu":
display_name: """Serissu"""
text: """Amikor egy baráti hajó 0-1-es távolságban védekezik, újradobhatja 1 kockáját.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Seventh Sister":
display_name: """Seventh Sister"""
text: """Amikor végrehajtasz egy elsődleges támadást, az <strong>Eredmények semlegesítése</strong> lépés előtt elkölthetsz 2 %FORCE% jelzőt, hogy hatástalaníts 1 %EVADE% eredményt."""
"Seyn Marana":
display_name: """Seyn Marana"""
text: """Amikor végrehajtasz egy támadást elkölthetsz 1 %CRIT% eredményt. Ha így teszel, a védekező kap 1 lefordított sérülés kártyát, majd hatástalanítsd a többi dobás eredményed."""
"Shara Bey":
display_name: """Shara Bey"""
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre, elköltheted az ellenfeledre tett bemérés jelződet, hogy hozzáadj 1 %FOCUS% eredményt dobásodhoz."""
"Sol Sixxa":
display_name: """Sol Sixxa"""
text: """Ha ledobnál egy eszközt az [1 %STRAIGHT%] sablon használatával, helyette ledobhatod más 1-es sebességű sablonnal."""
"Soontir Fel":
display_name: """Soontir Fel"""
text: """Az Ütközet fázis elején, ha van ellenséges hajó a %BULLSEYEARC% tűzívedben, kapsz 1 fókusz jelzőt.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Sunny Bounder":
display_name: """Sunny Bounder"""
text: """Amikor védekezel vagy támadást hajtasz végre, miután dobtál vagy újradobtál kockákat, ha minden eredményed egyforma, hozzáadhatsz 1 ugyanolyan eredményt a dobáshoz.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Talonbane Cobra":
display_name: """Talonbane Cobra"""
text: """Amikor 3-as távolságban védekezel vagy 1-es távolságban támadást hajtasz végre, dobj 1-gyel több kockával."""
"Tel Trevura":
display_name: """Tel Trevura"""
text: """Ha megsemmisülnél, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, dobd el az összes sérülés kártyádat, szenvedj el 5 %HIT% sérülést, majd helyezd magad tartalékba. A következő Tervezési fázis elején helyezd fel a hajód 1-es távolságban a saját oldaladon."""
"Ten Numb":
display_name: """Ten Numb"""
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 stressz jelzőt, hogy minden %FOCUS% eredményed megváltoztasd %EVADE% vagy %HIT% eredményre."""
"Thane Kyrell":
display_name: """Thane Kyrell"""
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %FOCUS%, %HIT% vagy %CRIT% eredményt, hogy megnézd a védekező képpel lefelé fordított sérülés kártyáit, kiválassz egyet és megfordítsd."""
"Tomax Bren":
display_name: """Tomax Bren"""
text: """Miután végrehajtasz egy %RELOAD% akciót, visszatölthetsz 1 %CHARGE% jelzőt 1 felszerelt %TALENT% fejlesztés kártyán.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Torani Kulda":
display_name: """Torani Kulda"""
text: """Miután végrehajtasz egy támadást, minden ellenséges hajó a %BULLSEYEARC% tűzívedben elszenved 1 %HIT% sérülést, hacsak el nem dob 1 zöld jelzőt.%LINEBREAK%<sasmall><strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"Torkil Mux":
display_name: """Torkil Mux"""
text: """Az Ütközet fázis elején kiválaszthatsz 1 hajót a tűzívedben. Ha így teszel, az a hajó ebben a körben 0-ás kezdeményezéssel kerül sorra a normál kezdeményezése helyett."""
"Turr Phennir":
display_name: """Turr Phennir"""
text: """Miután végrehajtasz egy támadást, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót akkor is ha stresszes vagy.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Unkar Plutt":
display_name: """Unkar Plutt"""
text: """Az Ütközet fázis elején, ha van egy vagy több másik hajó 0-ás távolságban tőled, te és a 0-ás távolságra lévő hajók kapnak egy vonósugár jelzőt.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"Valen Rudor":
display_name: """Valen Rudor"""
text: """Miután egy baráti hajó 0-1-es távolságban védekezik - a sérülések elkönyvelése után, ha volt -, végrehajthatsz egy akciót."""
"Ved Foslo":
display_name: """Ved Foslo"""
text: """Amikor végrehajtasz egy manővert, helyette végrehajthatsz egy manővert ugyanabban az irányban és nehézségben 1-gyel kisebb vagy nagyobb sebességgel.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Viktor Hel":
display_name: """Viktor Hel"""
text: """Miután védekeztél, ha nem pontosan 2 védekezőkockával dobtál, a támadó kap 1 stress jelzőt."""
"Wedge Antilles":
display_name: """Wedge Antilles"""
text: """Amikor támadást hajtasz végre, a védekező 1-gyel kevesebb védekezőkockával dob."""
"Wullffwarro":
display_name: """Wullffwarro"""
text: """Amikor elsődleges támadást hajtasz végre, ha sérült vagy, 1-gyel több támadókockával dobhatsz."""
"Zertik Strom":
display_name: """Zertik Strom"""
text: """A Vége fázis alatt elköltheted egy ellenséges hajón lévő bemérődet hogy felfordítsd egy sérülés kártyáját.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Zuckuss":
display_name: """Zuckuss"""
text: """Amikor végrehajtasz egy elsődleges támadást, 1-gyel több támadókockával dobhatsz. Ha így teszel, a védekező 1-gyel több védekezőkockával dob."""
'"Chopper"':
display_name: """“Chopper”"""
text: """Az Ütközet fázis elején minden 0-ás távolságban lévő ellenséges hajó 2 zavarás jelzőt kap.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
'"Countdown"':
display_name: """“Countdown”"""
text: """Amikor védekezel, az <strong>Eredmények semlegesítése</strong> lépés után, ha nem vagy stresszes, választhatod, hogy elszenvedsz 1 %HIT% sérülést és kapsz 1 stressz jelzőt. Ha így teszel, vess el minden kocka dobást.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Deathfire"':
display_name: """“Deathfire”"""
text: """Miután megsemmisülsz, mielőtt levennéd a hajód, végrehajthatsz egy támadást és ledobhatsz vagy kilőhetsz 1 eszközt.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
'"Deathrain"':
display_name: """“Deathrain”"""
text: """Miután ledobsz vagy kilősz egy eszközt, végrehajthatsz egy akciót."""
'"Double Edge"':
display_name: """“Double Edge”"""
text: """Miután végrehajtasz egy %TURRET% vagy %MISSILE% támadást ami nem talál, végrehajthatsz egy bónusz támadást egy másik fegyverrel."""
'"Duchess"':
display_name: """“Duchess”"""
text: """Választhatsz úgy, hogy nem használod az <strong>Adaptive Ailerons</strong> képességed. Használhatod akkor is <strong>Adaptive Ailerons</strong> képességed, amikor stresszes vagy.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Dutch" Vander':
display_name: """“Dutch” Vander"""
text: """Miután %LOCK% akciót hajtottál végre választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó is bemérheti az általad bemért objektumot, függetlenül a távolságtól."""
'"Echo"':
display_name: """“Echo”"""
text: """Amikor kijössz az álcázásból, a [2 %BANKLEFT%] vagy [2 %BANKRIGHT%] sablont <b>kell</b> használnod a [2 %STRAIGHT%] helyett.%LINEBREAK%<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
'"Howlrunner"':
display_name: """“Howlrunner”"""
text: """Amikor egy 0-1-es távolságban lévő baráti hajó elsődleges támadást hajt végre, 1 támadókockát újradobhat."""
'"Leebo"':
display_name: """“Leebo”"""
text: """Miután védekeztél vagy támadást hajtottál végre, ha elköltöttél egy kalkuláció jelzőt, kapsz 1 kalkuláció jelzőt.%LINEBREAK%<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
'"Mauler" Mithel':
display_name: """“Mauler” Mithel"""
text: """Amikor támadást hajtasz végre 1-es távolságban, dobj 1-gyel több támadókockával."""
'"Night Beast"':
display_name: """“Night Beast”"""
text: """Miután teljesen végrehajtasz egy kék manővert, végrehajthatsz egy %FOCUS% akciót."""
'"Pure Sabacc"':
display_name: """“Pure Sabacc”"""
text: """Amikor támadást hajtasz végre, ha 1 vagy kevesebb sérüléskártyád van, 1-gyel több támadókockával dobhatsz.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Redline"':
display_name: """“Redline”"""
text: """Fenntarthatsz 2 bemérő jelzőt. Miután végrehajtasz egy akciót, feltehetsz egy bemérő jelzőt."""
'"Scourge" Skutu':
display_name: """“Scourge” Skutu"""
text: """Amikor végrehajtasz egy támadást a %BULLSEYEARC% tűzívedben lévő védekező ellen, dobj 1-gyel több támadókockával."""
'"Vizier"':
display_name: """“Vizier”"""
text: """Miután teljesen végrehajtasz egy 1-es sebességű manővert az <strong>Adaptive Ailerons</strong> képességed használatával, végrehajthatsz egy %COORDINATE% akciót. Ha így teszel, hagyd ki az <strong>Akció végrehajtása</strong> lépést.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Wampa"':
display_name: """“Wampa”"""
text: """Amikor végrehajtasz egy támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy 1-gyel több támadókockával dobj. Védekezés után elvesztesz 1 %CHARGE% jelzőt."""
'"Whisper"':
display_name: """“Whisper”"""
text: """Miután végrehajtasz egy támadást ami talál, kapsz 1 kitérés jelzőt.%LINEBREAK%<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
'"Zeb" Orrelios':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
'"Zeb" Orrelios (Sheathipede)':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
'"Zeb" Orrelios (TIE Fighter)':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál."""
"Poe Dameron":
text: """Miután végrehajtasz egy akciót, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy fehér akciót pirosként kezelve.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Lieutenant Bastian":
text: """Miután egy hajó 1-2-es távolságban felhúz egy sérülés kártyát, felrakhatsz rá egy bemérő jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
'"Midnight"':
text: """Amikor védekezel vagy támadás hajtasz végre, ha van bemérőd azon az ellenséges hajón, az nem módosíthatja a kockáit."""
'"Longshot"':
text: """Amikor elsődleges támadást hajtasz végre 3-as távolságban, dobj 1-gyel több támadókockával."""
'"Muse"':
text: """Az Ütközet fázis elején válaszhatsz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó vegyen le 1 stressz jelzőt."""
"Kylo Ren":
text: """Miután védekeztél, elkölthetsz 1 %FORCE% jelzőt, hogy hozzárendeled az <strong>I'll Show You the Dark Side</strong> kondíciós kártyát a támadódhoz.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
'"Blackout"':
text: """Amikor végrehajtasz egy támadást, ha a támadás akadályozott egy akadály által, a védekező 2-vel kevesebb védekezőkockával dob.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Lieutenant Dormitz":
text: """Felhelyezés: Miután felhelyezésre kerültél, a többi baráti hajó bárhova helyezhető a játékterületen tőled 0-2-es távolságban.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Backdraft"':
text: """Amikor végrehajtasz egy %SINGLETURRETARC% elsődleges támadást, ha a védekező benne van a %REARARC% tűzívedben dobj 1-gyel több kockával.%LINEBREAK%<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
'"Quickdraw"':
text: """Miután elvesztesz egy pajzsot, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, végrehajthatsz egy bónusz elsődleges támadást.%LINEBREAK%<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Zeta Squadron Survivor":
text: """<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Rey":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy 1 üres eredményed %EVADE% vagy %HIT% eredményre változtasd."""
"Han Solo (Resistance)":
text: """Felhelyezés: Bárhova felhelyezheted a hajód a játékterületre 3-as távolságon túl az ellenséges hajóktól."""
"Chewbacca (Resistance)":
text: """Miután egy baráti hajó 0-3-as távolságban megsemmisül, végrehajthatsz egy akciót. Aztán végrehajthatsz egy bónusz támadást."""
"Captain Seevor":
text: """Amikor védekezel vagy támadást hajtasz végre, mielőtt a támadókockát elgurulnának, ha nem vagy az ellenséges hajó %BULLSEYEARC% tűzívében, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az ellenséges hajó kap egy zavarás jelzőt.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Mining Guild Surveyor":
text: """<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Mining Guild Sentry":
text: """<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Ahhav":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az elleséges hajó nagyobb talpméretű, dobj 1-gyel több kockával.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Finch Dallow":
text: """Mielőtt ledobnál egy bombát, ledobás helyett elhelyezheted a játékterületen úgy, hogy érintkezzen veled."""
"Major Stridan":
text: """Amikor koordinálsz vagy egy fejlesztés kártyád hatását alkalmaznád, kezelheted úgy a 2-3-as távolságban lévő baráti hajókat, mintha 0 vagy 1-es távolságban lennének.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"Kare Kun":
text: """Amikor gyorsítasz (%BOOST%), használhatod a [1 %TURNLEFT%] vagy [1 %TURNRIGHT%] sablonokat is.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Joph Seastriker":
text: """Miután elvesztesz 1 pajzsod, kapsz 1 %EVADE% jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Lieutenant Bastian":
text: """Miután egy hajó 1-2-es távolságban felhúz egy sérülés kártyát, felrakhatsz rá egy bemérő jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Jaycris Tubbs":
text: """Miután teljesen végrehajtasz egy kék manővert, választhatsz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó levesz egy stressz jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Black Squadron Ace (T-70)":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Red Squadron Expert":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Blue Squadron Rookie":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Cobalt Squadron Bomber":
text: """ """
"TN-3465":
text: """Amikor egy másik baráti hajó támadást hajt végre, ha 0-1 távolságban vagy a védekezőtől, elszenvedhetsz 1 %CRIT% sérülést, hogy a támadó 1 eredményét %CRIT% eredményre változtassa."""
'"Scorch"':
text: """Amikor elsődleges támadást hajtasz végre, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy 1-gyel több támadókockával dobj."""
'"Longshot"':
text: """Amikor elsődleges támadást hajtasz végre 3-as távolságban, dobj 1-gyel több támadókockával."""
'"Static"':
text: """Amikor elsődleges támadást hajtasz végre, elköltheted a védekezőn lévő bemérődet és egy %FOCUS% jelződ, hogy minden eredményed %CRIT% eredményre változtass."""
"Lieutenant Rivas":
text: """Miután egy hajó 1-2-es távolságban kap egy piros vagy narancs jelzőt, ha nem volt bemérőd a hajón, feltehetsz egyet rá."""
"Commander Malarus":
text: """Az Ütközet fázis elején elkölthetsz 1 %CHARGE% jelzőt, hogy kapj 1 stressz jelzőt. Ha így teszel, a kör végéig ha védekezel vagy támadást hajtasz végre, megváltoztathatsz minden %FOCUS% eredményed %EVADE% vagy %HIT% eredményre."""
"Omega Squadron Ace":
text: """"""
"Zeta Squadron Pilot":
text: """"""
"Epsilon Squadron Cadet":
text: """"""
"Greer Sonnel":
text: """Miután teljesen végrehajtasz egy manővert, forgathatod a %SINGLETURRETARC% tűzívedet.%SINGLETURRETARC% %LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"L'ulo L'ampar":
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre, ha stresszes vagy, 1-gyel kevesebb védekezőkockával vagy 1-gyel több támadókockával <strong>kell</strong> dobnod.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Zari Bangel":
text: """Ne hagyd ki az <strong>Akció végrehajtása</strong> lépést, miután részlegesen hajtottál végre egy manővert.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Tallissan Lintra":
text: """Amikor egy ellenséges hajó a %BULLSEYEARC% tűzívedben végrehajt egy támadást, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a védekező 1-gyel több kockával dob.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Darth Maul":
text: """Miután végrehajtasz egy támadást, elkölthetsz 2 %FORCE% jelzőt, hogy végrehajts egy bónusz elsődleges támadást egy másik célpont ellen. Ha az első támadás nem talált, a bónusz támadást végrehajthatod ugyanazon célpont ellen."""
'"Sinker"':
text: """Amikor 1-2-es távolságban és a %LEFTARC% vagy %RIGHTARC% tűzívedben lévő baráti hajó végrehajt egy elsődleges támadást, újradobhat 1 támadókockát."""
"Petty Officer Thanisson":
text: """Az Aktivációs vagy Ütközet fázis közben, miután egy hajó a %FRONTARC% tűzívedben 1-2-es távolságban kap 1 stressz jelzőt, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó kap egy vonósugár jelzőt.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"Captain Cardinal":
text: """Amikor egy baráti hajó 1-2-es távolságban, a tiédnél alacsonyabb kezdeményezéssel védekezik vagy támadást hajt végre, ha van legalább 1 %CHARGE% jelződ, az a hajó újradobhat 1 %FOCUS% eredményét. Miután egy ellenséges hajó 0-3-as távolságban megsemmisül, elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Avenger"':
text: """Miután egy ellenséges hajó 0-3-as távolságban megsemmisül végrehajthatsz egy akciót, akkor is ha stresszes vagy. %LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
'"Recoil"':
text: """Amikor stresszes vagy kezelheted úgy a %FRONTARC% tűzívedben 0-1-es távolságban lévő ellenséges hajókat, mintha a %BULLSEYEARC% tűzívedben lennének.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Omega Squadron Expert":
text: """<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Sienar-Jaemus Engineer":
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"First Order Test Pilot":
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Starkiller Base Pilot":
text: """<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"Lieutenant Tavson":
text: """Miután sérülést szenvedsz el, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy akciót.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Null"':
text: """Amíg nem vagy sérült, kezeld a kezdeményezési értéked 7-esként."""
"Cat":
text: """Amikor elsődleges támadást hajtasz végre, ha a védekező 0-1-es távolságban van legalább 1 baráti eszköztől, dobj 1-gyel több kockával."""
"Ben Teene":
text: """Miután végrehajtasz egy támadást, ha a védekező benne van a %SINGLETURRETARC% tűzívedben, rendeld hozzá a <strong>Rattled</strong> kondíciós kártyát a védekezőhöz."""
"Vennie":
text: """Amikor védkezel, ha a támadó benne van egy baráti hajó %SINGLETURRETARC% tűzívében, hozzáadhatsz 1 %FOCUS% eredményt a dobásodhoz."""
"Edon Kappehl":
text: """Miután teljesen végrehajtasz egy kék vagy fehér manővert, ha még nem dobtál vagy lőttél ki eszközt ebben a körben, kidobhatsz egy eszközt."""
"Resistance Sympathizer":
text: """"""
"Jessika Pava":
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CHARGE% jelzőt vagy a felszerelt %ASTROMECH% fejlesztéseden lévő 1 nem visszatölthető %CHARGE% jelzőt, hogy újradobj 1 kockát minden 0-1-es távolságban lévő baráti hajó után.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Temmin Wexley":
text: """Miután teljesen végrehajtasz egy 2-4 sebességű manővert, végrehajthatsz egy %BOOST% akciót%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Nien Nunb":
text: """Miután kapsz egy stressz jelzőt, ha van ellenséges hajó a %FRONTARC% tűzívedben 0-1 távolságban, leveheted a kapott stressz jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Ello Asty":
text: """Miután felfedtél egy piros Tallon Roll (%TROLLLEFT% vagy %TROLLRIGHT%) manővert, ha 2 vagy kevesebb stressz jelződ van, kezeld a manővert fehérként.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Blue Squadron Recruit":
text: """<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Green Squadron Expert":
text: """<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Foreman Proach":
text: """Mielőtt sorra kerülsz az Ütközet fázisban, választhasz 1 ellenséges hajót a %BULLSEYEARC% tűzívedben 1-2-es távolságban és kapsz 1 'inaktív fegyverzet' jelzőt. Ha így teszel, az a hajó kap 1 vonósugár jelzőt.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Overseer Yushyn":
text: """Mielőtt egy baráti hajó 1-es távolságban kapna 1 'inaktív fegyverzet' jelzőt, ha az a hajó nem stresszes, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó 1 stressz jelzőt kap helyette.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"General Grievous":
text: """Amikor elsődleges támadást hajtasz végre, ha nem vagy a védekező tűzívében, újradobhatod akár 2 támadókockádat is."""
"Wat Tambor":
text: """Amikor elsődleges támadást hajtasz végre, újradobhatsz 1 támadókockát minden kalkuláció tokennel rendelkező baráti hajó után ami a védekezőtől 1-es távolságban van."""
"Captain Sear":
text: """Amikor egy baráti hajó 0-3-as távolságban végrehajt egy elsődleges támadást, ha a védekező benne van annak %BULLSEYEARC% tűzívében, az 'Eredmények semlegesítése' lépés előtt a baráti hajó elkölthet 1 %CALCULATE% jelzőt, hogy semlegesítsen 1 %EVADE% eredményt."""
"Precise Hunter":
text: """Amikor támadást hajtasz végre, ha a védekező benne van a %BULLSEYEARC% tűzívedben, újradobhatsz 1 üres eredményt.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"Haor Chall Prototype":
text: """Miután egy ellenséges hajó a %BULLSEYEARC% tűzívedben 0-2-es távolságban védekezőnek jelöl egy másik baráti hajót, végrehajthatsz egy %CALCULATE% vagy %LOCK% akciót.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"DFS-081":
text: """Amikor egy baráti hajó 0-1 távolságban védekezik, elkölthet 1 %CALCULATE% jelzőt, hogy az összes %CRIT% eredményt %HIT% eredményre változtassa.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"Obi-Wan Kenobi":
text: """Miután egy baráti hajó 0-2-es távolságban elkölt egy %FOCUS% jelzőt, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, az a hajó kap 1 %FOCUS% jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Jedi Knight":
text: """FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Ahsoka Tano":
text: """Miután teljesen végrehajtasz egy manővert, választhatsz egy baráti hajót 0-1-es távolságban és költs el 1 %FORCE% jelzőt. Az a hajó végrehajthat egy akciót még ha stresszes is. %LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Anakin Skywalker":
text: """Miután teljesen végrehajtasz egy manővert, ha van egy ellenséges hajó a %FRONTARC% tűzívedben 0-1 távolságban vagy a %BULLSEYEARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy levegyél 1 stressz jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Barriss Offee":
text: """Amikor egy baráti hajó 0-2-es távolságban támadást hajt végre, ha a védekező benne van annak %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt, hogy átforgass 1 %FOCUS% eredményt %HIT% eredményre vagy 1 %HIT% eredményt %CRIT% eredményre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Luminara Unduli":
text: """Amikor egy baráti hajó 0-2-es távolságban védekezik, ha az nincs a támadó %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, forgass át 1 %CRIT% eredményt %HIT% eredményre vagy 1 %HIT% eredményt %FOCUS% eredményre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Plo Koon":
text: """Az Ütközet fázis elején elkölthetsz 1 %FORCE% jelzőt, hogy válassz egy másik baráti hajót 0-2-es távolságban. Ha így teszel, átadhatsz 1 zöld jelzőt neki vagy átvehetsz egy narancs jelzőt magadra.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Saesee Tiin":
text: """Miután egy baráti hajó 0-2-es távolságban felfedi a tárcsáját elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, állítsd át a tárcsáját egy másik hasonló sebességű és nehézségű manőverre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"Mace Windu":
text: """Miután teljesen végrehajtasz egy piros manővert, tölts vissza 1 %FORCE% jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
'"Kickback"':
text: """Miután végrehajtasz egy %BARRELROLL% akciót, végrehajthatsz egy piros %LOCK% akciót."""
'"Odd Ball"':
text: """Miután teljesen végrehajtasz egy piros manővert vagy piros akciót, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, feltehetsz egy bemérőt arra a hajóra."""
'"Sinker"':
text: """Amikor egy baráti hajó 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben elsődleges támadást hajt végre, újradobhat 1 támadókockát."""
'"Swoop"':
text: """Miután egy baráti kis vagy közepes hajó teljesen végrehajt egy 3-4 sebességű manővert, ha az 0-1-es távolságban van tőled, végrehajthat egy piros %BOOST% akciót."""
'"Axe"':
text: """Miután védekezel vagy támadást hajtasz végre, választhatsz egy baráti hajót 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben. Ha így teszel add át 1 zöld jelződet annak a hajónak."""
'"Tucker"':
text: """Miután egy baráti hajó 1-2-es távolságban végrehajt egy támadást egy ellenséges hajó ellen a %FRONTARC% tűzívedben, végrehajthatsz egy %FOCUS% akciót."""
"Bombardment Drone":
text: """Amikor ledobnál egy eszközt, ki is lőheted, ugyanazt a sablont használva. %LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"Count Dooku":
text: """Miután védekeztél, ha a támadó benne van a tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy levedd egy kék vagy piros jelződ.%LINEBREAK% Miután végrehajtasz egy támadást ami talált, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy akciót."""
"0-66":
text: """Miután védekezel, elkölthetsz 1 %CALCULATE% jelzőt, hogy végrehajts egy akciót."""
"DFS-311":
text: """Az Üzközet fázis elején, átteheted 1 %CALCULATE% jelződet egy másik baráti hajóra 0-3-as távolságban. %LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
'"Odd Ball" (ARC-170)':
text: """Miután teljesen végrehajtasz egy piros manővert vagy piros akciót, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, feltehetsz egy bemérőt arra a hajóra."""
'"Jag"':
text: """Miután egy baráti hajó 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben védekezik, feltehetsz egy bemérőt a támadóra."""
'"Wolffe"':
text: """Amikor végrehajtasz egy elsődleges %FRONTARC% támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 támadókockát. %LINEBREAK% Amikor végrehajtasz egy elsődleges %REARARC% támadást, visszaállíthatsz 1 %CHARGE% jelzőt, hogy 1-gyel több támadókockával dobj"""
upgrade_translations =
"0-0-0":
display_name: """0-0-0"""
text: """<i>Söpredék vagy Darth Vader a csapatban</i>%LINEBREAK%Az Ütközet fázis elején, kiválaszthatsz 1 ellenséges hajót 0-1-es távolságban. Ha így teszel, kapsz egy kalkuláció jelzőt, hacsak a hajó nem választja, hogy kap 1 stressz jelzőt."""
"4-LOM":
display_name: """4-LOM"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, a támadókockák eldobása után, megnevezhetsz egy zöld jelző típust. Ha így teszel, kapsz 2 ion jelzőt és ezen támadás alatt a védekező nem költheti el a megnevezett típusú jelzőt."""
"Andrasta":
display_name: """Andrasta"""
text: """<i>csak Söpredék</i>%LINEBREAK%<i>Kapott akció %RELOAD%</i>%LINEBREAK%Kapsz egy %DEVICE% fejlesztés helyet."""
"Dauntless":
display_name: """Dauntless"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután részlegesen hajtottál végre egy manővert, végrehajthatsz 1 fehér akciót pirosként kezelve."""
"Ghost":
display_name: """Ghost"""
text: """<i>csak Lázadók</i>%LINEBREAK%Bedokkoltathatsz 1 Attack shuttle-t vagy Sheathipede-class shuttle-t. A dokkolt hajót csak a hátsó pöcköktől dokkolhatod ki."""
"Havoc":
display_name: """Havoc"""
text: """<i>csak Söpredék</i>%LINEBREAK%Elveszted a %CREW% fejlesztés helyet. Kapsz egy %SENSOR% és egy %ASTROMECH% fejlesztés helyet."""
"Hound's Tooth":
display_name: """Hound’s Tooth"""
text: """<i>csak Söpredék</i>%LINEBREAK%1 Z-95-AF4 headhunter bedokkolhat."""
"IG-2000":
display_name: """IG-2000"""
text: """<i>csak Söpredék</i>%LINEBREAK%Megkapod minden másik <strong>IG-2000</strong> fejlesztéssel felszerelt baráti hajó pilóraképességét."""
"Marauder":
display_name: """Marauder"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges %REARARC% támadást, újradobhatsz 1 támadókockádat. Kapsz egy %GUNNER% fejlesztés helyet."""
"Millennium Falcon":
display_name: """Millennium Falcon"""
text: """<i>csak Lázadók</i>%LINEBREAK%<i>Kapott akció %EVADE%</i>%LINEBREAK%Amikor védekezel, ha van kitérés jelződ, újradobhatsz 1 védekezőkockát."""
"Mist Hunter":
display_name: """Mist Hunter"""
text: """<i>csak Söpredék</i>%LINEBREAK%<i>Kapott akció %BARRELROLL%</i>%LINEBREAK%Kapsz egy %CANNON% fejlesztés helyet."""
"Moldy Crow":
display_name: """Moldy Crow"""
text: """<i>csak Lázadók vagy Söpredék</i>%LINEBREAK%Kapsz egy %FRONTARC% elsődleges fegyvert 3-as támadóértékkel. A Vége fázis alatt megtarthatsz maximum 2 fókusz jelzőt."""
"Outrider":
display_name: """Outrider"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy támadást ami egy akadály által akadályozott, a védekező 1-gyel kevesebb védekezőkockával dob. Miután teljesen végrehajtasz egy manővert, ha áthaladtál vagy átfedésbe kerültél egy akadállyal, levehetsz 1 piros vagy narancs jelződet."""
"Phantom":
display_name: """Phantom"""
text: """<i>csak Lázadók</i>%LINEBREAK%Be tudsz dokkolni 0-1 távolságból."""
"Punishing One":
display_name: """Punishing One"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %FRONTARC% tűzívedben, dobj 1-gyel több támadókockával. Elveszted a %CREW% fejlesztés helyet. Kapsz egy %ASTROMECH% fejlesztés helyet."""
"ST-321":
display_name: """ST-321"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy %COORDINATE% akciót, kiválaszthatsz egy ellenséges hajót 0-3-as távolságban a koordinált hajótól. Ha így teszel, tegyél fel egy bemérőt arra az ellenséges hajóra figyelmen kívül hagyva a távolság megkötéseket."""
"Shadow Caster":
display_name: """Shadow Caster"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután végrehajtasz egy támadást ami talál, ha a védekező benne van a %SINGLETURRETARC% és %FRONTARC% tűzívedben is, a védekező kap 1 vonósugár jelzőt."""
"Slave I":
display_name: """Slave I"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután felfedtél egy kanyar (%TURNLEFT% vagy %TURNRIGHT%) vagy ív (%BANKLEFT% vagy %BANKRIGHT%) manővert, átforgathatod a tárcsádat az ellenkező irányba megtartva a sebességet és a mozgásformát. Kapsz egy %TORPEDO% fejlesztés helyet."""
"Virago":
display_name: """Virago"""
text: """<i>Kapsz egy %MODIFICATION% fejlesztés helyet. Adj 1 pajzs értéket a hajódhoz.</i>%LINEBREAK%A Vége fázis alatt, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy piros %BOOST% akciót."""
"Ablative Plating":
display_name: """Ablative Plating"""
text: """<i>közepes vagy nagy talp</i>%LINEBREAK%Mielőtt sérülést szenvednél egy akadálytól vagy baráti bomba robbanástól, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, megakadályozol 1 sérülést."""
"Admiral Sloane":
display_name: """Admiral Sloane"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután másik baráti hajó 0-3 távolságban védekezik, ha megsemmisül a támadó kap 2 stressz jelzőt. Amikor egy baráti hajó 0-3 távolságban végrehajt egy támadást egy stresszelt hajó ellen, 1 támadókockát újradobhat."""
"Adv. Proton Torpedoes":
display_name: """Adv. Proton Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong>Támadás (%LOCK%): Költs el 1 %CHARGE% jelzőt. Változtass 1 %HIT% eredményt %CRIT% eredményre."""
"Advanced SLAM":
display_name: """Advanced SLAM"""
text: """<i>Követelmény: %SLAM%</i>%LINEBREAK%Miután végrehajtasz egy %SLAM% akciót, ha teljesen végrehajtod azt a manővert, végrehajthatsz egy fehér akciót az akciósávodról pirosként kezelve."""
"Advanced Sensors":
display_name: """Advanced Sensors"""
text: """Miután felfeded a tárcsádat, végrehajthatsz 1 akciót. Ha így teszel, nem hajthatsz végre másik akciót a saját aktivációdban."""
"Afterburners":
display_name: """Afterburners"""
text: """<i>csak kis hajó</i>%LINEBREAK%Miután teljesen végrehajtasz egy 3-5 sebességű manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BOOST% akciót, még ha stresszes is vagy."""
"Agent Kallus":
display_name: """Agent Kallus"""
text: """<i>csak Birodalom</i>%LINEBREAK%<strong>Felhelyezés:</strong> rendelt hozzá a <strong>Hunted</strong> kondíciót 1 ellenséges hajóhoz. Amikor végrehajtasz egy támadást a <strong>Hunted</strong> kondícióval rendelkező hajó ellen, 1 %FOCUS% eredményed %HIT% eredményre változtathatod."""
"Agile Gunner":
display_name: """Agile Gunner"""
text: """A Vége fázisban elforgathatod a %SINGLETURRETARC% mutatódat."""
"BT-1":
display_name: """BT-1"""
text: """<i>Söpredék vagy Darth Vader a csapatban</i>%LINEBREAK%Amikor végrehajtasz egy támadást, megváltoztathatsz 1 %HIT% eredményt %CRIT% eredményre minden stressz jelző után ami a védekezőnek van."""
"Barrage Rockets":
display_name: """Barrage Rockets"""
text: """<strong>Támadás (%FOCUS%):</strong> Költs el 1 %CHARGE% jelzőt. Ha a védekező benne van a %BULLSEYEARC% tűzívedben, elkölthetsz 1 vagy több %CHARGE% jelzőt, hogy újradobj azzal egyenlő számú támadókockát."""
"Baze Malbus":
display_name: """Baze Malbus"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy %FOCUS% akciót, kezelheted pirosként. Ha így teszel minden egyes 0-1 távolságban lévő ellenséges hajó után kapsz 1 további fókusz jelzőt, de maximum 2 darabot."""
"Bistan":
display_name: """Bistan"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, ha van fókusz jelződ, végrehajthatsz egy bónusz %SINGLETURRETARC% támadást egy olyan hajó ellen, akit még nem támadtál ebben a körben."""
"Boba Fett":
display_name: """Boba Fett"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> tartalékban kezdesz. A Felrakási fázis végén tedd a hajód 0 távolságra egy akadálytól, de 3-as távolságon túl az ellenséges hajóktól."""
"Bomblet Generator":
display_name: """Bomblet Generator"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobd a Bomblet bombát a [1 %STRAIGHT%] sablonnal. Az Aktivációs fázis elején elkölthetsz 1 pajzsot, hogy visszatölts 2 %CHARGE% jelzőt."""
"Bossk":
display_name: """Bossk"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást ami nem talál, ha nem vagy stresszes kapsz 1 stressz jelzőt, hogy végrehajts egy bónusz támadást ugyanazon célpont ellen."""
"C-3PO":
display_name: """C-3PO"""
text: """<i>Kapott akció: %CALCULATE%</i>%LINEBREAK%<i>csak Lázadók</i>%LINEBREAK%Védekezőkocka gurítás előtt, elkölthetsz 1 %CALCULATE% jelzőt hogy hangosan tippelhess egy 1 vagy nagyobb számra. Ha így teszel és pontosan annyi %EVADE% eredményt dobsz, adjál hozzá még 1 %EVADE% eredményt. Miután végrehajtasz a %CALCULATE% akciót, kapsz 1 %CALCULATE% jelzőt."""
"Cad Bane":
display_name: """Cad Bane"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután ledobsz vagy kilősz egy eszközt, végrehajthatsz egy piros %BOOST% akciót."""
"Cassian Andor":
display_name: """Cassian Andor"""
text: """<i>csak Lázadók</i>%LINEBREAK%A Rendszer fázis alatt választhatsz 1 ellenséges hajót 1-2-es távolságban. Tippeld meg hangosan manővere irányát és sebességét, aztán nézd meg a tárcsáját. Ha az iránya és sebessége egyezik a tippeddel, megváltoztathatod a saját tárcsádat egy másik manőverre."""
"Chewbacca":
display_name: """Chewbacca"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis elején elkölthetsz 2 %CHARGE% jelzőt, hogy megjavíts 1 felfordított sérülés kártyát."""
"Chewbacca (Scum)":
display_name: """Chewbacca"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis elején elkölthetsz 1 %FOCUS% jelzőt, hogy megjavíts 1 felfordított sérülés kártyát."""
"Ciena Ree":
display_name: """Ciena Ree"""
text: """<i>Követelmény %COORDINATE% vagy <r>%COORDINATE%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%Miután végrehajtasz egy %COORDINATE% akciót, ha a koordinált hajó végrehajt egy %BARRELROLL% vagy %BOOST% akciót, kaphat 1 stressz jelzőt, hogy elforduljon 90 fokot."""
"Cikatro Vizago":
display_name: """Cikatro Vizago"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis alatt, választhatsz 2 %ILLICIT% fejlesztést ami baráti hajókra van felszerelve 0-1-es távolságban. Ha így teszel, megcserélheted ezeket a fejlesztéseket. A játék végén: tegyél vissza minden %ILLICIT% fejlesztést az eredeti hajójára."""
"Cloaking Device":
display_name: """Cloaking Device"""
text: """<i>kis vagy közepes talp</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy végrehajts egy %CLOAK% akciót. A tervezési fázis elején dobj 1 támadó kockával. %FOCUS% eredmény esetén hozd ki a hajód álcázásból vagy vedd le az álcázás jelzőt."""
"Cluster Missiles":
display_name: """Cluster Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Ezen támadás után végrehajthatod ezt a támadást, mint bónusz támadás egy másik célpont ellen 0-1 távolságra a védekezőtől, figyelmen kívül hagyva a %LOCK% követelményt."""
"Collision Detector":
display_name: """Collision Detector"""
text: """Amikor orsózol vagy gyorsítasz átmozoghatsz vagy rámozoghatsz akadályra. Miután átmozogtál vagy rámozogtál egy akadályra, elkölthetsz 1 %CHARGE% jelzőt, hogy figyelmen kívül hagyhatsd az akadály hatását a kör végéig."""
"Composure":
display_name: """Composure"""
text: """<i>Követelmény <r>%FOCUS%</r> vagy %FOCUS%</i>%LINEBREAK%Ha nem sikerül végrehajtani egy akciót és nincs zöld jelződ, végrehajthatsz egy %FOCUS% akciót."""
"Concussion Missiles":
display_name: """Concussion Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Ha a támadás talált, a védekezőtől 0-1 távolságban lévő minden hajó felfordítja egy sérülés kártyáját."""
"Conner Nets":
display_name: """Conner Nets"""
text: """<strong>Akna</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Conner Net aknát a [1 %STRAIGHT%] sablonnal. Ennak a kártyának a %CHARGE% jelzője <strong>nem</strong> újratölthető."""
"Contraband Cybernetics":
display_name: """Contraband Cybernetics"""
text: """Mielőtt aktiválódnál, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a kör végéig végrehajthatsz akciókat és piros manővereket, még stresszesen is."""
"Crack Shot":
display_name: """Crack Shot"""
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, még az <strong>Eredmények semlegesítése</strong> lépés előtt elkölthetsz 1 %CHARGE% jelzőt hogy hatástalaníts 1 %EVADE% eredményt."""
"Daredevil":
display_name: """Daredevil"""
text: """<i>Követelmény %BOOST%</i>%LINEBREAK%<i>csak kis hajó</i>%LINEBREAK%Amikor végrehajtasz egy fehér %BOOST% akciót, kezelheted pirosként, hogy a [1 %TURNLEFT%] vagy [1 %TURNRIGHT%] sablokokat használhasd."""
"Darth Vader":
display_name: """Darth Vader"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Ütközet fázis elején, válaszhatsz 1 hajót a tűzívedben 0-2-es távolságban és költs el 1 %FORCE% jelzőt. Ha így teszel, az a hajó elszenved 1 %HIT% sérülést, hacsak úgy nem dönt, hogy eldob 1 zöld jelzőt."""
"Deadman's Switch":
display_name: """Deadman’s Switch"""
text: """Miután megsemmisültél, minden hajó 0-1 távolságban elszenved 1 %HIT% sérülést."""
"Death Troopers":
display_name: """Death Troopers"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Aktivációs fázis alatt az ellenséges hajók 0-1-es távolságban nem vehetik le a stressz jelzőjüket."""
"Debris Gambit":
display_name: """Debris Gambit"""
text: """<i>Kapott akció: <r>%EVADE%</r></i>%LINEBREAK%<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor végrehajtasz egy piros %EVADE% akciót, ha van 0-1-es távolságban egy akadály, kezeld az akciót fehérként."""
"Dengar":
display_name: """Dengar"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután védekezel, ha a támadó a tűzívedben van, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, dobj 1 támadókockával, hacsak a támadó úgy nem dönt, hogy eldobja 1 zöld jelzőjét. %HIT% vagy %CRIT% eredmény esetén a támadó elszenved 1 %HIT% sérülést."""
"Director Krennic":
display_name: """Director Krennic"""
text: """<i>Kapott akció %LOCK%</i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%<strong>Felhelyezés:</strong> a hajók felhelyezése előtt, rendeld hozzá az <strong>Optimized Prototype</strong> kondíciót egy másik baráti hajóhoz."""
"Dorsal Turret":
display_name: """Dorsal Turret"""
text: """<i>Kapott akció %ROTATEARC%</i>%LINEBREAK%<strong>Támadás</strong>"""
"Electronic Baffle":
display_name: """Electronic Baffle"""
text: """A Vége fázis alatt, elszenvedhetsz 1 %HIT% sérülést, hogy levegyél 1 piros jelzőt."""
"Elusive":
display_name: """Elusive"""
text: """<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor védekezel, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 védekezőkockát. Miután teljesen végrehajtasz egy piros manővert, visszatölthetsz 1 %CHARGE% jelzőt."""
"Emperor Palpatine":
display_name: """Emperor Palpatine"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor egy másik baráti hajó védekezik vagy végrehajt egy támadást, elkölthetsz 1 %FORCE% jelzőt, hogy módosít annak 1 kockáját úgy, mintha az a hajó költött volna el 1 %FORCE% jelzőt."""
"Engine Upgrade":
display_name: """Engine Upgrade"""
text: """<i>Kapott akció %BOOST%</i>%LINEBREAK%<i>Követelmény <r>%BOOST%</r></i>%LINEBREAK%<i class = flavor_text>Ennek a fejlesztésnek változó a költsége. 3, 6 vagy 9 pont attól függően, hogy kis, közepes vagy nagy talpú hajóra tesszük fel.</i>"""
"Expert Handling":
display_name: """Expert Handling"""
text: """<i>Kapott akció %BARRELROLL%</i>%LINEBREAK%<i>Követelmény <r>%BARRELROLL%</r></i>%LINEBREAK%<i class = flavor_text>Ennek a fejlesztésnek változó a költsége. 2, 4 vagy 6 pont attól függően, hogy kis, közepes vagy nagy talpú hajóra tesszük fel.</i>"""
"Ezra Bridger":
display_name: """Ezra Bridger"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy bónusz %SINGLETURRETARC% támadást egy olyan %SINGLETURRETARC% fegyverrel, amivel még nem támadtál ebben a körben. Ha így teszel és stresszes vagy, újradobhatsz 1 támadókockát."""
"Fearless":
display_name: """Fearless"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy %FRONTARC% elsődleges támadást, ha a támadási távolság 1 és benne vagy a védekező %FRONTARC% tűzívében, megváltoztathatsz 1 eredményedet %HIT% eredményre."""
"Feedback Array":
display_name: """Feedback Array"""
text: """Mielőtt sor kerül rád az Üzközet fázisban, kaphatsz 1 ion jelzőt és 1 'inaktív fegyverzet' jelzőt. Ha így teszel, minden hajó 0-ás távolságban elszenved 1 %HIT% sérülést."""
"Fifth Brother":
display_name: """Fifth Brother"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elkölthetsz 1 %FORCE% jelzőt, hogy megváltoztass 1 %FOCUS% eredményed %CRIT% eredményre."""
"Fire-Control System":
display_name: """Fire-Control System"""
text: """Amikor végrehajtasz egy támadást, ha van bemérőd a védekezőn, újradobhatod 1 támadókockádat. Ha így teszel, nem költheted el a bemérődet ebben a támadásban."""
"Freelance Slicer":
display_name: """Freelance Slicer"""
text: """Amikor védekezel, mielőtt a támadó kockákat eldobnák, elköltheted a támadón lévő bemérődet, hogy dobj 1 támadókockával. Ha így teszel, a támadó kap 1 zavarás jelzőt. Majd %HIT% vagy %CRIT% eredménynél te is kapsz 1 zavarás jelzőt."""
'GNK "Gonk" Droid':
display_name: """GNK “Gonk” Droid"""
text: """<strong>Felhelyezés:</strong> Elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<strong>Akció:</strong> tölts vissza 1 %CHARGE% jelzőt. <strong>Akció:</strong>: költs el 1 %CHARGE% jelzőt, hogy visszatölts egy pajzsot."""
"Grand Inquisitor":
display_name: """Grand Inquisitor"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután egy ellenséges hajó 0-2-es távolságban felfedi a tárcsáját, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts 1 fehér akciót az akciósávodról, pirosként kezelve azt."""
"Grand Moff Tarkin":
display_name: """Grand Moff Tarkin"""
text: """<i>Követelmény %LOCK% vagy <r>%LOCK%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%A Rendszer fázis alatt elkölthetsz 2 %CHARGE% jelzőt. Ha így teszel, minden baráti hajó kap egy bemérőt arra a hajóra, amit te is bemértél."""
"Greedo":
display_name: """Greedo"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy megváltoztass 1 %HIT% eredméynyt %CRIT% eredményre. Amikor védekezel, ha a %CHARGE% jelződ aktív, a támadó megváltoztathat 1 %HIT% eredméynyt %CRIT% eredményre."""
"Han Solo":
display_name: """Han Solo"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis alatt, 7-es kezdeményezésnél, végrehajthatsz egy %SINGLETURRETARC% támadást. Nem támadhatsz újra ezzel a %SINGLETURRETARC% fegyverrel ebben a körben."""
"Han Solo (Scum)":
display_name: """Han Solo"""
text: """<i>csak Söpredék</i>%LINEBREAK%Mielőtt sor kerül rád az Üzközet fázisban, végrehajthatsz egy piros %FOCUS% akciót."""
"Heavy Laser Cannon":
display_name: """Heavy Laser Cannon"""
text: """<strong>Támadás:</strong> a <strong>Támadókockák módosítása</strong> lépés után változtasd az összes %CRIT% eredményt %HIT% eredményre."""
"Heightened Perception":
display_name: """Heightened Perception"""
text: """Az Ütközet fázis elején, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, 7-es kezdeményezéssel kerülsz sorra ebben a fázisban a rendes kezdeményezésed helyett."""
"Hera Syndulla":
display_name: """Hera Syndulla"""
text: """<i>csak Lázadók</i>%LINEBREAK%Stresszesen is végrehajthatsz piros manővert. Miután teljesen végrehajtasz egy piros manővert, ha 3 vagy több stressz jelződ van, vegyél le egy stressz jelzőt és szenvedj el 1 %HIT% sérülést."""
"Homing Missiles":
display_name: """Homing Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Miután kijelölted a védekezőt, a védekező dönthet úgy, hogy elszenved 1 %HIT% sérülést. Ha így tesz, ugorjátok át a <strong>Támadó és védekező kockák</strong> lépést és a támadást találtnak kezeljétek."""
"Hotshot Gunner":
display_name: """Hotshot Gunner"""
text: """Amikor végrehajtasz egy %SINGLETURRETARC% támadást, a <strong>Védekezőkockák módosítása</strong> lépés után a védekező dobja el 1 fókusz vagy kalkuláció jelzőjét."""
"Hull Upgrade":
display_name: """Hull Upgrade"""
text: """Adj 1 szerkezeti értéket a hajódhoz.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 2, 3, 5 vagy 7 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"IG-88D":
display_name: """IG-88D"""
text: """<i>Kapott akció %CALCULATE%</i>%LINEBREAK%<i>csak Söpredék</i>%LINEBREAK%Megkapod minden <strong>IG-2000</strong> fejlesztéssel felszerelt baráti hajó pilóraképességét. Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"ISB Slicer":
display_name: """ISB Slicer"""
text: """<i>csak Birodalom</i>%LINEBREAK%A Vége fázis alatt az ellenséges hajók 1-2-es távban nem vehetik le a zavarás jelzőket."""
"Inertial Dampeners":
display_name: """Inertial Dampeners"""
text: """Mielőtt végrehajtanál egy manővert, elkölthetsz 1 pajzsot. Ha így teszel, hajts végre egy fehér [0 %STOP%] manővert a tárcsázott helyett, aztán kapsz 1 stressz jelzőt."""
"Informant":
display_name: """Informant"""
text: """<strong>Felhelyezés:</strong> a hajók felhelyezése után válassz 1 ellenséges hajót és rendeld hozzá a <strong>Listening Device</strong> kondíciót."""
"Instinctive Aim":
display_name: """Instinctive Aim"""
text: """Amikor végrehajtasz egy speciális támadást, elkölthetsz 1 %FORCE% jelzőt, hogy figyelmen kívül hagyhatsd a %FOCUS% vagy %LOCK% követelményt."""
"Intimidation":
display_name: """Intimidation"""
text: """Amikor egy ellenséges hajó 0-ás távolságban védekezik, 1-gyel kevesebb védekezőkockával dob."""
"Ion Cannon":
display_name: """Ion Cannon"""
text: """<strong>Támadás:</strong> ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Cannon Turret":
display_name: """Ion Cannon Turret"""
text: """<i>Kapott akció %ROTATEARC%</i>%LINEBREAK%<strong>Támadás:</strong> ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Missiles":
display_name: """Ion Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Torpedoes":
display_name: """Ion Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Jabba the Hutt":
display_name: """Jabba the Hutt"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis alatt, kiválaszthatsz 1 baráti hajót 0-2-es távolságban, majd költs el 1 %CHARGE% jelzőt. Ha így teszel, a kiválasztott hajó visszatölthet 1 %CHARGE% jelzőt 1 felszerelt %ILLICIT% fejlesztésén."""
"Jamming Beam":
display_name: """Jamming Beam"""
text: """<strong>Támadás:</strong> ha a támadás talált, minden %HIT%/%CRIT% eredmény után sérülés helyett zavarás jelzőt kap a védekező."""
"Juke":
display_name: """Juke"""
text: """<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor végrehajtasz egy támadást, ha van kitérés jelződ, megváltoztathatod a védekező 1 %EVADE% eredményét %FOCUS% eredményre."""
"Jyn Erso":
display_name: """Jyn Erso"""
text: """<i>csak Lázadók</i>%LINEBREAK%Ha egy baráti hajó 0-3 távolságban fókusz jelzőt kapna, helyette kaphat 1 kitérés jelzőt."""
"Kanan Jarrus":
display_name: """Kanan Jarrus"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután egy baráti hajó 0-2-es távolságban teljesen végrehajt egy fehér manővert, elkölthetsz 1 %FORCE% jelzőt, hogy levegyél róla 1 stressz jelzőt."""
"Ketsu Onyo":
display_name: """Ketsu Onyo"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis elején, kiválaszthatsz 1 ellenséges hajót 0-2-es távolságban a tűzívedben. Ha így teszel, aza a hajó nem veheti le a vonósugár jelzőit."""
"L3-37":
display_name: """L3-37"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> felfordítva szereld fel ezt a kártyát. Amikor védekezel, lefordíthatod ezt a kártyát. Ha így teszel, a támadónak újra kell dobnia az összes támadókockát.%LINEBREAK%<i>L3-37 programja:</i> Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek."""
"Lando Calrissian":
display_name: """Lando Calrissian"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> dobj 2 védekezőkockával. Minden egyes %FOCUS% eredmény után kapsz 1 fókusz jelzőt. Minden egyes %EVADE% eredmény után kapsz 1 kitérés jelzőt. Ha mindkettő eredmény üres, az ellenfeled választ, hogy fókusz vagy kitérés. Kapsz 1, a választásnak megfelelő jelzőt."""
"Lando Calrissian (Scum)":
display_name: """Lando Calrissian"""
text: """<i>csak Söpredék</i>%LINEBREAK%Kockadobás után elkölthetsz 1 zöld jelzőt, hogy újradobj 2 kockádat."""
"Lando's Millennium Falcon":
display_name: """Lando’s Millennium Falcon"""
text: """<i>csak Söpredék</i>%LINEBREAK%1 Escape Craft be lehet dokkolva. Amikor egy Escape Craft be van dokkolva, elköltheted a pajzsait, mintha a te hajódon lenne. Amikor végrehajtasz egy elsődleges támadást stresszelt hajó ellen, dobj 1-gyel több támadókockával."""
"Latts Razzi":
display_name: """Latts Razzi"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor védekezel, ha a támadó stresszelt, levehetsz 1 stressz jelzőt a támadóról, hogy megváltoztass 1 üres/%FOCUS% eredményed %EVADE% eredményre."""
"Leia Organa":
display_name: """Leia Organa"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Aktivációs fázis elején, elkölthetsz 3 %CHARGE% jelzőt. Ezen fázis alatt minden baráti hajó csökkentse a piros manőverei nehézségét."""
"Lone Wolf":
display_name: """Lone Wolf"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha nincs másik baráti hajó 0-2-es távolságban, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 kockádat."""
"Luke Skywalker":
display_name: """Luke Skywalker"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis elején, elkölthetsz 1 %FORCE% jelzőt, hogy forgasd a %SINGLETURRETARC% mutatódat."""
"Magva Yarro":
display_name: """Magva Yarro"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután védekezel, ha a támadás talált, feltehetsz egy bemérőt a támadóra."""
"Marksmanship":
display_name: """Marksmanship"""
text: """Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, megváltoztathatsz 1 %HIT% eredményt %CRIT% eredményre."""
"Maul":
display_name: """Maul"""
text: """<i>Söpredék vagy Ezra Bridger a csapatban</i>%LINEBREAK%Miután sérülést szenvedsz, kaphatsz 1 stressz jelzőt, hogy visszatölts 1 %FORCE% jelzőt. Felszerelhetsz <strong>Dark Side</strong> fejlesztéseket."""
"Minister Tua":
display_name: """Minister Tua"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Ütközet fázis elején, ha sérült vagy, végrehajthatsz egy piros %REINFORCE% akciót."""
"Moff Jerjerrod":
display_name: """Moff Jerjerrod"""
text: """<i>Követelmény: %COORDINATE% vagy <r>%COORDINATE%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%A Rendszer fázis alatt, elkölthetsz 2 %CHARGE% jelzőt. Ha így teszel, válassz a [1 %BANKLEFT%], [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] sablonokból. Minden baráti hajó végrehajthat egy piros %BOOST% akciót a kiválasztott sablonnal."""
"Munitions Failsafe":
display_name: """Munitions Failsafe"""
text: """Amikor végrehajtasz egy %TORPEDO% vagy %MISSILE% támadást, a támadókockák eldobása után, elvetheted az összes kocka eredményed, hogy visszatölts 1 %CHARGE% jelzőt, amit a támadáshoz elköltöttél."""
"Nien Nunb":
display_name: """Nien Nunb"""
text: """<i>csak Lázadók</i>%LINEBREAK%Csökkentsd az íves manőverek [%BANKLEFT% és %BANKRIGHT%] nehézségét."""
"Novice Technician":
display_name: """Novice Technician"""
text: """A kör végén dobhatsz 1 támadó kockával, hogy megjavíts egy felfordított sérülés kártyát. %HIT% eredménynél, fordíts fel egy sérülés kártyát."""
"Os-1 Arsenal Loadout":
display_name: """Os-1 Arsenal Loadout"""
text: """<i>Kapsz egy %TORPEDO% és egy %MISSILE% fejlesztés helyet.</i>%LINEBREAK%Amikor pontosan 1 'inaktív fegyverzet' jelződ van, akkor is végre tudsz hajtani %TORPEDO% és %MISSILE% támadást bemért célpontok ellen. Ha így teszel, nem használhatod el a bemérődet a támadás alatt."""
"Outmaneuver":
display_name: """Outmaneuver"""
text: """Amikor végrehajtasz egy %FRONTARC% támadást, ha nem vagy a védekező tűzívében, a védekező 1-gyel kevesebb védekezőkockával dob."""
"Perceptive Copilot":
display_name: """Perceptive Copilot"""
text: """Miután végrehajtasz egy %FOCUS% akciót, kapsz 1 fókusz jelzőt."""
"Pivot Wing":
display_name: """Pivot Wing"""
text: """<strong>Csukva: </strong>Amikor védekezel, 1-gyel kevesebb védekezőkockával dobsz. Miután végrehajtasz egy [0 %STOP%] manővert, elforgathatod a hajód 90 vagy 180 fokkal. Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK%<strong>Nyitva:</Strong> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Predator":
display_name: """Predator"""
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, újradobhatsz 1 támadókockát."""
"Proton Bombs":
display_name: """Proton Bombs"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy kidobj egy Proton bombát az [1 %STRAIGHT%] sablonnal."""
"Proton Rockets":
display_name: """Proton Rockets"""
text: """<strong>Támadás (%FOCUS%):</strong> költs el 1 %CHARGE% jelzőt."""
"Proton Torpedoes":
display_name: """Proton Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. Változtass 1 %HIT% eredményt %CRIT% eredményre."""
"Proximity Mines":
display_name: """Proximity Mines"""
text: """<strong>Akna</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Proximity aknát az [1 %STRAIGHT%] sablonnal. Ennak a kártyának a %CHARGE% jelzője <strong>nem</strong> újratölthető."""
"Qi'ra":
display_name: """Qi’ra"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor mozogsz vagy támadást hajtasz végre, figyelmen kívül hagyhatod az összes akadályt, amit bemértél."""
"R2 Astromech":
display_name: """R2 Astromech"""
text: """Miután felfeded a tárcsád, elkölthetsz 1 %CHARGE% jelzőt és kapsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts egy pajzsot."""
"R2-D2 (Crew)":
display_name: """R2-D2"""
text: """<i>csak Lázadók</i>%LINEBREAK%A Vége fázis alatt, ha sérült vagy és nincs pajzsod, dobhatsz 1 támadókockával, hogy visszatölts 1 pajzsot. %HIT% eredménynél fordíts fel 1 sérüléskártyát."""
"R2-D2":
display_name: """R2-D2"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután felfeded a tárcsád, elkölthetsz 1 %CHARGE% jelzőt és kapsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts egy pajzsot."""
"R3 Astromech":
display_name: """R3 Astromech"""
text: """Fenntarthatsz 2 bemérőt. Mindegyik bemérő más célponton kell legyen. Miután végrehajtasz egy %LOCK% akciót, feltehetsz egy bemérőt."""
"R4 Astromech":
display_name: """R4 Astromech"""
text: """<i>csak kis hajó</i>%LINEBREAK%Csökkentsd a nehézségét az 1-2 sebességű alapmanővereidnek (%TURNLEFT%, %BANKLEFT%, %STRAIGHT%, %BANKRIGHT%, %TURNRIGHT%)."""
"R5 Astromech":
display_name: """R5 Astromech"""
text: """<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy megjavíts egy lefordított sérülés kártyát.%LINEBREAK%<strong>Akció:</strong> javíts meg 1 felfordított <strong>Ship</strong> sérülés kártyát."""
"R5-D8":
display_name: """R5-D8"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy megjavíts egy lefordított sérülés kártyát.%LINEBREAK%<strong>Akció:</strong> javíts meg 1 felfordított <strong>Ship</strong> sérülés kártyát."""
"R5-P8":
display_name: """R5-P8"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást a %FRONTARC% tűzívedben lévő védekező ellen, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 támadókockát. Ha az újradobott eredmény %CRIT%, szenvedj el 1 %CRIT% sérülést."""
"R5-TK":
display_name: """R5-TK"""
text: """<i>csak Söpredék</i>%LINEBREAK%Végrehajthatsz támadást baráti hajó ellen."""
"Rigged Cargo Chute":
display_name: """Rigged Cargo Chute"""
text: """<i>csak közepes vagy nagy hajó</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt. Dobj ki 1 rakomány jelzőt az [1 %STRAIGHT%] sablonnal."""
"Ruthless":
display_name: """Ruthless"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy támadást, kiválaszthatsz másik baráti hajót 0-1-es távolságra a védekezőtől. Ha így teszel, a kiválasztott hajó elszenved 1 %HIT% sérülést és te megváltoztathatsz 1 kocka eredményed %HIT% eredményre."""
"Sabine Wren":
display_name: """Sabine Wren"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Felhelyezés:</strong> tegyél fel 1 ion, 1 zavarás, 1 stressz és 1 vonósugár jelzőt erre a kártyára. Miután egy hajó sérülést szenved egy baráti bombától, levehetsz 1 ion, 1 zavarás, 1 stressz vagy 1 vonósugár jelzőt erről a kártyáról. Ha így teszel, az a hajó megkapja ezt a jelzőt."""
"Saturation Salvo":
display_name: """Saturation Salvo"""
text: """<i>Követelmény %RELOAD% vagy <r>%RELOAD%</r></i>%LINEBREAK%Amikor végrehajtasz egy %TORPEDO% vagy %MISSILE% támadást, elkölthetsz 1 %CHARGE% jelzőt arról a kártyától. Ha így teszel, válassz 2 védekezőkockát. A védekezőnek újra kell dobnia azokat a kockákat."""
"Saw Gerrera":
display_name: """Saw Gerrera"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elszenvedhetsz 1 %HIT% sérülést, hogy megváltoztasd az összes %FOCUS% eredményed %CRIT% eredményre."""
"Seasoned Navigator":
display_name: """Seasoned Navigator"""
text: """Miután felfedted a tárcsádat, átállíthatod egy másik nem piros manőverre ugyanazon sebességen. Amikor végrehajtod azt a manővert növeld meg a nehézségét."""
"Seismic Charges":
display_name: """Seismic Charges"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Seismic Charge bombát az [1 %STRAIGHT%] sablonnal."""
"Selfless":
display_name: """Selfless"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor másik baráti hajó 0-1-es távolságban védekezik, az <strong>Eredmények semlegesítése</strong> lépés előtt, ha benne vagy a támadási tűzívben, elszenvedhetsz 1 %CRIT% sérülést, hogy semlegesíts 1 %CRIT% eredményt."""
"Sense":
display_name: """Sense"""
text: """A Rendszer fázis alatt kiválaszthatsz 1 hajót 0-1-es távolságban és megnézheted a tárcsáját. Ha elköltesz 1 %FORCE% jelzőt választhatsz 0-3-as távolságból hajót."""
"Servomotor S-Foils":
display_name: """Servomotor S-foils"""
text: """<strong>Csukva: </strong><i>Kapott akciók: %BOOST% , %FOCUS% <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> <r>%BOOST%</r></i>%LINEBREAK% Amikor végrehajtasz egy elsődleges támadást, 1-gyel kevesebb támadókockával dobj.%LINEBREAK%Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK%<strong>Nyitva:</strong> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Seventh Sister":
display_name: """Seventh Sister"""
text: """<i>csak Birodalom</i>%LINEBREAK%Ha egy ellenséges hajó 0-1-es távolságra egy stressz jelzőt kapna, elkölthetsz 1 %FORCE% jelzőt, hogy 1 zavarás vagy vonósugár jelzőt kapjon helyette."""
"Shield Upgrade":
display_name: """Shield Upgrade"""
text: """Adj 1 pajzs értéket a hajódhoz.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 3, 4, 6 vagy 8 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"Skilled Bombardier":
display_name: """Skilled Bombardier"""
text: """Ha ledobsz vagy kilősz egy eszközt, megegyező irányban használhatsz 1-gyel nagyob vagy kisebb sablont."""
"Squad Leader":
display_name: """Squad Leader"""
text: """<i>Kapott akció <r>%COORDINATE%</r></i>%LINEBREAK%WAmikor koordinálsz, a kiválasztott hajó csak olyan akciót hajthat végre, ami a te akciósávodon is rajta van."""
"Static Discharge Vanes":
display_name: """Static Discharge Vanes"""
text: """Mielőtt kapnál 1 ion vagy zavarás jelzőt, ha nem vagy stresszes, választhatsz egy másik hajót 0-1-es távolságban és kapsz 1 stressz jelzőt. Ha így teszel, a kiválasztott hajó kapja meg az ion vagy zavarás jelzőt helyetted."""
"Stealth Device":
display_name: """Stealth Device"""
text: """Amikor védekezel, ha a %CHARGE% jelződ aktív, dobj 1-gyel több védekezőkockával. Miután elszenvedsz egy sérülés, elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 3, 4, 6 vagy 8 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"Supernatural Reflexes":
display_name: """Supernatural Reflexes"""
text: """<i>csak kis hajó</i>%LINEBREAK%Mielőtt aktiválódsz, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BARRELROLL% vagy %BOOST% akciót. Ha olyan akciót hajtottál végre, ami nincs az akciósávodon, elszenvedsz 1 %HIT% sérülést."""
"Swarm Tactics":
display_name: """Swarm Tactics"""
text: """Az ütközet fázis elején, kiválaszthatsz 1 baráti hajót 1-es távolságban. Ha így teszel, az a hajó a kör végéig kezelje úgy a kezdeményezés értékét, mintha egyenlő lenne a tiéddel."""
"Tactical Officer":
display_name: """Tactical Officer"""
text: """<i>Kapott akció: %COORDINATE%</i>%LINEBREAK%<i>Követelmény: <r>%COORDINATE%</r></i>"""
"Tactical Scrambler":
display_name: """Tactical Scrambler"""
text: """<i>csak közepes vagy nagy hajó</i>%LINEBREAK%Amikor akadályozod egy ellenséges hajó támadását, a védekező 1-gyel több védekezőkockával dob."""
"Tobias Beckett":
display_name: """Tobias Beckett"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> a hajók felhelyezése után, kiválaszthatsz 1 akadályt a pályáról. Ha így teszel, helyezd át bárhová 2-es távolságra a szélektől vagy hajóktól és 1-es távolságra más akadályoktól."""
"Tractor Beam":
display_name: """Tractor Beam"""
text: """<strong>Támadás:</strong> ha a támadás talált, minden %HIT%/%CRIT% eredmény után sérülés helyett vonósugár jelzőt kap a védekező."""
"Trajectory Simulator":
display_name: """Trajectory Simulator"""
text: """A Rendszer fázis alatt, ha ledobsz vagy kilősz egy bombát, kilőheted a [5 %STRAIGHT%] sablonnal."""
"Trick Shot":
display_name: """Trick Shot"""
text: """Amikor végrehajtasz egy támadást ami akadályozott egy akadály által, dobj 1-gyel több támadókockával."""
"Unkar Plutt":
display_name: """Unkar Plutt"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután részlegesen végrehajtasz egy manővert, elszenvedhetsz 1 %HIT% sérülést, hogy végrehajts 1 fehér akciót."""
"Veteran Tail Gunner":
display_name: """Veteran Tail Gunner"""
text: """<i>Követelmény: %REARARC%</i> %LINEBREAK%Miután végrehajtasz egy elsődleges %FRONTARC% támadást, végrehajthatsz egy bónusz elsődleges %REARARC% támadást."""
"Veteran Turret Gunner":
display_name: """Veteran Turret Gunner"""
text: """<i>Követelmény: %ROTATEARC% vagy <r>%ROTATEARC%</r></i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, végrehajthatsz egy bónusz %SINGLETURRETARC% támadást egy olyan %SINGLETURRETARC% tűzívben, amiből még nem támadtál ebben a körben."""
"Xg-1 Assault Configuration":
display_name: """Xg-1 Assault Configuration"""
text: """Amikor pontosan 1 'inaktív fegyverzet' jelződ van, akkor is végrehajthatsz %CANNON% támadást. Amikor %CANNON% támadást hajtasz végre 'inaktív fegyverzet' jelzővel, maximum 3 támadókockával dobhatsz.%LINEBREAK%Kapsz egy %CANNON% fejlesztés helyet."""
"Zuckuss":
display_name: """Zuckuss"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, ha nem vagy stresszes, válaszhatsz 1 védekezőkockát és kapsz 1 stressz jelzőt. Ha így teszel, a védekezőnek újra kell dobnia azt a kockát."""
'"Chopper" (Crew)':
display_name: """“Chopper”"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az <strong>Akció végrehajtása</strong> lépés közben még stresszesen is végrehajthatsz 1 akciót. Miután stresszesen végrehajtasz egy akciót szenvedj el 1 %HIT% sérülést vagy fordítsd fel 1 sérülés kártyád."""
'"Chopper" (Astromech)':
display_name: """“Chopper”"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 nem-újratölthető %CHARGE% jelzőt egy másik felszerelt fejlesztésről, hogy visszatölts 1 pajzsot%LINEBREAK%<strong>Akció:</strong> költs el 2 pajzsot, hogy visszatölts 1 nem-újratölthető %CHARGE% jelzőt egy felszerelt fejlesztésen."""
'"Genius"':
display_name: """“Genius”"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután teljesen végrehajtasz egy manővert, ha még nem dobtál vagy lőttél ki eszközt ebben a körben, kidobhatsz 1 bombát."""
'"Zeb" Orrelios':
display_name: """“Zeb” Orrelios"""
text: """<i>csak Lázadók</i>%LINEBREAK%Végrehajthatsz elsődleges támadást 0-ás távolságban. Az ellenséges hajók 0-ás távolságban végrehajthatnak elsődleges támadást ellened."""
"Hardpoint: Cannon":
text: """Kapsz egy %CANNON% fejlesztés helyet."""
"Hardpoint: Missile":
text: """Kapsz egy %MISSILE% fejlesztés helyet."""
"Hardpoint: Torpedo":
text: """Kapsz egy %TORPEDO% fejlesztés helyet."""
"Black One":
text: """<i>Kapott akció: %SLAM%</i> %LINEBREAK% Miután végrehajtasz egy %SLAM% akciót, elvesztesz 1 %CHARGE% jelzőt. Ezután kaphatsz 1 ion jelzőt, hogy levedd az inaktív fegyverzet jelzőt. Ha a %CHARGE% nem aktív, nem hajthatsz végre %SLAM% akciót."""
"Heroic":
text: """<i>csak Ellenállás</i><br>Amikor védekezel vagy támadást hajtasz végre, ha 2 vagy több csak üres eredményed van, újradobhatsz akárhány kockát."""
"Rose Tico":
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz egy dobás eredményed, hogy bemérőt rakj az ellenséges hajóra."""
"Finn":
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre,ha az ellenséges hajó a %FRONTARC% tűzívedben van, hozzáadhatsz 1 üres eredményt a dobásodhoz (ez a kocka újradobható vagy módosítható)."""
"Integrated S-Foils":
text: """<strong>Csukva: </strong><i>Kapott akció %BARRELROLL%, %FOCUS% <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> <r>%BARRELROLL%</r></i>%LINEBREAK% Amikor végrehajtasz egy elsődleges támadást, ha a védekező nincs a %BULLSEYEARC% tűzívedben, 1-gyel kevesebb támadókockával dobj. Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK% <b>Nyitva:</b> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Targeting Synchronizer":
text: """<i>Követelmény: %LOCK%</i> %LINEBREAK% Amikor egy baráti hajó 1-2-es távolságban végrehajt egy támadást olyan célpont ellen, amit már bemértél, az a hajó figyelmen kívül hagyhatja a %LOCK% támadási követelményt."""
"Primed Thrusters":
text: """<i>csak kis hajó</i> %LINEBREAK%Amikor 2 vagy kevesebb stressz jelződ van, végrehajthatsz %BARRELROLL% és %BOOST% akciót még ha stresszes is vagy."""
"Kylo Ren":
text: """<strong>Akció: </strong> Válassz 1 ellenséges hajót 1-3-as távolságban. Ha így teszel, költs el 1 %FORCE% jelzőt, hogy hozzárendeled az <strong>I'll Show You the Dark Side</strong> kondíciós kártyát a kiválasztott hajóhoz."""
"General Hux":
text: """Amikor végrehajtasz egy fehér %COORDINATE% akciót, kezelheted pirosként. Ha így teszel, koordinálhatsz további 2 azonos típusú hajót, mindegyikét azonos akcióval és pirosként kezelve."""
"Fanatical":
text: """Amikor végrehajtasz egy elsődleges támadást, ha nincs pajzsod, megváltoztathatsz 1 %FOCUS% eredményt %HIT% eredményre."""
"Special Forces Gunner":
text: """Amikor végrehajtasz egy elsődleges %FRONTARC% támadást, ha a %SINGLETURRETARC% tűzíved a %FRONTARC% tűzívedben van, 1-gyel több kockával dobhatsz. Miután végrehajtasz egy elsődleges %FRONTARC% támadást, ha a %SINGLETURRETARC% tűzíved a %REARARC% tűzívedben van, végrehajthatsz egy bónusz elsődleges %SINGLETURRETARC% támadást."""
"Captain Phasma":
text: """Az Ütközet fázis végén, minden 0-1 távolságban lévő ellenséges hajó ami nem stresszes, kap 1 stressz jelzőt."""
"Supreme Leader Snoke":
text: """A Rendszer fázis alatt kiválaszthatsz bármennyi hajót 1-es távolságon túl. Ha így teszel költs el annyi %FORCE% jelzőt, amennyi hajót kiválasztottál, hogy felfordítsd a tárcsájukat."""
"Hyperspace Tracking Data":
text: """<strong>Felhelyezés:</strong> a hajó felhelyezés előtt válassz egy számot 0 és 6 között. Kezeld a Initiative-od a kiválasztott számnak megfelelően. A felhelyezés után rendelj hozzá 1 %FOCUS% vagy %EVADE% jelzőt minden baráti hajóra 0-2-es távolságban."""
"Advanced Optics":
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %FOCUS% jelzőt, hogy 1 üres eredményed %HIT% eredményre változtass."""
"Rey":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy 1 üres eredményed %EVADE% vagy %HIT% eredményre változtass."""
"Chewbacca (Resistance)":
text: """<strong>Felhelyezés:</strong>: elvesztesz el 1 %CHARGE% jelzőt. %LINEBREAK% Miután egy baráti hajó 0-3-as távolságban felhúz 1 sérülés kártyát, állítsd helyre 1 %CHARGE% jelzőt. Amikor támadást hajtasz végre elkölthetsz 2 %CHARGE% jelzőt, hogy 1 %FOCUS% eredményed %CRIT% eredményre változtass."""
"Paige Tico":
text: """Miután véggrehajtasz egy elsődleges támadást, ledobhatsz egy bombát vagy forgathatod a %SINGLETURRETARC% tűzívedet. Miután megsemmisültél ledobhatsz 1 bombát."""
"R2-HA":
text: """Amikor védekezel, elköltheted a támadón lévő bemérődet, hogy újradobd bármennyi védőkockádat."""
"C-3PO (Resistance)":
text: """ <i>Kapott akció: %CALCULATE% <r>%COORDINATE%</r></i> %LINEBREAK% Amikor koordinálsz, választhatsz baráti hajót 2-es távolságon túl, ha annak van %CALCULATE% akciója. Miután végrehajtod a %CALCULATE% vagy %COORDINATE% akciót, kapsz 1 %CALCULATE% jelzőt."""
"Han Solo (Resistance)":
text: """ <i>Kapott akció: <r>%EVADE%</r></i> %LINEBREAK%Miután végrehajtasz egy %EVADE% akciót, annyival több %EVADE% jelzőt kapsz, ahány ellenséges hajó van 0-1-es távolságban."""
"Rey's Millennium Falcon":
text: """Ha 2 vagy kevesebb stressz jelződ van, végrehajthatsz piros Segnor Csavar manővert [%SLOOPLEFT% vagy %SLOOPRIGHT%] és végrehajthatsz %BOOST% és %ROTATEARC% akciókat, még ha stresszes is vagy."""
"Petty Officer Thanisson":
text: """Az Aktivációs vagy Ütközet fázis közben, miután egy ellenséges hajó a %FRONTARC% tűzívedben 0-1-es távolságban kap egy piros vagy narancs jelzőt, ha nem vagy stresszes, kaphatsz egy stressz jelzőt. Ha így teszel, az a hajó kap még egy jelzőt abból, amit kapott."""
"BB-8":
text: """Mielőtt végrehajtasz egy kék manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BARRELROLL% vagy %BOOST% akciót."""
"BB Astromech":
text: """Mielőtt végrehajtasz egy kék manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BARRELROLL% akciót."""
"M9-G8":
text: """Amikor egy hajó amit bemértél végrehajt egy támadást, kiválaszthatsz egy támadókockát. Ha így teszel, a támadó újradobja azt a kockát."""
"Ferrosphere Paint":
text: """Miután egy ellenséges hajó bemért téged, ha nem vagy annak a hajónak a %BULLSEYEARC% tűzívében, az kap egy stressz jelzőt."""
"Brilliant Evasion":
text: """Amikor védekezel, ha nem vagy a támadó %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt, hogy 2 %FOCUS% eredményed %EVADE% eredményre változtass."""
"Calibrated Laser Targeting":
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, adj a dobásodhoz 1 %FOCUS% eredményt."""
"Delta-7B":
text: """ <i>Kapott : 1 támadási érték, 2 pajzs %LINEBREAK% Elveszett: 1 védekezés</i> """
"Biohexacrypt Codes":
text: """Amikor koordinálsz vagy zavarsz, ha van bemérőd egy hajón, elköltheted azt a bemérőt, hogy a távolság követelményeket figyelmen kívül hagyd a hajó kiválasztákor."""
"Predictive Shot":
text: """Miután támadásra jelölsz egy célpontot, ha a védekező benne van a %BULLSEYEARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a védekező a <strong>Védekezőkockák dobása</strong> lépésben nem dobhat több kockával, mint a %HIT%/%CRIT% eredményeid száma."""
"Hate":
text: """Miután elszenvedsz 1 vagy több sérülést, feltölthetsz ugyanannyi %FORCE% jelzőt."""
"R5-X3":
text: """Mielőtt aktiválódsz vagy rád kerül a sor az Ütközet fázisban, elkölthetsz 1 %CHARGE% jelzőt, hogy figyelmen kívül hagyd az akadályokat annak a fázisnak a végéig."""
"Pattern Analyzer":
text: """Amikor teljesen végrehajtasz egy piros manővert, a <strong>Nehézség ellenőrzése</strong> lépés előtt végrehjathatsz 1 akciót."""
"Impervium Plating":
text: """Mielőtt egy felfordított <b>Ship</b> sérüléskártyát kapnál, elkölthetsz 1 %CHARGE% jelzőt, hogy eldobd."""
"Grappling Struts":
text: """<strong>Csukva: </strong> Felhelyezés: ezzel az oldalával helyezd fel. %LINEBREAK% Amikor végrehajtasz egy manővert, ha átfedésbe kerülsz egy aszteroidával vagy űrszeméttel és 1 vagy kevesebb másik baráti hajó van 0-ás távolságra attól az akadálytól, megfordíthatod ezt a kártyát.
%LINEBREAK% <b>Nyitva:</b> Hagyd figyelment kívül a 0-ás távolságnban lévő akadályokat amíg átmozogsz rajtuk. Miután felfeded a tárcsádat, ha más manővert fedtél fel mint [2 %STRAIGHT%] és 0-ás távolságra vagy egy aszteroidától vagy űrszeméttől, ugord át a 'Manőver végrehajtása' lépést és vegyél le 1 stresst jelzőt; ha jobb vagy bal manővert fedtél fel, forgasd a hajódat 90 fokkal abba az irányba. Miután végrehajtasz egy manővert fordítsd át ezt a kártyát."""
"Energy-Shell Charges":
text: """ <strong>Támadás (%CALCULATE%):</strong> Költs el 1 %CHARGE% jelzőt. Amikor végrehajtasz egy támadást, elkölthetsz 1 %CALCULATE% jelzőt, hogy megváltoztass 1 %FOCUS% eredményt %CRIT% eredményre.%LINEBREAK% <strong>Akció:</strong> Töltsd újra ezt a kártyát."""
"Dedicated":
text: """Amikor egy másik baráti hajó a %LEFTARC% vagy a %RIGHTARC% tűzívedben 0-2-es távolságban védekezik, ha az limitált vagy Dedicated fejlesztéssel felszerelt és nem vagy túlterhelve, kaphatsz 1 túlterhelés jelzőt. Ha így teszel a védekező újradobhatja 1 üres eredményét."""
"Synchronized Console":
text: """Miután végrehajtasz egy támadást, választhatsz egy baráti hajót 1-es távolságban vagy egy baráti hajót 'Synchronized Console' fejlesztéssel 1-3 távolságban és költsd el a védekezőn lévő bemérődet. Ha így teszel, a kiválasztott baráti hajó kaphat egy bemérőt a védekezőre."""
"Battle Meditation":
text: """Nem koordinálhatsz limitált hajót.%LINEBREAK%Amikor végrehajtasz egy lila %COORDINATE% akciót, koordinálhatsz 1 további ugyanolyan típusú nem limitált baráti hajót. Mindkét hajónak ugyanazt az akciót kell végrehajtania."""
"R4-P Astromech":
text: """Mielőtt végrehajtasz egy alapmanővert, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a manőver végrehajtása közben csökkentsd annak nehézségét."""
"R4-P17":
text: """Miután teljesen végrehajtasz egy piros manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy akciót, még ha stresses is vagy."""
"Spare Parts Canisters":
text: """Akció: költs el 1 %CHARGE% jelzőt, hogy visszatölts 1 %CHARGE% jelzőt egy felszerelt %ASTROMECH% fejlesztéseden.%LINEBREAK%
Akció: költs el 1 %CHARGE% jelzőt, hogy kidobj 1 tartalék alkatrész jelzőt, aztán vegyél le minden rajtad lévő bemérőt."""
"Scimitar":
text: """Felhelyezés: a hajók felhelyezése After the Place Forces step, you may cloak. %LINEBREAK% After you decloak, you may choose an enemy ship in your %BULLSEYEARC%. If you do, it gains 1 jam token."""
"Chancellor Palpatine":
text: """<strong>Felhelyezés:</strong> Ezzel az oldalával szereld fel.%LINEBREAK% Miután védekeztél, ha a támadó 0-2-es távolságban van, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a támadó kap egy stressz jelzőt.%LINEBREAK% A vége fázisban megfordíthatod ezt a kártyát.%LINEBREAK% <strong>Darth Sidious:</strong> Miután végrehajtasz egy lila %COORDINATE% akciót, a koordinált hajó kap 1 stressz jelzőt, majd kap 1 %FOCUS% jelzőt vagy visszatölt 1 %FORCE% jelzőt."""
"Count Dooku":
text: """Mielőtt egy hajó 0-2-es távolságban támadó vagy védekező kockákat gurít, ha minden %FORCE% jelződ aktív, elkölthetsz 1 %FORCE% jelzőt, hogy megnevezz egy eredményt. Ha a dobás nem tartalmazza megnevezett eredményt, a hajónak meg kell változtatni 1 kockáját arra az eredményre."""
"General Grievous":
text: """Amikor védekezel, az 'Eredmények semlegesítése' lépés után, ha 2 vagy több %HIT%/%CRIT% eredmény van, elkölthetsz 1 %CHARGE% jelzőt, hogy semlegesíts 1 %HIT% vagy %CRIT% eredményt.%LINEBREAK%Miután egy baráti hajó megsemmisül, tölts vissza 1 %CHARGE% jelzőt."""
"K2-B4":
text: """Amikor egy baráti hajó 0-3-as távolságban védekezik, elkölthet 1 %CALCULATE% jelzőt. Ha így tesz, adjon 1 %EVADE% eredményt a dobásához, hacsak a támadó nem tönt úgy, hogy kap 1 túlterhelés jelzőt."""
"DRK-1 Probe Droids":
text: """A Vége fázis alatt elkölthetsz 1 %CHARGE% jelzőt, hogy kidobj vagy kilőj 1 DRK-1 kutaszdroidot egy 3-as sebességű sablon segítségével.%LINEBREAK%E a kártya %CHARGE% jelzője nem visszatölthető."""
"Kraken":
text: """A Vége fázis alatt kiválaszthatsz akár 3 baráti hajót 0-3-as távolságban. Ha így teszel, ezen hajók nem dobják el 1 %CALCULATE% jelzőjüket."""
"TV-94":
text: """Amikor egy baráti hajó 0-3-as távolságban végrehajt egy elsődleges támadást egy a %BULLSEYEARC% tűzívében lévő védekező ellen, ha 2 vagy kevesebb a támadó kockák száma, elkölthet 1 %CALCULATE% jelzőt, hogy hozzáadjon a dobásához 1 %HIT% eredményt."""
"Discord Missiles":
text: """Az Ütközet fázis elején elkölthetsz 1 %CALCULATE% jelzőt és 1 %CHARGE% jelzőt, hogy kilőj 1 'buzz droid swarm' jelzőt a [3 %BANKLEFT%], [3 %STRAIGHT%] vagy [3 %BANKRIGHT%] használatával. Ennek a kártyának a %CHARGE% jelzője nem tölthető újra."""
"Clone Commander Cody":
text: """Miután végrehajtasz egy támadást ami nem talált, ha 1 vagy több %HIT%/%CRIT% eredményt lett semlegesítve, a védekező kap 1 túlterhelés jelzőt."""
"Seventh Fleet Gunner":
text: """Amikor egy másik baráti hajó végrehajt egy elsődleges támadást, ha a védekező a tűzívedben van, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel a támadó 1-gyel több kockával dob, de maximum 4-gyel. A rendszer fázisban kaphatsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts 1 %CHARGE% jelzőt."""
"R4-P44":
text: """Miután teljesen véggrehajtasz egy piros manővert, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, kapsz 1 %CALCULATE% jelzőt."""
"Treacherous":
text: """Amikor védekezel, kiválaszthatsz egy a támadást akadályozó hajót és költs el 1 %CHARGE% jelzőt. Ha így teszel, semlegesíts 1 %HIT% vagy %CRIT% eredményt és a kiválasztott hajó kap egy túlterhelés jelzőt. Ha egy hajó 0-3-as távolságban megsemmisül, tölts vissza 1 %CHARGE% jelzőt."""
"Soulless One":
text: """Amikor védekezel, ha a támadó a tűzíveden kívül van újradobhatsz 1 védekezőkockát."""
condition_translations =
'Suppressive Fire':
text: '''Amikor végrehajtasz egy támadást más hajó ellen mint <strong>Captain Rex</strong>, dobj 1-gyel kevesebb kockával.%LINEBREAK% Miután <strong>Captain Rex</strong> védekezik, vedd le ezt a kártyát. %LINEBREAK% Az Ütközet fázis végén, ha <strong>Captain Rex</strong> nem hajtott végre támadást ebben a fázisban, vedd le ezt a kártyát. %LINEBREAK% Miután <strong>Captain Rex</strong> megsemmisült, vedd le ezt a kártyát.'''
'Hunted':
text: '''Miután megsemmisültél, választanod kell egy baráti hajót és átadni neki ezt a kondíció kártyát.'''
'Listening Device':
text: '''A Rendszer fázisban, ha egy ellenséges hajó az <strong>Informant</strong> fejlesztéssel 0-2-es távolságban van, fedd fel a tárcsád.'''
'Rattled':
text: '''Miután egy bomba vagy akna 0-1-es távolságban felrobban, elszenvedsz 1 %CRIT% sérülést. Aztán vedd le ezt a kártyát.%LINEBREAK%<strong>Akció:</strong> Ha nincs bomba vagy akna 0-1-es távolságban, vedd ele ezt a kártyát.'''
'Optimized Prototype':
text: '''Amikor végrehajtasz egy elsődleges %FRONTARC% támadást egy olyan hajó ellen, amit bemért <strong>Director Krennic</strong> fejlesztéssel felszerelt hajó, elkölthetsz 1 %HIT%/%CRIT%/%FOCUS% eredményt. Ha így teszel, választhatsz, hogy a védekező elveszt 1 pajzsot vagy a védekező felfordítja 1 sérüléskártyáját.'''
'''I'll Show You the Dark Side''':
text: '''Mikor ezt a kártyát hozzárendelik egy hajódhoz, ha nincs felfordított sérüléskártya rajta, az ellenfél kikeres a sérüléskártyáidból egy pilóta típusút és felfordítva ráteszi. Aztán megkeveri a paklit. Amikor elszenvednél 1 %CRIT% sérülést, ezen a kártyán lévő sérüléskártyát kapod meg. Aztán vedd le ezt a lapot.'''
'Proton Bomb':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, minden hajó és távérzékelő 0–1-es távolságban elszenved 1 %CRIT% sérülést.'''
'Seismic Charge':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, válassz 1 akadály 0–1-es távolságban. Minden hajó és távérzékelő 0–1-es távolságra az akadálytól elszenved 1 %HIT% sérülést.'''
'Bomblet':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, minden hajó 0–1-es távolságban dob 2 támadókockával. Minden hajó és távérzékelő elszenved 1 %HIT% sérülést minden egyes %HIT%/%CRIT% eredmény után.'''
'Loose Cargo':
text: '''(Űrszemét jelző) - A kidobott rakomány űrszemétnek számít.'''
'Conner Net':
text: '''(Akna jelző) - Miután egy hajó átmozog vagy átfedésbe kerül ezzel az eszközzel, az felrobban. Amikor ez az eszköz felrobban, a hajó elszenved 1 %HIT% sérülést és kap 3 ion jelzőt.'''
'Proximity Mine':
text: '''(Akna jelző) - Miután egy hajó átmozog vagy átfedésbe kerül ezzel az eszközzel, az felrobban. Amikor ez az eszköz felrobban, a hajó dob 2 támadókockával, aztán elszenved 1 %HIT%, valamint a dobott eremény szerint 1-1 %HIT%/%CRIT% sérülést.'''
'DRK-1 Probe Droid':
text: '''INIT: 0 / MOZGÉKONYSÁG: 3 / HULL: 1 / (távérzékelő)%LINEBREAK%Amikor egy baráti hajó bemér egy objektumot vagy zavar egy ellenséges hajót, mérheti a távolságot tőled. Miután egy ellenséges hajó átfedésbe kerül veled, az dob egy támadókockával. %FOCUS% eredménynél elszenvedsz 1 %HIT% sérülést.%LINEBREAK%Rendszer fázis: a kezdeményezésednek megfelelően arrébb mozgathatod a [2 %BANKLEFT%], [2 %STRAIGHT%] vagy [2 %BANKRIGHT%] sablonnal.'''
'Buzz Droid Swarm':
text: '''INIT: 0 / MOZGÉKONYSÁG: 3 / HULL: 1 / (távérzékelő)%LINEBREAK%Miután egy ellenséges hajó átmozog rajtad vagy átfedésbe kerül veled, átteheted annak első vagy hátsó pöckeihez (ilyenkor 0-ás távolságra vagy a hajótól). Nem lehetsz átfedésbe egy objektummal sem ily módon. Ha nem tudod elhelyezni a pöckökhöz, te és a hajó is elszenvedtek 1 %HIT% sérülést.%LINEBREAK%Ütközet fázis: a kezdeményezésednek megfelelően minden 0-ás távolságba nlévő hajó elszenved 1 %CRIT% sérülést.'''
exportObj.setupTranslationCardData pilot_translations, upgrade_translations, condition_translations
| 178828 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.hu = 'Magyar'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Magyar =
slot:
"Astromech": "Astromech"
"Force": "Erő"
"Bomb": "Bomba"
"Cannon": "Ágyú"
"Crew": "Személyzet"
"Missile": "Rakéta"
"Sensor": "Szenzor"
"Torpedo": "Torpedó"
"Turret": "Lövegtorony"
"Hardpoint": "Fegyverfelfüggesztés"
"Illicit": "Tiltott"
"Configuration": "Konfiguráció"
"Talent": "Talentum"
"Modification": "Módosítás"
"Gunner": "Fegyverzet kezelő"
"Device": "Eszköz"
"Tech": "Tech"
"Title": "Nevesítés"
sources: # needed?
"Second Edition Core Set": "Second Edition Core Set"
"Rebel Alliance Conversion Kit": "Rebel Alliance Conversion Kit"
"Galactic Empire Conversion Kit": "Galactic Empire Conversion Kit"
"Scum and Villainy Conversion Kit": "Scum and Villainy Conversion Kit"
"T-65 X-Wing Expansion Pack": "T-65 X-Wing Expansion Pack"
"BTL-A4 Y-Wing Expansion Pack": "BTL-A4 Y-Wing Expansion Pack"
"TIE/ln Fighter Expansion Pack": "TIE/ln Fighter Expansion Pack"
"TIE Advanced x1 Expansion Pack": "TIE Advanced x1 Expansion Pack"
"Slave 1 Expansion Pack": "Slave 1 Expansion Pack"
"Fang Fighter Expansion Pack": "Fang Fighter Expansion Pack"
"Lando's Millennium Falcon Expansion Pack": "Lando's Millennium Falcon Expansion Pack"
"Saw's Renegades Expansion Pack": "Saw's Renegades Expansion Pack"
"TIE Reaper Expansion Pack": "TIE Reaper Expansion Pack"
ui:
shipSelectorPlaceholder: "Válassz egy hajót"
pilotSelectorPlaceholder: "Válassz egy pilótát"
upgradePlaceholder: (translator, language, slot) ->
"Nincs #{translator language, 'slot', slot} fejlesztés"
modificationPlaceholder: "Nincs módosítás"
titlePlaceholder: "Nincs nevesítés"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'slot', slot} fejlesztés"
unreleased: "kiadatlan"
epic: "epikus"
limited: "korlátozott"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'Ez a raj kiadatlan tartalmat használ!'
'.loading-failed-container .translated': 'It appears that you followed a broken link. No squad could be loaded!'
'.collection-invalid .translated': 'Ez a lista nem vihető pályára a készletedből!'
'.ship-number-invalid-container .translated': 'A tournament legal squad must contain 2-8 ships!'
# Type selector
'.game-type-selector option[value="standard"]': 'Kiterjesztett'
'.game-type-selector option[value="hyperspace"]': 'Hyperspace'
'.game-type-selector option[value="custom"]': 'Egyéni'
# Card browser
'.xwing-card-browser option[value="name"]': 'Név'
'.xwing-card-browser option[value="source"]': 'Forrás'
'.xwing-card-browser option[value="type-by-points"]': 'Típus (pont szerint)'
'.xwing-card-browser option[value="type-by-name"]': 'Típus (név szerint)'
'.xwing-card-browser .translate.select-a-card': 'Válassz a bal oldalon lévő kártyákból.'
'.xwing-card-browser .translate.sort-cards-by': 'Sort cards by'
# Info well
'.info-well .info-ship td.info-header': 'Hajó'
'.info-well .info-skill td.info-header': 'Kezdeményezés'
'.info-well .info-actions td.info-header': 'Akciók'
'.info-well .info-upgrades td.info-header': 'Fejlesztések'
'.info-well .info-range td.info-header': 'Távolság'
# Squadron edit buttons
'.clear-squad' : 'Új raj'
'.save-list' : '<i class="fa fa-floppy-o"></i> Mentés'
'.save-list-as' : '<i class="fa fa-files-o"></i> Mentés mint…'
'.delete-list' : '<i class="fa fa-trash-o"></i> Törlés'
'.backend-list-my-squads' : 'Raj betöltés'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Nyomtatás/Szövegnézet </span>'
'.randomize' : '<i class="fa fa-random"></i> Random!'
'.randomize-options' : 'Randomizer opciók…'
'.notes-container > span' : 'Jegyzetek'
# Print/View modal
'.bbcode-list' : 'Copy the BBCode below and paste it into your forum post.<textarea></textarea><button class="btn btn-copy">Másolás</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Másolás</button>'
'.vertical-space-checkbox' : """Hagyj helyet a sérülés és fejlesztéskártyáknak nyomtatáskor <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Színes nyomtatás <input type="checkbox" class="toggle-color-print" checked="checked" />"""
'.print-list' : '<i class="fa fa-print"></i> Nyomtatás'
# Randomizer options
'.do-randomize' : 'Randomize!'
# Top tab bar
'#browserTab' : 'Kártya tallózó'
'#aboutTab' : 'Rólunk'
# Obstacles
'.choose-obstacles' : 'Válassz akadályt'
'.choose-obstacles-description' : 'Choose up to three obstacles to include in the permalink for use in external programs. (This feature is in BETA; support for displaying which obstacles were selected in the printout is not yet supported.)'
'.coreasteroid0-select' : 'Core Asteroid 0'
'.coreasteroid1-select' : 'Core Asteroid 1'
'.coreasteroid2-select' : 'Core Asteroid 2'
'.coreasteroid3-select' : 'Core Asteroid 3'
'.coreasteroid4-select' : 'Core Asteroid 4'
'.coreasteroid5-select' : 'Core Asteroid 5'
'.yt2400debris0-select' : 'YT2400 Debris 0'
'.yt2400debris1-select' : 'YT2400 Debris 1'
'.yt2400debris2-select' : 'YT2400 Debris 2'
'.vt49decimatordebris0-select' : 'VT49 Debris 0'
'.vt49decimatordebris1-select' : 'VT49 Debris 1'
'.vt49decimatordebris2-select' : 'VT49 Debris 2'
'.core2asteroid0-select' : 'Force Awakens Asteroid 0'
'.core2asteroid1-select' : 'Force Awakens Asteroid 1'
'.core2asteroid2-select' : 'Force Awakens Asteroid 2'
'.core2asteroid3-select' : 'Force Awakens Asteroid 3'
'.core2asteroid4-select' : 'Force Awakens Asteroid 4'
'.core2asteroid5-select' : 'Force Awakens Asteroid 5'
# Collection
'.collection': '<i class="fa fa-folder-open hidden-phone hidden-tabler"></i> Gyűjteményed'
singular:
'pilots': 'Pilóta'
'modifications': 'Módosítás'
'titles': 'Nevesítés'
'ships' : 'Ship'
types:
'Pilot': 'Pilóta'
'Modification': 'Módosítás'
'Title': 'Nevesíés'
'Ship' : 'Ship'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Magyar = () ->
exportObj.cardLanguage = 'Magyar'
exportObj.renameShip """YT-1300""", """Modified YT-1300 Light Freighter"""
exportObj.renameShip """StarViper""", """StarViper-class Attack Platform"""
exportObj.renameShip """Scurrg H-6 Bomber""", """Scurrg H-6 Bomber"""
exportObj.renameShip """YT-2400""", """YT-2400 Light Freighter"""
exportObj.renameShip """Auzituck Gunship""", """Auzituck Gunship"""
exportObj.renameShip """Kihraxz Fighter""", """Kihraxz Fighter"""
exportObj.renameShip """Sheathipede-Class Shuttle""", """Sheathipede-class Shuttle"""
exportObj.renameShip """Quadjumper""", """Quadrijet Transfer Spacetug"""
exportObj.renameShip """Firespray-31""", """Firespray-class Patrol Craft"""
exportObj.renameShip """TIE Fighter""", """TIE/ln Fighter"""
exportObj.renameShip """Y-Wing""", """BTL-A4 Y-Wing"""
exportObj.renameShip """TIE Advanced""", """TIE Advanced x1"""
exportObj.renameShip """Alpha-Class Star Wing""", """Alpha-class Star Wing"""
exportObj.renameShip """U-Wing""", """UT-60D U-Wing"""
exportObj.renameShip """TIE Striker""", """TIE/sk Striker"""
exportObj.renameShip """B-Wing""", """A/SF-01 B-Wing"""
exportObj.renameShip """TIE Defender""", """TIE/D Defender"""
exportObj.renameShip """TIE Bomber""", """TIE/sa Bomber"""
exportObj.renameShip """TIE Punisher""", """TIE/ca Punisher"""
exportObj.renameShip """Aggressor""", """Aggressor Assault Fighter"""
exportObj.renameShip """G-1A Starfighter""", """G-1A Starfighter"""
exportObj.renameShip """VCX-100""", """VCX-100 Light Freighter"""
exportObj.renameShip """YV-666""", """YV-666 Light Freighter"""
exportObj.renameShip """TIE Advanced Prototype""", """TIE Advanced v1"""
exportObj.renameShip """Lambda-Class Shuttle""", """Lambda-class T-4a Shuttle"""
exportObj.renameShip """TIE Phantom""", """TIE/ph Phantom"""
exportObj.renameShip """VT-49 Decimator""", """VT-49 Decimator"""
exportObj.renameShip """TIE Aggressor""", """TIE/ag Aggressor"""
exportObj.renameShip """K-Wing""", """BTL-S8 K-Wing"""
exportObj.renameShip """ARC-170""", """ARC-170 Starfighter"""
exportObj.renameShip """Attack Shuttle""", """Attack Shuttle"""
exportObj.renameShip """X-Wing""", """T-65 X-Wing"""
exportObj.renameShip """HWK-290""", """HWK-290 Light Freighter"""
exportObj.renameShip """A-Wing""", """RZ-1 A-Wing"""
exportObj.renameShip """Fang Fighter""", """Fang Fighter"""
exportObj.renameShip """Z-95 Headhunter""", """Z-95-AF4 Headhunter"""
exportObj.renameShip """M1<NAME>-<NAME>""", """M12-L <NAME>er"""
exportObj.renameShip """E-Wing""", """E-Wing"""
exportObj.renameShip """TIE Interceptor""", """TIE Interceptor"""
exportObj.renameShip """Lancer-Class Pursuit Craft""", """Lancer-class Pursuit Craft"""
exportObj.renameShip """TIE Reaper""", """TIE Reaper"""
exportObj.renameShip """JumpMaster 5000""", """JumpMaster 5000"""
exportObj.renameShip """M3-A Interceptor""", """M3-A Interceptor"""
exportObj.renameShip """Scavenged YT-1300""", """Scavenged YT-1300 Light Freighter"""
exportObj.renameShip """Escape Craft""", """Escape Craft"""
# Names don't need updating, but text needs to be set
pilot_translations =
"Academy Pilot":
display_name: """Academy Pilot"""
text: """ """
"Alpha Squadron Pilot":
display_name: """Alpha Squadron Pilot"""
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Bandit Squadron Pilot":
display_name: """Bandit Squadron Pilot"""
text: """ """
"Baron of the Empire":
display_name: """Baron of the Empire"""
text: """ """
"Binayre Pirate":
display_name: """Bin<NAME>ate"""
text: """ """
"Black Squadron Ace":
display_name: """Black Squadron Ace"""
text: """ """
"Black Squadron Scout":
display_name: """Black Squadron Scout"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Black Sun Ace":
display_name: """Black Sun Ace"""
text: """ """
"Black Sun Assassin":
display_name: """Black Sun Assassin"""
text: """<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Black Sun Enforcer":
display_name: """Black Sun Enforcer"""
text: """<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Black Sun Soldier":
display_name: """Black Sun Soldier"""
text: """ """
"Blade Squadron Veteran":
display_name: """Blade Squadron Veteran"""
text: """ """
"Blue Squadron Escort":
display_name: """Blue Squadron Escort"""
text: """ """
"Blue Squadron Pilot":
display_name: """Blue Squadron Pilot"""
text: """ """
"Blue Squadron Scout":
display_name: """Blue Squadron Scout"""
text: """ """
"<NAME>":
display_name: """<NAME>"""
text: """ """
"Cartel Executioner":
display_name: """<NAME>"""
text: """<sasmall> <strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """ """
"Cartel Spacer":
display_name: """Cartel Spacer"""
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Ca<NAME> Ange<NAME> Zealot":
display_name: """Ca<NAME>"""
text: """ """
"Contracted Scout":
display_name: """Contracted Scout"""
text: """ """
"C<NAME>":
display_name: """<NAME>"""
text: """ """
"Cutlass Squadron Pilot":
display_name: """Cutlass Squadron Pilot"""
text: """ """
"Delta Squadron Pilot":
display_name: """Delta Squadron Pilot"""
text: """<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Freighter Captain":
display_name: """Freighter Captain"""
text: """"""
"Gamma Squadron Ace":
display_name: """Gamma Squadron Ace"""
text: """<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"<NAME>":
display_name: """<NAME>"""
text: """ """
"Gold Squadron Veteran":
display_name: """Gold Squadron Veteran"""
text: """ """
"Gray Squadron Bomber":
display_name: """Gray Squadron Bomber"""
text: """ """
"Green Squadron Pilot":
display_name: """Green Squadron Pilot"""
text: """<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Hired Gun":
display_name: """H<NAME>"""
text: """ """
"Imdaar Test Pilot":
display_name: """Imdaar Test Pilot"""
text: """<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
"Inquisitor":
display_name: """Inquisitor"""
text: """ """
"<NAME>":
display_name: """<NAME>"""
text: """<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"Kashyyyk Defender":
display_name: """<NAME> Defender"""
text: """ """
"Knave Squadron Escort":
display_name: """Kn<NAME> Escort"""
text: """<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Lok Revenant":
display_name: """L<NAME> Reven<NAME>"""
text: """ """
"Lothal Rebel":
display_name: """<NAME>"""
text: """<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"Nu Squadron Pilot":
display_name: """Nu Squadron Pilot"""
text: """ """
"Obsidian Squadron Pilot":
display_name: """Obsidian Squadron Pilot"""
text: """ """
"Omicron Group Pilot":
display_name: """Omicron Group Pilot"""
text: """ """
"Onyx Squadron Ace":
display_name: """Onyx Squadron Ace"""
text: """<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Onyx Squadron Scout":
display_name: """Onyx Squadron Scout"""
text: """ """
"Outer Rim Smuggler":
display_name: """Outer Rim Smuggler"""
text: """ """
"Partisan Renegade":
display_name: """Partisan Renegade"""
text: """ """
"Patrol Leader":
display_name: """Patrol Leader"""
text: """ """
"Phoenix Squadron Pilot":
display_name: """Phoenix Squadron Pilot"""
text: """<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Planetary Sentinel":
display_name: """Planetary Sentinel"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Rebel Scout":
display_name: """Rebel Scout"""
text: """ """
"Red Squadron Veteran":
display_name: """Red Squadron Veteran"""
text: """ """
"Rho Squadron Pilot":
display_name: """Rho Squadron Pilot"""
text: """ """
"Rogue Squadron Escort":
display_name: """Rogue Squadron Escort"""
text: """<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Saber Squadron Ace":
display_name: """Saber Squadron Ace"""
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Scarif Base Pilot":
display_name: """Scarif Base Pilot"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Scimitar Squadron Pilot":
display_name: """Scimitar Squadron Pilot"""
text: """<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Shadowport Hunter":
display_name: """Shadowport Hunter"""
text: """ """
"Sienar Specialist":
display_name: """Sienar Specialist"""
text: """ """
"Sigma Squadron Ace":
display_name: """Sigma Squadron Ace"""
text: """<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
"Skull Squadron Pilot":
display_name: """Skull Squadron Pilot"""
text: """<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Spice Runner":
display_name: """Spice Runner"""
text: """ """
"Storm Squadron Ace":
display_name: """Storm Squadron Ace"""
text: """<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Tala Squadron Pilot":
display_name: """Tala Squadron Pilot"""
text: """ """
"Tansarii Point Veteran":
display_name: """Tansarii Point Veteran"""
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Tempest Squadron Pilot":
display_name: """Tempest Squadron Pilot"""
text: """<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """ """
"Warden Squadron Pilot":
display_name: """Warden Squadron Pilot"""
text: """ """
"Wild Space Fringer":
display_name: """Wild Space Fringer"""
text: """<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
"Zealous Recruit":
display_name: """Zealous Recruit"""
text: """<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"4-LOM":
display_name: """4-LOM"""
text: """Miután teljesen végrehajtasz egy piros manővert, kapsz 1 kalkuláció jelzőt. A Vége fázis elején választhatsz 1 hajót 0-1-es távolságban. Ha így teszel, add át 1 stressz jelződ annak a hajónak."""
"<NAME>":
display_name: """<NAME>"""
text: """Csak vészhelyzet esetén válhatsz le az anyahajóról. Ebben az esetben megkapod a megsemmisült baráti Hound's Tooth pilóta nevet, kezdeményezést, pilóta képességet és hajó %CHARGE% jelzőt. %LINEBREAK% <strong>Escape Craft:</strong> <strong>Setup:</strong> <strong>Hound’s Tooth</strong> szükséges. A <strong>Hound’s Tooth</strong>-ra dokkolva <b>kell</b> kezdened a játékot."""
"AP-5":
display_name: """AP-5"""
text: """Amikor koordinálsz, ha a kiválasztott hajónak pontosan 1 stressz jelzője van, az végrehajthat akciókat.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy támadást, választhatsz 1 baráti hajót 1-es távolságban. Az a hajó végrehajthat egy akciót, pirosként kezelve."""
"<NAME>":
display_name: """<NAME>"""
text: """Végrehajthatsz elsődleges támadást 0-ás távolságban. Ha egy %BOOST% akcióddal átfedésbe kerülsz egy másik hajóval, úgy hajtsd végre, mintha csak részleges manőver lett volna. %LINEBREAK% VECTORED THRUSTERS: Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% gyorsítás akciót."""
"Asajj Ventress":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején választhatsz 1 ellenséges hajót a %SINGLETURRETARC% tűzívedben 0-2-es távolságban és költs 1 %FORCE% jelzőt. Ha így teszel, az a hajó kap 1 stressz jelzőt, hacsak nem távolít el 1 zöld jelzőt."""
"Autopilot Drone":
display_name: """Autopilot Drone"""
text: """<strong>Rigged Energy Cells:</strong> A Rendszer fázis alatt, ha nem vagy dokkolva, elvesztesz 1 %CHARGE% jelzőt. Az aktivációs fázis végén, ha már nincs %CHARGE% jelződ, megsemmisülsz. Mielőtt levennéd a hajód minden 0-1-es távolságban lévő hajó elszenved 1 %CRIT% sérülést."""
"Benthic Two Tubes":
display_name: """Benthic Two Tubes"""
text: """Miután végrehajtasz egy %FOCUS% akciót, átrakhatod 1 fókusz jelződ egy baráti hajóra 1-2-es távolságban."""
"Biggs Darklighter":
display_name: """Biggs Darklighter"""
text: """Amikor baráti hajó védekezik tőled 0-1-es távolságban, az <strong>Eredmények semlegesítése</strong> lépés előtt, ha a támadó tűzívében vagy, elszenvedhetsz 1 %HIT% vagy %CRIT% találatot, hogy hatástalaníts 1 azzal egyező találatot."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy végrehajtasz egy támadást, újradobhatsz 1 kockát, minden egyes 0-1-es távolságban lévő ellenséges hajó után."""
"<NAME>":
display_name: """<NAME>"""
text: """Baráti hajók bemérhetnek más baráti hajóktól 0-3-as távolságban lévő objektumokat."""
"Boss<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy elsődleges támadást, az <strong>Eredmények semlegesítése</strong> lépés után, elkölthetsz egy %CRIT% eredményt, hogy hozzáadj 2 %HIT% eredményt a dobásodhoz."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy végrehajtasz egy támadást, ha stresszes vagy, újradobhatod legfeljebb 2 kockádat."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel, ha a támadónak nincs zöld jelzője, megváltoztathatod 1 üres vagy %FOCUS% dobásod %EVADE% eredményre.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Capt<NAME>":
display_name: """<NAME>"""
text: """Amikor egy baráti hajó 0-1-es távolságban végrehajt egy %TORPEDO% vagy %MISSILE% támadást, az újradobhat legfeljebb 2 támadókockát.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután egy ellenséges hajó sérülést szenved és nem védekezett, végrehajthatsz egy bónusz támadást ellene."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején választhatsz egy vagy több baráti hajót 0-3-es távolságban. Ha így teszel, tedd át az összes ellenséges bemérés jelzőt a kiválasztott hajókról magadra."""
"<NAME>":
display_name: """<NAME>"""
text: """Mielőtt egy baráti bomba vagy akna <NAME>, elkölthetsz 1 %CHARGE% jelzőt, hogy megakadályozd a felrobbanását.%LINEBREAK%Mikor egy támadás ellen védekezel, amely akadályozott egy bomba vagy akna által, 1-gyel több védekezőkockával dobj."""
"<NAME>":
display_name: """<NAME>"""
text: """Végrehajthatsz elsődleges támadást 0-ás távolságban."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy támadást, jelöld meg a védekezőt a <strong>Suppressive Fire</strong> kondícióval."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Aktivációs fázis elején választhatsz 1 baráti hajót 1-3-as távolságban. Ha így teszel, az a hajó eltávolít 1 stressz jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Mielőtt felfordított sebzéskártyát kapnál, elkölthetsz 1 %CHARGE%-et, hogy a lapot képpel lefelé húzd fel."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Aktivációs fázis elején elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, amikor baráti hajók bemérés jelzőt tesznek fel ebben a körben, 3-as távolságon túl tehetik csak meg a 0-3-as távolság helyett."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre egy bemért hajó ellen, miután dobsz a kockákkal, feltehetsz egy bemérés jelzőt a védekezőre.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor kidobnál egy eszközt, helyette ki is lőheted egy [1 %STRAIGHT%] sablon használatával.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"<NAME>":
display_name: """<NAME>"""
text: """0-ás kezdeményezésnél végrehajthatsz egy bónusz elsődleges támadást egy ellenséges hajó ellen, aki a %BULLSEYEARC% tűzívedben van. Ha így teszel, a következő Tervezés fázisban kapsz 1 'inaktív fegyverzet' jelzőt.%LINEBREAK%<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtanál egy %STRAIGHT% manővert, megnövelheted annak nehézségét. Ha így teszel, helyette végrehajthatod mint %KTURN% manőver.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután egy ellenséges hajó 0-3-as távolságban kap legalább 1 ion jelzőt, elkölthetsz 3 %CHARGE% jelzőt. Ha így teszel, az a hajó kap 2 további ion jelzőt."""
"<NAME> (StarViper)":
display_name: """<NAME>"""
text: """Miután teljesen végrehajtasz egy manővert, kaphatsz 1 stressz jelzőt, hogy elforgasd a hajód 90 fokkal.%LINEBREAK% <sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején választhatsz 1 pajzzsal rendelkező hajót a %BULLSEYEARC% tűzívedben és elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó elveszít egy pajzsot, te pedig visszatöltesz 1 pajzsot.%LINEBREAK%<sasmall><strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy akciót, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy akciót.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Dash Rendar":
display_name: """Dash Rendar"""
text: """Amikor mozogsz, hagyd figyelmen kívül az akadályokat.%LINEBREAK%<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
"Del Meeko":
display_name: """<NAME>"""
text: """Amikor egy baráti 0-2 távolságban védekezik egy sérült támadó ellen, a védekező újradobhat 1 védekezőkockát."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután védekeztél, ha a támadó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy bónusz támadást a támadó ellen."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy baráti nem-limitált hajó végrehajt egy támadást, ha a védekező benne van a tűzívedben, a támadó újradobhatja 1 támadókockáját."""
"<NAME>":
display_name: """<NAME>"""
text: """Mielőtt aktiválódnál és van fókuszod, végrehajthatsz egy akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Ha ki szeretnél dobni egy eszközt az [1 %STRAIGHT%] sablonnal, használhatod helyette a [3 %TURNLEFT%], [3 %STRAIGHT%], vagy [3 %TURNRIGHT%] sablont."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy 0-2-es távolságban lévő baráti hajó védekezik vagy támadást hajt végre, elköltheti a te fókusz jelzőidet, mintha a saját hajójáé lenne."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején elkölthetsz 1 fókusz jelzőt, hogy kiválassz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó a kör végéig minden védekezésénél 1-gyel több védekezőkockával dob."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"<NAME> (<NAME>)":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"<NAME> (TIE Fighter)":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts."""
"<NAME> (<NAME>)":
display_name: """<NAME>"""
text: """Miután egy ellenséges hajó a tűzívedben sorra kerül az Ütközet fázisban, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt. Ha így teszel, az a hajó nem költhet el jelzőt, hogy módosítsa támadókockáit e fázis alatt.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha a támadás 1-es távolságban történik, 1-gyel több kockával dobhatsz.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"<NAME> (X-Wing)":
display_name: """<NAME>"""
text: """Miután elköltesz egy fókusz jelzőt, választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó kap 1 fókusz jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután elköltesz egy fókusz jelzőt, választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó kap 1 fókusz jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy baráti hajó végrehajt egy támadást, ha a védekező a %FRONTARC% tűzívedben van, a támadó 1 %HIT% eredményét %CRIT% eredményre módosíthatja.%LINEBREAK%<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Genesis <NAME>":
display_name: """<NAME>"""
text: """Miután feltettél egy bemérés jelzőt, le kell venned az összes fókusz és kitérés jelződet, aztán megkapsz annyi fókusz és kitérés jelzőt, ahány a bemért hajónak van.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy támadást sérült védekező ellen, 1-gyel több támadókockával dobhatsz."""
"Grand Inquisitor":
display_name: """Grand Inquisitor"""
text: """Amikor 1-es távolságban védekezel, elkölthetsz 1 %FORCE% tokent, hogy megakadályozd az 1-es távolság bónuszt. Amikor támadást hajtasz végre 2-3-as távolságban lévő védekező ellen, elkölthetsz 1 %FORCE% jelzőt, hogy megkapd az 1-es távolság bónuszt."""
"Graz":
display_name: """Graz"""
text: """Amikor védekezel, ha a támadó mögött vagy, 1-gyel több védekezőkockával dobhatsz. Amikor végrehajtasz egy támadást, ha a védekező mögött vagy, 1-gyel több támadókockával dobhatsz."""
"Guri":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején, ha legalább 1 ellenséges hajó van 0-1-es távolságban, kaphatsz egy fókusz jelzőt.%LINEBREAK% <sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Han Solo":
display_name: """Han Solo"""
text: """Miután dobtál, ha 0-1-es távolságban vagy akadálytól, újradobhatod az összes kockádat. Ez nem számít újradobásnak más hatások számára."""
"Han Solo (Scum)":
display_name: """Han <NAME>"""
text: """Amikor védekezel vagy elsődleges támadást hajtasz vége, ha a támadás akadály által akadályozott, 1-gyel több kockával dobhatsz."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután egy ellenséges hajó végrehajt egy manővert, ha 0-ás távolságba kerül, végrehajthatsz egy akciót."""
"H<NAME>ulla":
display_name: """<NAME>"""
text: """Miután piros vagy kék manővert fedtél fel, átállíthatod manőversablonod egy másik, azonos nehézségű manőverre.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"H<NAME> Syndulla (VCX-100)":
display_name: """<NAME>"""
text: """Miután piros vagy kék manővert fedtél fel, átállíthatod manőversablonod egy másik, azonos nehézségű manőverre.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, a védekezőtől 0-1-es távolságban lévő minden más baráti hajó után újradobhatsz 1 támadókockát."""
"IG-88A":
display_name: """IG-88A"""
text: """Az Ütközet fázis elején kiválaszthatsz egy %CALCULATE% akcióval rendelkező baráti hajót 1-3-as távolságban. Ha így teszel, add át 1 kalkuláció jelződet neki.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88B":
display_name: """IG-88B"""
text: """Miután végrehajtasz egy támadást ami nem talált, végrehajthatsz egy bónusz %CANNON% támadást.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88C":
display_name: """IG-88C"""
text: """Miután végrehajtasz egy %BOOST% akciót, végrehajthatsz egy %EVADE% akciót.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88D":
display_name: """IG-88D"""
text: """Amikor végrehajtasz egy Segnor's Loop [%SLOOPLEFT% vagy %SLOOPRIGHT%] manővert, használhatsz ugyanazon sebességű másik sablont helyette: vagy megegyező irányú kanyar [%TURNLEFT% vagy %TURNRIGHT%] vagy előre egyenes [%STRAIGHT%] sablont.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"I<NAME>":
display_name: """<NAME>"""
text: """Miután teljesen végrehajtasz egy manővert, ha stresszes vagy, dobhatsz 1 támadókockával. %HIT% vagy %CRIT% eredmény esetén távolíts el 1 stressz jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Mielőtt egy 0-1-es távolságban lévő baráti TIE/ln hajó elszenvedne 1 vagy több sérülést, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, megakadályozod a sérülést."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, elszenvedhetsz 1 %HIT% sérülést, hogy újradobj bármennyi kockát.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, választhatsz egy baráti hajót 0-1-es távolságban. Az a hajó végrehajthat egy %FOCUS% akciót.%LINEBREAK%<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy tűzíveden belüli baráti hajó elsődleges támadást hajt végre, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt. Ha így teszel, az a hajó 1-gyel több támadókockával dobhat."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután kapsz egy stressz jelzőt, dobhatsz 1 támadó kockával, hogy levedd. %HIT% eredmény esetén elszenvedsz 1 %HIT% sérülést."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %CHARGE% jelzőt egy felszerelt %TORPEDO% fejlesztésről. Ha így teszel a védekező 1-gyel kevesebb védekezőkockával dob.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején kiválaszthatsz egy 0-2-es távolságban lévő baráti hajót. Ha így teszel, áttehetsz róla 1 fókusz vagy kitérés jelzőt a magadra."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután teljesen végrehajtasz egy piros manővert, kapsz 2 fókusz jelzőt.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy tűzívedben lévő baráti hajó védekezik, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a támadó 1-gyel kevesebb támadókockával dob.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, ha legalább 1 nem-limitált baráti hajó van 0-ás távolságra a védekezőtől, dobj 1-gyel több támadókockával."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy nem-%FRONTARC% támadást hajtasz végre, dobj 1-gyel több támadókockával."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején választhatsz 1 hajót ami a %FRONTARC% és %SINGLETURRETARC% tűzívedben is benne van 0-1-es távolságban. Ha így teszel, az a hajó kap egy vonósugár jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó stresszes, újradobhatod 1 kockádat."""
"<NAME>":
display_name: """<NAME>"""
text: """Végrehajthatsz egy %FRONTARC% speciális támadást a %REARARC% tűzívedből. Amikor speciális támadást hajtasz végre, újradobhatsz egy támadókockát."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, megfordíthatod a felszerelt %CONFIG% fejlesztés kártyád."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején átadhatod 1 fókusz jelződet egy tűzívedben lévő baráti hajónak."""
"L3-37":
display_name: """L3-37"""
text: """Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek."""
"L3-37 (Escape Craft)":
display_name: """L3-37"""
text: """Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután védekezel vagy támadást hajtasz végre, ha a támadás nem talált, kapsz 1 kitérés jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután teljesen végrehajtasz egy kék manővert, választhatsz egy baráti hajót 0-3-as távolságban. Az a hajó végrehajthat egy akciót."""
"<NAME> (Scum)":
display_name: """<NAME>"""
text: """Miután dobsz a kockákkal, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy újradobhasd az összes üres eredményed."""
"<NAME> (Scum) (Escape Craft)":
display_name: """<NAME>"""
text: """Miután dobsz a kockákkal, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy újradobhasd az összes üres eredményed.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején kiválaszthatsz egy hajót 1-es távolságban és elköltheted a rajta lévő bemérés jelződet. Ha így teszel, az a hajó kap egy vonósugár jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, végrehajthatsz egy piros %EVADE% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor elsődleges támadást hajtasz végre, ha legalább 1 másik baráti hajó van 0-1-es távolságban a védekezőtől, 1-gyel több támadókockával dobhatsz."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután kapsz egy inaktív fegyverzet jelzőt, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy levegyél 1 inaktív fegyverzet jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, miután a védekező dob a kockáival, elkölthetsz 1 fókusz jelzőt, hogy semlegesítsd a védekező összes üres és fókusz eredményét."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy %COORDINATE% akciót, ha a koordinált hajó olyan akciót hajt végre, ami a te akciósávodon is rajta van, végrehajthatod azt az akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután egy 0-1-es távolságban lévő baráti hajó védekezővé válik, elkölthetsz 1 erősítés jelzőt. Ha így teszel, az a hajó kap 1 kitérés jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután védekező lettél (még a kockagurítás előtt), visszatölthetsz 1 %FORCE% jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, ha a védekező felfordított sérülés kártyát kapna, helyette húzz te 3 lapot, válassz egyet, a többit dobd el.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall> """
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy baráti hajó 0-2-es távolságban védekezik, a támadó maximum 1 kockáját dobhatja újra."""
"Major Rhymer":
display_name: """Major Rhymer"""
text: """Amikor végrhajtasz egy %TORPEDO% vagy %MISSILE% támadást, növelheted vagy csökkentheted a fegyver távolság követelményét 1-gyel, a 0-3 korláton belül.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Major Ver<NAME>":
display_name: """Major Vermeil"""
text: """Amikor támadást hajtasz végre, ha a védekezőnek nincs egy zöld jelzője sem, megváltoztathatod 1 üres vagy %FOCUS% eredményedet %HIT% eredményre.%LINEBREAK% %LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Major V<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel és van 'inaktív fegyverzet' jelződ, dobj 1-gyel több védekezőkockával."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején kiválaszthatsz egy 0-1-es távolságban lévő baráti hajót. Ha így teszel, add át neki az összes zöld jelződ."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor elsődleges támadást hajtasz végre, elkölthetsz 1 pajzsot, hogy 1-gyel több támadókockával dobj, vagy ha nincs pajzsod, dobhatsz 1-gyel kevesebb támadókockával, hogy visszatölts 1 pajzsot."""
"Mor<NAME>":
display_name: """<NAME>"""
text: """Ha lerepülsz a pályáról, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, helyezd a hajód tartalékba. A következő Tervezési fázis elején helyezd el a hajót a pálya szélétől 1-es távolságban azon az oldalon, ahol lerepültél."""
"<NAME> (Y-Wing)":
display_name: """<NAME>"""
text: """Amikor védekezel, ha az ellenség 0-1-es távolságban van, adj 1 %EVADE% eredményt a dobásodhoz."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel, ha az ellenség 0-1-es távolságban van, adj 1 %EVADE% eredményt a dobásodhoz."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor elődleges támadást hajtasz végre, ha nincs baráti hajó 0-2 távolságban, dobj 1-gyel több támadókockával."""
"Old <NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején, kiválaszthatsz 1 ellenséges hajót 1-es távolságban. Ha így teszel és benne vagy a %FRONTARC% tűzívében, leveheted az összes zöld jelzőjét.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Outer Rim Pioneer":
display_name: """Outer R<NAME>"""
text: """Baráti hajók 0-1-es távolságban végrehajthatnak támadást akadálytól 0 távolságra.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején kiválaszthatsz 1 ellenséges hajót a tűzívedben 0-2 távolságban. Ha így teszel tedd át 1 fókusz vagy kitérés jelzőjét magadra."""
"<NAME>":
display_name: """<NAME>"""
text: """<NAME> védekezel, az <strong>Eredmények semlegesítése</strong> lépés után, egy 0-1 távolságban lévő másik baráti hajó, aki benne van a támadó tűzívében, elszenvedhet 1 %HIT% vagy %CRIT% sérülést. Ha így tesz, hatástalaníts 1 ennek megfelelő eredményt.%LINEBREAK%<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején kaphatsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts 1 %CHARGE% jelzőt egy felszerelt fejlesztésen.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, ha van 'reinforce' jelződ és a védekező a reinforce-nak megfelelő %FULLFRONTARC% vagy %FULLREARARC% tűzívedben van, megváltoztathatod 1 %FOCUS% eredményed %CRIT% eredményre."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy támadást, ami talál, ha van kitérés jelződ, fordítsd fel a védekező egy sérülés kártyáját.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején választhatsz 1 tűzívedben lévő hajót. Ha így teszel, a kezdeményezési értéke ebben a fázisban 7 lesz, függetlenül a nyomtatott értékétől."""
"<NAME>":
display_name: """<NAME>"""
text: """Mielőtt aktiválódsz, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"<NAME> (TIE Fighter)":
display_name: """<NAME>"""
text: """Mielőtt aktiválódsz, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót."""
"<NAME> (Scum)":
display_name: """<NAME>"""
text: """Amikor védekezel, ha a támadó benne van a %SINGLETURRETARC% tűzívedben 0-2-es távolságban, hozzáadhatsz 1 %FOCUS% eredményt a dobásodhoz."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel kezelheted a mozgékonyság értékedet úgy, hogy az megegyezzen az ebben a körben végrehajtott manővered sebességével.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy sérült baráti hajó 0-3-as távolságban végrehajt egy támadást, újradobhat 1 támadókockát."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor egy baráti hajó 0-1-es távolságban védekezik, újradobhatja 1 kockáját.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy elsődleges támadást, az <strong>Eredmények semlegesítése</strong> lépés előtt elkölthetsz 2 %FORCE% jelzőt, hogy hatástalaníts 1 %EVADE% eredményt."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy támadást elkölthetsz 1 %CRIT% eredményt. Ha így teszel, a védekező kap 1 lefordított sérülés kártyát, majd hatástalanítsd a többi dobás eredményed."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre, elköltheted az ellenfeledre tett bemérés jelződet, hogy hozzáadj 1 %FOCUS% eredményt dobásodhoz."""
"<NAME>":
display_name: """<NAME>"""
text: """Ha ledobnál egy eszközt az [1 %STRAIGHT%] sablon használatával, helyette ledobhatod más 1-es sebességű sablonnal."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején, ha van ellenséges hajó a %BULLSEYEARC% tűzívedben, kapsz 1 fókusz jelzőt.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, miután dobtál vagy újradobtál kockákat, ha minden eredményed egyforma, hozzáadhatsz 1 ugyanolyan eredményt a dobáshoz.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor 3-as távolságban védekezel vagy 1-es távolságban támadást hajtasz végre, dobj 1-gyel több kockával."""
"<NAME>":
display_name: """<NAME>"""
text: """Ha megsemmisülnél, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, dobd el az összes sérülés kártyádat, szenvedj el 5 %HIT% sérülést, majd helyezd magad tartalékba. A következő Tervezési fázis elején helyezd fel a hajód 1-es távolságban a saját oldaladon."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 stressz jelzőt, hogy minden %FOCUS% eredményed megváltoztasd %EVADE% vagy %HIT% eredményre."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %FOCUS%, %HIT% vagy %CRIT% eredményt, hogy megnézd a védekező képpel lefelé fordított sérülés kártyáit, kiválassz egyet és megfordítsd."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy %RELOAD% akciót, visszatölthetsz 1 %CHARGE% jelzőt 1 felszerelt %TALENT% fejlesztés kártyán.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy támadást, minden ellenséges hajó a %BULLSEYEARC% tűzívedben elszenved 1 %HIT% sérülést, hacsak el nem dob 1 zöld jelzőt.%LINEBREAK%<sasmall><strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején kiválaszthatsz 1 hajót a tűzívedben. Ha így teszel, az a hajó ebben a körben 0-ás kezdeményezéssel kerül sorra a normál kezdeményezése helyett."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután végrehajtasz egy támadást, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót akkor is ha stresszes vagy.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Az Ütközet fázis elején, ha van egy vagy több másik hajó 0-ás távolságban tőled, te és a 0-ás távolságra lévő hajók kapnak egy vonósugár jelzőt.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"<NAME>":
display_name: """<NAME>"""
text: """Miután egy baráti hajó 0-1-es távolságban védekezik - a sérülések elkönyvelése után, ha volt -, végrehajthatsz egy akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy manővert, helyette végrehajthatsz egy manővert ugyanabban az irányban és nehézségben 1-gyel kisebb vagy nagyobb sebességgel.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Miután védekeztél, ha nem pontosan 2 védekezőkockával dobtál, a támadó kap 1 stress jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor támadást hajtasz végre, a védekező 1-gyel kevesebb védekezőkockával dob."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor elsődleges támadást hajtasz végre, ha sérült vagy, 1-gyel több támadókockával dobhatsz."""
"<NAME>":
display_name: """<NAME>"""
text: """A Vége fázis alatt elköltheted egy ellenséges hajón lévő bemérődet hogy felfordítsd egy sérülés kártyáját.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy elsődleges támadást, 1-gyel több támadókockával dobhatsz. Ha így teszel, a védekező 1-gyel több védekezőkockával dob."""
'"<NAME>"':
display_name: """“<NAME>”"""
text: """Az Ütközet fázis elején minden 0-ás távolságban lévő ellenséges hajó 2 zavarás jelzőt kap.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
'"Countdown"':
display_name: """“Countdown”"""
text: """Amikor védekezel, az <strong>Eredmények semlegesítése</strong> lépés után, ha nem vagy stresszes, választhatod, hogy elszenvedsz 1 %HIT% sérülést és kapsz 1 stressz jelzőt. Ha így teszel, vess el minden kocka dobást.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Deathfire"':
display_name: """“Deathfire”"""
text: """Miután megsemmisülsz, mielőtt levennéd a hajód, végrehajthatsz egy támadást és ledobhatsz vagy kilőhetsz 1 eszközt.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
'"Deathrain"':
display_name: """“Deathrain”"""
text: """Miután ledobsz vagy kilősz egy eszközt, végrehajthatsz egy akciót."""
'"Double Edge"':
display_name: """“Double Edge”"""
text: """Miután végrehajtasz egy %TURRET% vagy %MISSILE% támadást ami nem talál, végrehajthatsz egy bónusz támadást egy másik fegyverrel."""
'"D<NAME>"':
display_name: """“<NAME>”"""
text: """Választhatsz úgy, hogy nem használod az <strong>Adaptive Ailerons</strong> képességed. Használhatod akkor is <strong>Adaptive Ailerons</strong> képességed, amikor stresszes vagy.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Dutch" Vander':
display_name: """“Dutch” Vander"""
text: """Miután %LOCK% akciót hajtottál végre választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó is bemérheti az általad bemért objektumot, függetlenül a távolságtól."""
'"Echo"':
display_name: """“Echo”"""
text: """Amikor kijössz az álcázásból, a [2 %BANKLEFT%] vagy [2 %BANKRIGHT%] sablont <b>kell</b> használnod a [2 %STRAIGHT%] helyett.%LINEBREAK%<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
'"Howlrunner"':
display_name: """“<NAME>”"""
text: """Amikor egy 0-1-es távolságban lévő baráti hajó elsődleges támadást hajt végre, 1 támadókockát újradobhat."""
'"<NAME>"':
display_name: """“<NAME>”"""
text: """Miután védekeztél vagy támadást hajtottál végre, ha elköltöttél egy kalkuláció jelzőt, kapsz 1 kalkuláció jelzőt.%LINEBREAK%<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
'"<NAME>" <NAME>':
display_name: """“<NAME>” <NAME>"""
text: """Amikor támadást hajtasz végre 1-es távolságban, dobj 1-gyel több támadókockával."""
'"Night Beast"':
display_name: """“Night Beast”"""
text: """Miután teljesen végrehajtasz egy kék manővert, végrehajthatsz egy %FOCUS% akciót."""
'"Pure Sabacc"':
display_name: """“Pure S<NAME>”"""
text: """Amikor támadást hajtasz végre, ha 1 vagy kevesebb sérüléskártyád van, 1-gyel több támadókockával dobhatsz.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Red<NAME>"':
display_name: """“Red<NAME>”"""
text: """Fenntarthatsz 2 bemérő jelzőt. Miután végrehajtasz egy akciót, feltehetsz egy bemérő jelzőt."""
'"S<NAME>" Sk<NAME>u':
display_name: """“<NAME>” <NAME>"""
text: """Amikor végrehajtasz egy támadást a %BULLSEYEARC% tűzívedben lévő védekező ellen, dobj 1-gyel több támadókockával."""
'"<NAME>"':
display_name: """“<NAME>”"""
text: """Miután teljesen végrehajtasz egy 1-es sebességű manővert az <strong>Adaptive Ailerons</strong> képességed használatával, végrehajthatsz egy %COORDINATE% akciót. Ha így teszel, hagyd ki az <strong>Akció végrehajtása</strong> lépést.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"W<NAME>"':
display_name: """“<NAME>”"""
text: """Amikor végrehajtasz egy támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy 1-gyel több támadókockával dobj. Védekezés után elvesztesz 1 %CHARGE% jelzőt."""
'"Whisper"':
display_name: """“Whisper”"""
text: """Miután végrehajtasz egy támadást ami talál, kapsz 1 kitérés jelzőt.%LINEBREAK%<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
'"Zeb" Orrelios':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
'"Zeb" Orrelios (Sheathipede)':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
'"Zeb" Orrelios (TIE Fighter)':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál."""
"Po<NAME>":
text: """Miután végrehajtasz egy akciót, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy fehér akciót pirosként kezelve.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután egy hajó 1-2-es távolságban felhúz egy sérülés kártyát, felrakhatsz rá egy bemérő jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
'"Midnight"':
text: """Amikor védekezel vagy támadás hajtasz végre, ha van bemérőd azon az ellenséges hajón, az nem módosíthatja a kockáit."""
'"Longshot"':
text: """Amikor elsődleges támadást hajtasz végre 3-as távolságban, dobj 1-gyel több támadókockával."""
'"M<NAME>"':
text: """Az Ütközet fázis elején válaszhatsz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó vegyen le 1 stressz jelzőt."""
"<NAME>":
text: """Miután védekeztél, elkölthetsz 1 %FORCE% jelzőt, hogy hozzárendeled az <strong>I'll Show You the Dark Side</strong> kondíciós kártyát a támadódhoz.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
'"Blackout"':
text: """Amikor végrehajtasz egy támadást, ha a támadás akadályozott egy akadály által, a védekező 2-vel kevesebb védekezőkockával dob.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"<NAME>":
text: """Felhelyezés: Miután felhelyezésre kerültél, a többi baráti hajó bárhova helyezhető a játékterületen tőled 0-2-es távolságban.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Backdraft"':
text: """Amikor végrehajtasz egy %SINGLETURRETARC% elsődleges támadást, ha a védekező benne van a %REARARC% tűzívedben dobj 1-gyel több kockával.%LINEBREAK%<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
'"Quickdraw"':
text: """Miután elvesztesz egy pajzsot, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, végrehajthatsz egy bónusz elsődleges támadást.%LINEBREAK%<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Zeta Squadron Survivor":
text: """<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Rey":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy 1 üres eredményed %EVADE% vagy %HIT% eredményre változtasd."""
"Han Solo (Resistance)":
text: """Felhelyezés: Bárhova felhelyezheted a hajód a játékterületre 3-as távolságon túl az ellenséges hajóktól."""
"Chewbacca (Resistance)":
text: """Miután egy baráti hajó 0-3-as távolságban megsemmisül, végrehajthatsz egy akciót. Aztán végrehajthatsz egy bónusz támadást."""
"<NAME>":
text: """Amikor védekezel vagy támadást hajtasz végre, mielőtt a támadókockát elgurulnának, ha nem vagy az ellenséges hajó %BULLSEYEARC% tűzívében, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az ellenséges hajó kap egy zavarás jelzőt.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Mining Guild Surveyor":
text: """<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Mining Guild Sentry":
text: """<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"<NAME>":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az elleséges hajó nagyobb talpméretű, dobj 1-gyel több kockával.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"<NAME>":
text: """Mielőtt ledobnál egy bombát, ledobás helyett elhelyezheted a játékterületen úgy, hogy érintkezzen veled."""
"Major Stridan":
text: """Amikor koordinálsz vagy egy fejlesztés kártyád hatását alkalmaznád, kezelheted úgy a 2-3-as távolságban lévő baráti hajókat, mintha 0 vagy 1-es távolságban lennének.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"<NAME>":
text: """Amikor gyorsítasz (%BOOST%), használhatod a [1 %TURNLEFT%] vagy [1 %TURNRIGHT%] sablonokat is.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután elvesztesz 1 pajzsod, kapsz 1 %EVADE% jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután egy hajó 1-2-es távolságban felhúz egy sérülés kártyát, felrakhatsz rá egy bemérő jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután teljesen végrehajtasz egy kék manővert, választhatsz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó levesz egy stressz jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Black Squadron Ace (T-70)":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Red Squadron Expert":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Blue Squadron Rookie":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Cobalt Squadron Bomber":
text: """ """
"TN-3465":
text: """Amikor egy másik baráti hajó támadást hajt végre, ha 0-1 távolságban vagy a védekezőtől, elszenvedhetsz 1 %CRIT% sérülést, hogy a támadó 1 eredményét %CRIT% eredményre változtassa."""
'"Scorch"':
text: """Amikor elsődleges támadást hajtasz végre, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy 1-gyel több támadókockával dobj."""
'"Longshot"':
text: """Amikor elsődleges támadást hajtasz végre 3-as távolságban, dobj 1-gyel több támadókockával."""
'"Static"':
text: """Amikor elsődleges támadást hajtasz végre, elköltheted a védekezőn lévő bemérődet és egy %FOCUS% jelződ, hogy minden eredményed %CRIT% eredményre változtass."""
"<NAME>":
text: """Miután egy hajó 1-2-es távolságban kap egy piros vagy narancs jelzőt, ha nem volt bemérőd a hajón, feltehetsz egyet rá."""
"<NAME>":
text: """Az Ütközet fázis elején elkölthetsz 1 %CHARGE% jelzőt, hogy kapj 1 stressz jelzőt. Ha így teszel, a kör végéig ha védekezel vagy támadást hajtasz végre, megváltoztathatsz minden %FOCUS% eredményed %EVADE% vagy %HIT% eredményre."""
"Omega Squadron Ace":
text: """"""
"Zeta Squadron Pilot":
text: """"""
"Epsilon Squadron Cadet":
text: """"""
"<NAME>":
text: """Miután teljesen végrehajtasz egy manővert, forgathatod a %SINGLETURRETARC% tűzívedet.%SINGLETURRETARC% %LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"<NAME>":
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre, ha stresszes vagy, 1-gyel kevesebb védekezőkockával vagy 1-gyel több támadókockával <strong>kell</strong> dobnod.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"<NAME>":
text: """Ne hagyd ki az <strong>Akció végrehajtása</strong> lépést, miután részlegesen hajtottál végre egy manővert.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"<NAME>":
text: """Amikor egy ellenséges hajó a %BULLSEYEARC% tűzívedben végrehajt egy támadást, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a védekező 1-gyel több kockával dob.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"<NAME>":
text: """Miután végrehajtasz egy támadást, elkölthetsz 2 %FORCE% jelzőt, hogy végrehajts egy bónusz elsődleges támadást egy másik célpont ellen. Ha az első támadás nem talált, a bónusz támadást végrehajthatod ugyanazon célpont ellen."""
'"<NAME>"':
text: """Amikor 1-2-es távolságban és a %LEFTARC% vagy %RIGHTARC% tűzívedben lévő baráti hajó végrehajt egy elsődleges támadást, újradobhat 1 támadókockát."""
"<NAME> <NAME>":
text: """Az Aktivációs vagy Ütközet fázis közben, miután egy hajó a %FRONTARC% tűzívedben 1-2-es távolságban kap 1 stressz jelzőt, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó kap egy vonósugár jelzőt.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"Captain Card<NAME>":
text: """Amikor egy baráti hajó 1-2-es távolságban, a tiédnél alacsonyabb kezdeményezéssel védekezik vagy támadást hajt végre, ha van legalább 1 %CHARGE% jelződ, az a hajó újradobhat 1 %FOCUS% eredményét. Miután egy ellenséges hajó 0-3-as távolságban megsemmisül, elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Avenger"':
text: """Miután egy ellenséges hajó 0-3-as távolságban megsemmisül végrehajthatsz egy akciót, akkor is ha stresszes vagy. %LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
'"Recoil"':
text: """Amikor stresszes vagy kezelheted úgy a %FRONTARC% tűzívedben 0-1-es távolságban lévő ellenséges hajókat, mintha a %BULLSEYEARC% tűzívedben lennének.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Omega Squadron Expert":
text: """<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Sienar-Jaemus Engineer":
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"First Order Test Pilot":
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Starkiller Base Pilot":
text: """<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"<NAME>":
text: """Miután sérülést szenvedsz el, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy akciót.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Null"':
text: """Amíg nem vagy sérült, kezeld a kezdeményezési értéked 7-esként."""
"Cat":
text: """Amikor elsődleges támadást hajtasz végre, ha a védekező 0-1-es távolságban van legalább 1 baráti eszköztől, dobj 1-gyel több kockával."""
"<NAME>":
text: """Miután végrehajtasz egy támadást, ha a védekező benne van a %SINGLETURRETARC% tűzívedben, rendeld hozzá a <strong>Rattled</strong> kondíciós kártyát a védekezőhöz."""
"<NAME>":
text: """Amikor védkezel, ha a támadó benne van egy baráti hajó %SINGLETURRETARC% tűzívében, hozzáadhatsz 1 %FOCUS% eredményt a dobásodhoz."""
"<NAME>":
text: """Miután teljesen végrehajtasz egy kék vagy fehér manővert, ha még nem dobtál vagy lőttél ki eszközt ebben a körben, kidobhatsz egy eszközt."""
"Resistance Sympathizer":
text: """"""
"<NAME>":
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CHARGE% jelzőt vagy a felszerelt %ASTROMECH% fejlesztéseden lévő 1 nem visszatölthető %CHARGE% jelzőt, hogy újradobj 1 kockát minden 0-1-es távolságban lévő baráti hajó után.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután teljesen végrehajtasz egy 2-4 sebességű manővert, végrehajthatsz egy %BOOST% akciót%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután kapsz egy stressz jelzőt, ha van ellenséges hajó a %FRONTARC% tűzívedben 0-1 távolságban, leveheted a kapott stressz jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"<NAME>":
text: """Miután felfedtél egy piros Tallon Roll (%TROLLLEFT% vagy %TROLLRIGHT%) manővert, ha 2 vagy kevesebb stressz jelződ van, kezeld a manővert fehérként.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Blue Squadron Recruit":
text: """<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Green Squadron Expert":
text: """<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Foreman Proach":
text: """Mielőtt sorra kerülsz az Ütközet fázisban, választhasz 1 ellenséges hajót a %BULLSEYEARC% tűzívedben 1-2-es távolságban és kapsz 1 'inaktív fegyverzet' jelzőt. Ha így teszel, az a hajó kap 1 vonósugár jelzőt.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"<NAME>":
text: """Mielőtt egy baráti hajó 1-es távolságban kapna 1 'inaktív fegyverzet' jelzőt, ha az a hajó nem stresszes, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó 1 stressz jelzőt kap helyette.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"General Grievous":
text: """Amikor elsődleges támadást hajtasz végre, ha nem vagy a védekező tűzívében, újradobhatod akár 2 támadókockádat is."""
"<NAME>":
text: """Amikor elsődleges támadást hajtasz végre, újradobhatsz 1 támadókockát minden kalkuláció tokennel rendelkező baráti hajó után ami a védekezőtől 1-es távolságban van."""
"<NAME>":
text: """Amikor egy baráti hajó 0-3-as távolságban végrehajt egy elsődleges támadást, ha a védekező benne van annak %BULLSEYEARC% tűzívében, az 'Eredmények semlegesítése' lépés előtt a baráti hajó elkölthet 1 %CALCULATE% jelzőt, hogy semlegesítsen 1 %EVADE% eredményt."""
"<NAME>":
text: """Amikor támadást hajtasz végre, ha a védekező benne van a %BULLSEYEARC% tűzívedben, újradobhatsz 1 üres eredményt.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"Haor Chall Prototype":
text: """Miután egy ellenséges hajó a %BULLSEYEARC% tűzívedben 0-2-es távolságban védekezőnek jelöl egy másik baráti hajót, végrehajthatsz egy %CALCULATE% vagy %LOCK% akciót.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"DFS-081":
text: """Amikor egy baráti hajó 0-1 távolságban védekezik, elkölthet 1 %CALCULATE% jelzőt, hogy az összes %CRIT% eredményt %HIT% eredményre változtassa.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"<NAME>":
text: """Miután egy baráti hajó 0-2-es távolságban elkölt egy %FOCUS% jelzőt, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, az a hajó kap 1 %FOCUS% jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """Miután teljesen végrehajtasz egy manővert, választhatsz egy baráti hajót 0-1-es távolságban és költs el 1 %FORCE% jelzőt. Az a hajó végrehajthat egy akciót még ha stresszes is. %LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """Miután teljesen végrehajtasz egy manővert, ha van egy ellenséges hajó a %FRONTARC% tűzívedben 0-1 távolságban vagy a %BULLSEYEARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy levegyél 1 stressz jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """Amikor egy baráti hajó 0-2-es távolságban támadást hajt végre, ha a védekező benne van annak %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt, hogy átforgass 1 %FOCUS% eredményt %HIT% eredményre vagy 1 %HIT% eredményt %CRIT% eredményre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """Amikor egy baráti hajó 0-2-es távolságban védekezik, ha az nincs a támadó %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, forgass át 1 %CRIT% eredményt %HIT% eredményre vagy 1 %HIT% eredményt %FOCUS% eredményre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """Az Ütközet fázis elején elkölthetsz 1 %FORCE% jelzőt, hogy válassz egy másik baráti hajót 0-2-es távolságban. Ha így teszel, átadhatsz 1 zöld jelzőt neki vagy átvehetsz egy narancs jelzőt magadra.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"<NAME>":
text: """Miután egy baráti hajó 0-2-es távolságban felfedi a tárcsáját elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, állítsd át a tárcsáját egy másik hasonló sebességű és nehézségű manőverre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"M<NAME>":
text: """Miután teljesen végrehajtasz egy piros manővert, tölts vissza 1 %FORCE% jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
'"Kickback"':
text: """Miután végrehajtasz egy %BARRELROLL% akciót, végrehajthatsz egy piros %LOCK% akciót."""
'"Odd Ball"':
text: """Miután teljesen végrehajtasz egy piros manővert vagy piros akciót, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, feltehetsz egy bemérőt arra a hajóra."""
'"Sinker"':
text: """Amikor egy baráti hajó 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben elsődleges támadást hajt végre, újradobhat 1 támadókockát."""
'"Swoop"':
text: """Miután egy baráti kis vagy közepes hajó teljesen végrehajt egy 3-4 sebességű manővert, ha az 0-1-es távolságban van tőled, végrehajthat egy piros %BOOST% akciót."""
'"Axe"':
text: """Miután védekezel vagy támadást hajtasz végre, választhatsz egy baráti hajót 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben. Ha így teszel add át 1 zöld jelződet annak a hajónak."""
'"<NAME>"':
text: """Miután egy baráti hajó 1-2-es távolságban végrehajt egy támadást egy ellenséges hajó ellen a %FRONTARC% tűzívedben, végrehajthatsz egy %FOCUS% akciót."""
"<NAME>":
text: """Amikor ledobnál egy eszközt, ki is lőheted, ugyanazt a sablont használva. %LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"<NAME>":
text: """Miután védekeztél, ha a támadó benne van a tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy levedd egy kék vagy piros jelződ.%LINEBREAK% Miután végrehajtasz egy támadást ami talált, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy akciót."""
"0-66":
text: """Miután védekezel, elkölthetsz 1 %CALCULATE% jelzőt, hogy végrehajts egy akciót."""
"DFS-311":
text: """Az Üzközet fázis elején, átteheted 1 %CALCULATE% jelződet egy másik baráti hajóra 0-3-as távolságban. %LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
'"Odd Ball" (ARC-170)':
text: """Miután teljesen végrehajtasz egy piros manővert vagy piros akciót, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, feltehetsz egy bemérőt arra a hajóra."""
'"<NAME>"':
text: """Miután egy baráti hajó 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben védekezik, feltehetsz egy bemérőt a támadóra."""
'"<NAME>"':
text: """Amikor végrehajtasz egy elsődleges %FRONTARC% támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 támadókockát. %LINEBREAK% Amikor végrehajtasz egy elsődleges %REARARC% támadást, visszaállíthatsz 1 %CHARGE% jelzőt, hogy 1-gyel több támadókockával dobj"""
upgrade_translations =
"0-0-0":
display_name: """0-0-0"""
text: """<i>Söpredék vagy Darth Vader a csapatban</i>%LINEBREAK%Az Ütközet fázis elején, kiválaszthatsz 1 ellenséges hajót 0-1-es távolságban. Ha így teszel, kapsz egy kalkuláció jelzőt, hacsak a hajó nem választja, hogy kap 1 stressz jelzőt."""
"4-LOM":
display_name: """4-LOM"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, a támadókockák eldobása után, megnevezhetsz egy zöld jelző típust. Ha így teszel, kapsz 2 ion jelzőt és ezen támadás alatt a védekező nem költheti el a megnevezett típusú jelzőt."""
"Andrasta":
display_name: """And<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%<i>Kapott akció %RELOAD%</i>%LINEBREAK%Kapsz egy %DEVICE% fejlesztés helyet."""
"Dauntless":
display_name: """Da<NAME>"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután részlegesen hajtottál végre egy manővert, végrehajthatsz 1 fehér akciót pirosként kezelve."""
"Ghost":
display_name: """Ghost"""
text: """<i>csak Lázadók</i>%LINEBREAK%Bedokkoltathatsz 1 Attack shuttle-t vagy Sheathipede-class shuttle-t. A dokkolt hajót csak a hátsó pöcköktől dokkolhatod ki."""
"Havoc":
display_name: """H<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Elveszted a %CREW% fejlesztés helyet. Kapsz egy %SENSOR% és egy %ASTROMECH% fejlesztés helyet."""
"Hound's Tooth":
display_name: """Hound’s Tooth"""
text: """<i>csak Söpredék</i>%LINEBREAK%1 Z-95-AF4 headhunter bedokkolhat."""
"IG-2000":
display_name: """IG-2000"""
text: """<i>csak Söpredék</i>%LINEBREAK%Megkapod minden másik <strong>IG-2000</strong> fejlesztéssel felszerelt baráti hajó pilóraképességét."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges %REARARC% támadást, újradobhatsz 1 támadókockádat. Kapsz egy %GUNNER% fejlesztés helyet."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%<i>Kapott akció %EVADE%</i>%LINEBREAK%Amikor védekezel, ha van kitérés jelződ, újradobhatsz 1 védekezőkockát."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%<i>Kapott akció %BARRELROLL%</i>%LINEBREAK%Kapsz egy %CANNON% fejlesztés helyet."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók vagy Söpredék</i>%LINEBREAK%Kapsz egy %FRONTARC% elsődleges fegyvert 3-as támadóértékkel. A Vége fázis alatt megtarthatsz maximum 2 fókusz jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy támadást ami egy akadály által akadályozott, a védekező 1-gyel kevesebb védekezőkockával dob. Miután teljesen végrehajtasz egy manővert, ha áthaladtál vagy átfedésbe kerültél egy akadállyal, levehetsz 1 piros vagy narancs jelződet."""
"Phantom":
display_name: """Phantom"""
text: """<i>csak Lázadók</i>%LINEBREAK%Be tudsz dokkolni 0-1 távolságból."""
"Punishing One":
display_name: """Punishing One"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %FRONTARC% tűzívedben, dobj 1-gyel több támadókockával. Elveszted a %CREW% fejlesztés helyet. Kapsz egy %ASTROMECH% fejlesztés helyet."""
"ST-321":
display_name: """ST-321"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy %COORDINATE% akciót, kiválaszthatsz egy ellenséges hajót 0-3-as távolságban a koordinált hajótól. Ha így teszel, tegyél fel egy bemérőt arra az ellenséges hajóra figyelmen kívül hagyva a távolság megkötéseket."""
"Shadow Caster":
display_name: """Shadow Caster"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután végrehajtasz egy támadást ami talál, ha a védekező benne van a %SINGLETURRETARC% és %FRONTARC% tűzívedben is, a védekező kap 1 vonósugár jelzőt."""
"Slave I":
display_name: """Slave I"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután felfedtél egy kanyar (%TURNLEFT% vagy %TURNRIGHT%) vagy ív (%BANKLEFT% vagy %BANKRIGHT%) manővert, átforgathatod a tárcsádat az ellenkező irányba megtartva a sebességet és a mozgásformát. Kapsz egy %TORPEDO% fejlesztés helyet."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>Kapsz egy %MODIFICATION% fejlesztés helyet. Adj 1 pajzs értéket a hajódhoz.</i>%LINEBREAK%A Vége fázis alatt, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy piros %BOOST% akciót."""
"Ablative Plating":
display_name: """Ablative Plating"""
text: """<i>közepes vagy nagy talp</i>%LINEBREAK%Mielőtt sérülést szenvednél egy akadálytól vagy baráti bomba robbanástól, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, megakadályozol 1 sérülést."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután másik baráti hajó 0-3 távolságban védekezik, ha megsemmisül a támadó kap 2 stressz jelzőt. Amikor egy baráti hajó 0-3 távolságban végrehajt egy támadást egy stresszelt hajó ellen, 1 támadókockát újradobhat."""
"Adv. Proton Torpedoes":
display_name: """Adv. Proton Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong>Támadás (%LOCK%): Költs el 1 %CHARGE% jelzőt. Változtass 1 %HIT% eredményt %CRIT% eredményre."""
"Advanced SLAM":
display_name: """Advanced SLAM"""
text: """<i>Követelmény: %SLAM%</i>%LINEBREAK%Miután végrehajtasz egy %SLAM% akciót, ha teljesen végrehajtod azt a manővert, végrehajthatsz egy fehér akciót az akciósávodról pirosként kezelve."""
"Advanced Sensors":
display_name: """Advanced Sensors"""
text: """Miután felfeded a tárcsádat, végrehajthatsz 1 akciót. Ha így teszel, nem hajthatsz végre másik akciót a saját aktivációdban."""
"Afterburners":
display_name: """Afterburners"""
text: """<i>csak kis hajó</i>%LINEBREAK%Miután teljesen végrehajtasz egy 3-5 sebességű manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BOOST% akciót, még ha stresszes is vagy."""
"Agent <NAME>":
display_name: """<NAME> <NAME>"""
text: """<i>csak Birodalom</i>%LINEBREAK%<strong>Felhelyezés:</strong> rendelt hozzá a <strong>Hunted</strong> kondíciót 1 ellenséges hajóhoz. Amikor végrehajtasz egy támadást a <strong>Hunted</strong> kondícióval rendelkező hajó ellen, 1 %FOCUS% eredményed %HIT% eredményre változtathatod."""
"Agile Gunner":
display_name: """Agile Gunner"""
text: """A Vége fázisban elforgathatod a %SINGLETURRETARC% mutatódat."""
"BT-1":
display_name: """BT-1"""
text: """<i>Söpredék vagy <NAME> a csapatban</i>%LINEBREAK%Amikor végrehajtasz egy támadást, megváltoztathatsz 1 %HIT% eredményt %CRIT% eredményre minden stressz jelző után ami a védekezőnek van."""
"Barrage Rockets":
display_name: """Barrage Rockets"""
text: """<strong>Támadás (%FOCUS%):</strong> Költs el 1 %CHARGE% jelzőt. Ha a védekező benne van a %BULLSEYEARC% tűzívedben, elkölthetsz 1 vagy több %CHARGE% jelzőt, hogy újradobj azzal egyenlő számú támadókockát."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy %FOCUS% akciót, kezelheted pirosként. Ha így teszel minden egyes 0-1 távolságban lévő ellenséges hajó után kapsz 1 további fókusz jelzőt, de maximum 2 darabot."""
"Bistan":
display_name: """Bistan"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, ha van fókusz jelződ, végrehajthatsz egy bónusz %SINGLETURRETARC% támadást egy olyan hajó ellen, akit még nem támadtál ebben a körben."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> tartalékban kezdesz. A Felrakási fázis végén tedd a hajód 0 távolságra egy akadálytól, de 3-as távolságon túl az ellenséges hajóktól."""
"Bomblet Generator":
display_name: """Bomblet Generator"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobd a Bomblet bombát a [1 %STRAIGHT%] sablonnal. Az Aktivációs fázis elején elkölthetsz 1 pajzsot, hogy visszatölts 2 %CHARGE% jelzőt."""
"Bossk":
display_name: """Bossk"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást ami nem talál, ha nem vagy stresszes kapsz 1 stressz jelzőt, hogy végrehajts egy bónusz támadást ugyanazon célpont ellen."""
"C-3PO":
display_name: """C-3PO"""
text: """<i>Kapott akció: %CALCULATE%</i>%LINEBREAK%<i>csak Lázadók</i>%LINEBREAK%Védekezőkocka gurítás előtt, elkölthetsz 1 %CALCULATE% jelzőt hogy hangosan tippelhess egy 1 vagy nagyobb számra. Ha így teszel és pontosan annyi %EVADE% eredményt dobsz, adjál hozzá még 1 %EVADE% eredményt. Miután végrehajtasz a %CALCULATE% akciót, kapsz 1 %CALCULATE% jelzőt."""
"Cad Bane":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután ledobsz vagy kilősz egy eszközt, végrehajthatsz egy piros %BOOST% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%A Rendszer fázis alatt választhatsz 1 ellenséges hajót 1-2-es távolságban. Tippeld meg hangosan manővere irányát és sebességét, aztán nézd meg a tárcsáját. Ha az iránya és sebessége egyezik a tippeddel, megváltoztathatod a saját tárcsádat egy másik manőverre."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis elején elkölthetsz 2 %CHARGE% jelzőt, hogy megjavíts 1 felfordított sérülés kártyát."""
"<NAME> (Sc<NAME>)":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis elején elkölthetsz 1 %FOCUS% jelzőt, hogy megjavíts 1 felfordított sérülés kártyát."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>Követelmény %COORDINATE% vagy <r>%COORDINATE%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%Miután végrehajtasz egy %COORDINATE% akciót, ha a koordinált hajó végrehajt egy %BARRELROLL% vagy %BOOST% akciót, kaphat 1 stressz jelzőt, hogy elforduljon 90 fokot."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis alatt, választhatsz 2 %ILLICIT% fejlesztést ami baráti hajókra van felszerelve 0-1-es távolságban. Ha így teszel, megcserélheted ezeket a fejlesztéseket. A játék végén: tegyél vissza minden %ILLICIT% fejlesztést az eredeti hajójára."""
"Cloaking Device":
display_name: """Cloaking Device"""
text: """<i>kis vagy közepes talp</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy végrehajts egy %CLOAK% akciót. A tervezési fázis elején dobj 1 támadó kockával. %FOCUS% eredmény esetén hozd ki a hajód álcázásból vagy vedd le az álcázás jelzőt."""
"Cluster Missiles":
display_name: """Cluster Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Ezen támadás után végrehajthatod ezt a támadást, mint bónusz támadás egy másik célpont ellen 0-1 távolságra a védekezőtől, figyelmen kívül hagyva a %LOCK% követelményt."""
"Collision Detector":
display_name: """Collision Detector"""
text: """Amikor orsózol vagy gyorsítasz átmozoghatsz vagy rámozoghatsz akadályra. Miután átmozogtál vagy rámozogtál egy akadályra, elkölthetsz 1 %CHARGE% jelzőt, hogy figyelmen kívül hagyhatsd az akadály hatását a kör végéig."""
"Composure":
display_name: """Composure"""
text: """<i>Követelmény <r>%FOCUS%</r> vagy %FOCUS%</i>%LINEBREAK%Ha nem sikerül végrehajtani egy akciót és nincs zöld jelződ, végrehajthatsz egy %FOCUS% akciót."""
"Concussion Missiles":
display_name: """Concussion Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Ha a támadás talált, a védekezőtől 0-1 távolságban lévő minden hajó felfordítja egy sérülés kártyáját."""
"Conner Nets":
display_name: """Conner Nets"""
text: """<strong>Akna</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Conner Net aknát a [1 %STRAIGHT%] sablonnal. Ennak a kártyának a %CHARGE% jelzője <strong>nem</strong> újratölthető."""
"Contraband Cybernetics":
display_name: """Contraband Cybernetics"""
text: """Mielőtt aktiválódnál, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a kör végéig végrehajthatsz akciókat és piros manővereket, még stresszesen is."""
"Crack Shot":
display_name: """Crack Shot"""
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, még az <strong>Eredmények semlegesítése</strong> lépés előtt elkölthetsz 1 %CHARGE% jelzőt hogy hatástalaníts 1 %EVADE% eredményt."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>Követelmény %BOOST%</i>%LINEBREAK%<i>csak kis hajó</i>%LINEBREAK%Amikor végrehajtasz egy fehér %BOOST% akciót, kezelheted pirosként, hogy a [1 %TURNLEFT%] vagy [1 %TURNRIGHT%] sablokokat használhasd."""
"D<NAME>":
display_name: """<NAME>"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Ütközet fázis elején, válaszhatsz 1 hajót a tűzívedben 0-2-es távolságban és költs el 1 %FORCE% jelzőt. Ha így teszel, az a hajó elszenved 1 %HIT% sérülést, hacsak úgy nem dönt, hogy eldob 1 zöld jelzőt."""
"Deadman's Switch":
display_name: """Deadman’s Switch"""
text: """Miután megsemmisültél, minden hajó 0-1 távolságban elszenved 1 %HIT% sérülést."""
"Death Troopers":
display_name: """Death Troopers"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Aktivációs fázis alatt az ellenséges hajók 0-1-es távolságban nem vehetik le a stressz jelzőjüket."""
"Debris Gambit":
display_name: """Debr<NAME> G<NAME>bit"""
text: """<i>Kapott akció: <r>%EVADE%</r></i>%LINEBREAK%<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor végrehajtasz egy piros %EVADE% akciót, ha van 0-1-es távolságban egy akadály, kezeld az akciót fehérként."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután védekezel, ha a támadó a tűzívedben van, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, dobj 1 támadókockával, hacsak a támadó úgy nem dönt, hogy eldobja 1 zöld jelzőjét. %HIT% vagy %CRIT% eredmény esetén a támadó elszenved 1 %HIT% sérülést."""
"Director <NAME>":
display_name: """<NAME> <NAME>"""
text: """<i>Kapott akció %LOCK%</i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%<strong>Felhelyezés:</strong> a hajók felhelyezése előtt, rendeld hozzá az <strong>Optimized Prototype</strong> kondíciót egy másik baráti hajóhoz."""
"Dorsal Turret":
display_name: """<NAME> Turret"""
text: """<i>Kapott akció %ROTATEARC%</i>%LINEBREAK%<strong>Támadás</strong>"""
"Electronic Baffle":
display_name: """Electronic Baffle"""
text: """A Vége fázis alatt, elszenvedhetsz 1 %HIT% sérülést, hogy levegyél 1 piros jelzőt."""
"Elusive":
display_name: """<NAME>"""
text: """<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor védekezel, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 védekezőkockát. Miután teljesen végrehajtasz egy piros manővert, visszatölthetsz 1 %CHARGE% jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor egy másik baráti hajó védekezik vagy végrehajt egy támadást, elkölthetsz 1 %FORCE% jelzőt, hogy módosít annak 1 kockáját úgy, mintha az a hajó költött volna el 1 %FORCE% jelzőt."""
"Engine Upgrade":
display_name: """Engine Upgrade"""
text: """<i>Kapott akció %BOOST%</i>%LINEBREAK%<i>Követelmény <r>%BOOST%</r></i>%LINEBREAK%<i class = flavor_text>Ennek a fejlesztésnek változó a költsége. 3, 6 vagy 9 pont attól függően, hogy kis, közepes vagy nagy talpú hajóra tesszük fel.</i>"""
"Expert Handling":
display_name: """Expert Handling"""
text: """<i>Kapott akció %BARRELROLL%</i>%LINEBREAK%<i>Követelmény <r>%BARRELROLL%</r></i>%LINEBREAK%<i class = flavor_text>Ennek a fejlesztésnek változó a költsége. 2, 4 vagy 6 pont attól függően, hogy kis, közepes vagy nagy talpú hajóra tesszük fel.</i>"""
"Ezra Bridger":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy bónusz %SINGLETURRETARC% támadást egy olyan %SINGLETURRETARC% fegyverrel, amivel még nem támadtál ebben a körben. Ha így teszel és stresszes vagy, újradobhatsz 1 támadókockát."""
"Fearless":
display_name: """Fearless"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy %FRONTARC% elsődleges támadást, ha a támadási távolság 1 és benne vagy a védekező %FRONTARC% tűzívében, megváltoztathatsz 1 eredményedet %HIT% eredményre."""
"Feedback Array":
display_name: """Feedback Array"""
text: """Mielőtt sor kerül rád az Üzközet fázisban, kaphatsz 1 ion jelzőt és 1 'inaktív fegyverzet' jelzőt. Ha így teszel, minden hajó 0-ás távolságban elszenved 1 %HIT% sérülést."""
"Fifth Brother":
display_name: """Fifth Brother"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elkölthetsz 1 %FORCE% jelzőt, hogy megváltoztass 1 %FOCUS% eredményed %CRIT% eredményre."""
"Fire-Control System":
display_name: """Fire-Control System"""
text: """Amikor végrehajtasz egy támadást, ha van bemérőd a védekezőn, újradobhatod 1 támadókockádat. Ha így teszel, nem költheted el a bemérődet ebben a támadásban."""
"Freelance Slicer":
display_name: """Freelance Slicer"""
text: """Amikor védekezel, mielőtt a támadó kockákat eldobnák, elköltheted a támadón lévő bemérődet, hogy dobj 1 támadókockával. Ha így teszel, a támadó kap 1 zavarás jelzőt. Majd %HIT% vagy %CRIT% eredménynél te is kapsz 1 zavarás jelzőt."""
'GNK "Gonk" Droid':
display_name: """GNK “Gonk” Droid"""
text: """<strong>Felhelyezés:</strong> Elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<strong>Akció:</strong> tölts vissza 1 %CHARGE% jelzőt. <strong>Akció:</strong>: költs el 1 %CHARGE% jelzőt, hogy visszatölts egy pajzsot."""
"Grand Inquisitor":
display_name: """Grand Inquisitor"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután egy ellenséges hajó 0-2-es távolságban felfedi a tárcsáját, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts 1 fehér akciót az akciósávodról, pirosként kezelve azt."""
"Grand Moff Tarkin":
display_name: """Grand Moff Tarkin"""
text: """<i>Követelmény %LOCK% vagy <r>%LOCK%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%A Rendszer fázis alatt elkölthetsz 2 %CHARGE% jelzőt. Ha így teszel, minden baráti hajó kap egy bemérőt arra a hajóra, amit te is bemértél."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy megváltoztass 1 %HIT% eredméynyt %CRIT% eredményre. Amikor védekezel, ha a %CHARGE% jelződ aktív, a támadó megváltoztathat 1 %HIT% eredméynyt %CRIT% eredményre."""
"Han Solo":
display_name: """Han Solo"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis alatt, 7-es kezdeményezésnél, végrehajthatsz egy %SINGLETURRETARC% támadást. Nem támadhatsz újra ezzel a %SINGLETURRETARC% fegyverrel ebben a körben."""
"Han Solo (Scum)":
display_name: """Han Solo"""
text: """<i>csak Söpredék</i>%LINEBREAK%Mielőtt sor kerül rád az Üzközet fázisban, végrehajthatsz egy piros %FOCUS% akciót."""
"Heavy Laser Cannon":
display_name: """Heavy Laser Cannon"""
text: """<strong>Támadás:</strong> a <strong>Támadókockák módosítása</strong> lépés után változtasd az összes %CRIT% eredményt %HIT% eredményre."""
"Heightened Perception":
display_name: """Heightened Perception"""
text: """Az Ütközet fázis elején, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, 7-es kezdeményezéssel kerülsz sorra ebben a fázisban a rendes kezdeményezésed helyett."""
"Hera Syndulla":
display_name: """Hera Syndulla"""
text: """<i>csak Lázadók</i>%LINEBREAK%Stresszesen is végrehajthatsz piros manővert. Miután teljesen végrehajtasz egy piros manővert, ha 3 vagy több stressz jelződ van, vegyél le egy stressz jelzőt és szenvedj el 1 %HIT% sérülést."""
"Homing Missiles":
display_name: """Homing Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Miután kijelölted a védekezőt, a védekező dönthet úgy, hogy elszenved 1 %HIT% sérülést. Ha így tesz, ugorjátok át a <strong>Támadó és védekező kockák</strong> lépést és a támadást találtnak kezeljétek."""
"Hotshot Gunner":
display_name: """Hotshot Gunner"""
text: """Amikor végrehajtasz egy %SINGLETURRETARC% támadást, a <strong>Védekezőkockák módosítása</strong> lépés után a védekező dobja el 1 fókusz vagy kalkuláció jelzőjét."""
"Hull Upgrade":
display_name: """Hull Upgrade"""
text: """Adj 1 szerkezeti értéket a hajódhoz.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 2, 3, 5 vagy 7 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"IG-88D":
display_name: """IG-88D"""
text: """<i>Kapott akció %CALCULATE%</i>%LINEBREAK%<i>csak Söpredék</i>%LINEBREAK%Megkapod minden <strong>IG-2000</strong> fejlesztéssel felszerelt baráti hajó pilóraképességét. Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"ISB Slicer":
display_name: """ISB Slicer"""
text: """<i>csak Birodalom</i>%LINEBREAK%A Vége fázis alatt az ellenséges hajók 1-2-es távban nem vehetik le a zavarás jelzőket."""
"Inertial Dampeners":
display_name: """Inertial Dampeners"""
text: """Mielőtt végrehajtanál egy manővert, elkölthetsz 1 pajzsot. Ha így teszel, hajts végre egy fehér [0 %STOP%] manővert a tárcsázott helyett, aztán kapsz 1 stressz jelzőt."""
"Informant":
display_name: """Informant"""
text: """<strong>Felhelyezés:</strong> a hajók felhelyezése után válassz 1 ellenséges hajót és rendeld hozzá a <strong>Listening Device</strong> kondíciót."""
"Instinctive Aim":
display_name: """Instinctive Aim"""
text: """Amikor végrehajtasz egy speciális támadást, elkölthetsz 1 %FORCE% jelzőt, hogy figyelmen kívül hagyhatsd a %FOCUS% vagy %LOCK% követelményt."""
"Intimidation":
display_name: """Intimidation"""
text: """Amikor egy ellenséges hajó 0-ás távolságban védekezik, 1-gyel kevesebb védekezőkockával dob."""
"Ion Cannon":
display_name: """Ion Cannon"""
text: """<strong>Támadás:</strong> ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Cannon Turret":
display_name: """Ion Cannon Turret"""
text: """<i>Kapott akció %ROTATEARC%</i>%LINEBREAK%<strong>Támadás:</strong> ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Missiles":
display_name: """Ion Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Torpedoes":
display_name: """Ion Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak S<NAME>predék</i>%LINEBREAK%A Vége fázis alatt, kiválaszthatsz 1 baráti hajót 0-2-es távolságban, majd költs el 1 %CHARGE% jelzőt. Ha így teszel, a kiválasztott hajó visszatölthet 1 %CHARGE% jelzőt 1 felszerelt %ILLICIT% fejlesztésén."""
"<NAME>":
display_name: """<NAME>"""
text: """<strong>Támadás:</strong> ha a támadás talált, minden %HIT%/%CRIT% eredmény után sérülés helyett zavarás jelzőt kap a védekező."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor végrehajtasz egy támadást, ha van kitérés jelződ, megváltoztathatod a védekező 1 %EVADE% eredményét %FOCUS% eredményre."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Ha egy baráti hajó 0-3 távolságban fókusz jelzőt kapna, helyette kaphat 1 kitérés jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak <NAME>ázadók</i>%LINEBREAK%Miután egy baráti hajó 0-2-es távolságban teljesen végrehajt egy fehér manővert, elkölthetsz 1 %FORCE% jelzőt, hogy levegyél róla 1 stressz jelzőt."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis elején, kiválaszthatsz 1 ellenséges hajót 0-2-es távolságban a tűzívedben. Ha így teszel, aza a hajó nem veheti le a vonósugár jelzőit."""
"L3-37":
display_name: """L3-37"""
text: """<i>cs<NAME> Söpred<NAME></i>%LINEBREAK%<strong>Felhelyezés:</strong> felfordítva szereld fel ezt a kártyát. Amikor védekezel, lefordíthatod ezt a kártyát. Ha így teszel, a támadónak újra kell dobnia az összes támadókockát.%LINEBREAK%<i>L3-37 programja:</i> Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>cs<NAME></i>%LINEBREAK%<strong>Akció:</strong> dobj 2 védekezőkockával. Minden egyes %FOCUS% eredmény után kapsz 1 fókusz jelzőt. Minden egyes %EVADE% eredmény után kapsz 1 kitérés jelzőt. Ha mindkettő eredmény üres, az ellenfeled választ, hogy fókusz vagy kitérés. Kapsz 1, a választásnak megfelelő jelzőt."""
"<NAME> (Scum)":
display_name: """<NAME>"""
text: """<i>csak <NAME>öpredék</i>%LINEBREAK%Kockadobás után elkölthetsz 1 zöld jelzőt, hogy újradobj 2 kockádat."""
"Lando's Millennium Falcon":
display_name: """L<NAME>’s Millennium Falcon"""
text: """<i>csak Söpredék</i>%LINEBREAK%1 Escape Craft be lehet dokkolva. Amikor egy Escape Craft be van dokkolva, elköltheted a pajzsait, mintha a te hajódon lenne. Amikor végrehajtasz egy elsődleges támadást stresszelt hajó ellen, dobj 1-gyel több támadókockával."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor védekezel, ha a támadó stresszelt, levehetsz 1 stressz jelzőt a támadóról, hogy megváltoztass 1 üres/%FOCUS% eredményed %EVADE% eredményre."""
"Le<NAME>ana":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Aktivációs fázis elején, elkölthetsz 3 %CHARGE% jelzőt. Ezen fázis alatt minden baráti hajó csökkentse a piros manőverei nehézségét."""
"L<NAME>":
display_name: """<NAME>"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha nincs másik baráti hajó 0-2-es távolságban, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 kockádat."""
"Lu<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis elején, elkölthetsz 1 %FORCE% jelzőt, hogy forgasd a %SINGLETURRETARC% mutatódat."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután védekezel, ha a támadás talált, feltehetsz egy bemérőt a támadóra."""
"<NAME>":
display_name: """<NAME>"""
text: """Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, megváltoztathatsz 1 %HIT% eredményt %CRIT% eredményre."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>Söpredék vagy <NAME> a csapatban</i>%LINEBREAK%Miután sérülést szenvedsz, kaphatsz 1 stressz jelzőt, hogy visszatölts 1 %FORCE% jelzőt. Felszerelhetsz <strong>Dark Side</strong> fejlesztéseket."""
"Min<NAME>ua":
display_name: """<NAME>"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Ütközet fázis elején, ha sérült vagy, végrehajthatsz egy piros %REINFORCE% akciót."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>Követelmény: %COORDINATE% vagy <r>%COORDINATE%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%A Rendszer fázis alatt, elkölthetsz 2 %CHARGE% jelzőt. Ha így teszel, válassz a [1 %BANKLEFT%], [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] sablonokból. Minden baráti hajó végrehajthat egy piros %BOOST% akciót a kiválasztott sablonnal."""
"Munitions Failsafe":
display_name: """Munitions Failsafe"""
text: """Amikor végrehajtasz egy %TORPEDO% vagy %MISSILE% támadást, a támadókockák eldobása után, elvetheted az összes kocka eredményed, hogy visszatölts 1 %CHARGE% jelzőt, amit a támadáshoz elköltöttél."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Lázadók</i>%LINEBREAK%Csökkentsd az íves manőverek [%BANKLEFT% és %BANKRIGHT%] nehézségét."""
"Novice Technician":
display_name: """Novice Technician"""
text: """A kör végén dobhatsz 1 támadó kockával, hogy megjavíts egy felfordított sérülés kártyát. %HIT% eredménynél, fordíts fel egy sérülés kártyát."""
"Os-1 Arsenal Loadout":
display_name: """Os-1 Arsenal Loadout"""
text: """<i>Kapsz egy %TORPEDO% és egy %MISSILE% fejlesztés helyet.</i>%LINEBREAK%Amikor pontosan 1 'inaktív fegyverzet' jelződ van, akkor is végre tudsz hajtani %TORPEDO% és %MISSILE% támadást bemért célpontok ellen. Ha így teszel, nem használhatod el a bemérődet a támadás alatt."""
"Outmaneuver":
display_name: """Outmaneuver"""
text: """Amikor végrehajtasz egy %FRONTARC% támadást, ha nem vagy a védekező tűzívében, a védekező 1-gyel kevesebb védekezőkockával dob."""
"Perceptive Copilot":
display_name: """Perceptive Copilot"""
text: """Miután végrehajtasz egy %FOCUS% akciót, kapsz 1 fókusz jelzőt."""
"Pivot Wing":
display_name: """Pivot Wing"""
text: """<strong>Csukva: </strong>Amikor védekezel, 1-gyel kevesebb védekezőkockával dobsz. Miután végrehajtasz egy [0 %STOP%] manővert, elforgathatod a hajód 90 vagy 180 fokkal. Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK%<strong>Nyitva:</Strong> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Predator":
display_name: """Predator"""
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, újradobhatsz 1 támadókockát."""
"Proton Bombs":
display_name: """Proton Bombs"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy kidobj egy Proton bombát az [1 %STRAIGHT%] sablonnal."""
"Proton Rockets":
display_name: """Proton Rockets"""
text: """<strong>Támadás (%FOCUS%):</strong> költs el 1 %CHARGE% jelzőt."""
"Proton Torpedoes":
display_name: """Proton Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. Változtass 1 %HIT% eredményt %CRIT% eredményre."""
"Proximity Mines":
display_name: """Proximity Mines"""
text: """<strong>Akna</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Proximity aknát az [1 %STRAIGHT%] sablonnal. Ennak a kártyának a %CHARGE% jelzője <strong>nem</strong> újratölthető."""
"Qi'ra":
display_name: """Qi’ra"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor mozogsz vagy támadást hajtasz végre, figyelmen kívül hagyhatod az összes akadályt, amit bemértél."""
"R2 Astromech":
display_name: """R2 Astromech"""
text: """Miután felfeded a tárcsád, elkölthetsz 1 %CHARGE% jelzőt és kapsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts egy pajzsot."""
"R2-D2 (Crew)":
display_name: """R2-D2"""
text: """<i>csak Lázadók</i>%LINEBREAK%A Vége fázis alatt, ha sérült vagy és nincs pajzsod, dobhatsz 1 támadókockával, hogy visszatölts 1 pajzsot. %HIT% eredménynél fordíts fel 1 sérüléskártyát."""
"R2-D2":
display_name: """R2-D2"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután felfeded a tárcsád, elkölthetsz 1 %CHARGE% jelzőt és kapsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts egy pajzsot."""
"R3 Astromech":
display_name: """R3 Astromech"""
text: """Fenntarthatsz 2 bemérőt. Mindegyik bemérő más célponton kell legyen. Miután végrehajtasz egy %LOCK% akciót, feltehetsz egy bemérőt."""
"R4 Astromech":
display_name: """R4 Astromech"""
text: """<i>csak kis hajó</i>%LINEBREAK%Csökkentsd a nehézségét az 1-2 sebességű alapmanővereidnek (%TURNLEFT%, %BANKLEFT%, %STRAIGHT%, %BANKRIGHT%, %TURNRIGHT%)."""
"R5 Astromech":
display_name: """R5 Astromech"""
text: """<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy megjavíts egy lefordított sérülés kártyát.%LINEBREAK%<strong>Akció:</strong> javíts meg 1 felfordított <strong>Ship</strong> sérülés kártyát."""
"R5-D8":
display_name: """R5-D8"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy megjavíts egy lefordított sérülés kártyát.%LINEBREAK%<strong>Akció:</strong> javíts meg 1 felfordított <strong>Ship</strong> sérülés kártyát."""
"R5-P8":
display_name: """R5-P8"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást a %FRONTARC% tűzívedben lévő védekező ellen, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 támadókockát. Ha az újradobott eredmény %CRIT%, szenvedj el 1 %CRIT% sérülést."""
"R5-TK":
display_name: """R5-TK"""
text: """<i>csak Söpredék</i>%LINEBREAK%Végrehajthatsz támadást baráti hajó ellen."""
"R<NAME> C<NAME> Chute":
display_name: """R<NAME>"""
text: """<i>csak közepes vagy nagy hajó</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt. Dobj ki 1 rakomány jelzőt az [1 %STRAIGHT%] sablonnal."""
"R<NAME>":
display_name: """R<NAME>"""
text: """<i>cs<NAME></i>%LINEBREAK%Amikor végrehajtasz egy támadást, kiválaszthatsz másik baráti hajót 0-1-es távolságra a védekezőtől. Ha így teszel, a kiválasztott hajó elszenved 1 %HIT% sérülést és te megváltoztathatsz 1 kocka eredményed %HIT% eredményre."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Láz<NAME>ók</i>%LINEBREAK%<strong>Felhelyezés:</strong> tegyél fel 1 ion, 1 zavarás, 1 stressz és 1 vonósugár jelzőt erre a kártyára. Miután egy hajó sérülést szenved egy baráti bombától, levehetsz 1 ion, 1 zavarás, 1 stressz vagy 1 vonósugár jelzőt erről a kártyáról. Ha így teszel, az a hajó megkapja ezt a jelzőt."""
"Saturation Salvo":
display_name: """Saturation Salvo"""
text: """<i>Követelmény %RELOAD% vagy <r>%RELOAD%</r></i>%LINEBREAK%Amikor végrehajtasz egy %TORPEDO% vagy %MISSILE% támadást, elkölthetsz 1 %CHARGE% jelzőt arról a kártyától. Ha így teszel, válassz 2 védekezőkockát. A védekezőnek újra kell dobnia azokat a kockákat."""
"Saw Gerrera":
display_name: """Saw Gerrera"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elszenvedhetsz 1 %HIT% sérülést, hogy megváltoztasd az összes %FOCUS% eredményed %CRIT% eredményre."""
"Seasoned Navigator":
display_name: """Seasoned Navigator"""
text: """Miután felfedted a tárcsádat, átállíthatod egy másik nem piros manőverre ugyanazon sebességen. Amikor végrehajtod azt a manővert növeld meg a nehézségét."""
"Seismic Charges":
display_name: """Seismic Charges"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Seismic Charge bombát az [1 %STRAIGHT%] sablonnal."""
"Selfless":
display_name: """Selfless"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor másik baráti hajó 0-1-es távolságban védekezik, az <strong>Eredmények semlegesítése</strong> lépés előtt, ha benne vagy a támadási tűzívben, elszenvedhetsz 1 %CRIT% sérülést, hogy semlegesíts 1 %CRIT% eredményt."""
"Sense":
display_name: """Sense"""
text: """A Rendszer fázis alatt kiválaszthatsz 1 hajót 0-1-es távolságban és megnézheted a tárcsáját. Ha elköltesz 1 %FORCE% jelzőt választhatsz 0-3-as távolságból hajót."""
"Servomotor S-Foils":
display_name: """Servomotor S-foils"""
text: """<strong>Csukva: </strong><i>Kapott akciók: %BOOST% , %FOCUS% <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> <r>%BOOST%</r></i>%LINEBREAK% Amikor végrehajtasz egy elsődleges támadást, 1-gyel kevesebb támadókockával dobj.%LINEBREAK%Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK%<strong>Nyitva:</strong> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Seventh Sister":
display_name: """Seventh Sister"""
text: """<i>csak Birodalom</i>%LINEBREAK%Ha egy ellenséges hajó 0-1-es távolságra egy stressz jelzőt kapna, elkölthetsz 1 %FORCE% jelzőt, hogy 1 zavarás vagy vonósugár jelzőt kapjon helyette."""
"Shield Upgrade":
display_name: """Shield Upgrade"""
text: """Adj 1 pajzs értéket a hajódhoz.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 3, 4, 6 vagy 8 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"Skilled Bombardier":
display_name: """Skilled Bombardier"""
text: """Ha ledobsz vagy kilősz egy eszközt, megegyező irányban használhatsz 1-gyel nagyob vagy kisebb sablont."""
"Squad Leader":
display_name: """Squad Leader"""
text: """<i>Kapott akció <r>%COORDINATE%</r></i>%LINEBREAK%WAmikor koordinálsz, a kiválasztott hajó csak olyan akciót hajthat végre, ami a te akciósávodon is rajta van."""
"Static Discharge Vanes":
display_name: """Static Discharge Vanes"""
text: """Mielőtt kapnál 1 ion vagy zavarás jelzőt, ha nem vagy stresszes, választhatsz egy másik hajót 0-1-es távolságban és kapsz 1 stressz jelzőt. Ha így teszel, a kiválasztott hajó kapja meg az ion vagy zavarás jelzőt helyetted."""
"Stealth Device":
display_name: """Stealth Device"""
text: """Amikor védekezel, ha a %CHARGE% jelződ aktív, dobj 1-gyel több védekezőkockával. Miután elszenvedsz egy sérülés, elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 3, 4, 6 vagy 8 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"Supernatural Reflexes":
display_name: """Supernatural Reflexes"""
text: """<i>csak kis hajó</i>%LINEBREAK%Mielőtt aktiválódsz, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BARRELROLL% vagy %BOOST% akciót. Ha olyan akciót hajtottál végre, ami nincs az akciósávodon, elszenvedsz 1 %HIT% sérülést."""
"Swarm Tactics":
display_name: """Swarm Tactics"""
text: """Az ütközet fázis elején, kiválaszthatsz 1 baráti hajót 1-es távolságban. Ha így teszel, az a hajó a kör végéig kezelje úgy a kezdeményezés értékét, mintha egyenlő lenne a tiéddel."""
"Tactical Officer":
display_name: """Tactical Officer"""
text: """<i>Kapott akció: %COORDINATE%</i>%LINEBREAK%<i>Követelmény: <r>%COORDINATE%</r></i>"""
"Tactical Scrambler":
display_name: """Tactical Scrambler"""
text: """<i>csak közepes vagy nagy hajó</i>%LINEBREAK%Amikor akadályozod egy ellenséges hajó támadását, a védekező 1-gyel több védekezőkockával dob."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> a hajók felhelyezése után, kiválaszthatsz 1 akadályt a pályáról. Ha így teszel, helyezd át bárhová 2-es távolságra a szélektől vagy hajóktól és 1-es távolságra más akadályoktól."""
"Tractor Beam":
display_name: """Tractor Beam"""
text: """<strong>Támadás:</strong> ha a támadás talált, minden %HIT%/%CRIT% eredmény után sérülés helyett vonósugár jelzőt kap a védekező."""
"Trajectory Simulator":
display_name: """Trajectory Simulator"""
text: """A Rendszer fázis alatt, ha ledobsz vagy kilősz egy bombát, kilőheted a [5 %STRAIGHT%] sablonnal."""
"Trick Shot":
display_name: """Trick Shot"""
text: """Amikor végrehajtasz egy támadást ami akadályozott egy akadály által, dobj 1-gyel több támadókockával."""
"Unkar Plutt":
display_name: """Unkar Plutt"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután részlegesen végrehajtasz egy manővert, elszenvedhetsz 1 %HIT% sérülést, hogy végrehajts 1 fehér akciót."""
"Veteran Tail Gunner":
display_name: """Veteran Tail Gunner"""
text: """<i>Követelmény: %REARARC%</i> %LINEBREAK%Miután végrehajtasz egy elsődleges %FRONTARC% támadást, végrehajthatsz egy bónusz elsődleges %REARARC% támadást."""
"Veteran Turret Gunner":
display_name: """Veteran Turret Gunner"""
text: """<i>Követelmény: %ROTATEARC% vagy <r>%ROTATEARC%</r></i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, végrehajthatsz egy bónusz %SINGLETURRETARC% támadást egy olyan %SINGLETURRETARC% tűzívben, amiből még nem támadtál ebben a körben."""
"Xg-1 Assault Configuration":
display_name: """Xg-1 Assault Configuration"""
text: """Amikor pontosan 1 'inaktív fegyverzet' jelződ van, akkor is végrehajthatsz %CANNON% támadást. Amikor %CANNON% támadást hajtasz végre 'inaktív fegyverzet' jelzővel, maximum 3 támadókockával dobhatsz.%LINEBREAK%Kapsz egy %CANNON% fejlesztés helyet."""
"<NAME>":
display_name: """<NAME>"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, ha nem vagy stresszes, válaszhatsz 1 védekezőkockát és kapsz 1 stressz jelzőt. Ha így teszel, a védekezőnek újra kell dobnia azt a kockát."""
'"<NAME>" (Crew)':
display_name: """“<NAME>”"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az <strong>Akció végrehajtása</strong> lépés közben még stresszesen is végrehajthatsz 1 akciót. Miután stresszesen végrehajtasz egy akciót szenvedj el 1 %HIT% sérülést vagy fordítsd fel 1 sérülés kártyád."""
'"<NAME>" (Astromech)':
display_name: """“<NAME>”"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 nem-újratölthető %CHARGE% jelzőt egy másik felszerelt fejlesztésről, hogy visszatölts 1 pajzsot%LINEBREAK%<strong>Akció:</strong> költs el 2 pajzsot, hogy visszatölts 1 nem-újratölthető %CHARGE% jelzőt egy felszerelt fejlesztésen."""
'"Genius"':
display_name: """“Genius”"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután teljesen végrehajtasz egy manővert, ha még nem dobtál vagy lőttél ki eszközt ebben a körben, kidobhatsz 1 bombát."""
'"Zeb" Orrelios':
display_name: """“Zeb” Orrelios"""
text: """<i>csak Lázadók</i>%LINEBREAK%Végrehajthatsz elsődleges támadást 0-ás távolságban. Az ellenséges hajók 0-ás távolságban végrehajthatnak elsődleges támadást ellened."""
"Hardpoint: Cannon":
text: """Kapsz egy %CANNON% fejlesztés helyet."""
"Hardpoint: Missile":
text: """Kapsz egy %MISSILE% fejlesztés helyet."""
"Hardpoint: Torpedo":
text: """Kapsz egy %TORPEDO% fejlesztés helyet."""
"Black One":
text: """<i>Kapott akció: %SLAM%</i> %LINEBREAK% Miután végrehajtasz egy %SLAM% akciót, elvesztesz 1 %CHARGE% jelzőt. Ezután kaphatsz 1 ion jelzőt, hogy levedd az inaktív fegyverzet jelzőt. Ha a %CHARGE% nem aktív, nem hajthatsz végre %SLAM% akciót."""
"Heroic":
text: """<i>csak Ellenállás</i><br>Amikor védekezel vagy támadást hajtasz végre, ha 2 vagy több csak üres eredményed van, újradobhatsz akárhány kockát."""
"<NAME>":
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz egy dobás eredményed, hogy bemérőt rakj az ellenséges hajóra."""
"<NAME>":
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre,ha az ellenséges hajó a %FRONTARC% tűzívedben van, hozzáadhatsz 1 üres eredményt a dobásodhoz (ez a kocka újradobható vagy módosítható)."""
"Integrated S-Foils":
text: """<strong>Csukva: </strong><i>Kapott akció %BARRELROLL%, %FOCUS% <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> <r>%BARRELROLL%</r></i>%LINEBREAK% Amikor végrehajtasz egy elsődleges támadást, ha a védekező nincs a %BULLSEYEARC% tűzívedben, 1-gyel kevesebb támadókockával dobj. Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK% <b>Nyitva:</b> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Targeting Synchronizer":
text: """<i>Követelmény: %LOCK%</i> %LINEBREAK% Amikor egy baráti hajó 1-2-es távolságban végrehajt egy támadást olyan célpont ellen, amit már bemértél, az a hajó figyelmen kívül hagyhatja a %LOCK% támadási követelményt."""
"Primed Thrusters":
text: """<i>csak kis hajó</i> %LINEBREAK%Amikor 2 vagy kevesebb stressz jelződ van, végrehajthatsz %BARRELROLL% és %BOOST% akciót még ha stresszes is vagy."""
"<NAME>":
text: """<strong>Akció: </strong> Válassz 1 ellenséges hajót 1-3-as távolságban. Ha így teszel, költs el 1 %FORCE% jelzőt, hogy hozzárendeled az <strong>I'll Show You the Dark Side</strong> kondíciós kártyát a kiválasztott hajóhoz."""
"General Hux":
text: """Amikor végrehajtasz egy fehér %COORDINATE% akciót, kezelheted pirosként. Ha így teszel, koordinálhatsz további 2 azonos típusú hajót, mindegyikét azonos akcióval és pirosként kezelve."""
"Fanatical":
text: """Amikor végrehajtasz egy elsődleges támadást, ha nincs pajzsod, megváltoztathatsz 1 %FOCUS% eredményt %HIT% eredményre."""
"Special Forces Gunner":
text: """Amikor végrehajtasz egy elsődleges %FRONTARC% támadást, ha a %SINGLETURRETARC% tűzíved a %FRONTARC% tűzívedben van, 1-gyel több kockával dobhatsz. Miután végrehajtasz egy elsődleges %FRONTARC% támadást, ha a %SINGLETURRETARC% tűzíved a %REARARC% tűzívedben van, végrehajthatsz egy bónusz elsődleges %SINGLETURRETARC% támadást."""
"Captain Phasma":
text: """Az Ütközet fázis végén, minden 0-1 távolságban lévő ellenséges hajó ami nem stresszes, kap 1 stressz jelzőt."""
"Supreme Leader Snoke":
text: """A Rendszer fázis alatt kiválaszthatsz bármennyi hajót 1-es távolságon túl. Ha így teszel költs el annyi %FORCE% jelzőt, amennyi hajót kiválasztottál, hogy felfordítsd a tárcsájukat."""
"Hyperspace Tracking Data":
text: """<strong>Felhelyezés:</strong> a hajó felhelyezés előtt válassz egy számot 0 és 6 között. Kezeld a Initiative-od a kiválasztott számnak megfelelően. A felhelyezés után rendelj hozzá 1 %FOCUS% vagy %EVADE% jelzőt minden baráti hajóra 0-2-es távolságban."""
"Advanced Optics":
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %FOCUS% jelzőt, hogy 1 üres eredményed %HIT% eredményre változtass."""
"Rey":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy 1 üres eredményed %EVADE% vagy %HIT% eredményre változtass."""
"Chewbacca (Resistance)":
text: """<strong>Felhelyezés:</strong>: elvesztesz el 1 %CHARGE% jelzőt. %LINEBREAK% Miután egy baráti hajó 0-3-as távolságban felhúz 1 sérülés kártyát, állítsd helyre 1 %CHARGE% jelzőt. Amikor támadást hajtasz végre elkölthetsz 2 %CHARGE% jelzőt, hogy 1 %FOCUS% eredményed %CRIT% eredményre változtass."""
"<NAME>":
text: """Miután véggrehajtasz egy elsődleges támadást, ledobhatsz egy bombát vagy forgathatod a %SINGLETURRETARC% tűzívedet. Miután megsemmisültél ledobhatsz 1 bombát."""
"R2-HA":
text: """Amikor védekezel, elköltheted a támadón lévő bemérődet, hogy újradobd bármennyi védőkockádat."""
"C-3PO (Resistance)":
text: """ <i>Kapott akció: %CALCULATE% <r>%COORDINATE%</r></i> %LINEBREAK% Amikor koordinálsz, választhatsz baráti hajót 2-es távolságon túl, ha annak van %CALCULATE% akciója. Miután végrehajtod a %CALCULATE% vagy %COORDINATE% akciót, kapsz 1 %CALCULATE% jelzőt."""
"Han Solo (Resistance)":
text: """ <i>Kapott akció: <r>%EVADE%</r></i> %LINEBREAK%Miután végrehajtasz egy %EVADE% akciót, annyival több %EVADE% jelzőt kapsz, ahány ellenséges hajó van 0-1-es távolságban."""
"Rey's Millennium Falcon":
text: """Ha 2 vagy kevesebb stressz jelződ van, végrehajthatsz piros Segnor Csavar manővert [%SLOOPLEFT% vagy %SLOOPRIGHT%] és végrehajthatsz %BOOST% és %ROTATEARC% akciókat, még ha stresszes is vagy."""
"<NAME>":
text: """Az Aktivációs vagy Ütközet fázis közben, miután egy ellenséges hajó a %FRONTARC% tűzívedben 0-1-es távolságban kap egy piros vagy narancs jelzőt, ha nem vagy stresszes, kaphatsz egy stressz jelzőt. Ha így teszel, az a hajó kap még egy jelzőt abból, amit kapott."""
"BB-8":
text: """Mielőtt végrehajtasz egy kék manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BARRELROLL% vagy %BOOST% akciót."""
"BB Astromech":
text: """Mielőtt végrehajtasz egy kék manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BARRELROLL% akciót."""
"M9-G8":
text: """Amikor egy hajó amit bemértél végrehajt egy támadást, kiválaszthatsz egy támadókockát. Ha így teszel, a támadó újradobja azt a kockát."""
"Ferrosphere Paint":
text: """Miután egy ellenséges hajó bemért téged, ha nem vagy annak a hajónak a %BULLSEYEARC% tűzívében, az kap egy stressz jelzőt."""
"Brilliant Evasion":
text: """Amikor védekezel, ha nem vagy a támadó %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt, hogy 2 %FOCUS% eredményed %EVADE% eredményre változtass."""
"Calibrated Laser Targeting":
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, adj a dobásodhoz 1 %FOCUS% eredményt."""
"Delta-7B":
text: """ <i>Kapott : 1 támadási érték, 2 pajzs %LINEBREAK% Elveszett: 1 védekezés</i> """
"Biohexacrypt Codes":
text: """Amikor koordinálsz vagy zavarsz, ha van bemérőd egy hajón, elköltheted azt a bemérőt, hogy a távolság követelményeket figyelmen kívül hagyd a hajó kiválasztákor."""
"Predictive Shot":
text: """Miután támadásra jelölsz egy célpontot, ha a védekező benne van a %BULLSEYEARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a védekező a <strong>Védekezőkockák dobása</strong> lépésben nem dobhat több kockával, mint a %HIT%/%CRIT% eredményeid száma."""
"Hate":
text: """Miután elszenvedsz 1 vagy több sérülést, feltölthetsz ugyanannyi %FORCE% jelzőt."""
"R5-X3":
text: """Mielőtt aktiválódsz vagy rád kerül a sor az Ütközet fázisban, elkölthetsz 1 %CHARGE% jelzőt, hogy figyelmen kívül hagyd az akadályokat annak a fázisnak a végéig."""
"Pattern Analyzer":
text: """Amikor teljesen végrehajtasz egy piros manővert, a <strong>Nehézség ellenőrzése</strong> lépés előtt végrehjathatsz 1 akciót."""
"Impervium Plating":
text: """Mielőtt egy felfordított <b>Ship</b> sérüléskártyát kapnál, elkölthetsz 1 %CHARGE% jelzőt, hogy eldobd."""
"Grappling Struts":
text: """<strong>Csukva: </strong> Felhelyezés: ezzel az oldalával helyezd fel. %LINEBREAK% Amikor végrehajtasz egy manővert, ha átfedésbe kerülsz egy aszteroidával vagy űrszeméttel és 1 vagy kevesebb másik baráti hajó van 0-ás távolságra attól az akadálytól, megfordíthatod ezt a kártyát.
%LINEBREAK% <b>Nyitva:</b> Hagyd figyelment kívül a 0-ás távolságnban lévő akadályokat amíg átmozogsz rajtuk. Miután felfeded a tárcsádat, ha más manővert fedtél fel mint [2 %STRAIGHT%] és 0-ás távolságra vagy egy aszteroidától vagy űrszeméttől, ugord át a 'Manőver végrehajtása' lépést és vegyél le 1 stresst jelzőt; ha jobb vagy bal manővert fedtél fel, forgasd a hajódat 90 fokkal abba az irányba. Miután végrehajtasz egy manővert fordítsd át ezt a kártyát."""
"Energy-Shell Charges":
text: """ <strong>Támadás (%CALCULATE%):</strong> Költs el 1 %CHARGE% jelzőt. Amikor végrehajtasz egy támadást, elkölthetsz 1 %CALCULATE% jelzőt, hogy megváltoztass 1 %FOCUS% eredményt %CRIT% eredményre.%LINEBREAK% <strong>Akció:</strong> Töltsd újra ezt a kártyát."""
"Dedicated":
text: """Amikor egy másik baráti hajó a %LEFTARC% vagy a %RIGHTARC% tűzívedben 0-2-es távolságban védekezik, ha az limitált vagy Dedicated fejlesztéssel felszerelt és nem vagy túlterhelve, kaphatsz 1 túlterhelés jelzőt. Ha így teszel a védekező újradobhatja 1 üres eredményét."""
"Synchronized Console":
text: """Miután végrehajtasz egy támadást, választhatsz egy baráti hajót 1-es távolságban vagy egy baráti hajót 'Synchronized Console' fejlesztéssel 1-3 távolságban és költsd el a védekezőn lévő bemérődet. Ha így teszel, a kiválasztott baráti hajó kaphat egy bemérőt a védekezőre."""
"Battle Meditation":
text: """Nem koordinálhatsz limitált hajót.%LINEBREAK%Amikor végrehajtasz egy lila %COORDINATE% akciót, koordinálhatsz 1 további ugyanolyan típusú nem limitált baráti hajót. Mindkét hajónak ugyanazt az akciót kell végrehajtania."""
"R4-P Astromech":
text: """Mielőtt végrehajtasz egy alapmanővert, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a manőver végrehajtása közben csökkentsd annak nehézségét."""
"R4-P17":
text: """Miután teljesen végrehajtasz egy piros manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy akciót, még ha stresses is vagy."""
"Spare Parts Canisters":
text: """Akció: költs el 1 %CHARGE% jelzőt, hogy visszatölts 1 %CHARGE% jelzőt egy felszerelt %ASTROMECH% fejlesztéseden.%LINEBREAK%
Akció: költs el 1 %CHARGE% jelzőt, hogy kidobj 1 tartalék alkatrész jelzőt, aztán vegyél le minden rajtad lévő bemérőt."""
"<NAME>":
text: """Felhelyezés: a hajók felhelyezése After the Place Forces step, you may cloak. %LINEBREAK% After you decloak, you may choose an enemy ship in your %BULLSEYEARC%. If you do, it gains 1 jam token."""
"<NAME> <NAME>":
text: """<strong>Felhelyezés:</strong> Ezzel az oldalával szereld fel.%LINEBREAK% Miután védekeztél, ha a támadó 0-2-es távolságban van, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a támadó kap egy stressz jelzőt.%LINEBREAK% A vége fázisban megfordíthatod ezt a kártyát.%LINEBREAK% <strong>Darth Sidious:</strong> Miután végrehajtasz egy lila %COORDINATE% akciót, a koordinált hajó kap 1 stressz jelzőt, majd kap 1 %FOCUS% jelzőt vagy visszatölt 1 %FORCE% jelzőt."""
"Count Dooku":
text: """Mielőtt egy hajó 0-2-es távolságban támadó vagy védekező kockákat gurít, ha minden %FORCE% jelződ aktív, elkölthetsz 1 %FORCE% jelzőt, hogy megnevezz egy eredményt. Ha a dobás nem tartalmazza megnevezett eredményt, a hajónak meg kell változtatni 1 kockáját arra az eredményre."""
"General Grievous":
text: """Amikor védekezel, az 'Eredmények semlegesítése' lépés után, ha 2 vagy több %HIT%/%CRIT% eredmény van, elkölthetsz 1 %CHARGE% jelzőt, hogy semlegesíts 1 %HIT% vagy %CRIT% eredményt.%LINEBREAK%Miután egy baráti hajó megsemmisül, tölts vissza 1 %CHARGE% jelzőt."""
"K2-B4":
text: """Amikor egy baráti hajó 0-3-as távolságban védekezik, elkölthet 1 %CALCULATE% jelzőt. Ha így tesz, adjon 1 %EVADE% eredményt a dobásához, hacsak a támadó nem tönt úgy, hogy kap 1 túlterhelés jelzőt."""
"DRK-1 Probe Droids":
text: """A Vége fázis alatt elkölthetsz 1 %CHARGE% jelzőt, hogy kidobj vagy kilőj 1 DRK-1 kutaszdroidot egy 3-as sebességű sablon segítségével.%LINEBREAK%E a kártya %CHARGE% jelzője nem visszatölthető."""
"Kraken":
text: """A Vége fázis alatt kiválaszthatsz akár 3 baráti hajót 0-3-as távolságban. Ha így teszel, ezen hajók nem dobják el 1 %CALCULATE% jelzőjüket."""
"TV-94":
text: """Amikor egy baráti hajó 0-3-as távolságban végrehajt egy elsődleges támadást egy a %BULLSEYEARC% tűzívében lévő védekező ellen, ha 2 vagy kevesebb a támadó kockák száma, elkölthet 1 %CALCULATE% jelzőt, hogy hozzáadjon a dobásához 1 %HIT% eredményt."""
"Discord Missiles":
text: """Az Ütközet fázis elején elkölthetsz 1 %CALCULATE% jelzőt és 1 %CHARGE% jelzőt, hogy kilőj 1 'buzz droid swarm' jelzőt a [3 %BANKLEFT%], [3 %STRAIGHT%] vagy [3 %BANKRIGHT%] használatával. Ennek a kártyának a %CHARGE% jelzője nem tölthető újra."""
"Clone Commander Cody":
text: """Miután végrehajtasz egy támadást ami nem talált, ha 1 vagy több %HIT%/%CRIT% eredményt lett semlegesítve, a védekező kap 1 túlterhelés jelzőt."""
"Seventh Fleet Gunner":
text: """Amikor egy másik baráti hajó végrehajt egy elsődleges támadást, ha a védekező a tűzívedben van, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel a támadó 1-gyel több kockával dob, de maximum 4-gyel. A rendszer fázisban kaphatsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts 1 %CHARGE% jelzőt."""
"R4-P44":
text: """Miután teljesen véggrehajtasz egy piros manővert, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, kapsz 1 %CALCULATE% jelzőt."""
"Treacherous":
text: """Amikor védekezel, kiválaszthatsz egy a támadást akadályozó hajót és költs el 1 %CHARGE% jelzőt. Ha így teszel, semlegesíts 1 %HIT% vagy %CRIT% eredményt és a kiválasztott hajó kap egy túlterhelés jelzőt. Ha egy hajó 0-3-as távolságban megsemmisül, tölts vissza 1 %CHARGE% jelzőt."""
"Soulless One":
text: """Amikor védekezel, ha a támadó a tűzíveden kívül van újradobhatsz 1 védekezőkockát."""
condition_translations =
'Suppressive Fire':
text: '''Amikor végrehajtasz egy támadást más hajó ellen mint <strong>Captain Rex</strong>, dobj 1-gyel kevesebb kockával.%LINEBREAK% Miután <strong>Captain Rex</strong> védekezik, vedd le ezt a kártyát. %LINEBREAK% Az Ütközet fázis végén, ha <strong>Captain Rex</strong> nem hajtott végre támadást ebben a fázisban, vedd le ezt a kártyát. %LINEBREAK% Miután <strong>Captain Rex</strong> megsemmisült, vedd le ezt a kártyát.'''
'Hunted':
text: '''Miután megsemmisültél, választanod kell egy baráti hajót és átadni neki ezt a kondíció kártyát.'''
'Listening Device':
text: '''A Rendszer fázisban, ha egy ellenséges hajó az <strong>Informant</strong> fejlesztéssel 0-2-es távolságban van, fedd fel a tárcsád.'''
'Rattled':
text: '''Miután egy bomba vagy akna 0-1-es távolságban felrobban, elszenvedsz 1 %CRIT% sérülést. Aztán vedd le ezt a kártyát.%LINEBREAK%<strong>Akció:</strong> Ha nincs bomba vagy akna 0-1-es távolságban, vedd ele ezt a kártyát.'''
'Optimized Prototype':
text: '''Amikor végrehajtasz egy elsődleges %FRONTARC% támadást egy olyan hajó ellen, amit bemért <strong><NAME></strong> fejlesztéssel felszerelt hajó, elkölthetsz 1 %HIT%/%CRIT%/%FOCUS% eredményt. Ha így teszel, választhatsz, hogy a védekező elveszt 1 pajzsot vagy a védekező felfordítja 1 sérüléskártyáját.'''
'''I'll Show You the Dark Side''':
text: '''Mikor ezt a kártyát hozzárendelik egy hajódhoz, ha nincs felfordított sérüléskártya rajta, az ellenfél kikeres a sérüléskártyáidból egy pilóta típusút és felfordítva ráteszi. Aztán megkeveri a paklit. Amikor elszenvednél 1 %CRIT% sérülést, ezen a kártyán lévő sérüléskártyát kapod meg. Aztán vedd le ezt a lapot.'''
'Proton Bomb':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, minden hajó és távérzékelő 0–1-es távolságban elszenved 1 %CRIT% sérülést.'''
'Seismic Charge':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, válassz 1 akadály 0–1-es távolságban. Minden hajó és távérzékelő 0–1-es távolságra az akadálytól elszenved 1 %HIT% sérülést.'''
'Bomblet':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, minden hajó 0–1-es távolságban dob 2 támadókockával. Minden hajó és távérzékelő elszenved 1 %HIT% sérülést minden egyes %HIT%/%CRIT% eredmény után.'''
'Loose Cargo':
text: '''(Űrszemét jelző) - A kidobott rakomány űrszemétnek számít.'''
'Conner Net':
text: '''(Akna jelző) - Miután egy hajó átmozog vagy átfedésbe kerül ezzel az eszközzel, az felrobban. Amikor ez az eszköz felrobban, a hajó elszenved 1 %HIT% sérülést és kap 3 ion jelzőt.'''
'Proximity Mine':
text: '''(Akna jelző) - Miután egy hajó átmozog vagy átfedésbe kerül ezzel az eszközzel, az felrobban. Amikor ez az eszköz felrobban, a hajó dob 2 támadókockával, aztán elszenved 1 %HIT%, valamint a dobott eremény szerint 1-1 %HIT%/%CRIT% sérülést.'''
'DRK-1 Probe Droid':
text: '''INIT: 0 / MOZGÉKONYSÁG: 3 / HULL: 1 / (távérzékelő)%LINEBREAK%Amikor egy baráti hajó bemér egy objektumot vagy zavar egy ellenséges hajót, mérheti a távolságot tőled. Miután egy ellenséges hajó átfedésbe kerül veled, az dob egy támadókockával. %FOCUS% eredménynél elszenvedsz 1 %HIT% sérülést.%LINEBREAK%Rendszer fázis: a kezdeményezésednek megfelelően arrébb mozgathatod a [2 %BANKLEFT%], [2 %STRAIGHT%] vagy [2 %BANKRIGHT%] sablonnal.'''
'Buzz Droid Swarm':
text: '''INIT: 0 / MOZGÉKONYSÁG: 3 / HULL: 1 / (távérzékelő)%LINEBREAK%Miután egy ellenséges hajó átmozog rajtad vagy átfedésbe kerül veled, átteheted annak első vagy hátsó pöckeihez (ilyenkor 0-ás távolságra vagy a hajótól). Nem lehetsz átfedésbe egy objektummal sem ily módon. Ha nem tudod elhelyezni a pöckökhöz, te és a hajó is elszenvedtek 1 %HIT% sérülést.%LINEBREAK%Ütközet fázis: a kezdeményezésednek megfelelően minden 0-ás távolságba nlévő hajó elszenved 1 %CRIT% sérülést.'''
exportObj.setupTranslationCardData pilot_translations, upgrade_translations, condition_translations
| true | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.hu = 'Magyar'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Magyar =
slot:
"Astromech": "Astromech"
"Force": "Erő"
"Bomb": "Bomba"
"Cannon": "Ágyú"
"Crew": "Személyzet"
"Missile": "Rakéta"
"Sensor": "Szenzor"
"Torpedo": "Torpedó"
"Turret": "Lövegtorony"
"Hardpoint": "Fegyverfelfüggesztés"
"Illicit": "Tiltott"
"Configuration": "Konfiguráció"
"Talent": "Talentum"
"Modification": "Módosítás"
"Gunner": "Fegyverzet kezelő"
"Device": "Eszköz"
"Tech": "Tech"
"Title": "Nevesítés"
sources: # needed?
"Second Edition Core Set": "Second Edition Core Set"
"Rebel Alliance Conversion Kit": "Rebel Alliance Conversion Kit"
"Galactic Empire Conversion Kit": "Galactic Empire Conversion Kit"
"Scum and Villainy Conversion Kit": "Scum and Villainy Conversion Kit"
"T-65 X-Wing Expansion Pack": "T-65 X-Wing Expansion Pack"
"BTL-A4 Y-Wing Expansion Pack": "BTL-A4 Y-Wing Expansion Pack"
"TIE/ln Fighter Expansion Pack": "TIE/ln Fighter Expansion Pack"
"TIE Advanced x1 Expansion Pack": "TIE Advanced x1 Expansion Pack"
"Slave 1 Expansion Pack": "Slave 1 Expansion Pack"
"Fang Fighter Expansion Pack": "Fang Fighter Expansion Pack"
"Lando's Millennium Falcon Expansion Pack": "Lando's Millennium Falcon Expansion Pack"
"Saw's Renegades Expansion Pack": "Saw's Renegades Expansion Pack"
"TIE Reaper Expansion Pack": "TIE Reaper Expansion Pack"
ui:
shipSelectorPlaceholder: "Válassz egy hajót"
pilotSelectorPlaceholder: "Válassz egy pilótát"
upgradePlaceholder: (translator, language, slot) ->
"Nincs #{translator language, 'slot', slot} fejlesztés"
modificationPlaceholder: "Nincs módosítás"
titlePlaceholder: "Nincs nevesítés"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'slot', slot} fejlesztés"
unreleased: "kiadatlan"
epic: "epikus"
limited: "korlátozott"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'Ez a raj kiadatlan tartalmat használ!'
'.loading-failed-container .translated': 'It appears that you followed a broken link. No squad could be loaded!'
'.collection-invalid .translated': 'Ez a lista nem vihető pályára a készletedből!'
'.ship-number-invalid-container .translated': 'A tournament legal squad must contain 2-8 ships!'
# Type selector
'.game-type-selector option[value="standard"]': 'Kiterjesztett'
'.game-type-selector option[value="hyperspace"]': 'Hyperspace'
'.game-type-selector option[value="custom"]': 'Egyéni'
# Card browser
'.xwing-card-browser option[value="name"]': 'Név'
'.xwing-card-browser option[value="source"]': 'Forrás'
'.xwing-card-browser option[value="type-by-points"]': 'Típus (pont szerint)'
'.xwing-card-browser option[value="type-by-name"]': 'Típus (név szerint)'
'.xwing-card-browser .translate.select-a-card': 'Válassz a bal oldalon lévő kártyákból.'
'.xwing-card-browser .translate.sort-cards-by': 'Sort cards by'
# Info well
'.info-well .info-ship td.info-header': 'Hajó'
'.info-well .info-skill td.info-header': 'Kezdeményezés'
'.info-well .info-actions td.info-header': 'Akciók'
'.info-well .info-upgrades td.info-header': 'Fejlesztések'
'.info-well .info-range td.info-header': 'Távolság'
# Squadron edit buttons
'.clear-squad' : 'Új raj'
'.save-list' : '<i class="fa fa-floppy-o"></i> Mentés'
'.save-list-as' : '<i class="fa fa-files-o"></i> Mentés mint…'
'.delete-list' : '<i class="fa fa-trash-o"></i> Törlés'
'.backend-list-my-squads' : 'Raj betöltés'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Nyomtatás/Szövegnézet </span>'
'.randomize' : '<i class="fa fa-random"></i> Random!'
'.randomize-options' : 'Randomizer opciók…'
'.notes-container > span' : 'Jegyzetek'
# Print/View modal
'.bbcode-list' : 'Copy the BBCode below and paste it into your forum post.<textarea></textarea><button class="btn btn-copy">Másolás</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Másolás</button>'
'.vertical-space-checkbox' : """Hagyj helyet a sérülés és fejlesztéskártyáknak nyomtatáskor <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Színes nyomtatás <input type="checkbox" class="toggle-color-print" checked="checked" />"""
'.print-list' : '<i class="fa fa-print"></i> Nyomtatás'
# Randomizer options
'.do-randomize' : 'Randomize!'
# Top tab bar
'#browserTab' : 'Kártya tallózó'
'#aboutTab' : 'Rólunk'
# Obstacles
'.choose-obstacles' : 'Válassz akadályt'
'.choose-obstacles-description' : 'Choose up to three obstacles to include in the permalink for use in external programs. (This feature is in BETA; support for displaying which obstacles were selected in the printout is not yet supported.)'
'.coreasteroid0-select' : 'Core Asteroid 0'
'.coreasteroid1-select' : 'Core Asteroid 1'
'.coreasteroid2-select' : 'Core Asteroid 2'
'.coreasteroid3-select' : 'Core Asteroid 3'
'.coreasteroid4-select' : 'Core Asteroid 4'
'.coreasteroid5-select' : 'Core Asteroid 5'
'.yt2400debris0-select' : 'YT2400 Debris 0'
'.yt2400debris1-select' : 'YT2400 Debris 1'
'.yt2400debris2-select' : 'YT2400 Debris 2'
'.vt49decimatordebris0-select' : 'VT49 Debris 0'
'.vt49decimatordebris1-select' : 'VT49 Debris 1'
'.vt49decimatordebris2-select' : 'VT49 Debris 2'
'.core2asteroid0-select' : 'Force Awakens Asteroid 0'
'.core2asteroid1-select' : 'Force Awakens Asteroid 1'
'.core2asteroid2-select' : 'Force Awakens Asteroid 2'
'.core2asteroid3-select' : 'Force Awakens Asteroid 3'
'.core2asteroid4-select' : 'Force Awakens Asteroid 4'
'.core2asteroid5-select' : 'Force Awakens Asteroid 5'
# Collection
'.collection': '<i class="fa fa-folder-open hidden-phone hidden-tabler"></i> Gyűjteményed'
singular:
'pilots': 'Pilóta'
'modifications': 'Módosítás'
'titles': 'Nevesítés'
'ships' : 'Ship'
types:
'Pilot': 'Pilóta'
'Modification': 'Módosítás'
'Title': 'Nevesíés'
'Ship' : 'Ship'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Magyar = () ->
exportObj.cardLanguage = 'Magyar'
exportObj.renameShip """YT-1300""", """Modified YT-1300 Light Freighter"""
exportObj.renameShip """StarViper""", """StarViper-class Attack Platform"""
exportObj.renameShip """Scurrg H-6 Bomber""", """Scurrg H-6 Bomber"""
exportObj.renameShip """YT-2400""", """YT-2400 Light Freighter"""
exportObj.renameShip """Auzituck Gunship""", """Auzituck Gunship"""
exportObj.renameShip """Kihraxz Fighter""", """Kihraxz Fighter"""
exportObj.renameShip """Sheathipede-Class Shuttle""", """Sheathipede-class Shuttle"""
exportObj.renameShip """Quadjumper""", """Quadrijet Transfer Spacetug"""
exportObj.renameShip """Firespray-31""", """Firespray-class Patrol Craft"""
exportObj.renameShip """TIE Fighter""", """TIE/ln Fighter"""
exportObj.renameShip """Y-Wing""", """BTL-A4 Y-Wing"""
exportObj.renameShip """TIE Advanced""", """TIE Advanced x1"""
exportObj.renameShip """Alpha-Class Star Wing""", """Alpha-class Star Wing"""
exportObj.renameShip """U-Wing""", """UT-60D U-Wing"""
exportObj.renameShip """TIE Striker""", """TIE/sk Striker"""
exportObj.renameShip """B-Wing""", """A/SF-01 B-Wing"""
exportObj.renameShip """TIE Defender""", """TIE/D Defender"""
exportObj.renameShip """TIE Bomber""", """TIE/sa Bomber"""
exportObj.renameShip """TIE Punisher""", """TIE/ca Punisher"""
exportObj.renameShip """Aggressor""", """Aggressor Assault Fighter"""
exportObj.renameShip """G-1A Starfighter""", """G-1A Starfighter"""
exportObj.renameShip """VCX-100""", """VCX-100 Light Freighter"""
exportObj.renameShip """YV-666""", """YV-666 Light Freighter"""
exportObj.renameShip """TIE Advanced Prototype""", """TIE Advanced v1"""
exportObj.renameShip """Lambda-Class Shuttle""", """Lambda-class T-4a Shuttle"""
exportObj.renameShip """TIE Phantom""", """TIE/ph Phantom"""
exportObj.renameShip """VT-49 Decimator""", """VT-49 Decimator"""
exportObj.renameShip """TIE Aggressor""", """TIE/ag Aggressor"""
exportObj.renameShip """K-Wing""", """BTL-S8 K-Wing"""
exportObj.renameShip """ARC-170""", """ARC-170 Starfighter"""
exportObj.renameShip """Attack Shuttle""", """Attack Shuttle"""
exportObj.renameShip """X-Wing""", """T-65 X-Wing"""
exportObj.renameShip """HWK-290""", """HWK-290 Light Freighter"""
exportObj.renameShip """A-Wing""", """RZ-1 A-Wing"""
exportObj.renameShip """Fang Fighter""", """Fang Fighter"""
exportObj.renameShip """Z-95 Headhunter""", """Z-95-AF4 Headhunter"""
exportObj.renameShip """M1PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI""", """M12-L PI:NAME:<NAME>END_PIer"""
exportObj.renameShip """E-Wing""", """E-Wing"""
exportObj.renameShip """TIE Interceptor""", """TIE Interceptor"""
exportObj.renameShip """Lancer-Class Pursuit Craft""", """Lancer-class Pursuit Craft"""
exportObj.renameShip """TIE Reaper""", """TIE Reaper"""
exportObj.renameShip """JumpMaster 5000""", """JumpMaster 5000"""
exportObj.renameShip """M3-A Interceptor""", """M3-A Interceptor"""
exportObj.renameShip """Scavenged YT-1300""", """Scavenged YT-1300 Light Freighter"""
exportObj.renameShip """Escape Craft""", """Escape Craft"""
# Names don't need updating, but text needs to be set
pilot_translations =
"Academy Pilot":
display_name: """Academy Pilot"""
text: """ """
"Alpha Squadron Pilot":
display_name: """Alpha Squadron Pilot"""
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Bandit Squadron Pilot":
display_name: """Bandit Squadron Pilot"""
text: """ """
"Baron of the Empire":
display_name: """Baron of the Empire"""
text: """ """
"Binayre Pirate":
display_name: """BinPI:NAME:<NAME>END_PIate"""
text: """ """
"Black Squadron Ace":
display_name: """Black Squadron Ace"""
text: """ """
"Black Squadron Scout":
display_name: """Black Squadron Scout"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Black Sun Ace":
display_name: """Black Sun Ace"""
text: """ """
"Black Sun Assassin":
display_name: """Black Sun Assassin"""
text: """<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Black Sun Enforcer":
display_name: """Black Sun Enforcer"""
text: """<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Black Sun Soldier":
display_name: """Black Sun Soldier"""
text: """ """
"Blade Squadron Veteran":
display_name: """Blade Squadron Veteran"""
text: """ """
"Blue Squadron Escort":
display_name: """Blue Squadron Escort"""
text: """ """
"Blue Squadron Pilot":
display_name: """Blue Squadron Pilot"""
text: """ """
"Blue Squadron Scout":
display_name: """Blue Squadron Scout"""
text: """ """
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """ """
"Cartel Executioner":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<sasmall> <strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """ """
"Cartel Spacer":
display_name: """Cartel Spacer"""
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"CaPI:NAME:<NAME>END_PI AngePI:NAME:<NAME>END_PI Zealot":
display_name: """CaPI:NAME:<NAME>END_PI"""
text: """ """
"Contracted Scout":
display_name: """Contracted Scout"""
text: """ """
"CPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """ """
"Cutlass Squadron Pilot":
display_name: """Cutlass Squadron Pilot"""
text: """ """
"Delta Squadron Pilot":
display_name: """Delta Squadron Pilot"""
text: """<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Freighter Captain":
display_name: """Freighter Captain"""
text: """"""
"Gamma Squadron Ace":
display_name: """Gamma Squadron Ace"""
text: """<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """ """
"Gold Squadron Veteran":
display_name: """Gold Squadron Veteran"""
text: """ """
"Gray Squadron Bomber":
display_name: """Gray Squadron Bomber"""
text: """ """
"Green Squadron Pilot":
display_name: """Green Squadron Pilot"""
text: """<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Hired Gun":
display_name: """HPI:NAME:<NAME>END_PI"""
text: """ """
"Imdaar Test Pilot":
display_name: """Imdaar Test Pilot"""
text: """<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
"Inquisitor":
display_name: """Inquisitor"""
text: """ """
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"Kashyyyk Defender":
display_name: """PI:NAME:<NAME>END_PI Defender"""
text: """ """
"Knave Squadron Escort":
display_name: """KnPI:NAME:<NAME>END_PI Escort"""
text: """<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Lok Revenant":
display_name: """LPI:NAME:<NAME>END_PI RevenPI:NAME:<NAME>END_PI"""
text: """ """
"Lothal Rebel":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"Nu Squadron Pilot":
display_name: """Nu Squadron Pilot"""
text: """ """
"Obsidian Squadron Pilot":
display_name: """Obsidian Squadron Pilot"""
text: """ """
"Omicron Group Pilot":
display_name: """Omicron Group Pilot"""
text: """ """
"Onyx Squadron Ace":
display_name: """Onyx Squadron Ace"""
text: """<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"Onyx Squadron Scout":
display_name: """Onyx Squadron Scout"""
text: """ """
"Outer Rim Smuggler":
display_name: """Outer Rim Smuggler"""
text: """ """
"Partisan Renegade":
display_name: """Partisan Renegade"""
text: """ """
"Patrol Leader":
display_name: """Patrol Leader"""
text: """ """
"Phoenix Squadron Pilot":
display_name: """Phoenix Squadron Pilot"""
text: """<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"Planetary Sentinel":
display_name: """Planetary Sentinel"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Rebel Scout":
display_name: """Rebel Scout"""
text: """ """
"Red Squadron Veteran":
display_name: """Red Squadron Veteran"""
text: """ """
"Rho Squadron Pilot":
display_name: """Rho Squadron Pilot"""
text: """ """
"Rogue Squadron Escort":
display_name: """Rogue Squadron Escort"""
text: """<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Saber Squadron Ace":
display_name: """Saber Squadron Ace"""
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Scarif Base Pilot":
display_name: """Scarif Base Pilot"""
text: """<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Scimitar Squadron Pilot":
display_name: """Scimitar Squadron Pilot"""
text: """<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Shadowport Hunter":
display_name: """Shadowport Hunter"""
text: """ """
"Sienar Specialist":
display_name: """Sienar Specialist"""
text: """ """
"Sigma Squadron Ace":
display_name: """Sigma Squadron Ace"""
text: """<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
"Skull Squadron Pilot":
display_name: """Skull Squadron Pilot"""
text: """<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Spice Runner":
display_name: """Spice Runner"""
text: """ """
"Storm Squadron Ace":
display_name: """Storm Squadron Ace"""
text: """<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Tala Squadron Pilot":
display_name: """Tala Squadron Pilot"""
text: """ """
"Tansarii Point Veteran":
display_name: """Tansarii Point Veteran"""
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Tempest Squadron Pilot":
display_name: """Tempest Squadron Pilot"""
text: """<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """ """
"Warden Squadron Pilot":
display_name: """Warden Squadron Pilot"""
text: """ """
"Wild Space Fringer":
display_name: """Wild Space Fringer"""
text: """<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
"Zealous Recruit":
display_name: """Zealous Recruit"""
text: """<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"4-LOM":
display_name: """4-LOM"""
text: """Miután teljesen végrehajtasz egy piros manővert, kapsz 1 kalkuláció jelzőt. A Vége fázis elején választhatsz 1 hajót 0-1-es távolságban. Ha így teszel, add át 1 stressz jelződ annak a hajónak."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Csak vészhelyzet esetén válhatsz le az anyahajóról. Ebben az esetben megkapod a megsemmisült baráti Hound's Tooth pilóta nevet, kezdeményezést, pilóta képességet és hajó %CHARGE% jelzőt. %LINEBREAK% <strong>Escape Craft:</strong> <strong>Setup:</strong> <strong>Hound’s Tooth</strong> szükséges. A <strong>Hound’s Tooth</strong>-ra dokkolva <b>kell</b> kezdened a játékot."""
"AP-5":
display_name: """AP-5"""
text: """Amikor koordinálsz, ha a kiválasztott hajónak pontosan 1 stressz jelzője van, az végrehajthat akciókat.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy támadást, választhatsz 1 baráti hajót 1-es távolságban. Az a hajó végrehajthat egy akciót, pirosként kezelve."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Végrehajthatsz elsődleges támadást 0-ás távolságban. Ha egy %BOOST% akcióddal átfedésbe kerülsz egy másik hajóval, úgy hajtsd végre, mintha csak részleges manőver lett volna. %LINEBREAK% VECTORED THRUSTERS: Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% gyorsítás akciót."""
"Asajj Ventress":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején választhatsz 1 ellenséges hajót a %SINGLETURRETARC% tűzívedben 0-2-es távolságban és költs 1 %FORCE% jelzőt. Ha így teszel, az a hajó kap 1 stressz jelzőt, hacsak nem távolít el 1 zöld jelzőt."""
"Autopilot Drone":
display_name: """Autopilot Drone"""
text: """<strong>Rigged Energy Cells:</strong> A Rendszer fázis alatt, ha nem vagy dokkolva, elvesztesz 1 %CHARGE% jelzőt. Az aktivációs fázis végén, ha már nincs %CHARGE% jelződ, megsemmisülsz. Mielőtt levennéd a hajód minden 0-1-es távolságban lévő hajó elszenved 1 %CRIT% sérülést."""
"Benthic Two Tubes":
display_name: """Benthic Two Tubes"""
text: """Miután végrehajtasz egy %FOCUS% akciót, átrakhatod 1 fókusz jelződ egy baráti hajóra 1-2-es távolságban."""
"Biggs Darklighter":
display_name: """Biggs Darklighter"""
text: """Amikor baráti hajó védekezik tőled 0-1-es távolságban, az <strong>Eredmények semlegesítése</strong> lépés előtt, ha a támadó tűzívében vagy, elszenvedhetsz 1 %HIT% vagy %CRIT% találatot, hogy hatástalaníts 1 azzal egyező találatot."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy végrehajtasz egy támadást, újradobhatsz 1 kockát, minden egyes 0-1-es távolságban lévő ellenséges hajó után."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Baráti hajók bemérhetnek más baráti hajóktól 0-3-as távolságban lévő objektumokat."""
"BossPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy elsődleges támadást, az <strong>Eredmények semlegesítése</strong> lépés után, elkölthetsz egy %CRIT% eredményt, hogy hozzáadj 2 %HIT% eredményt a dobásodhoz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy végrehajtasz egy támadást, ha stresszes vagy, újradobhatod legfeljebb 2 kockádat."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel, ha a támadónak nincs zöld jelzője, megváltoztathatod 1 üres vagy %FOCUS% dobásod %EVADE% eredményre.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"CaptPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy baráti hajó 0-1-es távolságban végrehajt egy %TORPEDO% vagy %MISSILE% támadást, az újradobhat legfeljebb 2 támadókockát.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután egy ellenséges hajó sérülést szenved és nem védekezett, végrehajthatsz egy bónusz támadást ellene."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején választhatsz egy vagy több baráti hajót 0-3-es távolságban. Ha így teszel, tedd át az összes ellenséges bemérés jelzőt a kiválasztott hajókról magadra."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Mielőtt egy baráti bomba vagy akna PI:NAME:<NAME>END_PI, elkölthetsz 1 %CHARGE% jelzőt, hogy megakadályozd a felrobbanását.%LINEBREAK%Mikor egy támadás ellen védekezel, amely akadályozott egy bomba vagy akna által, 1-gyel több védekezőkockával dobj."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Végrehajthatsz elsődleges támadást 0-ás távolságban."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy támadást, jelöld meg a védekezőt a <strong>Suppressive Fire</strong> kondícióval."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Aktivációs fázis elején választhatsz 1 baráti hajót 1-3-as távolságban. Ha így teszel, az a hajó eltávolít 1 stressz jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Mielőtt felfordított sebzéskártyát kapnál, elkölthetsz 1 %CHARGE%-et, hogy a lapot képpel lefelé húzd fel."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Aktivációs fázis elején elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, amikor baráti hajók bemérés jelzőt tesznek fel ebben a körben, 3-as távolságon túl tehetik csak meg a 0-3-as távolság helyett."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre egy bemért hajó ellen, miután dobsz a kockákkal, feltehetsz egy bemérés jelzőt a védekezőre.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor kidobnál egy eszközt, helyette ki is lőheted egy [1 %STRAIGHT%] sablon használatával.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """0-ás kezdeményezésnél végrehajthatsz egy bónusz elsődleges támadást egy ellenséges hajó ellen, aki a %BULLSEYEARC% tűzívedben van. Ha így teszel, a következő Tervezés fázisban kapsz 1 'inaktív fegyverzet' jelzőt.%LINEBREAK%<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtanál egy %STRAIGHT% manővert, megnövelheted annak nehézségét. Ha így teszel, helyette végrehajthatod mint %KTURN% manőver.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután egy ellenséges hajó 0-3-as távolságban kap legalább 1 ion jelzőt, elkölthetsz 3 %CHARGE% jelzőt. Ha így teszel, az a hajó kap 2 további ion jelzőt."""
"PI:NAME:<NAME>END_PI (StarViper)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután teljesen végrehajtasz egy manővert, kaphatsz 1 stressz jelzőt, hogy elforgasd a hajód 90 fokkal.%LINEBREAK% <sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején választhatsz 1 pajzzsal rendelkező hajót a %BULLSEYEARC% tűzívedben és elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó elveszít egy pajzsot, te pedig visszatöltesz 1 pajzsot.%LINEBREAK%<sasmall><strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy akciót, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy akciót.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"Dash Rendar":
display_name: """Dash Rendar"""
text: """Amikor mozogsz, hagyd figyelmen kívül az akadályokat.%LINEBREAK%<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
"Del Meeko":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy baráti 0-2 távolságban védekezik egy sérült támadó ellen, a védekező újradobhat 1 védekezőkockát."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután védekeztél, ha a támadó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy bónusz támadást a támadó ellen."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy baráti nem-limitált hajó végrehajt egy támadást, ha a védekező benne van a tűzívedben, a támadó újradobhatja 1 támadókockáját."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Mielőtt aktiválódnál és van fókuszod, végrehajthatsz egy akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Ha ki szeretnél dobni egy eszközt az [1 %STRAIGHT%] sablonnal, használhatod helyette a [3 %TURNLEFT%], [3 %STRAIGHT%], vagy [3 %TURNRIGHT%] sablont."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy 0-2-es távolságban lévő baráti hajó védekezik vagy támadást hajt végre, elköltheti a te fókusz jelzőidet, mintha a saját hajójáé lenne."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején elkölthetsz 1 fókusz jelzőt, hogy kiválassz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó a kör végéig minden védekezésénél 1-gyel több védekezőkockával dob."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"PI:NAME:<NAME>END_PI (TIE Fighter)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha stresszes vagy, elkölthetsz 1 %FORCE% jelzőt, hogy legfeljebb 2 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre módosíts."""
"PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután egy ellenséges hajó a tűzívedben sorra kerül az Ütközet fázisban, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt. Ha így teszel, az a hajó nem költhet el jelzőt, hogy módosítsa támadókockáit e fázis alatt.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha a támadás 1-es távolságban történik, 1-gyel több kockával dobhatsz.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"PI:NAME:<NAME>END_PI (X-Wing)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután elköltesz egy fókusz jelzőt, választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó kap 1 fókusz jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután elköltesz egy fókusz jelzőt, választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó kap 1 fókusz jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy baráti hajó végrehajt egy támadást, ha a védekező a %FRONTARC% tűzívedben van, a támadó 1 %HIT% eredményét %CRIT% eredményre módosíthatja.%LINEBREAK%<sasmall><strong>Experimental Scanners:</strong> 3-as távolságon túl is bemérhetsz. Nem mérhetsz be 1-es távolságra.</sasmall>"""
"Genesis PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután feltettél egy bemérés jelzőt, le kell venned az összes fókusz és kitérés jelződet, aztán megkapsz annyi fókusz és kitérés jelzőt, ahány a bemért hajónak van.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy támadást sérült védekező ellen, 1-gyel több támadókockával dobhatsz."""
"Grand Inquisitor":
display_name: """Grand Inquisitor"""
text: """Amikor 1-es távolságban védekezel, elkölthetsz 1 %FORCE% tokent, hogy megakadályozd az 1-es távolság bónuszt. Amikor támadást hajtasz végre 2-3-as távolságban lévő védekező ellen, elkölthetsz 1 %FORCE% jelzőt, hogy megkapd az 1-es távolság bónuszt."""
"Graz":
display_name: """Graz"""
text: """Amikor védekezel, ha a támadó mögött vagy, 1-gyel több védekezőkockával dobhatsz. Amikor végrehajtasz egy támadást, ha a védekező mögött vagy, 1-gyel több támadókockával dobhatsz."""
"Guri":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején, ha legalább 1 ellenséges hajó van 0-1-es távolságban, kaphatsz egy fókusz jelzőt.%LINEBREAK% <sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"Han Solo":
display_name: """Han Solo"""
text: """Miután dobtál, ha 0-1-es távolságban vagy akadálytól, újradobhatod az összes kockádat. Ez nem számít újradobásnak más hatások számára."""
"Han Solo (Scum)":
display_name: """Han PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy elsődleges támadást hajtasz vége, ha a támadás akadály által akadályozott, 1-gyel több kockával dobhatsz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután egy ellenséges hajó végrehajt egy manővert, ha 0-ás távolságba kerül, végrehajthatsz egy akciót."""
"HPI:NAME:<NAME>END_PIulla":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután piros vagy kék manővert fedtél fel, átállíthatod manőversablonod egy másik, azonos nehézségű manőverre.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"HPI:NAME:<NAME>END_PI Syndulla (VCX-100)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután piros vagy kék manővert fedtél fel, átállíthatod manőversablonod egy másik, azonos nehézségű manőverre.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, a védekezőtől 0-1-es távolságban lévő minden más baráti hajó után újradobhatsz 1 támadókockát."""
"IG-88A":
display_name: """IG-88A"""
text: """Az Ütközet fázis elején kiválaszthatsz egy %CALCULATE% akcióval rendelkező baráti hajót 1-3-as távolságban. Ha így teszel, add át 1 kalkuláció jelződet neki.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88B":
display_name: """IG-88B"""
text: """Miután végrehajtasz egy támadást ami nem talált, végrehajthatsz egy bónusz %CANNON% támadást.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88C":
display_name: """IG-88C"""
text: """Miután végrehajtasz egy %BOOST% akciót, végrehajthatsz egy %EVADE% akciót.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IG-88D":
display_name: """IG-88D"""
text: """Amikor végrehajtasz egy Segnor's Loop [%SLOOPLEFT% vagy %SLOOPRIGHT%] manővert, használhatsz ugyanazon sebességű másik sablont helyette: vagy megegyező irányú kanyar [%TURNLEFT% vagy %TURNRIGHT%] vagy előre egyenes [%STRAIGHT%] sablont.%LINEBREAK%<strong>Advanced Droid Brain:</strong> Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"IPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután teljesen végrehajtasz egy manővert, ha stresszes vagy, dobhatsz 1 támadókockával. %HIT% vagy %CRIT% eredmény esetén távolíts el 1 stressz jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Mielőtt egy 0-1-es távolságban lévő baráti TIE/ln hajó elszenvedne 1 vagy több sérülést, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, megakadályozod a sérülést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, elszenvedhetsz 1 %HIT% sérülést, hogy újradobj bármennyi kockát.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, választhatsz egy baráti hajót 0-1-es távolságban. Az a hajó végrehajthat egy %FOCUS% akciót.%LINEBREAK%<sasmall><strong>Vectored Thrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% akciót.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy tűzíveden belüli baráti hajó elsődleges támadást hajt végre, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt. Ha így teszel, az a hajó 1-gyel több támadókockával dobhat."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután kapsz egy stressz jelzőt, dobhatsz 1 támadó kockával, hogy levedd. %HIT% eredmény esetén elszenvedsz 1 %HIT% sérülést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %CHARGE% jelzőt egy felszerelt %TORPEDO% fejlesztésről. Ha így teszel a védekező 1-gyel kevesebb védekezőkockával dob.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején kiválaszthatsz egy 0-2-es távolságban lévő baráti hajót. Ha így teszel, áttehetsz róla 1 fókusz vagy kitérés jelzőt a magadra."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután teljesen végrehajtasz egy piros manővert, kapsz 2 fókusz jelzőt.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy tűzívedben lévő baráti hajó védekezik, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a támadó 1-gyel kevesebb támadókockával dob.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, ha legalább 1 nem-limitált baráti hajó van 0-ás távolságra a védekezőtől, dobj 1-gyel több támadókockával."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy nem-%FRONTARC% támadást hajtasz végre, dobj 1-gyel több támadókockával."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején választhatsz 1 hajót ami a %FRONTARC% és %SINGLETURRETARC% tűzívedben is benne van 0-1-es távolságban. Ha így teszel, az a hajó kap egy vonósugár jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó stresszes, újradobhatod 1 kockádat."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Végrehajthatsz egy %FRONTARC% speciális támadást a %REARARC% tűzívedből. Amikor speciális támadást hajtasz végre, újradobhatsz egy támadókockát."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, megfordíthatod a felszerelt %CONFIG% fejlesztés kártyád."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején átadhatod 1 fókusz jelződet egy tűzívedben lévő baráti hajónak."""
"L3-37":
display_name: """L3-37"""
text: """Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek."""
"L3-37 (Escape Craft)":
display_name: """L3-37"""
text: """Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután védekezel vagy támadást hajtasz végre, ha a támadás nem talált, kapsz 1 kitérés jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután teljesen végrehajtasz egy kék manővert, választhatsz egy baráti hajót 0-3-as távolságban. Az a hajó végrehajthat egy akciót."""
"PI:NAME:<NAME>END_PI (Scum)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután dobsz a kockákkal, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy újradobhasd az összes üres eredményed."""
"PI:NAME:<NAME>END_PI (Scum) (Escape Craft)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután dobsz a kockákkal, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy újradobhasd az összes üres eredményed.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején kiválaszthatsz egy hajót 1-es távolságban és elköltheted a rajta lévő bemérés jelződet. Ha így teszel, az a hajó kap egy vonósugár jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy %BARRELROLL% vagy %BOOST% akciót, végrehajthatsz egy piros %EVADE% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor elsődleges támadást hajtasz végre, ha legalább 1 másik baráti hajó van 0-1-es távolságban a védekezőtől, 1-gyel több támadókockával dobhatsz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután kapsz egy inaktív fegyverzet jelzőt, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy levegyél 1 inaktív fegyverzet jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, miután a védekező dob a kockáival, elkölthetsz 1 fókusz jelzőt, hogy semlegesítsd a védekező összes üres és fókusz eredményét."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy %COORDINATE% akciót, ha a koordinált hajó olyan akciót hajt végre, ami a te akciósávodon is rajta van, végrehajthatod azt az akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután egy 0-1-es távolságban lévő baráti hajó védekezővé válik, elkölthetsz 1 erősítés jelzőt. Ha így teszel, az a hajó kap 1 kitérés jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután védekező lettél (még a kockagurítás előtt), visszatölthetsz 1 %FORCE% jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, ha a védekező felfordított sérülés kártyát kapna, helyette húzz te 3 lapot, válassz egyet, a többit dobd el.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall> """
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy baráti hajó 0-2-es távolságban védekezik, a támadó maximum 1 kockáját dobhatja újra."""
"Major Rhymer":
display_name: """Major Rhymer"""
text: """Amikor végrhajtasz egy %TORPEDO% vagy %MISSILE% támadást, növelheted vagy csökkentheted a fegyver távolság követelményét 1-gyel, a 0-3 korláton belül.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"Major VerPI:NAME:<NAME>END_PI":
display_name: """Major Vermeil"""
text: """Amikor támadást hajtasz végre, ha a védekezőnek nincs egy zöld jelzője sem, megváltoztathatod 1 üres vagy %FOCUS% eredményedet %HIT% eredményre.%LINEBREAK% %LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
"Major VPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel és van 'inaktív fegyverzet' jelződ, dobj 1-gyel több védekezőkockával."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején kiválaszthatsz egy 0-1-es távolságban lévő baráti hajót. Ha így teszel, add át neki az összes zöld jelződ."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor elsődleges támadást hajtasz végre, elkölthetsz 1 pajzsot, hogy 1-gyel több támadókockával dobj, vagy ha nincs pajzsod, dobhatsz 1-gyel kevesebb támadókockával, hogy visszatölts 1 pajzsot."""
"MorPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Ha lerepülsz a pályáról, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, helyezd a hajód tartalékba. A következő Tervezési fázis elején helyezd el a hajót a pálya szélétől 1-es távolságban azon az oldalon, ahol lerepültél."""
"PI:NAME:<NAME>END_PI (Y-Wing)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel, ha az ellenség 0-1-es távolságban van, adj 1 %EVADE% eredményt a dobásodhoz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel, ha az ellenség 0-1-es távolságban van, adj 1 %EVADE% eredményt a dobásodhoz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor elődleges támadást hajtasz végre, ha nincs baráti hajó 0-2 távolságban, dobj 1-gyel több támadókockával."""
"Old PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején, kiválaszthatsz 1 ellenséges hajót 1-es távolságban. Ha így teszel és benne vagy a %FRONTARC% tűzívében, leveheted az összes zöld jelzőjét.%LINEBREAK%<sasmall><strong>Concordia Faceoff:</strong> Amikor védekezel, ha a támadás 1-es távolságban történik és benne vagy a támadó %FRONTARC% tűzívében, megváltoztathatod 1 dobás eredményed %EVADE% eredményre.</sasmall>"""
"Outer Rim Pioneer":
display_name: """Outer RPI:NAME:<NAME>END_PI"""
text: """Baráti hajók 0-1-es távolságban végrehajthatnak támadást akadálytól 0 távolságra.%LINEBREAK%<strong>Co-Pilot:</strong> Amíg dokkolva vagy, az anyahajód megkapja a pilóta képességed, mintha a sajátja lenne."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején kiválaszthatsz 1 ellenséges hajót a tűzívedben 0-2 távolságban. Ha így teszel tedd át 1 fókusz vagy kitérés jelzőjét magadra."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """PI:NAME:<NAME>END_PI védekezel, az <strong>Eredmények semlegesítése</strong> lépés után, egy 0-1 távolságban lévő másik baráti hajó, aki benne van a támadó tűzívében, elszenvedhet 1 %HIT% vagy %CRIT% sérülést. Ha így tesz, hatástalaníts 1 ennek megfelelő eredményt.%LINEBREAK%<sasmall><strong>Microthrusters:</strong> Amikor orsózást hajtasz végre, a %BANKLEFT% vagy %BANKRIGHT% sablont <b>kell</b> használnod a %STRAIGHT% helyett.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején kaphatsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts 1 %CHARGE% jelzőt egy felszerelt fejlesztésen.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, ha van 'reinforce' jelződ és a védekező a reinforce-nak megfelelő %FULLFRONTARC% vagy %FULLREARARC% tűzívedben van, megváltoztathatod 1 %FOCUS% eredményed %CRIT% eredményre."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy támadást, ami talál, ha van kitérés jelződ, fordítsd fel a védekező egy sérülés kártyáját.%LINEBREAK%<strong>Full Throttle:</strong> Miután teljesen végrehajtasz egy 3-5 sebességű manővert, végrehajthatsz egy %EVADE% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején választhatsz 1 tűzívedben lévő hajót. Ha így teszel, a kezdeményezési értéke ebben a fázisban 7 lesz, függetlenül a nyomtatott értékétől."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Mielőtt aktiválódsz, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
"PI:NAME:<NAME>END_PI (TIE Fighter)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Mielőtt aktiválódsz, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót."""
"PI:NAME:<NAME>END_PI (Scum)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel, ha a támadó benne van a %SINGLETURRETARC% tűzívedben 0-2-es távolságban, hozzáadhatsz 1 %FOCUS% eredményt a dobásodhoz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel kezelheted a mozgékonyság értékedet úgy, hogy az megegyezzen az ebben a körben végrehajtott manővered sebességével.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy sérült baráti hajó 0-3-as távolságban végrehajt egy támadást, újradobhat 1 támadókockát."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor egy baráti hajó 0-1-es távolságban védekezik, újradobhatja 1 kockáját.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy elsődleges támadást, az <strong>Eredmények semlegesítése</strong> lépés előtt elkölthetsz 2 %FORCE% jelzőt, hogy hatástalaníts 1 %EVADE% eredményt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy támadást elkölthetsz 1 %CRIT% eredményt. Ha így teszel, a védekező kap 1 lefordított sérülés kártyát, majd hatástalanítsd a többi dobás eredményed."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre, elköltheted az ellenfeledre tett bemérés jelződet, hogy hozzáadj 1 %FOCUS% eredményt dobásodhoz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Ha ledobnál egy eszközt az [1 %STRAIGHT%] sablon használatával, helyette ledobhatod más 1-es sebességű sablonnal."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején, ha van ellenséges hajó a %BULLSEYEARC% tűzívedben, kapsz 1 fókusz jelzőt.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, miután dobtál vagy újradobtál kockákat, ha minden eredményed egyforma, hozzáadhatsz 1 ugyanolyan eredményt a dobáshoz.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor 3-as távolságban védekezel vagy 1-es távolságban támadást hajtasz végre, dobj 1-gyel több kockával."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Ha megsemmisülnél, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, dobd el az összes sérülés kártyádat, szenvedj el 5 %HIT% sérülést, majd helyezd magad tartalékba. A következő Tervezési fázis elején helyezd fel a hajód 1-es távolságban a saját oldaladon."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 stressz jelzőt, hogy minden %FOCUS% eredményed megváltoztasd %EVADE% vagy %HIT% eredményre."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %FOCUS%, %HIT% vagy %CRIT% eredményt, hogy megnézd a védekező képpel lefelé fordított sérülés kártyáit, kiválassz egyet és megfordítsd."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy %RELOAD% akciót, visszatölthetsz 1 %CHARGE% jelzőt 1 felszerelt %TALENT% fejlesztés kártyán.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy támadást, minden ellenséges hajó a %BULLSEYEARC% tűzívedben elszenved 1 %HIT% sérülést, hacsak el nem dob 1 zöld jelzőt.%LINEBREAK%<sasmall><strong>Dead to Rights:</strong> Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, a védekezőkockák nem módosíthatók zöld jelzőkkel.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején kiválaszthatsz 1 hajót a tűzívedben. Ha így teszel, az a hajó ebben a körben 0-ás kezdeményezéssel kerül sorra a normál kezdeményezése helyett."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután végrehajtasz egy támadást, végrehajthatsz egy %BARRELROLL% vagy %BOOST% akciót akkor is ha stresszes vagy.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Az Ütközet fázis elején, ha van egy vagy több másik hajó 0-ás távolságban tőled, te és a 0-ás távolságra lévő hajók kapnak egy vonósugár jelzőt.%LINEBREAK%<strong>Spacetug Tractor Array:</strong> <strong>Akció:</strong>: Válassz egy hajót a %FRONTARC% tűzívedben 1-es távolságban. Az a hajó kap 1 vonósugár jelzőt vagy 2 vonósugár jelzőt, ha benne van a %BULLSEYEARC% tűzívedben 1-es távolságban."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután egy baráti hajó 0-1-es távolságban védekezik - a sérülések elkönyvelése után, ha volt -, végrehajthatsz egy akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy manővert, helyette végrehajthatsz egy manővert ugyanabban az irányban és nehézségben 1-gyel kisebb vagy nagyobb sebességgel.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Miután védekeztél, ha nem pontosan 2 védekezőkockával dobtál, a támadó kap 1 stress jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre, a védekező 1-gyel kevesebb védekezőkockával dob."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor elsődleges támadást hajtasz végre, ha sérült vagy, 1-gyel több támadókockával dobhatsz."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """A Vége fázis alatt elköltheted egy ellenséges hajón lévő bemérődet hogy felfordítsd egy sérülés kártyáját.%LINEBREAK%<sasmall><strong>Advanced Targeting Computer:</strong> Amikor végrehajtasz egy elsődleges támadást egy olyan védekező ellen, akit bemértél, 1-gyel több támadókockával dobj és változtasd 1 %HIT% eredményed %CRIT% eredményre.</sasmall>"""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy elsődleges támadást, 1-gyel több támadókockával dobhatsz. Ha így teszel, a védekező 1-gyel több védekezőkockával dob."""
'"PI:NAME:<NAME>END_PI"':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """Az Ütközet fázis elején minden 0-ás távolságban lévő ellenséges hajó 2 zavarás jelzőt kap.%LINEBREAK%<strong>Tail Gun:</strong> ha van bedokkolt hajód, használhatod az elsődleges %REARARC% fegyvered, ugyanolyan támadási értékkel, mint a dokkolt hajó elsődleges %FRONTARC% támadási értéke."""
'"Countdown"':
display_name: """“Countdown”"""
text: """Amikor védekezel, az <strong>Eredmények semlegesítése</strong> lépés után, ha nem vagy stresszes, választhatod, hogy elszenvedsz 1 %HIT% sérülést és kapsz 1 stressz jelzőt. Ha így teszel, vess el minden kocka dobást.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Deathfire"':
display_name: """“Deathfire”"""
text: """Miután megsemmisülsz, mielőtt levennéd a hajód, végrehajthatsz egy támadást és ledobhatsz vagy kilőhetsz 1 eszközt.%LINEBREAK%<strong>Nimble Bomber:</strong> Ha ledobnál egy eszközt a %STRAIGHT% sablon segítségével, használhatod az azonos sebességű %BANKLEFT% vagy %BANKRIGHT% sablonokat helyette."""
'"Deathrain"':
display_name: """“Deathrain”"""
text: """Miután ledobsz vagy kilősz egy eszközt, végrehajthatsz egy akciót."""
'"Double Edge"':
display_name: """“Double Edge”"""
text: """Miután végrehajtasz egy %TURRET% vagy %MISSILE% támadást ami nem talál, végrehajthatsz egy bónusz támadást egy másik fegyverrel."""
'"DPI:NAME:<NAME>END_PI"':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """Választhatsz úgy, hogy nem használod az <strong>Adaptive Ailerons</strong> képességed. Használhatod akkor is <strong>Adaptive Ailerons</strong> képességed, amikor stresszes vagy.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"Dutch" Vander':
display_name: """“Dutch” Vander"""
text: """Miután %LOCK% akciót hajtottál végre választhatsz 1 baráti hajót 1-3-as távolságban. Az a hajó is bemérheti az általad bemért objektumot, függetlenül a távolságtól."""
'"Echo"':
display_name: """“Echo”"""
text: """Amikor kijössz az álcázásból, a [2 %BANKLEFT%] vagy [2 %BANKRIGHT%] sablont <b>kell</b> használnod a [2 %STRAIGHT%] helyett.%LINEBREAK%<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
'"Howlrunner"':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """Amikor egy 0-1-es távolságban lévő baráti hajó elsődleges támadást hajt végre, 1 támadókockát újradobhat."""
'"PI:NAME:<NAME>END_PI"':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """Miután védekeztél vagy támadást hajtottál végre, ha elköltöttél egy kalkuláció jelzőt, kapsz 1 kalkuláció jelzőt.%LINEBREAK%<strong>Sensor Blindspot:</strong> Amikor elsődleges támadást hajtasz végre 0-1-es távolságban, nem érvényesül a 0-1-es távolságért járó bónusz és 1-gyel kevesebb támadókockával dobsz."""
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
display_name: """“PI:NAME:<NAME>END_PI” PI:NAME:<NAME>END_PI"""
text: """Amikor támadást hajtasz végre 1-es távolságban, dobj 1-gyel több támadókockával."""
'"Night Beast"':
display_name: """“Night Beast”"""
text: """Miután teljesen végrehajtasz egy kék manővert, végrehajthatsz egy %FOCUS% akciót."""
'"Pure Sabacc"':
display_name: """“Pure SPI:NAME:<NAME>END_PI”"""
text: """Amikor támadást hajtasz végre, ha 1 vagy kevesebb sérüléskártyád van, 1-gyel több támadókockával dobhatsz.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"RedPI:NAME:<NAME>END_PI"':
display_name: """“RedPI:NAME:<NAME>END_PI”"""
text: """Fenntarthatsz 2 bemérő jelzőt. Miután végrehajtasz egy akciót, feltehetsz egy bemérő jelzőt."""
'"SPI:NAME:<NAME>END_PI" SkPI:NAME:<NAME>END_PIu':
display_name: """“PI:NAME:<NAME>END_PI” PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy támadást a %BULLSEYEARC% tűzívedben lévő védekező ellen, dobj 1-gyel több támadókockával."""
'"PI:NAME:<NAME>END_PI"':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """Miután teljesen végrehajtasz egy 1-es sebességű manővert az <strong>Adaptive Ailerons</strong> képességed használatával, végrehajthatsz egy %COORDINATE% akciót. Ha így teszel, hagyd ki az <strong>Akció végrehajtása</strong> lépést.%LINEBREAK%<sasmall><strong>Adaptive Ailerons:</strong> Mielőtt felfednéd a tárcsád, ha nem vagy stresszes, végre <b>kell</b> hajtanod egy fehér [1 %BANKLEFT%), [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] manővert.</sasmall>"""
'"WPI:NAME:<NAME>END_PI"':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """Amikor végrehajtasz egy támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy 1-gyel több támadókockával dobj. Védekezés után elvesztesz 1 %CHARGE% jelzőt."""
'"Whisper"':
display_name: """“Whisper”"""
text: """Miután végrehajtasz egy támadást ami talál, kapsz 1 kitérés jelzőt.%LINEBREAK%<strong>Stygium Array:</strong> Miután kijössz az álcázásból végrehajthatsz egy %EVADE% akciót. A Vége fázis elején elkölthetsz 1 kitérés jelzőt, hogy kapj egy álcázás jelzőt."""
'"Zeb" Orrelios':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál.%LINEBREAK%<sasmall><strong>Locked and Loaded:</strong> Amikor dokkolva vagy, miután az anyahajód végrehajtott egy elsődleges %FRONTARC% vagy %TURRET% támadást, végrehajthat egy bónusz %REARARC% támadást.</sasmall>"""
'"Zeb" Orrelios (Sheathipede)':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál.%LINEBREAK%<sasmall><strong>Comms Shuttle:</strong> Amikor dokkolva vagy az anyahajód %COORDINATE% akció lehetőséget kap. Az anyahajód aktiválása előtt végrehajthat egy %COORDINATE% akciót.</sasmall>"""
'"Zeb" Orrelios (TIE Fighter)':
display_name: """“Zeb” Orrelios"""
text: """Amikor védekezel a %CRIT% találatok előbb semlegesítődnek a %HIT% találatoknál."""
"PoPI:NAME:<NAME>END_PI":
text: """Miután végrehajtasz egy akciót, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy fehér akciót pirosként kezelve.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután egy hajó 1-2-es távolságban felhúz egy sérülés kártyát, felrakhatsz rá egy bemérő jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
'"Midnight"':
text: """Amikor védekezel vagy támadás hajtasz végre, ha van bemérőd azon az ellenséges hajón, az nem módosíthatja a kockáit."""
'"Longshot"':
text: """Amikor elsődleges támadást hajtasz végre 3-as távolságban, dobj 1-gyel több támadókockával."""
'"MPI:NAME:<NAME>END_PI"':
text: """Az Ütközet fázis elején válaszhatsz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó vegyen le 1 stressz jelzőt."""
"PI:NAME:<NAME>END_PI":
text: """Miután védekeztél, elkölthetsz 1 %FORCE% jelzőt, hogy hozzárendeled az <strong>I'll Show You the Dark Side</strong> kondíciós kártyát a támadódhoz.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
'"Blackout"':
text: """Amikor végrehajtasz egy támadást, ha a támadás akadályozott egy akadály által, a védekező 2-vel kevesebb védekezőkockával dob.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Felhelyezés: Miután felhelyezésre kerültél, a többi baráti hajó bárhova helyezhető a játékterületen tőled 0-2-es távolságban.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Backdraft"':
text: """Amikor végrehajtasz egy %SINGLETURRETARC% elsődleges támadást, ha a védekező benne van a %REARARC% tűzívedben dobj 1-gyel több kockával.%LINEBREAK%<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
'"Quickdraw"':
text: """Miután elvesztesz egy pajzsot, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, végrehajthatsz egy bónusz elsődleges támadást.%LINEBREAK%<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Zeta Squadron Survivor":
text: """<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Rey":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy 1 üres eredményed %EVADE% vagy %HIT% eredményre változtasd."""
"Han Solo (Resistance)":
text: """Felhelyezés: Bárhova felhelyezheted a hajód a játékterületre 3-as távolságon túl az ellenséges hajóktól."""
"Chewbacca (Resistance)":
text: """Miután egy baráti hajó 0-3-as távolságban megsemmisül, végrehajthatsz egy akciót. Aztán végrehajthatsz egy bónusz támadást."""
"PI:NAME:<NAME>END_PI":
text: """Amikor védekezel vagy támadást hajtasz végre, mielőtt a támadókockát elgurulnának, ha nem vagy az ellenséges hajó %BULLSEYEARC% tűzívében, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az ellenséges hajó kap egy zavarás jelzőt.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Mining Guild Surveyor":
text: """<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"Mining Guild Sentry":
text: """<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"PI:NAME:<NAME>END_PI":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az elleséges hajó nagyobb talpméretű, dobj 1-gyel több kockával.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"PI:NAME:<NAME>END_PI":
text: """Mielőtt ledobnál egy bombát, ledobás helyett elhelyezheted a játékterületen úgy, hogy érintkezzen veled."""
"Major Stridan":
text: """Amikor koordinálsz vagy egy fejlesztés kártyád hatását alkalmaznád, kezelheted úgy a 2-3-as távolságban lévő baráti hajókat, mintha 0 vagy 1-es távolságban lennének.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"PI:NAME:<NAME>END_PI":
text: """Amikor gyorsítasz (%BOOST%), használhatod a [1 %TURNLEFT%] vagy [1 %TURNRIGHT%] sablonokat is.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután elvesztesz 1 pajzsod, kapsz 1 %EVADE% jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután egy hajó 1-2-es távolságban felhúz egy sérülés kártyát, felrakhatsz rá egy bemérő jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy kék manővert, választhatsz egy baráti hajót 0-1-es távolságban. Ha így teszel, az a hajó levesz egy stressz jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Black Squadron Ace (T-70)":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Red Squadron Expert":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Blue Squadron Rookie":
text: """<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Cobalt Squadron Bomber":
text: """ """
"TN-3465":
text: """Amikor egy másik baráti hajó támadást hajt végre, ha 0-1 távolságban vagy a védekezőtől, elszenvedhetsz 1 %CRIT% sérülést, hogy a támadó 1 eredményét %CRIT% eredményre változtassa."""
'"Scorch"':
text: """Amikor elsődleges támadást hajtasz végre, ha nem vagy stresszes, kaphatsz 1 stressz jelzőt, hogy 1-gyel több támadókockával dobj."""
'"Longshot"':
text: """Amikor elsődleges támadást hajtasz végre 3-as távolságban, dobj 1-gyel több támadókockával."""
'"Static"':
text: """Amikor elsődleges támadást hajtasz végre, elköltheted a védekezőn lévő bemérődet és egy %FOCUS% jelződ, hogy minden eredményed %CRIT% eredményre változtass."""
"PI:NAME:<NAME>END_PI":
text: """Miután egy hajó 1-2-es távolságban kap egy piros vagy narancs jelzőt, ha nem volt bemérőd a hajón, feltehetsz egyet rá."""
"PI:NAME:<NAME>END_PI":
text: """Az Ütközet fázis elején elkölthetsz 1 %CHARGE% jelzőt, hogy kapj 1 stressz jelzőt. Ha így teszel, a kör végéig ha védekezel vagy támadást hajtasz végre, megváltoztathatsz minden %FOCUS% eredményed %EVADE% vagy %HIT% eredményre."""
"Omega Squadron Ace":
text: """"""
"Zeta Squadron Pilot":
text: """"""
"Epsilon Squadron Cadet":
text: """"""
"PI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy manővert, forgathatod a %SINGLETURRETARC% tűzívedet.%SINGLETURRETARC% %LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre, ha stresszes vagy, 1-gyel kevesebb védekezőkockával vagy 1-gyel több támadókockával <strong>kell</strong> dobnod.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Ne hagyd ki az <strong>Akció végrehajtása</strong> lépést, miután részlegesen hajtottál végre egy manővert.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Amikor egy ellenséges hajó a %BULLSEYEARC% tűzívedben végrehajt egy támadást, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a védekező 1-gyel több kockával dob.%LINEBREAK%<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Miután végrehajtasz egy támadást, elkölthetsz 2 %FORCE% jelzőt, hogy végrehajts egy bónusz elsődleges támadást egy másik célpont ellen. Ha az első támadás nem talált, a bónusz támadást végrehajthatod ugyanazon célpont ellen."""
'"PI:NAME:<NAME>END_PI"':
text: """Amikor 1-2-es távolságban és a %LEFTARC% vagy %RIGHTARC% tűzívedben lévő baráti hajó végrehajt egy elsődleges támadást, újradobhat 1 támadókockát."""
"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI":
text: """Az Aktivációs vagy Ütközet fázis közben, miután egy hajó a %FRONTARC% tűzívedben 1-2-es távolságban kap 1 stressz jelzőt, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó kap egy vonósugár jelzőt.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"Captain CardPI:NAME:<NAME>END_PI":
text: """Amikor egy baráti hajó 1-2-es távolságban, a tiédnél alacsonyabb kezdeményezéssel védekezik vagy támadást hajt végre, ha van legalább 1 %CHARGE% jelződ, az a hajó újradobhat 1 %FOCUS% eredményét. Miután egy ellenséges hajó 0-3-as távolságban megsemmisül, elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Avenger"':
text: """Miután egy ellenséges hajó 0-3-as távolságban megsemmisül végrehajthatsz egy akciót, akkor is ha stresszes vagy. %LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
'"Recoil"':
text: """Amikor stresszes vagy kezelheted úgy a %FRONTARC% tűzívedben 0-1-es távolságban lévő ellenséges hajókat, mintha a %BULLSEYEARC% tűzívedben lennének.%LINEBREAK%<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Omega Squadron Expert":
text: """<strong>Heavy Weapon Turret:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. A felszerelt %MISSILE% fejlesztésed %FRONTARC% követelményét kezeld úgy mintha %SINGLETURRETARC% lenne."""
"Sienar-Jaemus Engineer":
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"First Order Test Pilot":
text: """<strong>Autothrusters:</strong> Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BARRELROLL% vagy piros %BOOST% akciót."""
"Starkiller Base Pilot":
text: """<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
"PI:NAME:<NAME>END_PI":
text: """Miután sérülést szenvedsz el, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy akciót.%LINEBREAK%<strong>Linked battery:</strong> Amikor végrehajtasz egy %CANNON% támadást, dobj 1-gyel több támadókockával."""
'"Null"':
text: """Amíg nem vagy sérült, kezeld a kezdeményezési értéked 7-esként."""
"Cat":
text: """Amikor elsődleges támadást hajtasz végre, ha a védekező 0-1-es távolságban van legalább 1 baráti eszköztől, dobj 1-gyel több kockával."""
"PI:NAME:<NAME>END_PI":
text: """Miután végrehajtasz egy támadást, ha a védekező benne van a %SINGLETURRETARC% tűzívedben, rendeld hozzá a <strong>Rattled</strong> kondíciós kártyát a védekezőhöz."""
"PI:NAME:<NAME>END_PI":
text: """Amikor védkezel, ha a támadó benne van egy baráti hajó %SINGLETURRETARC% tűzívében, hozzáadhatsz 1 %FOCUS% eredményt a dobásodhoz."""
"PI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy kék vagy fehér manővert, ha még nem dobtál vagy lőttél ki eszközt ebben a körben, kidobhatsz egy eszközt."""
"Resistance Sympathizer":
text: """"""
"PI:NAME:<NAME>END_PI":
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CHARGE% jelzőt vagy a felszerelt %ASTROMECH% fejlesztéseden lévő 1 nem visszatölthető %CHARGE% jelzőt, hogy újradobj 1 kockát minden 0-1-es távolságban lévő baráti hajó után.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy 2-4 sebességű manővert, végrehajthatsz egy %BOOST% akciót%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután kapsz egy stressz jelzőt, ha van ellenséges hajó a %FRONTARC% tűzívedben 0-1 távolságban, leveheted a kapott stressz jelzőt.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"PI:NAME:<NAME>END_PI":
text: """Miután felfedtél egy piros Tallon Roll (%TROLLLEFT% vagy %TROLLRIGHT%) manővert, ha 2 vagy kevesebb stressz jelződ van, kezeld a manővert fehérként.%LINEBREAK%<strong>Weapon Hardpoint:</strong> Felszerelhetsz 1 %CANNON%, %TORPEDO% vagy %MISSILE% fejlesztést."""
"Blue Squadron Recruit":
text: """<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Green Squadron Expert":
text: """<strong>Refined Gyrostabilizers:</strong> A %SINGLETURRETARC% mutatódat csak %FRONTARC% vagy %REARARC% irányba forgathatod. Miután végrehajtasz egy akciót, végrehajthatsz egy piros %BOOST% vagy %ROTATEARC% akciót."""
"Foreman Proach":
text: """Mielőtt sorra kerülsz az Ütközet fázisban, választhasz 1 ellenséges hajót a %BULLSEYEARC% tűzívedben 1-2-es távolságban és kapsz 1 'inaktív fegyverzet' jelzőt. Ha így teszel, az a hajó kap 1 vonósugár jelzőt.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"PI:NAME:<NAME>END_PI":
text: """Mielőtt egy baráti hajó 1-es távolságban kapna 1 'inaktív fegyverzet' jelzőt, ha az a hajó nem stresszes, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, az a hajó 1 stressz jelzőt kap helyette.%LINEBREAK%<strong>Notched Stabilizers:</strong> Amikor mozogsz, hagyd figyelmen kívül az aszteroidákat."""
"General Grievous":
text: """Amikor elsődleges támadást hajtasz végre, ha nem vagy a védekező tűzívében, újradobhatod akár 2 támadókockádat is."""
"PI:NAME:<NAME>END_PI":
text: """Amikor elsődleges támadást hajtasz végre, újradobhatsz 1 támadókockát minden kalkuláció tokennel rendelkező baráti hajó után ami a védekezőtől 1-es távolságban van."""
"PI:NAME:<NAME>END_PI":
text: """Amikor egy baráti hajó 0-3-as távolságban végrehajt egy elsődleges támadást, ha a védekező benne van annak %BULLSEYEARC% tűzívében, az 'Eredmények semlegesítése' lépés előtt a baráti hajó elkölthet 1 %CALCULATE% jelzőt, hogy semlegesítsen 1 %EVADE% eredményt."""
"PI:NAME:<NAME>END_PI":
text: """Amikor támadást hajtasz végre, ha a védekező benne van a %BULLSEYEARC% tűzívedben, újradobhatsz 1 üres eredményt.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"Haor Chall Prototype":
text: """Miután egy ellenséges hajó a %BULLSEYEARC% tűzívedben 0-2-es távolságban védekezőnek jelöl egy másik baráti hajót, végrehajthatsz egy %CALCULATE% vagy %LOCK% akciót.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"DFS-081":
text: """Amikor egy baráti hajó 0-1 távolságban védekezik, elkölthet 1 %CALCULATE% jelzőt, hogy az összes %CRIT% eredményt %HIT% eredményre változtassa.%LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"PI:NAME:<NAME>END_PI":
text: """Miután egy baráti hajó 0-2-es távolságban elkölt egy %FOCUS% jelzőt, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, az a hajó kap 1 %FOCUS% jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy manővert, választhatsz egy baráti hajót 0-1-es távolságban és költs el 1 %FORCE% jelzőt. Az a hajó végrehajthat egy akciót még ha stresszes is. %LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy manővert, ha van egy ellenséges hajó a %FRONTARC% tűzívedben 0-1 távolságban vagy a %BULLSEYEARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy levegyél 1 stressz jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Amikor egy baráti hajó 0-2-es távolságban támadást hajt végre, ha a védekező benne van annak %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt, hogy átforgass 1 %FOCUS% eredményt %HIT% eredményre vagy 1 %HIT% eredményt %CRIT% eredményre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Amikor egy baráti hajó 0-2-es távolságban védekezik, ha az nincs a támadó %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, forgass át 1 %CRIT% eredményt %HIT% eredményre vagy 1 %HIT% eredményt %FOCUS% eredményre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Az Ütközet fázis elején elkölthetsz 1 %FORCE% jelzőt, hogy válassz egy másik baráti hajót 0-2-es távolságban. Ha így teszel, átadhatsz 1 zöld jelzőt neki vagy átvehetsz egy narancs jelzőt magadra.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Miután egy baráti hajó 0-2-es távolságban felfedi a tárcsáját elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, állítsd át a tárcsáját egy másik hasonló sebességű és nehézségű manőverre.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
"MPI:NAME:<NAME>END_PI":
text: """Miután teljesen végrehajtasz egy piros manővert, tölts vissza 1 %FORCE% jelzőt.%LINEBREAK% FINE-TUNED CONTROLS: Miután teljesen végrehajtasz egy manővert, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BOOST% vagy %BARRELROLL% akciót."""
'"Kickback"':
text: """Miután végrehajtasz egy %BARRELROLL% akciót, végrehajthatsz egy piros %LOCK% akciót."""
'"Odd Ball"':
text: """Miután teljesen végrehajtasz egy piros manővert vagy piros akciót, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, feltehetsz egy bemérőt arra a hajóra."""
'"Sinker"':
text: """Amikor egy baráti hajó 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben elsődleges támadást hajt végre, újradobhat 1 támadókockát."""
'"Swoop"':
text: """Miután egy baráti kis vagy közepes hajó teljesen végrehajt egy 3-4 sebességű manővert, ha az 0-1-es távolságban van tőled, végrehajthat egy piros %BOOST% akciót."""
'"Axe"':
text: """Miután védekezel vagy támadást hajtasz végre, választhatsz egy baráti hajót 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben. Ha így teszel add át 1 zöld jelződet annak a hajónak."""
'"PI:NAME:<NAME>END_PI"':
text: """Miután egy baráti hajó 1-2-es távolságban végrehajt egy támadást egy ellenséges hajó ellen a %FRONTARC% tűzívedben, végrehajthatsz egy %FOCUS% akciót."""
"PI:NAME:<NAME>END_PI":
text: """Amikor ledobnál egy eszközt, ki is lőheted, ugyanazt a sablont használva. %LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
"PI:NAME:<NAME>END_PI":
text: """Miután védekeztél, ha a támadó benne van a tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy levedd egy kék vagy piros jelződ.%LINEBREAK% Miután végrehajtasz egy támadást ami talált, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy akciót."""
"0-66":
text: """Miután védekezel, elkölthetsz 1 %CALCULATE% jelzőt, hogy végrehajts egy akciót."""
"DFS-311":
text: """Az Üzközet fázis elején, átteheted 1 %CALCULATE% jelződet egy másik baráti hajóra 0-3-as távolságban. %LINEBREAK% NETWORKED CALCULATIONS: Amikor védekezel vagy támadást hajtasz végre, elkölthetsz 1 %CALCULATE% jelzőt egy 0-1-es távolságban lévő baráti hajóról, hogy megváltoztass 1 %FOCUS% eredményt %EVADE% vagy %HIT% eredményre."""
'"Odd Ball" (ARC-170)':
text: """Miután teljesen végrehajtasz egy piros manővert vagy piros akciót, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, feltehetsz egy bemérőt arra a hajóra."""
'"PI:NAME:<NAME>END_PI"':
text: """Miután egy baráti hajó 1-2-es távolságban a %LEFTARC% vagy %RIGHTARC% tűzívedben védekezik, feltehetsz egy bemérőt a támadóra."""
'"PI:NAME:<NAME>END_PI"':
text: """Amikor végrehajtasz egy elsődleges %FRONTARC% támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 támadókockát. %LINEBREAK% Amikor végrehajtasz egy elsődleges %REARARC% támadást, visszaállíthatsz 1 %CHARGE% jelzőt, hogy 1-gyel több támadókockával dobj"""
upgrade_translations =
"0-0-0":
display_name: """0-0-0"""
text: """<i>Söpredék vagy Darth Vader a csapatban</i>%LINEBREAK%Az Ütközet fázis elején, kiválaszthatsz 1 ellenséges hajót 0-1-es távolságban. Ha így teszel, kapsz egy kalkuláció jelzőt, hacsak a hajó nem választja, hogy kap 1 stressz jelzőt."""
"4-LOM":
display_name: """4-LOM"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, a támadókockák eldobása után, megnevezhetsz egy zöld jelző típust. Ha így teszel, kapsz 2 ion jelzőt és ezen támadás alatt a védekező nem költheti el a megnevezett típusú jelzőt."""
"Andrasta":
display_name: """AndPI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%<i>Kapott akció %RELOAD%</i>%LINEBREAK%Kapsz egy %DEVICE% fejlesztés helyet."""
"Dauntless":
display_name: """DaPI:NAME:<NAME>END_PI"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután részlegesen hajtottál végre egy manővert, végrehajthatsz 1 fehér akciót pirosként kezelve."""
"Ghost":
display_name: """Ghost"""
text: """<i>csak Lázadók</i>%LINEBREAK%Bedokkoltathatsz 1 Attack shuttle-t vagy Sheathipede-class shuttle-t. A dokkolt hajót csak a hátsó pöcköktől dokkolhatod ki."""
"Havoc":
display_name: """HPI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Elveszted a %CREW% fejlesztés helyet. Kapsz egy %SENSOR% és egy %ASTROMECH% fejlesztés helyet."""
"Hound's Tooth":
display_name: """Hound’s Tooth"""
text: """<i>csak Söpredék</i>%LINEBREAK%1 Z-95-AF4 headhunter bedokkolhat."""
"IG-2000":
display_name: """IG-2000"""
text: """<i>csak Söpredék</i>%LINEBREAK%Megkapod minden másik <strong>IG-2000</strong> fejlesztéssel felszerelt baráti hajó pilóraképességét."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges %REARARC% támadást, újradobhatsz 1 támadókockádat. Kapsz egy %GUNNER% fejlesztés helyet."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%<i>Kapott akció %EVADE%</i>%LINEBREAK%Amikor védekezel, ha van kitérés jelződ, újradobhatsz 1 védekezőkockát."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%<i>Kapott akció %BARRELROLL%</i>%LINEBREAK%Kapsz egy %CANNON% fejlesztés helyet."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók vagy Söpredék</i>%LINEBREAK%Kapsz egy %FRONTARC% elsődleges fegyvert 3-as támadóértékkel. A Vége fázis alatt megtarthatsz maximum 2 fókusz jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy támadást ami egy akadály által akadályozott, a védekező 1-gyel kevesebb védekezőkockával dob. Miután teljesen végrehajtasz egy manővert, ha áthaladtál vagy átfedésbe kerültél egy akadállyal, levehetsz 1 piros vagy narancs jelződet."""
"Phantom":
display_name: """Phantom"""
text: """<i>csak Lázadók</i>%LINEBREAK%Be tudsz dokkolni 0-1 távolságból."""
"Punishing One":
display_name: """Punishing One"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %FRONTARC% tűzívedben, dobj 1-gyel több támadókockával. Elveszted a %CREW% fejlesztés helyet. Kapsz egy %ASTROMECH% fejlesztés helyet."""
"ST-321":
display_name: """ST-321"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy %COORDINATE% akciót, kiválaszthatsz egy ellenséges hajót 0-3-as távolságban a koordinált hajótól. Ha így teszel, tegyél fel egy bemérőt arra az ellenséges hajóra figyelmen kívül hagyva a távolság megkötéseket."""
"Shadow Caster":
display_name: """Shadow Caster"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután végrehajtasz egy támadást ami talál, ha a védekező benne van a %SINGLETURRETARC% és %FRONTARC% tűzívedben is, a védekező kap 1 vonósugár jelzőt."""
"Slave I":
display_name: """Slave I"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután felfedtél egy kanyar (%TURNLEFT% vagy %TURNRIGHT%) vagy ív (%BANKLEFT% vagy %BANKRIGHT%) manővert, átforgathatod a tárcsádat az ellenkező irányba megtartva a sebességet és a mozgásformát. Kapsz egy %TORPEDO% fejlesztés helyet."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>Kapsz egy %MODIFICATION% fejlesztés helyet. Adj 1 pajzs értéket a hajódhoz.</i>%LINEBREAK%A Vége fázis alatt, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy piros %BOOST% akciót."""
"Ablative Plating":
display_name: """Ablative Plating"""
text: """<i>közepes vagy nagy talp</i>%LINEBREAK%Mielőtt sérülést szenvednél egy akadálytól vagy baráti bomba robbanástól, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, megakadályozol 1 sérülést."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután másik baráti hajó 0-3 távolságban védekezik, ha megsemmisül a támadó kap 2 stressz jelzőt. Amikor egy baráti hajó 0-3 távolságban végrehajt egy támadást egy stresszelt hajó ellen, 1 támadókockát újradobhat."""
"Adv. Proton Torpedoes":
display_name: """Adv. Proton Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong>Támadás (%LOCK%): Költs el 1 %CHARGE% jelzőt. Változtass 1 %HIT% eredményt %CRIT% eredményre."""
"Advanced SLAM":
display_name: """Advanced SLAM"""
text: """<i>Követelmény: %SLAM%</i>%LINEBREAK%Miután végrehajtasz egy %SLAM% akciót, ha teljesen végrehajtod azt a manővert, végrehajthatsz egy fehér akciót az akciósávodról pirosként kezelve."""
"Advanced Sensors":
display_name: """Advanced Sensors"""
text: """Miután felfeded a tárcsádat, végrehajthatsz 1 akciót. Ha így teszel, nem hajthatsz végre másik akciót a saját aktivációdban."""
"Afterburners":
display_name: """Afterburners"""
text: """<i>csak kis hajó</i>%LINEBREAK%Miután teljesen végrehajtasz egy 3-5 sebességű manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BOOST% akciót, még ha stresszes is vagy."""
"Agent PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"""
text: """<i>csak Birodalom</i>%LINEBREAK%<strong>Felhelyezés:</strong> rendelt hozzá a <strong>Hunted</strong> kondíciót 1 ellenséges hajóhoz. Amikor végrehajtasz egy támadást a <strong>Hunted</strong> kondícióval rendelkező hajó ellen, 1 %FOCUS% eredményed %HIT% eredményre változtathatod."""
"Agile Gunner":
display_name: """Agile Gunner"""
text: """A Vége fázisban elforgathatod a %SINGLETURRETARC% mutatódat."""
"BT-1":
display_name: """BT-1"""
text: """<i>Söpredék vagy PI:NAME:<NAME>END_PI a csapatban</i>%LINEBREAK%Amikor végrehajtasz egy támadást, megváltoztathatsz 1 %HIT% eredményt %CRIT% eredményre minden stressz jelző után ami a védekezőnek van."""
"Barrage Rockets":
display_name: """Barrage Rockets"""
text: """<strong>Támadás (%FOCUS%):</strong> Költs el 1 %CHARGE% jelzőt. Ha a védekező benne van a %BULLSEYEARC% tűzívedben, elkölthetsz 1 vagy több %CHARGE% jelzőt, hogy újradobj azzal egyenlő számú támadókockát."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy %FOCUS% akciót, kezelheted pirosként. Ha így teszel minden egyes 0-1 távolságban lévő ellenséges hajó után kapsz 1 további fókusz jelzőt, de maximum 2 darabot."""
"Bistan":
display_name: """Bistan"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, ha van fókusz jelződ, végrehajthatsz egy bónusz %SINGLETURRETARC% támadást egy olyan hajó ellen, akit még nem támadtál ebben a körben."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> tartalékban kezdesz. A Felrakási fázis végén tedd a hajód 0 távolságra egy akadálytól, de 3-as távolságon túl az ellenséges hajóktól."""
"Bomblet Generator":
display_name: """Bomblet Generator"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobd a Bomblet bombát a [1 %STRAIGHT%] sablonnal. Az Aktivációs fázis elején elkölthetsz 1 pajzsot, hogy visszatölts 2 %CHARGE% jelzőt."""
"Bossk":
display_name: """Bossk"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást ami nem talál, ha nem vagy stresszes kapsz 1 stressz jelzőt, hogy végrehajts egy bónusz támadást ugyanazon célpont ellen."""
"C-3PO":
display_name: """C-3PO"""
text: """<i>Kapott akció: %CALCULATE%</i>%LINEBREAK%<i>csak Lázadók</i>%LINEBREAK%Védekezőkocka gurítás előtt, elkölthetsz 1 %CALCULATE% jelzőt hogy hangosan tippelhess egy 1 vagy nagyobb számra. Ha így teszel és pontosan annyi %EVADE% eredményt dobsz, adjál hozzá még 1 %EVADE% eredményt. Miután végrehajtasz a %CALCULATE% akciót, kapsz 1 %CALCULATE% jelzőt."""
"Cad Bane":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután ledobsz vagy kilősz egy eszközt, végrehajthatsz egy piros %BOOST% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%A Rendszer fázis alatt választhatsz 1 ellenséges hajót 1-2-es távolságban. Tippeld meg hangosan manővere irányát és sebességét, aztán nézd meg a tárcsáját. Ha az iránya és sebessége egyezik a tippeddel, megváltoztathatod a saját tárcsádat egy másik manőverre."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis elején elkölthetsz 2 %CHARGE% jelzőt, hogy megjavíts 1 felfordított sérülés kártyát."""
"PI:NAME:<NAME>END_PI (ScPI:NAME:<NAME>END_PI)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis elején elkölthetsz 1 %FOCUS% jelzőt, hogy megjavíts 1 felfordított sérülés kártyát."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>Követelmény %COORDINATE% vagy <r>%COORDINATE%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%Miután végrehajtasz egy %COORDINATE% akciót, ha a koordinált hajó végrehajt egy %BARRELROLL% vagy %BOOST% akciót, kaphat 1 stressz jelzőt, hogy elforduljon 90 fokot."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis alatt, választhatsz 2 %ILLICIT% fejlesztést ami baráti hajókra van felszerelve 0-1-es távolságban. Ha így teszel, megcserélheted ezeket a fejlesztéseket. A játék végén: tegyél vissza minden %ILLICIT% fejlesztést az eredeti hajójára."""
"Cloaking Device":
display_name: """Cloaking Device"""
text: """<i>kis vagy közepes talp</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy végrehajts egy %CLOAK% akciót. A tervezési fázis elején dobj 1 támadó kockával. %FOCUS% eredmény esetén hozd ki a hajód álcázásból vagy vedd le az álcázás jelzőt."""
"Cluster Missiles":
display_name: """Cluster Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Ezen támadás után végrehajthatod ezt a támadást, mint bónusz támadás egy másik célpont ellen 0-1 távolságra a védekezőtől, figyelmen kívül hagyva a %LOCK% követelményt."""
"Collision Detector":
display_name: """Collision Detector"""
text: """Amikor orsózol vagy gyorsítasz átmozoghatsz vagy rámozoghatsz akadályra. Miután átmozogtál vagy rámozogtál egy akadályra, elkölthetsz 1 %CHARGE% jelzőt, hogy figyelmen kívül hagyhatsd az akadály hatását a kör végéig."""
"Composure":
display_name: """Composure"""
text: """<i>Követelmény <r>%FOCUS%</r> vagy %FOCUS%</i>%LINEBREAK%Ha nem sikerül végrehajtani egy akciót és nincs zöld jelződ, végrehajthatsz egy %FOCUS% akciót."""
"Concussion Missiles":
display_name: """Concussion Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Ha a támadás talált, a védekezőtől 0-1 távolságban lévő minden hajó felfordítja egy sérülés kártyáját."""
"Conner Nets":
display_name: """Conner Nets"""
text: """<strong>Akna</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Conner Net aknát a [1 %STRAIGHT%] sablonnal. Ennak a kártyának a %CHARGE% jelzője <strong>nem</strong> újratölthető."""
"Contraband Cybernetics":
display_name: """Contraband Cybernetics"""
text: """Mielőtt aktiválódnál, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a kör végéig végrehajthatsz akciókat és piros manővereket, még stresszesen is."""
"Crack Shot":
display_name: """Crack Shot"""
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, még az <strong>Eredmények semlegesítése</strong> lépés előtt elkölthetsz 1 %CHARGE% jelzőt hogy hatástalaníts 1 %EVADE% eredményt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>Követelmény %BOOST%</i>%LINEBREAK%<i>csak kis hajó</i>%LINEBREAK%Amikor végrehajtasz egy fehér %BOOST% akciót, kezelheted pirosként, hogy a [1 %TURNLEFT%] vagy [1 %TURNRIGHT%] sablokokat használhasd."""
"DPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Ütközet fázis elején, válaszhatsz 1 hajót a tűzívedben 0-2-es távolságban és költs el 1 %FORCE% jelzőt. Ha így teszel, az a hajó elszenved 1 %HIT% sérülést, hacsak úgy nem dönt, hogy eldob 1 zöld jelzőt."""
"Deadman's Switch":
display_name: """Deadman’s Switch"""
text: """Miután megsemmisültél, minden hajó 0-1 távolságban elszenved 1 %HIT% sérülést."""
"Death Troopers":
display_name: """Death Troopers"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Aktivációs fázis alatt az ellenséges hajók 0-1-es távolságban nem vehetik le a stressz jelzőjüket."""
"Debris Gambit":
display_name: """DebrPI:NAME:<NAME>END_PI GPI:NAME:<NAME>END_PIbit"""
text: """<i>Kapott akció: <r>%EVADE%</r></i>%LINEBREAK%<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor végrehajtasz egy piros %EVADE% akciót, ha van 0-1-es távolságban egy akadály, kezeld az akciót fehérként."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután védekezel, ha a támadó a tűzívedben van, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, dobj 1 támadókockával, hacsak a támadó úgy nem dönt, hogy eldobja 1 zöld jelzőjét. %HIT% vagy %CRIT% eredmény esetén a támadó elszenved 1 %HIT% sérülést."""
"Director PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"""
text: """<i>Kapott akció %LOCK%</i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%<strong>Felhelyezés:</strong> a hajók felhelyezése előtt, rendeld hozzá az <strong>Optimized Prototype</strong> kondíciót egy másik baráti hajóhoz."""
"Dorsal Turret":
display_name: """PI:NAME:<NAME>END_PI Turret"""
text: """<i>Kapott akció %ROTATEARC%</i>%LINEBREAK%<strong>Támadás</strong>"""
"Electronic Baffle":
display_name: """Electronic Baffle"""
text: """A Vége fázis alatt, elszenvedhetsz 1 %HIT% sérülést, hogy levegyél 1 piros jelzőt."""
"Elusive":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor védekezel, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 védekezőkockát. Miután teljesen végrehajtasz egy piros manővert, visszatölthetsz 1 %CHARGE% jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor egy másik baráti hajó védekezik vagy végrehajt egy támadást, elkölthetsz 1 %FORCE% jelzőt, hogy módosít annak 1 kockáját úgy, mintha az a hajó költött volna el 1 %FORCE% jelzőt."""
"Engine Upgrade":
display_name: """Engine Upgrade"""
text: """<i>Kapott akció %BOOST%</i>%LINEBREAK%<i>Követelmény <r>%BOOST%</r></i>%LINEBREAK%<i class = flavor_text>Ennek a fejlesztésnek változó a költsége. 3, 6 vagy 9 pont attól függően, hogy kis, közepes vagy nagy talpú hajóra tesszük fel.</i>"""
"Expert Handling":
display_name: """Expert Handling"""
text: """<i>Kapott akció %BARRELROLL%</i>%LINEBREAK%<i>Követelmény <r>%BARRELROLL%</r></i>%LINEBREAK%<i class = flavor_text>Ennek a fejlesztésnek változó a költsége. 2, 4 vagy 6 pont attól függően, hogy kis, közepes vagy nagy talpú hajóra tesszük fel.</i>"""
"Ezra Bridger":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy bónusz %SINGLETURRETARC% támadást egy olyan %SINGLETURRETARC% fegyverrel, amivel még nem támadtál ebben a körben. Ha így teszel és stresszes vagy, újradobhatsz 1 támadókockát."""
"Fearless":
display_name: """Fearless"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy %FRONTARC% elsődleges támadást, ha a támadási távolság 1 és benne vagy a védekező %FRONTARC% tűzívében, megváltoztathatsz 1 eredményedet %HIT% eredményre."""
"Feedback Array":
display_name: """Feedback Array"""
text: """Mielőtt sor kerül rád az Üzközet fázisban, kaphatsz 1 ion jelzőt és 1 'inaktív fegyverzet' jelzőt. Ha így teszel, minden hajó 0-ás távolságban elszenved 1 %HIT% sérülést."""
"Fifth Brother":
display_name: """Fifth Brother"""
text: """<i>csak Birodalom</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elkölthetsz 1 %FORCE% jelzőt, hogy megváltoztass 1 %FOCUS% eredményed %CRIT% eredményre."""
"Fire-Control System":
display_name: """Fire-Control System"""
text: """Amikor végrehajtasz egy támadást, ha van bemérőd a védekezőn, újradobhatod 1 támadókockádat. Ha így teszel, nem költheted el a bemérődet ebben a támadásban."""
"Freelance Slicer":
display_name: """Freelance Slicer"""
text: """Amikor védekezel, mielőtt a támadó kockákat eldobnák, elköltheted a támadón lévő bemérődet, hogy dobj 1 támadókockával. Ha így teszel, a támadó kap 1 zavarás jelzőt. Majd %HIT% vagy %CRIT% eredménynél te is kapsz 1 zavarás jelzőt."""
'GNK "Gonk" Droid':
display_name: """GNK “Gonk” Droid"""
text: """<strong>Felhelyezés:</strong> Elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<strong>Akció:</strong> tölts vissza 1 %CHARGE% jelzőt. <strong>Akció:</strong>: költs el 1 %CHARGE% jelzőt, hogy visszatölts egy pajzsot."""
"Grand Inquisitor":
display_name: """Grand Inquisitor"""
text: """<i>csak Birodalom</i>%LINEBREAK%Miután egy ellenséges hajó 0-2-es távolságban felfedi a tárcsáját, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts 1 fehér akciót az akciósávodról, pirosként kezelve azt."""
"Grand Moff Tarkin":
display_name: """Grand Moff Tarkin"""
text: """<i>Követelmény %LOCK% vagy <r>%LOCK%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%A Rendszer fázis alatt elkölthetsz 2 %CHARGE% jelzőt. Ha így teszel, minden baráti hajó kap egy bemérőt arra a hajóra, amit te is bemértél."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elkölthetsz 1 %CHARGE% jelzőt, hogy megváltoztass 1 %HIT% eredméynyt %CRIT% eredményre. Amikor védekezel, ha a %CHARGE% jelződ aktív, a támadó megváltoztathat 1 %HIT% eredméynyt %CRIT% eredményre."""
"Han Solo":
display_name: """Han Solo"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis alatt, 7-es kezdeményezésnél, végrehajthatsz egy %SINGLETURRETARC% támadást. Nem támadhatsz újra ezzel a %SINGLETURRETARC% fegyverrel ebben a körben."""
"Han Solo (Scum)":
display_name: """Han Solo"""
text: """<i>csak Söpredék</i>%LINEBREAK%Mielőtt sor kerül rád az Üzközet fázisban, végrehajthatsz egy piros %FOCUS% akciót."""
"Heavy Laser Cannon":
display_name: """Heavy Laser Cannon"""
text: """<strong>Támadás:</strong> a <strong>Támadókockák módosítása</strong> lépés után változtasd az összes %CRIT% eredményt %HIT% eredményre."""
"Heightened Perception":
display_name: """Heightened Perception"""
text: """Az Ütközet fázis elején, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, 7-es kezdeményezéssel kerülsz sorra ebben a fázisban a rendes kezdeményezésed helyett."""
"Hera Syndulla":
display_name: """Hera Syndulla"""
text: """<i>csak Lázadók</i>%LINEBREAK%Stresszesen is végrehajthatsz piros manővert. Miután teljesen végrehajtasz egy piros manővert, ha 3 vagy több stressz jelződ van, vegyél le egy stressz jelzőt és szenvedj el 1 %HIT% sérülést."""
"Homing Missiles":
display_name: """Homing Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> Költs el 1 %CHARGE% jelzőt. Miután kijelölted a védekezőt, a védekező dönthet úgy, hogy elszenved 1 %HIT% sérülést. Ha így tesz, ugorjátok át a <strong>Támadó és védekező kockák</strong> lépést és a támadást találtnak kezeljétek."""
"Hotshot Gunner":
display_name: """Hotshot Gunner"""
text: """Amikor végrehajtasz egy %SINGLETURRETARC% támadást, a <strong>Védekezőkockák módosítása</strong> lépés után a védekező dobja el 1 fókusz vagy kalkuláció jelzőjét."""
"Hull Upgrade":
display_name: """Hull Upgrade"""
text: """Adj 1 szerkezeti értéket a hajódhoz.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 2, 3, 5 vagy 7 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"IG-88D":
display_name: """IG-88D"""
text: """<i>Kapott akció %CALCULATE%</i>%LINEBREAK%<i>csak Söpredék</i>%LINEBREAK%Megkapod minden <strong>IG-2000</strong> fejlesztéssel felszerelt baráti hajó pilóraképességét. Miután végrehajtasz egy %CALCULATE% akciót, kapsz 1 kalkuláció jelzőt."""
"ISB Slicer":
display_name: """ISB Slicer"""
text: """<i>csak Birodalom</i>%LINEBREAK%A Vége fázis alatt az ellenséges hajók 1-2-es távban nem vehetik le a zavarás jelzőket."""
"Inertial Dampeners":
display_name: """Inertial Dampeners"""
text: """Mielőtt végrehajtanál egy manővert, elkölthetsz 1 pajzsot. Ha így teszel, hajts végre egy fehér [0 %STOP%] manővert a tárcsázott helyett, aztán kapsz 1 stressz jelzőt."""
"Informant":
display_name: """Informant"""
text: """<strong>Felhelyezés:</strong> a hajók felhelyezése után válassz 1 ellenséges hajót és rendeld hozzá a <strong>Listening Device</strong> kondíciót."""
"Instinctive Aim":
display_name: """Instinctive Aim"""
text: """Amikor végrehajtasz egy speciális támadást, elkölthetsz 1 %FORCE% jelzőt, hogy figyelmen kívül hagyhatsd a %FOCUS% vagy %LOCK% követelményt."""
"Intimidation":
display_name: """Intimidation"""
text: """Amikor egy ellenséges hajó 0-ás távolságban védekezik, 1-gyel kevesebb védekezőkockával dob."""
"Ion Cannon":
display_name: """Ion Cannon"""
text: """<strong>Támadás:</strong> ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Cannon Turret":
display_name: """Ion Cannon Turret"""
text: """<i>Kapott akció %ROTATEARC%</i>%LINEBREAK%<strong>Támadás:</strong> ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Missiles":
display_name: """Ion Missiles"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"Ion Torpedoes":
display_name: """Ion Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. ha a támadás talált, költs 1 %HIT% vagy %CRIT% eredményt, hogy a védekező elszenvedjen 1 %HIT% sérülést. Minden fennmaradó %HIT%/%CRIT% eredmény után sérülés helyett ion jelzőt kap a védekező."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak SPI:NAME:<NAME>END_PIpredék</i>%LINEBREAK%A Vége fázis alatt, kiválaszthatsz 1 baráti hajót 0-2-es távolságban, majd költs el 1 %CHARGE% jelzőt. Ha így teszel, a kiválasztott hajó visszatölthet 1 %CHARGE% jelzőt 1 felszerelt %ILLICIT% fejlesztésén."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<strong>Támadás:</strong> ha a támadás talált, minden %HIT%/%CRIT% eredmény után sérülés helyett zavarás jelzőt kap a védekező."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak kis vagy közepes hajó</i>%LINEBREAK%Amikor végrehajtasz egy támadást, ha van kitérés jelződ, megváltoztathatod a védekező 1 %EVADE% eredményét %FOCUS% eredményre."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Ha egy baráti hajó 0-3 távolságban fókusz jelzőt kapna, helyette kaphat 1 kitérés jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak PI:NAME:<NAME>END_PIázadók</i>%LINEBREAK%Miután egy baráti hajó 0-2-es távolságban teljesen végrehajt egy fehér manővert, elkölthetsz 1 %FORCE% jelzőt, hogy levegyél róla 1 stressz jelzőt."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%A Vége fázis elején, kiválaszthatsz 1 ellenséges hajót 0-2-es távolságban a tűzívedben. Ha így teszel, aza a hajó nem veheti le a vonósugár jelzőit."""
"L3-37":
display_name: """L3-37"""
text: """<i>csPI:NAME:<NAME>END_PI SöpredPI:NAME:<NAME>END_PI</i>%LINEBREAK%<strong>Felhelyezés:</strong> felfordítva szereld fel ezt a kártyát. Amikor védekezel, lefordíthatod ezt a kártyát. Ha így teszel, a támadónak újra kell dobnia az összes támadókockát.%LINEBREAK%<i>L3-37 programja:</i> Ha nincs pajzsod, csökkentsd a nehézségét a (%BANKLEFT% és %BANKRIGHT%) manővereknek."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csPI:NAME:<NAME>END_PI</i>%LINEBREAK%<strong>Akció:</strong> dobj 2 védekezőkockával. Minden egyes %FOCUS% eredmény után kapsz 1 fókusz jelzőt. Minden egyes %EVADE% eredmény után kapsz 1 kitérés jelzőt. Ha mindkettő eredmény üres, az ellenfeled választ, hogy fókusz vagy kitérés. Kapsz 1, a választásnak megfelelő jelzőt."""
"PI:NAME:<NAME>END_PI (Scum)":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak PI:NAME:<NAME>END_PIöpredék</i>%LINEBREAK%Kockadobás után elkölthetsz 1 zöld jelzőt, hogy újradobj 2 kockádat."""
"Lando's Millennium Falcon":
display_name: """LPI:NAME:<NAME>END_PI’s Millennium Falcon"""
text: """<i>csak Söpredék</i>%LINEBREAK%1 Escape Craft be lehet dokkolva. Amikor egy Escape Craft be van dokkolva, elköltheted a pajzsait, mintha a te hajódon lenne. Amikor végrehajtasz egy elsődleges támadást stresszelt hajó ellen, dobj 1-gyel több támadókockával."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor védekezel, ha a támadó stresszelt, levehetsz 1 stressz jelzőt a támadóról, hogy megváltoztass 1 üres/%FOCUS% eredményed %EVADE% eredményre."""
"LePI:NAME:<NAME>END_PIana":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Aktivációs fázis elején, elkölthetsz 3 %CHARGE% jelzőt. Ezen fázis alatt minden baráti hajó csökkentse a piros manőverei nehézségét."""
"LPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor védekezel vagy támadást hajtasz végre, ha nincs másik baráti hajó 0-2-es távolságban, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 kockádat."""
"LuPI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az Ütközet fázis elején, elkölthetsz 1 %FORCE% jelzőt, hogy forgasd a %SINGLETURRETARC% mutatódat."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután védekezel, ha a támadás talált, feltehetsz egy bemérőt a támadóra."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """Amikor végrehajtasz egy támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, megváltoztathatsz 1 %HIT% eredményt %CRIT% eredményre."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>Söpredék vagy PI:NAME:<NAME>END_PI a csapatban</i>%LINEBREAK%Miután sérülést szenvedsz, kaphatsz 1 stressz jelzőt, hogy visszatölts 1 %FORCE% jelzőt. Felszerelhetsz <strong>Dark Side</strong> fejlesztéseket."""
"MinPI:NAME:<NAME>END_PIua":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Birodalom</i>%LINEBREAK%Az Ütközet fázis elején, ha sérült vagy, végrehajthatsz egy piros %REINFORCE% akciót."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>Követelmény: %COORDINATE% vagy <r>%COORDINATE%</r></i>%LINEBREAK%<i>csak Birodalom</i>%LINEBREAK%A Rendszer fázis alatt, elkölthetsz 2 %CHARGE% jelzőt. Ha így teszel, válassz a [1 %BANKLEFT%], [1 %STRAIGHT%] vagy [1 %BANKRIGHT%] sablonokból. Minden baráti hajó végrehajthat egy piros %BOOST% akciót a kiválasztott sablonnal."""
"Munitions Failsafe":
display_name: """Munitions Failsafe"""
text: """Amikor végrehajtasz egy %TORPEDO% vagy %MISSILE% támadást, a támadókockák eldobása után, elvetheted az összes kocka eredményed, hogy visszatölts 1 %CHARGE% jelzőt, amit a támadáshoz elköltöttél."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Lázadók</i>%LINEBREAK%Csökkentsd az íves manőverek [%BANKLEFT% és %BANKRIGHT%] nehézségét."""
"Novice Technician":
display_name: """Novice Technician"""
text: """A kör végén dobhatsz 1 támadó kockával, hogy megjavíts egy felfordított sérülés kártyát. %HIT% eredménynél, fordíts fel egy sérülés kártyát."""
"Os-1 Arsenal Loadout":
display_name: """Os-1 Arsenal Loadout"""
text: """<i>Kapsz egy %TORPEDO% és egy %MISSILE% fejlesztés helyet.</i>%LINEBREAK%Amikor pontosan 1 'inaktív fegyverzet' jelződ van, akkor is végre tudsz hajtani %TORPEDO% és %MISSILE% támadást bemért célpontok ellen. Ha így teszel, nem használhatod el a bemérődet a támadás alatt."""
"Outmaneuver":
display_name: """Outmaneuver"""
text: """Amikor végrehajtasz egy %FRONTARC% támadást, ha nem vagy a védekező tűzívében, a védekező 1-gyel kevesebb védekezőkockával dob."""
"Perceptive Copilot":
display_name: """Perceptive Copilot"""
text: """Miután végrehajtasz egy %FOCUS% akciót, kapsz 1 fókusz jelzőt."""
"Pivot Wing":
display_name: """Pivot Wing"""
text: """<strong>Csukva: </strong>Amikor védekezel, 1-gyel kevesebb védekezőkockával dobsz. Miután végrehajtasz egy [0 %STOP%] manővert, elforgathatod a hajód 90 vagy 180 fokkal. Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK%<strong>Nyitva:</Strong> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Predator":
display_name: """Predator"""
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, újradobhatsz 1 támadókockát."""
"Proton Bombs":
display_name: """Proton Bombs"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy kidobj egy Proton bombát az [1 %STRAIGHT%] sablonnal."""
"Proton Rockets":
display_name: """Proton Rockets"""
text: """<strong>Támadás (%FOCUS%):</strong> költs el 1 %CHARGE% jelzőt."""
"Proton Torpedoes":
display_name: """Proton Torpedoes"""
text: """<strong>Támadás (%LOCK%):</strong> költs el 1 %CHARGE% jelzőt. Változtass 1 %HIT% eredményt %CRIT% eredményre."""
"Proximity Mines":
display_name: """Proximity Mines"""
text: """<strong>Akna</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Proximity aknát az [1 %STRAIGHT%] sablonnal. Ennak a kártyának a %CHARGE% jelzője <strong>nem</strong> újratölthető."""
"Qi'ra":
display_name: """Qi’ra"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor mozogsz vagy támadást hajtasz végre, figyelmen kívül hagyhatod az összes akadályt, amit bemértél."""
"R2 Astromech":
display_name: """R2 Astromech"""
text: """Miután felfeded a tárcsád, elkölthetsz 1 %CHARGE% jelzőt és kapsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts egy pajzsot."""
"R2-D2 (Crew)":
display_name: """R2-D2"""
text: """<i>csak Lázadók</i>%LINEBREAK%A Vége fázis alatt, ha sérült vagy és nincs pajzsod, dobhatsz 1 támadókockával, hogy visszatölts 1 pajzsot. %HIT% eredménynél fordíts fel 1 sérüléskártyát."""
"R2-D2":
display_name: """R2-D2"""
text: """<i>csak Lázadók</i>%LINEBREAK%Miután felfeded a tárcsád, elkölthetsz 1 %CHARGE% jelzőt és kapsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts egy pajzsot."""
"R3 Astromech":
display_name: """R3 Astromech"""
text: """Fenntarthatsz 2 bemérőt. Mindegyik bemérő más célponton kell legyen. Miután végrehajtasz egy %LOCK% akciót, feltehetsz egy bemérőt."""
"R4 Astromech":
display_name: """R4 Astromech"""
text: """<i>csak kis hajó</i>%LINEBREAK%Csökkentsd a nehézségét az 1-2 sebességű alapmanővereidnek (%TURNLEFT%, %BANKLEFT%, %STRAIGHT%, %BANKRIGHT%, %TURNRIGHT%)."""
"R5 Astromech":
display_name: """R5 Astromech"""
text: """<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy megjavíts egy lefordított sérülés kártyát.%LINEBREAK%<strong>Akció:</strong> javíts meg 1 felfordított <strong>Ship</strong> sérülés kártyát."""
"R5-D8":
display_name: """R5-D8"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt, hogy megjavíts egy lefordított sérülés kártyát.%LINEBREAK%<strong>Akció:</strong> javíts meg 1 felfordított <strong>Ship</strong> sérülés kártyát."""
"R5-P8":
display_name: """R5-P8"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást a %FRONTARC% tűzívedben lévő védekező ellen, elkölthetsz 1 %CHARGE% jelzőt, hogy újradobj 1 támadókockát. Ha az újradobott eredmény %CRIT%, szenvedj el 1 %CRIT% sérülést."""
"R5-TK":
display_name: """R5-TK"""
text: """<i>csak Söpredék</i>%LINEBREAK%Végrehajthatsz támadást baráti hajó ellen."""
"RPI:NAME:<NAME>END_PI CPI:NAME:<NAME>END_PI Chute":
display_name: """RPI:NAME:<NAME>END_PI"""
text: """<i>csak közepes vagy nagy hajó</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 %CHARGE% jelzőt. Dobj ki 1 rakomány jelzőt az [1 %STRAIGHT%] sablonnal."""
"RPI:NAME:<NAME>END_PI":
display_name: """RPI:NAME:<NAME>END_PI"""
text: """<i>csPI:NAME:<NAME>END_PI</i>%LINEBREAK%Amikor végrehajtasz egy támadást, kiválaszthatsz másik baráti hajót 0-1-es távolságra a védekezőtől. Ha így teszel, a kiválasztott hajó elszenved 1 %HIT% sérülést és te megváltoztathatsz 1 kocka eredményed %HIT% eredményre."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak LázPI:NAME:<NAME>END_PIók</i>%LINEBREAK%<strong>Felhelyezés:</strong> tegyél fel 1 ion, 1 zavarás, 1 stressz és 1 vonósugár jelzőt erre a kártyára. Miután egy hajó sérülést szenved egy baráti bombától, levehetsz 1 ion, 1 zavarás, 1 stressz vagy 1 vonósugár jelzőt erről a kártyáról. Ha így teszel, az a hajó megkapja ezt a jelzőt."""
"Saturation Salvo":
display_name: """Saturation Salvo"""
text: """<i>Követelmény %RELOAD% vagy <r>%RELOAD%</r></i>%LINEBREAK%Amikor végrehajtasz egy %TORPEDO% vagy %MISSILE% támadást, elkölthetsz 1 %CHARGE% jelzőt arról a kártyától. Ha így teszel, válassz 2 védekezőkockát. A védekezőnek újra kell dobnia azokat a kockákat."""
"Saw Gerrera":
display_name: """Saw Gerrera"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor végrehajtasz egy támadást, elszenvedhetsz 1 %HIT% sérülést, hogy megváltoztasd az összes %FOCUS% eredményed %CRIT% eredményre."""
"Seasoned Navigator":
display_name: """Seasoned Navigator"""
text: """Miután felfedted a tárcsádat, átállíthatod egy másik nem piros manőverre ugyanazon sebességen. Amikor végrehajtod azt a manővert növeld meg a nehézségét."""
"Seismic Charges":
display_name: """Seismic Charges"""
text: """<strong>Bomba</strong>%LINEBREAK%A Rendszer fázisban elkölthetsz 1 %CHARGE% jelzőt, hogy ledobj egy Seismic Charge bombát az [1 %STRAIGHT%] sablonnal."""
"Selfless":
display_name: """Selfless"""
text: """<i>csak Lázadók</i>%LINEBREAK%Amikor másik baráti hajó 0-1-es távolságban védekezik, az <strong>Eredmények semlegesítése</strong> lépés előtt, ha benne vagy a támadási tűzívben, elszenvedhetsz 1 %CRIT% sérülést, hogy semlegesíts 1 %CRIT% eredményt."""
"Sense":
display_name: """Sense"""
text: """A Rendszer fázis alatt kiválaszthatsz 1 hajót 0-1-es távolságban és megnézheted a tárcsáját. Ha elköltesz 1 %FORCE% jelzőt választhatsz 0-3-as távolságból hajót."""
"Servomotor S-Foils":
display_name: """Servomotor S-foils"""
text: """<strong>Csukva: </strong><i>Kapott akciók: %BOOST% , %FOCUS% <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> <r>%BOOST%</r></i>%LINEBREAK% Amikor végrehajtasz egy elsődleges támadást, 1-gyel kevesebb támadókockával dobj.%LINEBREAK%Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK%<strong>Nyitva:</strong> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Seventh Sister":
display_name: """Seventh Sister"""
text: """<i>csak Birodalom</i>%LINEBREAK%Ha egy ellenséges hajó 0-1-es távolságra egy stressz jelzőt kapna, elkölthetsz 1 %FORCE% jelzőt, hogy 1 zavarás vagy vonósugár jelzőt kapjon helyette."""
"Shield Upgrade":
display_name: """Shield Upgrade"""
text: """Adj 1 pajzs értéket a hajódhoz.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 3, 4, 6 vagy 8 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"Skilled Bombardier":
display_name: """Skilled Bombardier"""
text: """Ha ledobsz vagy kilősz egy eszközt, megegyező irányban használhatsz 1-gyel nagyob vagy kisebb sablont."""
"Squad Leader":
display_name: """Squad Leader"""
text: """<i>Kapott akció <r>%COORDINATE%</r></i>%LINEBREAK%WAmikor koordinálsz, a kiválasztott hajó csak olyan akciót hajthat végre, ami a te akciósávodon is rajta van."""
"Static Discharge Vanes":
display_name: """Static Discharge Vanes"""
text: """Mielőtt kapnál 1 ion vagy zavarás jelzőt, ha nem vagy stresszes, választhatsz egy másik hajót 0-1-es távolságban és kapsz 1 stressz jelzőt. Ha így teszel, a kiválasztott hajó kapja meg az ion vagy zavarás jelzőt helyetted."""
"Stealth Device":
display_name: """Stealth Device"""
text: """Amikor védekezel, ha a %CHARGE% jelződ aktív, dobj 1-gyel több védekezőkockával. Miután elszenvedsz egy sérülés, elvesztesz 1 %CHARGE% jelzőt.%LINEBREAK%<i>Ennek a fejlesztésnek változó a költsége. 3, 4, 6 vagy 8 pont attól függően, hogy a hajó 0, 1, 2 vagy 3 védekezésű.</i>"""
"Supernatural Reflexes":
display_name: """Supernatural Reflexes"""
text: """<i>csak kis hajó</i>%LINEBREAK%Mielőtt aktiválódsz, elkölthetsz 1 %FORCE% jelzőt, hogy végrehajts egy %BARRELROLL% vagy %BOOST% akciót. Ha olyan akciót hajtottál végre, ami nincs az akciósávodon, elszenvedsz 1 %HIT% sérülést."""
"Swarm Tactics":
display_name: """Swarm Tactics"""
text: """Az ütközet fázis elején, kiválaszthatsz 1 baráti hajót 1-es távolságban. Ha így teszel, az a hajó a kör végéig kezelje úgy a kezdeményezés értékét, mintha egyenlő lenne a tiéddel."""
"Tactical Officer":
display_name: """Tactical Officer"""
text: """<i>Kapott akció: %COORDINATE%</i>%LINEBREAK%<i>Követelmény: <r>%COORDINATE%</r></i>"""
"Tactical Scrambler":
display_name: """Tactical Scrambler"""
text: """<i>csak közepes vagy nagy hajó</i>%LINEBREAK%Amikor akadályozod egy ellenséges hajó támadását, a védekező 1-gyel több védekezőkockával dob."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%<strong>Felhelyezés:</strong> a hajók felhelyezése után, kiválaszthatsz 1 akadályt a pályáról. Ha így teszel, helyezd át bárhová 2-es távolságra a szélektől vagy hajóktól és 1-es távolságra más akadályoktól."""
"Tractor Beam":
display_name: """Tractor Beam"""
text: """<strong>Támadás:</strong> ha a támadás talált, minden %HIT%/%CRIT% eredmény után sérülés helyett vonósugár jelzőt kap a védekező."""
"Trajectory Simulator":
display_name: """Trajectory Simulator"""
text: """A Rendszer fázis alatt, ha ledobsz vagy kilősz egy bombát, kilőheted a [5 %STRAIGHT%] sablonnal."""
"Trick Shot":
display_name: """Trick Shot"""
text: """Amikor végrehajtasz egy támadást ami akadályozott egy akadály által, dobj 1-gyel több támadókockával."""
"Unkar Plutt":
display_name: """Unkar Plutt"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután részlegesen végrehajtasz egy manővert, elszenvedhetsz 1 %HIT% sérülést, hogy végrehajts 1 fehér akciót."""
"Veteran Tail Gunner":
display_name: """Veteran Tail Gunner"""
text: """<i>Követelmény: %REARARC%</i> %LINEBREAK%Miután végrehajtasz egy elsődleges %FRONTARC% támadást, végrehajthatsz egy bónusz elsődleges %REARARC% támadást."""
"Veteran Turret Gunner":
display_name: """Veteran Turret Gunner"""
text: """<i>Követelmény: %ROTATEARC% vagy <r>%ROTATEARC%</r></i>%LINEBREAK%Amikor végrehajtasz egy elsődleges támadást, végrehajthatsz egy bónusz %SINGLETURRETARC% támadást egy olyan %SINGLETURRETARC% tűzívben, amiből még nem támadtál ebben a körben."""
"Xg-1 Assault Configuration":
display_name: """Xg-1 Assault Configuration"""
text: """Amikor pontosan 1 'inaktív fegyverzet' jelződ van, akkor is végrehajthatsz %CANNON% támadást. Amikor %CANNON% támadást hajtasz végre 'inaktív fegyverzet' jelzővel, maximum 3 támadókockával dobhatsz.%LINEBREAK%Kapsz egy %CANNON% fejlesztés helyet."""
"PI:NAME:<NAME>END_PI":
display_name: """PI:NAME:<NAME>END_PI"""
text: """<i>csak Söpredék</i>%LINEBREAK%Amikor végrehajtasz egy támadást, ha nem vagy stresszes, válaszhatsz 1 védekezőkockát és kapsz 1 stressz jelzőt. Ha így teszel, a védekezőnek újra kell dobnia azt a kockát."""
'"PI:NAME:<NAME>END_PI" (Crew)':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """<i>csak Lázadók</i>%LINEBREAK%Az <strong>Akció végrehajtása</strong> lépés közben még stresszesen is végrehajthatsz 1 akciót. Miután stresszesen végrehajtasz egy akciót szenvedj el 1 %HIT% sérülést vagy fordítsd fel 1 sérülés kártyád."""
'"PI:NAME:<NAME>END_PI" (Astromech)':
display_name: """“PI:NAME:<NAME>END_PI”"""
text: """<i>csak Lázadók</i>%LINEBREAK%<strong>Akció:</strong> költs el 1 nem-újratölthető %CHARGE% jelzőt egy másik felszerelt fejlesztésről, hogy visszatölts 1 pajzsot%LINEBREAK%<strong>Akció:</strong> költs el 2 pajzsot, hogy visszatölts 1 nem-újratölthető %CHARGE% jelzőt egy felszerelt fejlesztésen."""
'"Genius"':
display_name: """“Genius”"""
text: """<i>csak Söpredék</i>%LINEBREAK%Miután teljesen végrehajtasz egy manővert, ha még nem dobtál vagy lőttél ki eszközt ebben a körben, kidobhatsz 1 bombát."""
'"Zeb" Orrelios':
display_name: """“Zeb” Orrelios"""
text: """<i>csak Lázadók</i>%LINEBREAK%Végrehajthatsz elsődleges támadást 0-ás távolságban. Az ellenséges hajók 0-ás távolságban végrehajthatnak elsődleges támadást ellened."""
"Hardpoint: Cannon":
text: """Kapsz egy %CANNON% fejlesztés helyet."""
"Hardpoint: Missile":
text: """Kapsz egy %MISSILE% fejlesztés helyet."""
"Hardpoint: Torpedo":
text: """Kapsz egy %TORPEDO% fejlesztés helyet."""
"Black One":
text: """<i>Kapott akció: %SLAM%</i> %LINEBREAK% Miután végrehajtasz egy %SLAM% akciót, elvesztesz 1 %CHARGE% jelzőt. Ezután kaphatsz 1 ion jelzőt, hogy levedd az inaktív fegyverzet jelzőt. Ha a %CHARGE% nem aktív, nem hajthatsz végre %SLAM% akciót."""
"Heroic":
text: """<i>csak Ellenállás</i><br>Amikor védekezel vagy támadást hajtasz végre, ha 2 vagy több csak üres eredményed van, újradobhatsz akárhány kockát."""
"PI:NAME:<NAME>END_PI":
text: """Amikor védekezel vagy támadást hajtasz végre, elkölthetsz egy dobás eredményed, hogy bemérőt rakj az ellenséges hajóra."""
"PI:NAME:<NAME>END_PI":
text: """Amikor védekezel vagy elsődleges támadást hajtasz végre,ha az ellenséges hajó a %FRONTARC% tűzívedben van, hozzáadhatsz 1 üres eredményt a dobásodhoz (ez a kocka újradobható vagy módosítható)."""
"Integrated S-Foils":
text: """<strong>Csukva: </strong><i>Kapott akció %BARRELROLL%, %FOCUS% <i class="xwing-miniatures-font xwing-miniatures-font-linked"></i> <r>%BARRELROLL%</r></i>%LINEBREAK% Amikor végrehajtasz egy elsődleges támadást, ha a védekező nincs a %BULLSEYEARC% tűzívedben, 1-gyel kevesebb támadókockával dobj. Mielőtt aktiválódsz, megfordíthatod ezt a kártyát.%LINEBREAK% <b>Nyitva:</b> Mielőtt aktiválódsz, megfordíthatod ezt a kártyát."""
"Targeting Synchronizer":
text: """<i>Követelmény: %LOCK%</i> %LINEBREAK% Amikor egy baráti hajó 1-2-es távolságban végrehajt egy támadást olyan célpont ellen, amit már bemértél, az a hajó figyelmen kívül hagyhatja a %LOCK% támadási követelményt."""
"Primed Thrusters":
text: """<i>csak kis hajó</i> %LINEBREAK%Amikor 2 vagy kevesebb stressz jelződ van, végrehajthatsz %BARRELROLL% és %BOOST% akciót még ha stresszes is vagy."""
"PI:NAME:<NAME>END_PI":
text: """<strong>Akció: </strong> Válassz 1 ellenséges hajót 1-3-as távolságban. Ha így teszel, költs el 1 %FORCE% jelzőt, hogy hozzárendeled az <strong>I'll Show You the Dark Side</strong> kondíciós kártyát a kiválasztott hajóhoz."""
"General Hux":
text: """Amikor végrehajtasz egy fehér %COORDINATE% akciót, kezelheted pirosként. Ha így teszel, koordinálhatsz további 2 azonos típusú hajót, mindegyikét azonos akcióval és pirosként kezelve."""
"Fanatical":
text: """Amikor végrehajtasz egy elsődleges támadást, ha nincs pajzsod, megváltoztathatsz 1 %FOCUS% eredményt %HIT% eredményre."""
"Special Forces Gunner":
text: """Amikor végrehajtasz egy elsődleges %FRONTARC% támadást, ha a %SINGLETURRETARC% tűzíved a %FRONTARC% tűzívedben van, 1-gyel több kockával dobhatsz. Miután végrehajtasz egy elsődleges %FRONTARC% támadást, ha a %SINGLETURRETARC% tűzíved a %REARARC% tűzívedben van, végrehajthatsz egy bónusz elsődleges %SINGLETURRETARC% támadást."""
"Captain Phasma":
text: """Az Ütközet fázis végén, minden 0-1 távolságban lévő ellenséges hajó ami nem stresszes, kap 1 stressz jelzőt."""
"Supreme Leader Snoke":
text: """A Rendszer fázis alatt kiválaszthatsz bármennyi hajót 1-es távolságon túl. Ha így teszel költs el annyi %FORCE% jelzőt, amennyi hajót kiválasztottál, hogy felfordítsd a tárcsájukat."""
"Hyperspace Tracking Data":
text: """<strong>Felhelyezés:</strong> a hajó felhelyezés előtt válassz egy számot 0 és 6 között. Kezeld a Initiative-od a kiválasztott számnak megfelelően. A felhelyezés után rendelj hozzá 1 %FOCUS% vagy %EVADE% jelzőt minden baráti hajóra 0-2-es távolságban."""
"Advanced Optics":
text: """Amikor támadást hajtasz végre, elkölthetsz 1 %FOCUS% jelzőt, hogy 1 üres eredményed %HIT% eredményre változtass."""
"Rey":
text: """Amikor védekezel vagy támadást hajtasz végre, ha az ellenséges hajó benne van a %FRONTARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt, hogy 1 üres eredményed %EVADE% vagy %HIT% eredményre változtass."""
"Chewbacca (Resistance)":
text: """<strong>Felhelyezés:</strong>: elvesztesz el 1 %CHARGE% jelzőt. %LINEBREAK% Miután egy baráti hajó 0-3-as távolságban felhúz 1 sérülés kártyát, állítsd helyre 1 %CHARGE% jelzőt. Amikor támadást hajtasz végre elkölthetsz 2 %CHARGE% jelzőt, hogy 1 %FOCUS% eredményed %CRIT% eredményre változtass."""
"PI:NAME:<NAME>END_PI":
text: """Miután véggrehajtasz egy elsődleges támadást, ledobhatsz egy bombát vagy forgathatod a %SINGLETURRETARC% tűzívedet. Miután megsemmisültél ledobhatsz 1 bombát."""
"R2-HA":
text: """Amikor védekezel, elköltheted a támadón lévő bemérődet, hogy újradobd bármennyi védőkockádat."""
"C-3PO (Resistance)":
text: """ <i>Kapott akció: %CALCULATE% <r>%COORDINATE%</r></i> %LINEBREAK% Amikor koordinálsz, választhatsz baráti hajót 2-es távolságon túl, ha annak van %CALCULATE% akciója. Miután végrehajtod a %CALCULATE% vagy %COORDINATE% akciót, kapsz 1 %CALCULATE% jelzőt."""
"Han Solo (Resistance)":
text: """ <i>Kapott akció: <r>%EVADE%</r></i> %LINEBREAK%Miután végrehajtasz egy %EVADE% akciót, annyival több %EVADE% jelzőt kapsz, ahány ellenséges hajó van 0-1-es távolságban."""
"Rey's Millennium Falcon":
text: """Ha 2 vagy kevesebb stressz jelződ van, végrehajthatsz piros Segnor Csavar manővert [%SLOOPLEFT% vagy %SLOOPRIGHT%] és végrehajthatsz %BOOST% és %ROTATEARC% akciókat, még ha stresszes is vagy."""
"PI:NAME:<NAME>END_PI":
text: """Az Aktivációs vagy Ütközet fázis közben, miután egy ellenséges hajó a %FRONTARC% tűzívedben 0-1-es távolságban kap egy piros vagy narancs jelzőt, ha nem vagy stresszes, kaphatsz egy stressz jelzőt. Ha így teszel, az a hajó kap még egy jelzőt abból, amit kapott."""
"BB-8":
text: """Mielőtt végrehajtasz egy kék manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BARRELROLL% vagy %BOOST% akciót."""
"BB Astromech":
text: """Mielőtt végrehajtasz egy kék manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy %BARRELROLL% akciót."""
"M9-G8":
text: """Amikor egy hajó amit bemértél végrehajt egy támadást, kiválaszthatsz egy támadókockát. Ha így teszel, a támadó újradobja azt a kockát."""
"Ferrosphere Paint":
text: """Miután egy ellenséges hajó bemért téged, ha nem vagy annak a hajónak a %BULLSEYEARC% tűzívében, az kap egy stressz jelzőt."""
"Brilliant Evasion":
text: """Amikor védekezel, ha nem vagy a támadó %BULLSEYEARC% tűzívében, elkölthetsz 1 %FORCE% jelzőt, hogy 2 %FOCUS% eredményed %EVADE% eredményre változtass."""
"Calibrated Laser Targeting":
text: """Amikor végrehajtasz egy elsődleges támadást, ha a védekező benne van a %BULLSEYEARC% tűzívedben, adj a dobásodhoz 1 %FOCUS% eredményt."""
"Delta-7B":
text: """ <i>Kapott : 1 támadási érték, 2 pajzs %LINEBREAK% Elveszett: 1 védekezés</i> """
"Biohexacrypt Codes":
text: """Amikor koordinálsz vagy zavarsz, ha van bemérőd egy hajón, elköltheted azt a bemérőt, hogy a távolság követelményeket figyelmen kívül hagyd a hajó kiválasztákor."""
"Predictive Shot":
text: """Miután támadásra jelölsz egy célpontot, ha a védekező benne van a %BULLSEYEARC% tűzívedben, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a védekező a <strong>Védekezőkockák dobása</strong> lépésben nem dobhat több kockával, mint a %HIT%/%CRIT% eredményeid száma."""
"Hate":
text: """Miután elszenvedsz 1 vagy több sérülést, feltölthetsz ugyanannyi %FORCE% jelzőt."""
"R5-X3":
text: """Mielőtt aktiválódsz vagy rád kerül a sor az Ütközet fázisban, elkölthetsz 1 %CHARGE% jelzőt, hogy figyelmen kívül hagyd az akadályokat annak a fázisnak a végéig."""
"Pattern Analyzer":
text: """Amikor teljesen végrehajtasz egy piros manővert, a <strong>Nehézség ellenőrzése</strong> lépés előtt végrehjathatsz 1 akciót."""
"Impervium Plating":
text: """Mielőtt egy felfordított <b>Ship</b> sérüléskártyát kapnál, elkölthetsz 1 %CHARGE% jelzőt, hogy eldobd."""
"Grappling Struts":
text: """<strong>Csukva: </strong> Felhelyezés: ezzel az oldalával helyezd fel. %LINEBREAK% Amikor végrehajtasz egy manővert, ha átfedésbe kerülsz egy aszteroidával vagy űrszeméttel és 1 vagy kevesebb másik baráti hajó van 0-ás távolságra attól az akadálytól, megfordíthatod ezt a kártyát.
%LINEBREAK% <b>Nyitva:</b> Hagyd figyelment kívül a 0-ás távolságnban lévő akadályokat amíg átmozogsz rajtuk. Miután felfeded a tárcsádat, ha más manővert fedtél fel mint [2 %STRAIGHT%] és 0-ás távolságra vagy egy aszteroidától vagy űrszeméttől, ugord át a 'Manőver végrehajtása' lépést és vegyél le 1 stresst jelzőt; ha jobb vagy bal manővert fedtél fel, forgasd a hajódat 90 fokkal abba az irányba. Miután végrehajtasz egy manővert fordítsd át ezt a kártyát."""
"Energy-Shell Charges":
text: """ <strong>Támadás (%CALCULATE%):</strong> Költs el 1 %CHARGE% jelzőt. Amikor végrehajtasz egy támadást, elkölthetsz 1 %CALCULATE% jelzőt, hogy megváltoztass 1 %FOCUS% eredményt %CRIT% eredményre.%LINEBREAK% <strong>Akció:</strong> Töltsd újra ezt a kártyát."""
"Dedicated":
text: """Amikor egy másik baráti hajó a %LEFTARC% vagy a %RIGHTARC% tűzívedben 0-2-es távolságban védekezik, ha az limitált vagy Dedicated fejlesztéssel felszerelt és nem vagy túlterhelve, kaphatsz 1 túlterhelés jelzőt. Ha így teszel a védekező újradobhatja 1 üres eredményét."""
"Synchronized Console":
text: """Miután végrehajtasz egy támadást, választhatsz egy baráti hajót 1-es távolságban vagy egy baráti hajót 'Synchronized Console' fejlesztéssel 1-3 távolságban és költsd el a védekezőn lévő bemérődet. Ha így teszel, a kiválasztott baráti hajó kaphat egy bemérőt a védekezőre."""
"Battle Meditation":
text: """Nem koordinálhatsz limitált hajót.%LINEBREAK%Amikor végrehajtasz egy lila %COORDINATE% akciót, koordinálhatsz 1 további ugyanolyan típusú nem limitált baráti hajót. Mindkét hajónak ugyanazt az akciót kell végrehajtania."""
"R4-P Astromech":
text: """Mielőtt végrehajtasz egy alapmanővert, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel, a manőver végrehajtása közben csökkentsd annak nehézségét."""
"R4-P17":
text: """Miután teljesen végrehajtasz egy piros manővert, elkölthetsz 1 %CHARGE% jelzőt, hogy végrehajts egy akciót, még ha stresses is vagy."""
"Spare Parts Canisters":
text: """Akció: költs el 1 %CHARGE% jelzőt, hogy visszatölts 1 %CHARGE% jelzőt egy felszerelt %ASTROMECH% fejlesztéseden.%LINEBREAK%
Akció: költs el 1 %CHARGE% jelzőt, hogy kidobj 1 tartalék alkatrész jelzőt, aztán vegyél le minden rajtad lévő bemérőt."""
"PI:NAME:<NAME>END_PI":
text: """Felhelyezés: a hajók felhelyezése After the Place Forces step, you may cloak. %LINEBREAK% After you decloak, you may choose an enemy ship in your %BULLSEYEARC%. If you do, it gains 1 jam token."""
"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI":
text: """<strong>Felhelyezés:</strong> Ezzel az oldalával szereld fel.%LINEBREAK% Miután védekeztél, ha a támadó 0-2-es távolságban van, elkölthetsz 1 %FORCE% jelzőt. Ha így teszel, a támadó kap egy stressz jelzőt.%LINEBREAK% A vége fázisban megfordíthatod ezt a kártyát.%LINEBREAK% <strong>Darth Sidious:</strong> Miután végrehajtasz egy lila %COORDINATE% akciót, a koordinált hajó kap 1 stressz jelzőt, majd kap 1 %FOCUS% jelzőt vagy visszatölt 1 %FORCE% jelzőt."""
"Count Dooku":
text: """Mielőtt egy hajó 0-2-es távolságban támadó vagy védekező kockákat gurít, ha minden %FORCE% jelződ aktív, elkölthetsz 1 %FORCE% jelzőt, hogy megnevezz egy eredményt. Ha a dobás nem tartalmazza megnevezett eredményt, a hajónak meg kell változtatni 1 kockáját arra az eredményre."""
"General Grievous":
text: """Amikor védekezel, az 'Eredmények semlegesítése' lépés után, ha 2 vagy több %HIT%/%CRIT% eredmény van, elkölthetsz 1 %CHARGE% jelzőt, hogy semlegesíts 1 %HIT% vagy %CRIT% eredményt.%LINEBREAK%Miután egy baráti hajó megsemmisül, tölts vissza 1 %CHARGE% jelzőt."""
"K2-B4":
text: """Amikor egy baráti hajó 0-3-as távolságban védekezik, elkölthet 1 %CALCULATE% jelzőt. Ha így tesz, adjon 1 %EVADE% eredményt a dobásához, hacsak a támadó nem tönt úgy, hogy kap 1 túlterhelés jelzőt."""
"DRK-1 Probe Droids":
text: """A Vége fázis alatt elkölthetsz 1 %CHARGE% jelzőt, hogy kidobj vagy kilőj 1 DRK-1 kutaszdroidot egy 3-as sebességű sablon segítségével.%LINEBREAK%E a kártya %CHARGE% jelzője nem visszatölthető."""
"Kraken":
text: """A Vége fázis alatt kiválaszthatsz akár 3 baráti hajót 0-3-as távolságban. Ha így teszel, ezen hajók nem dobják el 1 %CALCULATE% jelzőjüket."""
"TV-94":
text: """Amikor egy baráti hajó 0-3-as távolságban végrehajt egy elsődleges támadást egy a %BULLSEYEARC% tűzívében lévő védekező ellen, ha 2 vagy kevesebb a támadó kockák száma, elkölthet 1 %CALCULATE% jelzőt, hogy hozzáadjon a dobásához 1 %HIT% eredményt."""
"Discord Missiles":
text: """Az Ütközet fázis elején elkölthetsz 1 %CALCULATE% jelzőt és 1 %CHARGE% jelzőt, hogy kilőj 1 'buzz droid swarm' jelzőt a [3 %BANKLEFT%], [3 %STRAIGHT%] vagy [3 %BANKRIGHT%] használatával. Ennek a kártyának a %CHARGE% jelzője nem tölthető újra."""
"Clone Commander Cody":
text: """Miután végrehajtasz egy támadást ami nem talált, ha 1 vagy több %HIT%/%CRIT% eredményt lett semlegesítve, a védekező kap 1 túlterhelés jelzőt."""
"Seventh Fleet Gunner":
text: """Amikor egy másik baráti hajó végrehajt egy elsődleges támadást, ha a védekező a tűzívedben van, elkölthetsz 1 %CHARGE% jelzőt. Ha így teszel a támadó 1-gyel több kockával dob, de maximum 4-gyel. A rendszer fázisban kaphatsz 1 'inaktív fegyverzet' jelzőt, hogy visszatölts 1 %CHARGE% jelzőt."""
"R4-P44":
text: """Miután teljesen véggrehajtasz egy piros manővert, ha van egy ellenséges hajó a %BULLSEYEARC% tűzívedben, kapsz 1 %CALCULATE% jelzőt."""
"Treacherous":
text: """Amikor védekezel, kiválaszthatsz egy a támadást akadályozó hajót és költs el 1 %CHARGE% jelzőt. Ha így teszel, semlegesíts 1 %HIT% vagy %CRIT% eredményt és a kiválasztott hajó kap egy túlterhelés jelzőt. Ha egy hajó 0-3-as távolságban megsemmisül, tölts vissza 1 %CHARGE% jelzőt."""
"Soulless One":
text: """Amikor védekezel, ha a támadó a tűzíveden kívül van újradobhatsz 1 védekezőkockát."""
condition_translations =
'Suppressive Fire':
text: '''Amikor végrehajtasz egy támadást más hajó ellen mint <strong>Captain Rex</strong>, dobj 1-gyel kevesebb kockával.%LINEBREAK% Miután <strong>Captain Rex</strong> védekezik, vedd le ezt a kártyát. %LINEBREAK% Az Ütközet fázis végén, ha <strong>Captain Rex</strong> nem hajtott végre támadást ebben a fázisban, vedd le ezt a kártyát. %LINEBREAK% Miután <strong>Captain Rex</strong> megsemmisült, vedd le ezt a kártyát.'''
'Hunted':
text: '''Miután megsemmisültél, választanod kell egy baráti hajót és átadni neki ezt a kondíció kártyát.'''
'Listening Device':
text: '''A Rendszer fázisban, ha egy ellenséges hajó az <strong>Informant</strong> fejlesztéssel 0-2-es távolságban van, fedd fel a tárcsád.'''
'Rattled':
text: '''Miután egy bomba vagy akna 0-1-es távolságban felrobban, elszenvedsz 1 %CRIT% sérülést. Aztán vedd le ezt a kártyát.%LINEBREAK%<strong>Akció:</strong> Ha nincs bomba vagy akna 0-1-es távolságban, vedd ele ezt a kártyát.'''
'Optimized Prototype':
text: '''Amikor végrehajtasz egy elsődleges %FRONTARC% támadást egy olyan hajó ellen, amit bemért <strong>PI:NAME:<NAME>END_PI</strong> fejlesztéssel felszerelt hajó, elkölthetsz 1 %HIT%/%CRIT%/%FOCUS% eredményt. Ha így teszel, választhatsz, hogy a védekező elveszt 1 pajzsot vagy a védekező felfordítja 1 sérüléskártyáját.'''
'''I'll Show You the Dark Side''':
text: '''Mikor ezt a kártyát hozzárendelik egy hajódhoz, ha nincs felfordított sérüléskártya rajta, az ellenfél kikeres a sérüléskártyáidból egy pilóta típusút és felfordítva ráteszi. Aztán megkeveri a paklit. Amikor elszenvednél 1 %CRIT% sérülést, ezen a kártyán lévő sérüléskártyát kapod meg. Aztán vedd le ezt a lapot.'''
'Proton Bomb':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, minden hajó és távérzékelő 0–1-es távolságban elszenved 1 %CRIT% sérülést.'''
'Seismic Charge':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, válassz 1 akadály 0–1-es távolságban. Minden hajó és távérzékelő 0–1-es távolságra az akadálytól elszenved 1 %HIT% sérülést.'''
'Bomblet':
text: '''(Bomba jelző) - Az Aktivációs fázis végén ez az eszköz felrobban. Amikor ez az eszköz felrobban, minden hajó 0–1-es távolságban dob 2 támadókockával. Minden hajó és távérzékelő elszenved 1 %HIT% sérülést minden egyes %HIT%/%CRIT% eredmény után.'''
'Loose Cargo':
text: '''(Űrszemét jelző) - A kidobott rakomány űrszemétnek számít.'''
'Conner Net':
text: '''(Akna jelző) - Miután egy hajó átmozog vagy átfedésbe kerül ezzel az eszközzel, az felrobban. Amikor ez az eszköz felrobban, a hajó elszenved 1 %HIT% sérülést és kap 3 ion jelzőt.'''
'Proximity Mine':
text: '''(Akna jelző) - Miután egy hajó átmozog vagy átfedésbe kerül ezzel az eszközzel, az felrobban. Amikor ez az eszköz felrobban, a hajó dob 2 támadókockával, aztán elszenved 1 %HIT%, valamint a dobott eremény szerint 1-1 %HIT%/%CRIT% sérülést.'''
'DRK-1 Probe Droid':
text: '''INIT: 0 / MOZGÉKONYSÁG: 3 / HULL: 1 / (távérzékelő)%LINEBREAK%Amikor egy baráti hajó bemér egy objektumot vagy zavar egy ellenséges hajót, mérheti a távolságot tőled. Miután egy ellenséges hajó átfedésbe kerül veled, az dob egy támadókockával. %FOCUS% eredménynél elszenvedsz 1 %HIT% sérülést.%LINEBREAK%Rendszer fázis: a kezdeményezésednek megfelelően arrébb mozgathatod a [2 %BANKLEFT%], [2 %STRAIGHT%] vagy [2 %BANKRIGHT%] sablonnal.'''
'Buzz Droid Swarm':
text: '''INIT: 0 / MOZGÉKONYSÁG: 3 / HULL: 1 / (távérzékelő)%LINEBREAK%Miután egy ellenséges hajó átmozog rajtad vagy átfedésbe kerül veled, átteheted annak első vagy hátsó pöckeihez (ilyenkor 0-ás távolságra vagy a hajótól). Nem lehetsz átfedésbe egy objektummal sem ily módon. Ha nem tudod elhelyezni a pöckökhöz, te és a hajó is elszenvedtek 1 %HIT% sérülést.%LINEBREAK%Ütközet fázis: a kezdeményezésednek megfelelően minden 0-ás távolságba nlévő hajó elszenved 1 %CRIT% sérülést.'''
exportObj.setupTranslationCardData pilot_translations, upgrade_translations, condition_translations
|
[
{
"context": "###\n# test/mocha/factory.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Tests for our ",
"end": 54,
"score": 0.9995285272598267,
"start": 43,
"tag": "NAME",
"value": "Dan Nichols"
},
{
"context": "efore ->\n Factory.define 'dummy',\n name... | test/mocha/factory.coffee | dlnichols/h_media | 0 | ###
# test/mocha/factory.coffee
#
# © 2014 Dan Nichols
# See LICENSE for more details
#
# Tests for our Factory factory
###
'use strict'
# External libs
should = require('chai').should()
expect = require('chai').expect
# Internal libs
Factory = require '../lib/factory.coffee'
describe 'Helper - Factory', ->
Model = ->
Model::save = (callback) ->
@saveCalled = true
callback()
Static = ->
Static:: = new Model()
Sync = ->
Sync:: = new Model()
Async = ->
Async:: = new Model()
Assoc = ->
Assoc:: = new Model()
before ->
Factory.define 'dummy',
name: 'Dummy'
Factory.define 'static', Static,
name: 'Monkey'
age: 12
syncCounter = 1
Factory.define 'sync', Sync,
name: ->
'Synchronous monkey ' + syncCounter++
Factory.define 'assoc', Assoc,
monkey: Factory.assoc 'static'
describe 'Method define', ->
it 'should throw an exception if no attributes are given', ->
expect(Factory.define).to.throw Error, /Invalid arguments/
expect(Factory.define.bind(null, 'name')).to.throw Error, /Invalid arguments/
expect(Factory.define.bind(null, 'name', dummy: true)).to.not.throw Error
describe 'Method attributesFor', ->
it 'should return the attributes when called synchronously', ->
attrs = Factory.attributesFor 'static'
expect(attrs).to.exist
expect(attrs).not.to.be.instanceof Static
expect(attrs).to.be.instanceof Object
it 'should pass attributes when called asynchronously', ->
Factory.attributesFor 'static', (err, attrs) ->
expect(attrs).to.exist
expect(attrs).not.to.be.instanceof Static
expect(attrs).to.be.instanceof Object
it 'should lazy evaluate synchronous functions', ->
attrs = Factory.attributesFor 'sync'
expect(attrs.name).to.match /^Synchronous monkey/
it 'should allow overriding and/or adding attributes', ->
attrs = Factory.build 'static',
name: 'Not a monkey'
foo: 'bar'
expect(attrs).to.be.instanceof Static
expect(attrs.name).to.eql 'Not a monkey'
expect(attrs.age).to.eql 12
expect(attrs.foo).to.exist
expect(attrs.foo).to.eql 'bar'
expect(attrs).to.not.have.property 'saveCalled'
it 'should allow synchronous dynamic attributes', ->
attrs = Factory.build 'sync'
expect(attrs).to.be.instanceof Sync
expect(attrs.name).to.match /^Synchronous monkey/
attrs2 = Factory.build 'sync'
expect(attrs2).to.be.instanceof Sync
expect(attrs2.name).to.match /^Synchronous monkey/
it 'should allow associative attributes', ->
model = Factory.build 'assoc'
expect(model).to.be.instanceof Assoc
expect(model.monkey).to.be.instanceof Static
expect(model.monkey.name).to.eql 'Monkey'
describe 'Method build', ->
it 'should return the model when called synchronously', ->
model = Factory.build 'static'
expect(model).to.exist
expect(model).to.be.instanceof Static
it 'should pass the model when call asynchronously', (done) ->
Factory.build 'static', (err, model) ->
expect(model).to.exist
expect(model).to.be.instanceof Static
done()
it 'should provide a dummy/stub factory class', ->
model = Factory.build 'dummy', dummy: true
expect(model).to.be.instanceof Factory.dummy
expect(model.name).to.eql 'Dummy'
expect(model.dummy).to.eql true
it 'should build, but not save the model', ->
model = Factory.build 'static'
expect(model).to.be.instanceof Static
expect(model.name).to.be.eql 'Monkey'
expect(model.age).to.be.eql 12
expect(model).to.not.have.property 'saveCalled'
describe 'Method create', ->
it 'should return the model when called synchronously', ->
model = Factory.create 'static'
expect(model).to.exist
expect(model).to.be.instanceof Static
it 'should pass the model when call asynchronously', (done) ->
Factory.create 'static', (err, model) ->
expect(model).to.exist
expect(model).to.be.instanceof Static
done()
it 'should build and save the model', ->
model = Factory.create 'static'
expect(model).to.be.instanceof Static
expect(model).to.have.property 'saveCalled'
expect(model.saveCalled).to.eql true
| 156909 | ###
# test/mocha/factory.coffee
#
# © 2014 <NAME>
# See LICENSE for more details
#
# Tests for our Factory factory
###
'use strict'
# External libs
should = require('chai').should()
expect = require('chai').expect
# Internal libs
Factory = require '../lib/factory.coffee'
describe 'Helper - Factory', ->
Model = ->
Model::save = (callback) ->
@saveCalled = true
callback()
Static = ->
Static:: = new Model()
Sync = ->
Sync:: = new Model()
Async = ->
Async:: = new Model()
Assoc = ->
Assoc:: = new Model()
before ->
Factory.define 'dummy',
name: '<NAME>'
Factory.define 'static', Static,
name: '<NAME>'
age: 12
syncCounter = 1
Factory.define 'sync', Sync,
name: ->
'Synchronous monkey ' + syncCounter++
Factory.define 'assoc', Assoc,
monkey: Factory.assoc 'static'
describe 'Method define', ->
it 'should throw an exception if no attributes are given', ->
expect(Factory.define).to.throw Error, /Invalid arguments/
expect(Factory.define.bind(null, 'name')).to.throw Error, /Invalid arguments/
expect(Factory.define.bind(null, 'name', dummy: true)).to.not.throw Error
describe 'Method attributesFor', ->
it 'should return the attributes when called synchronously', ->
attrs = Factory.attributesFor 'static'
expect(attrs).to.exist
expect(attrs).not.to.be.instanceof Static
expect(attrs).to.be.instanceof Object
it 'should pass attributes when called asynchronously', ->
Factory.attributesFor 'static', (err, attrs) ->
expect(attrs).to.exist
expect(attrs).not.to.be.instanceof Static
expect(attrs).to.be.instanceof Object
it 'should lazy evaluate synchronous functions', ->
attrs = Factory.attributesFor 'sync'
expect(attrs.name).to.match /^Synchronous monkey/
it 'should allow overriding and/or adding attributes', ->
attrs = Factory.build 'static',
name: '<NAME> monkey'
foo: 'bar'
expect(attrs).to.be.instanceof Static
expect(attrs.name).to.eql 'Not a monkey'
expect(attrs.age).to.eql 12
expect(attrs.foo).to.exist
expect(attrs.foo).to.eql 'bar'
expect(attrs).to.not.have.property 'saveCalled'
it 'should allow synchronous dynamic attributes', ->
attrs = Factory.build 'sync'
expect(attrs).to.be.instanceof Sync
expect(attrs.name).to.match /^Synchronous monkey/
attrs2 = Factory.build 'sync'
expect(attrs2).to.be.instanceof Sync
expect(attrs2.name).to.match /^Synchronous monkey/
it 'should allow associative attributes', ->
model = Factory.build 'assoc'
expect(model).to.be.instanceof Assoc
expect(model.monkey).to.be.instanceof Static
expect(model.monkey.name).to.eql 'Monkey'
describe 'Method build', ->
it 'should return the model when called synchronously', ->
model = Factory.build 'static'
expect(model).to.exist
expect(model).to.be.instanceof Static
it 'should pass the model when call asynchronously', (done) ->
Factory.build 'static', (err, model) ->
expect(model).to.exist
expect(model).to.be.instanceof Static
done()
it 'should provide a dummy/stub factory class', ->
model = Factory.build 'dummy', dummy: true
expect(model).to.be.instanceof Factory.dummy
expect(model.name).to.eql 'Dummy'
expect(model.dummy).to.eql true
it 'should build, but not save the model', ->
model = Factory.build 'static'
expect(model).to.be.instanceof Static
expect(model.name).to.be.eql 'Monkey'
expect(model.age).to.be.eql 12
expect(model).to.not.have.property 'saveCalled'
describe 'Method create', ->
it 'should return the model when called synchronously', ->
model = Factory.create 'static'
expect(model).to.exist
expect(model).to.be.instanceof Static
it 'should pass the model when call asynchronously', (done) ->
Factory.create 'static', (err, model) ->
expect(model).to.exist
expect(model).to.be.instanceof Static
done()
it 'should build and save the model', ->
model = Factory.create 'static'
expect(model).to.be.instanceof Static
expect(model).to.have.property 'saveCalled'
expect(model.saveCalled).to.eql true
| true | ###
# test/mocha/factory.coffee
#
# © 2014 PI:NAME:<NAME>END_PI
# See LICENSE for more details
#
# Tests for our Factory factory
###
'use strict'
# External libs
should = require('chai').should()
expect = require('chai').expect
# Internal libs
Factory = require '../lib/factory.coffee'
describe 'Helper - Factory', ->
Model = ->
Model::save = (callback) ->
@saveCalled = true
callback()
Static = ->
Static:: = new Model()
Sync = ->
Sync:: = new Model()
Async = ->
Async:: = new Model()
Assoc = ->
Assoc:: = new Model()
before ->
Factory.define 'dummy',
name: 'PI:NAME:<NAME>END_PI'
Factory.define 'static', Static,
name: 'PI:NAME:<NAME>END_PI'
age: 12
syncCounter = 1
Factory.define 'sync', Sync,
name: ->
'Synchronous monkey ' + syncCounter++
Factory.define 'assoc', Assoc,
monkey: Factory.assoc 'static'
describe 'Method define', ->
it 'should throw an exception if no attributes are given', ->
expect(Factory.define).to.throw Error, /Invalid arguments/
expect(Factory.define.bind(null, 'name')).to.throw Error, /Invalid arguments/
expect(Factory.define.bind(null, 'name', dummy: true)).to.not.throw Error
describe 'Method attributesFor', ->
it 'should return the attributes when called synchronously', ->
attrs = Factory.attributesFor 'static'
expect(attrs).to.exist
expect(attrs).not.to.be.instanceof Static
expect(attrs).to.be.instanceof Object
it 'should pass attributes when called asynchronously', ->
Factory.attributesFor 'static', (err, attrs) ->
expect(attrs).to.exist
expect(attrs).not.to.be.instanceof Static
expect(attrs).to.be.instanceof Object
it 'should lazy evaluate synchronous functions', ->
attrs = Factory.attributesFor 'sync'
expect(attrs.name).to.match /^Synchronous monkey/
it 'should allow overriding and/or adding attributes', ->
attrs = Factory.build 'static',
name: 'PI:NAME:<NAME>END_PI monkey'
foo: 'bar'
expect(attrs).to.be.instanceof Static
expect(attrs.name).to.eql 'Not a monkey'
expect(attrs.age).to.eql 12
expect(attrs.foo).to.exist
expect(attrs.foo).to.eql 'bar'
expect(attrs).to.not.have.property 'saveCalled'
it 'should allow synchronous dynamic attributes', ->
attrs = Factory.build 'sync'
expect(attrs).to.be.instanceof Sync
expect(attrs.name).to.match /^Synchronous monkey/
attrs2 = Factory.build 'sync'
expect(attrs2).to.be.instanceof Sync
expect(attrs2.name).to.match /^Synchronous monkey/
it 'should allow associative attributes', ->
model = Factory.build 'assoc'
expect(model).to.be.instanceof Assoc
expect(model.monkey).to.be.instanceof Static
expect(model.monkey.name).to.eql 'Monkey'
describe 'Method build', ->
it 'should return the model when called synchronously', ->
model = Factory.build 'static'
expect(model).to.exist
expect(model).to.be.instanceof Static
it 'should pass the model when call asynchronously', (done) ->
Factory.build 'static', (err, model) ->
expect(model).to.exist
expect(model).to.be.instanceof Static
done()
it 'should provide a dummy/stub factory class', ->
model = Factory.build 'dummy', dummy: true
expect(model).to.be.instanceof Factory.dummy
expect(model.name).to.eql 'Dummy'
expect(model.dummy).to.eql true
it 'should build, but not save the model', ->
model = Factory.build 'static'
expect(model).to.be.instanceof Static
expect(model.name).to.be.eql 'Monkey'
expect(model.age).to.be.eql 12
expect(model).to.not.have.property 'saveCalled'
describe 'Method create', ->
it 'should return the model when called synchronously', ->
model = Factory.create 'static'
expect(model).to.exist
expect(model).to.be.instanceof Static
it 'should pass the model when call asynchronously', (done) ->
Factory.create 'static', (err, model) ->
expect(model).to.exist
expect(model).to.be.instanceof Static
done()
it 'should build and save the model', ->
model = Factory.create 'static'
expect(model).to.be.instanceof Static
expect(model).to.have.property 'saveCalled'
expect(model.saveCalled).to.eql true
|
[
{
"context": "r morghulis\r\n# valar dohaeris\r\n#\r\n# Author:\r\n# FaytLeingod\r\n\r\n\r\nmodule.exports = (robot) ->\r\n robot.hear /v",
"end": 189,
"score": 0.9809980988502502,
"start": 178,
"tag": "NAME",
"value": "FaytLeingod"
}
] | Hubot/valyrian.coffee | FaytLeingod007/JabbR | 3 | # Description:
# Legitimate Valyrian
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# valar morghulis
# valar dohaeris
#
# Author:
# FaytLeingod
module.exports = (robot) ->
robot.hear /valar dohaeris/i, (msg) ->
robot.brain.set 'Valyrian', 0
msg.send 'All men must serve.'
robot.hear /(.+)/, (msg) ->
if (robot.brain.get('Valyrian') == 1)
translation = msg.match[1]
msg.send translation.replace /[aeiou]/gi, "y"
robot.hear /valar morghulis/i, (msg) ->
robot.brain.set 'Valyrian', 1
msg.send 'All men must die.' | 177949 | # Description:
# Legitimate Valyrian
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# valar morghulis
# valar dohaeris
#
# Author:
# <NAME>
module.exports = (robot) ->
robot.hear /valar dohaeris/i, (msg) ->
robot.brain.set 'Valyrian', 0
msg.send 'All men must serve.'
robot.hear /(.+)/, (msg) ->
if (robot.brain.get('Valyrian') == 1)
translation = msg.match[1]
msg.send translation.replace /[aeiou]/gi, "y"
robot.hear /valar morghulis/i, (msg) ->
robot.brain.set 'Valyrian', 1
msg.send 'All men must die.' | true | # Description:
# Legitimate Valyrian
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# valar morghulis
# valar dohaeris
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.hear /valar dohaeris/i, (msg) ->
robot.brain.set 'Valyrian', 0
msg.send 'All men must serve.'
robot.hear /(.+)/, (msg) ->
if (robot.brain.get('Valyrian') == 1)
translation = msg.match[1]
msg.send translation.replace /[aeiou]/gi, "y"
robot.hear /valar morghulis/i, (msg) ->
robot.brain.set 'Valyrian', 1
msg.send 'All men must die.' |
[
{
"context": "-\n# are not associated with the class\nHERO = 'Batman'\nSUPERSAY = -> console.log \"#{HERO} rulz!\"\n\nclass",
"end": 219,
"score": 0.9997732639312744,
"start": 213,
"tag": "NAME",
"value": "Batman"
},
{
"context": "-\n # defined without '@'\n constructor: (name ... | lib/User.coffee | Kikobeats/coffee_playground | 0 | # More information:
# http://coffeescriptcookbook.com/chapters/classes_and_objects/class-methods-and-instance-methods
# -- Helpers Method -------------------------
# are not associated with the class
HERO = 'Batman'
SUPERSAY = -> console.log "#{HERO} rulz!"
class User
# -- Static Class Method ------------------
# defined with '@'
# Public static method
@NAME: 'User'
@say: -> console.log "I'm a #{@NAME} model, u know ?"
# -- Private Class Method -----------------
# defined whit '_'
_surname: HERO
# If you declared a private method and reference a
# private variable need to reference the context (@)
_say: -> console.log "I'm #{@_surname}, but sssh!"
# -- Public Class Method -------------------
# defined without '@'
constructor: (name = 'Paco', alias = 'Paquito', from = 'Valencia') ->
# attributes declared in the constructor
# are accesibles (use @)
# For convention, if you can declare a private
# variable or method inside the class use '_'
@_name = name
@_alias = alias
@_from = from
# If you have too many arguments you can pass and
# object and make the assignment
# more information:
# http://coffeescript.org/#destructuring
# Class method
hello: ->
console.log "I'm #{@_name}, but my mum call me #{@_alias} and I'm from #{@_from}!"
exports = module.exports = User
| 172839 | # More information:
# http://coffeescriptcookbook.com/chapters/classes_and_objects/class-methods-and-instance-methods
# -- Helpers Method -------------------------
# are not associated with the class
HERO = '<NAME>'
SUPERSAY = -> console.log "#{HERO} rulz!"
class User
# -- Static Class Method ------------------
# defined with '@'
# Public static method
@NAME: 'User'
@say: -> console.log "I'm a #{@NAME} model, u know ?"
# -- Private Class Method -----------------
# defined whit '_'
_surname: HERO
# If you declared a private method and reference a
# private variable need to reference the context (@)
_say: -> console.log "I'm #{@_surname}, but sssh!"
# -- Public Class Method -------------------
# defined without '@'
constructor: (name = '<NAME>', alias = '<NAME>', from = 'Valencia') ->
# attributes declared in the constructor
# are accesibles (use @)
# For convention, if you can declare a private
# variable or method inside the class use '_'
@_name = name
@_alias = alias
@_from = from
# If you have too many arguments you can pass and
# object and make the assignment
# more information:
# http://coffeescript.org/#destructuring
# Class method
hello: ->
console.log "I'm #{@_name}, but my mum call me #{@_alias} and I'm from #{@_from}!"
exports = module.exports = User
| true | # More information:
# http://coffeescriptcookbook.com/chapters/classes_and_objects/class-methods-and-instance-methods
# -- Helpers Method -------------------------
# are not associated with the class
HERO = 'PI:NAME:<NAME>END_PI'
SUPERSAY = -> console.log "#{HERO} rulz!"
class User
# -- Static Class Method ------------------
# defined with '@'
# Public static method
@NAME: 'User'
@say: -> console.log "I'm a #{@NAME} model, u know ?"
# -- Private Class Method -----------------
# defined whit '_'
_surname: HERO
# If you declared a private method and reference a
# private variable need to reference the context (@)
_say: -> console.log "I'm #{@_surname}, but sssh!"
# -- Public Class Method -------------------
# defined without '@'
constructor: (name = 'PI:NAME:<NAME>END_PI', alias = 'PI:NAME:<NAME>END_PI', from = 'Valencia') ->
# attributes declared in the constructor
# are accesibles (use @)
# For convention, if you can declare a private
# variable or method inside the class use '_'
@_name = name
@_alias = alias
@_from = from
# If you have too many arguments you can pass and
# object and make the assignment
# more information:
# http://coffeescript.org/#destructuring
# Class method
hello: ->
console.log "I'm #{@_name}, but my mum call me #{@_alias} and I'm from #{@_from}!"
exports = module.exports = User
|
[
{
"context": "Item: ->\n\n return {title: 'Delete Post', key: 'showdeletepostprompt', onClick: @bound 'showDeletePostPromptModal'}\n\n\n",
"end": 4844,
"score": 0.6306018829345703,
"start": 4824,
"tag": "KEY",
"value": "showdeletepostprompt"
}
] | client/activity/lib/components/messageitemmenu/index.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
React = require 'kd-react'
ButtonWithMenu = require 'app/components/buttonwithmenu'
getMessageOwner = require 'app/util/getMessageOwner'
ActivityFlux = require 'activity/flux'
AppFlux = require 'app/flux'
immutable = require 'immutable'
whoami = require 'app/util/whoami'
remote = require('app/remote').getInstance()
BlockUserModal = require 'app/components/blockusermodal'
ActivityPromptModal = require 'app/components/activitypromptmodal'
MarkUserAsTrollModal = require 'app/components/markuserastrollmodal'
showErrorNotification = require 'app/util/showErrorNotification'
hasPermission = require 'app/util/hasPermission'
module.exports = class MessageItemMenu extends React.Component
@defaultProps =
disableAdminMenuItems : no
message : immutable.Map()
channelId : ''
constructor: (props) ->
super props
@state =
account : null
isDeleting : no
isOwnerExempt : no
isBlockUserModalVisible : no
isMarkUserAsTrollModalVisible : no
componentDidMount: ->
@checkTheOwnerIsExempt()
@getAccountInfo()
checkTheOwnerIsExempt: ->
getMessageOwner @props.message.toJS(), (err, owner) =>
return showErrorNotification err if err
@setState isOwnerExempt: owner.isExempt
getAccountInfo: ->
message = @props.message.toJS()
if message.account._id
remote.cacheable "JAccount", message.account._id, (err, account)=>
return @setState account: account if account
else if message.bongo_.constructorName is 'JAccount'
return @setState account: message if account
showBlockUserPromptModal: ->
@setState isBlockUserModalVisible: yes
closeBlockUserPromptModal: (event) ->
kd.utils.stopDOMEvent event
@setState isBlockUserModalVisible: no
showDeletePostPromptModal: ->
@setState isDeleting: yes
closeDeletePostModal: (event) ->
kd.utils.stopDOMEvent event
@setState isDeleting: no
showMarkUserAsTrollPromptModal: ->
@setState isMarkUserAsTrollModalVisible: yes
closeMarkUserAsTrollModal: (event) ->
kd.utils.stopDOMEvent event
@setState isMarkUserAsTrollModalVisible: no
unMarkUserAsTroll: (event) ->
kd.utils.stopDOMEvent event
AppFlux.actions.user.unmarkUserAsTroll @state.account
@closeMarkUserAsTrollModal()
editPost: ->
messageId = @props.message.get '_id'
ActivityFlux.actions.message.setMessageEditMode messageId, @props.channelId
deletePostButtonHandler: (event) ->
kd.utils.stopDOMEvent event
ActivityFlux.actions.message.removeMessage @props.message.get('id')
@closeDeletePostModal()
impersonateUser: (event) ->
kd.utils.stopDOMEvent event
{ message } = @props
AppFlux.actions.user.impersonateUser message.toJS()
getBlockUserModalProps: ->
account : @state.account
buttonConfirmTitle : "BLOCK USER"
className : "BlockUserModal"
onAbort : @bound "closeBlockUserPromptModal"
onClose : @bound "closeBlockUserPromptModal"
getDeleteItemModalProps: ->
title : "Delete post"
body : "Are you sure you want to delete this post?"
buttonConfirmTitle : "DELETE"
className : "Modal-DeleteItemPrompt"
onConfirm : @bound "deletePostButtonHandler"
onAbort : @bound "closeDeletePostModal"
onClose : @bound "closeDeletePostModal"
getMarkUserAsTrollModalProps: ->
account : @state.account
title : "MARK USER AS TROLL"
className : "MarkUserAsTrollModal"
onAbort : @bound "closeMarkUserAsTrollModal"
onClose : @bound "closeMarkUserAsTrollModal"
buttonConfirmTitle : "YES, THIS USER IS DEFINITELY A TROLL"
canEditPost: ->
canEdit = hasPermission 'edit posts'
canEditOwn = hasPermission 'edit own posts'
return canEdit or (canEditOwn and @isMyMessage())
canDeletePost: ->
canDelete = hasPermission 'delete posts'
canDeleteOwn = hasPermission 'delete own posts'
return canDelete or (canDeleteOwn and @isMyMessage())
isMyMessage: ->
return @props.message.get('accountId') is whoami().socialApiId
getMenuItems: ->
result = []
if @canEditPost() then result.push @getEditMenuItem()
if @canDeletePost() then result.push @getDeleteMenuItem()
return result
getEditMenuItem: ->
return {title: 'Edit Post' , key: 'editpost' , onClick: @bound 'editPost'}
getDeleteMenuItem: ->
return {title: 'Delete Post', key: 'showdeletepostprompt', onClick: @bound 'showDeletePostPromptModal'}
render: ->
{ message } = @props
return null unless message
return null if not @canEditPost() or not @canDeletePost()
<div className={@props.className}>
<ButtonWithMenu items={@getMenuItems()} />
<BlockUserModal
{...@getBlockUserModalProps()}
isOpen={@state.isBlockUserModalVisible} />
<MarkUserAsTrollModal
{...@getMarkUserAsTrollModalProps()}
isOpen={@state.isMarkUserAsTrollModalVisible} />
<ActivityPromptModal
{...@getDeleteItemModalProps()}
isOpen={@state.isDeleting}>
Are you sure you want to delete this post?
</ActivityPromptModal>
</div>
| 223531 | kd = require 'kd'
React = require 'kd-react'
ButtonWithMenu = require 'app/components/buttonwithmenu'
getMessageOwner = require 'app/util/getMessageOwner'
ActivityFlux = require 'activity/flux'
AppFlux = require 'app/flux'
immutable = require 'immutable'
whoami = require 'app/util/whoami'
remote = require('app/remote').getInstance()
BlockUserModal = require 'app/components/blockusermodal'
ActivityPromptModal = require 'app/components/activitypromptmodal'
MarkUserAsTrollModal = require 'app/components/markuserastrollmodal'
showErrorNotification = require 'app/util/showErrorNotification'
hasPermission = require 'app/util/hasPermission'
module.exports = class MessageItemMenu extends React.Component
@defaultProps =
disableAdminMenuItems : no
message : immutable.Map()
channelId : ''
constructor: (props) ->
super props
@state =
account : null
isDeleting : no
isOwnerExempt : no
isBlockUserModalVisible : no
isMarkUserAsTrollModalVisible : no
componentDidMount: ->
@checkTheOwnerIsExempt()
@getAccountInfo()
checkTheOwnerIsExempt: ->
getMessageOwner @props.message.toJS(), (err, owner) =>
return showErrorNotification err if err
@setState isOwnerExempt: owner.isExempt
getAccountInfo: ->
message = @props.message.toJS()
if message.account._id
remote.cacheable "JAccount", message.account._id, (err, account)=>
return @setState account: account if account
else if message.bongo_.constructorName is 'JAccount'
return @setState account: message if account
showBlockUserPromptModal: ->
@setState isBlockUserModalVisible: yes
closeBlockUserPromptModal: (event) ->
kd.utils.stopDOMEvent event
@setState isBlockUserModalVisible: no
showDeletePostPromptModal: ->
@setState isDeleting: yes
closeDeletePostModal: (event) ->
kd.utils.stopDOMEvent event
@setState isDeleting: no
showMarkUserAsTrollPromptModal: ->
@setState isMarkUserAsTrollModalVisible: yes
closeMarkUserAsTrollModal: (event) ->
kd.utils.stopDOMEvent event
@setState isMarkUserAsTrollModalVisible: no
unMarkUserAsTroll: (event) ->
kd.utils.stopDOMEvent event
AppFlux.actions.user.unmarkUserAsTroll @state.account
@closeMarkUserAsTrollModal()
editPost: ->
messageId = @props.message.get '_id'
ActivityFlux.actions.message.setMessageEditMode messageId, @props.channelId
deletePostButtonHandler: (event) ->
kd.utils.stopDOMEvent event
ActivityFlux.actions.message.removeMessage @props.message.get('id')
@closeDeletePostModal()
impersonateUser: (event) ->
kd.utils.stopDOMEvent event
{ message } = @props
AppFlux.actions.user.impersonateUser message.toJS()
getBlockUserModalProps: ->
account : @state.account
buttonConfirmTitle : "BLOCK USER"
className : "BlockUserModal"
onAbort : @bound "closeBlockUserPromptModal"
onClose : @bound "closeBlockUserPromptModal"
getDeleteItemModalProps: ->
title : "Delete post"
body : "Are you sure you want to delete this post?"
buttonConfirmTitle : "DELETE"
className : "Modal-DeleteItemPrompt"
onConfirm : @bound "deletePostButtonHandler"
onAbort : @bound "closeDeletePostModal"
onClose : @bound "closeDeletePostModal"
getMarkUserAsTrollModalProps: ->
account : @state.account
title : "MARK USER AS TROLL"
className : "MarkUserAsTrollModal"
onAbort : @bound "closeMarkUserAsTrollModal"
onClose : @bound "closeMarkUserAsTrollModal"
buttonConfirmTitle : "YES, THIS USER IS DEFINITELY A TROLL"
canEditPost: ->
canEdit = hasPermission 'edit posts'
canEditOwn = hasPermission 'edit own posts'
return canEdit or (canEditOwn and @isMyMessage())
canDeletePost: ->
canDelete = hasPermission 'delete posts'
canDeleteOwn = hasPermission 'delete own posts'
return canDelete or (canDeleteOwn and @isMyMessage())
isMyMessage: ->
return @props.message.get('accountId') is whoami().socialApiId
getMenuItems: ->
result = []
if @canEditPost() then result.push @getEditMenuItem()
if @canDeletePost() then result.push @getDeleteMenuItem()
return result
getEditMenuItem: ->
return {title: 'Edit Post' , key: 'editpost' , onClick: @bound 'editPost'}
getDeleteMenuItem: ->
return {title: 'Delete Post', key: '<KEY>', onClick: @bound 'showDeletePostPromptModal'}
render: ->
{ message } = @props
return null unless message
return null if not @canEditPost() or not @canDeletePost()
<div className={@props.className}>
<ButtonWithMenu items={@getMenuItems()} />
<BlockUserModal
{...@getBlockUserModalProps()}
isOpen={@state.isBlockUserModalVisible} />
<MarkUserAsTrollModal
{...@getMarkUserAsTrollModalProps()}
isOpen={@state.isMarkUserAsTrollModalVisible} />
<ActivityPromptModal
{...@getDeleteItemModalProps()}
isOpen={@state.isDeleting}>
Are you sure you want to delete this post?
</ActivityPromptModal>
</div>
| true | kd = require 'kd'
React = require 'kd-react'
ButtonWithMenu = require 'app/components/buttonwithmenu'
getMessageOwner = require 'app/util/getMessageOwner'
ActivityFlux = require 'activity/flux'
AppFlux = require 'app/flux'
immutable = require 'immutable'
whoami = require 'app/util/whoami'
remote = require('app/remote').getInstance()
BlockUserModal = require 'app/components/blockusermodal'
ActivityPromptModal = require 'app/components/activitypromptmodal'
MarkUserAsTrollModal = require 'app/components/markuserastrollmodal'
showErrorNotification = require 'app/util/showErrorNotification'
hasPermission = require 'app/util/hasPermission'
module.exports = class MessageItemMenu extends React.Component
@defaultProps =
disableAdminMenuItems : no
message : immutable.Map()
channelId : ''
constructor: (props) ->
super props
@state =
account : null
isDeleting : no
isOwnerExempt : no
isBlockUserModalVisible : no
isMarkUserAsTrollModalVisible : no
componentDidMount: ->
@checkTheOwnerIsExempt()
@getAccountInfo()
checkTheOwnerIsExempt: ->
getMessageOwner @props.message.toJS(), (err, owner) =>
return showErrorNotification err if err
@setState isOwnerExempt: owner.isExempt
getAccountInfo: ->
message = @props.message.toJS()
if message.account._id
remote.cacheable "JAccount", message.account._id, (err, account)=>
return @setState account: account if account
else if message.bongo_.constructorName is 'JAccount'
return @setState account: message if account
showBlockUserPromptModal: ->
@setState isBlockUserModalVisible: yes
closeBlockUserPromptModal: (event) ->
kd.utils.stopDOMEvent event
@setState isBlockUserModalVisible: no
showDeletePostPromptModal: ->
@setState isDeleting: yes
closeDeletePostModal: (event) ->
kd.utils.stopDOMEvent event
@setState isDeleting: no
showMarkUserAsTrollPromptModal: ->
@setState isMarkUserAsTrollModalVisible: yes
closeMarkUserAsTrollModal: (event) ->
kd.utils.stopDOMEvent event
@setState isMarkUserAsTrollModalVisible: no
unMarkUserAsTroll: (event) ->
kd.utils.stopDOMEvent event
AppFlux.actions.user.unmarkUserAsTroll @state.account
@closeMarkUserAsTrollModal()
editPost: ->
messageId = @props.message.get '_id'
ActivityFlux.actions.message.setMessageEditMode messageId, @props.channelId
deletePostButtonHandler: (event) ->
kd.utils.stopDOMEvent event
ActivityFlux.actions.message.removeMessage @props.message.get('id')
@closeDeletePostModal()
impersonateUser: (event) ->
kd.utils.stopDOMEvent event
{ message } = @props
AppFlux.actions.user.impersonateUser message.toJS()
getBlockUserModalProps: ->
account : @state.account
buttonConfirmTitle : "BLOCK USER"
className : "BlockUserModal"
onAbort : @bound "closeBlockUserPromptModal"
onClose : @bound "closeBlockUserPromptModal"
getDeleteItemModalProps: ->
title : "Delete post"
body : "Are you sure you want to delete this post?"
buttonConfirmTitle : "DELETE"
className : "Modal-DeleteItemPrompt"
onConfirm : @bound "deletePostButtonHandler"
onAbort : @bound "closeDeletePostModal"
onClose : @bound "closeDeletePostModal"
getMarkUserAsTrollModalProps: ->
account : @state.account
title : "MARK USER AS TROLL"
className : "MarkUserAsTrollModal"
onAbort : @bound "closeMarkUserAsTrollModal"
onClose : @bound "closeMarkUserAsTrollModal"
buttonConfirmTitle : "YES, THIS USER IS DEFINITELY A TROLL"
canEditPost: ->
canEdit = hasPermission 'edit posts'
canEditOwn = hasPermission 'edit own posts'
return canEdit or (canEditOwn and @isMyMessage())
canDeletePost: ->
canDelete = hasPermission 'delete posts'
canDeleteOwn = hasPermission 'delete own posts'
return canDelete or (canDeleteOwn and @isMyMessage())
isMyMessage: ->
return @props.message.get('accountId') is whoami().socialApiId
getMenuItems: ->
result = []
if @canEditPost() then result.push @getEditMenuItem()
if @canDeletePost() then result.push @getDeleteMenuItem()
return result
getEditMenuItem: ->
return {title: 'Edit Post' , key: 'editpost' , onClick: @bound 'editPost'}
getDeleteMenuItem: ->
return {title: 'Delete Post', key: 'PI:KEY:<KEY>END_PI', onClick: @bound 'showDeletePostPromptModal'}
render: ->
{ message } = @props
return null unless message
return null if not @canEditPost() or not @canDeletePost()
<div className={@props.className}>
<ButtonWithMenu items={@getMenuItems()} />
<BlockUserModal
{...@getBlockUserModalProps()}
isOpen={@state.isBlockUserModalVisible} />
<MarkUserAsTrollModal
{...@getMarkUserAsTrollModalProps()}
isOpen={@state.isMarkUserAsTrollModalVisible} />
<ActivityPromptModal
{...@getDeleteItemModalProps()}
isOpen={@state.isDeleting}>
Are you sure you want to delete this post?
</ActivityPromptModal>
</div>
|
[
{
"context": "nect\n @socket.incoming.emit 'disconnect', 'Eula Tucker'\n\n it 'should proxy the event', ->\n e",
"end": 1254,
"score": 0.9986823201179504,
"start": 1243,
"tag": "NAME",
"value": "Eula Tucker"
},
{
"context": " expect(@onDisconnect).to.have.been.ca... | test/src/proxy-socket-spec.coffee | octoblu/npm | 3 | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
ProxySocket = require '../../src/proxy-socket'
AsymetricSocket = require '../asymmetric-socket'
describe 'ProxySocket', ->
@timeout 100
describe 'with a connected BufferedSocket', ->
beforeEach ->
@socket = new AsymetricSocket
@socket.connect = sinon.stub().yields null
@sut = new ProxySocket {@socket}
@sut._proxyDefaultIncomingEvents()
describe 'on "config"', ->
beforeEach (done) ->
@onConfig = sinon.spy => done()
@sut.once 'config', @onConfig
@socket.incoming.emit 'config', foo: 'bar'
it 'should proxy the event', ->
expect(@onConfig).to.have.been.calledWith foo: 'bar'
describe 'on "connect"', ->
beforeEach (done) ->
@onConnect = sinon.spy => done()
@sut.once 'connect', @onConnect
@socket.incoming.emit 'connect', foo: 'bar'
it 'should proxy the event', ->
expect(@onConnect).to.have.been.calledWith foo: 'bar'
describe 'on "disconnect"', ->
beforeEach (done) ->
@onDisconnect = sinon.spy => done()
@sut.once 'disconnect', @onDisconnect
@socket.incoming.emit 'disconnect', 'Eula Tucker'
it 'should proxy the event', ->
expect(@onDisconnect).to.have.been.calledWith 'Eula Tucker'
describe 'on "error"', ->
beforeEach (done) ->
@onError = sinon.spy => done()
@sut.once 'error', @onError
@socket.incoming.emit 'error', 'Donald Bridges'
it 'should proxy the event', ->
expect(@onError).to.have.been.calledWith 'Donald Bridges'
describe 'on "message"', ->
beforeEach (done) ->
@onMessage = sinon.spy => done()
@sut.once 'message', @onMessage
@socket.incoming.emit 'message', name: 'me.net'
it 'should proxy the event', ->
expect(@onMessage).to.have.been.calledWith name: 'me.net'
describe 'on "notReady"', ->
describe 'when a generic "notReady" is emitted', ->
beforeEach (done) ->
@onNotReady = sinon.spy => done()
@sut.once 'notReady', @onNotReady
@socket.incoming.emit 'notReady', lawba: 'Loretta Cannon'
it 'should proxy the event', ->
expect(@onNotReady).to.have.been.calledWith lawba: 'Loretta Cannon'
describe 'on "ratelimited"', ->
beforeEach (done) ->
@onReady = sinon.spy => done()
@sut.once 'ratelimited', @onReady
@socket.incoming.emit 'ratelimited', mapjoziw: 'Soozie Whoalzel'
it 'should proxy the event', ->
expect(@onReady).to.have.been.calledWith mapjoziw: 'Soozie Whoalzel'
describe 'on "ready"', ->
beforeEach (done) ->
@onReady = sinon.spy => done()
@sut.once 'ready', @onReady
@socket.incoming.emit 'ready', mapjoziw: 'Edward Jensen'
it 'should proxy the event', ->
expect(@onReady).to.have.been.calledWith mapjoziw: 'Edward Jensen'
| 220258 | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
ProxySocket = require '../../src/proxy-socket'
AsymetricSocket = require '../asymmetric-socket'
describe 'ProxySocket', ->
@timeout 100
describe 'with a connected BufferedSocket', ->
beforeEach ->
@socket = new AsymetricSocket
@socket.connect = sinon.stub().yields null
@sut = new ProxySocket {@socket}
@sut._proxyDefaultIncomingEvents()
describe 'on "config"', ->
beforeEach (done) ->
@onConfig = sinon.spy => done()
@sut.once 'config', @onConfig
@socket.incoming.emit 'config', foo: 'bar'
it 'should proxy the event', ->
expect(@onConfig).to.have.been.calledWith foo: 'bar'
describe 'on "connect"', ->
beforeEach (done) ->
@onConnect = sinon.spy => done()
@sut.once 'connect', @onConnect
@socket.incoming.emit 'connect', foo: 'bar'
it 'should proxy the event', ->
expect(@onConnect).to.have.been.calledWith foo: 'bar'
describe 'on "disconnect"', ->
beforeEach (done) ->
@onDisconnect = sinon.spy => done()
@sut.once 'disconnect', @onDisconnect
@socket.incoming.emit 'disconnect', '<NAME>'
it 'should proxy the event', ->
expect(@onDisconnect).to.have.been.calledWith '<NAME>'
describe 'on "error"', ->
beforeEach (done) ->
@onError = sinon.spy => done()
@sut.once 'error', @onError
@socket.incoming.emit 'error', '<NAME>'
it 'should proxy the event', ->
expect(@onError).to.have.been.calledWith '<NAME>'
describe 'on "message"', ->
beforeEach (done) ->
@onMessage = sinon.spy => done()
@sut.once 'message', @onMessage
@socket.incoming.emit 'message', name: 'me.net'
it 'should proxy the event', ->
expect(@onMessage).to.have.been.calledWith name: 'me.net'
describe 'on "notReady"', ->
describe 'when a generic "notReady" is emitted', ->
beforeEach (done) ->
@onNotReady = sinon.spy => done()
@sut.once 'notReady', @onNotReady
@socket.incoming.emit 'notReady', lawba: '<NAME>'
it 'should proxy the event', ->
expect(@onNotReady).to.have.been.calledWith lawba: '<NAME>'
describe 'on "ratelimited"', ->
beforeEach (done) ->
@onReady = sinon.spy => done()
@sut.once 'ratelimited', @onReady
@socket.incoming.emit 'ratelimited', mapjoziw: '<NAME>'
it 'should proxy the event', ->
expect(@onReady).to.have.been.calledWith mapjoziw: '<NAME>'
describe 'on "ready"', ->
beforeEach (done) ->
@onReady = sinon.spy => done()
@sut.once 'ready', @onReady
@socket.incoming.emit 'ready', mapjoziw: '<NAME>'
it 'should proxy the event', ->
expect(@onReady).to.have.been.calledWith mapjoziw: '<NAME>'
| true | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
ProxySocket = require '../../src/proxy-socket'
AsymetricSocket = require '../asymmetric-socket'
describe 'ProxySocket', ->
@timeout 100
describe 'with a connected BufferedSocket', ->
beforeEach ->
@socket = new AsymetricSocket
@socket.connect = sinon.stub().yields null
@sut = new ProxySocket {@socket}
@sut._proxyDefaultIncomingEvents()
describe 'on "config"', ->
beforeEach (done) ->
@onConfig = sinon.spy => done()
@sut.once 'config', @onConfig
@socket.incoming.emit 'config', foo: 'bar'
it 'should proxy the event', ->
expect(@onConfig).to.have.been.calledWith foo: 'bar'
describe 'on "connect"', ->
beforeEach (done) ->
@onConnect = sinon.spy => done()
@sut.once 'connect', @onConnect
@socket.incoming.emit 'connect', foo: 'bar'
it 'should proxy the event', ->
expect(@onConnect).to.have.been.calledWith foo: 'bar'
describe 'on "disconnect"', ->
beforeEach (done) ->
@onDisconnect = sinon.spy => done()
@sut.once 'disconnect', @onDisconnect
@socket.incoming.emit 'disconnect', 'PI:NAME:<NAME>END_PI'
it 'should proxy the event', ->
expect(@onDisconnect).to.have.been.calledWith 'PI:NAME:<NAME>END_PI'
describe 'on "error"', ->
beforeEach (done) ->
@onError = sinon.spy => done()
@sut.once 'error', @onError
@socket.incoming.emit 'error', 'PI:NAME:<NAME>END_PI'
it 'should proxy the event', ->
expect(@onError).to.have.been.calledWith 'PI:NAME:<NAME>END_PI'
describe 'on "message"', ->
beforeEach (done) ->
@onMessage = sinon.spy => done()
@sut.once 'message', @onMessage
@socket.incoming.emit 'message', name: 'me.net'
it 'should proxy the event', ->
expect(@onMessage).to.have.been.calledWith name: 'me.net'
describe 'on "notReady"', ->
describe 'when a generic "notReady" is emitted', ->
beforeEach (done) ->
@onNotReady = sinon.spy => done()
@sut.once 'notReady', @onNotReady
@socket.incoming.emit 'notReady', lawba: 'PI:NAME:<NAME>END_PI'
it 'should proxy the event', ->
expect(@onNotReady).to.have.been.calledWith lawba: 'PI:NAME:<NAME>END_PI'
describe 'on "ratelimited"', ->
beforeEach (done) ->
@onReady = sinon.spy => done()
@sut.once 'ratelimited', @onReady
@socket.incoming.emit 'ratelimited', mapjoziw: 'PI:NAME:<NAME>END_PI'
it 'should proxy the event', ->
expect(@onReady).to.have.been.calledWith mapjoziw: 'PI:NAME:<NAME>END_PI'
describe 'on "ready"', ->
beforeEach (done) ->
@onReady = sinon.spy => done()
@sut.once 'ready', @onReady
@socket.incoming.emit 'ready', mapjoziw: 'PI:NAME:<NAME>END_PI'
it 'should proxy the event', ->
expect(@onReady).to.have.been.calledWith mapjoziw: 'PI:NAME:<NAME>END_PI'
|
[
{
"context": " gateblu.devices.push {uuid: device.uuid, token: device.token, connector: 'flow-runner'}\n @saveGat",
"end": 2467,
"score": 0.5681480765342712,
"start": 2461,
"tag": "PASSWORD",
"value": "device"
}
] | index.coffee | octoblu/gateblu-atomizer | 1 | _ = require 'lodash'
meshblu = require 'meshblu'
request = require 'request'
url = require 'url'
debug = require('debug')('gateblu-atomizer')
{EventEmitter} = require 'events'
class GatebluAtomizer extends EventEmitter
constructor: (config={}) ->
@meshbluOptions = _.pick config, 'uuid', 'token', 'server', 'port'
@target = {uuid: config.targetUuid, token: config.targetToken}
@queue = []
@processFunctions =
'add-device': @addDevice
'remove-device': @removeDevice
'nodered-instance-start': @addDevice
'nodered-instance-stop': @removeDevice
'create': @addDevice
'delete': @removeDevice
run: =>
@connection = meshblu.createConnection _.cloneDeep(@meshbluOptions)
@connection.on 'message', @onMessage
@connection.on 'notReady', @onNotReady
@connection.on 'ready', @onReady
@processQueue()
onMessage: (message) =>
debug 'onMessage', message.topic
@queue.push message
@processQueue()
onNotReady: (data) =>
console.error "Failed to authenticate", data
onReady: =>
@emit 'ready'
processQueue: =>
debug 'processQueue'
return if @processingQueue || !@queue.length
@processingQueue = true
message = @queue.pop()
gatebluUpdateFunction = @processFunctions[message.topic]
unless gatebluUpdateFunction?
console.error('unknown message topic', message)
@connection.message devices: message.fromUuid, topic: 'atomizer-error', error: 'unknown message topic', originalMessage: message
@processingQueue = false
_.defer @processQueue
return
gatebluUpdateFunction message.payload, (error) =>
debug 'gatebluUpdateFunction complete', error
if error?
console.error 'error updating gateblu', error
@connection.message devices: message.fromUuid, topic: 'atomizer-error', error: error, originalMessage: message
@processingQueue = false
_.defer @processQueue
addDevice: (device, callback=->) =>
debug 'addDevice', device.uuid
@removeDevice device, (error, body) =>
@getGateblu (error, gateblu) =>
debug 'gotGateblu', error, gateblu
return callback(error) if error?
gateblu.devices = null if _.isEmpty(gateblu.devices)
gateblu.devices ?= []
gateblu.devices = _.reject(gateblu.devices, uuid: device.uuid)
debug 'devices', gateblu.devices
gateblu.devices.push {uuid: device.uuid, token: device.token, connector: 'flow-runner'}
@saveGateblu gateblu, callback
removeDevice: (device, callback=->) =>
debug 'removeDevice', device
@getGateblu (error, gateblu) =>
gateblu.devices = _.reject gateblu.devices, uuid: device.uuid
@saveGateblu gateblu, callback
getGateblu: (callback=->) =>
options = @getGatebluRequestOptions()
options.method = 'GET'
request options, (error, response, body) =>
gateblu = _.omit _.first(body.devices), '_id'
_.defer callback, error, gateblu
saveGateblu: (gateblu, callback=->) =>
options = @getGatebluRequestOptions()
options.method = 'PUT'
options.json = gateblu
debug 'saveGateblu', JSON.stringify(options)
request options, (error, response, body) =>
debug 'put complete', error, response.statusCode, body
callback error, body
# @connection.update gateblu, (data) =>
# debug '@connection.update', data.error
# return callback(data) if data.error?
# callback()
getGatebluRequestOptions: =>
{
json: true
headers:
meshblu_auth_uuid: @target.uuid
meshblu_auth_token: @target.token
uri: url.format(
protocol: if @meshbluOptions.port == 443 then 'https' else 'http'
hostname: @meshbluOptions.server
port: @meshbluOptions.port
pathname: "/devices/#{@target.uuid}"
)
}
module.exports = GatebluAtomizer
| 207533 | _ = require 'lodash'
meshblu = require 'meshblu'
request = require 'request'
url = require 'url'
debug = require('debug')('gateblu-atomizer')
{EventEmitter} = require 'events'
class GatebluAtomizer extends EventEmitter
constructor: (config={}) ->
@meshbluOptions = _.pick config, 'uuid', 'token', 'server', 'port'
@target = {uuid: config.targetUuid, token: config.targetToken}
@queue = []
@processFunctions =
'add-device': @addDevice
'remove-device': @removeDevice
'nodered-instance-start': @addDevice
'nodered-instance-stop': @removeDevice
'create': @addDevice
'delete': @removeDevice
run: =>
@connection = meshblu.createConnection _.cloneDeep(@meshbluOptions)
@connection.on 'message', @onMessage
@connection.on 'notReady', @onNotReady
@connection.on 'ready', @onReady
@processQueue()
onMessage: (message) =>
debug 'onMessage', message.topic
@queue.push message
@processQueue()
onNotReady: (data) =>
console.error "Failed to authenticate", data
onReady: =>
@emit 'ready'
processQueue: =>
debug 'processQueue'
return if @processingQueue || !@queue.length
@processingQueue = true
message = @queue.pop()
gatebluUpdateFunction = @processFunctions[message.topic]
unless gatebluUpdateFunction?
console.error('unknown message topic', message)
@connection.message devices: message.fromUuid, topic: 'atomizer-error', error: 'unknown message topic', originalMessage: message
@processingQueue = false
_.defer @processQueue
return
gatebluUpdateFunction message.payload, (error) =>
debug 'gatebluUpdateFunction complete', error
if error?
console.error 'error updating gateblu', error
@connection.message devices: message.fromUuid, topic: 'atomizer-error', error: error, originalMessage: message
@processingQueue = false
_.defer @processQueue
addDevice: (device, callback=->) =>
debug 'addDevice', device.uuid
@removeDevice device, (error, body) =>
@getGateblu (error, gateblu) =>
debug 'gotGateblu', error, gateblu
return callback(error) if error?
gateblu.devices = null if _.isEmpty(gateblu.devices)
gateblu.devices ?= []
gateblu.devices = _.reject(gateblu.devices, uuid: device.uuid)
debug 'devices', gateblu.devices
gateblu.devices.push {uuid: device.uuid, token: <PASSWORD>.token, connector: 'flow-runner'}
@saveGateblu gateblu, callback
removeDevice: (device, callback=->) =>
debug 'removeDevice', device
@getGateblu (error, gateblu) =>
gateblu.devices = _.reject gateblu.devices, uuid: device.uuid
@saveGateblu gateblu, callback
getGateblu: (callback=->) =>
options = @getGatebluRequestOptions()
options.method = 'GET'
request options, (error, response, body) =>
gateblu = _.omit _.first(body.devices), '_id'
_.defer callback, error, gateblu
saveGateblu: (gateblu, callback=->) =>
options = @getGatebluRequestOptions()
options.method = 'PUT'
options.json = gateblu
debug 'saveGateblu', JSON.stringify(options)
request options, (error, response, body) =>
debug 'put complete', error, response.statusCode, body
callback error, body
# @connection.update gateblu, (data) =>
# debug '@connection.update', data.error
# return callback(data) if data.error?
# callback()
getGatebluRequestOptions: =>
{
json: true
headers:
meshblu_auth_uuid: @target.uuid
meshblu_auth_token: @target.token
uri: url.format(
protocol: if @meshbluOptions.port == 443 then 'https' else 'http'
hostname: @meshbluOptions.server
port: @meshbluOptions.port
pathname: "/devices/#{@target.uuid}"
)
}
module.exports = GatebluAtomizer
| true | _ = require 'lodash'
meshblu = require 'meshblu'
request = require 'request'
url = require 'url'
debug = require('debug')('gateblu-atomizer')
{EventEmitter} = require 'events'
class GatebluAtomizer extends EventEmitter
constructor: (config={}) ->
@meshbluOptions = _.pick config, 'uuid', 'token', 'server', 'port'
@target = {uuid: config.targetUuid, token: config.targetToken}
@queue = []
@processFunctions =
'add-device': @addDevice
'remove-device': @removeDevice
'nodered-instance-start': @addDevice
'nodered-instance-stop': @removeDevice
'create': @addDevice
'delete': @removeDevice
run: =>
@connection = meshblu.createConnection _.cloneDeep(@meshbluOptions)
@connection.on 'message', @onMessage
@connection.on 'notReady', @onNotReady
@connection.on 'ready', @onReady
@processQueue()
onMessage: (message) =>
debug 'onMessage', message.topic
@queue.push message
@processQueue()
onNotReady: (data) =>
console.error "Failed to authenticate", data
onReady: =>
@emit 'ready'
processQueue: =>
debug 'processQueue'
return if @processingQueue || !@queue.length
@processingQueue = true
message = @queue.pop()
gatebluUpdateFunction = @processFunctions[message.topic]
unless gatebluUpdateFunction?
console.error('unknown message topic', message)
@connection.message devices: message.fromUuid, topic: 'atomizer-error', error: 'unknown message topic', originalMessage: message
@processingQueue = false
_.defer @processQueue
return
gatebluUpdateFunction message.payload, (error) =>
debug 'gatebluUpdateFunction complete', error
if error?
console.error 'error updating gateblu', error
@connection.message devices: message.fromUuid, topic: 'atomizer-error', error: error, originalMessage: message
@processingQueue = false
_.defer @processQueue
addDevice: (device, callback=->) =>
debug 'addDevice', device.uuid
@removeDevice device, (error, body) =>
@getGateblu (error, gateblu) =>
debug 'gotGateblu', error, gateblu
return callback(error) if error?
gateblu.devices = null if _.isEmpty(gateblu.devices)
gateblu.devices ?= []
gateblu.devices = _.reject(gateblu.devices, uuid: device.uuid)
debug 'devices', gateblu.devices
gateblu.devices.push {uuid: device.uuid, token: PI:PASSWORD:<PASSWORD>END_PI.token, connector: 'flow-runner'}
@saveGateblu gateblu, callback
removeDevice: (device, callback=->) =>
debug 'removeDevice', device
@getGateblu (error, gateblu) =>
gateblu.devices = _.reject gateblu.devices, uuid: device.uuid
@saveGateblu gateblu, callback
getGateblu: (callback=->) =>
options = @getGatebluRequestOptions()
options.method = 'GET'
request options, (error, response, body) =>
gateblu = _.omit _.first(body.devices), '_id'
_.defer callback, error, gateblu
saveGateblu: (gateblu, callback=->) =>
options = @getGatebluRequestOptions()
options.method = 'PUT'
options.json = gateblu
debug 'saveGateblu', JSON.stringify(options)
request options, (error, response, body) =>
debug 'put complete', error, response.statusCode, body
callback error, body
# @connection.update gateblu, (data) =>
# debug '@connection.update', data.error
# return callback(data) if data.error?
# callback()
getGatebluRequestOptions: =>
{
json: true
headers:
meshblu_auth_uuid: @target.uuid
meshblu_auth_token: @target.token
uri: url.format(
protocol: if @meshbluOptions.port == 443 then 'https' else 'http'
hostname: @meshbluOptions.server
port: @meshbluOptions.port
pathname: "/devices/#{@target.uuid}"
)
}
module.exports = GatebluAtomizer
|
[
{
"context": "###\nCopyright 2014 Michael Krolikowski\n\nLicensed under the Apache License, Version 2.0 (",
"end": 38,
"score": 0.998443603515625,
"start": 19,
"tag": "NAME",
"value": "Michael Krolikowski"
}
] | src/main/javascript/shurl.coffee | mkroli/shurl | 1 | ###
Copyright 2014 Michael Krolikowski
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.
###
shurl = angular.module "shurl", ["ngRoute", "ngResource"]
shurl.config ["$routeProvider", "$locationProvider", ($routeProvider, $locationProvider) ->
$locationProvider.html5Mode(true)
$routeProvider
.when "/stats/:id",
templateUrl : "stats.html"
controller : "StatsController"
.otherwise
templateUrl : "main.html"
controller : "MainController"
]
shurl.factory "shurlBackend", ["$resource", ($resource) ->
$resource "/api/:visits/:id", null,
"shorten":
"method" : "PUT"
"headers" :
"Content-Type" : "text/plain"
"visits":
"params":
"visits" : "visits"
]
| 104792 | ###
Copyright 2014 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
shurl = angular.module "shurl", ["ngRoute", "ngResource"]
shurl.config ["$routeProvider", "$locationProvider", ($routeProvider, $locationProvider) ->
$locationProvider.html5Mode(true)
$routeProvider
.when "/stats/:id",
templateUrl : "stats.html"
controller : "StatsController"
.otherwise
templateUrl : "main.html"
controller : "MainController"
]
shurl.factory "shurlBackend", ["$resource", ($resource) ->
$resource "/api/:visits/:id", null,
"shorten":
"method" : "PUT"
"headers" :
"Content-Type" : "text/plain"
"visits":
"params":
"visits" : "visits"
]
| true | ###
Copyright 2014 PI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
shurl = angular.module "shurl", ["ngRoute", "ngResource"]
shurl.config ["$routeProvider", "$locationProvider", ($routeProvider, $locationProvider) ->
$locationProvider.html5Mode(true)
$routeProvider
.when "/stats/:id",
templateUrl : "stats.html"
controller : "StatsController"
.otherwise
templateUrl : "main.html"
controller : "MainController"
]
shurl.factory "shurlBackend", ["$resource", ($resource) ->
$resource "/api/:visits/:id", null,
"shorten":
"method" : "PUT"
"headers" :
"Content-Type" : "text/plain"
"visits":
"params":
"visits" : "visits"
]
|
[
{
"context": "###*\n@ngdoc ygHideOn\n@name ygHideOn\n@author\n Yusuke Goto <my.important.apes@gmail.com>\n@description\n hide",
"end": 57,
"score": 0.9998527765274048,
"start": 46,
"tag": "NAME",
"value": "Yusuke Goto"
},
{
"context": "oc ygHideOn\n@name ygHideOn\n@author\n Yusuke... | src/directives/hideOn.coffee | ygoto3/yg-events-on | 0 | ###*
@ngdoc ygHideOn
@name ygHideOn
@author
Yusuke Goto <my.important.apes@gmail.com>
@description
hides when it catches a given event
###
_dirName = 'ygHideOn'
_exports = {}
_exports[_dirName] = [
->
restrict: "A"
link: (iScope, iElem, iAttrs) ->
_val = iAttrs[_dirName]
iScope.$on _val, ->
iElem.addClass 'ng-hide'
return
return
]
module.exports = _exports
| 164318 | ###*
@ngdoc ygHideOn
@name ygHideOn
@author
<NAME> <<EMAIL>>
@description
hides when it catches a given event
###
_dirName = 'ygHideOn'
_exports = {}
_exports[_dirName] = [
->
restrict: "A"
link: (iScope, iElem, iAttrs) ->
_val = iAttrs[_dirName]
iScope.$on _val, ->
iElem.addClass 'ng-hide'
return
return
]
module.exports = _exports
| true | ###*
@ngdoc ygHideOn
@name ygHideOn
@author
PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@description
hides when it catches a given event
###
_dirName = 'ygHideOn'
_exports = {}
_exports[_dirName] = [
->
restrict: "A"
link: (iScope, iElem, iAttrs) ->
_val = iAttrs[_dirName]
iScope.$on _val, ->
iElem.addClass 'ng-hide'
return
return
]
module.exports = _exports
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998520612716675,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | src/geometry/shape.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
###
{Node} = require '../core/node'
{RGB,RGBA} = require '../colour/colour'
{Vec2, Vec3, PI, degToRad} = require '../math/math'
{Vertex, Triangle, Quad, Geometry} = require './primitive'
# ## Cuboid
# A basic Cuboid with indices
class Cuboid extends Geometry
# TODO - Add resolution here?
# TODO - Add tangents here too?
# **constructor**
# - **dim** - a Vec3 - Default Vec3(1,1,1)
# - **colour** - a Colour
constructor: (dim, colour) ->
super()
@indexed = true
if not dim?
dim = new Vec3 1.0,1.0,1.0
w = dim.x / 2
h = dim.y / 2
d = dim.z / 2
# front
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : Vec3.normalize new Vec3 -w,-h,d
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : Vec3.normalize new Vec3 w,-h,d
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : Vec3.normalize new Vec3 w,h,d
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : Vec3.normalize new Vec3 -w,h,d
t : new Vec2 0,1
# back
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : Vec3.normalize new Vec3 -w,-h,-d
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : Vec3.normalize new Vec3 w,-h,-d
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : Vec3.normalize new Vec3 w,h,-d
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : Vec3.normalize new Vec3 -w,h,-d
t : new Vec2 0,1
if colour?
for v in @vertices
v.c = colour
@indices = [0,1,2,0,2,3,6,5,4,6,4,7,4,0,3,4,3,7,1,5,2,5,6,2,3,2,6,3,6,7,4,5,1,4,1,0]
for i in [0..@indices.length-1] by 3
@faces.push new Triangle(@vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]])
# ## CuboidDup
# A basic Cuboid with no with no interpolated normals. Each corner has duplicated faces for normals
class CuboidDup extends Geometry
# TODO - Add resolution here?
# TODO - Add tangents here too?
# **constructor**
# - **dim** - a Vec3 - Default Vec3(1,1,1)
# - **colour** - a Colour
constructor: (dim, colour) ->
super()
@indexed = true
@layout = GL.TRIANGLES if GL?
if not dim?
dim = new Vec3 1.0,1.0,1.0
w = dim.x / 2
h = dim.y / 2
d = dim.z / 2
# front
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 0,0,1
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 0,0,1
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 0,0,1
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 0,0,1
t : new Vec2 0,1
# back
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 0,0,-1
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 0,0,-1
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 0,0,-1
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 0,0,-1
t : new Vec2 0,1
# left
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 -1,0,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 -1,0,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 -1,0,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 -1,0,0
t : new Vec2 0,1
# right
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 1,0,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 1,0,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 1,0,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 1,0,0
t : new Vec2 0,1
# top
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 0,1,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 0,1,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 0,1,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 0,1,0
t : new Vec2 0,1
# bottom
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 0,-1,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 0,-1,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 0,-1,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 0,-1,0
t : new Vec2 0,1
if colour?
for v in @vertices
v.c = colour
@indices = [0,1,2,0,2,3,6,5,4,7,6,4,8,9,10,8,10,11,14,13,12,15,14,12,16,17,18,16,18,19,22,21,20,23,22,20 ]
for i in [0..@indices.length-1] by 3
@faces.push new Triangle(@vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]])
# ## Sphere
# http://local.wasp.uwa.edu.au/~pbourke/texture_colour/spheremap/ Paul Bourke's sphere code
# We should weigh an alternative that reduces the batch count by using GL_TRIANGLES instead
# TODO - Add Tangents?
# TODO - not convinced this generation is correct
class Sphere extends Geometry
# **@constructor**
# - **radius** - a Number - Default 1.0
# - **segments** - a Number - Default 10
# - **colour** - a Colour
constructor: (radius, segments, colour) ->
super()
gl = PXL.Context.gl # Global / Current context
@layout = gl.TRIANGLE_STRIP
if radius?
if radius < 0
radius = 1.0
else
radius - 1.0
if segments?
if segments < 0
segments = 10
else
segments = 10
for j in [0..segments/2]
theta1 = j * 2 * PI / segments - (PI / 2)
theta2 = (j + 1) * 2 * PI / segments - (PI / 2)
for i in [0..segments+1]
e0 = new Vec3()
theta3 = i * 2 * PI / segments
e0.x = Math.cos(theta1) * Math.cos(theta3)
e0.y = Math.sin(theta1)
e0.z = Math.cos(theta1) * Math.sin(theta3)
p0 = Vec3.multScalar(e0,radius)
c0 = new RGBA(1.0,1.0,1.0,1.0)
t0 = new Vec2( 0.999 - i / segments, 0.999 - 2 * j / segments)
v = new Vertex
p : p0
t : t0
n : e0
@vertices.push v
e1 = new Vec3()
e1.x = Math.cos(theta2) * Math.cos(theta3)
e1.y = Math.sin(theta2)
e1.z = Math.cos(theta2) * Math.sin(theta3)
p1 = Vec3.multScalar(e1,radius)
t1 = new Vec2( 0.999 - i / segments, 0.999 - 2 * (j+1) / segments)
v = new Vertex
p : p1
n : e1
t : t1
@vertices.push v
for i in [2..@vertices.length-1] by 1
if i % 2 == 0
@faces.push new Triangle(@vertices[i], @vertices[i-1], @vertices[i-2])
else
@faces.push new Triangle(@vertices[i], @vertices[i-2], @vertices[i-1])
if colour?
for v in @vertices
v.c = colour
# ## Cylinder
# A basic cylinder
class Cylinder extends Geometry
# **@constructor**
# - **radius** - a Number - Default 0.5
# - **resolution** - a Number - Default 10
# - **height** - a Number - Default 1.0
# - **colour** - a Colour
constructor: (radius, resolution, segments, height, colour) ->
super()
@indices = []
@indexed = true
# TODO - This could be neater
if radius?
if radius < 0
radius = 0.5
else
radius = 0.5
if resolution?
if resolution < 0
resolution = 10.0
else
resolution = 10.0
if segments?
if segments < 0
segments = 10
else
segments = 10
if height?
if height < 0
height = 1.0
else
height = 1.0
hstep = height / segments
height = height / 2.0
# top
@vertices.push new Vertex
p : new Vec3(0,height,0)
n : new Vec3(0,1.0,0.0)
t : new Vec2(0.5,0.0)
a : new Vec2(0,0,0) # cx this - hairy coconut
for i in [1..resolution]
x = radius * Math.sin degToRad(360.0 / resolution * i)
z = radius * Math.cos degToRad(360.0 / resolution * i)
tangent = new Vec3(x,0,z)
tangent.normalize()
tangent.cross new Vec3(0,1,0)
@vertices.push new Vertex
p : new Vec3(x,height,z)
n : Vec3.normalize(new Vec3(x,1.0,z))
t : new Vec2(i/resolution, 0.0)
a : tangent
# top cap
for i in [1..resolution]
@indices.push 0
@indices.push i
if i == resolution
@indices.push 1
else
@indices.push (i+1)
for i in [1..segments]
# next end
for j in [1..resolution]
x = radius * Math.sin degToRad(360.0 / resolution * j)
z = radius * Math.cos degToRad(360.0 / resolution * j)
tangent = new Vec3(x,0,z)
tangent.normalize()
tangent.cross new Vec3(0,-1,0)
n0 = Vec3.normalize(new Vec3(x,0,z))
if i == segments
n0 = Vec3.normalize(new Vec3(x,-1,z))
@vertices.push new Vertex
p : new Vec3(x, height - (hstep * i) ,z)
n : n0
t : new Vec2(j/resolution, i/segments )
a : tangent
#sides1
s = (i - 1) * resolution + 1
e = s + resolution
for j in [0..resolution-1]
@indices.push (s + j)
@indices.push (e + j)
if j == (resolution-1)
@indices.push (e)
else
@indices.push (e + j + 1)
for j in [0..resolution-1]
@indices.push (s+j)
if j == (resolution-1)
@indices.push (e)
@indices.push (s)
else
@indices.push (e+j+1)
@indices.push (s+j+1)
# Very last point for bottom cap
@vertices.push new Vertex
p : new Vec3(0,-height,0)
n : new Vec3(0,-1.0,0.0)
t : new Vec2(0.5,1.0)
a : new Vec3(0,0,0)
# bottom cap
s = (segments * resolution) + 2
e = s + resolution - 1
for i in [s..e]
@indices.push (s - 1)
if i == e
@indices.push s
else
@indices.push (i+1)
@indices.push i
for i in [0..@indices.length-1] by 3
@faces.push new Triangle @vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]]
# Add colour - convert to RGBA here as that is what we expect in the shader
# Potentially this is bad but attributes are what they are and this is cheaper
if colour?
if not colour.a?
colour = new RGBA(colour.r,colour.g,colour.b,1.0)
for v in @vertices
v.c = colour
@
module.exports =
Cuboid: Cuboid
Sphere: Sphere
CuboidDup: CuboidDup
Cylinder : Cylinder
| 132672 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Node} = require '../core/node'
{RGB,RGBA} = require '../colour/colour'
{Vec2, Vec3, PI, degToRad} = require '../math/math'
{Vertex, Triangle, Quad, Geometry} = require './primitive'
# ## Cuboid
# A basic Cuboid with indices
class Cuboid extends Geometry
# TODO - Add resolution here?
# TODO - Add tangents here too?
# **constructor**
# - **dim** - a Vec3 - Default Vec3(1,1,1)
# - **colour** - a Colour
constructor: (dim, colour) ->
super()
@indexed = true
if not dim?
dim = new Vec3 1.0,1.0,1.0
w = dim.x / 2
h = dim.y / 2
d = dim.z / 2
# front
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : Vec3.normalize new Vec3 -w,-h,d
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : Vec3.normalize new Vec3 w,-h,d
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : Vec3.normalize new Vec3 w,h,d
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : Vec3.normalize new Vec3 -w,h,d
t : new Vec2 0,1
# back
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : Vec3.normalize new Vec3 -w,-h,-d
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : Vec3.normalize new Vec3 w,-h,-d
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : Vec3.normalize new Vec3 w,h,-d
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : Vec3.normalize new Vec3 -w,h,-d
t : new Vec2 0,1
if colour?
for v in @vertices
v.c = colour
@indices = [0,1,2,0,2,3,6,5,4,6,4,7,4,0,3,4,3,7,1,5,2,5,6,2,3,2,6,3,6,7,4,5,1,4,1,0]
for i in [0..@indices.length-1] by 3
@faces.push new Triangle(@vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]])
# ## CuboidDup
# A basic Cuboid with no with no interpolated normals. Each corner has duplicated faces for normals
class CuboidDup extends Geometry
# TODO - Add resolution here?
# TODO - Add tangents here too?
# **constructor**
# - **dim** - a Vec3 - Default Vec3(1,1,1)
# - **colour** - a Colour
constructor: (dim, colour) ->
super()
@indexed = true
@layout = GL.TRIANGLES if GL?
if not dim?
dim = new Vec3 1.0,1.0,1.0
w = dim.x / 2
h = dim.y / 2
d = dim.z / 2
# front
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 0,0,1
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 0,0,1
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 0,0,1
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 0,0,1
t : new Vec2 0,1
# back
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 0,0,-1
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 0,0,-1
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 0,0,-1
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 0,0,-1
t : new Vec2 0,1
# left
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 -1,0,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 -1,0,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 -1,0,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 -1,0,0
t : new Vec2 0,1
# right
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 1,0,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 1,0,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 1,0,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 1,0,0
t : new Vec2 0,1
# top
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 0,1,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 0,1,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 0,1,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 0,1,0
t : new Vec2 0,1
# bottom
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 0,-1,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 0,-1,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 0,-1,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 0,-1,0
t : new Vec2 0,1
if colour?
for v in @vertices
v.c = colour
@indices = [0,1,2,0,2,3,6,5,4,7,6,4,8,9,10,8,10,11,14,13,12,15,14,12,16,17,18,16,18,19,22,21,20,23,22,20 ]
for i in [0..@indices.length-1] by 3
@faces.push new Triangle(@vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]])
# ## Sphere
# http://local.wasp.uwa.edu.au/~pbourke/texture_colour/spheremap/ <NAME> Bourke's sphere code
# We should weigh an alternative that reduces the batch count by using GL_TRIANGLES instead
# TODO - Add Tangents?
# TODO - not convinced this generation is correct
class Sphere extends Geometry
# **@constructor**
# - **radius** - a Number - Default 1.0
# - **segments** - a Number - Default 10
# - **colour** - a Colour
constructor: (radius, segments, colour) ->
super()
gl = PXL.Context.gl # Global / Current context
@layout = gl.TRIANGLE_STRIP
if radius?
if radius < 0
radius = 1.0
else
radius - 1.0
if segments?
if segments < 0
segments = 10
else
segments = 10
for j in [0..segments/2]
theta1 = j * 2 * PI / segments - (PI / 2)
theta2 = (j + 1) * 2 * PI / segments - (PI / 2)
for i in [0..segments+1]
e0 = new Vec3()
theta3 = i * 2 * PI / segments
e0.x = Math.cos(theta1) * Math.cos(theta3)
e0.y = Math.sin(theta1)
e0.z = Math.cos(theta1) * Math.sin(theta3)
p0 = Vec3.multScalar(e0,radius)
c0 = new RGBA(1.0,1.0,1.0,1.0)
t0 = new Vec2( 0.999 - i / segments, 0.999 - 2 * j / segments)
v = new Vertex
p : p0
t : t0
n : e0
@vertices.push v
e1 = new Vec3()
e1.x = Math.cos(theta2) * Math.cos(theta3)
e1.y = Math.sin(theta2)
e1.z = Math.cos(theta2) * Math.sin(theta3)
p1 = Vec3.multScalar(e1,radius)
t1 = new Vec2( 0.999 - i / segments, 0.999 - 2 * (j+1) / segments)
v = new Vertex
p : p1
n : e1
t : t1
@vertices.push v
for i in [2..@vertices.length-1] by 1
if i % 2 == 0
@faces.push new Triangle(@vertices[i], @vertices[i-1], @vertices[i-2])
else
@faces.push new Triangle(@vertices[i], @vertices[i-2], @vertices[i-1])
if colour?
for v in @vertices
v.c = colour
# ## Cylinder
# A basic cylinder
class Cylinder extends Geometry
# **@constructor**
# - **radius** - a Number - Default 0.5
# - **resolution** - a Number - Default 10
# - **height** - a Number - Default 1.0
# - **colour** - a Colour
constructor: (radius, resolution, segments, height, colour) ->
super()
@indices = []
@indexed = true
# TODO - This could be neater
if radius?
if radius < 0
radius = 0.5
else
radius = 0.5
if resolution?
if resolution < 0
resolution = 10.0
else
resolution = 10.0
if segments?
if segments < 0
segments = 10
else
segments = 10
if height?
if height < 0
height = 1.0
else
height = 1.0
hstep = height / segments
height = height / 2.0
# top
@vertices.push new Vertex
p : new Vec3(0,height,0)
n : new Vec3(0,1.0,0.0)
t : new Vec2(0.5,0.0)
a : new Vec2(0,0,0) # cx this - hairy coconut
for i in [1..resolution]
x = radius * Math.sin degToRad(360.0 / resolution * i)
z = radius * Math.cos degToRad(360.0 / resolution * i)
tangent = new Vec3(x,0,z)
tangent.normalize()
tangent.cross new Vec3(0,1,0)
@vertices.push new Vertex
p : new Vec3(x,height,z)
n : Vec3.normalize(new Vec3(x,1.0,z))
t : new Vec2(i/resolution, 0.0)
a : tangent
# top cap
for i in [1..resolution]
@indices.push 0
@indices.push i
if i == resolution
@indices.push 1
else
@indices.push (i+1)
for i in [1..segments]
# next end
for j in [1..resolution]
x = radius * Math.sin degToRad(360.0 / resolution * j)
z = radius * Math.cos degToRad(360.0 / resolution * j)
tangent = new Vec3(x,0,z)
tangent.normalize()
tangent.cross new Vec3(0,-1,0)
n0 = Vec3.normalize(new Vec3(x,0,z))
if i == segments
n0 = Vec3.normalize(new Vec3(x,-1,z))
@vertices.push new Vertex
p : new Vec3(x, height - (hstep * i) ,z)
n : n0
t : new Vec2(j/resolution, i/segments )
a : tangent
#sides1
s = (i - 1) * resolution + 1
e = s + resolution
for j in [0..resolution-1]
@indices.push (s + j)
@indices.push (e + j)
if j == (resolution-1)
@indices.push (e)
else
@indices.push (e + j + 1)
for j in [0..resolution-1]
@indices.push (s+j)
if j == (resolution-1)
@indices.push (e)
@indices.push (s)
else
@indices.push (e+j+1)
@indices.push (s+j+1)
# Very last point for bottom cap
@vertices.push new Vertex
p : new Vec3(0,-height,0)
n : new Vec3(0,-1.0,0.0)
t : new Vec2(0.5,1.0)
a : new Vec3(0,0,0)
# bottom cap
s = (segments * resolution) + 2
e = s + resolution - 1
for i in [s..e]
@indices.push (s - 1)
if i == e
@indices.push s
else
@indices.push (i+1)
@indices.push i
for i in [0..@indices.length-1] by 3
@faces.push new Triangle @vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]]
# Add colour - convert to RGBA here as that is what we expect in the shader
# Potentially this is bad but attributes are what they are and this is cheaper
if colour?
if not colour.a?
colour = new RGBA(colour.r,colour.g,colour.b,1.0)
for v in @vertices
v.c = colour
@
module.exports =
Cuboid: Cuboid
Sphere: Sphere
CuboidDup: CuboidDup
Cylinder : Cylinder
| 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
###
{Node} = require '../core/node'
{RGB,RGBA} = require '../colour/colour'
{Vec2, Vec3, PI, degToRad} = require '../math/math'
{Vertex, Triangle, Quad, Geometry} = require './primitive'
# ## Cuboid
# A basic Cuboid with indices
class Cuboid extends Geometry
# TODO - Add resolution here?
# TODO - Add tangents here too?
# **constructor**
# - **dim** - a Vec3 - Default Vec3(1,1,1)
# - **colour** - a Colour
constructor: (dim, colour) ->
super()
@indexed = true
if not dim?
dim = new Vec3 1.0,1.0,1.0
w = dim.x / 2
h = dim.y / 2
d = dim.z / 2
# front
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : Vec3.normalize new Vec3 -w,-h,d
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : Vec3.normalize new Vec3 w,-h,d
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : Vec3.normalize new Vec3 w,h,d
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : Vec3.normalize new Vec3 -w,h,d
t : new Vec2 0,1
# back
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : Vec3.normalize new Vec3 -w,-h,-d
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : Vec3.normalize new Vec3 w,-h,-d
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : Vec3.normalize new Vec3 w,h,-d
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : Vec3.normalize new Vec3 -w,h,-d
t : new Vec2 0,1
if colour?
for v in @vertices
v.c = colour
@indices = [0,1,2,0,2,3,6,5,4,6,4,7,4,0,3,4,3,7,1,5,2,5,6,2,3,2,6,3,6,7,4,5,1,4,1,0]
for i in [0..@indices.length-1] by 3
@faces.push new Triangle(@vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]])
# ## CuboidDup
# A basic Cuboid with no with no interpolated normals. Each corner has duplicated faces for normals
class CuboidDup extends Geometry
# TODO - Add resolution here?
# TODO - Add tangents here too?
# **constructor**
# - **dim** - a Vec3 - Default Vec3(1,1,1)
# - **colour** - a Colour
constructor: (dim, colour) ->
super()
@indexed = true
@layout = GL.TRIANGLES if GL?
if not dim?
dim = new Vec3 1.0,1.0,1.0
w = dim.x / 2
h = dim.y / 2
d = dim.z / 2
# front
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 0,0,1
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 0,0,1
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 0,0,1
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 0,0,1
t : new Vec2 0,1
# back
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 0,0,-1
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 0,0,-1
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 0,0,-1
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 0,0,-1
t : new Vec2 0,1
# left
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 -1,0,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 -1,0,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 -1,0,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 -1,0,0
t : new Vec2 0,1
# right
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 1,0,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 1,0,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 1,0,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 1,0,0
t : new Vec2 0,1
# top
@vertices.push new Vertex
p : new Vec3 -w,h,-d
n : new Vec3 0,1,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,h,d
n : new Vec3 0,1,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,h,d
n : new Vec3 0,1,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,h,-d
n : new Vec3 0,1,0
t : new Vec2 0,1
# bottom
@vertices.push new Vertex
p : new Vec3 -w,-h,-d
n : new Vec3 0,-1,0
t : new Vec2 0,0
@vertices.push new Vertex
p : new Vec3 -w,-h,d
n : new Vec3 0,-1,0
t : new Vec2 1,0
@vertices.push new Vertex
p : new Vec3 w,-h,d
n : new Vec3 0,-1,0
t : new Vec2 1,1
@vertices.push new Vertex
p : new Vec3 w,-h,-d
n : new Vec3 0,-1,0
t : new Vec2 0,1
if colour?
for v in @vertices
v.c = colour
@indices = [0,1,2,0,2,3,6,5,4,7,6,4,8,9,10,8,10,11,14,13,12,15,14,12,16,17,18,16,18,19,22,21,20,23,22,20 ]
for i in [0..@indices.length-1] by 3
@faces.push new Triangle(@vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]])
# ## Sphere
# http://local.wasp.uwa.edu.au/~pbourke/texture_colour/spheremap/ PI:NAME:<NAME>END_PI Bourke's sphere code
# We should weigh an alternative that reduces the batch count by using GL_TRIANGLES instead
# TODO - Add Tangents?
# TODO - not convinced this generation is correct
class Sphere extends Geometry
# **@constructor**
# - **radius** - a Number - Default 1.0
# - **segments** - a Number - Default 10
# - **colour** - a Colour
constructor: (radius, segments, colour) ->
super()
gl = PXL.Context.gl # Global / Current context
@layout = gl.TRIANGLE_STRIP
if radius?
if radius < 0
radius = 1.0
else
radius - 1.0
if segments?
if segments < 0
segments = 10
else
segments = 10
for j in [0..segments/2]
theta1 = j * 2 * PI / segments - (PI / 2)
theta2 = (j + 1) * 2 * PI / segments - (PI / 2)
for i in [0..segments+1]
e0 = new Vec3()
theta3 = i * 2 * PI / segments
e0.x = Math.cos(theta1) * Math.cos(theta3)
e0.y = Math.sin(theta1)
e0.z = Math.cos(theta1) * Math.sin(theta3)
p0 = Vec3.multScalar(e0,radius)
c0 = new RGBA(1.0,1.0,1.0,1.0)
t0 = new Vec2( 0.999 - i / segments, 0.999 - 2 * j / segments)
v = new Vertex
p : p0
t : t0
n : e0
@vertices.push v
e1 = new Vec3()
e1.x = Math.cos(theta2) * Math.cos(theta3)
e1.y = Math.sin(theta2)
e1.z = Math.cos(theta2) * Math.sin(theta3)
p1 = Vec3.multScalar(e1,radius)
t1 = new Vec2( 0.999 - i / segments, 0.999 - 2 * (j+1) / segments)
v = new Vertex
p : p1
n : e1
t : t1
@vertices.push v
for i in [2..@vertices.length-1] by 1
if i % 2 == 0
@faces.push new Triangle(@vertices[i], @vertices[i-1], @vertices[i-2])
else
@faces.push new Triangle(@vertices[i], @vertices[i-2], @vertices[i-1])
if colour?
for v in @vertices
v.c = colour
# ## Cylinder
# A basic cylinder
class Cylinder extends Geometry
# **@constructor**
# - **radius** - a Number - Default 0.5
# - **resolution** - a Number - Default 10
# - **height** - a Number - Default 1.0
# - **colour** - a Colour
constructor: (radius, resolution, segments, height, colour) ->
super()
@indices = []
@indexed = true
# TODO - This could be neater
if radius?
if radius < 0
radius = 0.5
else
radius = 0.5
if resolution?
if resolution < 0
resolution = 10.0
else
resolution = 10.0
if segments?
if segments < 0
segments = 10
else
segments = 10
if height?
if height < 0
height = 1.0
else
height = 1.0
hstep = height / segments
height = height / 2.0
# top
@vertices.push new Vertex
p : new Vec3(0,height,0)
n : new Vec3(0,1.0,0.0)
t : new Vec2(0.5,0.0)
a : new Vec2(0,0,0) # cx this - hairy coconut
for i in [1..resolution]
x = radius * Math.sin degToRad(360.0 / resolution * i)
z = radius * Math.cos degToRad(360.0 / resolution * i)
tangent = new Vec3(x,0,z)
tangent.normalize()
tangent.cross new Vec3(0,1,0)
@vertices.push new Vertex
p : new Vec3(x,height,z)
n : Vec3.normalize(new Vec3(x,1.0,z))
t : new Vec2(i/resolution, 0.0)
a : tangent
# top cap
for i in [1..resolution]
@indices.push 0
@indices.push i
if i == resolution
@indices.push 1
else
@indices.push (i+1)
for i in [1..segments]
# next end
for j in [1..resolution]
x = radius * Math.sin degToRad(360.0 / resolution * j)
z = radius * Math.cos degToRad(360.0 / resolution * j)
tangent = new Vec3(x,0,z)
tangent.normalize()
tangent.cross new Vec3(0,-1,0)
n0 = Vec3.normalize(new Vec3(x,0,z))
if i == segments
n0 = Vec3.normalize(new Vec3(x,-1,z))
@vertices.push new Vertex
p : new Vec3(x, height - (hstep * i) ,z)
n : n0
t : new Vec2(j/resolution, i/segments )
a : tangent
#sides1
s = (i - 1) * resolution + 1
e = s + resolution
for j in [0..resolution-1]
@indices.push (s + j)
@indices.push (e + j)
if j == (resolution-1)
@indices.push (e)
else
@indices.push (e + j + 1)
for j in [0..resolution-1]
@indices.push (s+j)
if j == (resolution-1)
@indices.push (e)
@indices.push (s)
else
@indices.push (e+j+1)
@indices.push (s+j+1)
# Very last point for bottom cap
@vertices.push new Vertex
p : new Vec3(0,-height,0)
n : new Vec3(0,-1.0,0.0)
t : new Vec2(0.5,1.0)
a : new Vec3(0,0,0)
# bottom cap
s = (segments * resolution) + 2
e = s + resolution - 1
for i in [s..e]
@indices.push (s - 1)
if i == e
@indices.push s
else
@indices.push (i+1)
@indices.push i
for i in [0..@indices.length-1] by 3
@faces.push new Triangle @vertices[@indices[i]], @vertices[@indices[i+1]], @vertices[@indices[i+2]]
# Add colour - convert to RGBA here as that is what we expect in the shader
# Potentially this is bad but attributes are what they are and this is cheaper
if colour?
if not colour.a?
colour = new RGBA(colour.r,colour.g,colour.b,1.0)
for v in @vertices
v.c = colour
@
module.exports =
Cuboid: Cuboid
Sphere: Sphere
CuboidDup: CuboidDup
Cylinder : Cylinder
|
[
{
"context": "= localStorage.key(i)\n\t\tif key?.startsWith(\"Meteor.loginToken\") || key?.startsWith(\"Meteor.userId\") ",
"end": 3614,
"score": 0.5605220794677734,
"start": 3614,
"tag": "KEY",
"value": ""
},
{
"context": "()\n\t\treturn\n\tuserId = Meteor.userId()\n\tauthToken = A... | packages/steedos-base/client/bootstrap.coffee | steedos/creator | 42 | require('url-search-params-polyfill');
clone = require('clone')
getCookie = (name)->
pattern = RegExp(name + "=.[^;]*")
matched = document.cookie.match(pattern)
if(matched)
cookie = matched[0].split('=')
return cookie[1]
return false
@Setup = {}
Blaze._allowJavascriptUrls()
FlowRouter.wait();
Steedos.goResetPassword = (redirect)->
accountsUrl = Meteor.settings.public?.webservices?.accounts?.url
if accountsUrl
if !redirect
redirect = location.href.replace("/steedos/sign-in", "").replace("/steedos/logout", "")
if _.isFunction(Steedos.isCordova) && Steedos.isCordova()
rootUrl = new URL(__meteor_runtime_config__.ROOT_URL)
accountsUrl = rootUrl.origin + accountsUrl
window.location.href = accountsUrl + "/a/#/update-password?redirect_uri=" + redirect;
Steedos.redirectToSignIn = (redirect)->
accountsUrl = Meteor.settings.public?.webservices?.accounts?.url
if accountsUrl
if !redirect
redirect = location.href.replace("/steedos/sign-in", "").replace("/steedos/logout", "")
if _.isFunction(Steedos.isCordova) && Steedos.isCordova()
rootUrl = new URL(__meteor_runtime_config__.ROOT_URL)
accountsUrl = rootUrl.origin + accountsUrl
window.location.href = accountsUrl + "/authorize?redirect_uri=" + redirect;
Setup.validate = (onSuccess)->
# if window.location.pathname.indexOf('/steedos/sign-in')>=0
# if (!FlowRouter._initialized)
# FlowRouter.initialize();
# return;
console.log("Validating user...")
searchParams = new URLSearchParams(window.location.search);
# 优先使用 URL 变量
loginToken = searchParams.get("X-Auth-Token");
userId = searchParams.get("X-User-Id");
# 然后使用 Meteor LocalStorage 变量
if (!userId or !loginToken)
loginToken = Accounts._storedLoginToken()
userId = Accounts._storedUserId();
# 然后使用 Cookie 变量
if (!userId or !loginToken)
loginToken = getCookie("X-Auth-Token");
userId = getCookie("X-User-Id");
spaceId = localStorage.getItem("spaceId")
if (!spaceId)
spaceId = getCookie("X-Space-Id");
headers = {}
requestData = { 'utcOffset': moment().utcOffset() / 60 }
if loginToken && spaceId
headers['Authorization'] = 'Bearer ' + spaceId + ',' + loginToken
else if loginToken
# headers['Authorization'] = 'Bearer ' + loginToken
headers['X-User-Id'] = userId
headers['X-Auth-Token'] = loginToken
$.ajax
type: "POST",
url: Steedos.absoluteUrl("api/v4/users/validate"),
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(requestData),
xhrFields:
withCredentials: true
crossDomain: true
headers: headers
.done ( data ) ->
if Meteor.userId() != data.userId
Accounts.connection.setUserId(data.userId);
Accounts.loginWithToken data.authToken, (err) ->
if (err)
Meteor._debug("Error logging in with token: " + err);
FlowRouter.go "/steedos/logout"
return
if data.webservices
Steedos.settings.webservices = data.webservices
Setup.lastUserId = data.userId
if data.password_expired
Steedos.goResetPassword()
if data.spaceId
Setup.lastSpaceId = data.spaceId
if (data.spaceId != Session.get("spaceId"))
Steedos.setSpaceId(data.spaceId)
Creator.USER_CONTEXT = {
spaceId: data.spaceId,
userId: data.userId,
user: data
}
if !Meteor.loggingIn()
# 第一次在登录界面输入用户名密码登录后loggingIn为true,这时还没有登录成功
Setup.bootstrap(Session.get("spaceId"))
if onSuccess
onSuccess()
.fail ( e ) ->
if (e.status == 401)
Steedos.redirectToSignIn()
return
Setup.clearAuthLocalStorage = ()->
localStorage = window.localStorage;
i = 0
while i < localStorage.length
key = localStorage.key(i)
if key?.startsWith("Meteor.loginToken") || key?.startsWith("Meteor.userId") || key?.startsWith("Meteor.loginTokenExpires") || key?.startsWith('accounts:')
localStorage.removeItem(key)
i++
Setup.logout = (callback) ->
$.ajax
type: "POST",
url: Steedos.absoluteUrl("api/v4/users/logout"),
dataType: 'json',
xhrFields:
withCredentials: true
crossDomain: true,
.always ( data ) ->
Setup.clearAuthLocalStorage()
if callback
callback()
Meteor.startup ->
Setup.validate();
Accounts.onLogin ()->
console.log("onLogin")
if Meteor.userId() != Setup.lastUserId
Setup.validate();
else
Setup.bootstrap(Session.get("spaceId"))
# Tracker.autorun (c)->
# # 登录后需要清除登录前订阅的space数据,以防止默认选中登录前浏览器url参数中的的工作区ID所指向的工作区
# # 而且可能登录后的用户不属性该SpaceAvatar中订阅的工作区,所以需要清除订阅,由之前的订阅来决定当前用户可以选择哪些工作区
# if Steedos.subsSpaceBase.ready()
# c.stop()
# Steedos.subs["SpaceAvatar"]?.clear()
# return
return
Accounts.onLogout ()->
console.log("onLogout")
Setup.logout ()->
Creator.bootstrapLoaded.set(false)
$("body").removeClass('loading')
Setup.lastUserId = null;
Steedos.redirectToSignIn()
Tracker.autorun (c)->
spaceId = Session.get("spaceId");
if Setup.lastSpaceId && (Setup.lastSpaceId != spaceId)
# 一定要在spaceId变化时立即设置bootstrapLoaded为false,而不可以在请求bootstrap之前才设置为false
# 否则有订阅的话,在请求bootsrtrap前,会先触发订阅的变化,订阅又会触发Creator.bootstrapLoaded.get()值的变化,而且是true变为true
# 这样的话在autorun中监听Creator.bootstrapLoaded.get()变化就会多进入一次
Creator.bootstrapLoaded.set(false)
console.log("spaceId change from " + Setup.lastSpaceId + " to " + Session.get("spaceId"))
Setup.validate()
return
if (localStorage.getItem("app_id") && !Session.get("app_id"))
Session.set("app_id", localStorage.getItem("app_id"));
Tracker.autorun (c)->
#console.log("app_id change: " + Session.get("app_id"))
localStorage.setItem("app_id", Session.get("app_id"))
return
return
Creator.bootstrapLoaded = new ReactiveVar(false)
handleBootstrapData = (result, callback)->
Creator._recordSafeObjectCache = []; # 切换工作区时,情况object缓存
Creator.Objects = result.objects;
Creator.baseObject = Creator.Objects.base;
Creator.objectsByName = {};
object_listviews = result.object_listviews
Creator.object_workflows = result.object_workflows
isSpaceAdmin = Steedos.isSpaceAdmin()
Session.set "user_permission_sets", result.user_permission_sets
_.each Creator.Objects, (object, object_name)->
_object_listviews = object_listviews[object_name]
_.each _object_listviews, (_object_listview)->
if _.isString(_object_listview.options)
_object_listview.options = JSON.parse(_object_listview.options)
if _object_listview.api_name
_key = _object_listview.api_name
else
_key = _object_listview._id
if !object.list_views
object.list_views = {}
object.list_views[_key] = _object_listview
Creator.loadObjects object, object_name
Creator.Apps = ReactSteedos.creatorAppsSelector(ReactSteedos.store.getState())
Creator.Menus = result.assigned_menus
if Steedos.isMobile()
mobileApps = _.filter Creator.getVisibleApps(true), (item)->
return item._id !='admin' && !_.isEmpty(item.mobile_objects)
appIds = _.pluck(mobileApps, "_id")
else
appIds = _.pluck(Creator.getVisibleApps(true), "_id")
if (appIds && appIds.length>0)
if (!Session.get("app_id") || appIds.indexOf(Session.get("app_id"))<0)
Session.set("app_id", appIds[0])
Creator.Dashboards = if result.dashboards then result.dashboards else {};
Creator.Plugins = if result.plugins then result.plugins else {};
if _.isFunction(callback)
callback()
Creator.bootstrapLoaded.set(true)
if (!FlowRouter._initialized)
FlowRouter.initialize();
if FlowRouter.current()?.context?.pathname == "/steedos/sign-in"
if FlowRouter.current()?.queryParams?.redirect
document.location.href = FlowRouter.current().queryParams.redirect;
return
else
FlowRouter.go("/")
requestBootstrapDataUseAjax = (spaceId, callback)->
unless spaceId and Meteor.userId()
return
userId = Meteor.userId()
authToken = Accounts._storedLoginToken()
url = Steedos.absoluteUrl "/api/bootstrap/#{spaceId}"
headers = {}
headers['Authorization'] = 'Bearer ' + spaceId + ',' + authToken
headers['X-User-Id'] = userId
headers['X-Auth-Token'] = authToken
$.ajax
type: "get"
url: url
dataType: "json"
headers: headers
error: (jqXHR, textStatus, errorThrown) ->
FlowRouter.initialize();
error = jqXHR.responseJSON
console.error error
if error?.reason
toastr?.error?(TAPi18n.__(error.reason))
else if error?.message
toastr?.error?(TAPi18n.__(error.message))
else
toastr?.error?(error)
success: (result) ->
handleBootstrapData(result, callback);
requestBootstrapDataUseAction = (spaceId)->
SteedosReact = require('@steedos/react');
store.dispatch(SteedosReact.loadBootstrapEntitiesData({spaceId: spaceId}))
requestBootstrapData = (spaceId, callback)->
SteedosReact = require('@steedos/react');
if SteedosReact.store
requestBootstrapDataUseAction(spaceId);
else
requestBootstrapDataUseAjax(spaceId, callback);
Setup.bootstrap = (spaceId, callback)->
requestBootstrapData(spaceId, callback)
FlowRouter.route '/steedos/logout',
action: (params, queryParams)->
#AccountsTemplates.logout();
$("body").addClass('loading')
Meteor.logout ()->
# FlowRouter.go("/steedos/sign-in")
return
Meteor.startup ()->
SteedosReact = require('@steedos/react');
RequestStatusOption = SteedosReact.RequestStatusOption
lastBootStrapRequestStatus = '';
SteedosReact.store?.subscribe ()->
state = SteedosReact.store.getState();
if lastBootStrapRequestStatus == RequestStatusOption.STARTED
lastBootStrapRequestStatus = SteedosReact.getRequestStatus(state); # 由于handleBootstrapData函数执行比较慢,因此在handleBootstrapData执行前,给lastBootStrapRequestStatus更新值
if SteedosReact.isRequestSuccess(state)
handleBootstrapData(clone(SteedosReact.getBootstrapData(state)));
else
lastBootStrapRequestStatus = SteedosReact.getRequestStatus(state); | 180673 | require('url-search-params-polyfill');
clone = require('clone')
getCookie = (name)->
pattern = RegExp(name + "=.[^;]*")
matched = document.cookie.match(pattern)
if(matched)
cookie = matched[0].split('=')
return cookie[1]
return false
@Setup = {}
Blaze._allowJavascriptUrls()
FlowRouter.wait();
Steedos.goResetPassword = (redirect)->
accountsUrl = Meteor.settings.public?.webservices?.accounts?.url
if accountsUrl
if !redirect
redirect = location.href.replace("/steedos/sign-in", "").replace("/steedos/logout", "")
if _.isFunction(Steedos.isCordova) && Steedos.isCordova()
rootUrl = new URL(__meteor_runtime_config__.ROOT_URL)
accountsUrl = rootUrl.origin + accountsUrl
window.location.href = accountsUrl + "/a/#/update-password?redirect_uri=" + redirect;
Steedos.redirectToSignIn = (redirect)->
accountsUrl = Meteor.settings.public?.webservices?.accounts?.url
if accountsUrl
if !redirect
redirect = location.href.replace("/steedos/sign-in", "").replace("/steedos/logout", "")
if _.isFunction(Steedos.isCordova) && Steedos.isCordova()
rootUrl = new URL(__meteor_runtime_config__.ROOT_URL)
accountsUrl = rootUrl.origin + accountsUrl
window.location.href = accountsUrl + "/authorize?redirect_uri=" + redirect;
Setup.validate = (onSuccess)->
# if window.location.pathname.indexOf('/steedos/sign-in')>=0
# if (!FlowRouter._initialized)
# FlowRouter.initialize();
# return;
console.log("Validating user...")
searchParams = new URLSearchParams(window.location.search);
# 优先使用 URL 变量
loginToken = searchParams.get("X-Auth-Token");
userId = searchParams.get("X-User-Id");
# 然后使用 Meteor LocalStorage 变量
if (!userId or !loginToken)
loginToken = Accounts._storedLoginToken()
userId = Accounts._storedUserId();
# 然后使用 Cookie 变量
if (!userId or !loginToken)
loginToken = getCookie("X-Auth-Token");
userId = getCookie("X-User-Id");
spaceId = localStorage.getItem("spaceId")
if (!spaceId)
spaceId = getCookie("X-Space-Id");
headers = {}
requestData = { 'utcOffset': moment().utcOffset() / 60 }
if loginToken && spaceId
headers['Authorization'] = 'Bearer ' + spaceId + ',' + loginToken
else if loginToken
# headers['Authorization'] = 'Bearer ' + loginToken
headers['X-User-Id'] = userId
headers['X-Auth-Token'] = loginToken
$.ajax
type: "POST",
url: Steedos.absoluteUrl("api/v4/users/validate"),
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(requestData),
xhrFields:
withCredentials: true
crossDomain: true
headers: headers
.done ( data ) ->
if Meteor.userId() != data.userId
Accounts.connection.setUserId(data.userId);
Accounts.loginWithToken data.authToken, (err) ->
if (err)
Meteor._debug("Error logging in with token: " + err);
FlowRouter.go "/steedos/logout"
return
if data.webservices
Steedos.settings.webservices = data.webservices
Setup.lastUserId = data.userId
if data.password_expired
Steedos.goResetPassword()
if data.spaceId
Setup.lastSpaceId = data.spaceId
if (data.spaceId != Session.get("spaceId"))
Steedos.setSpaceId(data.spaceId)
Creator.USER_CONTEXT = {
spaceId: data.spaceId,
userId: data.userId,
user: data
}
if !Meteor.loggingIn()
# 第一次在登录界面输入用户名密码登录后loggingIn为true,这时还没有登录成功
Setup.bootstrap(Session.get("spaceId"))
if onSuccess
onSuccess()
.fail ( e ) ->
if (e.status == 401)
Steedos.redirectToSignIn()
return
Setup.clearAuthLocalStorage = ()->
localStorage = window.localStorage;
i = 0
while i < localStorage.length
key = localStorage.key(i)
if key?.startsWith("Meteor<KEY>.loginToken") || key?.startsWith("Meteor.userId") || key?.startsWith("Meteor.loginTokenExpires") || key?.startsWith('accounts:')
localStorage.removeItem(key)
i++
Setup.logout = (callback) ->
$.ajax
type: "POST",
url: Steedos.absoluteUrl("api/v4/users/logout"),
dataType: 'json',
xhrFields:
withCredentials: true
crossDomain: true,
.always ( data ) ->
Setup.clearAuthLocalStorage()
if callback
callback()
Meteor.startup ->
Setup.validate();
Accounts.onLogin ()->
console.log("onLogin")
if Meteor.userId() != Setup.lastUserId
Setup.validate();
else
Setup.bootstrap(Session.get("spaceId"))
# Tracker.autorun (c)->
# # 登录后需要清除登录前订阅的space数据,以防止默认选中登录前浏览器url参数中的的工作区ID所指向的工作区
# # 而且可能登录后的用户不属性该SpaceAvatar中订阅的工作区,所以需要清除订阅,由之前的订阅来决定当前用户可以选择哪些工作区
# if Steedos.subsSpaceBase.ready()
# c.stop()
# Steedos.subs["SpaceAvatar"]?.clear()
# return
return
Accounts.onLogout ()->
console.log("onLogout")
Setup.logout ()->
Creator.bootstrapLoaded.set(false)
$("body").removeClass('loading')
Setup.lastUserId = null;
Steedos.redirectToSignIn()
Tracker.autorun (c)->
spaceId = Session.get("spaceId");
if Setup.lastSpaceId && (Setup.lastSpaceId != spaceId)
# 一定要在spaceId变化时立即设置bootstrapLoaded为false,而不可以在请求bootstrap之前才设置为false
# 否则有订阅的话,在请求bootsrtrap前,会先触发订阅的变化,订阅又会触发Creator.bootstrapLoaded.get()值的变化,而且是true变为true
# 这样的话在autorun中监听Creator.bootstrapLoaded.get()变化就会多进入一次
Creator.bootstrapLoaded.set(false)
console.log("spaceId change from " + Setup.lastSpaceId + " to " + Session.get("spaceId"))
Setup.validate()
return
if (localStorage.getItem("app_id") && !Session.get("app_id"))
Session.set("app_id", localStorage.getItem("app_id"));
Tracker.autorun (c)->
#console.log("app_id change: " + Session.get("app_id"))
localStorage.setItem("app_id", Session.get("app_id"))
return
return
Creator.bootstrapLoaded = new ReactiveVar(false)
handleBootstrapData = (result, callback)->
Creator._recordSafeObjectCache = []; # 切换工作区时,情况object缓存
Creator.Objects = result.objects;
Creator.baseObject = Creator.Objects.base;
Creator.objectsByName = {};
object_listviews = result.object_listviews
Creator.object_workflows = result.object_workflows
isSpaceAdmin = Steedos.isSpaceAdmin()
Session.set "user_permission_sets", result.user_permission_sets
_.each Creator.Objects, (object, object_name)->
_object_listviews = object_listviews[object_name]
_.each _object_listviews, (_object_listview)->
if _.isString(_object_listview.options)
_object_listview.options = JSON.parse(_object_listview.options)
if _object_listview.api_name
_key = _object_listview.api_name
else
_key = _object_listview._id
if !object.list_views
object.list_views = {}
object.list_views[_key] = _object_listview
Creator.loadObjects object, object_name
Creator.Apps = ReactSteedos.creatorAppsSelector(ReactSteedos.store.getState())
Creator.Menus = result.assigned_menus
if Steedos.isMobile()
mobileApps = _.filter Creator.getVisibleApps(true), (item)->
return item._id !='admin' && !_.isEmpty(item.mobile_objects)
appIds = _.pluck(mobileApps, "_id")
else
appIds = _.pluck(Creator.getVisibleApps(true), "_id")
if (appIds && appIds.length>0)
if (!Session.get("app_id") || appIds.indexOf(Session.get("app_id"))<0)
Session.set("app_id", appIds[0])
Creator.Dashboards = if result.dashboards then result.dashboards else {};
Creator.Plugins = if result.plugins then result.plugins else {};
if _.isFunction(callback)
callback()
Creator.bootstrapLoaded.set(true)
if (!FlowRouter._initialized)
FlowRouter.initialize();
if FlowRouter.current()?.context?.pathname == "/steedos/sign-in"
if FlowRouter.current()?.queryParams?.redirect
document.location.href = FlowRouter.current().queryParams.redirect;
return
else
FlowRouter.go("/")
requestBootstrapDataUseAjax = (spaceId, callback)->
unless spaceId and Meteor.userId()
return
userId = Meteor.userId()
authToken = <KEY>LoginToken()
url = Steedos.absoluteUrl "/api/bootstrap/#{spaceId}"
headers = {}
headers['Authorization'] = 'Bearer ' + spaceId + ',' + authToken
headers['X-User-Id'] = userId
headers['X-Auth-Token'] = authToken
$.ajax
type: "get"
url: url
dataType: "json"
headers: headers
error: (jqXHR, textStatus, errorThrown) ->
FlowRouter.initialize();
error = jqXHR.responseJSON
console.error error
if error?.reason
toastr?.error?(TAPi18n.__(error.reason))
else if error?.message
toastr?.error?(TAPi18n.__(error.message))
else
toastr?.error?(error)
success: (result) ->
handleBootstrapData(result, callback);
requestBootstrapDataUseAction = (spaceId)->
SteedosReact = require('@steedos/react');
store.dispatch(SteedosReact.loadBootstrapEntitiesData({spaceId: spaceId}))
requestBootstrapData = (spaceId, callback)->
SteedosReact = require('@steedos/react');
if SteedosReact.store
requestBootstrapDataUseAction(spaceId);
else
requestBootstrapDataUseAjax(spaceId, callback);
Setup.bootstrap = (spaceId, callback)->
requestBootstrapData(spaceId, callback)
FlowRouter.route '/steedos/logout',
action: (params, queryParams)->
#AccountsTemplates.logout();
$("body").addClass('loading')
Meteor.logout ()->
# FlowRouter.go("/steedos/sign-in")
return
Meteor.startup ()->
SteedosReact = require('@steedos/react');
RequestStatusOption = SteedosReact.RequestStatusOption
lastBootStrapRequestStatus = '';
SteedosReact.store?.subscribe ()->
state = SteedosReact.store.getState();
if lastBootStrapRequestStatus == RequestStatusOption.STARTED
lastBootStrapRequestStatus = SteedosReact.getRequestStatus(state); # 由于handleBootstrapData函数执行比较慢,因此在handleBootstrapData执行前,给lastBootStrapRequestStatus更新值
if SteedosReact.isRequestSuccess(state)
handleBootstrapData(clone(SteedosReact.getBootstrapData(state)));
else
lastBootStrapRequestStatus = SteedosReact.getRequestStatus(state); | true | require('url-search-params-polyfill');
clone = require('clone')
getCookie = (name)->
pattern = RegExp(name + "=.[^;]*")
matched = document.cookie.match(pattern)
if(matched)
cookie = matched[0].split('=')
return cookie[1]
return false
@Setup = {}
Blaze._allowJavascriptUrls()
FlowRouter.wait();
Steedos.goResetPassword = (redirect)->
accountsUrl = Meteor.settings.public?.webservices?.accounts?.url
if accountsUrl
if !redirect
redirect = location.href.replace("/steedos/sign-in", "").replace("/steedos/logout", "")
if _.isFunction(Steedos.isCordova) && Steedos.isCordova()
rootUrl = new URL(__meteor_runtime_config__.ROOT_URL)
accountsUrl = rootUrl.origin + accountsUrl
window.location.href = accountsUrl + "/a/#/update-password?redirect_uri=" + redirect;
Steedos.redirectToSignIn = (redirect)->
accountsUrl = Meteor.settings.public?.webservices?.accounts?.url
if accountsUrl
if !redirect
redirect = location.href.replace("/steedos/sign-in", "").replace("/steedos/logout", "")
if _.isFunction(Steedos.isCordova) && Steedos.isCordova()
rootUrl = new URL(__meteor_runtime_config__.ROOT_URL)
accountsUrl = rootUrl.origin + accountsUrl
window.location.href = accountsUrl + "/authorize?redirect_uri=" + redirect;
Setup.validate = (onSuccess)->
# if window.location.pathname.indexOf('/steedos/sign-in')>=0
# if (!FlowRouter._initialized)
# FlowRouter.initialize();
# return;
console.log("Validating user...")
searchParams = new URLSearchParams(window.location.search);
# 优先使用 URL 变量
loginToken = searchParams.get("X-Auth-Token");
userId = searchParams.get("X-User-Id");
# 然后使用 Meteor LocalStorage 变量
if (!userId or !loginToken)
loginToken = Accounts._storedLoginToken()
userId = Accounts._storedUserId();
# 然后使用 Cookie 变量
if (!userId or !loginToken)
loginToken = getCookie("X-Auth-Token");
userId = getCookie("X-User-Id");
spaceId = localStorage.getItem("spaceId")
if (!spaceId)
spaceId = getCookie("X-Space-Id");
headers = {}
requestData = { 'utcOffset': moment().utcOffset() / 60 }
if loginToken && spaceId
headers['Authorization'] = 'Bearer ' + spaceId + ',' + loginToken
else if loginToken
# headers['Authorization'] = 'Bearer ' + loginToken
headers['X-User-Id'] = userId
headers['X-Auth-Token'] = loginToken
$.ajax
type: "POST",
url: Steedos.absoluteUrl("api/v4/users/validate"),
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(requestData),
xhrFields:
withCredentials: true
crossDomain: true
headers: headers
.done ( data ) ->
if Meteor.userId() != data.userId
Accounts.connection.setUserId(data.userId);
Accounts.loginWithToken data.authToken, (err) ->
if (err)
Meteor._debug("Error logging in with token: " + err);
FlowRouter.go "/steedos/logout"
return
if data.webservices
Steedos.settings.webservices = data.webservices
Setup.lastUserId = data.userId
if data.password_expired
Steedos.goResetPassword()
if data.spaceId
Setup.lastSpaceId = data.spaceId
if (data.spaceId != Session.get("spaceId"))
Steedos.setSpaceId(data.spaceId)
Creator.USER_CONTEXT = {
spaceId: data.spaceId,
userId: data.userId,
user: data
}
if !Meteor.loggingIn()
# 第一次在登录界面输入用户名密码登录后loggingIn为true,这时还没有登录成功
Setup.bootstrap(Session.get("spaceId"))
if onSuccess
onSuccess()
.fail ( e ) ->
if (e.status == 401)
Steedos.redirectToSignIn()
return
Setup.clearAuthLocalStorage = ()->
localStorage = window.localStorage;
i = 0
while i < localStorage.length
key = localStorage.key(i)
if key?.startsWith("MeteorPI:KEY:<KEY>END_PI.loginToken") || key?.startsWith("Meteor.userId") || key?.startsWith("Meteor.loginTokenExpires") || key?.startsWith('accounts:')
localStorage.removeItem(key)
i++
Setup.logout = (callback) ->
$.ajax
type: "POST",
url: Steedos.absoluteUrl("api/v4/users/logout"),
dataType: 'json',
xhrFields:
withCredentials: true
crossDomain: true,
.always ( data ) ->
Setup.clearAuthLocalStorage()
if callback
callback()
Meteor.startup ->
Setup.validate();
Accounts.onLogin ()->
console.log("onLogin")
if Meteor.userId() != Setup.lastUserId
Setup.validate();
else
Setup.bootstrap(Session.get("spaceId"))
# Tracker.autorun (c)->
# # 登录后需要清除登录前订阅的space数据,以防止默认选中登录前浏览器url参数中的的工作区ID所指向的工作区
# # 而且可能登录后的用户不属性该SpaceAvatar中订阅的工作区,所以需要清除订阅,由之前的订阅来决定当前用户可以选择哪些工作区
# if Steedos.subsSpaceBase.ready()
# c.stop()
# Steedos.subs["SpaceAvatar"]?.clear()
# return
return
Accounts.onLogout ()->
console.log("onLogout")
Setup.logout ()->
Creator.bootstrapLoaded.set(false)
$("body").removeClass('loading')
Setup.lastUserId = null;
Steedos.redirectToSignIn()
Tracker.autorun (c)->
spaceId = Session.get("spaceId");
if Setup.lastSpaceId && (Setup.lastSpaceId != spaceId)
# 一定要在spaceId变化时立即设置bootstrapLoaded为false,而不可以在请求bootstrap之前才设置为false
# 否则有订阅的话,在请求bootsrtrap前,会先触发订阅的变化,订阅又会触发Creator.bootstrapLoaded.get()值的变化,而且是true变为true
# 这样的话在autorun中监听Creator.bootstrapLoaded.get()变化就会多进入一次
Creator.bootstrapLoaded.set(false)
console.log("spaceId change from " + Setup.lastSpaceId + " to " + Session.get("spaceId"))
Setup.validate()
return
if (localStorage.getItem("app_id") && !Session.get("app_id"))
Session.set("app_id", localStorage.getItem("app_id"));
Tracker.autorun (c)->
#console.log("app_id change: " + Session.get("app_id"))
localStorage.setItem("app_id", Session.get("app_id"))
return
return
Creator.bootstrapLoaded = new ReactiveVar(false)
handleBootstrapData = (result, callback)->
Creator._recordSafeObjectCache = []; # 切换工作区时,情况object缓存
Creator.Objects = result.objects;
Creator.baseObject = Creator.Objects.base;
Creator.objectsByName = {};
object_listviews = result.object_listviews
Creator.object_workflows = result.object_workflows
isSpaceAdmin = Steedos.isSpaceAdmin()
Session.set "user_permission_sets", result.user_permission_sets
_.each Creator.Objects, (object, object_name)->
_object_listviews = object_listviews[object_name]
_.each _object_listviews, (_object_listview)->
if _.isString(_object_listview.options)
_object_listview.options = JSON.parse(_object_listview.options)
if _object_listview.api_name
_key = _object_listview.api_name
else
_key = _object_listview._id
if !object.list_views
object.list_views = {}
object.list_views[_key] = _object_listview
Creator.loadObjects object, object_name
Creator.Apps = ReactSteedos.creatorAppsSelector(ReactSteedos.store.getState())
Creator.Menus = result.assigned_menus
if Steedos.isMobile()
mobileApps = _.filter Creator.getVisibleApps(true), (item)->
return item._id !='admin' && !_.isEmpty(item.mobile_objects)
appIds = _.pluck(mobileApps, "_id")
else
appIds = _.pluck(Creator.getVisibleApps(true), "_id")
if (appIds && appIds.length>0)
if (!Session.get("app_id") || appIds.indexOf(Session.get("app_id"))<0)
Session.set("app_id", appIds[0])
Creator.Dashboards = if result.dashboards then result.dashboards else {};
Creator.Plugins = if result.plugins then result.plugins else {};
if _.isFunction(callback)
callback()
Creator.bootstrapLoaded.set(true)
if (!FlowRouter._initialized)
FlowRouter.initialize();
if FlowRouter.current()?.context?.pathname == "/steedos/sign-in"
if FlowRouter.current()?.queryParams?.redirect
document.location.href = FlowRouter.current().queryParams.redirect;
return
else
FlowRouter.go("/")
requestBootstrapDataUseAjax = (spaceId, callback)->
unless spaceId and Meteor.userId()
return
userId = Meteor.userId()
authToken = PI:KEY:<KEY>END_PILoginToken()
url = Steedos.absoluteUrl "/api/bootstrap/#{spaceId}"
headers = {}
headers['Authorization'] = 'Bearer ' + spaceId + ',' + authToken
headers['X-User-Id'] = userId
headers['X-Auth-Token'] = authToken
$.ajax
type: "get"
url: url
dataType: "json"
headers: headers
error: (jqXHR, textStatus, errorThrown) ->
FlowRouter.initialize();
error = jqXHR.responseJSON
console.error error
if error?.reason
toastr?.error?(TAPi18n.__(error.reason))
else if error?.message
toastr?.error?(TAPi18n.__(error.message))
else
toastr?.error?(error)
success: (result) ->
handleBootstrapData(result, callback);
requestBootstrapDataUseAction = (spaceId)->
SteedosReact = require('@steedos/react');
store.dispatch(SteedosReact.loadBootstrapEntitiesData({spaceId: spaceId}))
requestBootstrapData = (spaceId, callback)->
SteedosReact = require('@steedos/react');
if SteedosReact.store
requestBootstrapDataUseAction(spaceId);
else
requestBootstrapDataUseAjax(spaceId, callback);
Setup.bootstrap = (spaceId, callback)->
requestBootstrapData(spaceId, callback)
FlowRouter.route '/steedos/logout',
action: (params, queryParams)->
#AccountsTemplates.logout();
$("body").addClass('loading')
Meteor.logout ()->
# FlowRouter.go("/steedos/sign-in")
return
Meteor.startup ()->
SteedosReact = require('@steedos/react');
RequestStatusOption = SteedosReact.RequestStatusOption
lastBootStrapRequestStatus = '';
SteedosReact.store?.subscribe ()->
state = SteedosReact.store.getState();
if lastBootStrapRequestStatus == RequestStatusOption.STARTED
lastBootStrapRequestStatus = SteedosReact.getRequestStatus(state); # 由于handleBootstrapData函数执行比较慢,因此在handleBootstrapData执行前,给lastBootStrapRequestStatus更新值
if SteedosReact.isRequestSuccess(state)
handleBootstrapData(clone(SteedosReact.getBootstrapData(state)));
else
lastBootStrapRequestStatus = SteedosReact.getRequestStatus(state); |
[
{
"context": "tationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)\n\n\t\t\tit \"should return the default num",
"end": 2438,
"score": 0.8601672649383545,
"start": 2430,
"tag": "USERNAME",
"value": "@user_id"
},
{
"context": "tationsManager.allowedNumberOfCollabora... | test/unit/coffee/Subscription/LimitationsManagerTests.coffee | dtu-compute/web-sharelatex | 0 | SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
require('chai').should()
modulePath = require('path').join __dirname, '../../../../app/js/Features/Subscription/LimitationsManager'
Settings = require("settings-sharelatex")
describe "LimitationsManager", ->
beforeEach ->
@project = { _id: @project_id = "project-id" }
@user = { _id: @user_id = "user-id", features:{} }
@ProjectGetter =
getProject: (project_id, fields, callback) =>
if project_id == @project_id
callback null, @project
else
callback null, null
@UserGetter =
getUser: (user_id, filter, callback) =>
if user_id == @user_id
callback null, @user
else
callback null, null
@SubscriptionLocator =
getUsersSubscription: sinon.stub()
@LimitationsManager = SandboxedModule.require modulePath, requires:
'../Project/ProjectGetter': @ProjectGetter
'../User/UserGetter' : @UserGetter
'./SubscriptionLocator':@SubscriptionLocator
'settings-sharelatex' : @Settings = {}
"../Collaborators/CollaboratorsHandler": @CollaboratorsHandler = {}
"../Collaborators/CollaboratorsInviteHandler": @CollaboratorsInviteHandler = {}
'logger-sharelatex':log:->
describe "allowedNumberOfCollaboratorsInProject", ->
describe "when the project is owned by a user without a subscription", ->
beforeEach ->
@Settings.defaultPlanCode = collaborators: 23
@project.owner_ref = @user_id
delete @user.features
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsInProject(@project_id, @callback)
it "should return the default number", ->
@callback.calledWith(null, @Settings.defaultPlanCode.collaborators).should.equal true
describe "when the project is owned by a user with a subscription", ->
beforeEach ->
@project.owner_ref = @user_id
@user.features =
collaborators: 21
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsInProject(@project_id, @callback)
it "should return the number of collaborators the user is allowed", ->
@callback.calledWith(null, @user.features.collaborators).should.equal true
describe "allowedNumberOfCollaboratorsForUser", ->
describe "when the user has no features", ->
beforeEach ->
@Settings.defaultPlanCode = collaborators: 23
delete @user.features
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)
it "should return the default number", ->
@callback.calledWith(null, @Settings.defaultPlanCode.collaborators).should.equal true
describe "when the user has features", ->
beforeEach ->
@user.features =
collaborators: 21
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)
it "should return the number of collaborators the user is allowed", ->
@callback.calledWith(null, @user.features.collaborators).should.equal true
describe "canAddXCollaborators", ->
describe "when the project has fewer collaborators than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe "when the project has fewer collaborators and invites than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 4
@invite_count = 1
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe "when the project has fewer collaborators than allowed but I want to add more than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 2, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "when the project has more collaborators than allowed", ->
beforeEach ->
@current_number = 3
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "when the project has infinite collaborators", ->
beforeEach ->
@current_number = 100
@allowed_number = -1
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe 'when the project has more invites than allowed', ->
beforeEach ->
@current_number = 0
@allowed_number = 2
@invite_count = 2
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe 'when the project has more invites and collaborators than allowed', ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 1
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "userHasSubscription", ->
beforeEach ->
@SubscriptionLocator.getUsersSubscription = sinon.stub()
it "should return true if the recurly token is set", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, recurlySubscription_id : "1234")
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal true
done()
it "should return false if the recurly token is not set", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {})
@subscription = {}
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal false
done()
it "should return false if the subscription is undefined", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1)
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal false
done()
it "should return the subscription", (done)->
stubbedSubscription = {freeTrial:{}, token:""}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, stubbedSubscription)
@LimitationsManager.userHasSubscription @user, (err, hasSubOrIsGroupMember, subscription)->
subscription.should.deep.equal stubbedSubscription
done()
describe "when user has a custom account", ->
beforeEach ->
@fakeSubscription = {customAccount: true}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @fakeSubscription)
it 'should return true', (done) ->
@LimitationsManager.userHasSubscription @user, (err, hasSubscription, subscription)->
hasSubscription.should.equal true
done()
it 'should return the subscription', (done) ->
@LimitationsManager.userHasSubscription @user, (err, hasSubscription, subscription)=>
subscription.should.deep.equal @fakeSubscription
done()
describe "userIsMemberOfGroupSubscription", ->
beforeEach ->
@SubscriptionLocator.getMemberSubscriptions = sinon.stub()
it "should return false if there are no groups subcriptions", (done)->
@SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, [])
@LimitationsManager.userIsMemberOfGroupSubscription @user, (err, isMember)->
isMember.should.equal false
done()
it "should return true if there are no groups subcriptions", (done)->
@SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, subscriptions = ["mock-subscription"])
@LimitationsManager.userIsMemberOfGroupSubscription @user, (err, isMember, retSubscriptions)->
isMember.should.equal true
retSubscriptions.should.equal subscriptions
done()
describe "userHasSubscriptionOrIsGroupMember", ->
beforeEach ->
@LimitationsManager.userIsMemberOfGroupSubscription = sinon.stub()
@LimitationsManager.userHasSubscription = sinon.stub()
it "should return true if both are true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return true if one is true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return true if other is true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return false if both are false", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal false
done()
describe "hasGroupMembersLimitReached", ->
beforeEach ->
@user_id = "12312"
@subscription =
membersLimit: 3
member_ids: ["", ""]
invited_emails: ["bob@example.com"]
it "should return true if the limit is hit (including members and invites)", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal true
done()
it "should return false if the limit is not hit (including members and invites)", (done)->
@subscription.membersLimit = 4
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal false
done()
it "should return true if the limit has been exceded (including members and invites)", (done)->
@subscription.membersLimit = 2
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal true
done()
| 12567 | SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
require('chai').should()
modulePath = require('path').join __dirname, '../../../../app/js/Features/Subscription/LimitationsManager'
Settings = require("settings-sharelatex")
describe "LimitationsManager", ->
beforeEach ->
@project = { _id: @project_id = "project-id" }
@user = { _id: @user_id = "user-id", features:{} }
@ProjectGetter =
getProject: (project_id, fields, callback) =>
if project_id == @project_id
callback null, @project
else
callback null, null
@UserGetter =
getUser: (user_id, filter, callback) =>
if user_id == @user_id
callback null, @user
else
callback null, null
@SubscriptionLocator =
getUsersSubscription: sinon.stub()
@LimitationsManager = SandboxedModule.require modulePath, requires:
'../Project/ProjectGetter': @ProjectGetter
'../User/UserGetter' : @UserGetter
'./SubscriptionLocator':@SubscriptionLocator
'settings-sharelatex' : @Settings = {}
"../Collaborators/CollaboratorsHandler": @CollaboratorsHandler = {}
"../Collaborators/CollaboratorsInviteHandler": @CollaboratorsInviteHandler = {}
'logger-sharelatex':log:->
describe "allowedNumberOfCollaboratorsInProject", ->
describe "when the project is owned by a user without a subscription", ->
beforeEach ->
@Settings.defaultPlanCode = collaborators: 23
@project.owner_ref = @user_id
delete @user.features
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsInProject(@project_id, @callback)
it "should return the default number", ->
@callback.calledWith(null, @Settings.defaultPlanCode.collaborators).should.equal true
describe "when the project is owned by a user with a subscription", ->
beforeEach ->
@project.owner_ref = @user_id
@user.features =
collaborators: 21
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsInProject(@project_id, @callback)
it "should return the number of collaborators the user is allowed", ->
@callback.calledWith(null, @user.features.collaborators).should.equal true
describe "allowedNumberOfCollaboratorsForUser", ->
describe "when the user has no features", ->
beforeEach ->
@Settings.defaultPlanCode = collaborators: 23
delete @user.features
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)
it "should return the default number", ->
@callback.calledWith(null, @Settings.defaultPlanCode.collaborators).should.equal true
describe "when the user has features", ->
beforeEach ->
@user.features =
collaborators: 21
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)
it "should return the number of collaborators the user is allowed", ->
@callback.calledWith(null, @user.features.collaborators).should.equal true
describe "canAddXCollaborators", ->
describe "when the project has fewer collaborators than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe "when the project has fewer collaborators and invites than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 4
@invite_count = 1
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe "when the project has fewer collaborators than allowed but I want to add more than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 2, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "when the project has more collaborators than allowed", ->
beforeEach ->
@current_number = 3
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "when the project has infinite collaborators", ->
beforeEach ->
@current_number = 100
@allowed_number = -1
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe 'when the project has more invites than allowed', ->
beforeEach ->
@current_number = 0
@allowed_number = 2
@invite_count = 2
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe 'when the project has more invites and collaborators than allowed', ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 1
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "userHasSubscription", ->
beforeEach ->
@SubscriptionLocator.getUsersSubscription = sinon.stub()
it "should return true if the recurly token is set", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, recurlySubscription_id : "1234")
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal true
done()
it "should return false if the recurly token is not set", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {})
@subscription = {}
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal false
done()
it "should return false if the subscription is undefined", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1)
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal false
done()
it "should return the subscription", (done)->
stubbedSubscription = {freeTrial:{}, token:""}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, stubbedSubscription)
@LimitationsManager.userHasSubscription @user, (err, hasSubOrIsGroupMember, subscription)->
subscription.should.deep.equal stubbedSubscription
done()
describe "when user has a custom account", ->
beforeEach ->
@fakeSubscription = {customAccount: true}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @fakeSubscription)
it 'should return true', (done) ->
@LimitationsManager.userHasSubscription @user, (err, hasSubscription, subscription)->
hasSubscription.should.equal true
done()
it 'should return the subscription', (done) ->
@LimitationsManager.userHasSubscription @user, (err, hasSubscription, subscription)=>
subscription.should.deep.equal @fakeSubscription
done()
describe "userIsMemberOfGroupSubscription", ->
beforeEach ->
@SubscriptionLocator.getMemberSubscriptions = sinon.stub()
it "should return false if there are no groups subcriptions", (done)->
@SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, [])
@LimitationsManager.userIsMemberOfGroupSubscription @user, (err, isMember)->
isMember.should.equal false
done()
it "should return true if there are no groups subcriptions", (done)->
@SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, subscriptions = ["mock-subscription"])
@LimitationsManager.userIsMemberOfGroupSubscription @user, (err, isMember, retSubscriptions)->
isMember.should.equal true
retSubscriptions.should.equal subscriptions
done()
describe "userHasSubscriptionOrIsGroupMember", ->
beforeEach ->
@LimitationsManager.userIsMemberOfGroupSubscription = sinon.stub()
@LimitationsManager.userHasSubscription = sinon.stub()
it "should return true if both are true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return true if one is true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return true if other is true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return false if both are false", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal false
done()
describe "hasGroupMembersLimitReached", ->
beforeEach ->
@user_id = "12312"
@subscription =
membersLimit: 3
member_ids: ["", ""]
invited_emails: ["<EMAIL>"]
it "should return true if the limit is hit (including members and invites)", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal true
done()
it "should return false if the limit is not hit (including members and invites)", (done)->
@subscription.membersLimit = 4
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal false
done()
it "should return true if the limit has been exceded (including members and invites)", (done)->
@subscription.membersLimit = 2
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal true
done()
| true | SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
require('chai').should()
modulePath = require('path').join __dirname, '../../../../app/js/Features/Subscription/LimitationsManager'
Settings = require("settings-sharelatex")
describe "LimitationsManager", ->
beforeEach ->
@project = { _id: @project_id = "project-id" }
@user = { _id: @user_id = "user-id", features:{} }
@ProjectGetter =
getProject: (project_id, fields, callback) =>
if project_id == @project_id
callback null, @project
else
callback null, null
@UserGetter =
getUser: (user_id, filter, callback) =>
if user_id == @user_id
callback null, @user
else
callback null, null
@SubscriptionLocator =
getUsersSubscription: sinon.stub()
@LimitationsManager = SandboxedModule.require modulePath, requires:
'../Project/ProjectGetter': @ProjectGetter
'../User/UserGetter' : @UserGetter
'./SubscriptionLocator':@SubscriptionLocator
'settings-sharelatex' : @Settings = {}
"../Collaborators/CollaboratorsHandler": @CollaboratorsHandler = {}
"../Collaborators/CollaboratorsInviteHandler": @CollaboratorsInviteHandler = {}
'logger-sharelatex':log:->
describe "allowedNumberOfCollaboratorsInProject", ->
describe "when the project is owned by a user without a subscription", ->
beforeEach ->
@Settings.defaultPlanCode = collaborators: 23
@project.owner_ref = @user_id
delete @user.features
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsInProject(@project_id, @callback)
it "should return the default number", ->
@callback.calledWith(null, @Settings.defaultPlanCode.collaborators).should.equal true
describe "when the project is owned by a user with a subscription", ->
beforeEach ->
@project.owner_ref = @user_id
@user.features =
collaborators: 21
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsInProject(@project_id, @callback)
it "should return the number of collaborators the user is allowed", ->
@callback.calledWith(null, @user.features.collaborators).should.equal true
describe "allowedNumberOfCollaboratorsForUser", ->
describe "when the user has no features", ->
beforeEach ->
@Settings.defaultPlanCode = collaborators: 23
delete @user.features
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)
it "should return the default number", ->
@callback.calledWith(null, @Settings.defaultPlanCode.collaborators).should.equal true
describe "when the user has features", ->
beforeEach ->
@user.features =
collaborators: 21
@callback = sinon.stub()
@LimitationsManager.allowedNumberOfCollaboratorsForUser(@user_id, @callback)
it "should return the number of collaborators the user is allowed", ->
@callback.calledWith(null, @user.features.collaborators).should.equal true
describe "canAddXCollaborators", ->
describe "when the project has fewer collaborators than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe "when the project has fewer collaborators and invites than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 4
@invite_count = 1
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe "when the project has fewer collaborators than allowed but I want to add more than allowed", ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 2, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "when the project has more collaborators than allowed", ->
beforeEach ->
@current_number = 3
@allowed_number = 2
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "when the project has infinite collaborators", ->
beforeEach ->
@current_number = 100
@allowed_number = -1
@invite_count = 0
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return true", ->
@callback.calledWith(null, true).should.equal true
describe 'when the project has more invites than allowed', ->
beforeEach ->
@current_number = 0
@allowed_number = 2
@invite_count = 2
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe 'when the project has more invites and collaborators than allowed', ->
beforeEach ->
@current_number = 1
@allowed_number = 2
@invite_count = 1
@CollaboratorsHandler.getInvitedCollaboratorCount = (project_id, callback) => callback(null, @current_number)
@CollaboratorsInviteHandler.getInviteCount = (project_id, callback) => callback(null, @invite_count)
sinon.stub @LimitationsManager, "allowedNumberOfCollaboratorsInProject", (project_id, callback) =>
callback(null, @allowed_number)
@callback = sinon.stub()
@LimitationsManager.canAddXCollaborators(@project_id, 1, @callback)
it "should return false", ->
@callback.calledWith(null, false).should.equal true
describe "userHasSubscription", ->
beforeEach ->
@SubscriptionLocator.getUsersSubscription = sinon.stub()
it "should return true if the recurly token is set", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, recurlySubscription_id : "1234")
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal true
done()
it "should return false if the recurly token is not set", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {})
@subscription = {}
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal false
done()
it "should return false if the subscription is undefined", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1)
@LimitationsManager.userHasSubscription @user, (err, hasSubscription)->
hasSubscription.should.equal false
done()
it "should return the subscription", (done)->
stubbedSubscription = {freeTrial:{}, token:""}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, stubbedSubscription)
@LimitationsManager.userHasSubscription @user, (err, hasSubOrIsGroupMember, subscription)->
subscription.should.deep.equal stubbedSubscription
done()
describe "when user has a custom account", ->
beforeEach ->
@fakeSubscription = {customAccount: true}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @fakeSubscription)
it 'should return true', (done) ->
@LimitationsManager.userHasSubscription @user, (err, hasSubscription, subscription)->
hasSubscription.should.equal true
done()
it 'should return the subscription', (done) ->
@LimitationsManager.userHasSubscription @user, (err, hasSubscription, subscription)=>
subscription.should.deep.equal @fakeSubscription
done()
describe "userIsMemberOfGroupSubscription", ->
beforeEach ->
@SubscriptionLocator.getMemberSubscriptions = sinon.stub()
it "should return false if there are no groups subcriptions", (done)->
@SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, [])
@LimitationsManager.userIsMemberOfGroupSubscription @user, (err, isMember)->
isMember.should.equal false
done()
it "should return true if there are no groups subcriptions", (done)->
@SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, subscriptions = ["mock-subscription"])
@LimitationsManager.userIsMemberOfGroupSubscription @user, (err, isMember, retSubscriptions)->
isMember.should.equal true
retSubscriptions.should.equal subscriptions
done()
describe "userHasSubscriptionOrIsGroupMember", ->
beforeEach ->
@LimitationsManager.userIsMemberOfGroupSubscription = sinon.stub()
@LimitationsManager.userHasSubscription = sinon.stub()
it "should return true if both are true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return true if one is true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return true if other is true", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, true)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal true
done()
it "should return false if both are false", (done)->
@LimitationsManager.userIsMemberOfGroupSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscription.callsArgWith(1, null, false)
@LimitationsManager.userHasSubscriptionOrIsGroupMember @user, (err, hasSubOrIsGroupMember)->
hasSubOrIsGroupMember.should.equal false
done()
describe "hasGroupMembersLimitReached", ->
beforeEach ->
@user_id = "12312"
@subscription =
membersLimit: 3
member_ids: ["", ""]
invited_emails: ["PI:EMAIL:<EMAIL>END_PI"]
it "should return true if the limit is hit (including members and invites)", (done)->
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal true
done()
it "should return false if the limit is not hit (including members and invites)", (done)->
@subscription.membersLimit = 4
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal false
done()
it "should return true if the limit has been exceded (including members and invites)", (done)->
@subscription.membersLimit = 2
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@LimitationsManager.hasGroupMembersLimitReached @user_id, (err, limitReached)->
limitReached.should.equal true
done()
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999120831489563,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/post-preview.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 @PostPreview
constructor: ->
@debouncedLoadPreview = _.debounce @loadPreview, 500
$(document).on 'input', '.js-post-preview--auto', (e) =>
# get the target immediately because event object may change later.
@debouncedLoadPreview(e.currentTarget)
loadPreview: (target) =>
$form = $(target).closest('form')
body = target.value
$preview = $form.find('.js-post-preview--preview')
preview = $preview[0]
$previewBox = $form.find('.js-post-preview--box')
if !preview?
return
preview._xhr?.abort()
if body == ''
$previewBox.addClass 'hidden'
return
if $preview.attr('data-raw') == body
$previewBox.removeClass 'hidden'
return
preview._xhr = $.post(laroute.route('bbcode-preview'), text: body)
.done (data) =>
$preview.html data
$preview.attr 'data-raw', body
$previewBox.removeClass 'hidden'
osu.pageChange()
| 85696 | # 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 @PostPreview
constructor: ->
@debouncedLoadPreview = _.debounce @loadPreview, 500
$(document).on 'input', '.js-post-preview--auto', (e) =>
# get the target immediately because event object may change later.
@debouncedLoadPreview(e.currentTarget)
loadPreview: (target) =>
$form = $(target).closest('form')
body = target.value
$preview = $form.find('.js-post-preview--preview')
preview = $preview[0]
$previewBox = $form.find('.js-post-preview--box')
if !preview?
return
preview._xhr?.abort()
if body == ''
$previewBox.addClass 'hidden'
return
if $preview.attr('data-raw') == body
$previewBox.removeClass 'hidden'
return
preview._xhr = $.post(laroute.route('bbcode-preview'), text: body)
.done (data) =>
$preview.html data
$preview.attr 'data-raw', body
$previewBox.removeClass 'hidden'
osu.pageChange()
| 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 @PostPreview
constructor: ->
@debouncedLoadPreview = _.debounce @loadPreview, 500
$(document).on 'input', '.js-post-preview--auto', (e) =>
# get the target immediately because event object may change later.
@debouncedLoadPreview(e.currentTarget)
loadPreview: (target) =>
$form = $(target).closest('form')
body = target.value
$preview = $form.find('.js-post-preview--preview')
preview = $preview[0]
$previewBox = $form.find('.js-post-preview--box')
if !preview?
return
preview._xhr?.abort()
if body == ''
$previewBox.addClass 'hidden'
return
if $preview.attr('data-raw') == body
$previewBox.removeClass 'hidden'
return
preview._xhr = $.post(laroute.route('bbcode-preview'), text: body)
.done (data) =>
$preview.html data
$preview.attr 'data-raw', body
$previewBox.removeClass 'hidden'
osu.pageChange()
|
[
{
"context": "defined\n timestamp = new Date().getTime()\n key = \"#{timestamp}\"\n expected = 'test'\n\n before ->\n client = red",
"end": 235,
"score": 0.8550440669059753,
"start": 221,
"tag": "KEY",
"value": "\"#{timestamp}\""
}
] | test/integration/redis-test.coffee | apiaryio/redis-utils | 0 | require 'mocha'
{assert} = require 'chai'
redis = require 'redis'
redutils = require '../../src/redis-helpers'
describe 'Test Redis utils', ->
client = undefined
timestamp = new Date().getTime()
key = "#{timestamp}"
expected = 'test'
before ->
client = redutils.getClient()
client.set key, expected, redis.print
after ->
client.quit()
it 'Get reply', (done) ->
client.get key, (err, reply) ->
if err then return done err
assert.equal reply, expected
done()
| 145172 | require 'mocha'
{assert} = require 'chai'
redis = require 'redis'
redutils = require '../../src/redis-helpers'
describe 'Test Redis utils', ->
client = undefined
timestamp = new Date().getTime()
key = <KEY>
expected = 'test'
before ->
client = redutils.getClient()
client.set key, expected, redis.print
after ->
client.quit()
it 'Get reply', (done) ->
client.get key, (err, reply) ->
if err then return done err
assert.equal reply, expected
done()
| true | require 'mocha'
{assert} = require 'chai'
redis = require 'redis'
redutils = require '../../src/redis-helpers'
describe 'Test Redis utils', ->
client = undefined
timestamp = new Date().getTime()
key = PI:KEY:<KEY>END_PI
expected = 'test'
before ->
client = redutils.getClient()
client.set key, expected, redis.print
after ->
client.quit()
it 'Get reply', (done) ->
client.get key, (err, reply) ->
if err then return done err
assert.equal reply, expected
done()
|
[
{
"context": ";\n @canceled();\n\n connect: ->\n password = @clientConfig.password;\n passphrase = @clientConfig.passphrase;\n\n ",
"end": 751,
"score": 0.7793843746185303,
"start": 729,
"tag": "PASSWORD",
"value": "@clientConfig.password"
},
{
"context": "sword = @cli... | lib/fs/ftp/sftp-session.coffee | morassman/atom-commander | 43 | fs = require 'fs'
SSH2 = require 'ssh2'
Utils = require '../../utils'
module.exports =
class SFTPSession
constructor: (@fileSystem) ->
@config = @fileSystem.config;
@clientConfig = @fileSystem.clientConfig;
@client = null;
@ssh2 = null;
@open = null;
getClient: ->
return @client;
# Called if connecting failed due to invalid credentials. This will only try
# to connect again if a password or passphrase should be prompted for.
reconnect: (err) ->
delete @clientConfig.password;
delete @clientConfig.passphrase;
if @config.loginWithPassword or @config.usePassphrase
@connect();
else
@fileSystem.emitError(err);
@canceled();
connect: ->
password = @clientConfig.password;
passphrase = @clientConfig.passphrase;
if !password?
password = '';
if !passphrase?
passphrase = '';
if @config.loginWithPassword
@connectWith(password, passphrase);
return;
if @config.usePassphrase and passphrase.length > 0
@connectWith(password, passphrase);
return;
if !@config.usePassphrase
@connectWith(password, passphrase);
return;
# Only the passphrase needs to be prompted for. The password will
# be prompted for by ssh2.
prompt = "Enter passphrase for ";
prompt += @clientConfig.username;
prompt += "@";
prompt += @clientConfig.host;
prompt += ":"
Utils.promptForPassword prompt, (input) =>
if input?
@connectWith(password, input);
else
err = {};
err.canceled = true;
err.message = "Incorrect credentials for "+@clientConfig.host;
@fileSystem.emitError(err);
@canceled();
# All connectWith? functions boil down to this one.
#
# password: The password that should be used. empty if not logging in with password.
# passphrase: The passphrase to use when loggin in with a private key. empty if it shouldn't be used.
connectWith: (password, passphrase) ->
@client = null;
@ssh2 = new SSH2();
@ssh2.on "ready", =>
@ssh2.sftp (err, sftp) =>
if err?
@fileSystem.emitError(err);
@close();
return;
@client = sftp;
@client.on "end", =>
@close();
# If the connection was successful then remember the password for
# the rest of the session.
if password.length > 0
@clientConfig.password = password;
if passphrase.length > 0
@clientConfig.passphrase = passphrase;
@opened();
@ssh2.on "error", (err) =>
if err.level == "client-authentication"
atom.notifications.addWarning("Incorrect credentials for "+@clientConfig.host);
err = {};
err.canceled = false;
err.message = "Incorrect credentials for "+@clientConfig.host;
@reconnect(err);
else
@fileSystem.emitError(err);
@ssh2.on "close", =>
@close();
@ssh2.on "end", =>
@close();
@ssh2.on "keyboard-interactive", (name, instructions, instructionsLang, prompt, finish) =>
if password.length > 0
finish([password]);
else
prompts = prompt.map (p) -> p.prompt;
values = [];
@prompt(0, prompts, values, finish);
connectConfig = {};
for key, val of @clientConfig
connectConfig[key] = val;
connectConfig.password = password;
connectConfig.passphrase = passphrase;
if (connectConfig.password.length == 0)
delete connectConfig['password'];
if (connectConfig.passphrase.length == 0)
delete connectConfig['passphrase'];
@ssh2.connect(connectConfig);
disconnect: ->
if @client?
@client.end();
@client = null;
if @ssh2?
@ssh2.end();
@ssh2 = null;
@close();
opened: ->
@open = true;
@fileSystem.sessionOpened(@);
canceled: ->
@disconnect();
@fileSystem.sessionCanceled(@);
close: ->
if @open
@open = false;
@fileSystem.sessionClosed(@);
prompt: (index, prompts, values, finish) ->
Utils.promptForPassword prompts[index], (input) =>
if input?
values.push(input);
if prompts.length == (index + 1)
finish(values);
else
@prompt(index + 1, prompts, values, finish);
else
err = {};
err.canceled = true;
err.message = "Incorrect credentials for "+@clientConfig.host;
@fileSystem.emitError(err);
@canceled();
| 167512 | fs = require 'fs'
SSH2 = require 'ssh2'
Utils = require '../../utils'
module.exports =
class SFTPSession
constructor: (@fileSystem) ->
@config = @fileSystem.config;
@clientConfig = @fileSystem.clientConfig;
@client = null;
@ssh2 = null;
@open = null;
getClient: ->
return @client;
# Called if connecting failed due to invalid credentials. This will only try
# to connect again if a password or passphrase should be prompted for.
reconnect: (err) ->
delete @clientConfig.password;
delete @clientConfig.passphrase;
if @config.loginWithPassword or @config.usePassphrase
@connect();
else
@fileSystem.emitError(err);
@canceled();
connect: ->
password = <PASSWORD>;
passphrase = @<PASSWORD>;
if !password?
password = '';
if !passphrase?
passphrase = '';
if @config.loginWithPassword
@connectWith(password, passphrase);
return;
if @config.usePassphrase and passphrase.length > 0
@connectWith(password, passphrase);
return;
if !@config.usePassphrase
@connectWith(password, passphrase);
return;
# Only the passphrase needs to be prompted for. The password will
# be prompted for by ssh2.
prompt = "Enter passphrase for ";
prompt += @clientConfig.username;
prompt += "@";
prompt += @clientConfig.host;
prompt += ":"
Utils.promptForPassword prompt, (input) =>
if input?
@connectWith(password, input);
else
err = {};
err.canceled = true;
err.message = "Incorrect credentials for "+@clientConfig.host;
@fileSystem.emitError(err);
@canceled();
# All connectWith? functions boil down to this one.
#
# password: The password that should be used. empty if not logging in with password.
# passphrase: The passphrase to use when loggin in with a private key. empty if it shouldn't be used.
connectWith: (password, passphrase) ->
@client = null;
@ssh2 = new SSH2();
@ssh2.on "ready", =>
@ssh2.sftp (err, sftp) =>
if err?
@fileSystem.emitError(err);
@close();
return;
@client = sftp;
@client.on "end", =>
@close();
# If the connection was successful then remember the password for
# the rest of the session.
if password.length > 0
@clientConfig.password = <PASSWORD>;
if passphrase.length > 0
@clientConfig.passphrase = <PASSWORD>;
@opened();
@ssh2.on "error", (err) =>
if err.level == "client-authentication"
atom.notifications.addWarning("Incorrect credentials for "+@clientConfig.host);
err = {};
err.canceled = false;
err.message = "Incorrect credentials for "+@clientConfig.host;
@reconnect(err);
else
@fileSystem.emitError(err);
@ssh2.on "close", =>
@close();
@ssh2.on "end", =>
@close();
@ssh2.on "keyboard-interactive", (name, instructions, instructionsLang, prompt, finish) =>
if password.length > 0
finish([password]);
else
prompts = prompt.map (p) -> p.prompt;
values = [];
@prompt(0, prompts, values, finish);
connectConfig = {};
for key, val of @clientConfig
connectConfig[key] = val;
connectConfig.password = <PASSWORD>;
connectConfig.passphrase = <PASSWORD>;
if (connectConfig.password.length == 0)
delete connectConfig['password'];
if (connectConfig.passphrase.length == 0)
delete connectConfig['passphrase'];
@ssh2.connect(connectConfig);
disconnect: ->
if @client?
@client.end();
@client = null;
if @ssh2?
@ssh2.end();
@ssh2 = null;
@close();
opened: ->
@open = true;
@fileSystem.sessionOpened(@);
canceled: ->
@disconnect();
@fileSystem.sessionCanceled(@);
close: ->
if @open
@open = false;
@fileSystem.sessionClosed(@);
prompt: (index, prompts, values, finish) ->
Utils.promptForPassword prompts[index], (input) =>
if input?
values.push(input);
if prompts.length == (index + 1)
finish(values);
else
@prompt(index + 1, prompts, values, finish);
else
err = {};
err.canceled = true;
err.message = "Incorrect credentials for "+@clientConfig.host;
@fileSystem.emitError(err);
@canceled();
| true | fs = require 'fs'
SSH2 = require 'ssh2'
Utils = require '../../utils'
module.exports =
class SFTPSession
constructor: (@fileSystem) ->
@config = @fileSystem.config;
@clientConfig = @fileSystem.clientConfig;
@client = null;
@ssh2 = null;
@open = null;
getClient: ->
return @client;
# Called if connecting failed due to invalid credentials. This will only try
# to connect again if a password or passphrase should be prompted for.
reconnect: (err) ->
delete @clientConfig.password;
delete @clientConfig.passphrase;
if @config.loginWithPassword or @config.usePassphrase
@connect();
else
@fileSystem.emitError(err);
@canceled();
connect: ->
password = PI:PASSWORD:<PASSWORD>END_PI;
passphrase = @PI:PASSWORD:<PASSWORD>END_PI;
if !password?
password = '';
if !passphrase?
passphrase = '';
if @config.loginWithPassword
@connectWith(password, passphrase);
return;
if @config.usePassphrase and passphrase.length > 0
@connectWith(password, passphrase);
return;
if !@config.usePassphrase
@connectWith(password, passphrase);
return;
# Only the passphrase needs to be prompted for. The password will
# be prompted for by ssh2.
prompt = "Enter passphrase for ";
prompt += @clientConfig.username;
prompt += "@";
prompt += @clientConfig.host;
prompt += ":"
Utils.promptForPassword prompt, (input) =>
if input?
@connectWith(password, input);
else
err = {};
err.canceled = true;
err.message = "Incorrect credentials for "+@clientConfig.host;
@fileSystem.emitError(err);
@canceled();
# All connectWith? functions boil down to this one.
#
# password: The password that should be used. empty if not logging in with password.
# passphrase: The passphrase to use when loggin in with a private key. empty if it shouldn't be used.
connectWith: (password, passphrase) ->
@client = null;
@ssh2 = new SSH2();
@ssh2.on "ready", =>
@ssh2.sftp (err, sftp) =>
if err?
@fileSystem.emitError(err);
@close();
return;
@client = sftp;
@client.on "end", =>
@close();
# If the connection was successful then remember the password for
# the rest of the session.
if password.length > 0
@clientConfig.password = PI:PASSWORD:<PASSWORD>END_PI;
if passphrase.length > 0
@clientConfig.passphrase = PI:PASSWORD:<PASSWORD>END_PI;
@opened();
@ssh2.on "error", (err) =>
if err.level == "client-authentication"
atom.notifications.addWarning("Incorrect credentials for "+@clientConfig.host);
err = {};
err.canceled = false;
err.message = "Incorrect credentials for "+@clientConfig.host;
@reconnect(err);
else
@fileSystem.emitError(err);
@ssh2.on "close", =>
@close();
@ssh2.on "end", =>
@close();
@ssh2.on "keyboard-interactive", (name, instructions, instructionsLang, prompt, finish) =>
if password.length > 0
finish([password]);
else
prompts = prompt.map (p) -> p.prompt;
values = [];
@prompt(0, prompts, values, finish);
connectConfig = {};
for key, val of @clientConfig
connectConfig[key] = val;
connectConfig.password = PI:PASSWORD:<PASSWORD>END_PI;
connectConfig.passphrase = PI:PASSWORD:<PASSWORD>END_PI;
if (connectConfig.password.length == 0)
delete connectConfig['password'];
if (connectConfig.passphrase.length == 0)
delete connectConfig['passphrase'];
@ssh2.connect(connectConfig);
disconnect: ->
if @client?
@client.end();
@client = null;
if @ssh2?
@ssh2.end();
@ssh2 = null;
@close();
opened: ->
@open = true;
@fileSystem.sessionOpened(@);
canceled: ->
@disconnect();
@fileSystem.sessionCanceled(@);
close: ->
if @open
@open = false;
@fileSystem.sessionClosed(@);
prompt: (index, prompts, values, finish) ->
Utils.promptForPassword prompts[index], (input) =>
if input?
values.push(input);
if prompts.length == (index + 1)
finish(values);
else
@prompt(index + 1, prompts, values, finish);
else
err = {};
err.canceled = true;
err.message = "Incorrect credentials for "+@clientConfig.host;
@fileSystem.emitError(err);
@canceled();
|
[
{
"context": "###*\n* Collect actors\n*\n* @author David Jegat <david.jegat@gmail.com>\n###\nclass ActorCollection",
"end": 45,
"score": 0.999893844127655,
"start": 34,
"tag": "NAME",
"value": "David Jegat"
},
{
"context": "###*\n* Collect actors\n*\n* @author David Jegat <david.jega... | src/Collection/ActorCollection.coffee | Djeg/MicroRacing | 1 | ###*
* Collect actors
*
* @author David Jegat <david.jegat@gmail.com>
###
class ActorCollection extends Collection
###*
* Redefined the add method to handle BaseActor object
*
* @param {BaseActor} actor
* @throws String
* @return {ActorCollection}
###
add: (actor) ->
if not actor instanceof BaseActor
throw "Invalid actor"
super actor
@
###*
* Get ordered items
*
* @throws String, if two order is the same
* @return {Array}
###
getOrderedItems: () ->
ordered = []
for name, actor of @items
if ordered[actor.order] instanceof BaseActor
throw "The actor #{actor.name} has same order than #{ordered[actor.order].name}"
ordered[actor.order] = actor
ordered
| 41781 | ###*
* Collect actors
*
* @author <NAME> <<EMAIL>>
###
class ActorCollection extends Collection
###*
* Redefined the add method to handle BaseActor object
*
* @param {BaseActor} actor
* @throws String
* @return {ActorCollection}
###
add: (actor) ->
if not actor instanceof BaseActor
throw "Invalid actor"
super actor
@
###*
* Get ordered items
*
* @throws String, if two order is the same
* @return {Array}
###
getOrderedItems: () ->
ordered = []
for name, actor of @items
if ordered[actor.order] instanceof BaseActor
throw "The actor #{actor.name} has same order than #{ordered[actor.order].name}"
ordered[actor.order] = actor
ordered
| true | ###*
* Collect actors
*
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
class ActorCollection extends Collection
###*
* Redefined the add method to handle BaseActor object
*
* @param {BaseActor} actor
* @throws String
* @return {ActorCollection}
###
add: (actor) ->
if not actor instanceof BaseActor
throw "Invalid actor"
super actor
@
###*
* Get ordered items
*
* @throws String, if two order is the same
* @return {Array}
###
getOrderedItems: () ->
ordered = []
for name, actor of @items
if ordered[actor.order] instanceof BaseActor
throw "The actor #{actor.name} has same order than #{ordered[actor.order].name}"
ordered[actor.order] = actor
ordered
|
[
{
"context": "ate that a value is not on a blacklist\n # @author Daniel Bartholomae\n class BlacklistValidatorRule extends ValidatorR",
"end": 372,
"score": 0.9998927712440491,
"start": 354,
"tag": "NAME",
"value": "Daniel Bartholomae"
}
] | src/rules/Blacklist.coffee | dbartholomae/node-validation-codes | 0 | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( ['./Rule'], (ValidatorRule) ->
# A rule to validate that a value is not on a blacklist
# @author Daniel Bartholomae
class BlacklistValidatorRule extends ValidatorRule
# Create a new BlacklistValidatorRule
#
# @param [Object] (options) An optional list of options
# @option options [Array] blacklist List of blacklisted values Default: []
constructor: (options) ->
@options =
blacklist: []
super
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> ['Blacklisted']
# Validate that a value is not in options.blacklist
#
# @param [Object] value The value to validate
# @return [Array<String>] [] if the value is valid, ['Blacklisted'] if it is in the blacklist
validate: (value) ->
return ['Blacklisted'] if value in @options.blacklist
return []
) | 203930 | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( ['./Rule'], (ValidatorRule) ->
# A rule to validate that a value is not on a blacklist
# @author <NAME>
class BlacklistValidatorRule extends ValidatorRule
# Create a new BlacklistValidatorRule
#
# @param [Object] (options) An optional list of options
# @option options [Array] blacklist List of blacklisted values Default: []
constructor: (options) ->
@options =
blacklist: []
super
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> ['Blacklisted']
# Validate that a value is not in options.blacklist
#
# @param [Object] value The value to validate
# @return [Array<String>] [] if the value is valid, ['Blacklisted'] if it is in the blacklist
validate: (value) ->
return ['Blacklisted'] if value in @options.blacklist
return []
) | true | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( ['./Rule'], (ValidatorRule) ->
# A rule to validate that a value is not on a blacklist
# @author PI:NAME:<NAME>END_PI
class BlacklistValidatorRule extends ValidatorRule
# Create a new BlacklistValidatorRule
#
# @param [Object] (options) An optional list of options
# @option options [Array] blacklist List of blacklisted values Default: []
constructor: (options) ->
@options =
blacklist: []
super
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> ['Blacklisted']
# Validate that a value is not in options.blacklist
#
# @param [Object] value The value to validate
# @return [Array<String>] [] if the value is valid, ['Blacklisted'] if it is in the blacklist
validate: (value) ->
return ['Blacklisted'] if value in @options.blacklist
return []
) |
[
{
"context": "# Copyright (c) 2008-2013 Michael Dvorkin and contributors.\n#\n# Fat Free CRM is freely dist",
"end": 41,
"score": 0.9998638033866882,
"start": 26,
"tag": "NAME",
"value": "Michael Dvorkin"
}
] | app/assets/javascripts/crm_chosen.js.coffee | ramses-lopez/re-crm | 1 | # Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# Initialize chosen for multiselect tag list
crm.chosen_taglist = (asset, controller, id)->
new Chosen $(asset + '_tag_list'), {
allow_option_creation: true
on_option_add: (tag) ->
crm.load_field_group(controller, tag, id)
on_option_remove: (tag) ->
crm.remove_field_group(tag)
}
crm.ensure_chosen_account = ->
unless $("account_id_chzn")
new ajaxChosen $("account_id"), {
allow_single_deselect: true
show_on_activate: true
url: "/accounts/auto_complete.json"
parameters: { limit: 25 }
query_key: "auto_complete_query"
}
(($j) ->
# Prefer standard select2 dropdown for non-Ajaxy selectboxes
add_select2_boxes = ->
$j("select[name*='assigned_to'], select[name*='[country]'], .chzn-select" ).each ->
$j(this).select2()
# Apply pop up to merge links when document is loaded
$j(document).ready ->
add_select2_boxes()
# Apply pop up to merge links when jquery event (e.g. search) occurs
$j(document).ajaxComplete ->
add_select2_boxes()
# Apply pop up to merge links when protoype event (e.g. cancel edit) occurs
Ajax.Responders.register({
onComplete: ->
add_select2_boxes()
})
) (jQuery)
| 50318 | # Copyright (c) 2008-2013 <NAME> and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# Initialize chosen for multiselect tag list
crm.chosen_taglist = (asset, controller, id)->
new Chosen $(asset + '_tag_list'), {
allow_option_creation: true
on_option_add: (tag) ->
crm.load_field_group(controller, tag, id)
on_option_remove: (tag) ->
crm.remove_field_group(tag)
}
crm.ensure_chosen_account = ->
unless $("account_id_chzn")
new ajaxChosen $("account_id"), {
allow_single_deselect: true
show_on_activate: true
url: "/accounts/auto_complete.json"
parameters: { limit: 25 }
query_key: "auto_complete_query"
}
(($j) ->
# Prefer standard select2 dropdown for non-Ajaxy selectboxes
add_select2_boxes = ->
$j("select[name*='assigned_to'], select[name*='[country]'], .chzn-select" ).each ->
$j(this).select2()
# Apply pop up to merge links when document is loaded
$j(document).ready ->
add_select2_boxes()
# Apply pop up to merge links when jquery event (e.g. search) occurs
$j(document).ajaxComplete ->
add_select2_boxes()
# Apply pop up to merge links when protoype event (e.g. cancel edit) occurs
Ajax.Responders.register({
onComplete: ->
add_select2_boxes()
})
) (jQuery)
| true | # Copyright (c) 2008-2013 PI:NAME:<NAME>END_PI and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# Initialize chosen for multiselect tag list
crm.chosen_taglist = (asset, controller, id)->
new Chosen $(asset + '_tag_list'), {
allow_option_creation: true
on_option_add: (tag) ->
crm.load_field_group(controller, tag, id)
on_option_remove: (tag) ->
crm.remove_field_group(tag)
}
crm.ensure_chosen_account = ->
unless $("account_id_chzn")
new ajaxChosen $("account_id"), {
allow_single_deselect: true
show_on_activate: true
url: "/accounts/auto_complete.json"
parameters: { limit: 25 }
query_key: "auto_complete_query"
}
(($j) ->
# Prefer standard select2 dropdown for non-Ajaxy selectboxes
add_select2_boxes = ->
$j("select[name*='assigned_to'], select[name*='[country]'], .chzn-select" ).each ->
$j(this).select2()
# Apply pop up to merge links when document is loaded
$j(document).ready ->
add_select2_boxes()
# Apply pop up to merge links when jquery event (e.g. search) occurs
$j(document).ajaxComplete ->
add_select2_boxes()
# Apply pop up to merge links when protoype event (e.g. cancel edit) occurs
Ajax.Responders.register({
onComplete: ->
add_select2_boxes()
})
) (jQuery)
|
[
{
"context": "ique id. Ported from TartJS.\n https://github.com/tart/tartJS/blob/master/tart/tart.js#L26 -- amcalar <3",
"end": 212,
"score": 0.999519407749176,
"start": 208,
"tag": "USERNAME",
"value": "tart"
},
{
"context": "ub.com/tart/tartJS/blob/master/tart/tart.js#L26 -- amcal... | src/lib/utils/utils.coffee | dashersw/spark | 1 | goog.provide 'spark.utils'
goog.require 'spark.validation'
goog.require 'goog.string'
counter = Math.floor Math.random() * 2147483648
###*
Returns a unique id. Ported from TartJS.
https://github.com/tart/tartJS/blob/master/tart/tart.js#L26 -- amcalar <3
@export
@return {string} Unique id.
###
spark.utils.getUid = ->
return (counter++).toString 36
###*
Concats strings together with a space.
@export
@param {...*} var_args A list of strings to concatenate.
@return {string} The concatenation of {@code var_args}.
###
spark.utils.concatString = (var_args) ->
strings = []
for arg in arguments when typeof arg is 'string'
if arg.indexOf(' ') > -1
for item in arg.split ' '
strings.push item if strings.indexOf(item) is -1
else
strings.push arg
return strings.join ' '
###*
Replaces mustache like template tags with the value in the given data.
Currently only parses variable tags like `{{name}}`. I am planning to make it
more powerful with upcoming releases. Tags are not whitespace sensitive.
So `{{ name }}` and `{{name}}` and `{{ name }}` are the same. Here is a
usage example. Replaced values are html escaped to avoid possible XSS attempt.
You can also use nested variables to walk in your object keys.
```coffee
template = """
<img src="{{ details.avatar.full }}" />
<span>{{firstName}} {{lastName}} - @{{userName}}</span>
"""
data =
firstName : 'Fatih'
lastName : 'Acet'
userName : 'fatihacet'
details :
avatar :
full : 'fatihacet.png'
spark.utils.parseTemplate template, data
# will return "<img src="fatihacet.png" />\n<span>Fatih Acet - @fatihacet</span>"
```
@export
@param {!string} template Template string will the parser executed on.
@param {*=} data Data of the template. # FIXME: annotation, should be `{Object}`
@param {string=} defaultText Default text which will be replaced if the tag
keyword doesn't exist in the given data.
@return {string} Template with parsed and replaced data.
###
spark.utils.parseTemplate = (template, data, defaultText) ->
TAG_MATCHER_REGEX = /({{\s*[a-zA-z0-9.]+\s*}})/g
TAG_CAPTURE_REGEX = /(\s*[a-zA-z0-9.]+\s*)/
defaultText or= ''
tags = template.match TAG_MATCHER_REGEX
return template unless tags
tags.forEach (tag) ->
keyword = goog.string.trim tag.match(TAG_CAPTURE_REGEX)[1]
parts = keyword.split '.'
value = data[parts.shift()]
if parts.length
for part, index in parts
value = value[part]
value = if spark.validation.isString value then value else defaultText
template = template.replace tag, goog.string.htmlEscape value or defaultText
return template
| 93414 | goog.provide 'spark.utils'
goog.require 'spark.validation'
goog.require 'goog.string'
counter = Math.floor Math.random() * 2147483648
###*
Returns a unique id. Ported from TartJS.
https://github.com/tart/tartJS/blob/master/tart/tart.js#L26 -- amcalar <3
@export
@return {string} Unique id.
###
spark.utils.getUid = ->
return (counter++).toString 36
###*
Concats strings together with a space.
@export
@param {...*} var_args A list of strings to concatenate.
@return {string} The concatenation of {@code var_args}.
###
spark.utils.concatString = (var_args) ->
strings = []
for arg in arguments when typeof arg is 'string'
if arg.indexOf(' ') > -1
for item in arg.split ' '
strings.push item if strings.indexOf(item) is -1
else
strings.push arg
return strings.join ' '
###*
Replaces mustache like template tags with the value in the given data.
Currently only parses variable tags like `{{name}}`. I am planning to make it
more powerful with upcoming releases. Tags are not whitespace sensitive.
So `{{ name }}` and `{{name}}` and `{{ name }}` are the same. Here is a
usage example. Replaced values are html escaped to avoid possible XSS attempt.
You can also use nested variables to walk in your object keys.
```coffee
template = """
<img src="{{ details.avatar.full }}" />
<span>{{firstName}} {{lastName}} - @{{userName}}</span>
"""
data =
firstName : '<NAME>'
lastName : '<NAME>'
userName : 'fatihacet'
details :
avatar :
full : 'fatihacet.png'
spark.utils.parseTemplate template, data
# will return "<img src="fatihacet.png" />\n<span>Fatih Acet - @fatihacet</span>"
```
@export
@param {!string} template Template string will the parser executed on.
@param {*=} data Data of the template. # FIXME: annotation, should be `{Object}`
@param {string=} defaultText Default text which will be replaced if the tag
keyword doesn't exist in the given data.
@return {string} Template with parsed and replaced data.
###
spark.utils.parseTemplate = (template, data, defaultText) ->
TAG_MATCHER_REGEX = /({{\s*[a-zA-z0-9.]+\s*}})/g
TAG_CAPTURE_REGEX = /(\s*[a-zA-z0-9.]+\s*)/
defaultText or= ''
tags = template.match TAG_MATCHER_REGEX
return template unless tags
tags.forEach (tag) ->
keyword = goog.string.trim tag.match(TAG_CAPTURE_REGEX)[1]
parts = keyword.split '.'
value = data[parts.shift()]
if parts.length
for part, index in parts
value = value[part]
value = if spark.validation.isString value then value else defaultText
template = template.replace tag, goog.string.htmlEscape value or defaultText
return template
| true | goog.provide 'spark.utils'
goog.require 'spark.validation'
goog.require 'goog.string'
counter = Math.floor Math.random() * 2147483648
###*
Returns a unique id. Ported from TartJS.
https://github.com/tart/tartJS/blob/master/tart/tart.js#L26 -- amcalar <3
@export
@return {string} Unique id.
###
spark.utils.getUid = ->
return (counter++).toString 36
###*
Concats strings together with a space.
@export
@param {...*} var_args A list of strings to concatenate.
@return {string} The concatenation of {@code var_args}.
###
spark.utils.concatString = (var_args) ->
strings = []
for arg in arguments when typeof arg is 'string'
if arg.indexOf(' ') > -1
for item in arg.split ' '
strings.push item if strings.indexOf(item) is -1
else
strings.push arg
return strings.join ' '
###*
Replaces mustache like template tags with the value in the given data.
Currently only parses variable tags like `{{name}}`. I am planning to make it
more powerful with upcoming releases. Tags are not whitespace sensitive.
So `{{ name }}` and `{{name}}` and `{{ name }}` are the same. Here is a
usage example. Replaced values are html escaped to avoid possible XSS attempt.
You can also use nested variables to walk in your object keys.
```coffee
template = """
<img src="{{ details.avatar.full }}" />
<span>{{firstName}} {{lastName}} - @{{userName}}</span>
"""
data =
firstName : 'PI:NAME:<NAME>END_PI'
lastName : 'PI:NAME:<NAME>END_PI'
userName : 'fatihacet'
details :
avatar :
full : 'fatihacet.png'
spark.utils.parseTemplate template, data
# will return "<img src="fatihacet.png" />\n<span>Fatih Acet - @fatihacet</span>"
```
@export
@param {!string} template Template string will the parser executed on.
@param {*=} data Data of the template. # FIXME: annotation, should be `{Object}`
@param {string=} defaultText Default text which will be replaced if the tag
keyword doesn't exist in the given data.
@return {string} Template with parsed and replaced data.
###
spark.utils.parseTemplate = (template, data, defaultText) ->
TAG_MATCHER_REGEX = /({{\s*[a-zA-z0-9.]+\s*}})/g
TAG_CAPTURE_REGEX = /(\s*[a-zA-z0-9.]+\s*)/
defaultText or= ''
tags = template.match TAG_MATCHER_REGEX
return template unless tags
tags.forEach (tag) ->
keyword = goog.string.trim tag.match(TAG_CAPTURE_REGEX)[1]
parts = keyword.split '.'
value = data[parts.shift()]
if parts.length
for part, index in parts
value = value[part]
value = if spark.validation.isString value then value else defaultText
template = template.replace tag, goog.string.htmlEscape value or defaultText
return template
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.