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": "ip_viola_configurator.conf'\n mongodb: 'mongodb://127.0.0.1:27017/viola'\n ami:\n port: 5038\n host: 'loc",
"end": 151,
"score": 0.9997017979621887,
"start": 142,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " port: 5038\n host: 'localhost'\n ... | config.coffee | antirek/viola-configurator | 0 | module.exports =
port: 3000
filePath: "#{__dirname}/uploads"
sipConf: '/etc/asterisk/sip_viola_configurator.conf'
mongodb: 'mongodb://127.0.0.1:27017/viola'
ami:
port: 5038
host: 'localhost'
username: 'admin'
password: 'admin'
debug: false | 188407 | module.exports =
port: 3000
filePath: "#{__dirname}/uploads"
sipConf: '/etc/asterisk/sip_viola_configurator.conf'
mongodb: 'mongodb://127.0.0.1:27017/viola'
ami:
port: 5038
host: 'localhost'
username: 'admin'
password: '<PASSWORD>'
debug: false | true | module.exports =
port: 3000
filePath: "#{__dirname}/uploads"
sipConf: '/etc/asterisk/sip_viola_configurator.conf'
mongodb: 'mongodb://127.0.0.1:27017/viola'
ami:
port: 5038
host: 'localhost'
username: 'admin'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
debug: false |
[
{
"context": "ystem http://glawn.org\n#\n# Copyright (c) 2012,2013 Eamonn O'Brien-Strain All rights\n# reserved. This program and the accom",
"end": 109,
"score": 0.9998900890350342,
"start": 88,
"tag": "NAME",
"value": "Eamonn O'Brien-Strain"
},
{
"context": "ipse.org/legal/epl-v10.... | test-coffee/rotimgSpec.coffee | eobrain/glan | 0 | ###
# This file is part of the Glan system http://glawn.org
#
# Copyright (c) 2012,2013 Eamonn O'Brien-Strain All rights
# reserved. This program and the accompanying materials are made
# available under the terms of the Eclipse Public License v1.0 which
# accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Eamonn O'Brien-Strain e@obrain.com - initial author
###
#wait until page is loaded
$ ->
$imgOdd = $ '#rotimg-odd'
$imgEven = $ '#rotimg-even'
describe 'rotimg is a plugin to Glan that rotates through a set of images', ->
it 'initially, odd image is displayed and even image is not', ->
runs ->
#ajax has not jet returned the images.json
expect($imgOdd.css 'display').not.toBe 'none'
waitsFor ->
($imgOdd.css 'display') == 'none'
runs ->
expect($imgEven.css 'display').toBe 'inline'
expect($imgOdd.css 'display').toBe 'none'
it 'each hash change swaps what image is displayed', ->
#check display status is as expected
expectEvenOdd = (displayEven, displayOdd) ->
expect($imgOdd.css 'display').toBe displayOdd
expect($imgEven.css 'display').toBe displayEven
runs ->
expectEvenOdd 'inline', 'none'
window.location.hash = '#aaa'
waits 800
runs ->
expectEvenOdd 'none', 'inline'
window.location.hash = 'bbb'
waits 800
runs ->
expectEvenOdd 'inline', 'none'
window.location.hash = '#ccc'
waits 800
runs ->
expectEvenOdd 'none', 'inline'
it 'image changes on every hashchange', ->
$activeImg = ->
if ($imgOdd.css 'display') == 'inline'
$imgOdd
else
$imgEven
pastUrls = []
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#xxx'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#yyy'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#zzz'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#ppp'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#qqq'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#rrr'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = 'sss'
| 155108 | ###
# This file is part of the Glan system http://glawn.org
#
# Copyright (c) 2012,2013 <NAME> All rights
# reserved. This program and the accompanying materials are made
# available under the terms of the Eclipse Public License v1.0 which
# accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# <NAME> <EMAIL> - initial author
###
#wait until page is loaded
$ ->
$imgOdd = $ '#rotimg-odd'
$imgEven = $ '#rotimg-even'
describe 'rotimg is a plugin to Glan that rotates through a set of images', ->
it 'initially, odd image is displayed and even image is not', ->
runs ->
#ajax has not jet returned the images.json
expect($imgOdd.css 'display').not.toBe 'none'
waitsFor ->
($imgOdd.css 'display') == 'none'
runs ->
expect($imgEven.css 'display').toBe 'inline'
expect($imgOdd.css 'display').toBe 'none'
it 'each hash change swaps what image is displayed', ->
#check display status is as expected
expectEvenOdd = (displayEven, displayOdd) ->
expect($imgOdd.css 'display').toBe displayOdd
expect($imgEven.css 'display').toBe displayEven
runs ->
expectEvenOdd 'inline', 'none'
window.location.hash = '#aaa'
waits 800
runs ->
expectEvenOdd 'none', 'inline'
window.location.hash = 'bbb'
waits 800
runs ->
expectEvenOdd 'inline', 'none'
window.location.hash = '#ccc'
waits 800
runs ->
expectEvenOdd 'none', 'inline'
it 'image changes on every hashchange', ->
$activeImg = ->
if ($imgOdd.css 'display') == 'inline'
$imgOdd
else
$imgEven
pastUrls = []
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#xxx'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#yyy'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#zzz'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#ppp'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#qqq'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#rrr'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = 'sss'
| true | ###
# This file is part of the Glan system http://glawn.org
#
# Copyright (c) 2012,2013 PI:NAME:<NAME>END_PI All rights
# reserved. This program and the accompanying materials are made
# available under the terms of the Eclipse Public License v1.0 which
# accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI - initial author
###
#wait until page is loaded
$ ->
$imgOdd = $ '#rotimg-odd'
$imgEven = $ '#rotimg-even'
describe 'rotimg is a plugin to Glan that rotates through a set of images', ->
it 'initially, odd image is displayed and even image is not', ->
runs ->
#ajax has not jet returned the images.json
expect($imgOdd.css 'display').not.toBe 'none'
waitsFor ->
($imgOdd.css 'display') == 'none'
runs ->
expect($imgEven.css 'display').toBe 'inline'
expect($imgOdd.css 'display').toBe 'none'
it 'each hash change swaps what image is displayed', ->
#check display status is as expected
expectEvenOdd = (displayEven, displayOdd) ->
expect($imgOdd.css 'display').toBe displayOdd
expect($imgEven.css 'display').toBe displayEven
runs ->
expectEvenOdd 'inline', 'none'
window.location.hash = '#aaa'
waits 800
runs ->
expectEvenOdd 'none', 'inline'
window.location.hash = 'bbb'
waits 800
runs ->
expectEvenOdd 'inline', 'none'
window.location.hash = '#ccc'
waits 800
runs ->
expectEvenOdd 'none', 'inline'
it 'image changes on every hashchange', ->
$activeImg = ->
if ($imgOdd.css 'display') == 'inline'
$imgOdd
else
$imgEven
pastUrls = []
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#xxx'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#yyy'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#zzz'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#ppp'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#qqq'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = '#rrr'
waits 800
runs ->
url = $activeImg().attr 'src'
expect(pastUrls).not.toContain url
pastUrls.push url
window.location.hash = 'sss'
|
[
{
"context": "overview Tests for block-scoped-var rule\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n#-",
"end": 74,
"score": 0.9997773170471191,
"start": 63,
"tag": "NAME",
"value": "Matt DuVall"
},
{
"context": " e\n e\n '''\n ,\n # https:... | src/tests/rules/block-scoped-var.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for block-scoped-var rule
# @author Matt DuVall <http://www.mattduvall.com>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/block-scoped-var'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'block-scoped-var', rule,
valid: [
# See issue https://github.com/eslint/eslint/issues/2242
code: '''
f = ->
f()
exports = { f: f }
'''
,
'!(f = -> f)'
'''
f = ->
a = true
b = a
'''
'''
a = null
f = ->
b = a
'''
'f = (a) ->'
'!((a) ->)'
'!(f = (a) ->)'
'f = (a) -> b = a'
'!(f = (a) -> b = a)'
'f = -> g = f'
'''
f = ->
g = ->
f = g
'''
'''
f = ->
g()
g = ->
'''
'''
if yes
a = 1
a
'''
'''
a = null
if yes
a
'''
'''
for i in [0...10]
i
'''
'''
i for i in [0...10]
'''
'''
i = null
for [0...10]
i
'''
,
code: '''
myFunc = (foo) ->
"use strict"
{ bar } = foo
bar.hello()
'''
,
code: '''
myFunc = (foo) ->
"use strict"
[ bar ] = foo
bar.hello()
'''
,
code: 'myFunc = (...foo) -> return foo'
,
code: '''
class Foo
export default Foo
'''
,
code: 'new Date', globals: Date: no
,
code: 'new Date', globals: {}
,
code: "eslint = require('eslint')", globals: require: no
,
code: 'fun = ({x}) -> return x'
,
code: 'fun = ([,x]) -> x'
,
'f = (a) -> return a.b'
'a = { "foo": 3 }'
'a = { foo: 3 }'
'a = { foo: 3, bar: 5 }'
# 'a = { set foo(a){}, get bar(){} };'
'f = (a) -> arguments[0]'
'''
f = ->
a = f
'''
'''
f = ->
for a in {}
a
'''
'''
f = ->
a for a in {}
'''
'''
f = ->
switch 2
when 1
b = 2
b
else
b
'''
,
code: '''
React = require("react/addons")
cx = React.addons.classSet
'''
globals: require: no
,
'''
v = 1
x = -> return v
'''
'''
import * as y from "./other.js"
y()
'''
'''
import y from "./other.js"
y()
'''
'''
import {x as y} from "./other.js"
y()
'''
'''
x = null
export {x}
'''
'''
x = null
export {x as v}
'''
'export {x} from "./other.js"'
'export {x as v} from "./other.js"'
'''
class Test
myFunction: ->
return true
'''
# 'class Test { get flag() { return true; }}'
'''
Test = class
myFunction: ->
return true
'''
,
code: '''
doStuff = null
{x: y} = {x: 1}
doStuff(y)
'''
,
'foo = ({x: y}) -> y'
# those are the same as `no-undef`.
'''
!(f = ->)
f
'''
'''
f = foo = ->
foo()
exports = { f: foo }
'''
'f = => x'
"eslint = require('eslint')"
'f = (a) -> a[b]'
'f = -> b.a'
'a = { foo: bar }'
'a = foo: foo'
'a = { bar: 7, foo: bar }'
'a = arguments'
'''
x = ->
a = arguments
'''
'''
z = (b) ->
a = b
'''
'''
z = ->
b = null
a = b
'''
'''
f = ->
try
catch e
e
'''
,
# https://github.com/eslint/eslint/issues/2253
code: '''
###global React###
{PropTypes, addons: {PureRenderMixin}} = React
Test = React.createClass({mixins: [PureRenderMixin]})
'''
,
code: '''
###global prevState###
{ virtualSize: prevVirtualSize = 0 } = prevState
'''
,
code: '''
{ dummy: { data, isLoading }, auth: { isLoggedIn } } = @props
'''
,
# https://github.com/eslint/eslint/issues/2747
'''
a = (n) ->
if n > 0 then b(n - 1) else "a"
b = (n) ->
if n > 0 then a(n - 1) else "b"
'''
# https://github.com/eslint/eslint/issues/2967
'''
(-> foo())()
foo = ->
'''
'''
do -> foo()
foo = ->
'''
'''
for i in []
;
'''
'''
for i, j in []
i + j
'''
'''
i for i in []
'''
]
invalid: [
code: '''
f = ->
try
a = 0
catch e
b = a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
a = ->
for b of {}
c = b
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
a = ->
for b from {}
c = b
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
a = ->
c = b for b in []
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
f = ->
switch 2
when 1
b = 2
b
else
b
b
'''
errors: [messageId: 'outOfScope', data: {name: 'b'}, type: 'Identifier']
,
code: '''
for a in []
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
for a of {}
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
for a from []
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
if yes
a = null
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
if yes
a = 1
else
a = 2
'''
errors: [
messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier'
# ,
# messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier'
]
,
code: '''
for i in []
;
for i in []
;
'''
errors: [
messageId: 'outOfScope', data: {name: 'i'}, type: 'Identifier'
,
messageId: 'outOfScope', data: {name: 'i'}, type: 'Identifier'
]
]
| 34252 | ###*
# @fileoverview Tests for block-scoped-var rule
# @author <NAME> <http://www.mattduvall.com>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/block-scoped-var'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'block-scoped-var', rule,
valid: [
# See issue https://github.com/eslint/eslint/issues/2242
code: '''
f = ->
f()
exports = { f: f }
'''
,
'!(f = -> f)'
'''
f = ->
a = true
b = a
'''
'''
a = null
f = ->
b = a
'''
'f = (a) ->'
'!((a) ->)'
'!(f = (a) ->)'
'f = (a) -> b = a'
'!(f = (a) -> b = a)'
'f = -> g = f'
'''
f = ->
g = ->
f = g
'''
'''
f = ->
g()
g = ->
'''
'''
if yes
a = 1
a
'''
'''
a = null
if yes
a
'''
'''
for i in [0...10]
i
'''
'''
i for i in [0...10]
'''
'''
i = null
for [0...10]
i
'''
,
code: '''
myFunc = (foo) ->
"use strict"
{ bar } = foo
bar.hello()
'''
,
code: '''
myFunc = (foo) ->
"use strict"
[ bar ] = foo
bar.hello()
'''
,
code: 'myFunc = (...foo) -> return foo'
,
code: '''
class Foo
export default Foo
'''
,
code: 'new Date', globals: Date: no
,
code: 'new Date', globals: {}
,
code: "eslint = require('eslint')", globals: require: no
,
code: 'fun = ({x}) -> return x'
,
code: 'fun = ([,x]) -> x'
,
'f = (a) -> return a.b'
'a = { "foo": 3 }'
'a = { foo: 3 }'
'a = { foo: 3, bar: 5 }'
# 'a = { set foo(a){}, get bar(){} };'
'f = (a) -> arguments[0]'
'''
f = ->
a = f
'''
'''
f = ->
for a in {}
a
'''
'''
f = ->
a for a in {}
'''
'''
f = ->
switch 2
when 1
b = 2
b
else
b
'''
,
code: '''
React = require("react/addons")
cx = React.addons.classSet
'''
globals: require: no
,
'''
v = 1
x = -> return v
'''
'''
import * as y from "./other.js"
y()
'''
'''
import y from "./other.js"
y()
'''
'''
import {x as y} from "./other.js"
y()
'''
'''
x = null
export {x}
'''
'''
x = null
export {x as v}
'''
'export {x} from "./other.js"'
'export {x as v} from "./other.js"'
'''
class Test
myFunction: ->
return true
'''
# 'class Test { get flag() { return true; }}'
'''
Test = class
myFunction: ->
return true
'''
,
code: '''
doStuff = null
{x: y} = {x: 1}
doStuff(y)
'''
,
'foo = ({x: y}) -> y'
# those are the same as `no-undef`.
'''
!(f = ->)
f
'''
'''
f = foo = ->
foo()
exports = { f: foo }
'''
'f = => x'
"eslint = require('eslint')"
'f = (a) -> a[b]'
'f = -> b.a'
'a = { foo: bar }'
'a = foo: foo'
'a = { bar: 7, foo: bar }'
'a = arguments'
'''
x = ->
a = arguments
'''
'''
z = (b) ->
a = b
'''
'''
z = ->
b = null
a = b
'''
'''
f = ->
try
catch e
e
'''
,
# https://github.com/eslint/eslint/issues/2253
code: '''
###global React###
{PropTypes, addons: {PureRenderMixin}} = React
Test = React.createClass({mixins: [PureRenderMixin]})
'''
,
code: '''
###global prevState###
{ virtualSize: prevVirtualSize = 0 } = prevState
'''
,
code: '''
{ dummy: { data, isLoading }, auth: { isLoggedIn } } = @props
'''
,
# https://github.com/eslint/eslint/issues/2747
'''
a = (n) ->
if n > 0 then b(n - 1) else "a"
b = (n) ->
if n > 0 then a(n - 1) else "b"
'''
# https://github.com/eslint/eslint/issues/2967
'''
(-> foo())()
foo = ->
'''
'''
do -> foo()
foo = ->
'''
'''
for i in []
;
'''
'''
for i, j in []
i + j
'''
'''
i for i in []
'''
]
invalid: [
code: '''
f = ->
try
a = 0
catch e
b = a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
a = ->
for b of {}
c = b
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
a = ->
for b from {}
c = b
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
a = ->
c = b for b in []
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
f = ->
switch 2
when 1
b = 2
b
else
b
b
'''
errors: [messageId: 'outOfScope', data: {name: 'b'}, type: 'Identifier']
,
code: '''
for a in []
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
for a of {}
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
for a from []
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
if yes
a = null
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
if yes
a = 1
else
a = 2
'''
errors: [
messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier'
# ,
# messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier'
]
,
code: '''
for i in []
;
for i in []
;
'''
errors: [
messageId: 'outOfScope', data: {name: 'i'}, type: 'Identifier'
,
messageId: 'outOfScope', data: {name: 'i'}, type: 'Identifier'
]
]
| true | ###*
# @fileoverview Tests for block-scoped-var rule
# @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/block-scoped-var'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'block-scoped-var', rule,
valid: [
# See issue https://github.com/eslint/eslint/issues/2242
code: '''
f = ->
f()
exports = { f: f }
'''
,
'!(f = -> f)'
'''
f = ->
a = true
b = a
'''
'''
a = null
f = ->
b = a
'''
'f = (a) ->'
'!((a) ->)'
'!(f = (a) ->)'
'f = (a) -> b = a'
'!(f = (a) -> b = a)'
'f = -> g = f'
'''
f = ->
g = ->
f = g
'''
'''
f = ->
g()
g = ->
'''
'''
if yes
a = 1
a
'''
'''
a = null
if yes
a
'''
'''
for i in [0...10]
i
'''
'''
i for i in [0...10]
'''
'''
i = null
for [0...10]
i
'''
,
code: '''
myFunc = (foo) ->
"use strict"
{ bar } = foo
bar.hello()
'''
,
code: '''
myFunc = (foo) ->
"use strict"
[ bar ] = foo
bar.hello()
'''
,
code: 'myFunc = (...foo) -> return foo'
,
code: '''
class Foo
export default Foo
'''
,
code: 'new Date', globals: Date: no
,
code: 'new Date', globals: {}
,
code: "eslint = require('eslint')", globals: require: no
,
code: 'fun = ({x}) -> return x'
,
code: 'fun = ([,x]) -> x'
,
'f = (a) -> return a.b'
'a = { "foo": 3 }'
'a = { foo: 3 }'
'a = { foo: 3, bar: 5 }'
# 'a = { set foo(a){}, get bar(){} };'
'f = (a) -> arguments[0]'
'''
f = ->
a = f
'''
'''
f = ->
for a in {}
a
'''
'''
f = ->
a for a in {}
'''
'''
f = ->
switch 2
when 1
b = 2
b
else
b
'''
,
code: '''
React = require("react/addons")
cx = React.addons.classSet
'''
globals: require: no
,
'''
v = 1
x = -> return v
'''
'''
import * as y from "./other.js"
y()
'''
'''
import y from "./other.js"
y()
'''
'''
import {x as y} from "./other.js"
y()
'''
'''
x = null
export {x}
'''
'''
x = null
export {x as v}
'''
'export {x} from "./other.js"'
'export {x as v} from "./other.js"'
'''
class Test
myFunction: ->
return true
'''
# 'class Test { get flag() { return true; }}'
'''
Test = class
myFunction: ->
return true
'''
,
code: '''
doStuff = null
{x: y} = {x: 1}
doStuff(y)
'''
,
'foo = ({x: y}) -> y'
# those are the same as `no-undef`.
'''
!(f = ->)
f
'''
'''
f = foo = ->
foo()
exports = { f: foo }
'''
'f = => x'
"eslint = require('eslint')"
'f = (a) -> a[b]'
'f = -> b.a'
'a = { foo: bar }'
'a = foo: foo'
'a = { bar: 7, foo: bar }'
'a = arguments'
'''
x = ->
a = arguments
'''
'''
z = (b) ->
a = b
'''
'''
z = ->
b = null
a = b
'''
'''
f = ->
try
catch e
e
'''
,
# https://github.com/eslint/eslint/issues/2253
code: '''
###global React###
{PropTypes, addons: {PureRenderMixin}} = React
Test = React.createClass({mixins: [PureRenderMixin]})
'''
,
code: '''
###global prevState###
{ virtualSize: prevVirtualSize = 0 } = prevState
'''
,
code: '''
{ dummy: { data, isLoading }, auth: { isLoggedIn } } = @props
'''
,
# https://github.com/eslint/eslint/issues/2747
'''
a = (n) ->
if n > 0 then b(n - 1) else "a"
b = (n) ->
if n > 0 then a(n - 1) else "b"
'''
# https://github.com/eslint/eslint/issues/2967
'''
(-> foo())()
foo = ->
'''
'''
do -> foo()
foo = ->
'''
'''
for i in []
;
'''
'''
for i, j in []
i + j
'''
'''
i for i in []
'''
]
invalid: [
code: '''
f = ->
try
a = 0
catch e
b = a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
a = ->
for b of {}
c = b
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
a = ->
for b from {}
c = b
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
a = ->
c = b for b in []
c
'''
errors: [messageId: 'outOfScope', data: {name: 'c'}, type: 'Identifier']
,
code: '''
f = ->
switch 2
when 1
b = 2
b
else
b
b
'''
errors: [messageId: 'outOfScope', data: {name: 'b'}, type: 'Identifier']
,
code: '''
for a in []
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
for a of {}
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
for a from []
;
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
if yes
a = null
a
'''
errors: [messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier']
,
code: '''
if yes
a = 1
else
a = 2
'''
errors: [
messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier'
# ,
# messageId: 'outOfScope', data: {name: 'a'}, type: 'Identifier'
]
,
code: '''
for i in []
;
for i in []
;
'''
errors: [
messageId: 'outOfScope', data: {name: 'i'}, type: 'Identifier'
,
messageId: 'outOfScope', data: {name: 'i'}, type: 'Identifier'
]
]
|
[
{
"context": " \"server_id\": @guild_id,\n \"user_id\": @user_id,\n \"session_id\": @session_id,\n \"toke",
"end": 1721,
"score": 0.997366189956665,
"start": 1713,
"tag": "USERNAME",
"value": "@user_id"
},
{
"context": " \"session_id\": @session_id,\... | discordClient/voice/voiceHandler.coffee | motorlatitude/MotorBot | 4 | u = require('../utils.coffee')
utils = new u()
Constants = require './../constants.coffee'
ws = require 'ws'
zlib = require 'zlib'
fs = require 'fs'
Opus = require 'cjopus'
UDPClient = require './udpClient'
audioPlayer = require './AudioPlayer.coffee'
VoicePacket = require './voicePacket.coffee'
class VoiceConnection
###
# PRIVATE METHODS
###
constructor: (@discordClient) ->
utils.debug("New Voice Connection Started")
@sequence = 0
@timestamp = 0
@timestamp_inc = (48000 / 100) * 2;
connect: (params) ->
@token = params.token
@guild_id = params.guild_id
@endpoint = params.endpoint
@user_id = @discordClient.internals.user_id
@session_id = @discordClient.internals.session_id
@localPort = undefined
@vws = null
@vhb = null
@packageList = []
@streamPacketList = []
@connectTime = new Date().getTime()
@volume = 0.5
@users = {}
@pings = []
@totalPings = 0
@avgPing = 0
@bytesTransmitted = 0
@buffer_size = 0
@AudioPlayers = []
utils.debug("Generating new voice WebSocket connection")
@vws = new ws("wss://" + @endpoint.split(":")[0]) #using version 3 now
self = @
@opusEncoder = new Opus.OpusEncoder(48000, 2)
@vws.once('open', () -> self.voiceGatewayOpen())
@vws.once('close', () -> self.voiceGatewayClose())
@vws.once('error', (err) -> self.voiceGatewayError(err))
@vws.on('message', (msg, flags) -> self.voiceGatewayMessage(msg, flags))
voiceGatewayOpen: (guild_id) ->
utils.debug("Connected to Voice Gateway Server: " + @endpoint, "info")
#send identity package
idpackage = {
"op": 0
"d": {
"server_id": @guild_id,
"user_id": @user_id,
"session_id": @session_id,
"token": @token
}
}
@vws.send(JSON.stringify(idpackage))
voiceGatewayClose: () ->
utils.debug("Voice gateway server is CLOSED", "warn")
#reset voice data, we need full reconnect
clearInterval(@vhb)
voiceGatewayError: (err, guild_id) ->
utils.debug("Voice gateway server encountered an error: " + err.toString(), "error")
voiceGatewayMessage: (data, flags) ->
msg = if flags.binary then JSON.parse(zlib.inflateSync(data).toString()) else JSON.parse(data)
switch msg.op
when Constants.voice.PacketCodes.READY then @handleReady(msg)
when Constants.voice.PacketCodes.HEARTBEAT then @handleHeartbeat(msg)
when Constants.voice.PacketCodes.SPEAKING then @handleSpeaking(msg)
when Constants.voice.PacketCodes.SESSION_DESC then @handleSession(msg)
when 8 then utils.debug("Got Heartbeat Interval", "info")
else
utils.debug("Unhandled Voice OP: " + msg.op, "warn")
handleReady: (msg) ->
#start HB
self = @
@vhb = setInterval(() ->
hbpackage = {
"op": 3,
"d": null
}
self.gatewayPing = new Date().getTime()
self.vws.send(JSON.stringify(hbpackage))
, msg.d.heartbeat_interval)
@ssrc = msg.d.ssrc
@port = msg.d.port
conn = {
"ssrc": msg.d.ssrc
"port": msg.d.port
"endpoint": @endpoint.split(":")[0]
}
#start UDP Connection
@udpClient = new UDPClient(@)
@udpClient.init(conn)
@udpClient.on('ready', (localIP, localPort) ->
self.localPort = localPort
selectProtocolPayload = {
"op": 1
"d": {
"protocol": "udp"
"data": {
"address": localIP
"port": parseInt(localPort)
"mode": "xsalsa20_poly1305"
}
}
}
self.vws.send(JSON.stringify(selectProtocolPayload))
self.packageData(new Date().getTime(), 1)
self.send(new Date().getTime(), 1)
)
handleSpeaking: (msg) ->
@users[msg.d.user_id] = {ssrc: msg.d.ssrc} #for receiving voice data
@discordClient.emit("voiceUpdate_Speaking", msg.d)
handleHeartbeat: (msg, guild_id) ->
ping = new Date().getTime() - @gatewayPing
@pings.push(ping)
@totalPings += ping
@avgPing = @totalPings / @pings.length
utils.debug("Voice Heartbeat Sent (" + ping + "ms - average: " + (Math.round(@avgPing * 100)/100) + "ms)")
handleSession: (msg) ->
@secretKey = msg.d.secret_key
@mode = msg.d.mode
utils.debug("Received Voice Session Description")
setSpeaking: (value) ->
speakingPackage = {
"op": 5
"d": {
"speaking": value
"delay": 0
"ssrc": @ssrc
}
}
if @vws.readyState == @vws.OPEN
@vws.send(JSON.stringify(speakingPackage))
else
utils.debug("Websocket Connection not open to set bot to speaking", "warn")
packageData: (startTime, cnt) ->
channels = 2 #just assume it's 2 for now
self = @
streamPacket = @streamPacketList.shift()
if streamPacket
streamBuff = streamPacket
@sequence = if (@sequence + 1) < 65535 then @sequence += 1 else @sequence = 0
@timestamp = if (@timestamp + @timestamp_inc) < 4294967295 then @timestamp += @timestamp_inc else @timestamp = 0
out = new Buffer(streamBuff.length);
i = 0
while i < streamBuff.length
if i >= streamBuff.length - 1
break
multiplier = Math.pow(self.volume, 1.660964);
uint = Math.floor(multiplier * streamBuff.readInt16LE(i))
# Ensure value stays within 16bit
if uint > 32767 || uint < -32767
utils.debug("Audio Peaking, Lowering Volume","warn")
self.volume = self.volume - 0.05 #lower volume automatically if we're peaking
uint = Math.min(32767, uint)
uint = Math.max(-32767, uint)
# Write 2 new bytes into other buffer;
out.writeInt16LE(uint, i)
i += 2
streamBuff = out;
encoded = @opusEncoder.encode(streamBuff, 1920*channels)
audioPacket = new VoicePacket(encoded, @)
@packageList.push(audioPacket)
nextTime = startTime + (cnt + 1) * 20
return setTimeout(() ->
self.packageData(startTime, cnt + 1)
, 20 + (nextTime - new Date().getTime()));
else
return setTimeout(() ->
self.packageData(startTime, cnt)
, 200);
send: (startTime, cnt) ->
self = @
packet = @packageList.shift()
if packet
self.bytesTransmitted += packet.length
@udpClient.send(packet, 0, packet.length, @port, @endpoint.split(":")[0], (err, bytes) ->
if err
utils.debug("Error Sending Voice Packet: " + err.toString(), "error")
)
return setTimeout(() ->
self.send(startTime, (cnt + 1))
, 1)
playFromStream: (stream) ->
self = @
if @AudioPlayers.length > 0
utils.debug("MORE THAN ONE AUDIO PLAYER FOR THIS VOICE HANDLER!!!!")
for a in @AudioPlayers
if a
a.stop_kill()
i = self.AudioPlayers.indexOf(a)
if i > -1
@AudioPlayers.splice(i,1)
@streamPacketList = []
ah = new audioPlayer(stream, @, @discordClient)
@AudioPlayers.push(ah)
return ah
else
ah = new audioPlayer(stream, @, @discordClient)
@AudioPlayers.push(ah)
return ah
playFromFile: (file) ->
ps = new audioPlayer(fs.createReadStream(file), @, @discordClient)
return ps
module.exports = VoiceConnection
| 41803 | u = require('../utils.coffee')
utils = new u()
Constants = require './../constants.coffee'
ws = require 'ws'
zlib = require 'zlib'
fs = require 'fs'
Opus = require 'cjopus'
UDPClient = require './udpClient'
audioPlayer = require './AudioPlayer.coffee'
VoicePacket = require './voicePacket.coffee'
class VoiceConnection
###
# PRIVATE METHODS
###
constructor: (@discordClient) ->
utils.debug("New Voice Connection Started")
@sequence = 0
@timestamp = 0
@timestamp_inc = (48000 / 100) * 2;
connect: (params) ->
@token = params.token
@guild_id = params.guild_id
@endpoint = params.endpoint
@user_id = @discordClient.internals.user_id
@session_id = @discordClient.internals.session_id
@localPort = undefined
@vws = null
@vhb = null
@packageList = []
@streamPacketList = []
@connectTime = new Date().getTime()
@volume = 0.5
@users = {}
@pings = []
@totalPings = 0
@avgPing = 0
@bytesTransmitted = 0
@buffer_size = 0
@AudioPlayers = []
utils.debug("Generating new voice WebSocket connection")
@vws = new ws("wss://" + @endpoint.split(":")[0]) #using version 3 now
self = @
@opusEncoder = new Opus.OpusEncoder(48000, 2)
@vws.once('open', () -> self.voiceGatewayOpen())
@vws.once('close', () -> self.voiceGatewayClose())
@vws.once('error', (err) -> self.voiceGatewayError(err))
@vws.on('message', (msg, flags) -> self.voiceGatewayMessage(msg, flags))
voiceGatewayOpen: (guild_id) ->
utils.debug("Connected to Voice Gateway Server: " + @endpoint, "info")
#send identity package
idpackage = {
"op": 0
"d": {
"server_id": @guild_id,
"user_id": @user_id,
"session_id": @session_id,
"token":<PASSWORD> @token
}
}
@vws.send(JSON.stringify(idpackage))
voiceGatewayClose: () ->
utils.debug("Voice gateway server is CLOSED", "warn")
#reset voice data, we need full reconnect
clearInterval(@vhb)
voiceGatewayError: (err, guild_id) ->
utils.debug("Voice gateway server encountered an error: " + err.toString(), "error")
voiceGatewayMessage: (data, flags) ->
msg = if flags.binary then JSON.parse(zlib.inflateSync(data).toString()) else JSON.parse(data)
switch msg.op
when Constants.voice.PacketCodes.READY then @handleReady(msg)
when Constants.voice.PacketCodes.HEARTBEAT then @handleHeartbeat(msg)
when Constants.voice.PacketCodes.SPEAKING then @handleSpeaking(msg)
when Constants.voice.PacketCodes.SESSION_DESC then @handleSession(msg)
when 8 then utils.debug("Got Heartbeat Interval", "info")
else
utils.debug("Unhandled Voice OP: " + msg.op, "warn")
handleReady: (msg) ->
#start HB
self = @
@vhb = setInterval(() ->
hbpackage = {
"op": 3,
"d": null
}
self.gatewayPing = new Date().getTime()
self.vws.send(JSON.stringify(hbpackage))
, msg.d.heartbeat_interval)
@ssrc = msg.d.ssrc
@port = msg.d.port
conn = {
"ssrc": msg.d.ssrc
"port": msg.d.port
"endpoint": @endpoint.split(":")[0]
}
#start UDP Connection
@udpClient = new UDPClient(@)
@udpClient.init(conn)
@udpClient.on('ready', (localIP, localPort) ->
self.localPort = localPort
selectProtocolPayload = {
"op": 1
"d": {
"protocol": "udp"
"data": {
"address": localIP
"port": parseInt(localPort)
"mode": "xsalsa20_poly1305"
}
}
}
self.vws.send(JSON.stringify(selectProtocolPayload))
self.packageData(new Date().getTime(), 1)
self.send(new Date().getTime(), 1)
)
handleSpeaking: (msg) ->
@users[msg.d.user_id] = {ssrc: msg.d.ssrc} #for receiving voice data
@discordClient.emit("voiceUpdate_Speaking", msg.d)
handleHeartbeat: (msg, guild_id) ->
ping = new Date().getTime() - @gatewayPing
@pings.push(ping)
@totalPings += ping
@avgPing = @totalPings / @pings.length
utils.debug("Voice Heartbeat Sent (" + ping + "ms - average: " + (Math.round(@avgPing * 100)/100) + "ms)")
handleSession: (msg) ->
@secretKey = msg.d.secret_key
@mode = msg.d.mode
utils.debug("Received Voice Session Description")
setSpeaking: (value) ->
speakingPackage = {
"op": 5
"d": {
"speaking": value
"delay": 0
"ssrc": @ssrc
}
}
if @vws.readyState == @vws.OPEN
@vws.send(JSON.stringify(speakingPackage))
else
utils.debug("Websocket Connection not open to set bot to speaking", "warn")
packageData: (startTime, cnt) ->
channels = 2 #just assume it's 2 for now
self = @
streamPacket = @streamPacketList.shift()
if streamPacket
streamBuff = streamPacket
@sequence = if (@sequence + 1) < 65535 then @sequence += 1 else @sequence = 0
@timestamp = if (@timestamp + @timestamp_inc) < 4294967295 then @timestamp += @timestamp_inc else @timestamp = 0
out = new Buffer(streamBuff.length);
i = 0
while i < streamBuff.length
if i >= streamBuff.length - 1
break
multiplier = Math.pow(self.volume, 1.660964);
uint = Math.floor(multiplier * streamBuff.readInt16LE(i))
# Ensure value stays within 16bit
if uint > 32767 || uint < -32767
utils.debug("Audio Peaking, Lowering Volume","warn")
self.volume = self.volume - 0.05 #lower volume automatically if we're peaking
uint = Math.min(32767, uint)
uint = Math.max(-32767, uint)
# Write 2 new bytes into other buffer;
out.writeInt16LE(uint, i)
i += 2
streamBuff = out;
encoded = @opusEncoder.encode(streamBuff, 1920*channels)
audioPacket = new VoicePacket(encoded, @)
@packageList.push(audioPacket)
nextTime = startTime + (cnt + 1) * 20
return setTimeout(() ->
self.packageData(startTime, cnt + 1)
, 20 + (nextTime - new Date().getTime()));
else
return setTimeout(() ->
self.packageData(startTime, cnt)
, 200);
send: (startTime, cnt) ->
self = @
packet = @packageList.shift()
if packet
self.bytesTransmitted += packet.length
@udpClient.send(packet, 0, packet.length, @port, @endpoint.split(":")[0], (err, bytes) ->
if err
utils.debug("Error Sending Voice Packet: " + err.toString(), "error")
)
return setTimeout(() ->
self.send(startTime, (cnt + 1))
, 1)
playFromStream: (stream) ->
self = @
if @AudioPlayers.length > 0
utils.debug("MORE THAN ONE AUDIO PLAYER FOR THIS VOICE HANDLER!!!!")
for a in @AudioPlayers
if a
a.stop_kill()
i = self.AudioPlayers.indexOf(a)
if i > -1
@AudioPlayers.splice(i,1)
@streamPacketList = []
ah = new audioPlayer(stream, @, @discordClient)
@AudioPlayers.push(ah)
return ah
else
ah = new audioPlayer(stream, @, @discordClient)
@AudioPlayers.push(ah)
return ah
playFromFile: (file) ->
ps = new audioPlayer(fs.createReadStream(file), @, @discordClient)
return ps
module.exports = VoiceConnection
| true | u = require('../utils.coffee')
utils = new u()
Constants = require './../constants.coffee'
ws = require 'ws'
zlib = require 'zlib'
fs = require 'fs'
Opus = require 'cjopus'
UDPClient = require './udpClient'
audioPlayer = require './AudioPlayer.coffee'
VoicePacket = require './voicePacket.coffee'
class VoiceConnection
###
# PRIVATE METHODS
###
constructor: (@discordClient) ->
utils.debug("New Voice Connection Started")
@sequence = 0
@timestamp = 0
@timestamp_inc = (48000 / 100) * 2;
connect: (params) ->
@token = params.token
@guild_id = params.guild_id
@endpoint = params.endpoint
@user_id = @discordClient.internals.user_id
@session_id = @discordClient.internals.session_id
@localPort = undefined
@vws = null
@vhb = null
@packageList = []
@streamPacketList = []
@connectTime = new Date().getTime()
@volume = 0.5
@users = {}
@pings = []
@totalPings = 0
@avgPing = 0
@bytesTransmitted = 0
@buffer_size = 0
@AudioPlayers = []
utils.debug("Generating new voice WebSocket connection")
@vws = new ws("wss://" + @endpoint.split(":")[0]) #using version 3 now
self = @
@opusEncoder = new Opus.OpusEncoder(48000, 2)
@vws.once('open', () -> self.voiceGatewayOpen())
@vws.once('close', () -> self.voiceGatewayClose())
@vws.once('error', (err) -> self.voiceGatewayError(err))
@vws.on('message', (msg, flags) -> self.voiceGatewayMessage(msg, flags))
voiceGatewayOpen: (guild_id) ->
utils.debug("Connected to Voice Gateway Server: " + @endpoint, "info")
#send identity package
idpackage = {
"op": 0
"d": {
"server_id": @guild_id,
"user_id": @user_id,
"session_id": @session_id,
"token":PI:PASSWORD:<PASSWORD>END_PI @token
}
}
@vws.send(JSON.stringify(idpackage))
voiceGatewayClose: () ->
utils.debug("Voice gateway server is CLOSED", "warn")
#reset voice data, we need full reconnect
clearInterval(@vhb)
voiceGatewayError: (err, guild_id) ->
utils.debug("Voice gateway server encountered an error: " + err.toString(), "error")
voiceGatewayMessage: (data, flags) ->
msg = if flags.binary then JSON.parse(zlib.inflateSync(data).toString()) else JSON.parse(data)
switch msg.op
when Constants.voice.PacketCodes.READY then @handleReady(msg)
when Constants.voice.PacketCodes.HEARTBEAT then @handleHeartbeat(msg)
when Constants.voice.PacketCodes.SPEAKING then @handleSpeaking(msg)
when Constants.voice.PacketCodes.SESSION_DESC then @handleSession(msg)
when 8 then utils.debug("Got Heartbeat Interval", "info")
else
utils.debug("Unhandled Voice OP: " + msg.op, "warn")
handleReady: (msg) ->
#start HB
self = @
@vhb = setInterval(() ->
hbpackage = {
"op": 3,
"d": null
}
self.gatewayPing = new Date().getTime()
self.vws.send(JSON.stringify(hbpackage))
, msg.d.heartbeat_interval)
@ssrc = msg.d.ssrc
@port = msg.d.port
conn = {
"ssrc": msg.d.ssrc
"port": msg.d.port
"endpoint": @endpoint.split(":")[0]
}
#start UDP Connection
@udpClient = new UDPClient(@)
@udpClient.init(conn)
@udpClient.on('ready', (localIP, localPort) ->
self.localPort = localPort
selectProtocolPayload = {
"op": 1
"d": {
"protocol": "udp"
"data": {
"address": localIP
"port": parseInt(localPort)
"mode": "xsalsa20_poly1305"
}
}
}
self.vws.send(JSON.stringify(selectProtocolPayload))
self.packageData(new Date().getTime(), 1)
self.send(new Date().getTime(), 1)
)
handleSpeaking: (msg) ->
@users[msg.d.user_id] = {ssrc: msg.d.ssrc} #for receiving voice data
@discordClient.emit("voiceUpdate_Speaking", msg.d)
handleHeartbeat: (msg, guild_id) ->
ping = new Date().getTime() - @gatewayPing
@pings.push(ping)
@totalPings += ping
@avgPing = @totalPings / @pings.length
utils.debug("Voice Heartbeat Sent (" + ping + "ms - average: " + (Math.round(@avgPing * 100)/100) + "ms)")
handleSession: (msg) ->
@secretKey = msg.d.secret_key
@mode = msg.d.mode
utils.debug("Received Voice Session Description")
setSpeaking: (value) ->
speakingPackage = {
"op": 5
"d": {
"speaking": value
"delay": 0
"ssrc": @ssrc
}
}
if @vws.readyState == @vws.OPEN
@vws.send(JSON.stringify(speakingPackage))
else
utils.debug("Websocket Connection not open to set bot to speaking", "warn")
packageData: (startTime, cnt) ->
channels = 2 #just assume it's 2 for now
self = @
streamPacket = @streamPacketList.shift()
if streamPacket
streamBuff = streamPacket
@sequence = if (@sequence + 1) < 65535 then @sequence += 1 else @sequence = 0
@timestamp = if (@timestamp + @timestamp_inc) < 4294967295 then @timestamp += @timestamp_inc else @timestamp = 0
out = new Buffer(streamBuff.length);
i = 0
while i < streamBuff.length
if i >= streamBuff.length - 1
break
multiplier = Math.pow(self.volume, 1.660964);
uint = Math.floor(multiplier * streamBuff.readInt16LE(i))
# Ensure value stays within 16bit
if uint > 32767 || uint < -32767
utils.debug("Audio Peaking, Lowering Volume","warn")
self.volume = self.volume - 0.05 #lower volume automatically if we're peaking
uint = Math.min(32767, uint)
uint = Math.max(-32767, uint)
# Write 2 new bytes into other buffer;
out.writeInt16LE(uint, i)
i += 2
streamBuff = out;
encoded = @opusEncoder.encode(streamBuff, 1920*channels)
audioPacket = new VoicePacket(encoded, @)
@packageList.push(audioPacket)
nextTime = startTime + (cnt + 1) * 20
return setTimeout(() ->
self.packageData(startTime, cnt + 1)
, 20 + (nextTime - new Date().getTime()));
else
return setTimeout(() ->
self.packageData(startTime, cnt)
, 200);
send: (startTime, cnt) ->
self = @
packet = @packageList.shift()
if packet
self.bytesTransmitted += packet.length
@udpClient.send(packet, 0, packet.length, @port, @endpoint.split(":")[0], (err, bytes) ->
if err
utils.debug("Error Sending Voice Packet: " + err.toString(), "error")
)
return setTimeout(() ->
self.send(startTime, (cnt + 1))
, 1)
playFromStream: (stream) ->
self = @
if @AudioPlayers.length > 0
utils.debug("MORE THAN ONE AUDIO PLAYER FOR THIS VOICE HANDLER!!!!")
for a in @AudioPlayers
if a
a.stop_kill()
i = self.AudioPlayers.indexOf(a)
if i > -1
@AudioPlayers.splice(i,1)
@streamPacketList = []
ah = new audioPlayer(stream, @, @discordClient)
@AudioPlayers.push(ah)
return ah
else
ah = new audioPlayer(stream, @, @discordClient)
@AudioPlayers.push(ah)
return ah
playFromFile: (file) ->
ps = new audioPlayer(fs.createReadStream(file), @, @discordClient)
return ps
module.exports = VoiceConnection
|
[
{
"context": " macPlist:\n NSHumanReadableCopyright: 'aluxian.com'\n CFBundleIdentifier: 'com.aluxian.print",
"end": 1891,
"score": 0.799946665763855,
"start": 1880,
"tag": "EMAIL",
"value": "aluxian.com"
},
{
"context": "ld:osx64'], ->\n shelljs.exec 'codesign -... | gulpfile.coffee | printsepeti/desktop | 0 | gulp = require 'gulp'
shelljs = require 'shelljs'
mergeStream = require 'merge-stream'
runSequence = require 'run-sequence'
manifest = require './package.json'
$ = require('gulp-load-plugins')()
# Remove directories used by the tasks
gulp.task 'clean', ->
shelljs.rm '-rf', './build'
shelljs.rm '-rf', './dist'
# Build for each platform; on OSX/Linux, you need Wine installed to build win32 (or remove winIco below)
['win32', 'osx64', 'linux32', 'linux64'].forEach (platform) ->
gulp.task 'build:' + platform, ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": false', '"toolbar": true', './src/package.json'
gulp.src './src/**'
.pipe $.nodeWebkitBuilder
platforms: [platform]
version: '0.12.2'
winIco: if process.argv.indexOf('--noicon') > 0 then undefined else './assets-windows/icon.ico'
macIcns: './assets-osx/icon.icns'
macZip: true
macPlist:
NSHumanReadableCopyright: 'aluxian.com'
CFBundleIdentifier: 'com.aluxian.printsepeti'
.on 'end', ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": true', '"toolbar": false', './src/package.json'
# Build for each platform; on OSX/Linux, you need Wine installed to build win32 (or remove winIco below)
['win32', 'osx64', 'linux32', 'linux64'].forEach (platform) ->
gulp.task 'build:' + platform, ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": false', '"toolbar": true', './src/package.json'
gulp.src './src/**'
.pipe $.nodeWebkitBuilder
platforms: [platform]
version: '0.12.2'
winIco: if process.argv.indexOf('--noicon') > 0 then undefined else './assets-windows/icon.ico'
macIcns: './assets-osx/icon.icns'
macZip: true
macPlist:
NSHumanReadableCopyright: 'aluxian.com'
CFBundleIdentifier: 'com.aluxian.printsepeti'
.on 'end', ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": true', '"toolbar": false', './src/package.json'
# Only runs on OSX (requires XCode properly configured)
gulp.task 'sign:osx64', ['build:osx64'], ->
shelljs.exec 'codesign -v -f -s "Alexandru Rosianu Apps" ./build/printsepeti/osx64/printsepeti.app/Contents/Frameworks/*'
shelljs.exec 'codesign -v -f -s "Alexandru Rosianu Apps" ./build/printsepeti/osx64/printsepeti.app'
shelljs.exec 'codesign -v --display ./build/printsepeti/osx64/printsepeti.app'
shelljs.exec 'codesign -v --verify ./build/printsepeti/osx64/printsepeti.app'
# Create a DMG for osx64; only works on OS X because of appdmg
gulp.task 'pack:osx64', ['sign:osx64'], ->
shelljs.mkdir '-p', './dist' # appdmg fails if ./dist doesn't exist
shelljs.rm '-f', './dist/printsepeti.dmg' # appdmg fails if the dmg already exists
gulp.src []
.pipe require('gulp-appdmg')
source: './assets-osx/dmg.json'
target: './dist/PrintSepeti.dmg'
# Create a nsis installer for win32; must have `makensis` installed
gulp.task 'pack:win32', ['build:win32'], ->
shelljs.exec 'makensis ./assets-windows/installer.nsi'
# Create packages for linux
[32, 64].forEach (arch) ->
['deb', 'rpm'].forEach (target) ->
gulp.task "pack:linux#{arch}:#{target}", ['build:linux' + arch], ->
shelljs.rm '-rf', './build/linux'
move_opt = gulp.src [
'./assets-linux/printsepeti.desktop'
'./assets-linux/after-install.sh'
'./assets-linux/after-remove.sh'
'./build/printsepeti/linux' + arch + '/**'
]
.pipe gulp.dest './build/linux/opt/printsepeti'
move_png48 = gulp.src './assets-linux/icons/48/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/48x48/apps'
move_png256 = gulp.src './assets-linux/icons/256/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/256x256/apps'
move_svg = gulp.src './assets-linux/icons/scalable/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/scalable/apps'
mergeStream move_opt, move_png48, move_png256, move_svg
.on 'end', ->
shelljs.cd './build/linux'
port = if arch == 32 then 'i386' else 'amd64'
output = "../../dist/printsepeti#{arch}.#{target}"
shelljs.mkdir '-p', '../../dist' # it fails if the dir doesn't exist
shelljs.rm '-f', output # it fails if the package already exists
shelljs.exec "fpm -s dir -t #{target} -a #{port} -n printsepeti --after-install ./opt/printsepeti/after-install.sh --after-remove ./opt/printsepeti/after-remove.sh --license MIT --category Chat --url \"https://printsepeti.com\" --description \"Printsepeti desktop app..\" -m \"Printsepeti <info@printsepeti.com>\" -p #{output} -v #{manifest.version} ."
shelljs.cd '../..'
# Make packages for all platforms
gulp.task 'pack:all', (callback) ->
runSequence 'pack:osx64', 'pack:win32', 'pack:linux32:deb', 'pack:linux64:deb', callback
# Build osx64 and run it
gulp.task 'run:osx64', ['build:osx64'], ->
shelljs.exec 'open ./build/printsepeti/osx64/printsepeti.app'
# Run osx64 without building
gulp.task 'open:osx64', ->
shelljs.exec 'open ./build/printsepeti/osx64/printsepeti.app'
# Upload release to GitHub
gulp.task 'release', ['pack:all'], (callback) ->
gulp.src './dist/*'
.pipe $.githubRelease
draft: true
manifest: manifest
# Make packages for all platforms by default
gulp.task 'default', ['pack:all']
| 80112 | gulp = require 'gulp'
shelljs = require 'shelljs'
mergeStream = require 'merge-stream'
runSequence = require 'run-sequence'
manifest = require './package.json'
$ = require('gulp-load-plugins')()
# Remove directories used by the tasks
gulp.task 'clean', ->
shelljs.rm '-rf', './build'
shelljs.rm '-rf', './dist'
# Build for each platform; on OSX/Linux, you need Wine installed to build win32 (or remove winIco below)
['win32', 'osx64', 'linux32', 'linux64'].forEach (platform) ->
gulp.task 'build:' + platform, ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": false', '"toolbar": true', './src/package.json'
gulp.src './src/**'
.pipe $.nodeWebkitBuilder
platforms: [platform]
version: '0.12.2'
winIco: if process.argv.indexOf('--noicon') > 0 then undefined else './assets-windows/icon.ico'
macIcns: './assets-osx/icon.icns'
macZip: true
macPlist:
NSHumanReadableCopyright: 'aluxian.com'
CFBundleIdentifier: 'com.aluxian.printsepeti'
.on 'end', ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": true', '"toolbar": false', './src/package.json'
# Build for each platform; on OSX/Linux, you need Wine installed to build win32 (or remove winIco below)
['win32', 'osx64', 'linux32', 'linux64'].forEach (platform) ->
gulp.task 'build:' + platform, ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": false', '"toolbar": true', './src/package.json'
gulp.src './src/**'
.pipe $.nodeWebkitBuilder
platforms: [platform]
version: '0.12.2'
winIco: if process.argv.indexOf('--noicon') > 0 then undefined else './assets-windows/icon.ico'
macIcns: './assets-osx/icon.icns'
macZip: true
macPlist:
NSHumanReadableCopyright: '<EMAIL>'
CFBundleIdentifier: 'com.aluxian.printsepeti'
.on 'end', ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": true', '"toolbar": false', './src/package.json'
# Only runs on OSX (requires XCode properly configured)
gulp.task 'sign:osx64', ['build:osx64'], ->
shelljs.exec 'codesign -v -f -s "<NAME>" ./build/printsepeti/osx64/printsepeti.app/Contents/Frameworks/*'
shelljs.exec 'codesign -v -f -s "<NAME>" ./build/printsepeti/osx64/printsepeti.app'
shelljs.exec 'codesign -v --display ./build/printsepeti/osx64/printsepeti.app'
shelljs.exec 'codesign -v --verify ./build/printsepeti/osx64/printsepeti.app'
# Create a DMG for osx64; only works on OS X because of appdmg
gulp.task 'pack:osx64', ['sign:osx64'], ->
shelljs.mkdir '-p', './dist' # appdmg fails if ./dist doesn't exist
shelljs.rm '-f', './dist/printsepeti.dmg' # appdmg fails if the dmg already exists
gulp.src []
.pipe require('gulp-appdmg')
source: './assets-osx/dmg.json'
target: './dist/PrintSepeti.dmg'
# Create a nsis installer for win32; must have `makensis` installed
gulp.task 'pack:win32', ['build:win32'], ->
shelljs.exec 'makensis ./assets-windows/installer.nsi'
# Create packages for linux
[32, 64].forEach (arch) ->
['deb', 'rpm'].forEach (target) ->
gulp.task "pack:linux#{arch}:#{target}", ['build:linux' + arch], ->
shelljs.rm '-rf', './build/linux'
move_opt = gulp.src [
'./assets-linux/printsepeti.desktop'
'./assets-linux/after-install.sh'
'./assets-linux/after-remove.sh'
'./build/printsepeti/linux' + arch + '/**'
]
.pipe gulp.dest './build/linux/opt/printsepeti'
move_png48 = gulp.src './assets-linux/icons/48/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/48x48/apps'
move_png256 = gulp.src './assets-linux/icons/256/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/256x256/apps'
move_svg = gulp.src './assets-linux/icons/scalable/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/scalable/apps'
mergeStream move_opt, move_png48, move_png256, move_svg
.on 'end', ->
shelljs.cd './build/linux'
port = if arch == 32 then 'i386' else 'amd64'
output = "../../dist/printsepeti#{arch}.#{target}"
shelljs.mkdir '-p', '../../dist' # it fails if the dir doesn't exist
shelljs.rm '-f', output # it fails if the package already exists
shelljs.exec "fpm -s dir -t #{target} -a #{port} -n printsepeti --after-install ./opt/printsepeti/after-install.sh --after-remove ./opt/printsepeti/after-remove.sh --license MIT --category Chat --url \"https://printsepeti.com\" --description \"Printsepeti desktop app..\" -m \"Printse<NAME> <<EMAIL>>\" -p #{output} -v #{manifest.version} ."
shelljs.cd '../..'
# Make packages for all platforms
gulp.task 'pack:all', (callback) ->
runSequence 'pack:osx64', 'pack:win32', 'pack:linux32:deb', 'pack:linux64:deb', callback
# Build osx64 and run it
gulp.task 'run:osx64', ['build:osx64'], ->
shelljs.exec 'open ./build/printsepeti/osx64/printsepeti.app'
# Run osx64 without building
gulp.task 'open:osx64', ->
shelljs.exec 'open ./build/printsepeti/osx64/printsepeti.app'
# Upload release to GitHub
gulp.task 'release', ['pack:all'], (callback) ->
gulp.src './dist/*'
.pipe $.githubRelease
draft: true
manifest: manifest
# Make packages for all platforms by default
gulp.task 'default', ['pack:all']
| true | gulp = require 'gulp'
shelljs = require 'shelljs'
mergeStream = require 'merge-stream'
runSequence = require 'run-sequence'
manifest = require './package.json'
$ = require('gulp-load-plugins')()
# Remove directories used by the tasks
gulp.task 'clean', ->
shelljs.rm '-rf', './build'
shelljs.rm '-rf', './dist'
# Build for each platform; on OSX/Linux, you need Wine installed to build win32 (or remove winIco below)
['win32', 'osx64', 'linux32', 'linux64'].forEach (platform) ->
gulp.task 'build:' + platform, ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": false', '"toolbar": true', './src/package.json'
gulp.src './src/**'
.pipe $.nodeWebkitBuilder
platforms: [platform]
version: '0.12.2'
winIco: if process.argv.indexOf('--noicon') > 0 then undefined else './assets-windows/icon.ico'
macIcns: './assets-osx/icon.icns'
macZip: true
macPlist:
NSHumanReadableCopyright: 'aluxian.com'
CFBundleIdentifier: 'com.aluxian.printsepeti'
.on 'end', ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": true', '"toolbar": false', './src/package.json'
# Build for each platform; on OSX/Linux, you need Wine installed to build win32 (or remove winIco below)
['win32', 'osx64', 'linux32', 'linux64'].forEach (platform) ->
gulp.task 'build:' + platform, ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": false', '"toolbar": true', './src/package.json'
gulp.src './src/**'
.pipe $.nodeWebkitBuilder
platforms: [platform]
version: '0.12.2'
winIco: if process.argv.indexOf('--noicon') > 0 then undefined else './assets-windows/icon.ico'
macIcns: './assets-osx/icon.icns'
macZip: true
macPlist:
NSHumanReadableCopyright: 'PI:EMAIL:<EMAIL>END_PI'
CFBundleIdentifier: 'com.aluxian.printsepeti'
.on 'end', ->
if process.argv.indexOf('--toolbar') > 0
shelljs.sed '-i', '"toolbar": true', '"toolbar": false', './src/package.json'
# Only runs on OSX (requires XCode properly configured)
gulp.task 'sign:osx64', ['build:osx64'], ->
shelljs.exec 'codesign -v -f -s "PI:NAME:<NAME>END_PI" ./build/printsepeti/osx64/printsepeti.app/Contents/Frameworks/*'
shelljs.exec 'codesign -v -f -s "PI:NAME:<NAME>END_PI" ./build/printsepeti/osx64/printsepeti.app'
shelljs.exec 'codesign -v --display ./build/printsepeti/osx64/printsepeti.app'
shelljs.exec 'codesign -v --verify ./build/printsepeti/osx64/printsepeti.app'
# Create a DMG for osx64; only works on OS X because of appdmg
gulp.task 'pack:osx64', ['sign:osx64'], ->
shelljs.mkdir '-p', './dist' # appdmg fails if ./dist doesn't exist
shelljs.rm '-f', './dist/printsepeti.dmg' # appdmg fails if the dmg already exists
gulp.src []
.pipe require('gulp-appdmg')
source: './assets-osx/dmg.json'
target: './dist/PrintSepeti.dmg'
# Create a nsis installer for win32; must have `makensis` installed
gulp.task 'pack:win32', ['build:win32'], ->
shelljs.exec 'makensis ./assets-windows/installer.nsi'
# Create packages for linux
[32, 64].forEach (arch) ->
['deb', 'rpm'].forEach (target) ->
gulp.task "pack:linux#{arch}:#{target}", ['build:linux' + arch], ->
shelljs.rm '-rf', './build/linux'
move_opt = gulp.src [
'./assets-linux/printsepeti.desktop'
'./assets-linux/after-install.sh'
'./assets-linux/after-remove.sh'
'./build/printsepeti/linux' + arch + '/**'
]
.pipe gulp.dest './build/linux/opt/printsepeti'
move_png48 = gulp.src './assets-linux/icons/48/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/48x48/apps'
move_png256 = gulp.src './assets-linux/icons/256/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/256x256/apps'
move_svg = gulp.src './assets-linux/icons/scalable/printsepeti.png'
.pipe gulp.dest './build/linux/usr/share/icons/hicolor/scalable/apps'
mergeStream move_opt, move_png48, move_png256, move_svg
.on 'end', ->
shelljs.cd './build/linux'
port = if arch == 32 then 'i386' else 'amd64'
output = "../../dist/printsepeti#{arch}.#{target}"
shelljs.mkdir '-p', '../../dist' # it fails if the dir doesn't exist
shelljs.rm '-f', output # it fails if the package already exists
shelljs.exec "fpm -s dir -t #{target} -a #{port} -n printsepeti --after-install ./opt/printsepeti/after-install.sh --after-remove ./opt/printsepeti/after-remove.sh --license MIT --category Chat --url \"https://printsepeti.com\" --description \"Printsepeti desktop app..\" -m \"PrintsePI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>\" -p #{output} -v #{manifest.version} ."
shelljs.cd '../..'
# Make packages for all platforms
gulp.task 'pack:all', (callback) ->
runSequence 'pack:osx64', 'pack:win32', 'pack:linux32:deb', 'pack:linux64:deb', callback
# Build osx64 and run it
gulp.task 'run:osx64', ['build:osx64'], ->
shelljs.exec 'open ./build/printsepeti/osx64/printsepeti.app'
# Run osx64 without building
gulp.task 'open:osx64', ->
shelljs.exec 'open ./build/printsepeti/osx64/printsepeti.app'
# Upload release to GitHub
gulp.task 'release', ['pack:all'], (callback) ->
gulp.src './dist/*'
.pipe $.githubRelease
draft: true
manifest: manifest
# Make packages for all platforms by default
gulp.task 'default', ['pack:all']
|
[
{
"context": "----------------------------------------\n# Author: Alexander Kravets <alex@slatestudio.com>,\n# Slate Studio (h",
"end": 107,
"score": 0.9998753666877747,
"start": 90,
"tag": "NAME",
"value": "Alexander Kravets"
},
{
"context": "--------------------\n# Author: ... | app/assets/javascripts/loft/inputs/loft-image.coffee | slate-studio/loft | 0 | # -----------------------------------------------------------------------------
# Author: Alexander Kravets <alex@slatestudio.com>,
# Slate Studio (http://www.slatestudio.com)
# -----------------------------------------------------------------------------
# INPUT LOFT IMAGE
# -----------------------------------------------------------------------------
class @InputLoftImage extends InputString
# PRIVATE ===================================================================
_add_input: ->
@config.placeholder ?= 'Image URL'
type = "string"
if @config.fullsizePreview
@$el.addClass "fullsize-preview"
type = "hidden"
@$input =$ """<input type='#{type}'
name='#{ @name }'
value='#{ @_safe_value() }'
id='#{ @name }' />"""
@$el.append @$input
@$input.on 'change', (e) =>
@updateValue($(e.target).val())
if @config.fullsizePreview
@_update_preview_background()
else
@_add_image()
@_update_image()
@_add_actions()
@_update_input_class()
_add_image: ->
@$image =$ "<a href='' target='_blank' class='image'><img src='' /></a>"
@$el.append @$image
_add_actions: ->
@$actions =$ "<span class='input-actions'></span>"
@$label.append @$actions
@_add_choose_button()
@_add_remove_button()
_add_choose_button: ->
@$chooseBtn =$ "<button class='choose'>#{Icons.upload}</button>"
@$actions.append @$chooseBtn
@$chooseBtn.on 'click', (e) =>
chr.modules.loft.showImages false, (objects) =>
asset = objects[0]
@updateValue(asset.file.url)
_add_remove_button: ->
@$removeBtn =$ "<button class='remove'>#{Icons.remove}</button>"
@$actions.append @$removeBtn
@$removeBtn.on 'click', (e) =>
if confirm('Are you sure?')
@updateValue('')
_update_preview_background: ->
url = @value
@$el.css { "background-image": "url(#{url})" }
_update_image: ->
url = @value
@$image.attr('href', url).children().attr('src', url)
if url == ''
@$image.hide()
else
@$image.show()
_update_input_class: ->
if @value == ''
@$el.removeClass('has-value')
else
@$el.addClass('has-value')
# PUBLIC ====================================================================
updateValue: (@value) ->
@$input.val(@value)
if @config.fullsizePreview
@_update_preview_background()
else
@_update_image()
@_update_input_class()
chr.formInputs['loft-image'] = InputLoftImage
| 62319 | # -----------------------------------------------------------------------------
# Author: <NAME> <<EMAIL>>,
# Slate Studio (http://www.slatestudio.com)
# -----------------------------------------------------------------------------
# INPUT LOFT IMAGE
# -----------------------------------------------------------------------------
class @InputLoftImage extends InputString
# PRIVATE ===================================================================
_add_input: ->
@config.placeholder ?= 'Image URL'
type = "string"
if @config.fullsizePreview
@$el.addClass "fullsize-preview"
type = "hidden"
@$input =$ """<input type='#{type}'
name='#{ @name }'
value='#{ @_safe_value() }'
id='#{ @name }' />"""
@$el.append @$input
@$input.on 'change', (e) =>
@updateValue($(e.target).val())
if @config.fullsizePreview
@_update_preview_background()
else
@_add_image()
@_update_image()
@_add_actions()
@_update_input_class()
_add_image: ->
@$image =$ "<a href='' target='_blank' class='image'><img src='' /></a>"
@$el.append @$image
_add_actions: ->
@$actions =$ "<span class='input-actions'></span>"
@$label.append @$actions
@_add_choose_button()
@_add_remove_button()
_add_choose_button: ->
@$chooseBtn =$ "<button class='choose'>#{Icons.upload}</button>"
@$actions.append @$chooseBtn
@$chooseBtn.on 'click', (e) =>
chr.modules.loft.showImages false, (objects) =>
asset = objects[0]
@updateValue(asset.file.url)
_add_remove_button: ->
@$removeBtn =$ "<button class='remove'>#{Icons.remove}</button>"
@$actions.append @$removeBtn
@$removeBtn.on 'click', (e) =>
if confirm('Are you sure?')
@updateValue('')
_update_preview_background: ->
url = @value
@$el.css { "background-image": "url(#{url})" }
_update_image: ->
url = @value
@$image.attr('href', url).children().attr('src', url)
if url == ''
@$image.hide()
else
@$image.show()
_update_input_class: ->
if @value == ''
@$el.removeClass('has-value')
else
@$el.addClass('has-value')
# PUBLIC ====================================================================
updateValue: (@value) ->
@$input.val(@value)
if @config.fullsizePreview
@_update_preview_background()
else
@_update_image()
@_update_input_class()
chr.formInputs['loft-image'] = InputLoftImage
| true | # -----------------------------------------------------------------------------
# Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>,
# Slate Studio (http://www.slatestudio.com)
# -----------------------------------------------------------------------------
# INPUT LOFT IMAGE
# -----------------------------------------------------------------------------
class @InputLoftImage extends InputString
# PRIVATE ===================================================================
_add_input: ->
@config.placeholder ?= 'Image URL'
type = "string"
if @config.fullsizePreview
@$el.addClass "fullsize-preview"
type = "hidden"
@$input =$ """<input type='#{type}'
name='#{ @name }'
value='#{ @_safe_value() }'
id='#{ @name }' />"""
@$el.append @$input
@$input.on 'change', (e) =>
@updateValue($(e.target).val())
if @config.fullsizePreview
@_update_preview_background()
else
@_add_image()
@_update_image()
@_add_actions()
@_update_input_class()
_add_image: ->
@$image =$ "<a href='' target='_blank' class='image'><img src='' /></a>"
@$el.append @$image
_add_actions: ->
@$actions =$ "<span class='input-actions'></span>"
@$label.append @$actions
@_add_choose_button()
@_add_remove_button()
_add_choose_button: ->
@$chooseBtn =$ "<button class='choose'>#{Icons.upload}</button>"
@$actions.append @$chooseBtn
@$chooseBtn.on 'click', (e) =>
chr.modules.loft.showImages false, (objects) =>
asset = objects[0]
@updateValue(asset.file.url)
_add_remove_button: ->
@$removeBtn =$ "<button class='remove'>#{Icons.remove}</button>"
@$actions.append @$removeBtn
@$removeBtn.on 'click', (e) =>
if confirm('Are you sure?')
@updateValue('')
_update_preview_background: ->
url = @value
@$el.css { "background-image": "url(#{url})" }
_update_image: ->
url = @value
@$image.attr('href', url).children().attr('src', url)
if url == ''
@$image.hide()
else
@$image.show()
_update_input_class: ->
if @value == ''
@$el.removeClass('has-value')
else
@$el.addClass('has-value')
# PUBLIC ====================================================================
updateValue: (@value) ->
@$input.val(@value)
if @config.fullsizePreview
@_update_preview_background()
else
@_update_image()
@_update_input_class()
chr.formInputs['loft-image'] = InputLoftImage
|
[
{
"context": " #\n # Category.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http:/",
"end": 45,
"score": 0.9802770614624023,
"start": 35,
"tag": "NAME",
"value": "hector spc"
},
{
"context": " #\n # Category.\n #\n # Created by hector spc <hector@aer... | src/models/category_model.coffee | aerstudio/Phallanxpress | 1 | #
# Category.
#
# Created by hector spc <hector@aerstudio.com>
# Aer Studio
# http://www.aerstudio.com
#
# Sun Mar 04 2012
#
# models/category_model.js.coffee
#
class Phallanxpress.Category extends Phallanxpress.Model
children: ->
@collection.filter( (model)=>
model.get('parent') is @id
)
| 183136 | #
# Category.
#
# Created by <NAME> <<EMAIL>>
# Aer Studio
# http://www.aerstudio.com
#
# Sun Mar 04 2012
#
# models/category_model.js.coffee
#
class Phallanxpress.Category extends Phallanxpress.Model
children: ->
@collection.filter( (model)=>
model.get('parent') is @id
)
| true | #
# Category.
#
# Created by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Aer Studio
# http://www.aerstudio.com
#
# Sun Mar 04 2012
#
# models/category_model.js.coffee
#
class Phallanxpress.Category extends Phallanxpress.Model
children: ->
@collection.filter( (model)=>
model.get('parent') is @id
)
|
[
{
"context": "fk, fv of v['fields']\n availableKeys.push(\"#{k}.#{fk}\")\n else\n availableKeys.push(k)\n\n",
"end": 4522,
"score": 0.6050570607185364,
"start": 4517,
"tag": "KEY",
"value": "#{k}."
},
{
"context": "eserialize: (data) ->\n @data = data['mapping... | src/modeleditor.coffee | wendyrogers/CSV2IATI | 1 | SAMPLE_DATA =
"Project ID": "AGNA64"
"Title Project": "WE CAN end violence against women in Afghanistan"
"Short Descr Project": """The project is part of PIP P00115 which is the South Asia regional “We Can end violence against women campaign”. The objective is to challenge and change the patriarchal idea, beliefs, attitude, behaviour and practice that perpetuate violence against women. Project will take numbers of initiatives, which ultimately contribute to breaking the silence of domestic violence, which has huge prevalence all over the Afghan society. Under this project numbers of campaign initiatives will be taken to mobilise 2000 change makers and to make them aware about the issue and bring positive change in their personal attitudes, behaviours and practices."""
"Project Starts": "1-May-07"
"Project Ends": "31-Mar-11"
"Level of Impact": "Country"
"ISO CODE": "AF"
"Loc of Impact":"Afghanistan"
"Loc Info": " Kabul "
"% Aim 1: Right to Sustainable Livelihoods": "-0"
"% Aim 2: Right to Essential services": "-0"
"% Aim 3: Right to Life and Security": "-0"
"% Aim 4: Right to be heard": "10"
"% Aim 5: Right to Equity": "90"
" Expenditure prior to 2010/11": " 95,018 "
"Expenditure in 2010/11": " 40,415 "
" Revised Budget in current and future years (£) ": "-0"
"Total Value all years (£)": " 135,433 "
DEFAULT_MODEL =
organisation: {}
mapping:
'iati-identifier': {}
'title': {}
'description': {}
'activity-status': {}
'activity-date-start':
datatype: 'compound'
label: 'Activity Start Date'
'iati-field':'activity-date'
fields:
'type':
'constant': 'start-planned'
'datatype': 'constant'
'iso-date': {}
'text': {}
'activity-date-end':
datatype: 'compound'
label: 'Activity End Date'
'iati-field':'activity-date'
fields:
'type':
'constant': 'end-planned'
'datatype': 'constant'
'iso-date': {}
'text': {}
'recipient-country': {}
'recipient-region': {}
'funding-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Funding Organisation'
fields:
'role':
'constant': 'Funding'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
'extending-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Extending Organisation'
fields:
'role':
'constant': 'Extending'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
'implementing-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Implementing Organisation'
fields:
'role':
'constant': 'Implementing'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
sector: {}
transaction: {}
for key,value of DEFAULT_MODEL.mapping
if $.isEmptyObject(value)
$.extend(value, DEFAULT_FIELD_SETUP[key])
value['iati-field'] = key
FIELDS_META =
label:
required: true
String::dasherize = ->
this.replace /_/g, "-"
util =
# Turns a nested object into a flat mapping with PHP-like query string
# parameters as keys.
#
# Examples
#
# # Flatten a nested object structure
# flattenObject({'one': {'two': 'foo'}})
# # => Returns {'one[two]': 'foo'}
#
# # Flatten an object containing arrays
# flattenObject({'list': [1,2,3]})
# # => Returns {'list[]': [1,2,3]}
#
# Returns the flattened object
flattenObject: (obj) ->
flat = {}
pathStr = (path) ->
ary = [path[0]]
ary = ary.concat("[#{p}]" for p in path[1..-1])
ary.join ''
walk = (path, o) ->
for key, value of o
newpath = $.extend([], path)
newpath.push(key)
if $.type(value) is 'object'
walk newpath, value
else
if $.type(value) is 'array'
newpath.push ''
flat[pathStr(newpath)] = value
walk([], obj)
flat
class Widget extends Delegator
deserialize: (data) ->
class UniqueKeyWidget extends Widget
events:
'span click': 'onKeyClick'
deserialize: (data) ->
uniq = (data['dataset']?['unique_keys'] or [])
availableKeys = []
for k, v of data['mapping']
if v['datatype'] isnt 'value'
for fk, fv of v['fields']
availableKeys.push("#{k}.#{fk}")
else
availableKeys.push(k)
@keys = ({'name': k, 'used': k in uniq} for k in availableKeys)
this.render()
promptAddDimensionNamed: (props, thename) ->
return false
render: ->
@element.html($.tmpl('tpl_unique_keys', {'keys': @keys}))
onKeyClick: (e) ->
idx = @element.find('span').index(e.currentTarget)
@keys[idx]['used'] = not @keys[idx]['used']
this.render()
# Futzing with the DOM and adding form fields does not trigger form change
# events, so we have to trigger them manually.
@element.parents('form').first().change()
class DimensionWidget extends Widget
events:
'.add_field change': 'onAddFieldClick'
'.field_add_alternative click': 'onAddAlternativeClick'
'.field_add_transform click': 'onAddTransformClick'
'.field_remove_transform click': 'onRemoveTransformClick'
'.field_switch_constant change': 'onFieldSwitchConstantClick'
'.field_switch_column change': 'onFieldSwitchColumnClick'
'.field_rm click': 'onFieldRemoveClick'
'.delete_dimension click': 'onDeleteDimensionClick'
'.delete_tdatafield click': 'onDeleteTDataFieldClick'
'.column change' : 'onColumnChange'
'.show_advanced click': 'onShowAdvanced'
constructor: (name, container, options) ->
@name = name
el = $("<fieldset class='dimension' data-dimension-name='#{@name}'>
</fieldset>").appendTo(container)
super el, options
@id = "#{@element.parents('.modeleditor').attr('id')}_dim_#{@name}"
@element.attr('id', @id)
deserialize: (data) ->
@data = data['mapping']?[@name] or {}
# Meta needs to be for the relevant iati-field
@iati_field = data['mapping']?[@name]['iati-field'] or ''
@meta = DIMENSION_META[@iati_field] or {}
# Default fields
@default_fields = DEFAULT_FIELD_SETUP?[@iati_field] or {}
# Prepopulate field-less non-value dimensions with a label field
if @data.datatype isnt 'value' and 'fields' not of @data
@data.fields = {'label': {'datatype': 'string'}}
@element.html($.tmpl('tpl_dimension', this))
@element.trigger('fillColumnsRequest', [@element.find('select.column')])
@element.trigger('fillIATIfieldsRequest', [$(document).find('select.iati_field_add')])
formObj = {'mapping': {}}
formObj['mapping'][@name] = @data
for k, v of util.flattenObject(formObj)
@element.find("[name=\"#{k}\"]").val(v)
formFieldPrefix: () =>
"mapping[#{@name}][fields]"
formFieldRequired: (fieldName,fieldParent) =>
if (fieldParent)
FIELDS_META[fieldName]?['required'] or false
else
false
formFieldRequired2: (fieldName, fieldParent, transactionField) =>
#NB that fieldParent is the IATI field here
if (fieldParent)
if (DEFAULT_FIELD_SETUP[fieldParent])
if ((DEFAULT_FIELD_SETUP[fieldParent]['fields']) and (DEFAULT_FIELD_SETUP[fieldParent]['fields'][fieldName]))
DEFAULT_FIELD_SETUP[fieldParent]['fields'][fieldName]?['required'] or false
else
false
else
false
else
FIELDS_META[fieldName]?['required'] or false
onAddFieldClick: (e) ->
name = e.currentTarget.value
curRow = $(e.currentTarget).parents('tr').first()
try
# FIXME
default_fields_fields = eval('this.default_fields'+curRow.attr('data-prefix').replace('mapping['+@name+']','').replace(/\[/g,'["').replace(/\]/g,'"]'))
catch error
default_fields_fields = {}
if name == ''
return false
else if name == 'customnested'
return @onAddNestedElClick(e)
else if name == 'custom'
name = prompt("Field name:").trim()
else if name of default_fields_fields and default_fields_fields[name].datatype == 'compound'
return @onAddNestedElClick(e)
row = this._makeFieldRow(name, curRow.data('prefix'), curRow.data('level'))
row.insertBefore(curRow)
@element.trigger('fillColumnsRequest', [row.find('select.column')])
return false
onAddNestedElClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
name = e.currentTarget.value
if name =='customnested'
name = prompt("Element name:").trim()
prefix = curRow.data('prefix')
level = curRow.data('level')
data = {'fields':{}}
try
# FIXME
default_fields_fields = eval('this.default_fields'+curRow.attr('data-prefix').replace('mapping['+@name+']','').replace(/\[/g,'["').replace(/\]/g,'"]'))
catch error
default_fields_fields = {}
if name of default_fields_fields
data['fields'][name] = default_fields_fields[name]
else
data['fields'][name] = {
'datatype':'compound'
'label':name
'iati_field':name
'fields': {}
}
#data.fields[name].fields = {}
row = $.tmpl 'tpl_table_recursive',
'data': data
'dimensionName': ''
'prefix2': ''
'iati_field': ''
'prefix': prefix
'level': level
'formFieldRequired2': @formFieldRequired2
'default_fields': @default_fields
row.insertBefore(curRow)
#@element.trigger('fillColumnsRequest', [row.find('select.column')])
# This involves refreshing the whole dimension, but works
@element.parents('form').first().change()
return false
onDeleteDimensionClick: (e) ->
theform = @element.parents('form').first()
$(e.currentTarget).parents('fieldset').first().remove()
theform.change()
return false
onDeleteTDataFieldClick: (e) ->
theform = @element.parents('form').first()
$(e.currentTarget).parents('fieldset').first().remove()
theform.change()
return false
onColumnChange: (e) ->
curDimension = $(e.currentTarget).parents('fieldset').first()
dimension_name = curDimension.data('dimension-name')
dimension_data = curDimension.serializeObject()['mapping']
thiscolumn = $(e.currentTarget).val()
construct_iatifield = this.doIATIFieldSample(dimension_name, dimension_data,thiscolumn)
curDimension.find('span').first().html('Sample data: <code></code>')
curDimension.find('span code').first().text(construct_iatifield)
@element.parents('form').first().change()
return false
doIATIFieldSample: (dimension_name,dimension_data,thiscolumn) ->
construct_iatifield = '<' + dimension_data[dimension_name]['iati-field']
for k, v of dimension_data[dimension_name]['fields']
if (k == 'text')
if (v['datatype'] == 'constant')
textdata = dimension_data[dimension_name]['fields'][k]['constant']
else
textdata = this.dataSample(dimension_data[dimension_name]['fields'][k]['column'])
else
if (v['datatype'] == 'constant')
samplevalue = dimension_data[dimension_name]['fields'][k]['constant']
else
samplevalue = this.dataSample(dimension_data[dimension_name]['fields'][k]['column'])
construct_iatifield = construct_iatifield + ' ' + k + '="' + samplevalue + '"'
if (textdata)
construct_iatifield=construct_iatifield + ">" + textdata + "</" + dimension_data[dimension_name]['iati-field'] + ">"
else
construct_iatifield=construct_iatifield + "/>"
return construct_iatifield
onFieldRemoveClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = curRow.attr('data-prefix')+'['+curRow.attr('data-field-name')+']'
$(e.currentTarget).parents('tbody').first().children('[data-prefix^="'+prefix+'"]').remove()
$(e.currentTarget).parents('tbody').first().children('[name^="'+prefix+'"]').remove()
curRow.next('.alternativesCounter').remove()
curRow.remove()
@element.parents('form').first().change()
return false
onAddAlternativeClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = @formFieldPrefix()
fieldName = curRow.data('field-name')
alternativesCounter = curRow.data('alternatives-counter')
alternativesCounter += 1
curRow.next('.alternativesCounter').first().val(alternativesCounter)
curRow.after("<tr><td><input name=\"#{prefix}[#{fieldName}][alternatives][#{alternativesCounter}]\" value=\"test\" /></td></tr>")
@element.parents('form').first().change()
return false
onAddTransformClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = curRow.data('prefix')
fieldName = curRow.data('field-name')
curRow.after("<tr><td><input name=\"#{prefix}[#{fieldName}][text-transform-type]\" value=\"\" /></td></tr>")
@element.parents('form').first().change()
return false
onRemoveTransformClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curRow.find('.transform').remove()
@element.parents('form').first().change()
return false
onFieldSwitchConstantClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curDimension = $(e.currentTarget).parents('fieldset').first()
iatiField = $(e.currentTarget).parents('fieldset').first().find('.iatifield').val()
row = this._makeFieldRow(curRow.data('field-name'), curRow.data('prefix'), curRow.data('level'), curDimension.data('dimension-name'), iatiField, true)
curRow.replaceWith(row)
@element.parents('form').first().change()
return false
onFieldSwitchColumnClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curDimension = $(e.currentTarget).parents('fieldset').first()
iatiField = $(e.currentTarget).parents('fieldset').first().find('.iatifield').val()
row = this._makeFieldRow(curRow.data('field-name'), curRow.data('prefix'), curRow.data('level'), curDimension.data('dimension-name'), iatiField, false)
curRow.replaceWith(row)
@element.trigger('fillColumnsRequest', [row.find('select.column')])
@element.parents('form').first().change()
return false
onShowAdvanced: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curRow.find('.advanced').toggle()
return false
promptAddDimensionNamed: (props, thename) ->
return false
dataSample: (columnName) ->
(SAMPLE_DATA[columnName])
_makeFieldRow: (name, prefix, level, dimensionName, iatiField, constant=false) ->
tplName = if constant then 'tpl_dimension_field_const' else 'tpl_dimension_field'
$.tmpl tplName,
'fieldName': name
'dimensionName': dimensionName
'iatiField': iatiField
'prefix': prefix
'level': level
'required': this.formFieldRequired
field: {}
_makeFieldRowUpdate: (name, thisfield, requiredvar, constant=false) ->
tplName = if constant then 'tpl_dimension_field_const' else 'tpl_dimension_field'
$.tmpl tplName,
'fieldName': name
'prefix': this.formFieldPrefix
'required': this.formFieldRequired2
class DimensionsWidget extends Delegator
events:
'.iati_field_add change': 'onAddIATIFieldClick'
'.add_value_dimension click': 'onAddValueDimensionClick'
'.add_compound_dimension click': 'onAddCompoundDimensionClick'
'.copy_dimension click': 'onCopyDimensionClick'
constructor: (element, options) ->
super
@widgets = []
@dimsEl = @element.find('.dimensions').get(0)
@element.trigger('doFieldSelectors', 'iatifield')
@element.trigger('doFieldSelectors', 'column')
addDimension: (name) ->
w = new DimensionWidget(name, @dimsEl)
@widgets.push(w)
return w
removeDimension: (name) ->
idx = null
for w in @widgets
if w.name is name
idx = @widgets.indexOf(w)
break
if idx isnt null
@widgets.splice(idx, 1)[0].element.remove()
deserialize: (data) ->
return if @ignoreParent
dims = data['mapping'] or {}
toRemove = []
for widget in @widgets
if widget.name of dims
widget.deserialize(data)
delete dims[widget.name]
else
toRemove.push(widget.name)
# Remove any widgets not in dims
for name in toRemove
this.removeDimension(name)
# Any keys left in dims need to be added
for name, obj of dims
this.addDimension(name).deserialize(data)
createName: (name) ->
names = @widgets.map((x) -> x.name)
while true
if name in names
name += '~'
else
return name
onCopyDimensionClick: (e) ->
fieldset = $(e.currentTarget).parents('fieldset').first()
name = prompt("Give a unique name for your copy of this dimension (letters and numbers, no spaces):")
data = {'mapping': {}}
data['mapping'][name] = {}
for widget in @widgets
if widget.name == fieldset.data('dimension-name')
data['mapping'][name] = widget.data
break
data['mapping'][name]['label'] = name
this.addDimension(name.trim()).deserialize(data)
return false
promptAddDimension: (props) ->
name = prompt("Give a unique name for your new dimension (letters and numbers, no spaces):", @createName(props['iati-field']))
return false unless name
data = {'mapping': {}}
data['mapping'][name] = props
iati_field = data['mapping'][name]['iati-field']
data['mapping'][name] = DEFAULT_FIELD_SETUP[iati_field]
data['mapping'][name]['label'] = name
data['mapping'][name]['iati-field'] = iati_field
w = this.addDimension(name.trim())
w.deserialize(data)
w.element.get(0).scrollIntoView()
promptAddDimensionNamed: (thename, props) ->
alert("Column \"" + thename + "\" has been added.")
name = thename
return false unless name
data = {'mapping': {}}
data['mapping'][name] = props
this.addDimension(name.trim()).deserialize(data)
onAddValueDimensionClick: (e) ->
this.promptAddDimension({'datatype': 'value'})
return false
onAddCompoundDimensionClick: (e) ->
this.promptAddDimension({'datatype': 'compound'})
return false
onAddIATIFieldClick: (e) ->
thefield = $(e.currentTarget).val()
this.promptAddDimension({'datatype': 'compound','iati-field':thefield})
$(e.currentTarget).val('')
return false
class ModelEditor extends Delegator
widgetTypes:
'.unique_keys_widget': UniqueKeyWidget
'.dimensions_widget': DimensionsWidget
events:
'multipleSectorsRequest': 'onMultipleSectorsSetup'
'modelChange': 'onModelChange'
'fillColumnsRequest': 'onFillColumnsRequest'
'fillIATIfieldsRequest': 'onFillIATIfieldsRequest'
'.steps > ul > li click': 'onStepClick'
'.steps > ul > li > ul > li click': 'onStepDimensionClick'
'.forms form submit': 'onFormSubmit'
'.forms form change': 'onFormChange'
'#showdebug click': 'onShowDebugClick'
'#hidedebug click': 'onHideDebugClick'
'.add_data_field click': 'onAddDataFieldClick'
'doFieldSelectors' : 'onDoFieldSelectors'
'#iatifields .availablebtn click': 'onIATIFieldsAvailableClick'
'#iatifields .allbtn click': 'onIATIFieldsAllClick'
constructor: (element, options) ->
super
$('#multiple_rows_selector').html(
"<option value=''>One row per activity</option>" + ("<option value='#{x}'>Multiple #{x} rows per activity</option>" for x in @options.iatifields when x isnt '').join('\n')
)
if (@options.model_data)
model_data = JSON.parse(@options.model_data)
else
model_data = DEFAULT_MODEL
@data = $.extend(true, {}, model_data)
@widgets = []
@form = $(element).find('.forms form').eq(0)
@id = @element.attr('id')
if not @id?
@id = Math.floor((Math.random()*0xffffffff)).toString(16)
@element.attr('id', @id)
# Precompile templates
@element.find('script[type="text/x-jquery-tmpl"]').each ->
$(this).template($(this).attr('id'))
# Initialize widgets
for selector, ctor of @widgetTypes
@widgets.push(new ctor(e)) for e in @element.find(selector).get()
@element.trigger 'modelChange'
this.setStep 0
setStep: (s) ->
$(@element).find('.steps > ul > li')
.removeClass('active')
.eq(s).addClass('active')
$(@element).find('.forms div.formpart').hide().eq(s).show()
onStepClick: (e) ->
idx = @element.find('.steps > ul > li').index(e.currentTarget)
this.setStep idx
return false
onAddDataFieldClick: (e) ->
thevar = $(e.currentTarget).text()
for w in @widgets
w.promptAddDimensionNamed(thevar,{'datatype': 'value','column':thevar,'label':thevar})
@data = @form.serializeObject()
@element.trigger 'modelChange'
$(e.currentTarget).removeClass('add_data_field available').addClass('unavailable')
onShowDebugClick: (e) ->
$('#model_data').show()
$(document).keydown( (event)->
if event.which == 27
$('#model_data').hide()
)
return false
onHideDebugClick: (e) ->
$('#model_data').hide()
return false
onFormChange: (e) ->
return if @ignoreFormChange
@data = @form.serializeObject()
@element.trigger('doFieldSelectors', 'iatifield')
@element.trigger('doFieldSelectors', 'column')
@ignoreFormChange = true
@element.trigger 'modelChange'
@ignoreFormChange = false
# Missnamed now
onDoFieldSelectors: (e) ->
key = e + 's_used'
@options[key] = []
used = @options[key]
@form.find('.' + e).each ->
iatiname = ($(this).val())
if iatiname not in used
used.push(iatiname)
used.sort()
onFormSubmit: (e) ->
# Conversion...
# Need to know:
# 1) model file
# 2) csv file
## these should be in hidden inputs, and then only submit those to the API
# 3) conversion API address should be stored by the system, and the request should be handled by the server.
e.preventDefault();
api_address = 'api_convert';
model_file = $('#convert_model_file_URL').val()
csv_file = $('#convert_csv_file_URL').val()
$.post(api_address, { csv_file: csv_file, model_file: model_file }, complete:(result) ->
alert(result.status);
, "json");
return false;
onModelChange: () ->
# Populate straightforward bits
for k, v of util.flattenObject(@data)
# FIXME? this may not deal with complex form elements such as radio
# buttons or <select multiple>.
@form.find("[name=\"#{k}\"]").val(v)
# Send updated model copy to each subcomponent, as more complex
# components may not have been correctly filled out by the above.
for w in @widgets
w.deserialize($.extend(true, {}, @data))
# Update dimension list in sidebar
dimNames = (k for k, v of @data['mapping'])
@element.find('.steps ul.steps_dimensions').html(
('<li><a href="#' + "m1_dim_#{n}" + '">' + "#{@data['mapping'][n]['label']}</a>" for n in dimNames).join('\n')
)
$('#debug').text(JSON.stringify(@data, null, 2))
onFillColumnsRequest: (elem) ->
options = ["<option></option>", "<option disabled>Unused columns:</option>"]
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.columns when x not in @options.columns_used and x!='' ))
options.push('<option disabled>Previously used columns:</option>')
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.columns_used when x!='' ))
$(elem).html(
options.join('\n')
)
onFillIATIfieldsRequest: (elem) ->
options = ["<option>Add a new element</option>", "<option disabled>Unused elements:</option>"]
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.iatifields when x not in @options.iatifields_used and x!='' ))
options.push('<option disabled>Previously used elements:</option>')
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.iatifields_used when x!='' ))
$(elem).html(
options.join('\n')
)
$.plugin 'modelEditor', ModelEditor
this.ModelEditor = ModelEditor
| 113392 | SAMPLE_DATA =
"Project ID": "AGNA64"
"Title Project": "WE CAN end violence against women in Afghanistan"
"Short Descr Project": """The project is part of PIP P00115 which is the South Asia regional “We Can end violence against women campaign”. The objective is to challenge and change the patriarchal idea, beliefs, attitude, behaviour and practice that perpetuate violence against women. Project will take numbers of initiatives, which ultimately contribute to breaking the silence of domestic violence, which has huge prevalence all over the Afghan society. Under this project numbers of campaign initiatives will be taken to mobilise 2000 change makers and to make them aware about the issue and bring positive change in their personal attitudes, behaviours and practices."""
"Project Starts": "1-May-07"
"Project Ends": "31-Mar-11"
"Level of Impact": "Country"
"ISO CODE": "AF"
"Loc of Impact":"Afghanistan"
"Loc Info": " Kabul "
"% Aim 1: Right to Sustainable Livelihoods": "-0"
"% Aim 2: Right to Essential services": "-0"
"% Aim 3: Right to Life and Security": "-0"
"% Aim 4: Right to be heard": "10"
"% Aim 5: Right to Equity": "90"
" Expenditure prior to 2010/11": " 95,018 "
"Expenditure in 2010/11": " 40,415 "
" Revised Budget in current and future years (£) ": "-0"
"Total Value all years (£)": " 135,433 "
DEFAULT_MODEL =
organisation: {}
mapping:
'iati-identifier': {}
'title': {}
'description': {}
'activity-status': {}
'activity-date-start':
datatype: 'compound'
label: 'Activity Start Date'
'iati-field':'activity-date'
fields:
'type':
'constant': 'start-planned'
'datatype': 'constant'
'iso-date': {}
'text': {}
'activity-date-end':
datatype: 'compound'
label: 'Activity End Date'
'iati-field':'activity-date'
fields:
'type':
'constant': 'end-planned'
'datatype': 'constant'
'iso-date': {}
'text': {}
'recipient-country': {}
'recipient-region': {}
'funding-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Funding Organisation'
fields:
'role':
'constant': 'Funding'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
'extending-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Extending Organisation'
fields:
'role':
'constant': 'Extending'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
'implementing-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Implementing Organisation'
fields:
'role':
'constant': 'Implementing'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
sector: {}
transaction: {}
for key,value of DEFAULT_MODEL.mapping
if $.isEmptyObject(value)
$.extend(value, DEFAULT_FIELD_SETUP[key])
value['iati-field'] = key
FIELDS_META =
label:
required: true
String::dasherize = ->
this.replace /_/g, "-"
util =
# Turns a nested object into a flat mapping with PHP-like query string
# parameters as keys.
#
# Examples
#
# # Flatten a nested object structure
# flattenObject({'one': {'two': 'foo'}})
# # => Returns {'one[two]': 'foo'}
#
# # Flatten an object containing arrays
# flattenObject({'list': [1,2,3]})
# # => Returns {'list[]': [1,2,3]}
#
# Returns the flattened object
flattenObject: (obj) ->
flat = {}
pathStr = (path) ->
ary = [path[0]]
ary = ary.concat("[#{p}]" for p in path[1..-1])
ary.join ''
walk = (path, o) ->
for key, value of o
newpath = $.extend([], path)
newpath.push(key)
if $.type(value) is 'object'
walk newpath, value
else
if $.type(value) is 'array'
newpath.push ''
flat[pathStr(newpath)] = value
walk([], obj)
flat
class Widget extends Delegator
deserialize: (data) ->
class UniqueKeyWidget extends Widget
events:
'span click': 'onKeyClick'
deserialize: (data) ->
uniq = (data['dataset']?['unique_keys'] or [])
availableKeys = []
for k, v of data['mapping']
if v['datatype'] isnt 'value'
for fk, fv of v['fields']
availableKeys.push("<KEY>#{fk}")
else
availableKeys.push(k)
@keys = ({'name': k, 'used': k in uniq} for k in availableKeys)
this.render()
promptAddDimensionNamed: (props, thename) ->
return false
render: ->
@element.html($.tmpl('tpl_unique_keys', {'keys': @keys}))
onKeyClick: (e) ->
idx = @element.find('span').index(e.currentTarget)
@keys[idx]['used'] = not @keys[idx]['used']
this.render()
# Futzing with the DOM and adding form fields does not trigger form change
# events, so we have to trigger them manually.
@element.parents('form').first().change()
class DimensionWidget extends Widget
events:
'.add_field change': 'onAddFieldClick'
'.field_add_alternative click': 'onAddAlternativeClick'
'.field_add_transform click': 'onAddTransformClick'
'.field_remove_transform click': 'onRemoveTransformClick'
'.field_switch_constant change': 'onFieldSwitchConstantClick'
'.field_switch_column change': 'onFieldSwitchColumnClick'
'.field_rm click': 'onFieldRemoveClick'
'.delete_dimension click': 'onDeleteDimensionClick'
'.delete_tdatafield click': 'onDeleteTDataFieldClick'
'.column change' : 'onColumnChange'
'.show_advanced click': 'onShowAdvanced'
constructor: (name, container, options) ->
@name = name
el = $("<fieldset class='dimension' data-dimension-name='#{@name}'>
</fieldset>").appendTo(container)
super el, options
@id = "#{@element.parents('.modeleditor').attr('id')}_dim_#{@name}"
@element.attr('id', @id)
deserialize: (data) ->
@data = data['mapping']?[@name] or {}
# Meta needs to be for the relevant iati-field
@iati_field = data['mapping']?[@name]['iati-field'] or ''
@meta = DIMENSION_META[@iati_field] or {}
# Default fields
@default_fields = DEFAULT_FIELD_SETUP?[@iati_field] or {}
# Prepopulate field-less non-value dimensions with a label field
if @data.datatype isnt 'value' and 'fields' not of @data
@data.fields = {'label': {'datatype': 'string'}}
@element.html($.tmpl('tpl_dimension', this))
@element.trigger('fillColumnsRequest', [@element.find('select.column')])
@element.trigger('fillIATIfieldsRequest', [$(document).find('select.iati_field_add')])
formObj = {'mapping': {}}
formObj['mapping'][@name] = @data
for k, v of util.flattenObject(formObj)
@element.find("[name=\"#{k}\"]").val(v)
formFieldPrefix: () =>
"mapping[#{@name}][fields]"
formFieldRequired: (fieldName,fieldParent) =>
if (fieldParent)
FIELDS_META[fieldName]?['required'] or false
else
false
formFieldRequired2: (fieldName, fieldParent, transactionField) =>
#NB that fieldParent is the IATI field here
if (fieldParent)
if (DEFAULT_FIELD_SETUP[fieldParent])
if ((DEFAULT_FIELD_SETUP[fieldParent]['fields']) and (DEFAULT_FIELD_SETUP[fieldParent]['fields'][fieldName]))
DEFAULT_FIELD_SETUP[fieldParent]['fields'][fieldName]?['required'] or false
else
false
else
false
else
FIELDS_META[fieldName]?['required'] or false
onAddFieldClick: (e) ->
name = e.currentTarget.value
curRow = $(e.currentTarget).parents('tr').first()
try
# FIXME
default_fields_fields = eval('this.default_fields'+curRow.attr('data-prefix').replace('mapping['+@name+']','').replace(/\[/g,'["').replace(/\]/g,'"]'))
catch error
default_fields_fields = {}
if name == ''
return false
else if name == 'customnested'
return @onAddNestedElClick(e)
else if name == 'custom'
name = prompt("Field name:").trim()
else if name of default_fields_fields and default_fields_fields[name].datatype == 'compound'
return @onAddNestedElClick(e)
row = this._makeFieldRow(name, curRow.data('prefix'), curRow.data('level'))
row.insertBefore(curRow)
@element.trigger('fillColumnsRequest', [row.find('select.column')])
return false
onAddNestedElClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
name = e.currentTarget.value
if name =='customnested'
name = prompt("Element name:").trim()
prefix = curRow.data('prefix')
level = curRow.data('level')
data = {'fields':{}}
try
# FIXME
default_fields_fields = eval('this.default_fields'+curRow.attr('data-prefix').replace('mapping['+@name+']','').replace(/\[/g,'["').replace(/\]/g,'"]'))
catch error
default_fields_fields = {}
if name of default_fields_fields
data['fields'][name] = default_fields_fields[name]
else
data['fields'][name] = {
'datatype':'compound'
'label':name
'iati_field':name
'fields': {}
}
#data.fields[name].fields = {}
row = $.tmpl 'tpl_table_recursive',
'data': data
'dimensionName': ''
'prefix2': ''
'iati_field': ''
'prefix': prefix
'level': level
'formFieldRequired2': @formFieldRequired2
'default_fields': @default_fields
row.insertBefore(curRow)
#@element.trigger('fillColumnsRequest', [row.find('select.column')])
# This involves refreshing the whole dimension, but works
@element.parents('form').first().change()
return false
onDeleteDimensionClick: (e) ->
theform = @element.parents('form').first()
$(e.currentTarget).parents('fieldset').first().remove()
theform.change()
return false
onDeleteTDataFieldClick: (e) ->
theform = @element.parents('form').first()
$(e.currentTarget).parents('fieldset').first().remove()
theform.change()
return false
onColumnChange: (e) ->
curDimension = $(e.currentTarget).parents('fieldset').first()
dimension_name = curDimension.data('dimension-name')
dimension_data = curDimension.serializeObject()['mapping']
thiscolumn = $(e.currentTarget).val()
construct_iatifield = this.doIATIFieldSample(dimension_name, dimension_data,thiscolumn)
curDimension.find('span').first().html('Sample data: <code></code>')
curDimension.find('span code').first().text(construct_iatifield)
@element.parents('form').first().change()
return false
doIATIFieldSample: (dimension_name,dimension_data,thiscolumn) ->
construct_iatifield = '<' + dimension_data[dimension_name]['iati-field']
for k, v of dimension_data[dimension_name]['fields']
if (k == 'text')
if (v['datatype'] == 'constant')
textdata = dimension_data[dimension_name]['fields'][k]['constant']
else
textdata = this.dataSample(dimension_data[dimension_name]['fields'][k]['column'])
else
if (v['datatype'] == 'constant')
samplevalue = dimension_data[dimension_name]['fields'][k]['constant']
else
samplevalue = this.dataSample(dimension_data[dimension_name]['fields'][k]['column'])
construct_iatifield = construct_iatifield + ' ' + k + '="' + samplevalue + '"'
if (textdata)
construct_iatifield=construct_iatifield + ">" + textdata + "</" + dimension_data[dimension_name]['iati-field'] + ">"
else
construct_iatifield=construct_iatifield + "/>"
return construct_iatifield
onFieldRemoveClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = curRow.attr('data-prefix')+'['+curRow.attr('data-field-name')+']'
$(e.currentTarget).parents('tbody').first().children('[data-prefix^="'+prefix+'"]').remove()
$(e.currentTarget).parents('tbody').first().children('[name^="'+prefix+'"]').remove()
curRow.next('.alternativesCounter').remove()
curRow.remove()
@element.parents('form').first().change()
return false
onAddAlternativeClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = @formFieldPrefix()
fieldName = curRow.data('field-name')
alternativesCounter = curRow.data('alternatives-counter')
alternativesCounter += 1
curRow.next('.alternativesCounter').first().val(alternativesCounter)
curRow.after("<tr><td><input name=\"#{prefix}[#{fieldName}][alternatives][#{alternativesCounter}]\" value=\"test\" /></td></tr>")
@element.parents('form').first().change()
return false
onAddTransformClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = curRow.data('prefix')
fieldName = curRow.data('field-name')
curRow.after("<tr><td><input name=\"#{prefix}[#{fieldName}][text-transform-type]\" value=\"\" /></td></tr>")
@element.parents('form').first().change()
return false
onRemoveTransformClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curRow.find('.transform').remove()
@element.parents('form').first().change()
return false
onFieldSwitchConstantClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curDimension = $(e.currentTarget).parents('fieldset').first()
iatiField = $(e.currentTarget).parents('fieldset').first().find('.iatifield').val()
row = this._makeFieldRow(curRow.data('field-name'), curRow.data('prefix'), curRow.data('level'), curDimension.data('dimension-name'), iatiField, true)
curRow.replaceWith(row)
@element.parents('form').first().change()
return false
onFieldSwitchColumnClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curDimension = $(e.currentTarget).parents('fieldset').first()
iatiField = $(e.currentTarget).parents('fieldset').first().find('.iatifield').val()
row = this._makeFieldRow(curRow.data('field-name'), curRow.data('prefix'), curRow.data('level'), curDimension.data('dimension-name'), iatiField, false)
curRow.replaceWith(row)
@element.trigger('fillColumnsRequest', [row.find('select.column')])
@element.parents('form').first().change()
return false
onShowAdvanced: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curRow.find('.advanced').toggle()
return false
promptAddDimensionNamed: (props, thename) ->
return false
dataSample: (columnName) ->
(SAMPLE_DATA[columnName])
_makeFieldRow: (name, prefix, level, dimensionName, iatiField, constant=false) ->
tplName = if constant then 'tpl_dimension_field_const' else 'tpl_dimension_field'
$.tmpl tplName,
'fieldName': name
'dimensionName': dimensionName
'iatiField': iatiField
'prefix': prefix
'level': level
'required': this.formFieldRequired
field: {}
_makeFieldRowUpdate: (name, thisfield, requiredvar, constant=false) ->
tplName = if constant then 'tpl_dimension_field_const' else 'tpl_dimension_field'
$.tmpl tplName,
'fieldName': name
'prefix': this.formFieldPrefix
'required': this.formFieldRequired2
class DimensionsWidget extends Delegator
events:
'.iati_field_add change': 'onAddIATIFieldClick'
'.add_value_dimension click': 'onAddValueDimensionClick'
'.add_compound_dimension click': 'onAddCompoundDimensionClick'
'.copy_dimension click': 'onCopyDimensionClick'
constructor: (element, options) ->
super
@widgets = []
@dimsEl = @element.find('.dimensions').get(0)
@element.trigger('doFieldSelectors', 'iatifield')
@element.trigger('doFieldSelectors', 'column')
addDimension: (name) ->
w = new DimensionWidget(name, @dimsEl)
@widgets.push(w)
return w
removeDimension: (name) ->
idx = null
for w in @widgets
if w.name is name
idx = @widgets.indexOf(w)
break
if idx isnt null
@widgets.splice(idx, 1)[0].element.remove()
deserialize: (data) ->
return if @ignoreParent
dims = data['mapping'] or {}
toRemove = []
for widget in @widgets
if widget.name of dims
widget.deserialize(data)
delete dims[widget.name]
else
toRemove.push(widget.name)
# Remove any widgets not in dims
for name in toRemove
this.removeDimension(name)
# Any keys left in dims need to be added
for name, obj of dims
this.addDimension(name).deserialize(data)
createName: (name) ->
names = @widgets.map((x) -> x.name)
while true
if name in names
name += '~'
else
return name
onCopyDimensionClick: (e) ->
fieldset = $(e.currentTarget).parents('fieldset').first()
name = prompt("Give a unique name for your copy of this dimension (letters and numbers, no spaces):")
data = {'mapping': {}}
data['mapping'][name] = {}
for widget in @widgets
if widget.name == fieldset.data('dimension-name')
data['mapping'][name] = widget.data
break
data['mapping'][name]['label'] = name
this.addDimension(name.trim()).deserialize(data)
return false
promptAddDimension: (props) ->
name = prompt("Give a unique name for your new dimension (letters and numbers, no spaces):", @createName(props['iati-field']))
return false unless name
data = {'mapping': {}}
data['mapping'][name] = props
iati_field = data['mapping'][name]['iati-field']
data['mapping'][name] = DEFAULT_FIELD_SETUP[iati_field]
data['mapping'][name]['label'] = name
data['mapping'][name]['iati-field'] = iati_field
w = this.addDimension(name.trim())
w.deserialize(data)
w.element.get(0).scrollIntoView()
promptAddDimensionNamed: (thename, props) ->
alert("Column \"" + thename + "\" has been added.")
name = thename
return false unless name
data = {'mapping': {}}
data['mapping'][name] = props
this.addDimension(name.trim()).deserialize(data)
onAddValueDimensionClick: (e) ->
this.promptAddDimension({'datatype': 'value'})
return false
onAddCompoundDimensionClick: (e) ->
this.promptAddDimension({'datatype': 'compound'})
return false
onAddIATIFieldClick: (e) ->
thefield = $(e.currentTarget).val()
this.promptAddDimension({'datatype': 'compound','iati-field':thefield})
$(e.currentTarget).val('')
return false
class ModelEditor extends Delegator
widgetTypes:
'.unique_keys_widget': UniqueKeyWidget
'.dimensions_widget': DimensionsWidget
events:
'multipleSectorsRequest': 'onMultipleSectorsSetup'
'modelChange': 'onModelChange'
'fillColumnsRequest': 'onFillColumnsRequest'
'fillIATIfieldsRequest': 'onFillIATIfieldsRequest'
'.steps > ul > li click': 'onStepClick'
'.steps > ul > li > ul > li click': 'onStepDimensionClick'
'.forms form submit': 'onFormSubmit'
'.forms form change': 'onFormChange'
'#showdebug click': 'onShowDebugClick'
'#hidedebug click': 'onHideDebugClick'
'.add_data_field click': 'onAddDataFieldClick'
'doFieldSelectors' : 'onDoFieldSelectors'
'#iatifields .availablebtn click': 'onIATIFieldsAvailableClick'
'#iatifields .allbtn click': 'onIATIFieldsAllClick'
constructor: (element, options) ->
super
$('#multiple_rows_selector').html(
"<option value=''>One row per activity</option>" + ("<option value='#{x}'>Multiple #{x} rows per activity</option>" for x in @options.iatifields when x isnt '').join('\n')
)
if (@options.model_data)
model_data = JSON.parse(@options.model_data)
else
model_data = DEFAULT_MODEL
@data = $.extend(true, {}, model_data)
@widgets = []
@form = $(element).find('.forms form').eq(0)
@id = @element.attr('id')
if not @id?
@id = Math.floor((Math.random()*0xffffffff)).toString(16)
@element.attr('id', @id)
# Precompile templates
@element.find('script[type="text/x-jquery-tmpl"]').each ->
$(this).template($(this).attr('id'))
# Initialize widgets
for selector, ctor of @widgetTypes
@widgets.push(new ctor(e)) for e in @element.find(selector).get()
@element.trigger 'modelChange'
this.setStep 0
setStep: (s) ->
$(@element).find('.steps > ul > li')
.removeClass('active')
.eq(s).addClass('active')
$(@element).find('.forms div.formpart').hide().eq(s).show()
onStepClick: (e) ->
idx = @element.find('.steps > ul > li').index(e.currentTarget)
this.setStep idx
return false
onAddDataFieldClick: (e) ->
thevar = $(e.currentTarget).text()
for w in @widgets
w.promptAddDimensionNamed(thevar,{'datatype': 'value','column':thevar,'label':thevar})
@data = @form.serializeObject()
@element.trigger 'modelChange'
$(e.currentTarget).removeClass('add_data_field available').addClass('unavailable')
onShowDebugClick: (e) ->
$('#model_data').show()
$(document).keydown( (event)->
if event.which == 27
$('#model_data').hide()
)
return false
onHideDebugClick: (e) ->
$('#model_data').hide()
return false
onFormChange: (e) ->
return if @ignoreFormChange
@data = @form.serializeObject()
@element.trigger('doFieldSelectors', 'iatifield')
@element.trigger('doFieldSelectors', 'column')
@ignoreFormChange = true
@element.trigger 'modelChange'
@ignoreFormChange = false
# Missnamed now
onDoFieldSelectors: (e) ->
key = <KEY> + '<KEY>'
@options[key] = []
used = @options[key]
@form.find('.' + e).each ->
iatiname = ($(this).val())
if iatiname not in used
used.push(iatiname)
used.sort()
onFormSubmit: (e) ->
# Conversion...
# Need to know:
# 1) model file
# 2) csv file
## these should be in hidden inputs, and then only submit those to the API
# 3) conversion API address should be stored by the system, and the request should be handled by the server.
e.preventDefault();
api_address = 'api_convert';
model_file = $('#convert_model_file_URL').val()
csv_file = $('#convert_csv_file_URL').val()
$.post(api_address, { csv_file: csv_file, model_file: model_file }, complete:(result) ->
alert(result.status);
, "json");
return false;
onModelChange: () ->
# Populate straightforward bits
for k, v of util.flattenObject(@data)
# FIXME? this may not deal with complex form elements such as radio
# buttons or <select multiple>.
@form.find("[name=\"#{k}\"]").val(v)
# Send updated model copy to each subcomponent, as more complex
# components may not have been correctly filled out by the above.
for w in @widgets
w.deserialize($.extend(true, {}, @data))
# Update dimension list in sidebar
dimNames = (k for k, v of @data['mapping'])
@element.find('.steps ul.steps_dimensions').html(
('<li><a href="#' + "m1_dim_#{n}" + '">' + "#{@data['mapping'][n]['label']}</a>" for n in dimNames).join('\n')
)
$('#debug').text(JSON.stringify(@data, null, 2))
onFillColumnsRequest: (elem) ->
options = ["<option></option>", "<option disabled>Unused columns:</option>"]
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.columns when x not in @options.columns_used and x!='' ))
options.push('<option disabled>Previously used columns:</option>')
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.columns_used when x!='' ))
$(elem).html(
options.join('\n')
)
onFillIATIfieldsRequest: (elem) ->
options = ["<option>Add a new element</option>", "<option disabled>Unused elements:</option>"]
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.iatifields when x not in @options.iatifields_used and x!='' ))
options.push('<option disabled>Previously used elements:</option>')
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.iatifields_used when x!='' ))
$(elem).html(
options.join('\n')
)
$.plugin 'modelEditor', ModelEditor
this.ModelEditor = ModelEditor
| true | SAMPLE_DATA =
"Project ID": "AGNA64"
"Title Project": "WE CAN end violence against women in Afghanistan"
"Short Descr Project": """The project is part of PIP P00115 which is the South Asia regional “We Can end violence against women campaign”. The objective is to challenge and change the patriarchal idea, beliefs, attitude, behaviour and practice that perpetuate violence against women. Project will take numbers of initiatives, which ultimately contribute to breaking the silence of domestic violence, which has huge prevalence all over the Afghan society. Under this project numbers of campaign initiatives will be taken to mobilise 2000 change makers and to make them aware about the issue and bring positive change in their personal attitudes, behaviours and practices."""
"Project Starts": "1-May-07"
"Project Ends": "31-Mar-11"
"Level of Impact": "Country"
"ISO CODE": "AF"
"Loc of Impact":"Afghanistan"
"Loc Info": " Kabul "
"% Aim 1: Right to Sustainable Livelihoods": "-0"
"% Aim 2: Right to Essential services": "-0"
"% Aim 3: Right to Life and Security": "-0"
"% Aim 4: Right to be heard": "10"
"% Aim 5: Right to Equity": "90"
" Expenditure prior to 2010/11": " 95,018 "
"Expenditure in 2010/11": " 40,415 "
" Revised Budget in current and future years (£) ": "-0"
"Total Value all years (£)": " 135,433 "
DEFAULT_MODEL =
organisation: {}
mapping:
'iati-identifier': {}
'title': {}
'description': {}
'activity-status': {}
'activity-date-start':
datatype: 'compound'
label: 'Activity Start Date'
'iati-field':'activity-date'
fields:
'type':
'constant': 'start-planned'
'datatype': 'constant'
'iso-date': {}
'text': {}
'activity-date-end':
datatype: 'compound'
label: 'Activity End Date'
'iati-field':'activity-date'
fields:
'type':
'constant': 'end-planned'
'datatype': 'constant'
'iso-date': {}
'text': {}
'recipient-country': {}
'recipient-region': {}
'funding-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Funding Organisation'
fields:
'role':
'constant': 'Funding'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
'extending-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Extending Organisation'
fields:
'role':
'constant': 'Extending'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
'implementing-organisation':
datatype: 'compound'
'iati-field': 'participating-org'
label: 'Implementing Organisation'
fields:
'role':
'constant': 'Implementing'
'datatype': 'constant'
'text': {}
'ref': {}
'type': {}
sector: {}
transaction: {}
for key,value of DEFAULT_MODEL.mapping
if $.isEmptyObject(value)
$.extend(value, DEFAULT_FIELD_SETUP[key])
value['iati-field'] = key
FIELDS_META =
label:
required: true
String::dasherize = ->
this.replace /_/g, "-"
util =
# Turns a nested object into a flat mapping with PHP-like query string
# parameters as keys.
#
# Examples
#
# # Flatten a nested object structure
# flattenObject({'one': {'two': 'foo'}})
# # => Returns {'one[two]': 'foo'}
#
# # Flatten an object containing arrays
# flattenObject({'list': [1,2,3]})
# # => Returns {'list[]': [1,2,3]}
#
# Returns the flattened object
flattenObject: (obj) ->
flat = {}
pathStr = (path) ->
ary = [path[0]]
ary = ary.concat("[#{p}]" for p in path[1..-1])
ary.join ''
walk = (path, o) ->
for key, value of o
newpath = $.extend([], path)
newpath.push(key)
if $.type(value) is 'object'
walk newpath, value
else
if $.type(value) is 'array'
newpath.push ''
flat[pathStr(newpath)] = value
walk([], obj)
flat
class Widget extends Delegator
deserialize: (data) ->
class UniqueKeyWidget extends Widget
events:
'span click': 'onKeyClick'
deserialize: (data) ->
uniq = (data['dataset']?['unique_keys'] or [])
availableKeys = []
for k, v of data['mapping']
if v['datatype'] isnt 'value'
for fk, fv of v['fields']
availableKeys.push("PI:KEY:<KEY>END_PI#{fk}")
else
availableKeys.push(k)
@keys = ({'name': k, 'used': k in uniq} for k in availableKeys)
this.render()
promptAddDimensionNamed: (props, thename) ->
return false
render: ->
@element.html($.tmpl('tpl_unique_keys', {'keys': @keys}))
onKeyClick: (e) ->
idx = @element.find('span').index(e.currentTarget)
@keys[idx]['used'] = not @keys[idx]['used']
this.render()
# Futzing with the DOM and adding form fields does not trigger form change
# events, so we have to trigger them manually.
@element.parents('form').first().change()
class DimensionWidget extends Widget
events:
'.add_field change': 'onAddFieldClick'
'.field_add_alternative click': 'onAddAlternativeClick'
'.field_add_transform click': 'onAddTransformClick'
'.field_remove_transform click': 'onRemoveTransformClick'
'.field_switch_constant change': 'onFieldSwitchConstantClick'
'.field_switch_column change': 'onFieldSwitchColumnClick'
'.field_rm click': 'onFieldRemoveClick'
'.delete_dimension click': 'onDeleteDimensionClick'
'.delete_tdatafield click': 'onDeleteTDataFieldClick'
'.column change' : 'onColumnChange'
'.show_advanced click': 'onShowAdvanced'
constructor: (name, container, options) ->
@name = name
el = $("<fieldset class='dimension' data-dimension-name='#{@name}'>
</fieldset>").appendTo(container)
super el, options
@id = "#{@element.parents('.modeleditor').attr('id')}_dim_#{@name}"
@element.attr('id', @id)
deserialize: (data) ->
@data = data['mapping']?[@name] or {}
# Meta needs to be for the relevant iati-field
@iati_field = data['mapping']?[@name]['iati-field'] or ''
@meta = DIMENSION_META[@iati_field] or {}
# Default fields
@default_fields = DEFAULT_FIELD_SETUP?[@iati_field] or {}
# Prepopulate field-less non-value dimensions with a label field
if @data.datatype isnt 'value' and 'fields' not of @data
@data.fields = {'label': {'datatype': 'string'}}
@element.html($.tmpl('tpl_dimension', this))
@element.trigger('fillColumnsRequest', [@element.find('select.column')])
@element.trigger('fillIATIfieldsRequest', [$(document).find('select.iati_field_add')])
formObj = {'mapping': {}}
formObj['mapping'][@name] = @data
for k, v of util.flattenObject(formObj)
@element.find("[name=\"#{k}\"]").val(v)
formFieldPrefix: () =>
"mapping[#{@name}][fields]"
formFieldRequired: (fieldName,fieldParent) =>
if (fieldParent)
FIELDS_META[fieldName]?['required'] or false
else
false
formFieldRequired2: (fieldName, fieldParent, transactionField) =>
#NB that fieldParent is the IATI field here
if (fieldParent)
if (DEFAULT_FIELD_SETUP[fieldParent])
if ((DEFAULT_FIELD_SETUP[fieldParent]['fields']) and (DEFAULT_FIELD_SETUP[fieldParent]['fields'][fieldName]))
DEFAULT_FIELD_SETUP[fieldParent]['fields'][fieldName]?['required'] or false
else
false
else
false
else
FIELDS_META[fieldName]?['required'] or false
onAddFieldClick: (e) ->
name = e.currentTarget.value
curRow = $(e.currentTarget).parents('tr').first()
try
# FIXME
default_fields_fields = eval('this.default_fields'+curRow.attr('data-prefix').replace('mapping['+@name+']','').replace(/\[/g,'["').replace(/\]/g,'"]'))
catch error
default_fields_fields = {}
if name == ''
return false
else if name == 'customnested'
return @onAddNestedElClick(e)
else if name == 'custom'
name = prompt("Field name:").trim()
else if name of default_fields_fields and default_fields_fields[name].datatype == 'compound'
return @onAddNestedElClick(e)
row = this._makeFieldRow(name, curRow.data('prefix'), curRow.data('level'))
row.insertBefore(curRow)
@element.trigger('fillColumnsRequest', [row.find('select.column')])
return false
onAddNestedElClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
name = e.currentTarget.value
if name =='customnested'
name = prompt("Element name:").trim()
prefix = curRow.data('prefix')
level = curRow.data('level')
data = {'fields':{}}
try
# FIXME
default_fields_fields = eval('this.default_fields'+curRow.attr('data-prefix').replace('mapping['+@name+']','').replace(/\[/g,'["').replace(/\]/g,'"]'))
catch error
default_fields_fields = {}
if name of default_fields_fields
data['fields'][name] = default_fields_fields[name]
else
data['fields'][name] = {
'datatype':'compound'
'label':name
'iati_field':name
'fields': {}
}
#data.fields[name].fields = {}
row = $.tmpl 'tpl_table_recursive',
'data': data
'dimensionName': ''
'prefix2': ''
'iati_field': ''
'prefix': prefix
'level': level
'formFieldRequired2': @formFieldRequired2
'default_fields': @default_fields
row.insertBefore(curRow)
#@element.trigger('fillColumnsRequest', [row.find('select.column')])
# This involves refreshing the whole dimension, but works
@element.parents('form').first().change()
return false
onDeleteDimensionClick: (e) ->
theform = @element.parents('form').first()
$(e.currentTarget).parents('fieldset').first().remove()
theform.change()
return false
onDeleteTDataFieldClick: (e) ->
theform = @element.parents('form').first()
$(e.currentTarget).parents('fieldset').first().remove()
theform.change()
return false
onColumnChange: (e) ->
curDimension = $(e.currentTarget).parents('fieldset').first()
dimension_name = curDimension.data('dimension-name')
dimension_data = curDimension.serializeObject()['mapping']
thiscolumn = $(e.currentTarget).val()
construct_iatifield = this.doIATIFieldSample(dimension_name, dimension_data,thiscolumn)
curDimension.find('span').first().html('Sample data: <code></code>')
curDimension.find('span code').first().text(construct_iatifield)
@element.parents('form').first().change()
return false
doIATIFieldSample: (dimension_name,dimension_data,thiscolumn) ->
construct_iatifield = '<' + dimension_data[dimension_name]['iati-field']
for k, v of dimension_data[dimension_name]['fields']
if (k == 'text')
if (v['datatype'] == 'constant')
textdata = dimension_data[dimension_name]['fields'][k]['constant']
else
textdata = this.dataSample(dimension_data[dimension_name]['fields'][k]['column'])
else
if (v['datatype'] == 'constant')
samplevalue = dimension_data[dimension_name]['fields'][k]['constant']
else
samplevalue = this.dataSample(dimension_data[dimension_name]['fields'][k]['column'])
construct_iatifield = construct_iatifield + ' ' + k + '="' + samplevalue + '"'
if (textdata)
construct_iatifield=construct_iatifield + ">" + textdata + "</" + dimension_data[dimension_name]['iati-field'] + ">"
else
construct_iatifield=construct_iatifield + "/>"
return construct_iatifield
onFieldRemoveClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = curRow.attr('data-prefix')+'['+curRow.attr('data-field-name')+']'
$(e.currentTarget).parents('tbody').first().children('[data-prefix^="'+prefix+'"]').remove()
$(e.currentTarget).parents('tbody').first().children('[name^="'+prefix+'"]').remove()
curRow.next('.alternativesCounter').remove()
curRow.remove()
@element.parents('form').first().change()
return false
onAddAlternativeClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = @formFieldPrefix()
fieldName = curRow.data('field-name')
alternativesCounter = curRow.data('alternatives-counter')
alternativesCounter += 1
curRow.next('.alternativesCounter').first().val(alternativesCounter)
curRow.after("<tr><td><input name=\"#{prefix}[#{fieldName}][alternatives][#{alternativesCounter}]\" value=\"test\" /></td></tr>")
@element.parents('form').first().change()
return false
onAddTransformClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
prefix = curRow.data('prefix')
fieldName = curRow.data('field-name')
curRow.after("<tr><td><input name=\"#{prefix}[#{fieldName}][text-transform-type]\" value=\"\" /></td></tr>")
@element.parents('form').first().change()
return false
onRemoveTransformClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curRow.find('.transform').remove()
@element.parents('form').first().change()
return false
onFieldSwitchConstantClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curDimension = $(e.currentTarget).parents('fieldset').first()
iatiField = $(e.currentTarget).parents('fieldset').first().find('.iatifield').val()
row = this._makeFieldRow(curRow.data('field-name'), curRow.data('prefix'), curRow.data('level'), curDimension.data('dimension-name'), iatiField, true)
curRow.replaceWith(row)
@element.parents('form').first().change()
return false
onFieldSwitchColumnClick: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curDimension = $(e.currentTarget).parents('fieldset').first()
iatiField = $(e.currentTarget).parents('fieldset').first().find('.iatifield').val()
row = this._makeFieldRow(curRow.data('field-name'), curRow.data('prefix'), curRow.data('level'), curDimension.data('dimension-name'), iatiField, false)
curRow.replaceWith(row)
@element.trigger('fillColumnsRequest', [row.find('select.column')])
@element.parents('form').first().change()
return false
onShowAdvanced: (e) ->
curRow = $(e.currentTarget).parents('tr').first()
curRow.find('.advanced').toggle()
return false
promptAddDimensionNamed: (props, thename) ->
return false
dataSample: (columnName) ->
(SAMPLE_DATA[columnName])
_makeFieldRow: (name, prefix, level, dimensionName, iatiField, constant=false) ->
tplName = if constant then 'tpl_dimension_field_const' else 'tpl_dimension_field'
$.tmpl tplName,
'fieldName': name
'dimensionName': dimensionName
'iatiField': iatiField
'prefix': prefix
'level': level
'required': this.formFieldRequired
field: {}
_makeFieldRowUpdate: (name, thisfield, requiredvar, constant=false) ->
tplName = if constant then 'tpl_dimension_field_const' else 'tpl_dimension_field'
$.tmpl tplName,
'fieldName': name
'prefix': this.formFieldPrefix
'required': this.formFieldRequired2
class DimensionsWidget extends Delegator
events:
'.iati_field_add change': 'onAddIATIFieldClick'
'.add_value_dimension click': 'onAddValueDimensionClick'
'.add_compound_dimension click': 'onAddCompoundDimensionClick'
'.copy_dimension click': 'onCopyDimensionClick'
constructor: (element, options) ->
super
@widgets = []
@dimsEl = @element.find('.dimensions').get(0)
@element.trigger('doFieldSelectors', 'iatifield')
@element.trigger('doFieldSelectors', 'column')
addDimension: (name) ->
w = new DimensionWidget(name, @dimsEl)
@widgets.push(w)
return w
removeDimension: (name) ->
idx = null
for w in @widgets
if w.name is name
idx = @widgets.indexOf(w)
break
if idx isnt null
@widgets.splice(idx, 1)[0].element.remove()
deserialize: (data) ->
return if @ignoreParent
dims = data['mapping'] or {}
toRemove = []
for widget in @widgets
if widget.name of dims
widget.deserialize(data)
delete dims[widget.name]
else
toRemove.push(widget.name)
# Remove any widgets not in dims
for name in toRemove
this.removeDimension(name)
# Any keys left in dims need to be added
for name, obj of dims
this.addDimension(name).deserialize(data)
createName: (name) ->
names = @widgets.map((x) -> x.name)
while true
if name in names
name += '~'
else
return name
onCopyDimensionClick: (e) ->
fieldset = $(e.currentTarget).parents('fieldset').first()
name = prompt("Give a unique name for your copy of this dimension (letters and numbers, no spaces):")
data = {'mapping': {}}
data['mapping'][name] = {}
for widget in @widgets
if widget.name == fieldset.data('dimension-name')
data['mapping'][name] = widget.data
break
data['mapping'][name]['label'] = name
this.addDimension(name.trim()).deserialize(data)
return false
promptAddDimension: (props) ->
name = prompt("Give a unique name for your new dimension (letters and numbers, no spaces):", @createName(props['iati-field']))
return false unless name
data = {'mapping': {}}
data['mapping'][name] = props
iati_field = data['mapping'][name]['iati-field']
data['mapping'][name] = DEFAULT_FIELD_SETUP[iati_field]
data['mapping'][name]['label'] = name
data['mapping'][name]['iati-field'] = iati_field
w = this.addDimension(name.trim())
w.deserialize(data)
w.element.get(0).scrollIntoView()
promptAddDimensionNamed: (thename, props) ->
alert("Column \"" + thename + "\" has been added.")
name = thename
return false unless name
data = {'mapping': {}}
data['mapping'][name] = props
this.addDimension(name.trim()).deserialize(data)
onAddValueDimensionClick: (e) ->
this.promptAddDimension({'datatype': 'value'})
return false
onAddCompoundDimensionClick: (e) ->
this.promptAddDimension({'datatype': 'compound'})
return false
onAddIATIFieldClick: (e) ->
thefield = $(e.currentTarget).val()
this.promptAddDimension({'datatype': 'compound','iati-field':thefield})
$(e.currentTarget).val('')
return false
class ModelEditor extends Delegator
widgetTypes:
'.unique_keys_widget': UniqueKeyWidget
'.dimensions_widget': DimensionsWidget
events:
'multipleSectorsRequest': 'onMultipleSectorsSetup'
'modelChange': 'onModelChange'
'fillColumnsRequest': 'onFillColumnsRequest'
'fillIATIfieldsRequest': 'onFillIATIfieldsRequest'
'.steps > ul > li click': 'onStepClick'
'.steps > ul > li > ul > li click': 'onStepDimensionClick'
'.forms form submit': 'onFormSubmit'
'.forms form change': 'onFormChange'
'#showdebug click': 'onShowDebugClick'
'#hidedebug click': 'onHideDebugClick'
'.add_data_field click': 'onAddDataFieldClick'
'doFieldSelectors' : 'onDoFieldSelectors'
'#iatifields .availablebtn click': 'onIATIFieldsAvailableClick'
'#iatifields .allbtn click': 'onIATIFieldsAllClick'
constructor: (element, options) ->
super
$('#multiple_rows_selector').html(
"<option value=''>One row per activity</option>" + ("<option value='#{x}'>Multiple #{x} rows per activity</option>" for x in @options.iatifields when x isnt '').join('\n')
)
if (@options.model_data)
model_data = JSON.parse(@options.model_data)
else
model_data = DEFAULT_MODEL
@data = $.extend(true, {}, model_data)
@widgets = []
@form = $(element).find('.forms form').eq(0)
@id = @element.attr('id')
if not @id?
@id = Math.floor((Math.random()*0xffffffff)).toString(16)
@element.attr('id', @id)
# Precompile templates
@element.find('script[type="text/x-jquery-tmpl"]').each ->
$(this).template($(this).attr('id'))
# Initialize widgets
for selector, ctor of @widgetTypes
@widgets.push(new ctor(e)) for e in @element.find(selector).get()
@element.trigger 'modelChange'
this.setStep 0
setStep: (s) ->
$(@element).find('.steps > ul > li')
.removeClass('active')
.eq(s).addClass('active')
$(@element).find('.forms div.formpart').hide().eq(s).show()
onStepClick: (e) ->
idx = @element.find('.steps > ul > li').index(e.currentTarget)
this.setStep idx
return false
onAddDataFieldClick: (e) ->
thevar = $(e.currentTarget).text()
for w in @widgets
w.promptAddDimensionNamed(thevar,{'datatype': 'value','column':thevar,'label':thevar})
@data = @form.serializeObject()
@element.trigger 'modelChange'
$(e.currentTarget).removeClass('add_data_field available').addClass('unavailable')
onShowDebugClick: (e) ->
$('#model_data').show()
$(document).keydown( (event)->
if event.which == 27
$('#model_data').hide()
)
return false
onHideDebugClick: (e) ->
$('#model_data').hide()
return false
onFormChange: (e) ->
return if @ignoreFormChange
@data = @form.serializeObject()
@element.trigger('doFieldSelectors', 'iatifield')
@element.trigger('doFieldSelectors', 'column')
@ignoreFormChange = true
@element.trigger 'modelChange'
@ignoreFormChange = false
# Missnamed now
onDoFieldSelectors: (e) ->
key = PI:KEY:<KEY>END_PI + 'PI:KEY:<KEY>END_PI'
@options[key] = []
used = @options[key]
@form.find('.' + e).each ->
iatiname = ($(this).val())
if iatiname not in used
used.push(iatiname)
used.sort()
onFormSubmit: (e) ->
# Conversion...
# Need to know:
# 1) model file
# 2) csv file
## these should be in hidden inputs, and then only submit those to the API
# 3) conversion API address should be stored by the system, and the request should be handled by the server.
e.preventDefault();
api_address = 'api_convert';
model_file = $('#convert_model_file_URL').val()
csv_file = $('#convert_csv_file_URL').val()
$.post(api_address, { csv_file: csv_file, model_file: model_file }, complete:(result) ->
alert(result.status);
, "json");
return false;
onModelChange: () ->
# Populate straightforward bits
for k, v of util.flattenObject(@data)
# FIXME? this may not deal with complex form elements such as radio
# buttons or <select multiple>.
@form.find("[name=\"#{k}\"]").val(v)
# Send updated model copy to each subcomponent, as more complex
# components may not have been correctly filled out by the above.
for w in @widgets
w.deserialize($.extend(true, {}, @data))
# Update dimension list in sidebar
dimNames = (k for k, v of @data['mapping'])
@element.find('.steps ul.steps_dimensions').html(
('<li><a href="#' + "m1_dim_#{n}" + '">' + "#{@data['mapping'][n]['label']}</a>" for n in dimNames).join('\n')
)
$('#debug').text(JSON.stringify(@data, null, 2))
onFillColumnsRequest: (elem) ->
options = ["<option></option>", "<option disabled>Unused columns:</option>"]
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.columns when x not in @options.columns_used and x!='' ))
options.push('<option disabled>Previously used columns:</option>')
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.columns_used when x!='' ))
$(elem).html(
options.join('\n')
)
onFillIATIfieldsRequest: (elem) ->
options = ["<option>Add a new element</option>", "<option disabled>Unused elements:</option>"]
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.iatifields when x not in @options.iatifields_used and x!='' ))
options.push('<option disabled>Previously used elements:</option>')
options = options.concat(( "<option value='#{x}'>#{x}</option>" for x in @options.iatifields_used when x!='' ))
$(elem).html(
options.join('\n')
)
$.plugin 'modelEditor', ModelEditor
this.ModelEditor = ModelEditor
|
[
{
"context": "t_type: 'refresh_token'\n refresh_token: unencrypted_refresh\n\n postmanMock.withArgs(postData, route).re",
"end": 932,
"score": 0.6477846503257751,
"start": 913,
"tag": "PASSWORD",
"value": "unencrypted_refresh"
},
{
"context": "ype: 'refresh_token'\n... | test/auth/refresh-spec.coffee | theodorick/ocelot | 13 | assert = require('assert')
sinon = require('sinon')
postman = require('../../src/auth/postman')
redirect = require('../../src/auth/redirect')
setCookies = require('../../src/auth/set-cookies')
refresh = require('../../src/auth/refresh/auth-code-refresh')
crypt = require('../../src/auth/crypt')
postmanMock = undefined
setCookiesMock = undefined
redirectMock = undefined
restore = (mockFunc) ->
if mockFunc and mockFunc.restore
mockFunc.restore()
describe 'refresh', ->
it 'refreshes if post is successful', (done) ->
secret = 'secret'
unencrypted_refresh = 'abc'
req = {}
res = id: 'res'
route = id: 'route'
auth = id: 'auth'
route['cookie-name'] = 'something'
route['client-secret'] = secret
postmanMock = sinon.stub(postman, 'post')
postData =
grant_type: 'refresh_token'
refresh_token: unencrypted_refresh
postmanMock.withArgs(postData, route).returns then: (s, f) ->
s auth
setCookiesMock = sinon.stub(setCookies, 'setAuthCookies')
setCookiesMock.withArgs(res, route, auth).returns then: (s, f) ->
s res
redirectMock = sinon.stub(redirect, 'refreshPage');
redirectMock.withArgs(req, res);
cookies = {'something_rt': crypt.encrypt(unencrypted_refresh, secret)}
refresh.complete req, res, route, cookies
.then ->
assert postmanMock.calledOnce == true
assert redirectMock.calledOnce == true
done()
.catch done
it 'redirects if post is unsuccessful', (done) ->
secret = 'secret'
unencrypted_refresh = 'abc'
req = {}
res = id: 'res'
route = id: 'route'
auth = id: 'auth'
route['cookie-name'] = 'something'
route['client-secret'] = secret
postmanMock = sinon.stub(postman, 'post')
postData =
grant_type: 'refresh_token'
refresh_token: unencrypted_refresh
postmanMock.withArgs(postData, route).returns then: (s, f) ->
f auth
cookies = {'something_rt': crypt.encrypt(unencrypted_refresh, secret)}
redirectMock = sinon.stub(redirect, 'startAuthCode')
redirectMock.withArgs req, res, route, cookies
refresh.complete req, res, route, cookies
.then ->
assert postmanMock.calledOnce == true
assert redirectMock.calledOnce == true
done()
.catch done
afterEach ->
restore postmanMock
restore setCookiesMock
restore redirectMock
| 203106 | assert = require('assert')
sinon = require('sinon')
postman = require('../../src/auth/postman')
redirect = require('../../src/auth/redirect')
setCookies = require('../../src/auth/set-cookies')
refresh = require('../../src/auth/refresh/auth-code-refresh')
crypt = require('../../src/auth/crypt')
postmanMock = undefined
setCookiesMock = undefined
redirectMock = undefined
restore = (mockFunc) ->
if mockFunc and mockFunc.restore
mockFunc.restore()
describe 'refresh', ->
it 'refreshes if post is successful', (done) ->
secret = 'secret'
unencrypted_refresh = 'abc'
req = {}
res = id: 'res'
route = id: 'route'
auth = id: 'auth'
route['cookie-name'] = 'something'
route['client-secret'] = secret
postmanMock = sinon.stub(postman, 'post')
postData =
grant_type: 'refresh_token'
refresh_token: <PASSWORD>
postmanMock.withArgs(postData, route).returns then: (s, f) ->
s auth
setCookiesMock = sinon.stub(setCookies, 'setAuthCookies')
setCookiesMock.withArgs(res, route, auth).returns then: (s, f) ->
s res
redirectMock = sinon.stub(redirect, 'refreshPage');
redirectMock.withArgs(req, res);
cookies = {'something_rt': crypt.encrypt(unencrypted_refresh, secret)}
refresh.complete req, res, route, cookies
.then ->
assert postmanMock.calledOnce == true
assert redirectMock.calledOnce == true
done()
.catch done
it 'redirects if post is unsuccessful', (done) ->
secret = 'secret'
unencrypted_refresh = 'abc'
req = {}
res = id: 'res'
route = id: 'route'
auth = id: 'auth'
route['cookie-name'] = 'something'
route['client-secret'] = secret
postmanMock = sinon.stub(postman, 'post')
postData =
grant_type: 'refresh_token'
refresh_token: un<PASSWORD>_<PASSWORD>
postmanMock.withArgs(postData, route).returns then: (s, f) ->
f auth
cookies = {'something_rt': crypt.encrypt(unencrypted_refresh, secret)}
redirectMock = sinon.stub(redirect, 'startAuthCode')
redirectMock.withArgs req, res, route, cookies
refresh.complete req, res, route, cookies
.then ->
assert postmanMock.calledOnce == true
assert redirectMock.calledOnce == true
done()
.catch done
afterEach ->
restore postmanMock
restore setCookiesMock
restore redirectMock
| true | assert = require('assert')
sinon = require('sinon')
postman = require('../../src/auth/postman')
redirect = require('../../src/auth/redirect')
setCookies = require('../../src/auth/set-cookies')
refresh = require('../../src/auth/refresh/auth-code-refresh')
crypt = require('../../src/auth/crypt')
postmanMock = undefined
setCookiesMock = undefined
redirectMock = undefined
restore = (mockFunc) ->
if mockFunc and mockFunc.restore
mockFunc.restore()
describe 'refresh', ->
it 'refreshes if post is successful', (done) ->
secret = 'secret'
unencrypted_refresh = 'abc'
req = {}
res = id: 'res'
route = id: 'route'
auth = id: 'auth'
route['cookie-name'] = 'something'
route['client-secret'] = secret
postmanMock = sinon.stub(postman, 'post')
postData =
grant_type: 'refresh_token'
refresh_token: PI:PASSWORD:<PASSWORD>END_PI
postmanMock.withArgs(postData, route).returns then: (s, f) ->
s auth
setCookiesMock = sinon.stub(setCookies, 'setAuthCookies')
setCookiesMock.withArgs(res, route, auth).returns then: (s, f) ->
s res
redirectMock = sinon.stub(redirect, 'refreshPage');
redirectMock.withArgs(req, res);
cookies = {'something_rt': crypt.encrypt(unencrypted_refresh, secret)}
refresh.complete req, res, route, cookies
.then ->
assert postmanMock.calledOnce == true
assert redirectMock.calledOnce == true
done()
.catch done
it 'redirects if post is unsuccessful', (done) ->
secret = 'secret'
unencrypted_refresh = 'abc'
req = {}
res = id: 'res'
route = id: 'route'
auth = id: 'auth'
route['cookie-name'] = 'something'
route['client-secret'] = secret
postmanMock = sinon.stub(postman, 'post')
postData =
grant_type: 'refresh_token'
refresh_token: unPI:PASSWORD:<PASSWORD>END_PI_PI:PASSWORD:<PASSWORD>END_PI
postmanMock.withArgs(postData, route).returns then: (s, f) ->
f auth
cookies = {'something_rt': crypt.encrypt(unencrypted_refresh, secret)}
redirectMock = sinon.stub(redirect, 'startAuthCode')
redirectMock.withArgs req, res, route, cookies
refresh.complete req, res, route, cookies
.then ->
assert postmanMock.calledOnce == true
assert redirectMock.calledOnce == true
done()
.catch done
afterEach ->
restore postmanMock
restore setCookiesMock
restore redirectMock
|
[
{
"context": "LogParser constructor.\nDEFAULT_QUERYSTRING_KEY = 'hashmonitor'\n\nclass HttpAccessLogParser\n\n constructor: (key)",
"end": 198,
"score": 0.9981241226196289,
"start": 187,
"tag": "KEY",
"value": "hashmonitor"
}
] | lib/inputs/httpaccess.coffee | olark/hashmonitor | 8 | # We match HTTP access log lines with querystring `hashmonitor=<encoded_data>`
# by default, but this can be overridden in the HttpAccessLogParser constructor.
DEFAULT_QUERYSTRING_KEY = 'hashmonitor'
class HttpAccessLogParser
constructor: (key) ->
# We match all log lines against this pattern.
key or= DEFAULT_QUERYSTRING_KEY
@lineRegex = new RegExp("#{key}\\=([^\\s\\&\\?\\#\\'\\\"$]+)")
parse: (line) ->
# Make a best attempt to parse, but return the original line if
# anything fails.
matches = line.match(@lineRegex)
if matches
try
return decodeURIComponent(matches[1])
catch error
console.warn(error)
return line
else
return line
exports.HttpAccessLogParser = HttpAccessLogParser
| 160948 | # We match HTTP access log lines with querystring `hashmonitor=<encoded_data>`
# by default, but this can be overridden in the HttpAccessLogParser constructor.
DEFAULT_QUERYSTRING_KEY = '<KEY>'
class HttpAccessLogParser
constructor: (key) ->
# We match all log lines against this pattern.
key or= DEFAULT_QUERYSTRING_KEY
@lineRegex = new RegExp("#{key}\\=([^\\s\\&\\?\\#\\'\\\"$]+)")
parse: (line) ->
# Make a best attempt to parse, but return the original line if
# anything fails.
matches = line.match(@lineRegex)
if matches
try
return decodeURIComponent(matches[1])
catch error
console.warn(error)
return line
else
return line
exports.HttpAccessLogParser = HttpAccessLogParser
| true | # We match HTTP access log lines with querystring `hashmonitor=<encoded_data>`
# by default, but this can be overridden in the HttpAccessLogParser constructor.
DEFAULT_QUERYSTRING_KEY = 'PI:KEY:<KEY>END_PI'
class HttpAccessLogParser
constructor: (key) ->
# We match all log lines against this pattern.
key or= DEFAULT_QUERYSTRING_KEY
@lineRegex = new RegExp("#{key}\\=([^\\s\\&\\?\\#\\'\\\"$]+)")
parse: (line) ->
# Make a best attempt to parse, but return the original line if
# anything fails.
matches = line.match(@lineRegex)
if matches
try
return decodeURIComponent(matches[1])
catch error
console.warn(error)
return line
else
return line
exports.HttpAccessLogParser = HttpAccessLogParser
|
[
{
"context": "./lib/jquery.formance.js')\n\nVALID_EMAILS = [\n 'john@example.com'\n 'very.common@example.com'\n 'a.little.leng",
"end": 152,
"score": 0.999808132648468,
"start": 136,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": "s')\n\nVALID_EMAILS = [\n 'j... | test/fields/email.coffee | hedou/jquery.formance | 149 | assert = require('assert')
$ = require('jquery')
global.jQuery = $
require('../../lib/jquery.formance.js')
VALID_EMAILS = [
'john@example.com'
'very.common@example.com'
'a.little.lengthy.but.fine@dept.example.com'
'disposable.style.email.with+symbol@example.com'
# 'user@[IPv6:2001:db8:1ff::a0b:dbd0]'
# '"much.more unusual"@example.com'
# '"very.unusual.@.unusual.com"@example.com'
# '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com'
# 'postbox@com'
# 'admin@mailserver1'
'!#$%&\'*+-/=?^_`{}|~@example.org'
# '"()<>[]:,;@\\\"!#$%&\'*+-/=?^_`{}| ~.a"@example.org'
# '" "@example.org'
]
INVALID_EMAILS = [
# 'Abc.example.com'
# 'A@b@c@example.com'
'a"b(c)d,e:f;g<h>i[j\k]l@example.com'
'just"not"right@example.com'
# 'this is"not\allowed@example.com'
# 'this\ still\"not\\allowed@example.com'
]
describe 'email.js', ->
describe 'Validating an email address', ->
it 'should fail if empty', ->
$email = $('<input>').val('')
assert.equal false, $email.formance('validate_email')
it 'should fail if it is a bunch of spaces', ->
$email = $('<input>').val(' ')
assert.equal false, $email.formance('validate_email')
it 'should succeed with valid emails', ->
for email in VALID_EMAILS
$email = $('<input>').val(email)
assert.equal true, $email.formance('validate_email')
it 'should succeed with invalid emails, (using the simple algorithm) has false nagatives', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
assert.equal true, $email.formance('validate_email')
# complex algorithm
it 'should succeed with valid emails using the complex algorithm', ->
for email in VALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'complex')
assert.equal true, $email.formance('validate_email')
it 'should fail with invalid emails using the complex algorithm', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'complex')
assert.equal false, $email.formance('validate_email')
# algorithm that does not exist
it 'should resort to simple algorithm if it can\'t find the algorithm specified', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'does_not_exist')
assert.equal true, $email.formance('validate_email')
| 75298 | assert = require('assert')
$ = require('jquery')
global.jQuery = $
require('../../lib/jquery.formance.js')
VALID_EMAILS = [
'<EMAIL>'
'<EMAIL>'
'<EMAIL>'
'<EMAIL>'
# 'user@[IPv6:2001:db8:1ff::a0b:dbd0]'
# '"much.more unusual"@<EMAIL>'
# '"<EMAIL>"@<EMAIL>'
# '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@str<EMAIL>'
# 'postbox@com'
# 'admin@mailserver1'
'!#$%&\'*+-/=?^_`{}|~@<EMAIL>'
# '"()<>[]:,;@\\\"!#$%&\'*+-/=?^_`{}| ~.a"@<EMAIL>'
# '" "@example.org'
]
INVALID_EMAILS = [
# '<EMAIL>'
# '<EMAIL>'
'a"b(c)d,e:f;g<h>i[j\k]<EMAIL>'
'just"not"<EMAIL>'
# 'this is"<EMAIL>'
# 'this\ still\"<EMAIL>'
]
describe 'email.js', ->
describe 'Validating an email address', ->
it 'should fail if empty', ->
$email = $('<input>').val('')
assert.equal false, $email.formance('validate_email')
it 'should fail if it is a bunch of spaces', ->
$email = $('<input>').val(' ')
assert.equal false, $email.formance('validate_email')
it 'should succeed with valid emails', ->
for email in VALID_EMAILS
$email = $('<input>').val(email)
assert.equal true, $email.formance('validate_email')
it 'should succeed with invalid emails, (using the simple algorithm) has false nagatives', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
assert.equal true, $email.formance('validate_email')
# complex algorithm
it 'should succeed with valid emails using the complex algorithm', ->
for email in VALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'complex')
assert.equal true, $email.formance('validate_email')
it 'should fail with invalid emails using the complex algorithm', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'complex')
assert.equal false, $email.formance('validate_email')
# algorithm that does not exist
it 'should resort to simple algorithm if it can\'t find the algorithm specified', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'does_not_exist')
assert.equal true, $email.formance('validate_email')
| true | assert = require('assert')
$ = require('jquery')
global.jQuery = $
require('../../lib/jquery.formance.js')
VALID_EMAILS = [
'PI:EMAIL:<EMAIL>END_PI'
'PI:EMAIL:<EMAIL>END_PI'
'PI:EMAIL:<EMAIL>END_PI'
'PI:EMAIL:<EMAIL>END_PI'
# 'user@[IPv6:2001:db8:1ff::a0b:dbd0]'
# '"much.more unusual"@PI:EMAIL:<EMAIL>END_PI'
# '"PI:EMAIL:<EMAIL>END_PI"@PI:EMAIL:<EMAIL>END_PI'
# '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strPI:EMAIL:<EMAIL>END_PI'
# 'postbox@com'
# 'admin@mailserver1'
'!#$%&\'*+-/=?^_`{}|~@PI:EMAIL:<EMAIL>END_PI'
# '"()<>[]:,;@\\\"!#$%&\'*+-/=?^_`{}| ~.a"@PI:EMAIL:<EMAIL>END_PI'
# '" "@example.org'
]
INVALID_EMAILS = [
# 'PI:EMAIL:<EMAIL>END_PI'
# 'PI:EMAIL:<EMAIL>END_PI'
'a"b(c)d,e:f;g<h>i[j\k]PI:EMAIL:<EMAIL>END_PI'
'just"not"PI:EMAIL:<EMAIL>END_PI'
# 'this is"PI:EMAIL:<EMAIL>END_PI'
# 'this\ still\"PI:EMAIL:<EMAIL>END_PI'
]
describe 'email.js', ->
describe 'Validating an email address', ->
it 'should fail if empty', ->
$email = $('<input>').val('')
assert.equal false, $email.formance('validate_email')
it 'should fail if it is a bunch of spaces', ->
$email = $('<input>').val(' ')
assert.equal false, $email.formance('validate_email')
it 'should succeed with valid emails', ->
for email in VALID_EMAILS
$email = $('<input>').val(email)
assert.equal true, $email.formance('validate_email')
it 'should succeed with invalid emails, (using the simple algorithm) has false nagatives', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
assert.equal true, $email.formance('validate_email')
# complex algorithm
it 'should succeed with valid emails using the complex algorithm', ->
for email in VALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'complex')
assert.equal true, $email.formance('validate_email')
it 'should fail with invalid emails using the complex algorithm', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'complex')
assert.equal false, $email.formance('validate_email')
# algorithm that does not exist
it 'should resort to simple algorithm if it can\'t find the algorithm specified', ->
for email in INVALID_EMAILS
$email = $('<input>').val(email)
.data('formance_algorithm', 'does_not_exist')
assert.equal true, $email.formance('validate_email')
|
[
{
"context": "', ($scope) ->\n $scope.quotes = [\n { author: \"Spock\", text: \"Insufficient facts always invite danger.",
"end": 121,
"score": 0.9995951652526855,
"start": 116,
"tag": "NAME",
"value": "Spock"
},
{
"context": "ent facts always invite danger.\" }\n { author: \"... | app/assets/javascripts/angular/base/controllers/ipsum.coffee | reckoning/app | 9 | angular.module 'Reckoning'
.controller 'IpsumController', ['$scope', ($scope) ->
$scope.quotes = [
{ author: "Spock", text: "Insufficient facts always invite danger." }
{ author: "Spock", text: "There are always alternatives." }
{ author: "Spock", text: "Without followers, evil cannot spread." }
{ author: "William T. Riker", text: "The unexpected is our normal routine." }
{ author: "Spock", text: "Change is the essential process of all existence." }
{ author: "James T. Kirk", text: "... a dream that became a reality and spread throughout the stars" }
{ author: "Spock", text: "Creativity is necessary for the health of the body." }
{ author: "Spock", text: "Logic is the beginning of wisdom, not the end." }
]
$scope.quote = $scope.quotes[Math.floor(Math.random() * $scope.quotes.length)]
]
| 31604 | angular.module 'Reckoning'
.controller 'IpsumController', ['$scope', ($scope) ->
$scope.quotes = [
{ author: "<NAME>", text: "Insufficient facts always invite danger." }
{ author: "<NAME>", text: "There are always alternatives." }
{ author: "<NAME>", text: "Without followers, evil cannot spread." }
{ author: "<NAME>", text: "The unexpected is our normal routine." }
{ author: "<NAME>", text: "Change is the essential process of all existence." }
{ author: "<NAME>", text: "... a dream that became a reality and spread throughout the stars" }
{ author: "<NAME>", text: "Creativity is necessary for the health of the body." }
{ author: "<NAME>", text: "Logic is the beginning of wisdom, not the end." }
]
$scope.quote = $scope.quotes[Math.floor(Math.random() * $scope.quotes.length)]
]
| true | angular.module 'Reckoning'
.controller 'IpsumController', ['$scope', ($scope) ->
$scope.quotes = [
{ author: "PI:NAME:<NAME>END_PI", text: "Insufficient facts always invite danger." }
{ author: "PI:NAME:<NAME>END_PI", text: "There are always alternatives." }
{ author: "PI:NAME:<NAME>END_PI", text: "Without followers, evil cannot spread." }
{ author: "PI:NAME:<NAME>END_PI", text: "The unexpected is our normal routine." }
{ author: "PI:NAME:<NAME>END_PI", text: "Change is the essential process of all existence." }
{ author: "PI:NAME:<NAME>END_PI", text: "... a dream that became a reality and spread throughout the stars" }
{ author: "PI:NAME:<NAME>END_PI", text: "Creativity is necessary for the health of the body." }
{ author: "PI:NAME:<NAME>END_PI", text: "Logic is the beginning of wisdom, not the end." }
]
$scope.quote = $scope.quotes[Math.floor(Math.random() * $scope.quotes.length)]
]
|
[
{
"context": "###\nCopyright (c) 2014 Ramesh Nair (hiddentao.com)\n\nPermission is hereby granted, fr",
"end": 34,
"score": 0.9998830556869507,
"start": 23,
"tag": "NAME",
"value": "Ramesh Nair"
},
{
"context": " #\n # Original idea posted in https://github.com/hiddentao/export/issu... | src/squel.coffee | SimeonC/squel | 0 | ###
Copyright (c) 2014 Ramesh Nair (hiddentao.com)
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.
###
# Extend given object's with other objects' properties, overriding existing ones if necessary
_extend = (dst, sources...) ->
if sources
for src in sources
if src
for own k,v of src
dst[k] = v
dst
# Get a copy of given object with given properties removed
_without = (obj, properties...) ->
dst = _extend {}, obj
for p in properties
delete dst[p]
dst
# Register a value type handler
#
# Note: this will override any existing handler registered for this value type.
registerValueHandler = (handlers, type, handler) ->
if 'function' isnt typeof type and 'string' isnt typeof type
throw new Error "type must be a class constructor or string denoting 'typeof' result"
if 'function' isnt typeof handler
throw new Error "handler must be a function"
for typeHandler in handlers
if typeHandler.type is type
typeHandler.handler = handler
return
handlers.push
type: type
handler: handler
# Get value type handler for given type
getValueHandler = (value, handlerLists...) ->
for handlers in handlerLists
for typeHandler in handlers
# if type is a string then use `typeof` or else use `instanceof`
if typeHandler.type is typeof value or (typeof typeHandler.type isnt 'string' and value instanceof typeHandler.type)
return typeHandler.handler
undefined
# Build base squel classes and methods
_buildSquel = ->
# Holds classes
cls = {}
# Default query builder options
cls.DefaultQueryBuilderOptions =
# If true then table names will be rendered inside quotes. The quote character used is configurable via the
# nameQuoteCharacter option.
autoQuoteTableNames: false
# If true then field names will rendered inside quotes. The quote character used is configurable via the
# nameQuoteCharacter option.
autoQuoteFieldNames: false
# If true then alias names will rendered inside quotes. The quote character used is configurable via the `tableAliasQuoteCharacter` and `fieldAliasQuoteCharacter` options.
autoQuoteAliasNames: true
# The quote character used for when quoting table and field names
nameQuoteCharacter: '`'
# The quote character used for when quoting table alias names
tableAliasQuoteCharacter: '`'
# The quote character used for when quoting table alias names
fieldAliasQuoteCharacter: '"'
# Custom value handlers where key is the value type and the value is the handler function
valueHandlers: []
# Number parameters returned from toParam() as $1, $2, etc. Default is to use '?', startAt 1 will give $1...
numberedParameters: false
numberedParametersStartAt: 1
# If true then replaces all single quotes within strings. The replacement string used is configurable via the `singleQuoteReplacement` option.
replaceSingleQuotes: false
# The string to replace single quotes with in query strings
singleQuoteReplacement: '\'\''
# String used to join individual blocks in a query when it's stringified
separator: ' '
# Global custom value handlers for all instances of builder
cls.globalValueHandlers = []
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Custom value types
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Register a new value handler
cls.registerValueHandler = (type, handler) ->
registerValueHandler cls.globalValueHandlers, type, handler
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.FuncVal
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# A function value
class cls.FuncVal
# Constructor
#
# str - the string
# values - the parameter values
constructor: (str, values) ->
@str = str
@values = values
# Construct a FuncVal object
cls.fval = (str, values...) ->
new cls.FuncVal(str, values)
# default value handler for cls.FuncVal
cls.fval_handler = (value, asParam = false) ->
if asParam
{
text: value.str
values: value.values
}
else
str = value.str
finalStr = ''
values = value.values
for idx in [0...str.length]
c = str.charAt(idx)
if '?' is c and 0 < values.length
c = values.shift()
finalStr += c
finalStr
cls.registerValueHandler cls.FuncVal, cls.fval_handler
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base classes
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base class for cloneable builders
class cls.Cloneable
# Clone this builder
clone: ->
newInstance = new @constructor;
# Fast deep copy using JSON conversion, see http://stackoverflow.com/a/5344074
_extend newInstance, JSON.parse(JSON.stringify(@))
# Base class for all builders
class cls.BaseBuilder extends cls.Cloneable
# Constructor
#
# options is an Object overriding one or more of cls.DefaultQueryBuilderOptions
#
constructor: (options) ->
defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions))
@options = _extend {}, defaults, options
# Register a custom value handler for this builder instance.
#
# Note: this will override any globally registered handler for this value type.
registerValueHandler: (type, handler) ->
registerValueHandler @options.valueHandlers, type, handler
@
# Get class name of given object.
_getObjectClassName: (obj) ->
if obj && obj.constructor && obj.constructor.toString
arr = obj.constructor.toString().match /function\s*(\w+)/;
if arr && arr.length is 2
return arr[1]
return undefined
# Sanitize the given condition.
_sanitizeCondition: (condition) ->
# If it's not an Expression builder instance
if not (condition instanceof cls.Expression)
# It must then be a string
if "string" isnt typeof condition
throw new Error "condition must be a string or Expression instance"
condition
# Sanitize the given name.
# The 'type' parameter is used to construct a meaningful error message in case validation fails.
_sanitizeName: (value, type) ->
if "string" isnt typeof value
throw new Error "#{type} must be a string"
value
_sanitizeField: (item, formattingOptions = {}) ->
if item instanceof cls.QueryBuilder
item = "(#{item})"
else
item = @_sanitizeName item, "field name"
if @options.autoQuoteFieldNames
quoteChar = @options.nameQuoteCharacter
if formattingOptions.ignorePeriodsForFieldNameQuotes
# a.b.c -> `a.b.c`
item = "#{quoteChar}#{item}#{quoteChar}"
else
# a.b.c -> `a`.`b`.`c`
item = item
.split('.')
.map( (v) ->
# treat '*' as special case (#79)
return if '*' is v then v else "#{quoteChar}#{v}#{quoteChar}"
)
.join('.')
item
_sanitizeNestableQuery: (item) =>
return item if item instanceof cls.QueryBuilder and item.isNestable()
throw new Error "must be a nestable query, e.g. SELECT"
_sanitizeTable: (item, allowNested = false) ->
if allowNested
if "string" is typeof item
sanitized = item
else
try
sanitized = @_sanitizeNestableQuery(item)
catch e
throw new Error "table name must be a string or a nestable query instance"
else
sanitized = @_sanitizeName item, 'table name'
if @options.autoQuoteTableNames
"#{@options.nameQuoteCharacter}#{sanitized}#{@options.nameQuoteCharacter}"
else
sanitized
_sanitizeTableAlias: (item) ->
sanitized = @_sanitizeName item, "table alias"
if @options.autoQuoteAliasNames
"#{@options.tableAliasQuoteCharacter}#{sanitized}#{@options.tableAliasQuoteCharacter}"
else
sanitized
_sanitizeFieldAlias: (item) ->
sanitized = @_sanitizeName item, "field alias"
if @options.autoQuoteAliasNames
"#{@options.fieldAliasQuoteCharacter}#{sanitized}#{@options.fieldAliasQuoteCharacter}"
else
sanitized
# Sanitize the given limit/offset value.
_sanitizeLimitOffset: (value) ->
value = parseInt(value)
if 0 > value or isNaN(value)
throw new Error "limit/offset must be >= 0"
value
# Santize the given field value
_sanitizeValue: (item) ->
itemType = typeof item
if null is item
# null is allowed
else if "string" is itemType or "number" is itemType or "boolean" is itemType
# primitives are allowed
else if item instanceof cls.QueryBuilder and item.isNestable()
# QueryBuilder instances allowed
else if item instanceof cls.FuncVal
# FuncVal instances allowed
else
typeIsValid = undefined isnt getValueHandler(item, @options.valueHandlers, cls.globalValueHandlers)
unless typeIsValid
# type is not valid
throw new Error "field value must be a string, number, boolean, null or one of the registered custom value types"
item
# Escape a string value, e.g. escape quotes and other characters within it.
_escapeValue: (value) ->
return value unless true is @options.replaceSingleQuotes
value.replace /\'/g, @options.singleQuoteReplacement
# Format the given custom value
_formatCustomValue: (value, asParam = false) ->
# user defined custom handlers takes precedence
customHandler = getValueHandler(value, @options.valueHandlers, cls.globalValueHandlers)
if customHandler
# use the custom handler if available
value = customHandler(value, asParam)
value
# Format the given field value for inclusion into query parameter array
_formatValueAsParam: (value) ->
if Array.isArray(value)
value.map (v) => @_formatValueAsParam v
else
if value instanceof cls.QueryBuilder and value.isNestable()
value.updateOptions( { "nestedBuilder": true } )
p = value.toParam()
else if value instanceof cls.Expression
p = value.toParam()
else
@_formatCustomValue(value, true)
# Format the given field value for inclusion into the query string
_formatValue: (value, formattingOptions = {}) ->
customFormattedValue = @_formatCustomValue(value)
# if formatting took place then return it directly
if customFormattedValue isnt value
return "(#{customFormattedValue})"
# if it's an array then format each element separately
if Array.isArray(value)
value = value.map (v) => @_formatValue v
value = "(#{value.join(', ')})"
else
if null is value
value = "NULL"
else if "boolean" is typeof value
value = if value then "TRUE" else "FALSE"
else if value instanceof cls.QueryBuilder
value = "(#{value})"
else if value instanceof cls.Expression
value = "(#{value})"
else if "number" isnt typeof value
value = @_escapeValue(value)
value = if formattingOptions.dontQuote then "#{value}" else "'#{value}'"
value
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Expressions
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# An SQL expression builder.
#
# SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
#
# This builder works by building up the expression as a hierarchical tree of nodes. The toString() method then
# traverses this tree in order to build the final expression string.
#
# cls.Expressions can be nested. Nested expression contains can themselves contain nested expressions.
# When rendered a nested expression will be fully contained within brackets.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class cls.Expression extends cls.BaseBuilder
# The expression tree.
tree: null
# The part of the expression tree we're currently working on.
current: null
# Initialise the expression.
constructor: ->
super()
@tree =
parent: null
nodes: []
@current = @tree
# Begin a nested expression and combine it with the current expression using the given operator.
@_begin = (op) =>
new_tree =
type: op
parent: @current
nodes: []
@current.nodes.push new_tree
@current = @current.nodes[@current.nodes.length-1]
@
# Begin a nested expression and combine it with the current expression using the intersection operator (AND).
and_begin: ->
@_begin 'AND'
# Begin a nested expression and combine it with the current expression using the union operator (OR).
or_begin: ->
@_begin 'OR'
# End the current compound expression.
#
# This will throw an error if begin() hasn't been called yet.
end: ->
if not @current.parent
throw new Error "begin() needs to be called"
@current = @current.parent
@
# Combine the current expression with the given expression using the intersection operator (AND).
and: (expr, param) ->
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'AND'
expr: expr
para: param
@
# Combine the current expression with the given expression using the union operator (OR).
or: (expr, param) ->
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'OR'
expr: expr
para: param
@
# Get the final fully constructed expression string.
toString: ->
if null isnt @current.parent
throw new Error "end() needs to be called"
@_toString @tree
# Get the final fully constructed expression string.
toParam: ->
if null isnt @current.parent
throw new Error "end() needs to be called"
@_toString @tree, true
# Get a string representation of the given expression tree node.
_toString: (node, paramMode = false) ->
str = ""
params = []
for child in node.nodes
if child.expr?
nodeStr = child.expr
# have param?
if undefined isnt child.para
if not paramMode
nodeStr = nodeStr.replace '?', @_formatValue(child.para)
else
cv = @_formatValueAsParam child.para
if (cv?.text?)
params = params.concat(cv.values)
nodeStr = nodeStr.replace '?', "(#{cv.text})"
else
params = params.concat(cv)
# IN ? -> IN (?, ?, ..., ?)
if Array.isArray(child.para)
inStr = Array.apply(null, new Array(child.para.length)).map () -> '?'
nodeStr = nodeStr.replace '?', "(#{inStr.join(', ')})"
else
nodeStr = @_toString(child, paramMode)
if paramMode
params = params.concat(nodeStr.values)
nodeStr = nodeStr.text
# wrap nested expressions in brackets
if "" isnt nodeStr
nodeStr = "(" + nodeStr + ")"
if "" isnt nodeStr
# if this isn't first expression then add the operator
if "" isnt str then str += " " + child.type + " "
str += nodeStr
if paramMode
return {
text: str
values: params
}
else
return str
###
Clone this expression.
Note that the algorithm contained within this method is probably non-optimal, so please avoid cloning large
expression trees.
###
clone: ->
newInstance = new @constructor;
(_cloneTree = (node) ->
for child in node.nodes
if child.expr?
newInstance.current.nodes.push JSON.parse(JSON.stringify(child))
else
newInstance._begin child.type
_cloneTree child
if not @current is child
newInstance.end()
)(@tree)
newInstance
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Building blocks
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# A building block represents a single build-step within a query building process.
#
# Query builders consist of one or more building blocks which get run in a particular order. Building blocks can
# optionally specify methods to expose through the query builder interface. They can access all the input data for
# the query builder and manipulate it as necessary, as well as append to the final query string output.
#
# If you wish to customize how queries get built or add proprietary query phrases and content then it is recommended
# that you do so using one or more custom building blocks.
#
# Original idea posted in https://github.com/hiddentao/export/issues/10#issuecomment-15016427
class cls.Block extends cls.BaseBuilder
# Get input methods to expose within the query builder.
#
# By default all methods except the following get returned:
# methods prefixed with _
# constructor and buildStr()
#
# @return Object key -> function pairs
exposedMethods: ->
ret = {}
for attr, value of @
# only want functions from this class
if typeof value is "function" and attr.charAt(0) isnt '_' and !cls.Block::[attr]
ret[attr] = value
ret
# Build this block.
#
# Subclasses may override this method.
#
# @param queryBuilder cls.QueryBuilder a reference to the query builder that owns this block.
#
# @return String the string representing this block
buildStr: (queryBuilder) ->
''
buildParam: (queryBuilder) ->
{ text: @buildStr(queryBuilder), values: [] }
# A String which always gets output
class cls.StringBlock extends cls.Block
constructor: (options, str) ->
super options
@str = str
buildStr: (queryBuilder) ->
@str
# A values which gets output as is
class cls.AbstractValueBlock extends cls.Block
constructor: (options) ->
super options
@_val = null
_setValue: (val) ->
@_val = val
buildStr: (queryBuilder) ->
if not @_val then "" else @_val
# Table specifier base class
#
# Additional options
# - singleTable - only allow one table to be specified (default: false)
# - allowNested - allow nested query to be specified as a table (default: false)
class cls.AbstractTableBlock extends cls.Block
constructor: (options) ->
super options
@tables = []
# Update given table.
#
# An alias may also be specified for the table.
#
# Concrete subclasses should provide a method which calls this
_table: (table, alias = null) ->
alias = @_sanitizeTableAlias(alias) if alias
table = @_sanitizeTable(table, @options.allowNested or false)
if @options.singleTable
@tables = []
@tables.push
table: table
alias: alias
buildStr: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "_table() needs to be called"
tables = ""
for table in @tables
tables += ", " if "" isnt tables
if "string" is typeof table.table
tables += table.table
else
# building a nested query
tables += "(#{table.table})"
if table.alias
# add the table alias, the AS keyword is optional
tables += " #{table.alias}"
tables
_buildParam: (queryBuilder, prefix = null) ->
ret =
text: ""
values: []
params = []
paramStr = ""
if 0 >= @tables.length then return ret
# retrieve the parameterised queries
for blk in @tables
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
p.table = blk
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
if paramStr isnt ""
paramStr += ", "
else
paramStr += "#{prefix} #{paramStr}" if prefix? and prefix isnt ""
paramStr
if "string" is typeof p.table.table
paramStr += "#{p.text}"
else
paramStr += "(#{p.text})"
# add the table alias, the AS keyword is optional
paramStr += " #{p.table.alias}" if p.table.alias?
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += paramStr
ret
buildParam: (queryBuilder) ->
@_buildParam(queryBuilder)
# Update Table
class cls.UpdateTableBlock extends cls.AbstractTableBlock
table: (table, alias = null) ->
@_table(table, alias)
# FROM table
class cls.FromTableBlock extends cls.AbstractTableBlock
from: (table, alias = null) ->
@_table(table, alias)
buildStr: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "from() needs to be called"
tables = super queryBuilder
"FROM #{tables}"
buildParam: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "from() needs to be called"
@_buildParam(queryBuilder, "FROM")
# INTO table
class cls.IntoTableBlock extends cls.Block
constructor: (options) ->
super options
@table = null
# Into given table.
into: (table) ->
# do not allow nested table to be the target
@table = @_sanitizeTable(table, false)
buildStr: (queryBuilder) ->
if not @table then throw new Error "into() needs to be called"
"INTO #{@table}"
# (SELECT) Get field
class cls.GetFieldBlock extends cls.Block
constructor: (options) ->
super options
@_fieldAliases = {}
@_fields = []
# Add the given fields to the final result set.
#
# The parameter is an Object containing field names (or database functions) as the keys and aliases for the fields
# as the values. If the value for a key is null then no alias is set for that field.
#
# Internally this method simply calls the field() method of this block to add each individual field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
fields: (_fields, options = {}) ->
if Array.isArray(_fields)
for field in _fields
@field field, null, options
else
for field, alias of _fields
@field(field, alias, options)
# Add the given field to the final result set.
#
# The 'field' parameter does not necessarily have to be a fieldname. It can use database functions too,
# e.g. DATE_FORMAT(a.started, "%H")
#
# An alias may also be specified for this field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
field: (field, alias = null, options = {}) ->
field = @_sanitizeField(field, options)
alias = @_sanitizeFieldAlias(alias) if alias
# if field-alias already present then don't add
return if @_fieldAliases[field] is alias
@_fieldAliases[field] = alias
@_fields.push
name: field
alias: alias
buildStr: (queryBuilder) ->
fields = ""
for field in @_fields
fields += ", " if "" isnt fields
fields += field.name
fields += " AS #{field.alias}" if field.alias
if "" is fields then "*" else fields
# Base class for setting fields to values (used for INSERT and UPDATE queries)
class cls.AbstractSetFieldBlock extends cls.Block
constructor: (options) ->
super options
@fieldOptions = []
@fields = []
@values = []
# Update the given field with the given value.
# This will override any previously set value for the given field.
_set: (field, value, options = {}) ->
throw new Error "Cannot call set or setFields on multiple rows of fields." if @values.length > 1
value = @_sanitizeValue(value) if undefined isnt value
# Explicity overwrite existing fields
index = @fields.indexOf(@_sanitizeField(field, options))
if index isnt -1
@values[0][index] = value
@fieldOptions[0][index] = options
else
@fields.push @_sanitizeField(field, options)
index = @fields.length - 1
# The first value added needs to create the array of values for the row
if Array.isArray(@values[0])
@values[0][index] = value
@fieldOptions[0][index] = options
else
@values.push [value]
@fieldOptions.push [options]
@
# Insert fields based on the key/value pairs in the given object
_setFields: (fields, options = {}) ->
throw new Error "Expected an object but got " + typeof fields unless typeof fields is 'object'
for own field of fields
@_set field, fields[field], options
@
# Insert multiple rows for the given fields. Accepts an array of objects.
# This will override all previously set values for every field.
_setFieldsRows: (fieldsRows, options = {}) ->
throw new Error "Expected an array of objects but got " + typeof fieldsRows unless Array.isArray(fieldsRows)
# Reset the objects stored fields and values
@fields = []
@values = []
for i in [0...fieldsRows.length]
for own field of fieldsRows[i]
index = @fields.indexOf(@_sanitizeField(field, options))
throw new Error 'All fields in subsequent rows must match the fields in the first row' if 0 < i and -1 is index
# Add field only if it hasn't been added before
if -1 is index
@fields.push @_sanitizeField(field, options)
index = @fields.length - 1
value = @_sanitizeValue(fieldsRows[i][field])
# The first value added needs to add the array
if Array.isArray(@values[i])
@values[i][index] = value
@fieldOptions[i][index] = options
else
@values[i] = [value]
@fieldOptions[i] = [options]
@
buildStr: ->
throw new Error('Not yet implemented')
buildParam: ->
throw new Error('Not yet implemented')
# (UPDATE) SET field=value
class cls.SetFieldBlock extends cls.AbstractSetFieldBlock
set: (field, value, options) ->
@_set field, value, options
setFields: (fields, options) ->
@_setFields fields, options
buildStr: (queryBuilder) ->
if 0 >= @fields.length then throw new Error "set() needs to be called"
str = ""
for i in [0...@fields.length]
field = @fields[i]
str += ", " if "" isnt str
value = @values[0][i]
fieldOptions = @fieldOptions[0][i]
if typeof value is 'undefined' # e.g. if field is an expression such as: count = count + 1
str += field
else
str += "#{field} = #{if fieldOptions.dontQuote and typeof value is 'string' then value else @_formatValue(value, fieldOptions)}"
"SET #{str}"
buildParam: (queryBuilder) ->
if 0 >= @fields.length then throw new Error "set() needs to be called"
str = ""
vals = []
for i in [0...@fields.length]
field = @fields[i]
str += ", " if "" isnt str
value = @values[0][i]
if typeof value is 'undefined' # e.g. if field is an expression such as: count = count + 1
str += field
else
p = @_formatValueAsParam( value )
if p?.text?
str += "#{field} = (#{p.text})"
for v in p.values
vals.push v
else
str += "#{field} = ?"
vals.push p
{ text: "SET #{str}", values: vals }
# (INSERT INTO) ... field ... value
class cls.InsertFieldValueBlock extends cls.AbstractSetFieldBlock
set: (field, value, options = {}) ->
@_set field, value, options
setFields: (fields, options) ->
@_setFields fields, options
setFieldsRows: (fieldsRows, options) ->
@_setFieldsRows fieldsRows, options
_buildVals: ->
vals = []
for i in [0...@values.length]
for j in [0...@values[i].length]
formattedValue = if @fieldOptions[i][j].dontQuote and typeof @values[i][j] is 'string' then @values[i][j] else @_formatValue @values[i][j], @fieldOptions[i][j]
if 'string' is typeof vals[i]
vals[i] += ', ' + formattedValue
else
vals[i] = '' + formattedValue
vals
_buildValParams: ->
vals = []
params = []
for i in [0...@values.length]
for j in [0...@values[i].length]
p = @_formatValueAsParam( @values[i][j] )
if p?.text?
str = p.text
for v in p.values
params.push v
else
str = '?'
params.push p
if 'string' is typeof vals[i]
vals[i] += ", #{str}"
else
vals[i] = "#{str}"
vals: vals
params: params
buildStr: (queryBuilder) ->
return '' if 0 >= @fields.length
"(#{@fields.join(', ')}) VALUES (#{@_buildVals().join('), (')})"
buildParam: (queryBuilder) ->
return { text: '', values: [] } if 0 >= @fields.length
# fields
str = ""
{vals, params} = @_buildValParams()
for i in [0...@fields.length]
str += ", " if "" isnt str
str += @fields[i]
{ text: "(#{str}) VALUES (#{vals.join('), (')})", values: params }
# (INSERT INTO) ... field ... (SELECT ... FROM ...)
class cls.InsertFieldsFromQueryBlock extends cls.Block
constructor: (options) ->
super options
@_fields = []
@_query = null
fromQuery: (fields, selectQuery) ->
@_fields = fields.map ( (v) => @_sanitizeField(v) )
@_query = @_sanitizeNestableQuery(selectQuery)
buildStr: (queryBuilder) ->
return '' if 0 >= @_fields.length
"(#{@_fields.join(', ')}) (#{@_query.toString()})"
buildParam: (queryBuilder) ->
return { text: '', values: [] } if 0 >= @_fields.length
qryParam = @_query.toParam()
{
text: "(#{@_fields.join(', ')}) (#{qryParam.text})",
values: qryParam.values,
}
# DISTINCT
class cls.DistinctBlock extends cls.Block
constructor: (options) ->
super options
@useDistinct = false
# Add the DISTINCT keyword to the query.
distinct: ->
@useDistinct = true
buildStr: (queryBuilder) ->
if @useDistinct then "DISTINCT" else ""
# GROUP BY
class cls.GroupByBlock extends cls.Block
constructor: (options) ->
super options
@groups = []
# Add a GROUP BY transformation for the given field.
group: (field) ->
field = @_sanitizeField(field)
@groups.push field
buildStr: (queryBuilder) ->
groups = ""
if 0 < @groups.length
for f in @groups
groups += ", " if "" isnt groups
groups += f
groups = "GROUP BY #{groups}"
groups
# OFFSET x
class cls.OffsetBlock extends cls.Block
constructor: (options) ->
super options
@offsets = null
# Set the OFFSET transformation.
#
# Call this will override the previously set offset for this query. Also note that Passing 0 for 'max' will remove
# the offset.
offset: (start) ->
start = @_sanitizeLimitOffset(start)
@offsets = start
buildStr: (queryBuilder) ->
if @offsets then "OFFSET #{@offsets}" else ""
# WHERE
class cls.WhereBlock extends cls.Block
constructor: (options) ->
super options
@wheres = []
# Add a WHERE condition.
#
# When the final query is constructed all the WHERE conditions are combined using the intersection (AND) operator.
where: (condition, values...) ->
condition = @_sanitizeCondition(condition)
finalCondition = ""
finalValues = []
# if it's an Expression instance then convert to text and values
if condition instanceof cls.Expression
t = condition.toParam()
finalCondition = t.text
finalValues = t.values
else
for idx in [0...condition.length]
c = condition.charAt(idx)
if '?' is c and 0 < values.length
nextValue = values.shift()
if Array.isArray(nextValue) # where b in (?, ? ?)
inValues = []
for item in nextValue
inValues.push @_sanitizeValue(item)
finalValues = finalValues.concat(inValues)
finalCondition += "(#{('?' for item in inValues).join ', '})"
else
finalCondition += '?'
finalValues.push @_sanitizeValue(nextValue)
else
finalCondition += c
if "" isnt finalCondition
@wheres.push
text: finalCondition
values: finalValues
buildStr: (queryBuilder) ->
if 0 >= @wheres.length then return ""
whereStr = ""
for where in @wheres
if "" isnt whereStr then whereStr += ") AND ("
if 0 < where.values.length
# replace placeholders with actual parameter values
pIndex = 0
for idx in [0...where.text.length]
c = where.text.charAt(idx)
if '?' is c
whereStr += @_formatValue( where.values[pIndex++] )
else
whereStr += c
else
whereStr += where.text
"WHERE (#{whereStr})"
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
if 0 >= @wheres.length then return ret
whereStr = ""
for where in @wheres
if "" isnt whereStr then whereStr += ") AND ("
str = where.text.split('?')
i = 0
for v in where.values
whereStr += "#{str[i]}" if str[i]?
p = @_formatValueAsParam(v)
if (p?.text?)
whereStr += "(#{p.text})"
for qv in p.values
ret.values.push( qv )
else
whereStr += "?"
ret.values.push( p )
i = i+1
whereStr += "#{str[i]}" if str[i]?
ret.text = "WHERE (#{whereStr})"
ret
# ORDER BY
class cls.OrderByBlock extends cls.Block
constructor: (options) ->
super options
@orders = []
@_values = []
# Add an ORDER BY transformation for the given field in the given order.
#
# To specify descending order pass false for the 'asc' parameter.
order: (field, asc = true, values...) ->
field = @_sanitizeField(field)
@_values = values
@orders.push
field: field
dir: if asc then true else false
_buildStr: (toParam = false) ->
if 0 < @orders.length
pIndex = 0
orders = ""
for o in @orders
orders += ", " if "" isnt orders
fstr = ""
if not toParam
for idx in [0...o.field.length]
c = o.field.charAt(idx)
if '?' is c
fstr += @_formatValue( @_values[pIndex++] )
else
fstr += c
else
fstr = o.field
orders += "#{fstr} #{if o.dir then 'ASC' else 'DESC'}"
"ORDER BY #{orders}"
else
""
buildStr: (queryBuilder) ->
@_buildStr()
buildParam: (queryBuilder) ->
{
text: @_buildStr(true)
values: @_values.map (v) => @_formatValueAsParam(v)
}
# LIMIT
class cls.LimitBlock extends cls.Block
constructor: (options) ->
super options
@limits = null
# Set the LIMIT transformation.
#
# Call this will override the previously set limit for this query. Also note that Passing 0 for 'max' will remove
# the limit.
limit: (max) ->
max = @_sanitizeLimitOffset(max)
@limits = max
buildStr: (queryBuilder) ->
if @limits then "LIMIT #{@limits}" else ""
# JOIN
class cls.JoinBlock extends cls.Block
constructor: (options) ->
super options
@joins = []
# Add a JOIN with the given table.
#
# 'table' is the name of the table to join with.
#
# 'alias' is an optional alias for the table name.
#
# 'condition' is an optional condition (containing an SQL expression) for the JOIN. If this is an instance of
# an expression builder then it gets evaluated straight away.
#
# 'type' must be either one of INNER, OUTER, LEFT or RIGHT. Default is 'INNER'.
#
join: (table, alias = null, condition = null, type = 'INNER') ->
table = @_sanitizeTable(table, true)
alias = @_sanitizeTableAlias(alias) if alias
condition = @_sanitizeCondition(condition) if condition
@joins.push
type: type
table: table
alias: alias
condition: condition
@
# Add a LEFT JOIN with the given table.
left_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'LEFT'
# Add a RIGHT JOIN with the given table.
right_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'RIGHT'
# Add an OUTER JOIN with the given table.
outer_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'OUTER'
# Add a LEFT JOIN with the given table.
left_outer_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'LEFT OUTER'
# Add an FULL JOIN with the given table.
full_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'FULL'
# Add an CROSS JOIN with the given table.
cross_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'CROSS'
buildStr: (queryBuilder) ->
joins = ""
for j in (@joins or [])
if joins isnt "" then joins += " "
joins += "#{j.type} JOIN "
if "string" is typeof j.table
joins += j.table
else
joins += "(#{j.table})"
joins += " #{j.alias}" if j.alias
joins += " ON (#{j.condition})" if j.condition
joins
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
params = []
joinStr = ""
if 0 >= @joins.length then return ret
# retrieve the parameterised queries
for blk in @joins
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
if blk.condition instanceof cls.Expression
cp = blk.condition.toParam()
p.condition = cp.text
p.values = p.values.concat(cp.values)
else
p.condition = blk.condition
p.join = blk
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
if joinStr isnt "" then joinStr += " "
joinStr += "#{p.join.type} JOIN "
if "string" is typeof p.join.table
joinStr += p.text
else
joinStr += "(#{p.text})"
joinStr += " #{p.join.alias}" if p.join.alias
joinStr += " ON (#{p.condition})" if p.condition
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += joinStr
ret
# UNION
class cls.UnionBlock extends cls.Block
constructor: (options) ->
super options
@unions = []
# Add a UNION with the given table/query.
#
# 'table' is the name of the table or query to union with.
#
#
# 'type' must be either one of UNION or UNION ALL.... Default is 'UNION'.
#
union: (table, type = 'UNION') ->
table = @_sanitizeTable(table, true)
@unions.push
type: type
table: table
@
# Add a UNION ALL with the given table/query.
union_all: (table) ->
@union table, 'UNION ALL'
buildStr: (queryBuilder) ->
unionStr = ""
for j in (@unions or [])
if unionStr isnt "" then unionStr += " "
unionStr += "#{j.type} "
if "string" is typeof j.table
unionStr += j.table
else
unionStr += "(#{j.table})"
unionStr
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
params = []
unionStr = ""
if 0 >= @unions.length then return ret
# retrieve the parameterised queries
for blk in (@unions or [])
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
p.type = blk.type
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
unionStr += " " if unionStr isnt ""
unionStr += "#{p.type} (#{p.text})"
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += unionStr
ret
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builders
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builder base class
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class cls.QueryBuilder extends cls.BaseBuilder
# Constructor
#
# blocks - array of cls.BaseBuilderBlock instances to build the query with.
constructor: (options, blocks) ->
super options
@blocks = blocks or []
# Copy exposed methods into myself
for block in @blocks
for methodName, methodBody of block.exposedMethods()
if @[methodName]?
throw new Error "#{@_getObjectClassName(@)} already has a builder method called: #{methodName}"
( (block, name, body) =>
@[name] = =>
body.apply(block, arguments)
@
)(block, methodName, methodBody)
# Register a custom value handler for this query builder and all its contained blocks.
#
# Note: This will override any globally registered handler for this value type.
registerValueHandler: (type, handler) ->
for block in @blocks
block.registerValueHandler type, handler
super type, handler
@
# Update query builder options
#
# This will update the options for all blocks too. Use this method with caution as it allows you to change the
# behaviour of your query builder mid-build.
updateOptions: (options) ->
@options = _extend({}, @options, options)
for block in @blocks
block.options = _extend({}, block.options, options)
# Get the final fully constructed query string.
toString: ->
(block.buildStr(@) for block in @blocks).filter (v) ->
0 < v.length
.join(@options.separator)
# Get the final fully constructed query param obj.
toParam: (options = undefined)->
old = @options
@options = _extend({}, @options, options) if options?
result = { text: '', values: [] }
blocks = (block.buildParam(@) for block in @blocks)
result.text = (block.text for block in blocks).filter (v) ->
0 < v.length
.join(@options.separator)
result.values = [].concat (block.values for block in blocks)...
if not @options.nestedBuilder?
if @options.numberedParameters || options?.numberedParametersStartAt?
i = 1
i = @options.numberedParametersStartAt if @options.numberedParametersStartAt?
result.text = result.text.replace /\?/g, () -> return "$#{i++}"
@options = old
result
# Deep clone
clone: ->
new @constructor @options, (block.clone() for block in @blocks)
# Get whether queries built with this builder can be nested within other queries
isNestable: ->
false
# SELECT query builder.
class cls.Select extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'SELECT'),
new cls.DistinctBlock(options),
new cls.GetFieldBlock(options),
new cls.FromTableBlock(_extend({}, options, { allowNested: true })),
new cls.JoinBlock(_extend({}, options, { allowNested: true })),
new cls.WhereBlock(options),
new cls.GroupByBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options),
new cls.OffsetBlock(options),
new cls.UnionBlock(_extend({}, options, { allowNested: true }))
]
super options, blocks
isNestable: ->
true
# UPDATE query builder.
class cls.Update extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'UPDATE'),
new cls.UpdateTableBlock(options),
new cls.SetFieldBlock(options),
new cls.WhereBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options)
]
super options, blocks
# DELETE query builder.
class cls.Delete extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'DELETE'),
new cls.FromTableBlock( _extend({}, options, { singleTable: true }) ),
new cls.JoinBlock(options),
new cls.WhereBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options),
]
super options, blocks
# An INSERT query builder.
#
class cls.Insert extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'INSERT'),
new cls.IntoTableBlock(options),
new cls.InsertFieldValueBlock(options),
new cls.InsertFieldsFromQueryBlock(options),
]
super options, blocks
_squel =
VERSION: '<<VERSION_STRING>>'
expr: -> new cls.Expression
# Don't have a space-efficient elegant-way of .apply()-ing to constructors, so we specify the args
select: (options, blocks) -> new cls.Select(options, blocks)
update: (options, blocks) -> new cls.Update(options, blocks)
insert: (options, blocks) -> new cls.Insert(options, blocks)
delete: (options, blocks) -> new cls.Delete(options, blocks)
registerValueHandler: cls.registerValueHandler
fval: cls.fval
# aliases
_squel.remove = _squel.delete
# classes
_squel.cls = cls
return _squel
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Exported API
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
squel = _buildSquel()
# AMD
if define?.amd
define ->
return squel
# CommonJS
else if module?.exports
module.exports = squel
# Browser
else
window?.squel = squel
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Squel SQL flavours
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Available flavours
squel.flavours = {}
# Setup Squel for a particular SQL flavour
squel.useFlavour = (flavour = null) ->
return squel if not flavour
if squel.flavours[flavour] instanceof Function
s = _buildSquel()
squel.flavours[flavour].call null, s
return s
else
throw new Error "Flavour not available: #{flavour}"
| 28574 | ###
Copyright (c) 2014 <NAME> (hiddentao.com)
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.
###
# Extend given object's with other objects' properties, overriding existing ones if necessary
_extend = (dst, sources...) ->
if sources
for src in sources
if src
for own k,v of src
dst[k] = v
dst
# Get a copy of given object with given properties removed
_without = (obj, properties...) ->
dst = _extend {}, obj
for p in properties
delete dst[p]
dst
# Register a value type handler
#
# Note: this will override any existing handler registered for this value type.
registerValueHandler = (handlers, type, handler) ->
if 'function' isnt typeof type and 'string' isnt typeof type
throw new Error "type must be a class constructor or string denoting 'typeof' result"
if 'function' isnt typeof handler
throw new Error "handler must be a function"
for typeHandler in handlers
if typeHandler.type is type
typeHandler.handler = handler
return
handlers.push
type: type
handler: handler
# Get value type handler for given type
getValueHandler = (value, handlerLists...) ->
for handlers in handlerLists
for typeHandler in handlers
# if type is a string then use `typeof` or else use `instanceof`
if typeHandler.type is typeof value or (typeof typeHandler.type isnt 'string' and value instanceof typeHandler.type)
return typeHandler.handler
undefined
# Build base squel classes and methods
_buildSquel = ->
# Holds classes
cls = {}
# Default query builder options
cls.DefaultQueryBuilderOptions =
# If true then table names will be rendered inside quotes. The quote character used is configurable via the
# nameQuoteCharacter option.
autoQuoteTableNames: false
# If true then field names will rendered inside quotes. The quote character used is configurable via the
# nameQuoteCharacter option.
autoQuoteFieldNames: false
# If true then alias names will rendered inside quotes. The quote character used is configurable via the `tableAliasQuoteCharacter` and `fieldAliasQuoteCharacter` options.
autoQuoteAliasNames: true
# The quote character used for when quoting table and field names
nameQuoteCharacter: '`'
# The quote character used for when quoting table alias names
tableAliasQuoteCharacter: '`'
# The quote character used for when quoting table alias names
fieldAliasQuoteCharacter: '"'
# Custom value handlers where key is the value type and the value is the handler function
valueHandlers: []
# Number parameters returned from toParam() as $1, $2, etc. Default is to use '?', startAt 1 will give $1...
numberedParameters: false
numberedParametersStartAt: 1
# If true then replaces all single quotes within strings. The replacement string used is configurable via the `singleQuoteReplacement` option.
replaceSingleQuotes: false
# The string to replace single quotes with in query strings
singleQuoteReplacement: '\'\''
# String used to join individual blocks in a query when it's stringified
separator: ' '
# Global custom value handlers for all instances of builder
cls.globalValueHandlers = []
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Custom value types
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Register a new value handler
cls.registerValueHandler = (type, handler) ->
registerValueHandler cls.globalValueHandlers, type, handler
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.FuncVal
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# A function value
class cls.FuncVal
# Constructor
#
# str - the string
# values - the parameter values
constructor: (str, values) ->
@str = str
@values = values
# Construct a FuncVal object
cls.fval = (str, values...) ->
new cls.FuncVal(str, values)
# default value handler for cls.FuncVal
cls.fval_handler = (value, asParam = false) ->
if asParam
{
text: value.str
values: value.values
}
else
str = value.str
finalStr = ''
values = value.values
for idx in [0...str.length]
c = str.charAt(idx)
if '?' is c and 0 < values.length
c = values.shift()
finalStr += c
finalStr
cls.registerValueHandler cls.FuncVal, cls.fval_handler
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base classes
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base class for cloneable builders
class cls.Cloneable
# Clone this builder
clone: ->
newInstance = new @constructor;
# Fast deep copy using JSON conversion, see http://stackoverflow.com/a/5344074
_extend newInstance, JSON.parse(JSON.stringify(@))
# Base class for all builders
class cls.BaseBuilder extends cls.Cloneable
# Constructor
#
# options is an Object overriding one or more of cls.DefaultQueryBuilderOptions
#
constructor: (options) ->
defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions))
@options = _extend {}, defaults, options
# Register a custom value handler for this builder instance.
#
# Note: this will override any globally registered handler for this value type.
registerValueHandler: (type, handler) ->
registerValueHandler @options.valueHandlers, type, handler
@
# Get class name of given object.
_getObjectClassName: (obj) ->
if obj && obj.constructor && obj.constructor.toString
arr = obj.constructor.toString().match /function\s*(\w+)/;
if arr && arr.length is 2
return arr[1]
return undefined
# Sanitize the given condition.
_sanitizeCondition: (condition) ->
# If it's not an Expression builder instance
if not (condition instanceof cls.Expression)
# It must then be a string
if "string" isnt typeof condition
throw new Error "condition must be a string or Expression instance"
condition
# Sanitize the given name.
# The 'type' parameter is used to construct a meaningful error message in case validation fails.
_sanitizeName: (value, type) ->
if "string" isnt typeof value
throw new Error "#{type} must be a string"
value
_sanitizeField: (item, formattingOptions = {}) ->
if item instanceof cls.QueryBuilder
item = "(#{item})"
else
item = @_sanitizeName item, "field name"
if @options.autoQuoteFieldNames
quoteChar = @options.nameQuoteCharacter
if formattingOptions.ignorePeriodsForFieldNameQuotes
# a.b.c -> `a.b.c`
item = "#{quoteChar}#{item}#{quoteChar}"
else
# a.b.c -> `a`.`b`.`c`
item = item
.split('.')
.map( (v) ->
# treat '*' as special case (#79)
return if '*' is v then v else "#{quoteChar}#{v}#{quoteChar}"
)
.join('.')
item
_sanitizeNestableQuery: (item) =>
return item if item instanceof cls.QueryBuilder and item.isNestable()
throw new Error "must be a nestable query, e.g. SELECT"
_sanitizeTable: (item, allowNested = false) ->
if allowNested
if "string" is typeof item
sanitized = item
else
try
sanitized = @_sanitizeNestableQuery(item)
catch e
throw new Error "table name must be a string or a nestable query instance"
else
sanitized = @_sanitizeName item, 'table name'
if @options.autoQuoteTableNames
"#{@options.nameQuoteCharacter}#{sanitized}#{@options.nameQuoteCharacter}"
else
sanitized
_sanitizeTableAlias: (item) ->
sanitized = @_sanitizeName item, "table alias"
if @options.autoQuoteAliasNames
"#{@options.tableAliasQuoteCharacter}#{sanitized}#{@options.tableAliasQuoteCharacter}"
else
sanitized
_sanitizeFieldAlias: (item) ->
sanitized = @_sanitizeName item, "field alias"
if @options.autoQuoteAliasNames
"#{@options.fieldAliasQuoteCharacter}#{sanitized}#{@options.fieldAliasQuoteCharacter}"
else
sanitized
# Sanitize the given limit/offset value.
_sanitizeLimitOffset: (value) ->
value = parseInt(value)
if 0 > value or isNaN(value)
throw new Error "limit/offset must be >= 0"
value
# Santize the given field value
_sanitizeValue: (item) ->
itemType = typeof item
if null is item
# null is allowed
else if "string" is itemType or "number" is itemType or "boolean" is itemType
# primitives are allowed
else if item instanceof cls.QueryBuilder and item.isNestable()
# QueryBuilder instances allowed
else if item instanceof cls.FuncVal
# FuncVal instances allowed
else
typeIsValid = undefined isnt getValueHandler(item, @options.valueHandlers, cls.globalValueHandlers)
unless typeIsValid
# type is not valid
throw new Error "field value must be a string, number, boolean, null or one of the registered custom value types"
item
# Escape a string value, e.g. escape quotes and other characters within it.
_escapeValue: (value) ->
return value unless true is @options.replaceSingleQuotes
value.replace /\'/g, @options.singleQuoteReplacement
# Format the given custom value
_formatCustomValue: (value, asParam = false) ->
# user defined custom handlers takes precedence
customHandler = getValueHandler(value, @options.valueHandlers, cls.globalValueHandlers)
if customHandler
# use the custom handler if available
value = customHandler(value, asParam)
value
# Format the given field value for inclusion into query parameter array
_formatValueAsParam: (value) ->
if Array.isArray(value)
value.map (v) => @_formatValueAsParam v
else
if value instanceof cls.QueryBuilder and value.isNestable()
value.updateOptions( { "nestedBuilder": true } )
p = value.toParam()
else if value instanceof cls.Expression
p = value.toParam()
else
@_formatCustomValue(value, true)
# Format the given field value for inclusion into the query string
_formatValue: (value, formattingOptions = {}) ->
customFormattedValue = @_formatCustomValue(value)
# if formatting took place then return it directly
if customFormattedValue isnt value
return "(#{customFormattedValue})"
# if it's an array then format each element separately
if Array.isArray(value)
value = value.map (v) => @_formatValue v
value = "(#{value.join(', ')})"
else
if null is value
value = "NULL"
else if "boolean" is typeof value
value = if value then "TRUE" else "FALSE"
else if value instanceof cls.QueryBuilder
value = "(#{value})"
else if value instanceof cls.Expression
value = "(#{value})"
else if "number" isnt typeof value
value = @_escapeValue(value)
value = if formattingOptions.dontQuote then "#{value}" else "'#{value}'"
value
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Expressions
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# An SQL expression builder.
#
# SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
#
# This builder works by building up the expression as a hierarchical tree of nodes. The toString() method then
# traverses this tree in order to build the final expression string.
#
# cls.Expressions can be nested. Nested expression contains can themselves contain nested expressions.
# When rendered a nested expression will be fully contained within brackets.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class cls.Expression extends cls.BaseBuilder
# The expression tree.
tree: null
# The part of the expression tree we're currently working on.
current: null
# Initialise the expression.
constructor: ->
super()
@tree =
parent: null
nodes: []
@current = @tree
# Begin a nested expression and combine it with the current expression using the given operator.
@_begin = (op) =>
new_tree =
type: op
parent: @current
nodes: []
@current.nodes.push new_tree
@current = @current.nodes[@current.nodes.length-1]
@
# Begin a nested expression and combine it with the current expression using the intersection operator (AND).
and_begin: ->
@_begin 'AND'
# Begin a nested expression and combine it with the current expression using the union operator (OR).
or_begin: ->
@_begin 'OR'
# End the current compound expression.
#
# This will throw an error if begin() hasn't been called yet.
end: ->
if not @current.parent
throw new Error "begin() needs to be called"
@current = @current.parent
@
# Combine the current expression with the given expression using the intersection operator (AND).
and: (expr, param) ->
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'AND'
expr: expr
para: param
@
# Combine the current expression with the given expression using the union operator (OR).
or: (expr, param) ->
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'OR'
expr: expr
para: param
@
# Get the final fully constructed expression string.
toString: ->
if null isnt @current.parent
throw new Error "end() needs to be called"
@_toString @tree
# Get the final fully constructed expression string.
toParam: ->
if null isnt @current.parent
throw new Error "end() needs to be called"
@_toString @tree, true
# Get a string representation of the given expression tree node.
_toString: (node, paramMode = false) ->
str = ""
params = []
for child in node.nodes
if child.expr?
nodeStr = child.expr
# have param?
if undefined isnt child.para
if not paramMode
nodeStr = nodeStr.replace '?', @_formatValue(child.para)
else
cv = @_formatValueAsParam child.para
if (cv?.text?)
params = params.concat(cv.values)
nodeStr = nodeStr.replace '?', "(#{cv.text})"
else
params = params.concat(cv)
# IN ? -> IN (?, ?, ..., ?)
if Array.isArray(child.para)
inStr = Array.apply(null, new Array(child.para.length)).map () -> '?'
nodeStr = nodeStr.replace '?', "(#{inStr.join(', ')})"
else
nodeStr = @_toString(child, paramMode)
if paramMode
params = params.concat(nodeStr.values)
nodeStr = nodeStr.text
# wrap nested expressions in brackets
if "" isnt nodeStr
nodeStr = "(" + nodeStr + ")"
if "" isnt nodeStr
# if this isn't first expression then add the operator
if "" isnt str then str += " " + child.type + " "
str += nodeStr
if paramMode
return {
text: str
values: params
}
else
return str
###
Clone this expression.
Note that the algorithm contained within this method is probably non-optimal, so please avoid cloning large
expression trees.
###
clone: ->
newInstance = new @constructor;
(_cloneTree = (node) ->
for child in node.nodes
if child.expr?
newInstance.current.nodes.push JSON.parse(JSON.stringify(child))
else
newInstance._begin child.type
_cloneTree child
if not @current is child
newInstance.end()
)(@tree)
newInstance
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Building blocks
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# A building block represents a single build-step within a query building process.
#
# Query builders consist of one or more building blocks which get run in a particular order. Building blocks can
# optionally specify methods to expose through the query builder interface. They can access all the input data for
# the query builder and manipulate it as necessary, as well as append to the final query string output.
#
# If you wish to customize how queries get built or add proprietary query phrases and content then it is recommended
# that you do so using one or more custom building blocks.
#
# Original idea posted in https://github.com/hiddentao/export/issues/10#issuecomment-15016427
class cls.Block extends cls.BaseBuilder
# Get input methods to expose within the query builder.
#
# By default all methods except the following get returned:
# methods prefixed with _
# constructor and buildStr()
#
# @return Object key -> function pairs
exposedMethods: ->
ret = {}
for attr, value of @
# only want functions from this class
if typeof value is "function" and attr.charAt(0) isnt '_' and !cls.Block::[attr]
ret[attr] = value
ret
# Build this block.
#
# Subclasses may override this method.
#
# @param queryBuilder cls.QueryBuilder a reference to the query builder that owns this block.
#
# @return String the string representing this block
buildStr: (queryBuilder) ->
''
buildParam: (queryBuilder) ->
{ text: @buildStr(queryBuilder), values: [] }
# A String which always gets output
class cls.StringBlock extends cls.Block
constructor: (options, str) ->
super options
@str = str
buildStr: (queryBuilder) ->
@str
# A values which gets output as is
class cls.AbstractValueBlock extends cls.Block
constructor: (options) ->
super options
@_val = null
_setValue: (val) ->
@_val = val
buildStr: (queryBuilder) ->
if not @_val then "" else @_val
# Table specifier base class
#
# Additional options
# - singleTable - only allow one table to be specified (default: false)
# - allowNested - allow nested query to be specified as a table (default: false)
class cls.AbstractTableBlock extends cls.Block
constructor: (options) ->
super options
@tables = []
# Update given table.
#
# An alias may also be specified for the table.
#
# Concrete subclasses should provide a method which calls this
_table: (table, alias = null) ->
alias = @_sanitizeTableAlias(alias) if alias
table = @_sanitizeTable(table, @options.allowNested or false)
if @options.singleTable
@tables = []
@tables.push
table: table
alias: alias
buildStr: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "_table() needs to be called"
tables = ""
for table in @tables
tables += ", " if "" isnt tables
if "string" is typeof table.table
tables += table.table
else
# building a nested query
tables += "(#{table.table})"
if table.alias
# add the table alias, the AS keyword is optional
tables += " #{table.alias}"
tables
_buildParam: (queryBuilder, prefix = null) ->
ret =
text: ""
values: []
params = []
paramStr = ""
if 0 >= @tables.length then return ret
# retrieve the parameterised queries
for blk in @tables
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
p.table = blk
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
if paramStr isnt ""
paramStr += ", "
else
paramStr += "#{prefix} #{paramStr}" if prefix? and prefix isnt ""
paramStr
if "string" is typeof p.table.table
paramStr += "#{p.text}"
else
paramStr += "(#{p.text})"
# add the table alias, the AS keyword is optional
paramStr += " #{p.table.alias}" if p.table.alias?
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += paramStr
ret
buildParam: (queryBuilder) ->
@_buildParam(queryBuilder)
# Update Table
class cls.UpdateTableBlock extends cls.AbstractTableBlock
table: (table, alias = null) ->
@_table(table, alias)
# FROM table
class cls.FromTableBlock extends cls.AbstractTableBlock
from: (table, alias = null) ->
@_table(table, alias)
buildStr: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "from() needs to be called"
tables = super queryBuilder
"FROM #{tables}"
buildParam: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "from() needs to be called"
@_buildParam(queryBuilder, "FROM")
# INTO table
class cls.IntoTableBlock extends cls.Block
constructor: (options) ->
super options
@table = null
# Into given table.
into: (table) ->
# do not allow nested table to be the target
@table = @_sanitizeTable(table, false)
buildStr: (queryBuilder) ->
if not @table then throw new Error "into() needs to be called"
"INTO #{@table}"
# (SELECT) Get field
class cls.GetFieldBlock extends cls.Block
constructor: (options) ->
super options
@_fieldAliases = {}
@_fields = []
# Add the given fields to the final result set.
#
# The parameter is an Object containing field names (or database functions) as the keys and aliases for the fields
# as the values. If the value for a key is null then no alias is set for that field.
#
# Internally this method simply calls the field() method of this block to add each individual field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
fields: (_fields, options = {}) ->
if Array.isArray(_fields)
for field in _fields
@field field, null, options
else
for field, alias of _fields
@field(field, alias, options)
# Add the given field to the final result set.
#
# The 'field' parameter does not necessarily have to be a fieldname. It can use database functions too,
# e.g. DATE_FORMAT(a.started, "%H")
#
# An alias may also be specified for this field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
field: (field, alias = null, options = {}) ->
field = @_sanitizeField(field, options)
alias = @_sanitizeFieldAlias(alias) if alias
# if field-alias already present then don't add
return if @_fieldAliases[field] is alias
@_fieldAliases[field] = alias
@_fields.push
name: field
alias: alias
buildStr: (queryBuilder) ->
fields = ""
for field in @_fields
fields += ", " if "" isnt fields
fields += field.name
fields += " AS #{field.alias}" if field.alias
if "" is fields then "*" else fields
# Base class for setting fields to values (used for INSERT and UPDATE queries)
class cls.AbstractSetFieldBlock extends cls.Block
constructor: (options) ->
super options
@fieldOptions = []
@fields = []
@values = []
# Update the given field with the given value.
# This will override any previously set value for the given field.
_set: (field, value, options = {}) ->
throw new Error "Cannot call set or setFields on multiple rows of fields." if @values.length > 1
value = @_sanitizeValue(value) if undefined isnt value
# Explicity overwrite existing fields
index = @fields.indexOf(@_sanitizeField(field, options))
if index isnt -1
@values[0][index] = value
@fieldOptions[0][index] = options
else
@fields.push @_sanitizeField(field, options)
index = @fields.length - 1
# The first value added needs to create the array of values for the row
if Array.isArray(@values[0])
@values[0][index] = value
@fieldOptions[0][index] = options
else
@values.push [value]
@fieldOptions.push [options]
@
# Insert fields based on the key/value pairs in the given object
_setFields: (fields, options = {}) ->
throw new Error "Expected an object but got " + typeof fields unless typeof fields is 'object'
for own field of fields
@_set field, fields[field], options
@
# Insert multiple rows for the given fields. Accepts an array of objects.
# This will override all previously set values for every field.
_setFieldsRows: (fieldsRows, options = {}) ->
throw new Error "Expected an array of objects but got " + typeof fieldsRows unless Array.isArray(fieldsRows)
# Reset the objects stored fields and values
@fields = []
@values = []
for i in [0...fieldsRows.length]
for own field of fieldsRows[i]
index = @fields.indexOf(@_sanitizeField(field, options))
throw new Error 'All fields in subsequent rows must match the fields in the first row' if 0 < i and -1 is index
# Add field only if it hasn't been added before
if -1 is index
@fields.push @_sanitizeField(field, options)
index = @fields.length - 1
value = @_sanitizeValue(fieldsRows[i][field])
# The first value added needs to add the array
if Array.isArray(@values[i])
@values[i][index] = value
@fieldOptions[i][index] = options
else
@values[i] = [value]
@fieldOptions[i] = [options]
@
buildStr: ->
throw new Error('Not yet implemented')
buildParam: ->
throw new Error('Not yet implemented')
# (UPDATE) SET field=value
class cls.SetFieldBlock extends cls.AbstractSetFieldBlock
set: (field, value, options) ->
@_set field, value, options
setFields: (fields, options) ->
@_setFields fields, options
buildStr: (queryBuilder) ->
if 0 >= @fields.length then throw new Error "set() needs to be called"
str = ""
for i in [0...@fields.length]
field = @fields[i]
str += ", " if "" isnt str
value = @values[0][i]
fieldOptions = @fieldOptions[0][i]
if typeof value is 'undefined' # e.g. if field is an expression such as: count = count + 1
str += field
else
str += "#{field} = #{if fieldOptions.dontQuote and typeof value is 'string' then value else @_formatValue(value, fieldOptions)}"
"SET #{str}"
buildParam: (queryBuilder) ->
if 0 >= @fields.length then throw new Error "set() needs to be called"
str = ""
vals = []
for i in [0...@fields.length]
field = @fields[i]
str += ", " if "" isnt str
value = @values[0][i]
if typeof value is 'undefined' # e.g. if field is an expression such as: count = count + 1
str += field
else
p = @_formatValueAsParam( value )
if p?.text?
str += "#{field} = (#{p.text})"
for v in p.values
vals.push v
else
str += "#{field} = ?"
vals.push p
{ text: "SET #{str}", values: vals }
# (INSERT INTO) ... field ... value
class cls.InsertFieldValueBlock extends cls.AbstractSetFieldBlock
set: (field, value, options = {}) ->
@_set field, value, options
setFields: (fields, options) ->
@_setFields fields, options
setFieldsRows: (fieldsRows, options) ->
@_setFieldsRows fieldsRows, options
_buildVals: ->
vals = []
for i in [0...@values.length]
for j in [0...@values[i].length]
formattedValue = if @fieldOptions[i][j].dontQuote and typeof @values[i][j] is 'string' then @values[i][j] else @_formatValue @values[i][j], @fieldOptions[i][j]
if 'string' is typeof vals[i]
vals[i] += ', ' + formattedValue
else
vals[i] = '' + formattedValue
vals
_buildValParams: ->
vals = []
params = []
for i in [0...@values.length]
for j in [0...@values[i].length]
p = @_formatValueAsParam( @values[i][j] )
if p?.text?
str = p.text
for v in p.values
params.push v
else
str = '?'
params.push p
if 'string' is typeof vals[i]
vals[i] += ", #{str}"
else
vals[i] = "#{str}"
vals: vals
params: params
buildStr: (queryBuilder) ->
return '' if 0 >= @fields.length
"(#{@fields.join(', ')}) VALUES (#{@_buildVals().join('), (')})"
buildParam: (queryBuilder) ->
return { text: '', values: [] } if 0 >= @fields.length
# fields
str = ""
{vals, params} = @_buildValParams()
for i in [0...@fields.length]
str += ", " if "" isnt str
str += @fields[i]
{ text: "(#{str}) VALUES (#{vals.join('), (')})", values: params }
# (INSERT INTO) ... field ... (SELECT ... FROM ...)
class cls.InsertFieldsFromQueryBlock extends cls.Block
constructor: (options) ->
super options
@_fields = []
@_query = null
fromQuery: (fields, selectQuery) ->
@_fields = fields.map ( (v) => @_sanitizeField(v) )
@_query = @_sanitizeNestableQuery(selectQuery)
buildStr: (queryBuilder) ->
return '' if 0 >= @_fields.length
"(#{@_fields.join(', ')}) (#{@_query.toString()})"
buildParam: (queryBuilder) ->
return { text: '', values: [] } if 0 >= @_fields.length
qryParam = @_query.toParam()
{
text: "(#{@_fields.join(', ')}) (#{qryParam.text})",
values: qryParam.values,
}
# DISTINCT
class cls.DistinctBlock extends cls.Block
constructor: (options) ->
super options
@useDistinct = false
# Add the DISTINCT keyword to the query.
distinct: ->
@useDistinct = true
buildStr: (queryBuilder) ->
if @useDistinct then "DISTINCT" else ""
# GROUP BY
class cls.GroupByBlock extends cls.Block
constructor: (options) ->
super options
@groups = []
# Add a GROUP BY transformation for the given field.
group: (field) ->
field = @_sanitizeField(field)
@groups.push field
buildStr: (queryBuilder) ->
groups = ""
if 0 < @groups.length
for f in @groups
groups += ", " if "" isnt groups
groups += f
groups = "GROUP BY #{groups}"
groups
# OFFSET x
class cls.OffsetBlock extends cls.Block
constructor: (options) ->
super options
@offsets = null
# Set the OFFSET transformation.
#
# Call this will override the previously set offset for this query. Also note that Passing 0 for 'max' will remove
# the offset.
offset: (start) ->
start = @_sanitizeLimitOffset(start)
@offsets = start
buildStr: (queryBuilder) ->
if @offsets then "OFFSET #{@offsets}" else ""
# WHERE
class cls.WhereBlock extends cls.Block
constructor: (options) ->
super options
@wheres = []
# Add a WHERE condition.
#
# When the final query is constructed all the WHERE conditions are combined using the intersection (AND) operator.
where: (condition, values...) ->
condition = @_sanitizeCondition(condition)
finalCondition = ""
finalValues = []
# if it's an Expression instance then convert to text and values
if condition instanceof cls.Expression
t = condition.toParam()
finalCondition = t.text
finalValues = t.values
else
for idx in [0...condition.length]
c = condition.charAt(idx)
if '?' is c and 0 < values.length
nextValue = values.shift()
if Array.isArray(nextValue) # where b in (?, ? ?)
inValues = []
for item in nextValue
inValues.push @_sanitizeValue(item)
finalValues = finalValues.concat(inValues)
finalCondition += "(#{('?' for item in inValues).join ', '})"
else
finalCondition += '?'
finalValues.push @_sanitizeValue(nextValue)
else
finalCondition += c
if "" isnt finalCondition
@wheres.push
text: finalCondition
values: finalValues
buildStr: (queryBuilder) ->
if 0 >= @wheres.length then return ""
whereStr = ""
for where in @wheres
if "" isnt whereStr then whereStr += ") AND ("
if 0 < where.values.length
# replace placeholders with actual parameter values
pIndex = 0
for idx in [0...where.text.length]
c = where.text.charAt(idx)
if '?' is c
whereStr += @_formatValue( where.values[pIndex++] )
else
whereStr += c
else
whereStr += where.text
"WHERE (#{whereStr})"
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
if 0 >= @wheres.length then return ret
whereStr = ""
for where in @wheres
if "" isnt whereStr then whereStr += ") AND ("
str = where.text.split('?')
i = 0
for v in where.values
whereStr += "#{str[i]}" if str[i]?
p = @_formatValueAsParam(v)
if (p?.text?)
whereStr += "(#{p.text})"
for qv in p.values
ret.values.push( qv )
else
whereStr += "?"
ret.values.push( p )
i = i+1
whereStr += "#{str[i]}" if str[i]?
ret.text = "WHERE (#{whereStr})"
ret
# ORDER BY
class cls.OrderByBlock extends cls.Block
constructor: (options) ->
super options
@orders = []
@_values = []
# Add an ORDER BY transformation for the given field in the given order.
#
# To specify descending order pass false for the 'asc' parameter.
order: (field, asc = true, values...) ->
field = @_sanitizeField(field)
@_values = values
@orders.push
field: field
dir: if asc then true else false
_buildStr: (toParam = false) ->
if 0 < @orders.length
pIndex = 0
orders = ""
for o in @orders
orders += ", " if "" isnt orders
fstr = ""
if not toParam
for idx in [0...o.field.length]
c = o.field.charAt(idx)
if '?' is c
fstr += @_formatValue( @_values[pIndex++] )
else
fstr += c
else
fstr = o.field
orders += "#{fstr} #{if o.dir then 'ASC' else 'DESC'}"
"ORDER BY #{orders}"
else
""
buildStr: (queryBuilder) ->
@_buildStr()
buildParam: (queryBuilder) ->
{
text: @_buildStr(true)
values: @_values.map (v) => @_formatValueAsParam(v)
}
# LIMIT
class cls.LimitBlock extends cls.Block
constructor: (options) ->
super options
@limits = null
# Set the LIMIT transformation.
#
# Call this will override the previously set limit for this query. Also note that Passing 0 for 'max' will remove
# the limit.
limit: (max) ->
max = @_sanitizeLimitOffset(max)
@limits = max
buildStr: (queryBuilder) ->
if @limits then "LIMIT #{@limits}" else ""
# JOIN
class cls.JoinBlock extends cls.Block
constructor: (options) ->
super options
@joins = []
# Add a JOIN with the given table.
#
# 'table' is the name of the table to join with.
#
# 'alias' is an optional alias for the table name.
#
# 'condition' is an optional condition (containing an SQL expression) for the JOIN. If this is an instance of
# an expression builder then it gets evaluated straight away.
#
# 'type' must be either one of INNER, OUTER, LEFT or RIGHT. Default is 'INNER'.
#
join: (table, alias = null, condition = null, type = 'INNER') ->
table = @_sanitizeTable(table, true)
alias = @_sanitizeTableAlias(alias) if alias
condition = @_sanitizeCondition(condition) if condition
@joins.push
type: type
table: table
alias: alias
condition: condition
@
# Add a LEFT JOIN with the given table.
left_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'LEFT'
# Add a RIGHT JOIN with the given table.
right_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'RIGHT'
# Add an OUTER JOIN with the given table.
outer_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'OUTER'
# Add a LEFT JOIN with the given table.
left_outer_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'LEFT OUTER'
# Add an FULL JOIN with the given table.
full_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'FULL'
# Add an CROSS JOIN with the given table.
cross_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'CROSS'
buildStr: (queryBuilder) ->
joins = ""
for j in (@joins or [])
if joins isnt "" then joins += " "
joins += "#{j.type} JOIN "
if "string" is typeof j.table
joins += j.table
else
joins += "(#{j.table})"
joins += " #{j.alias}" if j.alias
joins += " ON (#{j.condition})" if j.condition
joins
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
params = []
joinStr = ""
if 0 >= @joins.length then return ret
# retrieve the parameterised queries
for blk in @joins
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
if blk.condition instanceof cls.Expression
cp = blk.condition.toParam()
p.condition = cp.text
p.values = p.values.concat(cp.values)
else
p.condition = blk.condition
p.join = blk
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
if joinStr isnt "" then joinStr += " "
joinStr += "#{p.join.type} JOIN "
if "string" is typeof p.join.table
joinStr += p.text
else
joinStr += "(#{p.text})"
joinStr += " #{p.join.alias}" if p.join.alias
joinStr += " ON (#{p.condition})" if p.condition
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += joinStr
ret
# UNION
class cls.UnionBlock extends cls.Block
constructor: (options) ->
super options
@unions = []
# Add a UNION with the given table/query.
#
# 'table' is the name of the table or query to union with.
#
#
# 'type' must be either one of UNION or UNION ALL.... Default is 'UNION'.
#
union: (table, type = 'UNION') ->
table = @_sanitizeTable(table, true)
@unions.push
type: type
table: table
@
# Add a UNION ALL with the given table/query.
union_all: (table) ->
@union table, 'UNION ALL'
buildStr: (queryBuilder) ->
unionStr = ""
for j in (@unions or [])
if unionStr isnt "" then unionStr += " "
unionStr += "#{j.type} "
if "string" is typeof j.table
unionStr += j.table
else
unionStr += "(#{j.table})"
unionStr
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
params = []
unionStr = ""
if 0 >= @unions.length then return ret
# retrieve the parameterised queries
for blk in (@unions or [])
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
p.type = blk.type
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
unionStr += " " if unionStr isnt ""
unionStr += "#{p.type} (#{p.text})"
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += unionStr
ret
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builders
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builder base class
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class cls.QueryBuilder extends cls.BaseBuilder
# Constructor
#
# blocks - array of cls.BaseBuilderBlock instances to build the query with.
constructor: (options, blocks) ->
super options
@blocks = blocks or []
# Copy exposed methods into myself
for block in @blocks
for methodName, methodBody of block.exposedMethods()
if @[methodName]?
throw new Error "#{@_getObjectClassName(@)} already has a builder method called: #{methodName}"
( (block, name, body) =>
@[name] = =>
body.apply(block, arguments)
@
)(block, methodName, methodBody)
# Register a custom value handler for this query builder and all its contained blocks.
#
# Note: This will override any globally registered handler for this value type.
registerValueHandler: (type, handler) ->
for block in @blocks
block.registerValueHandler type, handler
super type, handler
@
# Update query builder options
#
# This will update the options for all blocks too. Use this method with caution as it allows you to change the
# behaviour of your query builder mid-build.
updateOptions: (options) ->
@options = _extend({}, @options, options)
for block in @blocks
block.options = _extend({}, block.options, options)
# Get the final fully constructed query string.
toString: ->
(block.buildStr(@) for block in @blocks).filter (v) ->
0 < v.length
.join(@options.separator)
# Get the final fully constructed query param obj.
toParam: (options = undefined)->
old = @options
@options = _extend({}, @options, options) if options?
result = { text: '', values: [] }
blocks = (block.buildParam(@) for block in @blocks)
result.text = (block.text for block in blocks).filter (v) ->
0 < v.length
.join(@options.separator)
result.values = [].concat (block.values for block in blocks)...
if not @options.nestedBuilder?
if @options.numberedParameters || options?.numberedParametersStartAt?
i = 1
i = @options.numberedParametersStartAt if @options.numberedParametersStartAt?
result.text = result.text.replace /\?/g, () -> return "$#{i++}"
@options = old
result
# Deep clone
clone: ->
new @constructor @options, (block.clone() for block in @blocks)
# Get whether queries built with this builder can be nested within other queries
isNestable: ->
false
# SELECT query builder.
class cls.Select extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'SELECT'),
new cls.DistinctBlock(options),
new cls.GetFieldBlock(options),
new cls.FromTableBlock(_extend({}, options, { allowNested: true })),
new cls.JoinBlock(_extend({}, options, { allowNested: true })),
new cls.WhereBlock(options),
new cls.GroupByBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options),
new cls.OffsetBlock(options),
new cls.UnionBlock(_extend({}, options, { allowNested: true }))
]
super options, blocks
isNestable: ->
true
# UPDATE query builder.
class cls.Update extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'UPDATE'),
new cls.UpdateTableBlock(options),
new cls.SetFieldBlock(options),
new cls.WhereBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options)
]
super options, blocks
# DELETE query builder.
class cls.Delete extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'DELETE'),
new cls.FromTableBlock( _extend({}, options, { singleTable: true }) ),
new cls.JoinBlock(options),
new cls.WhereBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options),
]
super options, blocks
# An INSERT query builder.
#
class cls.Insert extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'INSERT'),
new cls.IntoTableBlock(options),
new cls.InsertFieldValueBlock(options),
new cls.InsertFieldsFromQueryBlock(options),
]
super options, blocks
_squel =
VERSION: '<<VERSION_STRING>>'
expr: -> new cls.Expression
# Don't have a space-efficient elegant-way of .apply()-ing to constructors, so we specify the args
select: (options, blocks) -> new cls.Select(options, blocks)
update: (options, blocks) -> new cls.Update(options, blocks)
insert: (options, blocks) -> new cls.Insert(options, blocks)
delete: (options, blocks) -> new cls.Delete(options, blocks)
registerValueHandler: cls.registerValueHandler
fval: cls.fval
# aliases
_squel.remove = _squel.delete
# classes
_squel.cls = cls
return _squel
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Exported API
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
squel = _buildSquel()
# AMD
if define?.amd
define ->
return squel
# CommonJS
else if module?.exports
module.exports = squel
# Browser
else
window?.squel = squel
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Squel SQL flavours
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Available flavours
squel.flavours = {}
# Setup Squel for a particular SQL flavour
squel.useFlavour = (flavour = null) ->
return squel if not flavour
if squel.flavours[flavour] instanceof Function
s = _buildSquel()
squel.flavours[flavour].call null, s
return s
else
throw new Error "Flavour not available: #{flavour}"
| true | ###
Copyright (c) 2014 PI:NAME:<NAME>END_PI (hiddentao.com)
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.
###
# Extend given object's with other objects' properties, overriding existing ones if necessary
_extend = (dst, sources...) ->
if sources
for src in sources
if src
for own k,v of src
dst[k] = v
dst
# Get a copy of given object with given properties removed
_without = (obj, properties...) ->
dst = _extend {}, obj
for p in properties
delete dst[p]
dst
# Register a value type handler
#
# Note: this will override any existing handler registered for this value type.
registerValueHandler = (handlers, type, handler) ->
if 'function' isnt typeof type and 'string' isnt typeof type
throw new Error "type must be a class constructor or string denoting 'typeof' result"
if 'function' isnt typeof handler
throw new Error "handler must be a function"
for typeHandler in handlers
if typeHandler.type is type
typeHandler.handler = handler
return
handlers.push
type: type
handler: handler
# Get value type handler for given type
getValueHandler = (value, handlerLists...) ->
for handlers in handlerLists
for typeHandler in handlers
# if type is a string then use `typeof` or else use `instanceof`
if typeHandler.type is typeof value or (typeof typeHandler.type isnt 'string' and value instanceof typeHandler.type)
return typeHandler.handler
undefined
# Build base squel classes and methods
_buildSquel = ->
# Holds classes
cls = {}
# Default query builder options
cls.DefaultQueryBuilderOptions =
# If true then table names will be rendered inside quotes. The quote character used is configurable via the
# nameQuoteCharacter option.
autoQuoteTableNames: false
# If true then field names will rendered inside quotes. The quote character used is configurable via the
# nameQuoteCharacter option.
autoQuoteFieldNames: false
# If true then alias names will rendered inside quotes. The quote character used is configurable via the `tableAliasQuoteCharacter` and `fieldAliasQuoteCharacter` options.
autoQuoteAliasNames: true
# The quote character used for when quoting table and field names
nameQuoteCharacter: '`'
# The quote character used for when quoting table alias names
tableAliasQuoteCharacter: '`'
# The quote character used for when quoting table alias names
fieldAliasQuoteCharacter: '"'
# Custom value handlers where key is the value type and the value is the handler function
valueHandlers: []
# Number parameters returned from toParam() as $1, $2, etc. Default is to use '?', startAt 1 will give $1...
numberedParameters: false
numberedParametersStartAt: 1
# If true then replaces all single quotes within strings. The replacement string used is configurable via the `singleQuoteReplacement` option.
replaceSingleQuotes: false
# The string to replace single quotes with in query strings
singleQuoteReplacement: '\'\''
# String used to join individual blocks in a query when it's stringified
separator: ' '
# Global custom value handlers for all instances of builder
cls.globalValueHandlers = []
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Custom value types
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Register a new value handler
cls.registerValueHandler = (type, handler) ->
registerValueHandler cls.globalValueHandlers, type, handler
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.FuncVal
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# A function value
class cls.FuncVal
# Constructor
#
# str - the string
# values - the parameter values
constructor: (str, values) ->
@str = str
@values = values
# Construct a FuncVal object
cls.fval = (str, values...) ->
new cls.FuncVal(str, values)
# default value handler for cls.FuncVal
cls.fval_handler = (value, asParam = false) ->
if asParam
{
text: value.str
values: value.values
}
else
str = value.str
finalStr = ''
values = value.values
for idx in [0...str.length]
c = str.charAt(idx)
if '?' is c and 0 < values.length
c = values.shift()
finalStr += c
finalStr
cls.registerValueHandler cls.FuncVal, cls.fval_handler
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base classes
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base class for cloneable builders
class cls.Cloneable
# Clone this builder
clone: ->
newInstance = new @constructor;
# Fast deep copy using JSON conversion, see http://stackoverflow.com/a/5344074
_extend newInstance, JSON.parse(JSON.stringify(@))
# Base class for all builders
class cls.BaseBuilder extends cls.Cloneable
# Constructor
#
# options is an Object overriding one or more of cls.DefaultQueryBuilderOptions
#
constructor: (options) ->
defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions))
@options = _extend {}, defaults, options
# Register a custom value handler for this builder instance.
#
# Note: this will override any globally registered handler for this value type.
registerValueHandler: (type, handler) ->
registerValueHandler @options.valueHandlers, type, handler
@
# Get class name of given object.
_getObjectClassName: (obj) ->
if obj && obj.constructor && obj.constructor.toString
arr = obj.constructor.toString().match /function\s*(\w+)/;
if arr && arr.length is 2
return arr[1]
return undefined
# Sanitize the given condition.
_sanitizeCondition: (condition) ->
# If it's not an Expression builder instance
if not (condition instanceof cls.Expression)
# It must then be a string
if "string" isnt typeof condition
throw new Error "condition must be a string or Expression instance"
condition
# Sanitize the given name.
# The 'type' parameter is used to construct a meaningful error message in case validation fails.
_sanitizeName: (value, type) ->
if "string" isnt typeof value
throw new Error "#{type} must be a string"
value
_sanitizeField: (item, formattingOptions = {}) ->
if item instanceof cls.QueryBuilder
item = "(#{item})"
else
item = @_sanitizeName item, "field name"
if @options.autoQuoteFieldNames
quoteChar = @options.nameQuoteCharacter
if formattingOptions.ignorePeriodsForFieldNameQuotes
# a.b.c -> `a.b.c`
item = "#{quoteChar}#{item}#{quoteChar}"
else
# a.b.c -> `a`.`b`.`c`
item = item
.split('.')
.map( (v) ->
# treat '*' as special case (#79)
return if '*' is v then v else "#{quoteChar}#{v}#{quoteChar}"
)
.join('.')
item
_sanitizeNestableQuery: (item) =>
return item if item instanceof cls.QueryBuilder and item.isNestable()
throw new Error "must be a nestable query, e.g. SELECT"
_sanitizeTable: (item, allowNested = false) ->
if allowNested
if "string" is typeof item
sanitized = item
else
try
sanitized = @_sanitizeNestableQuery(item)
catch e
throw new Error "table name must be a string or a nestable query instance"
else
sanitized = @_sanitizeName item, 'table name'
if @options.autoQuoteTableNames
"#{@options.nameQuoteCharacter}#{sanitized}#{@options.nameQuoteCharacter}"
else
sanitized
_sanitizeTableAlias: (item) ->
sanitized = @_sanitizeName item, "table alias"
if @options.autoQuoteAliasNames
"#{@options.tableAliasQuoteCharacter}#{sanitized}#{@options.tableAliasQuoteCharacter}"
else
sanitized
_sanitizeFieldAlias: (item) ->
sanitized = @_sanitizeName item, "field alias"
if @options.autoQuoteAliasNames
"#{@options.fieldAliasQuoteCharacter}#{sanitized}#{@options.fieldAliasQuoteCharacter}"
else
sanitized
# Sanitize the given limit/offset value.
_sanitizeLimitOffset: (value) ->
value = parseInt(value)
if 0 > value or isNaN(value)
throw new Error "limit/offset must be >= 0"
value
# Santize the given field value
_sanitizeValue: (item) ->
itemType = typeof item
if null is item
# null is allowed
else if "string" is itemType or "number" is itemType or "boolean" is itemType
# primitives are allowed
else if item instanceof cls.QueryBuilder and item.isNestable()
# QueryBuilder instances allowed
else if item instanceof cls.FuncVal
# FuncVal instances allowed
else
typeIsValid = undefined isnt getValueHandler(item, @options.valueHandlers, cls.globalValueHandlers)
unless typeIsValid
# type is not valid
throw new Error "field value must be a string, number, boolean, null or one of the registered custom value types"
item
# Escape a string value, e.g. escape quotes and other characters within it.
_escapeValue: (value) ->
return value unless true is @options.replaceSingleQuotes
value.replace /\'/g, @options.singleQuoteReplacement
# Format the given custom value
_formatCustomValue: (value, asParam = false) ->
# user defined custom handlers takes precedence
customHandler = getValueHandler(value, @options.valueHandlers, cls.globalValueHandlers)
if customHandler
# use the custom handler if available
value = customHandler(value, asParam)
value
# Format the given field value for inclusion into query parameter array
_formatValueAsParam: (value) ->
if Array.isArray(value)
value.map (v) => @_formatValueAsParam v
else
if value instanceof cls.QueryBuilder and value.isNestable()
value.updateOptions( { "nestedBuilder": true } )
p = value.toParam()
else if value instanceof cls.Expression
p = value.toParam()
else
@_formatCustomValue(value, true)
# Format the given field value for inclusion into the query string
_formatValue: (value, formattingOptions = {}) ->
customFormattedValue = @_formatCustomValue(value)
# if formatting took place then return it directly
if customFormattedValue isnt value
return "(#{customFormattedValue})"
# if it's an array then format each element separately
if Array.isArray(value)
value = value.map (v) => @_formatValue v
value = "(#{value.join(', ')})"
else
if null is value
value = "NULL"
else if "boolean" is typeof value
value = if value then "TRUE" else "FALSE"
else if value instanceof cls.QueryBuilder
value = "(#{value})"
else if value instanceof cls.Expression
value = "(#{value})"
else if "number" isnt typeof value
value = @_escapeValue(value)
value = if formattingOptions.dontQuote then "#{value}" else "'#{value}'"
value
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Expressions
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# An SQL expression builder.
#
# SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
#
# This builder works by building up the expression as a hierarchical tree of nodes. The toString() method then
# traverses this tree in order to build the final expression string.
#
# cls.Expressions can be nested. Nested expression contains can themselves contain nested expressions.
# When rendered a nested expression will be fully contained within brackets.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class cls.Expression extends cls.BaseBuilder
# The expression tree.
tree: null
# The part of the expression tree we're currently working on.
current: null
# Initialise the expression.
constructor: ->
super()
@tree =
parent: null
nodes: []
@current = @tree
# Begin a nested expression and combine it with the current expression using the given operator.
@_begin = (op) =>
new_tree =
type: op
parent: @current
nodes: []
@current.nodes.push new_tree
@current = @current.nodes[@current.nodes.length-1]
@
# Begin a nested expression and combine it with the current expression using the intersection operator (AND).
and_begin: ->
@_begin 'AND'
# Begin a nested expression and combine it with the current expression using the union operator (OR).
or_begin: ->
@_begin 'OR'
# End the current compound expression.
#
# This will throw an error if begin() hasn't been called yet.
end: ->
if not @current.parent
throw new Error "begin() needs to be called"
@current = @current.parent
@
# Combine the current expression with the given expression using the intersection operator (AND).
and: (expr, param) ->
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'AND'
expr: expr
para: param
@
# Combine the current expression with the given expression using the union operator (OR).
or: (expr, param) ->
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'OR'
expr: expr
para: param
@
# Get the final fully constructed expression string.
toString: ->
if null isnt @current.parent
throw new Error "end() needs to be called"
@_toString @tree
# Get the final fully constructed expression string.
toParam: ->
if null isnt @current.parent
throw new Error "end() needs to be called"
@_toString @tree, true
# Get a string representation of the given expression tree node.
_toString: (node, paramMode = false) ->
str = ""
params = []
for child in node.nodes
if child.expr?
nodeStr = child.expr
# have param?
if undefined isnt child.para
if not paramMode
nodeStr = nodeStr.replace '?', @_formatValue(child.para)
else
cv = @_formatValueAsParam child.para
if (cv?.text?)
params = params.concat(cv.values)
nodeStr = nodeStr.replace '?', "(#{cv.text})"
else
params = params.concat(cv)
# IN ? -> IN (?, ?, ..., ?)
if Array.isArray(child.para)
inStr = Array.apply(null, new Array(child.para.length)).map () -> '?'
nodeStr = nodeStr.replace '?', "(#{inStr.join(', ')})"
else
nodeStr = @_toString(child, paramMode)
if paramMode
params = params.concat(nodeStr.values)
nodeStr = nodeStr.text
# wrap nested expressions in brackets
if "" isnt nodeStr
nodeStr = "(" + nodeStr + ")"
if "" isnt nodeStr
# if this isn't first expression then add the operator
if "" isnt str then str += " " + child.type + " "
str += nodeStr
if paramMode
return {
text: str
values: params
}
else
return str
###
Clone this expression.
Note that the algorithm contained within this method is probably non-optimal, so please avoid cloning large
expression trees.
###
clone: ->
newInstance = new @constructor;
(_cloneTree = (node) ->
for child in node.nodes
if child.expr?
newInstance.current.nodes.push JSON.parse(JSON.stringify(child))
else
newInstance._begin child.type
_cloneTree child
if not @current is child
newInstance.end()
)(@tree)
newInstance
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Building blocks
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# A building block represents a single build-step within a query building process.
#
# Query builders consist of one or more building blocks which get run in a particular order. Building blocks can
# optionally specify methods to expose through the query builder interface. They can access all the input data for
# the query builder and manipulate it as necessary, as well as append to the final query string output.
#
# If you wish to customize how queries get built or add proprietary query phrases and content then it is recommended
# that you do so using one or more custom building blocks.
#
# Original idea posted in https://github.com/hiddentao/export/issues/10#issuecomment-15016427
class cls.Block extends cls.BaseBuilder
# Get input methods to expose within the query builder.
#
# By default all methods except the following get returned:
# methods prefixed with _
# constructor and buildStr()
#
# @return Object key -> function pairs
exposedMethods: ->
ret = {}
for attr, value of @
# only want functions from this class
if typeof value is "function" and attr.charAt(0) isnt '_' and !cls.Block::[attr]
ret[attr] = value
ret
# Build this block.
#
# Subclasses may override this method.
#
# @param queryBuilder cls.QueryBuilder a reference to the query builder that owns this block.
#
# @return String the string representing this block
buildStr: (queryBuilder) ->
''
buildParam: (queryBuilder) ->
{ text: @buildStr(queryBuilder), values: [] }
# A String which always gets output
class cls.StringBlock extends cls.Block
constructor: (options, str) ->
super options
@str = str
buildStr: (queryBuilder) ->
@str
# A values which gets output as is
class cls.AbstractValueBlock extends cls.Block
constructor: (options) ->
super options
@_val = null
_setValue: (val) ->
@_val = val
buildStr: (queryBuilder) ->
if not @_val then "" else @_val
# Table specifier base class
#
# Additional options
# - singleTable - only allow one table to be specified (default: false)
# - allowNested - allow nested query to be specified as a table (default: false)
class cls.AbstractTableBlock extends cls.Block
constructor: (options) ->
super options
@tables = []
# Update given table.
#
# An alias may also be specified for the table.
#
# Concrete subclasses should provide a method which calls this
_table: (table, alias = null) ->
alias = @_sanitizeTableAlias(alias) if alias
table = @_sanitizeTable(table, @options.allowNested or false)
if @options.singleTable
@tables = []
@tables.push
table: table
alias: alias
buildStr: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "_table() needs to be called"
tables = ""
for table in @tables
tables += ", " if "" isnt tables
if "string" is typeof table.table
tables += table.table
else
# building a nested query
tables += "(#{table.table})"
if table.alias
# add the table alias, the AS keyword is optional
tables += " #{table.alias}"
tables
_buildParam: (queryBuilder, prefix = null) ->
ret =
text: ""
values: []
params = []
paramStr = ""
if 0 >= @tables.length then return ret
# retrieve the parameterised queries
for blk in @tables
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
p.table = blk
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
if paramStr isnt ""
paramStr += ", "
else
paramStr += "#{prefix} #{paramStr}" if prefix? and prefix isnt ""
paramStr
if "string" is typeof p.table.table
paramStr += "#{p.text}"
else
paramStr += "(#{p.text})"
# add the table alias, the AS keyword is optional
paramStr += " #{p.table.alias}" if p.table.alias?
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += paramStr
ret
buildParam: (queryBuilder) ->
@_buildParam(queryBuilder)
# Update Table
class cls.UpdateTableBlock extends cls.AbstractTableBlock
table: (table, alias = null) ->
@_table(table, alias)
# FROM table
class cls.FromTableBlock extends cls.AbstractTableBlock
from: (table, alias = null) ->
@_table(table, alias)
buildStr: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "from() needs to be called"
tables = super queryBuilder
"FROM #{tables}"
buildParam: (queryBuilder) ->
if 0 >= @tables.length then throw new Error "from() needs to be called"
@_buildParam(queryBuilder, "FROM")
# INTO table
class cls.IntoTableBlock extends cls.Block
constructor: (options) ->
super options
@table = null
# Into given table.
into: (table) ->
# do not allow nested table to be the target
@table = @_sanitizeTable(table, false)
buildStr: (queryBuilder) ->
if not @table then throw new Error "into() needs to be called"
"INTO #{@table}"
# (SELECT) Get field
class cls.GetFieldBlock extends cls.Block
constructor: (options) ->
super options
@_fieldAliases = {}
@_fields = []
# Add the given fields to the final result set.
#
# The parameter is an Object containing field names (or database functions) as the keys and aliases for the fields
# as the values. If the value for a key is null then no alias is set for that field.
#
# Internally this method simply calls the field() method of this block to add each individual field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
fields: (_fields, options = {}) ->
if Array.isArray(_fields)
for field in _fields
@field field, null, options
else
for field, alias of _fields
@field(field, alias, options)
# Add the given field to the final result set.
#
# The 'field' parameter does not necessarily have to be a fieldname. It can use database functions too,
# e.g. DATE_FORMAT(a.started, "%H")
#
# An alias may also be specified for this field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
field: (field, alias = null, options = {}) ->
field = @_sanitizeField(field, options)
alias = @_sanitizeFieldAlias(alias) if alias
# if field-alias already present then don't add
return if @_fieldAliases[field] is alias
@_fieldAliases[field] = alias
@_fields.push
name: field
alias: alias
buildStr: (queryBuilder) ->
fields = ""
for field in @_fields
fields += ", " if "" isnt fields
fields += field.name
fields += " AS #{field.alias}" if field.alias
if "" is fields then "*" else fields
# Base class for setting fields to values (used for INSERT and UPDATE queries)
class cls.AbstractSetFieldBlock extends cls.Block
constructor: (options) ->
super options
@fieldOptions = []
@fields = []
@values = []
# Update the given field with the given value.
# This will override any previously set value for the given field.
_set: (field, value, options = {}) ->
throw new Error "Cannot call set or setFields on multiple rows of fields." if @values.length > 1
value = @_sanitizeValue(value) if undefined isnt value
# Explicity overwrite existing fields
index = @fields.indexOf(@_sanitizeField(field, options))
if index isnt -1
@values[0][index] = value
@fieldOptions[0][index] = options
else
@fields.push @_sanitizeField(field, options)
index = @fields.length - 1
# The first value added needs to create the array of values for the row
if Array.isArray(@values[0])
@values[0][index] = value
@fieldOptions[0][index] = options
else
@values.push [value]
@fieldOptions.push [options]
@
# Insert fields based on the key/value pairs in the given object
_setFields: (fields, options = {}) ->
throw new Error "Expected an object but got " + typeof fields unless typeof fields is 'object'
for own field of fields
@_set field, fields[field], options
@
# Insert multiple rows for the given fields. Accepts an array of objects.
# This will override all previously set values for every field.
_setFieldsRows: (fieldsRows, options = {}) ->
throw new Error "Expected an array of objects but got " + typeof fieldsRows unless Array.isArray(fieldsRows)
# Reset the objects stored fields and values
@fields = []
@values = []
for i in [0...fieldsRows.length]
for own field of fieldsRows[i]
index = @fields.indexOf(@_sanitizeField(field, options))
throw new Error 'All fields in subsequent rows must match the fields in the first row' if 0 < i and -1 is index
# Add field only if it hasn't been added before
if -1 is index
@fields.push @_sanitizeField(field, options)
index = @fields.length - 1
value = @_sanitizeValue(fieldsRows[i][field])
# The first value added needs to add the array
if Array.isArray(@values[i])
@values[i][index] = value
@fieldOptions[i][index] = options
else
@values[i] = [value]
@fieldOptions[i] = [options]
@
buildStr: ->
throw new Error('Not yet implemented')
buildParam: ->
throw new Error('Not yet implemented')
# (UPDATE) SET field=value
class cls.SetFieldBlock extends cls.AbstractSetFieldBlock
set: (field, value, options) ->
@_set field, value, options
setFields: (fields, options) ->
@_setFields fields, options
buildStr: (queryBuilder) ->
if 0 >= @fields.length then throw new Error "set() needs to be called"
str = ""
for i in [0...@fields.length]
field = @fields[i]
str += ", " if "" isnt str
value = @values[0][i]
fieldOptions = @fieldOptions[0][i]
if typeof value is 'undefined' # e.g. if field is an expression such as: count = count + 1
str += field
else
str += "#{field} = #{if fieldOptions.dontQuote and typeof value is 'string' then value else @_formatValue(value, fieldOptions)}"
"SET #{str}"
buildParam: (queryBuilder) ->
if 0 >= @fields.length then throw new Error "set() needs to be called"
str = ""
vals = []
for i in [0...@fields.length]
field = @fields[i]
str += ", " if "" isnt str
value = @values[0][i]
if typeof value is 'undefined' # e.g. if field is an expression such as: count = count + 1
str += field
else
p = @_formatValueAsParam( value )
if p?.text?
str += "#{field} = (#{p.text})"
for v in p.values
vals.push v
else
str += "#{field} = ?"
vals.push p
{ text: "SET #{str}", values: vals }
# (INSERT INTO) ... field ... value
class cls.InsertFieldValueBlock extends cls.AbstractSetFieldBlock
set: (field, value, options = {}) ->
@_set field, value, options
setFields: (fields, options) ->
@_setFields fields, options
setFieldsRows: (fieldsRows, options) ->
@_setFieldsRows fieldsRows, options
_buildVals: ->
vals = []
for i in [0...@values.length]
for j in [0...@values[i].length]
formattedValue = if @fieldOptions[i][j].dontQuote and typeof @values[i][j] is 'string' then @values[i][j] else @_formatValue @values[i][j], @fieldOptions[i][j]
if 'string' is typeof vals[i]
vals[i] += ', ' + formattedValue
else
vals[i] = '' + formattedValue
vals
_buildValParams: ->
vals = []
params = []
for i in [0...@values.length]
for j in [0...@values[i].length]
p = @_formatValueAsParam( @values[i][j] )
if p?.text?
str = p.text
for v in p.values
params.push v
else
str = '?'
params.push p
if 'string' is typeof vals[i]
vals[i] += ", #{str}"
else
vals[i] = "#{str}"
vals: vals
params: params
buildStr: (queryBuilder) ->
return '' if 0 >= @fields.length
"(#{@fields.join(', ')}) VALUES (#{@_buildVals().join('), (')})"
buildParam: (queryBuilder) ->
return { text: '', values: [] } if 0 >= @fields.length
# fields
str = ""
{vals, params} = @_buildValParams()
for i in [0...@fields.length]
str += ", " if "" isnt str
str += @fields[i]
{ text: "(#{str}) VALUES (#{vals.join('), (')})", values: params }
# (INSERT INTO) ... field ... (SELECT ... FROM ...)
class cls.InsertFieldsFromQueryBlock extends cls.Block
constructor: (options) ->
super options
@_fields = []
@_query = null
fromQuery: (fields, selectQuery) ->
@_fields = fields.map ( (v) => @_sanitizeField(v) )
@_query = @_sanitizeNestableQuery(selectQuery)
buildStr: (queryBuilder) ->
return '' if 0 >= @_fields.length
"(#{@_fields.join(', ')}) (#{@_query.toString()})"
buildParam: (queryBuilder) ->
return { text: '', values: [] } if 0 >= @_fields.length
qryParam = @_query.toParam()
{
text: "(#{@_fields.join(', ')}) (#{qryParam.text})",
values: qryParam.values,
}
# DISTINCT
class cls.DistinctBlock extends cls.Block
constructor: (options) ->
super options
@useDistinct = false
# Add the DISTINCT keyword to the query.
distinct: ->
@useDistinct = true
buildStr: (queryBuilder) ->
if @useDistinct then "DISTINCT" else ""
# GROUP BY
class cls.GroupByBlock extends cls.Block
constructor: (options) ->
super options
@groups = []
# Add a GROUP BY transformation for the given field.
group: (field) ->
field = @_sanitizeField(field)
@groups.push field
buildStr: (queryBuilder) ->
groups = ""
if 0 < @groups.length
for f in @groups
groups += ", " if "" isnt groups
groups += f
groups = "GROUP BY #{groups}"
groups
# OFFSET x
class cls.OffsetBlock extends cls.Block
constructor: (options) ->
super options
@offsets = null
# Set the OFFSET transformation.
#
# Call this will override the previously set offset for this query. Also note that Passing 0 for 'max' will remove
# the offset.
offset: (start) ->
start = @_sanitizeLimitOffset(start)
@offsets = start
buildStr: (queryBuilder) ->
if @offsets then "OFFSET #{@offsets}" else ""
# WHERE
class cls.WhereBlock extends cls.Block
constructor: (options) ->
super options
@wheres = []
# Add a WHERE condition.
#
# When the final query is constructed all the WHERE conditions are combined using the intersection (AND) operator.
where: (condition, values...) ->
condition = @_sanitizeCondition(condition)
finalCondition = ""
finalValues = []
# if it's an Expression instance then convert to text and values
if condition instanceof cls.Expression
t = condition.toParam()
finalCondition = t.text
finalValues = t.values
else
for idx in [0...condition.length]
c = condition.charAt(idx)
if '?' is c and 0 < values.length
nextValue = values.shift()
if Array.isArray(nextValue) # where b in (?, ? ?)
inValues = []
for item in nextValue
inValues.push @_sanitizeValue(item)
finalValues = finalValues.concat(inValues)
finalCondition += "(#{('?' for item in inValues).join ', '})"
else
finalCondition += '?'
finalValues.push @_sanitizeValue(nextValue)
else
finalCondition += c
if "" isnt finalCondition
@wheres.push
text: finalCondition
values: finalValues
buildStr: (queryBuilder) ->
if 0 >= @wheres.length then return ""
whereStr = ""
for where in @wheres
if "" isnt whereStr then whereStr += ") AND ("
if 0 < where.values.length
# replace placeholders with actual parameter values
pIndex = 0
for idx in [0...where.text.length]
c = where.text.charAt(idx)
if '?' is c
whereStr += @_formatValue( where.values[pIndex++] )
else
whereStr += c
else
whereStr += where.text
"WHERE (#{whereStr})"
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
if 0 >= @wheres.length then return ret
whereStr = ""
for where in @wheres
if "" isnt whereStr then whereStr += ") AND ("
str = where.text.split('?')
i = 0
for v in where.values
whereStr += "#{str[i]}" if str[i]?
p = @_formatValueAsParam(v)
if (p?.text?)
whereStr += "(#{p.text})"
for qv in p.values
ret.values.push( qv )
else
whereStr += "?"
ret.values.push( p )
i = i+1
whereStr += "#{str[i]}" if str[i]?
ret.text = "WHERE (#{whereStr})"
ret
# ORDER BY
class cls.OrderByBlock extends cls.Block
constructor: (options) ->
super options
@orders = []
@_values = []
# Add an ORDER BY transformation for the given field in the given order.
#
# To specify descending order pass false for the 'asc' parameter.
order: (field, asc = true, values...) ->
field = @_sanitizeField(field)
@_values = values
@orders.push
field: field
dir: if asc then true else false
_buildStr: (toParam = false) ->
if 0 < @orders.length
pIndex = 0
orders = ""
for o in @orders
orders += ", " if "" isnt orders
fstr = ""
if not toParam
for idx in [0...o.field.length]
c = o.field.charAt(idx)
if '?' is c
fstr += @_formatValue( @_values[pIndex++] )
else
fstr += c
else
fstr = o.field
orders += "#{fstr} #{if o.dir then 'ASC' else 'DESC'}"
"ORDER BY #{orders}"
else
""
buildStr: (queryBuilder) ->
@_buildStr()
buildParam: (queryBuilder) ->
{
text: @_buildStr(true)
values: @_values.map (v) => @_formatValueAsParam(v)
}
# LIMIT
class cls.LimitBlock extends cls.Block
constructor: (options) ->
super options
@limits = null
# Set the LIMIT transformation.
#
# Call this will override the previously set limit for this query. Also note that Passing 0 for 'max' will remove
# the limit.
limit: (max) ->
max = @_sanitizeLimitOffset(max)
@limits = max
buildStr: (queryBuilder) ->
if @limits then "LIMIT #{@limits}" else ""
# JOIN
class cls.JoinBlock extends cls.Block
constructor: (options) ->
super options
@joins = []
# Add a JOIN with the given table.
#
# 'table' is the name of the table to join with.
#
# 'alias' is an optional alias for the table name.
#
# 'condition' is an optional condition (containing an SQL expression) for the JOIN. If this is an instance of
# an expression builder then it gets evaluated straight away.
#
# 'type' must be either one of INNER, OUTER, LEFT or RIGHT. Default is 'INNER'.
#
join: (table, alias = null, condition = null, type = 'INNER') ->
table = @_sanitizeTable(table, true)
alias = @_sanitizeTableAlias(alias) if alias
condition = @_sanitizeCondition(condition) if condition
@joins.push
type: type
table: table
alias: alias
condition: condition
@
# Add a LEFT JOIN with the given table.
left_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'LEFT'
# Add a RIGHT JOIN with the given table.
right_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'RIGHT'
# Add an OUTER JOIN with the given table.
outer_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'OUTER'
# Add a LEFT JOIN with the given table.
left_outer_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'LEFT OUTER'
# Add an FULL JOIN with the given table.
full_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'FULL'
# Add an CROSS JOIN with the given table.
cross_join: (table, alias = null, condition = null) ->
@join table, alias, condition, 'CROSS'
buildStr: (queryBuilder) ->
joins = ""
for j in (@joins or [])
if joins isnt "" then joins += " "
joins += "#{j.type} JOIN "
if "string" is typeof j.table
joins += j.table
else
joins += "(#{j.table})"
joins += " #{j.alias}" if j.alias
joins += " ON (#{j.condition})" if j.condition
joins
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
params = []
joinStr = ""
if 0 >= @joins.length then return ret
# retrieve the parameterised queries
for blk in @joins
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
if blk.condition instanceof cls.Expression
cp = blk.condition.toParam()
p.condition = cp.text
p.values = p.values.concat(cp.values)
else
p.condition = blk.condition
p.join = blk
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
if joinStr isnt "" then joinStr += " "
joinStr += "#{p.join.type} JOIN "
if "string" is typeof p.join.table
joinStr += p.text
else
joinStr += "(#{p.text})"
joinStr += " #{p.join.alias}" if p.join.alias
joinStr += " ON (#{p.condition})" if p.condition
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += joinStr
ret
# UNION
class cls.UnionBlock extends cls.Block
constructor: (options) ->
super options
@unions = []
# Add a UNION with the given table/query.
#
# 'table' is the name of the table or query to union with.
#
#
# 'type' must be either one of UNION or UNION ALL.... Default is 'UNION'.
#
union: (table, type = 'UNION') ->
table = @_sanitizeTable(table, true)
@unions.push
type: type
table: table
@
# Add a UNION ALL with the given table/query.
union_all: (table) ->
@union table, 'UNION ALL'
buildStr: (queryBuilder) ->
unionStr = ""
for j in (@unions or [])
if unionStr isnt "" then unionStr += " "
unionStr += "#{j.type} "
if "string" is typeof j.table
unionStr += j.table
else
unionStr += "(#{j.table})"
unionStr
buildParam: (queryBuilder) ->
ret =
text: ""
values: []
params = []
unionStr = ""
if 0 >= @unions.length then return ret
# retrieve the parameterised queries
for blk in (@unions or [])
if "string" is typeof blk.table
p = { "text": "#{blk.table}", "values": [] }
else if blk.table instanceof cls.QueryBuilder
# building a nested query
blk.table.updateOptions( { "nestedBuilder": true } )
p = blk.table.toParam()
else
# building a nested query
blk.updateOptions( { "nestedBuilder": true } )
p = blk.buildParam(queryBuilder)
p.type = blk.type
params.push( p )
# join the queries and their parameters
# this is the last building block processed so always add UNION if there are any UNION blocks
for p in params
unionStr += " " if unionStr isnt ""
unionStr += "#{p.type} (#{p.text})"
for v in p.values
ret.values.push( @_formatCustomValue v )
ret.text += unionStr
ret
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builders
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builder base class
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class cls.QueryBuilder extends cls.BaseBuilder
# Constructor
#
# blocks - array of cls.BaseBuilderBlock instances to build the query with.
constructor: (options, blocks) ->
super options
@blocks = blocks or []
# Copy exposed methods into myself
for block in @blocks
for methodName, methodBody of block.exposedMethods()
if @[methodName]?
throw new Error "#{@_getObjectClassName(@)} already has a builder method called: #{methodName}"
( (block, name, body) =>
@[name] = =>
body.apply(block, arguments)
@
)(block, methodName, methodBody)
# Register a custom value handler for this query builder and all its contained blocks.
#
# Note: This will override any globally registered handler for this value type.
registerValueHandler: (type, handler) ->
for block in @blocks
block.registerValueHandler type, handler
super type, handler
@
# Update query builder options
#
# This will update the options for all blocks too. Use this method with caution as it allows you to change the
# behaviour of your query builder mid-build.
updateOptions: (options) ->
@options = _extend({}, @options, options)
for block in @blocks
block.options = _extend({}, block.options, options)
# Get the final fully constructed query string.
toString: ->
(block.buildStr(@) for block in @blocks).filter (v) ->
0 < v.length
.join(@options.separator)
# Get the final fully constructed query param obj.
toParam: (options = undefined)->
old = @options
@options = _extend({}, @options, options) if options?
result = { text: '', values: [] }
blocks = (block.buildParam(@) for block in @blocks)
result.text = (block.text for block in blocks).filter (v) ->
0 < v.length
.join(@options.separator)
result.values = [].concat (block.values for block in blocks)...
if not @options.nestedBuilder?
if @options.numberedParameters || options?.numberedParametersStartAt?
i = 1
i = @options.numberedParametersStartAt if @options.numberedParametersStartAt?
result.text = result.text.replace /\?/g, () -> return "$#{i++}"
@options = old
result
# Deep clone
clone: ->
new @constructor @options, (block.clone() for block in @blocks)
# Get whether queries built with this builder can be nested within other queries
isNestable: ->
false
# SELECT query builder.
class cls.Select extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'SELECT'),
new cls.DistinctBlock(options),
new cls.GetFieldBlock(options),
new cls.FromTableBlock(_extend({}, options, { allowNested: true })),
new cls.JoinBlock(_extend({}, options, { allowNested: true })),
new cls.WhereBlock(options),
new cls.GroupByBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options),
new cls.OffsetBlock(options),
new cls.UnionBlock(_extend({}, options, { allowNested: true }))
]
super options, blocks
isNestable: ->
true
# UPDATE query builder.
class cls.Update extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'UPDATE'),
new cls.UpdateTableBlock(options),
new cls.SetFieldBlock(options),
new cls.WhereBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options)
]
super options, blocks
# DELETE query builder.
class cls.Delete extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'DELETE'),
new cls.FromTableBlock( _extend({}, options, { singleTable: true }) ),
new cls.JoinBlock(options),
new cls.WhereBlock(options),
new cls.OrderByBlock(options),
new cls.LimitBlock(options),
]
super options, blocks
# An INSERT query builder.
#
class cls.Insert extends cls.QueryBuilder
constructor: (options, blocks = null) ->
blocks or= [
new cls.StringBlock(options, 'INSERT'),
new cls.IntoTableBlock(options),
new cls.InsertFieldValueBlock(options),
new cls.InsertFieldsFromQueryBlock(options),
]
super options, blocks
_squel =
VERSION: '<<VERSION_STRING>>'
expr: -> new cls.Expression
# Don't have a space-efficient elegant-way of .apply()-ing to constructors, so we specify the args
select: (options, blocks) -> new cls.Select(options, blocks)
update: (options, blocks) -> new cls.Update(options, blocks)
insert: (options, blocks) -> new cls.Insert(options, blocks)
delete: (options, blocks) -> new cls.Delete(options, blocks)
registerValueHandler: cls.registerValueHandler
fval: cls.fval
# aliases
_squel.remove = _squel.delete
# classes
_squel.cls = cls
return _squel
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Exported API
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
squel = _buildSquel()
# AMD
if define?.amd
define ->
return squel
# CommonJS
else if module?.exports
module.exports = squel
# Browser
else
window?.squel = squel
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Squel SQL flavours
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Available flavours
squel.flavours = {}
# Setup Squel for a particular SQL flavour
squel.useFlavour = (flavour = null) ->
return squel if not flavour
if squel.flavours[flavour] instanceof Function
s = _buildSquel()
squel.flavours[flavour].call null, s
return s
else
throw new Error "Flavour not available: #{flavour}"
|
[
{
"context": "VG To HTML Image Library v0.06\nhttps://github.com/CindyLinz/Coffee-svg2html_img\n\nCopyright 2012, Cindy Wang (",
"end": 65,
"score": 0.9996631741523743,
"start": 56,
"tag": "USERNAME",
"value": "CindyLinz"
},
{
"context": "com/CindyLinz/Coffee-svg2html_img\n\nCopyrigh... | lib/svg2html_image.coffee | CindyLinz/Coffee-svg2html_img | 1 | ###
SVG To HTML Image Library v0.06
https://github.com/CindyLinz/Coffee-svg2html_img
Copyright 2012, Cindy Wang (CindyLinz)
Dual licensed under the MIT or GPL Version 2 licenses.
Date: 2012.5.2
###
log = (msg) ->
window.console.log(msg) if window.console?
ajax_load = (url, cb) ->
req =
if window.XMLHttpRequest
new XMLHttpRequest()
else if window.ActiveXObject
try
new ActiveXObject("Msxml2.XMLHTTP")
catch e
new ActiveXObject("Microsoft.XMLHTTP")
else
log("no ajax supported")
unless req?
cb(req)
return
req.onreadystatechange = () ->
if req.readyState==4
cb(req)
req.open('GET', url)
req.send(null)
base64_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
utf8_encode = (input) ->
return input.replace(/[^\x00-\x7F]/g, ($0) ->
code = $0.charCodeAt(0)
out = ''
while code > 63
out = String.fromCharCode(code & 63 | 128) + out
code >>= 6
switch out.length
when 1
return String.fromCharCode(code | 192) + out
when 2
return String.fromCharCode(code | 224) + out
when 3
return String.fromCharCode(code | 240) + out
when 4
return String.fromCharCode(code | 248) + out
when 5
return String.fromCharCode(code | 252) + out
)
base64_encode = (input) ->
out = ''
for i in [0...input.length-2] by 3
out += base64_letter.charAt( a = input.charCodeAt(i) >> 2 )
out += base64_letter.charAt( b = ((input.charCodeAt(i)&3) << 4) | (input.charCodeAt(i+1) >> 4) )
out += base64_letter.charAt( c = ((input.charCodeAt(i+1)&15) << 2) | (input.charCodeAt(i+2) >> 6) )
out += base64_letter.charAt( d = input.charCodeAt(i+2)&63 )
switch input.length % 3
when 1
out += base64_letter.charAt( input.charCodeAt(input.length-1) >> 2 )
out += base64_letter.charAt( (input.charCodeAt(input.length-1)&3) << 4 )
out += '=='
when 2
out += base64_letter.charAt( input.charCodeAt(input.length-2) >> 2 )
out += base64_letter.charAt( ((input.charCodeAt(input.length-2)&3) << 4) | (input.charCodeAt(input.length-1) >> 4) )
out += base64_letter.charAt( (input.charCodeAt(input.length-1)&15) << 2 )
out += '='
return out
node2text = (node) ->
out = ''
build = (node) ->
unless node?
return
if node.nodeName == '#comment'
return
if node.nodeName == '#text'
out += node.data
return
if node.nodeName.charAt(0) == '#'
log "node2text: unimplemented dom node type #{node.nodeName}"
return
out += '<'
out += node.nodeName
for attr in node.attributes
out += ' '
out += attr.nodeName
out += '="'
out += attr.nodeValue.
replace(/&/g, '&').
replace(/"/g, '"')
out += '"'
if node.nodeName=='svg'
out += ' xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"'
if node.hasChildNodes()
out += '>'
build(child) for child in node.childNodes
out += '</'
out += node.nodeName
out += '>'
else
out += '/>'
build(node)
return out
build_image = (svg) ->
return unless svg?
doc = window.document
doc.getElementsByTagName('body')[0].appendChild(svg)
#log svg.getBBox()
bbox = svg.getBBox()
#alert "bbox = #{bbox.width}x#{bbox.height}+#{bbox.x}+#{bbox.y}"
svg.parentNode.removeChild(svg)
img = doc.createElement('img')
img.style.position = 'absolute'
img.style.visibility = 'hidden'
img.style.left = '-9999px'
img.style.top = '-9999px'
if svg.getAttribute('width')? && svg.getAttribute('height')?
img.style.width = svg.getAttribute('width')
img.style.height = svg.getAttribute('height')
#img.style.width = '1000px'
#img.style.height = '666px'
#log img.complete
img.src = 'data:image/svg+xml;base64,' + base64_encode utf8_encode node2text svg
#log img.complete
#alert base64_encode utf8_encode node2text svg
#img.src = 'svg_basic/chips.svg'
doc.getElementsByTagName('body')[0].appendChild(img)
return [img, bbox]
build_images = (svg, id_list, cb) ->
build_id2node = (node, id2node) ->
return id2node if node.nodeType==3 || node.nodeType==4
if node.nodeType==1
id = node.getAttribute('id')
if id?
if id2node[id]?
log "duplicated id: #{id}"
id2node[id] = node
build_id2node(child, id2node) for child in node.childNodes
return id2node
id2node = build_id2node(svg, {})
find_dep = (node, dep_node) ->
return dep_node if node.nodeName.charAt(0) == '#'
for attr in node.attributes
matches = attr.nodeValue.match(/#[^\s()]+/g)
if matches?
for match in matches
ref_id = match.substr(1)
if id2node[ref_id]?
unless dep_node[ref_id]?
dep_node[ref_id] = id2node[ref_id]
find_dep(id2node[ref_id], dep_node)
find_dep(child, dep_node) for child in node.childNodes
return dep_node
extract_svg = (id_series) ->
positive_nodes = []
negative_ids = {}
negative_prefixes = []
for id in id_series.split(/\s+/)
if id==''
continue
if id.charAt(0) == '-'
if id.charAt(id.length-1) == '*'
negative_prefixes.push(id.substr(1, id.length-2))
else
negative_ids[id.substr(1)] = yes
else
if id.charAt(id.length-1) == '*'
prefix = id.substr(0, id.length-1)
for node_id, node of id2node
if node_id.substr(0, prefix.length) == prefix
positive_nodes.push(node)
else if node = id2node[id]
positive_nodes.push(node)
if positive_nodes.length==0
positive_nodes.push svg
deps = {}
for node in positive_nodes
find_dep(node, deps)
seeds = ( node for node in positive_nodes )
for dep_id, dep_node of deps
seeds.push(dep_node)
for seed, i in seeds
ptr = seed
seeds[i] = [seed]
while ptr!=svg && ptr.parentNode?
ptr = ptr.parentNode
seeds[i].unshift(ptr)
do_clone = (node, depth, get_all) ->
unless get_all
take = no
for seed in seeds
if seed[depth]==node
if depth==seed.length-1
get_all = yes
take = yes
break
return unless take
if node.nodeType==3 || node.nodeType==4
return window.document.createTextNode(node.nodeValue)
if node.nodeType==9 || node.nodeType==11
for child in node.childNodes
cloned_child = do_clone(child, depth+1, get_all)
return cloned_child if cloned_child
if node.nodeType!=1
return
if id = node.getAttribute('id')
if negative_ids[id]
return
for neg_id in negative_prefixes
if id.substr(0, neg_id.length) == neg_id
return
cloned_node = window.document.createElementNS(node.namespaceURI, node.nodeName)
for attr in node.attributes
continue if attr.nodeName.match(/^xmlns\b/)
cloned_node.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.nodeValue)
for child in node.childNodes
cloned_child = do_clone(child, depth+1, get_all)
cloned_node.appendChild(cloned_child) if cloned_child
return cloned_node
return do_clone(svg, 0, no)
form1 =
if id_list?
no
else
id_list = ['']
true
done_one = () ->
--waiting
if waiting<=0
window.setTimeout( () ->
if form1
if imgs[0]?
cb(imgs[0]...)
else
cb(null, null, null)
else
cb(imgs)
, 0)
waiting = id_list.length
imgs =
for id in id_list
extrated_svg = extract_svg id
img_and_bbox = build_image extrated_svg
if img_and_bbox?
[img, bbox] = img_and_bbox
img.onload = done_one
[img, bbox, extrated_svg]
else
done_one()
null
svg2html_image = (svg, id_list, cb) ->
unless cb?
cb = id_list
id_list = undefined
if typeof(svg)=='string'
if svg.match(/^\s*</)
xml =
if window.DOMParser?
parser = new DOMParser
parser.parseFromString(svg, 'text/xml')
else
xml = new ActiveXObject('Microsoft.XMLDOM')
xml.async = no
xml.loadXML(svg.replace(/<!DOCTYPE svg[^>]*>/, ''))
xml
build_images(xml, id_list, cb)
else
ajax_load(svg, (req) ->
success = yes
unless req?
success = no
if success && req.status!=200
log "fetch #{svg} fail: #{req.status}"
success = no
if success && !req.responseXML
log "fetch #{svg} fail: not XML"
success = no
if success && !req.responseXML.documentElement
log "fetch #{svg} fail: no documentElement"
success = no
if success
build_images(req.responseXML.documentElement, id_list, cb)
unless success
out = ( null for x in id_list )
cb(out)
)
else
build_images(svg, id_list, cb)
if window.require? and window.define?
define([], () -> svg2html_image)
else
window.svg2html_image = svg2html_image
| 201245 | ###
SVG To HTML Image Library v0.06
https://github.com/CindyLinz/Coffee-svg2html_img
Copyright 2012, <NAME> (CindyLinz)
Dual licensed under the MIT or GPL Version 2 licenses.
Date: 2012.5.2
###
log = (msg) ->
window.console.log(msg) if window.console?
ajax_load = (url, cb) ->
req =
if window.XMLHttpRequest
new XMLHttpRequest()
else if window.ActiveXObject
try
new ActiveXObject("Msxml2.XMLHTTP")
catch e
new ActiveXObject("Microsoft.XMLHTTP")
else
log("no ajax supported")
unless req?
cb(req)
return
req.onreadystatechange = () ->
if req.readyState==4
cb(req)
req.open('GET', url)
req.send(null)
base64_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
utf8_encode = (input) ->
return input.replace(/[^\x00-\x7F]/g, ($0) ->
code = $0.charCodeAt(0)
out = ''
while code > 63
out = String.fromCharCode(code & 63 | 128) + out
code >>= 6
switch out.length
when 1
return String.fromCharCode(code | 192) + out
when 2
return String.fromCharCode(code | 224) + out
when 3
return String.fromCharCode(code | 240) + out
when 4
return String.fromCharCode(code | 248) + out
when 5
return String.fromCharCode(code | 252) + out
)
base64_encode = (input) ->
out = ''
for i in [0...input.length-2] by 3
out += base64_letter.charAt( a = input.charCodeAt(i) >> 2 )
out += base64_letter.charAt( b = ((input.charCodeAt(i)&3) << 4) | (input.charCodeAt(i+1) >> 4) )
out += base64_letter.charAt( c = ((input.charCodeAt(i+1)&15) << 2) | (input.charCodeAt(i+2) >> 6) )
out += base64_letter.charAt( d = input.charCodeAt(i+2)&63 )
switch input.length % 3
when 1
out += base64_letter.charAt( input.charCodeAt(input.length-1) >> 2 )
out += base64_letter.charAt( (input.charCodeAt(input.length-1)&3) << 4 )
out += '=='
when 2
out += base64_letter.charAt( input.charCodeAt(input.length-2) >> 2 )
out += base64_letter.charAt( ((input.charCodeAt(input.length-2)&3) << 4) | (input.charCodeAt(input.length-1) >> 4) )
out += base64_letter.charAt( (input.charCodeAt(input.length-1)&15) << 2 )
out += '='
return out
node2text = (node) ->
out = ''
build = (node) ->
unless node?
return
if node.nodeName == '#comment'
return
if node.nodeName == '#text'
out += node.data
return
if node.nodeName.charAt(0) == '#'
log "node2text: unimplemented dom node type #{node.nodeName}"
return
out += '<'
out += node.nodeName
for attr in node.attributes
out += ' '
out += attr.nodeName
out += '="'
out += attr.nodeValue.
replace(/&/g, '&').
replace(/"/g, '"')
out += '"'
if node.nodeName=='svg'
out += ' xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"'
if node.hasChildNodes()
out += '>'
build(child) for child in node.childNodes
out += '</'
out += node.nodeName
out += '>'
else
out += '/>'
build(node)
return out
build_image = (svg) ->
return unless svg?
doc = window.document
doc.getElementsByTagName('body')[0].appendChild(svg)
#log svg.getBBox()
bbox = svg.getBBox()
#alert "bbox = #{bbox.width}x#{bbox.height}+#{bbox.x}+#{bbox.y}"
svg.parentNode.removeChild(svg)
img = doc.createElement('img')
img.style.position = 'absolute'
img.style.visibility = 'hidden'
img.style.left = '-9999px'
img.style.top = '-9999px'
if svg.getAttribute('width')? && svg.getAttribute('height')?
img.style.width = svg.getAttribute('width')
img.style.height = svg.getAttribute('height')
#img.style.width = '1000px'
#img.style.height = '666px'
#log img.complete
img.src = 'data:image/svg+xml;base64,' + base64_encode utf8_encode node2text svg
#log img.complete
#alert base64_encode utf8_encode node2text svg
#img.src = 'svg_basic/chips.svg'
doc.getElementsByTagName('body')[0].appendChild(img)
return [img, bbox]
build_images = (svg, id_list, cb) ->
build_id2node = (node, id2node) ->
return id2node if node.nodeType==3 || node.nodeType==4
if node.nodeType==1
id = node.getAttribute('id')
if id?
if id2node[id]?
log "duplicated id: #{id}"
id2node[id] = node
build_id2node(child, id2node) for child in node.childNodes
return id2node
id2node = build_id2node(svg, {})
find_dep = (node, dep_node) ->
return dep_node if node.nodeName.charAt(0) == '#'
for attr in node.attributes
matches = attr.nodeValue.match(/#[^\s()]+/g)
if matches?
for match in matches
ref_id = match.substr(1)
if id2node[ref_id]?
unless dep_node[ref_id]?
dep_node[ref_id] = id2node[ref_id]
find_dep(id2node[ref_id], dep_node)
find_dep(child, dep_node) for child in node.childNodes
return dep_node
extract_svg = (id_series) ->
positive_nodes = []
negative_ids = {}
negative_prefixes = []
for id in id_series.split(/\s+/)
if id==''
continue
if id.charAt(0) == '-'
if id.charAt(id.length-1) == '*'
negative_prefixes.push(id.substr(1, id.length-2))
else
negative_ids[id.substr(1)] = yes
else
if id.charAt(id.length-1) == '*'
prefix = id.substr(0, id.length-1)
for node_id, node of id2node
if node_id.substr(0, prefix.length) == prefix
positive_nodes.push(node)
else if node = id2node[id]
positive_nodes.push(node)
if positive_nodes.length==0
positive_nodes.push svg
deps = {}
for node in positive_nodes
find_dep(node, deps)
seeds = ( node for node in positive_nodes )
for dep_id, dep_node of deps
seeds.push(dep_node)
for seed, i in seeds
ptr = seed
seeds[i] = [seed]
while ptr!=svg && ptr.parentNode?
ptr = ptr.parentNode
seeds[i].unshift(ptr)
do_clone = (node, depth, get_all) ->
unless get_all
take = no
for seed in seeds
if seed[depth]==node
if depth==seed.length-1
get_all = yes
take = yes
break
return unless take
if node.nodeType==3 || node.nodeType==4
return window.document.createTextNode(node.nodeValue)
if node.nodeType==9 || node.nodeType==11
for child in node.childNodes
cloned_child = do_clone(child, depth+1, get_all)
return cloned_child if cloned_child
if node.nodeType!=1
return
if id = node.getAttribute('id')
if negative_ids[id]
return
for neg_id in negative_prefixes
if id.substr(0, neg_id.length) == neg_id
return
cloned_node = window.document.createElementNS(node.namespaceURI, node.nodeName)
for attr in node.attributes
continue if attr.nodeName.match(/^xmlns\b/)
cloned_node.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.nodeValue)
for child in node.childNodes
cloned_child = do_clone(child, depth+1, get_all)
cloned_node.appendChild(cloned_child) if cloned_child
return cloned_node
return do_clone(svg, 0, no)
form1 =
if id_list?
no
else
id_list = ['']
true
done_one = () ->
--waiting
if waiting<=0
window.setTimeout( () ->
if form1
if imgs[0]?
cb(imgs[0]...)
else
cb(null, null, null)
else
cb(imgs)
, 0)
waiting = id_list.length
imgs =
for id in id_list
extrated_svg = extract_svg id
img_and_bbox = build_image extrated_svg
if img_and_bbox?
[img, bbox] = img_and_bbox
img.onload = done_one
[img, bbox, extrated_svg]
else
done_one()
null
svg2html_image = (svg, id_list, cb) ->
unless cb?
cb = id_list
id_list = undefined
if typeof(svg)=='string'
if svg.match(/^\s*</)
xml =
if window.DOMParser?
parser = new DOMParser
parser.parseFromString(svg, 'text/xml')
else
xml = new ActiveXObject('Microsoft.XMLDOM')
xml.async = no
xml.loadXML(svg.replace(/<!DOCTYPE svg[^>]*>/, ''))
xml
build_images(xml, id_list, cb)
else
ajax_load(svg, (req) ->
success = yes
unless req?
success = no
if success && req.status!=200
log "fetch #{svg} fail: #{req.status}"
success = no
if success && !req.responseXML
log "fetch #{svg} fail: not XML"
success = no
if success && !req.responseXML.documentElement
log "fetch #{svg} fail: no documentElement"
success = no
if success
build_images(req.responseXML.documentElement, id_list, cb)
unless success
out = ( null for x in id_list )
cb(out)
)
else
build_images(svg, id_list, cb)
if window.require? and window.define?
define([], () -> svg2html_image)
else
window.svg2html_image = svg2html_image
| true | ###
SVG To HTML Image Library v0.06
https://github.com/CindyLinz/Coffee-svg2html_img
Copyright 2012, PI:NAME:<NAME>END_PI (CindyLinz)
Dual licensed under the MIT or GPL Version 2 licenses.
Date: 2012.5.2
###
log = (msg) ->
window.console.log(msg) if window.console?
ajax_load = (url, cb) ->
req =
if window.XMLHttpRequest
new XMLHttpRequest()
else if window.ActiveXObject
try
new ActiveXObject("Msxml2.XMLHTTP")
catch e
new ActiveXObject("Microsoft.XMLHTTP")
else
log("no ajax supported")
unless req?
cb(req)
return
req.onreadystatechange = () ->
if req.readyState==4
cb(req)
req.open('GET', url)
req.send(null)
base64_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
utf8_encode = (input) ->
return input.replace(/[^\x00-\x7F]/g, ($0) ->
code = $0.charCodeAt(0)
out = ''
while code > 63
out = String.fromCharCode(code & 63 | 128) + out
code >>= 6
switch out.length
when 1
return String.fromCharCode(code | 192) + out
when 2
return String.fromCharCode(code | 224) + out
when 3
return String.fromCharCode(code | 240) + out
when 4
return String.fromCharCode(code | 248) + out
when 5
return String.fromCharCode(code | 252) + out
)
base64_encode = (input) ->
out = ''
for i in [0...input.length-2] by 3
out += base64_letter.charAt( a = input.charCodeAt(i) >> 2 )
out += base64_letter.charAt( b = ((input.charCodeAt(i)&3) << 4) | (input.charCodeAt(i+1) >> 4) )
out += base64_letter.charAt( c = ((input.charCodeAt(i+1)&15) << 2) | (input.charCodeAt(i+2) >> 6) )
out += base64_letter.charAt( d = input.charCodeAt(i+2)&63 )
switch input.length % 3
when 1
out += base64_letter.charAt( input.charCodeAt(input.length-1) >> 2 )
out += base64_letter.charAt( (input.charCodeAt(input.length-1)&3) << 4 )
out += '=='
when 2
out += base64_letter.charAt( input.charCodeAt(input.length-2) >> 2 )
out += base64_letter.charAt( ((input.charCodeAt(input.length-2)&3) << 4) | (input.charCodeAt(input.length-1) >> 4) )
out += base64_letter.charAt( (input.charCodeAt(input.length-1)&15) << 2 )
out += '='
return out
node2text = (node) ->
out = ''
build = (node) ->
unless node?
return
if node.nodeName == '#comment'
return
if node.nodeName == '#text'
out += node.data
return
if node.nodeName.charAt(0) == '#'
log "node2text: unimplemented dom node type #{node.nodeName}"
return
out += '<'
out += node.nodeName
for attr in node.attributes
out += ' '
out += attr.nodeName
out += '="'
out += attr.nodeValue.
replace(/&/g, '&').
replace(/"/g, '"')
out += '"'
if node.nodeName=='svg'
out += ' xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"'
if node.hasChildNodes()
out += '>'
build(child) for child in node.childNodes
out += '</'
out += node.nodeName
out += '>'
else
out += '/>'
build(node)
return out
build_image = (svg) ->
return unless svg?
doc = window.document
doc.getElementsByTagName('body')[0].appendChild(svg)
#log svg.getBBox()
bbox = svg.getBBox()
#alert "bbox = #{bbox.width}x#{bbox.height}+#{bbox.x}+#{bbox.y}"
svg.parentNode.removeChild(svg)
img = doc.createElement('img')
img.style.position = 'absolute'
img.style.visibility = 'hidden'
img.style.left = '-9999px'
img.style.top = '-9999px'
if svg.getAttribute('width')? && svg.getAttribute('height')?
img.style.width = svg.getAttribute('width')
img.style.height = svg.getAttribute('height')
#img.style.width = '1000px'
#img.style.height = '666px'
#log img.complete
img.src = 'data:image/svg+xml;base64,' + base64_encode utf8_encode node2text svg
#log img.complete
#alert base64_encode utf8_encode node2text svg
#img.src = 'svg_basic/chips.svg'
doc.getElementsByTagName('body')[0].appendChild(img)
return [img, bbox]
build_images = (svg, id_list, cb) ->
build_id2node = (node, id2node) ->
return id2node if node.nodeType==3 || node.nodeType==4
if node.nodeType==1
id = node.getAttribute('id')
if id?
if id2node[id]?
log "duplicated id: #{id}"
id2node[id] = node
build_id2node(child, id2node) for child in node.childNodes
return id2node
id2node = build_id2node(svg, {})
find_dep = (node, dep_node) ->
return dep_node if node.nodeName.charAt(0) == '#'
for attr in node.attributes
matches = attr.nodeValue.match(/#[^\s()]+/g)
if matches?
for match in matches
ref_id = match.substr(1)
if id2node[ref_id]?
unless dep_node[ref_id]?
dep_node[ref_id] = id2node[ref_id]
find_dep(id2node[ref_id], dep_node)
find_dep(child, dep_node) for child in node.childNodes
return dep_node
extract_svg = (id_series) ->
positive_nodes = []
negative_ids = {}
negative_prefixes = []
for id in id_series.split(/\s+/)
if id==''
continue
if id.charAt(0) == '-'
if id.charAt(id.length-1) == '*'
negative_prefixes.push(id.substr(1, id.length-2))
else
negative_ids[id.substr(1)] = yes
else
if id.charAt(id.length-1) == '*'
prefix = id.substr(0, id.length-1)
for node_id, node of id2node
if node_id.substr(0, prefix.length) == prefix
positive_nodes.push(node)
else if node = id2node[id]
positive_nodes.push(node)
if positive_nodes.length==0
positive_nodes.push svg
deps = {}
for node in positive_nodes
find_dep(node, deps)
seeds = ( node for node in positive_nodes )
for dep_id, dep_node of deps
seeds.push(dep_node)
for seed, i in seeds
ptr = seed
seeds[i] = [seed]
while ptr!=svg && ptr.parentNode?
ptr = ptr.parentNode
seeds[i].unshift(ptr)
do_clone = (node, depth, get_all) ->
unless get_all
take = no
for seed in seeds
if seed[depth]==node
if depth==seed.length-1
get_all = yes
take = yes
break
return unless take
if node.nodeType==3 || node.nodeType==4
return window.document.createTextNode(node.nodeValue)
if node.nodeType==9 || node.nodeType==11
for child in node.childNodes
cloned_child = do_clone(child, depth+1, get_all)
return cloned_child if cloned_child
if node.nodeType!=1
return
if id = node.getAttribute('id')
if negative_ids[id]
return
for neg_id in negative_prefixes
if id.substr(0, neg_id.length) == neg_id
return
cloned_node = window.document.createElementNS(node.namespaceURI, node.nodeName)
for attr in node.attributes
continue if attr.nodeName.match(/^xmlns\b/)
cloned_node.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.nodeValue)
for child in node.childNodes
cloned_child = do_clone(child, depth+1, get_all)
cloned_node.appendChild(cloned_child) if cloned_child
return cloned_node
return do_clone(svg, 0, no)
form1 =
if id_list?
no
else
id_list = ['']
true
done_one = () ->
--waiting
if waiting<=0
window.setTimeout( () ->
if form1
if imgs[0]?
cb(imgs[0]...)
else
cb(null, null, null)
else
cb(imgs)
, 0)
waiting = id_list.length
imgs =
for id in id_list
extrated_svg = extract_svg id
img_and_bbox = build_image extrated_svg
if img_and_bbox?
[img, bbox] = img_and_bbox
img.onload = done_one
[img, bbox, extrated_svg]
else
done_one()
null
svg2html_image = (svg, id_list, cb) ->
unless cb?
cb = id_list
id_list = undefined
if typeof(svg)=='string'
if svg.match(/^\s*</)
xml =
if window.DOMParser?
parser = new DOMParser
parser.parseFromString(svg, 'text/xml')
else
xml = new ActiveXObject('Microsoft.XMLDOM')
xml.async = no
xml.loadXML(svg.replace(/<!DOCTYPE svg[^>]*>/, ''))
xml
build_images(xml, id_list, cb)
else
ajax_load(svg, (req) ->
success = yes
unless req?
success = no
if success && req.status!=200
log "fetch #{svg} fail: #{req.status}"
success = no
if success && !req.responseXML
log "fetch #{svg} fail: not XML"
success = no
if success && !req.responseXML.documentElement
log "fetch #{svg} fail: no documentElement"
success = no
if success
build_images(req.responseXML.documentElement, id_list, cb)
unless success
out = ( null for x in id_list )
cb(out)
)
else
build_images(svg, id_list, cb)
if window.require? and window.define?
define([], () -> svg2html_image)
else
window.svg2html_image = svg2html_image
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero G",
"end": 27,
"score": 0.5886922478675842,
"start": 21,
"tag": "NAME",
"value": "ty Ltd"
},
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Pub... | resources/assets/coffee/react/comments-index.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { CommentsManager } from 'comments-manager'
import core from 'osu-core-singleton'
import { Main } from './comments-index/main'
reactTurbolinks.registerPersistent 'comments-index', CommentsManager, true, ->
commentBundle = osu.parseJson('json-index')
core.dataStore.updateWithCommentBundleJSON(commentBundle)
core.dataStore.uiState.initializeWithCommentBundleJSON(commentBundle)
component: Main
| 36673 | # Copyright (c) ppy P<NAME> <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { CommentsManager } from 'comments-manager'
import core from 'osu-core-singleton'
import { Main } from './comments-index/main'
reactTurbolinks.registerPersistent 'comments-index', CommentsManager, true, ->
commentBundle = osu.parseJson('json-index')
core.dataStore.updateWithCommentBundleJSON(commentBundle)
core.dataStore.uiState.initializeWithCommentBundleJSON(commentBundle)
component: Main
| true | # Copyright (c) ppy PPI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { CommentsManager } from 'comments-manager'
import core from 'osu-core-singleton'
import { Main } from './comments-index/main'
reactTurbolinks.registerPersistent 'comments-index', CommentsManager, true, ->
commentBundle = osu.parseJson('json-index')
core.dataStore.updateWithCommentBundleJSON(commentBundle)
core.dataStore.uiState.initializeWithCommentBundleJSON(commentBundle)
component: Main
|
[
{
"context": "}\n @followingItemsLookup: {}\n \n \n constructor: (@name, details, messages) ->\n @constructor.idLookup[",
"end": 158,
"score": 0.9942777752876282,
"start": 152,
"tag": "USERNAME",
"value": "(@name"
},
{
"context": "e, details, messages) ->\n @constructor.idL... | coffee/main.coffee | yoshifan/smgalaxy-routing | 0 | class Item
# A level, cutscene, or event. Basically a block of a full game run.
@idLookup: {}
@followingItemsLookup: {}
constructor: (@name, details, messages) ->
@constructor.idLookup[@name] = this
@requirements = details.requirements
@startLocation = details.start_location
@endLocation = details.end_location
for itemName in details.follows
if itemName of @constructor.followingItemsLookup
@constructor.followingItemsLookup[itemName].push(this)
else
@constructor.followingItemsLookup[itemName] = [this]
@messages = []
for message in messages
@messages.push {
id: message['id']
case: message['case'] ? null
skippable: message['skippable'] ? false
}
frames: (argSet) ->
totalFrames = 0
for message in @messages
# Don't include skippable messages in our frame count.
if message.skippable
continue
id = message.id
if typeof id isnt 'string'
# Object containing multiple cases. The only possible factor for
# message id is character.
id = id[argSet.character]
m = Message.lookup(id, argSet.langCode)
messageFrames = m.frames(argSet, message.case)
totalFrames += messageFrames
return totalFrames
showFrameDetails: (argSets) ->
# Show a message by message breakdown of frame counts for a particular
# route item.
$itemDetails = $('#item-details')
$itemDetails.empty()
# Display item name
$h3 = $('<h3>').text(@name)
$itemDetails.append $h3
# Message by message frame breakdown table
$table = $('<table>')
$tbody = $('<tbody>')
$table.append $tbody
$itemDetails.append $table
# Header row
$tr = $('<tr>')
$tr.append $('<td>').text "Message ID"
for argSet in argSets
$tr.append $('<td>').text argSet.display
$tbody.append $tr
for message in @messages
# Create a table row for the message.
$tr = $('<tr>')
$tbody.append $tr
# Display message id (or possible message ids).
$td = $('<td>')
if typeof message.id is 'string'
$td.text message.id
else
# Only other possibility is a map from character to message id.
# If the argSets have the same character, just show that character's
# message id. Otherwise, show both.
if argSets[0].character is argSets[1].character
$td.text message.id[argSets[0].character]
else
$td.append document.createTextNode message.id[argSets[0].character]
$td.append document.createElement 'br'
$td.append document.createTextNode message.id[argSets[1].character]
$td.addClass 'message-id-display'
$tr.append $td
for argSet in argSets
if typeof message.id is 'string'
messageId = message.id
else
messageId = message.id[argSet.character]
messageObj = Message.lookup(messageId, argSet.langCode)
# Display message frames.
framesText = messageObj.frames(argSet, message.case)
$td = $('<td>').text(framesText)
$tr.append $td
# When this cell is clicked, display full frame details for this
# message + argSet.
$td.addClass 'message-frames'
f = (messageObj_, argSet_, messageCase_) ->
messageObj_.showFrameDetails(argSet_, messageCase_)
$td.click(Util.curry(f, messageObj, argSet, message.case))
# Style skippable messages differently.
if message.skippable
$tr.addClass 'skippable'
class Action extends Item
# An Item that needs to be specified in a human readable route.
# It's not an automatically occurring cutscene or anything like that, it's
# something the player needs to know when to do.
# Map/dict from human-readable strings to actions they represent.
# Used when accepting a route as text.
# e.g. either "Good Egg 4" or "Good Egg C" refers to Dino Piranha Speed Run.
@aliases: {}
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-action'
@addAlias(@name)
addAlias: (alias) ->
# Add to the class variable 'aliases'.
# Map from alias to the standard name.
# Make all aliases lowercase, so we can do case insensitive recognition.
@constructor.aliases[alias.toLowerCase()] = this
@addAliases: () ->
# The Level constructor added a basic alias for every level: the level
# name itself.
# Here we add more aliases for various actions (mostly levels).
replaceLastChar = (s1, s2) -> s1.slice(0, s1.length - 1) + s2
# Make a way to filter aliases based on a boolean test.
getAliases = (boolFunc) ->
if not boolFunc?
return Action.aliases
aliasSubset = {}
for alias, action of Action.aliases
if boolFunc(alias)
aliasSubset[alias] = action
return aliasSubset
for alias, action of getAliases((a) -> a.startsWith("bowser's "))
# Can omit this part
action.addAlias alias.replace("bowser's ", "")
for alias, action of getAliases((a) -> a.startsWith("bowser jr.'s "))
# Can omit this part
action.addAlias alias.replace("bowser jr.'s ", "")
# Detect single-star galaxies - easier to do this before we've added
# more star ending possibilities.
starEndings = ['1','2','3','h','g','l','c','p']
for alias, action of getAliases((a) -> not a.endsWith(starEndings))
if action instanceof Level
# This should be a galaxy with only one star.
# Accept an alias ending in " 1".
action.addAlias (alias + " 1")
for alias, action of getAliases((a) -> a.endsWith(" c"))
# Add alias that replaces c with 4, or comet
action.addAlias replaceLastChar(alias, "4")
action.addAlias replaceLastChar(alias, "comet")
for alias, action of getAliases((a) -> a.endsWith(" p"))
action.addAlias replaceLastChar(alias, "100")
action.addAlias replaceLastChar(alias, "purples")
action.addAlias replaceLastChar(alias, "purple coins")
action.addAlias replaceLastChar(alias, "purple comet")
if alias is "gateway p"
action.addAlias replaceLastChar(alias, "2")
else
action.addAlias replaceLastChar(alias, "5")
for alias, action of getAliases()
if alias in ["good egg l", "honeyhive l", "buoy base g"]
action.addAlias replaceLastChar(alias, "h")
if alias in ["battlerock l", "dusty dune g"]
action.addAlias replaceLastChar(alias, "h2")
action.addAlias replaceLastChar(alias, "hidden 2")
action.addAlias replaceLastChar(alias, "hidden star 2")
action.addAlias replaceLastChar(alias, "s2")
action.addAlias replaceLastChar(alias, "secret 2")
action.addAlias replaceLastChar(alias, "secret star 2")
action.addAlias replaceLastChar(alias, "7")
if alias is "battlerock l"
action.addAlias replaceLastChar(alias, "g")
for alias, action of getAliases((a) -> a.endsWith(" h"))
action.addAlias replaceLastChar(alias, "hidden")
action.addAlias replaceLastChar(alias, "hidden star")
action.addAlias replaceLastChar(alias, "s")
action.addAlias replaceLastChar(alias, "secret")
action.addAlias replaceLastChar(alias, "secret star")
if alias is "buoy base h"
action.addAlias replaceLastChar(alias, "2")
else
action.addAlias replaceLastChar(alias, "6")
for alias, action of getAliases((a) -> a.endsWith(" l"))
action.addAlias replaceLastChar(alias, "luigi")
action.addAlias replaceLastChar(alias, "luigi star")
for alias, action of getAliases((a) -> a.endsWith(" g"))
action.addAlias replaceLastChar(alias, "green")
action.addAlias replaceLastChar(alias, "green star")
text: () ->
return "> " + @name
class Level extends Action
# An action that yields a star.
@starNameLookup: {}
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-level'
@starNameId = details.star_name
if @name.endsWith(" C")
@nameCellClass = 'name-level-comet'
if @name.endsWith(" P") and @name isnt "Gateway P"
@nameCellClass = 'name-level-comet'
# Add to starNameLookup.
# Note: This requires usenglish messages to be initialized
# before levels are initialized.
# We could accept star names in other languages besides usenglish, but
# this would only make sense if galaxy names, event names, etc. were
# also accepted in multiple languages...
starName = @starName('usenglish', 'mario')
@constructor.starNameLookup[starName.toLowerCase()] = this
starName = @starName('usenglish', 'luigi')
@constructor.starNameLookup[starName.toLowerCase()] = this
starName: (langCode, character) ->
argSet = {character: character, langCode: langCode}
# Assume a star name message only has 1 box.
box = Message.lookup(@starNameId, langCode).computeBoxes(argSet, null)[0]
return box.text
text: (starCount, character) ->
if not starCount
# Duplicate star (e.g. Bowser's Galaxy Reactor)
return "#{@name} - #{@starName('usenglish', character)}"
return "#{starCount.toString()}. #{@name} - #{@starName('usenglish', character)}"
class Event extends Item
# An Item that doesn't need to be specified in a human readable route.
# For example, an automatically occurring cutscene.
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-event'
text: () ->
return "* #{@name} "
class MessageUtil
@hideMessageDetails: () ->
$('#message-details').hide()
$('#route-table-container').show()
@decodeUTF16BigEndian: (byteArray) ->
# Idea from http://stackoverflow.com/a/14601808
numCodePoints = byteArray.length / 2
codePoints = []
for i in [0..(numCodePoints - 1)]
codePoints.push(
byteArray[i*2]
+ byteArray[i*2 + 1] << 8
)
return String.fromCharCode.apply(String, codePoints)
@bytesStartWith: (bytes, arr2) ->
# bytes is an array of integers. Return true if bytes
# starts with a sub-array equal to arr2.
# Get a byte array from the beginning of bytes, max
# length equal to arr2's length
arr1 = bytes.slice(0, arr2.length)
# See if arr1 and arr2 are equal
if arr1.length isnt arr2.length
return false
return arr1.every((element, index) ->
return element is arr2[index]
)
@processEscapeSequence: (
escapeBytes, boxes, messageId, argSet, messageCase,
displayColors=false, displayFurigana=false) ->
# Add the escape sequence contents to the boxes structure.
escapeBytesStartWith = Util.curry(@bytesStartWith, escapeBytes)
lastBox = boxes[boxes.length-1]
if escapeBytesStartWith [1,0,0,0]
# Text pause - length is either 10, 15, 30, or 60.
pauseLength = escapeBytes[4]
text = "<Text pause, #{pauseLength.toString()}L>"
if 'pauseLength' of lastBox
lastBox.pauseLength += pauseLength
else
lastBox.pauseLength = pauseLength
else if escapeBytesStartWith [1,0,1]
# Message box break.
text = ""
boxes.push({chars: 0, text: ""})
else if escapeBytesStartWith [1,0,2]
text = '<Lower-baseline text>'
else if escapeBytesStartWith [1,0,3]
text = '<Center align>'
else if escapeBytesStartWith [2,0,0,0,0x53]
text = '<Play voice audio>'
else if escapeBytesStartWith [3,0]
# Icon.
iconByte = escapeBytes[2]
iconName = messageLookup.icons[iconByte]
text = "<#{iconName} icon>"
# Any icon counts as one character.
lastBox.chars += 1
else if escapeBytesStartWith [4,0,0]
text = '<Small text>'
else if escapeBytesStartWith [4,0,2]
text = '<Large text>'
else if escapeBytesStartWith [5,0,0,0,0]
# Mario's name or Luigi's name.
if messageCase is 'general'
# TODO: Use this case
text = '<Player name>'
else
if argSet.character is 'mario'
textMessageId = 'System_PlayerName000'
else if argSet.character is 'luigi'
textMessageId = 'System_PlayerName100'
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else if escapeBytesStartWith [5,0,0,1,0]
# Mario's name or Luigi's name, drawn out excitedly.
if messageCase is 'general'
# TODO: Use this case
text = '<Mr. Plaaayer naaame>'
else
if argSet.character is 'mario'
textMessageId = 'System_PlayerName001'
else if argSet.character is 'luigi'
textMessageId = 'System_PlayerName101'
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else if (escapeBytesStartWith [6]) or (escapeBytesStartWith [7])
# A number or name variable.
# The actual text is message dependent, or even case dependent beyond
# that (e.g. which level a Hungry Luma is in). But we have defined the
# text for the cases that we care about.
if messageId of messageLookup.numbersNames
obj = messageLookup.numbersNames[messageId]
numberNameType = obj._type
if messageCase is 'general'
# TODO: Use this case
text = obj._placeholder
else if numberNameType is 'text'
if messageCase of obj
text = obj[messageCase]
else if argSet.character of obj
text = obj[argSet.character]
lastBox.chars += text.length
else if numberNameType is 'message'
if messageCase of obj
textMessageId = obj[messageCase]
else if argSet.character of obj
textMessageId = obj[argSet.character]
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else
console.log(
"Don't know how to handle number/name variable"
+ "for message: #{messageId}"
)
# TODO: Indicate an error somehow?
else if escapeBytesStartWith [9,0,5]
# Race time (Spooky Sprint, etc.)
text = 'xx:xx:xx'
lastBox.chars += text.length
else if escapeBytesStartWith [0xFF,0,0]
# Signify start or end of text color.
colorByte = escapeBytes[3]
colorType = messageLookup.colors[colorByte]
if displayColors
text = "<#{colorType} color>"
else
text = ""
else if escapeBytesStartWith [0xFF,0,2]
# Japanese furigana (kanji reading help).
kanjiCount = escapeBytes[3]
furiganaBytes = escapeBytes.slice(4)
furiganaStr = @decodeUTF16BigEndian(furiganaBytes)
if displayFurigana
text = "<#{furiganaStr}>"
else
text = ""
else
console.log("Unknown escape sequence: #{escapeBytes}")
# TODO: Indicate an error somehow?
lastBox.text += text
@boxTextDisplayHTML: ($el, box) ->
# Append a display of a box's text to the jQuery element $el.
boxTextLines = box.text.split('\n')
for line, index in boxTextLines
notLastLine = index < boxTextLines.length - 1
# Since the webpage display sometimes has extra linebreaks,
# make it clear where the actual message linebreaks are
if notLastLine
line += '↵'
# Add box text
$el.append document.createTextNode(line)
if notLastLine
# Put a br between text lines
$el.append $('<br>')
# TODO: Make a version of this function (or different argument?) for
# box text display for CSV.
@computeBoxLength: (box, langCode, $el=null) ->
# Compute the length of the box and store the result in box.length.
#
# If a jQuery element $el is given, append an explanation of the
# box length computation to that element.
charAlphaReq = messageLookup.languageSpeeds[langCode].alphaReq
fadeRate = messageLookup.languageSpeeds[langCode].fadeRate
$ul = $('<ul>')
if $el?
$el.append $ul
alphaReq = (box.chars * charAlphaReq) + 1
line = "(#{box.chars} chars * #{charAlphaReq} alpha req per char)
+ 1 extra alpha req = "
result = "#{alphaReq.toFixed(1)} alpha req"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
length = Math.floor(alphaReq / fadeRate)
line = "floor(... / #{fadeRate} fade rate) = "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Confine to float32 precision to see what the game actually computes
f32 = Math.fround
alphaReqF32 = f32(f32(box.chars) * f32(charAlphaReq)) + f32(1)
lengthF32 = Math.floor(f32(f32(alphaReqF32) / f32(fadeRate)))
if length isnt lengthF32
length = lengthF32
line = "Due to 32-bit float imprecision, it's actually "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if 'pauseLength' of box
# Add pause length if applicable.
length += box.pauseLength
line = "... + #{box.pauseLength} pause length = "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Set the computed length in the box object.
box.length = length
# Whatever the final result element was, style it as the final result.
$finalResult = $li.find('span.mid-result')
$finalResult.removeClass('mid-result').addClass('final-result')
@messageFrames: (boxes, messageId, boxEndTimingError, $el=null) ->
boxLengths = (b.length for b in boxes)
# Append a message frames explanation to the jQuery element $el.
$ul = $('<ul>')
if $el?
$el.append $ul
if messageId in messageLookup.forcedSlow
line = "Forced slow text, so 1 frame per length unit"
$ul.append $('<li>').text(line)
frames = 0
for boxLength, index in boxLengths
if index > 0
line = "... + "
else
line = ""
frames += boxLength + 2
line += "(#{boxLength} box length / 1) + 2 box end delay frames = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
else
line = "When holding A, 1 frame per 3 length units"
$ul.append $('<li>').text(line)
if boxLengths.length > 1
line = "When pressing A to end a box, the next box starts with up to
10 frames of slow text because A was re-pressed"
$ul.append $('<li>').text(line)
frames = 0
for boxLength, index in boxLengths
if index == 0
# First box
frames += Math.ceil(boxLength / 3)
line = "ceiling(#{boxLength} box length / 3) "
else
# Second box or later
line = "... "
if boxLength <= 10
# Box is within 10 length
frames += boxLength
line += "+ (#{boxLength} length / 1) "
else
# Longer length
frames += 10 + Math.ceil((boxLength-10) / 3)
line += "+ (10 length / 1) "
line += "+ ceiling((#{boxLength} length - 10) / 3) "
frames += 2
if index == 0
line += "+ 2 box-end delay frames = "
else
line += "+ 2 delay frames = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if boxEndTimingError > 0
# We've specified an average box end timing error of more than 0 frames.
numBoxes = boxLengths.length
frames += (numBoxes * boxEndTimingError)
line = "... + (#{numBoxes} box endings
* #{boxEndTimingError} frames of human timing error) = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if messageId of messageLookup.animationTimes
# There's a cutscene with animations that have to play out entirely before
# advancing, even if the message is done.
animationTime = messageLookup.animationTimes[messageId]
frames = Math.max(frames, animationTime)
line = "max(..., #{animationTime} cutscene animation frames) = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Whatever the final result was, style it as the final result.
$finalResult = $li.find('span.mid-result')
$finalResult.removeClass('mid-result').addClass('final-result')
# Return the computed frame count.
return frames
class Message
@lookupStructure: {}
constructor: (@id, @langCode, @data) ->
# Index into the look up as [idGoesHere/langCodeGoesHere].
# Assumes there are no slashes in message ids or language codes.
@constructor.lookupStructure["#{@id}/#{@langCode}"] = this
@lookup: (id, langCode) ->
return @lookupStructure["#{id}/#{langCode}"]
computeBoxes: (argSet, messageCase) ->
# TODO: Handle @data == null
# TODO: Handle @data == []
boxes = [{chars: 0, text: ""}]
for item in @data
# An item could be a box break which changes the last box, so
# re-set this after every item.
lastBox = boxes[boxes.length-1]
if typeof(item) is "string"
# Text.
# A message box break seems to always be followed by a
# newline character, but in this situation the newline
# doesn't affect the time the box text takes to scroll.
# So we won't count such a newline as a character for our
# purposes.
#
# Box break check: the latest box's text is empty.
# Action: Chop off the leading newline.
newlineAfterBoxBreak = \
item.charAt(0) is '\n' and lastBox.text is ""
if newlineAfterBoxBreak
item = item.slice(1)
lastBox.chars += item.length
lastBox.text += item
else
# Escape sequence.
# This function will add the escape sequence contents
# to the boxes structure.
MessageUtil.processEscapeSequence(
item, boxes, @id, argSet, messageCase
)
# At this point we've got text and chars covered, and pauseLength
# if applicable. Compute the box lengths.
for box in boxes
MessageUtil.computeBoxLength(box, argSet.langCode)
return boxes
frames: (argSet, messageCase) ->
boxes = @computeBoxes(argSet, messageCase)
frames = MessageUtil.messageFrames(boxes, @id, argSet.boxEndTimingError)
return frames
showFrameDetails: (argSet, messageCase) ->
$messageDetails = $('#message-details')
$messageDetails.empty()
# Display a Back button to make the route table viewable again
$backButton = $('<button>')
$backButton.text "Back"
$backButton.click MessageUtil.hideMessageDetails
$messageDetails.append $backButton
# Display the message id and argSet
$h3 = $('<h3>').text("#{@id}, #{argSet.display}")
$messageDetails.append $h3
# Make a box length explanations table
$table = $('<table>')
$tbody = $('<tbody>')
$table.append $tbody
$('#route-table-container').hide()
$messageDetails.show()
boxes = @computeBoxes(argSet, messageCase)
# Display box level frame details
for box in boxes
$tr = $('<tr>')
$tbody.append $tr
# Box text
$td = $('<td>')
$td.addClass 'box-text'
MessageUtil.boxTextDisplayHTML($td, box)
$tr.append $td
# Box length explanation
$td = $('<td>')
$td.addClass 'box-length-explanation'
MessageUtil.computeBoxLength(box, argSet.langCode, $td)
$tr.append $td
# Display message level frame details
MessageUtil.messageFrames(
boxes, @id, argSet.boxEndTimingError, $messageDetails
)
# Append box length explanations
$messageDetails.append $table
class Route
@numAndLevelRegex = /// ^
\d+ # Number
[\.|\)] # . or )
(.+) # 1 or more chars of anything
$ ///
@actionAndParensNoteRegex = /// ^
(.+) # 1 or more chars of anything
\( # Left parens
.+ # 1 or more chars of anything
\) # Right parens
$ ///
# 70 stars, 1 star, etc.
@starsReqRegex = /^(\d+) stars?$/
# Less than 70 stars, Less than 1 star, etc.
@lessThanStarsReqRegex = /^Less than (\d+) stars?$/
# 400 star bits, etc.
@starBitReqRegex = /^(\d+) star bits$/
isComplete: false
constructor: (text, category) ->
@actions = []
# Split text into lines
lines = Util.splitlines(text)
# First line = route name
@name = lines[0]
lines = lines[1..]
$('#route-status').empty()
for line in lines
line = line.trim()
if line is ""
# Blank line
continue
action = @lineToAction(line)
if not action
@addRouteStatus("Could not recognize as a level/action: " + line)
break
else if action is 'comment'
# Just a comment line in the text route; ignore it.
continue
@actions.push(action)
if category is "Any%"
@endItemName = "Bowser's Galaxy Reactor"
@endRequirements = []
else if category is "120 Star"
@endItemName = "Bowser's Galaxy Reactor"
@endRequirements = ["120 stars"]
addRouteStatus: (s) ->
$('#route-status').append(document.createTextNode(s))
$('#route-status').append(document.createElement('br'))
lineToAction: (line) ->
# Make item recognition non-case-sensitive
line = line.toLowerCase()
if line.startsWith '*'
# Assumed to be just a comment, e.g. "* Back to start of observatory"
return 'comment'
if line.startsWith '>'
# Assumed to be an action with an exact name, e.g. "> Luigi letter 2".
line = line.slice(1).trim()
# Check if line begins with a star number like "5." or "17)"
# If so, remove it
match = @constructor.numAndLevelRegex.exec(line)
if match
line = match[1].trim()
# Check if we have an alias match
if line of Action.aliases
return Action.aliases[line]
# Check if line ends with a parenthesized thing like "(skip cutscenes)"
# If so, remove it
match = @constructor.actionAndParensNoteRegex.exec(line)
if match
line = match[1].trim()
# Check again if we have an alias match
if line of Action.aliases
return Action.aliases[line]
# Check for just the star name
if line of Level.starNameLookup
return Level.starNameLookup[line]
# Check if there's a dash, and if so, see if we can find a
# galaxy+number - starname match like "Good Egg 1 - Dino Piranha".
# Either one will do, don't need both correct.
# (e.g. "Good Egg - Dino Piranha" should work fine too.)
# Try all the dashes if there's more than one.
indexOfDash = line.indexOf('-')
while indexOfDash isnt -1
possibleGalaxyAndNum = line.slice(0, indexOfDash).trim()
if possibleGalaxyAndNum of Action.aliases
return Action.aliases[possibleGalaxyAndNum]
possibleStarName = line.slice(indexOfDash+1).trim()
if possibleStarName of Level.starNameLookup
return Level.starNameLookup[possibleStarName]
indexOfDash = line.indexOf('-', indexOfDash+1)
# Tried everything we could think of
return null
fulfilledRequirement: (req, completedItemNames, starCount) ->
# Way 1 to satisfy requirement: req matches name of a completed action
if req in completedItemNames
return true
# Way 2: it's a >= stars req and we've got it
match = @constructor.starsReqRegex.exec(req)
if match
reqStars = Number(match[1].trim())
if starCount >= reqStars
return true
# Way 3: it's a < stars req and we've got it
match = @constructor.lessThanStarsReqRegex.exec(req)
if match
reqLessThanStars = Number(match[1].trim())
if starCount < reqLessThanStars
return true
# Way 4: it's a star bits req
# TODO: Actually check this. For now we have no way of checking possible
# or probable star bit count, so we skip the check.
match = @constructor.starBitReqRegex.exec(req)
if match
return true
return false
isEndOfRoute: (item, completedItemNames, starCount) ->
# If the run only ends on a particular route item, check for that
# route item
if @endItemName
if item.name isnt @endItemName
return false
# Check that other end requirements are met
for req in @endRequirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
return false
return true
checkAndAddEvents: () ->
# Add between-level events to the route.
@isComplete = false
@items = []
starCount = 0
greenStarCount = 0
expectedActionName = null
completedItemNames = []
# luigiStars goes up to 3: Good Egg L, Battlerock L, Honeyhive L
luigiStatus = {talkedAtGarage: false, luigiStars: 0, betweenStars: 0}
for action in @actions
# Check if we are expecting a specific action here at this point in
# the route.
if expectedActionName
if action.name isnt expectedActionName
s = "At this point the route must have: '" \
+ expectedActionName + "' but instead it has: '" \
+ action.name + "'"
@addRouteStatus(s)
expectedActionName = null
# Check requirements for this item.
for req in action.requirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
s = "'" + action.name + "' has an unfulfilled requirement: " + req
@addRouteStatus(s)
return
# Check special requirements for Luigi events.
if action.name is "Luigi letter 2"
if not (luigiStatus.luigiStars is 1 and luigiStatus.betweenStars >= 5)
s = "'" + action.name \
+ "' has an unfulfilled requirement: Must have 1 Luigi star and
5 in-between stars since that Luigi star. Current status: " \
+ luigiStatus.luigiStars.toString() + " Luigi star(s) and " \
+ luigiStatus.betweenStars.toString() + " in-between star(s)."
@addRouteStatus(s)
return
else if action.name is "Luigi letter 3"
if not (luigiStatus.luigiStars is 2 and luigiStatus.betweenStars >= 5)
s = "'" + action.name \
+ "' has an unfulfilled requirement: Must have 2 Luigi stars and
5 in-between stars since that Luigi star. Current status: " \
+ luigiStatus.luigiStars.toString() + " Luigi star(s) and " \
+ luigiStatus.betweenStars.toString() + " in-between star(s)."
@addRouteStatus(s)
return
# Add the action to the route.
followingItems = []
if action instanceof Level
if action.name in completedItemNames
# Duplicate star
@items.push {
item: action
starCount: null
}
else
starCount += 1
@items.push {
item: action
starCount: starCount
}
# Check for "x star(s)" triggers
if starCount is 1
starCountStr = "1 star"
else
starCountStr = "#{starCount} stars"
if starCountStr of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[starCountStr]...)
else
@items.push {
item: action
}
completedItemNames.push action.name
if @isEndOfRoute(action, completedItemNames, starCount)
@isComplete = true
return
# Update Green Star count if applicable
if action.name in ["Battlerock L", "Buoy Base G", "Dusty Dune G"]
greenStarCount += 1
# Check for "x green star(s)" triggers
if greenStarCount is 1
starCountStr = "1 green star"
else
starCountStr = "#{greenStarCount} green stars"
if starCountStr of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[starCountStr]...)
# Update Luigi status if applicable
if action.name is "Talk to Luigi at Garage"
luigiStatus.talkedAtGarage = true
else if luigiStatus.talkedAtGarage and action instanceof Level
if action.name in ["Good Egg L", "Battlerock L", "Honeyhive L"]
luigiStatus.luigiStars += 1
luigiStatus.betweenStars = 0
else
luigiStatus.betweenStars += 1
# Check for Luigi letter 1 event
if luigiStatus.luigiStars is 0 and luigiStatus.betweenStars is 1
followingItems.push(Item.idLookup["Luigi letter 1"])
# Items triggered by this action specifically
if action.name of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[action.name]...)
while followingItems.length > 0
followingItem = followingItems.shift()
if followingItem instanceof Action
# By some special case, this following "event" is also considered
# an action of some sort. We'll go to the next iteration to process
# this action, and we'll make a note to check that this action is
# indeed the next item in the route.
expectedActionName = followingItem.name
continue
# Ensure all of this item's trigger requirements are met before
# adding the item. If the requirements aren't met, the item is not
# triggered.
reqFailed = false
for req in followingItem.requirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
reqFailed = true
if reqFailed
continue
# Add the item to the route.
@items.push {
item: followingItem
}
completedItemNames.push followingItem.name
if @isEndOfRoute(followingItem, completedItemNames, starCount)
return
# Check if other items are triggered by this item
if followingItem.name of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[followingItem.name]...)
makeTable: (argSets) ->
$tableContainer = $('#route-table-container')
$table = $('<table>')
$tableContainer.empty().append($table)
$thead = $('<thead>')
$tbody = $('<tbody>')
$table.append $thead
$table.append $tbody
$row = $('<tr>')
$thead.append $row
$row.append $('<th>').text(@name)
for argSet in argSets
$row.append $('<th>').text(argSet.display)
# Determine whether to use Mario or Luigi in star names by seeing if
# Mario or Luigi has more argSets. (If tied, it goes to Mario.)
characterCounts = {mario: 0, luigi: 0}
argSetCharacters = (argSet.character for argSet in argSets)
for character in argSetCharacters
characterCounts[character] += 1
if characterCounts['mario'] >= characterCounts['luigi']
preferredCharacter = 'mario'
else
preferredCharacter = 'luigi'
# Add route items to the table as rows.
textFrameTotals = (0 for argSet in argSets)
for itemObj in @items
item = itemObj.item
if itemObj.starCount
itemText = item.text(itemObj.starCount, preferredCharacter)
else
itemText = item.text()
$row = $('<tr>')
$tbody.append $row
$row.addClass 'route-item'
# Click on a route item row -> show a frames breakdown.
#
# Currying a class function directly doesn't work,
# so we use an intermediate function.
f = (item_, argSets_) -> item_.showFrameDetails(argSets_)
$row.click(Util.curry(f, item, argSets))
# Item name cell
$cell = $('<td>')
$cell.text itemText
$cell.addClass item.nameCellClass
$row.append $cell
for argSet, index in argSets
frames = item.frames argSet
# Frame count cell for each argSet
$cell = $('<td>')
$cell.text frames
$row.append $cell
textFrameTotals[index] += frames
if not @isComplete
# If the route isn't complete, don't do any totals.
return
# Add frame-totals row.
$totalsRow = $('<tr>')
$tbody.append $totalsRow
$cell = $('<td>').text "Total of relative text times"
$totalsRow.append $cell
for total in textFrameTotals
$cell = $('<td>').text total
$totalsRow.append $cell
# Add differences column(s) and summary sentence
# if there are exactly two argSets.
if argSets.length is 2
# Header cells
$headerRow = $thead.find('tr')
$cell = $('<th>').text("Diff (f)")
$headerRow.append $cell
$cell = $('<th>').text("Diff (s)")
$headerRow.append $cell
# Data cells
$rows = $tbody.find('tr')
$rows.each( (_, row) =>
cellTexts = ($(cell).text() for cell in $(row).find('td'))
frameDiff = Number(cellTexts[1]) - Number(cellTexts[2])
# Frames difference
$cell = $('<td>').text frameDiff
$(row).append $cell
# Seconds difference
$cell = $('<td>').text (frameDiff/(60/1.001)).toFixed(2)
$(row).append $cell
)
# Summary sentence
secondsDiff = $totalsRow.find('td')[4].textContent
if secondsDiff.charAt(0) is '-'
# Negative diff
summary = "#{argSets[0].display} is #{secondsDiff.slice(1)} seconds
faster than #{argSets[1].display} for this route"
else
# Positive diff
summary = "#{argSets[1].display} is #{secondsDiff} seconds
faster than #{argSets[0].display} for this route"
$('#route-status').append $('<h3>').text summary
determineArgSets = (languageLookup) ->
# Build sets of text-frame-counting params/arguments from the fields
argSets = []
for set in ['set1', 'set2']
argSet = {}
for fieldName in ['langCode', 'character', 'boxEndTimingError']
$field = $("##{set}-#{fieldName}")
argSet[fieldName] = $field.val()
argSet.boxEndTimingError = Number(argSet.boxEndTimingError)
argSets.push argSet
# Figure out suitable display names based on the argSets' differences
if argSets[0].langCode isnt argSets[1].langCode
lang1 = languageLookup[argSets[0].langCode]
lang2 = languageLookup[argSets[1].langCode]
if lang1.region isnt lang2.region
# Language / region
argSets[0].display = lang1.region
argSets[1].display = lang2.region
else
# Language / language name
argSets[0].display = lang1.language
argSets[1].display = lang2.language
else if argSets[0].character isnt argSets[1].character
# Character
char = argSets[0].character
argSets[0].display = char.slice(0,1).toUpperCase() + char.slice(1)
char = argSets[1].character
argSets[1].display = char.slice(0,1).toUpperCase() + char.slice(1)
else
# Box end timing error
argSets[0].display = argSets[0].boxEndTimingError.toString() + " BTE"
argSets[1].display = argSets[1].boxEndTimingError.toString() + " BTE"
return argSets
addLanguages = (langCodes, callbackAfterInitAllLanguages) ->
# If all requested languages are already loaded, call the passed callback
# and we're done
allLanguagesLoaded = langCodes.every(
(code) -> return (window.messages? and code of window.messages)
)
if allLanguagesLoaded
do callbackAfterInitAllLanguages
return
# Else, we must load at least 1 language first
for langCode in langCodes
# If we've already loaded this language, move onto the next one
if window.messages? and langCode of window.messages
continue
# Callback that runs when this language is loaded
cb = (langCode_, langCodes_, callbackAfterInitAllLanguages_) ->
# Initialize messages for this language
for own messageId, data of window.messages[langCode_]
new Message(messageId, langCode_, data)
# Check if ALL requested languages are loaded (not just this one)
allLanguagesLoaded = langCodes_.every(
(code) -> return (code of window.messages)
)
if allLanguagesLoaded
# Call the passed callback
do callbackAfterInitAllLanguages_
# Load this language
callbackAfterLoadingLanguage = Util.curry(
cb, langCode, langCodes, callbackAfterInitAllLanguages
)
Util.readServerJSFile(
"js/messages/#{langCode}.js", callbackAfterLoadingLanguage
)
class Main
routeTextChanged: false
init: (itemDetails, itemMessages) ->
callback = Util.curry(@init2, itemDetails, itemMessages)
addLanguages(['usenglish'], callback)
init2: (itemDetails, itemMessages) ->
# Initialize possible route items.
for own itemKey, details of itemDetails
args = [itemKey, details, itemMessages[itemKey] ? []]
if details.type is 'Level'
new Level(args...)
else if details.type is 'Action'
new Action(args...)
else if details.type is 'Event'
new Event(args...)
else
console.log(
"Invalid item type: " + details.type
)
# Add text aliases for possible route items.
Action.addAliases()
# Get info on the available languages.
languages = []
languageLookup = {}
for own langCode, _ of messageLookup.languageSpeeds
# The first 2 chars should be the region, rest should be language.
obj = {
code: langCode
region: langCode.slice(0,2).toUpperCase()
language: langCode.slice(2,3).toUpperCase() + langCode.slice(3)
}
obj.display = "#{obj.language} (#{obj.region})"
languages.push obj
languageLookup[langCode] = obj
# The languages array will serve as a way to sort the languages.
sortFunc = (a,b) ->
if a.display < b.display
return -1
else if a.display > b.display
return 1
else
return 0
languages.sort(sortFunc)
# Initialize the language dropdowns
for set in ['set1', 'set2']
$select = $("##{set}-langCode")
# Fill with the ordered languages.
for lang in languages
$select.append(
$('<option>').attr('value', lang.code).text(lang.display)
)
# Initialize with US English for the first, JP Japanese for the second.
if set is 'set1'
$select.val('usenglish')
else
$select.val('jpjapanese')
# Initialize the boxEndTimingError dropdowns
for set in ['set1', 'set2']
$select = $("##{set}-boxEndTimingError")
for num in [0..15]
value = num.toString()
text = num.toString()
if text is "0"
text = "0 (TAS)"
$select.append $('<option>').attr('value', value).text(text)
# Initialize the value.
$select.val("10")
# Initialize the route processing button
document.getElementById('route-button').onclick = (event) =>
$('#route-status').empty()
routeText = document.getElementById('route-textarea').value
category = $('#route-category').val()
route = new Route(routeText, category)
route.checkAndAddEvents()
if not route.isComplete
route.addRouteStatus("Route is incomplete!")
argSets = determineArgSets(languageLookup)
# Get the required languages, then make the route table
callback = () -> route.makeTable argSets
addLanguages((argSet.langCode for argSet in argSets), callback)
# Initialize help button(s)
$('.help-button').each( () ->
buttonIdRegex = /^(.+)-button$/
result = buttonIdRegex.exec(this.id)
helpTextId = result[1]
# When this help button is clicked, open the corresponding
# help text in a modal window.
clickCallback = (helpTextId_, helpButtonE) ->
$helpText = $('#'+helpTextId_)
$helpText.dialog({
modal: true
width: 500
height: 600
position: {
my: "center top"
at: "center bottom"
of: helpButtonE
}
})
# NOTE: The below only applies to the route textarea help, so if
# there's another help button at some point, then this code needs
# to be moved somewhere else.
# Part of the help text involves listing all the non-level actions.
# The first time this help text is opened, fill the list.
$actionList = $('#action-list')
if $actionList.is(':empty')
for id, item of Item.idLookup
# Ensure we're listing non-level actions.
if (item instanceof Action) and not (item instanceof Level)
$actionList.append(
$('<li>').append $('<code>').text('> '+item.name)
)
# Make the dialog's scroll position start at the top. If we don't do
# this, then it starts where the in-dialog button is, for some reason.
$helpText.scrollTop(0)
$(this).click(
Util.curry(clickCallback, helpTextId, this)
)
)
# Initialize fill-with-sample-route buttons
applySampleRoute = (categoryValue, sampleRouteFilename) =>
if @routeTextChanged
message = "This'll overwrite the current route with the" \
+ " Sample " + categoryValue + " route. Are you sure?"
# If user chooses yes, proceed; if chooses no, return
if not confirm(message)
return
# Reset the "route changed" state
@routeTextChanged = false
$('#route-category').val(categoryValue)
callback = (text) ->
document.getElementById('route-textarea').value = text
Util.readServerTextFile(sampleRouteFilename, callback)
$('#sample-any-route-button').click(
Util.curry(applySampleRoute, "Any%", "samplerouteany.txt")
)
$('#sample-120-route-button').click(
Util.curry(applySampleRoute, "120 Star", "sampleroute120.txt")
)
# Watch for route text changes via typing.
# (Precisely: The textarea lost focus and its value changed
# since gaining focus.)
$('#route-textarea').change( () =>
@routeTextChanged = true
)
window.main = new Main | 210742 | class Item
# A level, cutscene, or event. Basically a block of a full game run.
@idLookup: {}
@followingItemsLookup: {}
constructor: (@name, details, messages) ->
@constructor.idLookup[@name] = this
@requirements = details.requirements
@startLocation = details.start_location
@endLocation = details.end_location
for itemName in details.follows
if itemName of @constructor.followingItemsLookup
@constructor.followingItemsLookup[itemName].push(this)
else
@constructor.followingItemsLookup[itemName] = [this]
@messages = []
for message in messages
@messages.push {
id: message['id']
case: message['case'] ? null
skippable: message['skippable'] ? false
}
frames: (argSet) ->
totalFrames = 0
for message in @messages
# Don't include skippable messages in our frame count.
if message.skippable
continue
id = message.id
if typeof id isnt 'string'
# Object containing multiple cases. The only possible factor for
# message id is character.
id = id[argSet.character]
m = Message.lookup(id, argSet.langCode)
messageFrames = m.frames(argSet, message.case)
totalFrames += messageFrames
return totalFrames
showFrameDetails: (argSets) ->
# Show a message by message breakdown of frame counts for a particular
# route item.
$itemDetails = $('#item-details')
$itemDetails.empty()
# Display item name
$h3 = $('<h3>').text(@name)
$itemDetails.append $h3
# Message by message frame breakdown table
$table = $('<table>')
$tbody = $('<tbody>')
$table.append $tbody
$itemDetails.append $table
# Header row
$tr = $('<tr>')
$tr.append $('<td>').text "Message ID"
for argSet in argSets
$tr.append $('<td>').text argSet.display
$tbody.append $tr
for message in @messages
# Create a table row for the message.
$tr = $('<tr>')
$tbody.append $tr
# Display message id (or possible message ids).
$td = $('<td>')
if typeof message.id is 'string'
$td.text message.id
else
# Only other possibility is a map from character to message id.
# If the argSets have the same character, just show that character's
# message id. Otherwise, show both.
if argSets[0].character is argSets[1].character
$td.text message.id[argSets[0].character]
else
$td.append document.createTextNode message.id[argSets[0].character]
$td.append document.createElement 'br'
$td.append document.createTextNode message.id[argSets[1].character]
$td.addClass 'message-id-display'
$tr.append $td
for argSet in argSets
if typeof message.id is 'string'
messageId = message.id
else
messageId = message.id[argSet.character]
messageObj = Message.lookup(messageId, argSet.langCode)
# Display message frames.
framesText = messageObj.frames(argSet, message.case)
$td = $('<td>').text(framesText)
$tr.append $td
# When this cell is clicked, display full frame details for this
# message + argSet.
$td.addClass 'message-frames'
f = (messageObj_, argSet_, messageCase_) ->
messageObj_.showFrameDetails(argSet_, messageCase_)
$td.click(Util.curry(f, messageObj, argSet, message.case))
# Style skippable messages differently.
if message.skippable
$tr.addClass 'skippable'
class Action extends Item
# An Item that needs to be specified in a human readable route.
# It's not an automatically occurring cutscene or anything like that, it's
# something the player needs to know when to do.
# Map/dict from human-readable strings to actions they represent.
# Used when accepting a route as text.
# e.g. either "Good Egg 4" or "Good Egg C" refers to Dino Piranha Speed Run.
@aliases: {}
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-action'
@addAlias(@name)
addAlias: (alias) ->
# Add to the class variable 'aliases'.
# Map from alias to the standard name.
# Make all aliases lowercase, so we can do case insensitive recognition.
@constructor.aliases[alias.toLowerCase()] = this
@addAliases: () ->
# The Level constructor added a basic alias for every level: the level
# name itself.
# Here we add more aliases for various actions (mostly levels).
replaceLastChar = (s1, s2) -> s1.slice(0, s1.length - 1) + s2
# Make a way to filter aliases based on a boolean test.
getAliases = (boolFunc) ->
if not boolFunc?
return Action.aliases
aliasSubset = {}
for alias, action of Action.aliases
if boolFunc(alias)
aliasSubset[alias] = action
return aliasSubset
for alias, action of getAliases((a) -> a.startsWith("bowser's "))
# Can omit this part
action.addAlias alias.replace("bowser's ", "")
for alias, action of getAliases((a) -> a.startsWith("bowser jr.'s "))
# Can omit this part
action.addAlias alias.replace("bowser jr.'s ", "")
# Detect single-star galaxies - easier to do this before we've added
# more star ending possibilities.
starEndings = ['1','2','3','h','g','l','c','p']
for alias, action of getAliases((a) -> not a.endsWith(starEndings))
if action instanceof Level
# This should be a galaxy with only one star.
# Accept an alias ending in " 1".
action.addAlias (alias + " 1")
for alias, action of getAliases((a) -> a.endsWith(" c"))
# Add alias that replaces c with 4, or comet
action.addAlias replaceLastChar(alias, "4")
action.addAlias replaceLastChar(alias, "comet")
for alias, action of getAliases((a) -> a.endsWith(" p"))
action.addAlias replaceLastChar(alias, "100")
action.addAlias replaceLastChar(alias, "purples")
action.addAlias replaceLastChar(alias, "purple coins")
action.addAlias replaceLastChar(alias, "purple comet")
if alias is "gateway p"
action.addAlias replaceLastChar(alias, "2")
else
action.addAlias replaceLastChar(alias, "5")
for alias, action of getAliases()
if alias in ["good egg l", "honeyhive l", "buoy base g"]
action.addAlias replaceLastChar(alias, "h")
if alias in ["battlerock l", "dusty dune g"]
action.addAlias replaceLastChar(alias, "h2")
action.addAlias replaceLastChar(alias, "hidden 2")
action.addAlias replaceLastChar(alias, "hidden star 2")
action.addAlias replaceLastChar(alias, "s2")
action.addAlias replaceLastChar(alias, "secret 2")
action.addAlias replaceLastChar(alias, "secret star 2")
action.addAlias replaceLastChar(alias, "7")
if alias is "battlerock l"
action.addAlias replaceLastChar(alias, "g")
for alias, action of getAliases((a) -> a.endsWith(" h"))
action.addAlias replaceLastChar(alias, "hidden")
action.addAlias replaceLastChar(alias, "hidden star")
action.addAlias replaceLastChar(alias, "s")
action.addAlias replaceLastChar(alias, "secret")
action.addAlias replaceLastChar(alias, "secret star")
if alias is "buoy base h"
action.addAlias replaceLastChar(alias, "2")
else
action.addAlias replaceLastChar(alias, "6")
for alias, action of getAliases((a) -> a.endsWith(" l"))
action.addAlias replaceLastChar(alias, "luigi")
action.addAlias replaceLastChar(alias, "luigi star")
for alias, action of getAliases((a) -> a.endsWith(" g"))
action.addAlias replaceLastChar(alias, "green")
action.addAlias replaceLastChar(alias, "green star")
text: () ->
return "> " + @name
class Level extends Action
# An action that yields a star.
@starNameLookup: {}
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-level'
@starNameId = details.star_name
if @name.endsWith(" C")
@nameCellClass = 'name-level-comet'
if @name.endsWith(" P") and @name isnt "Gateway P"
@nameCellClass = 'name-level-comet'
# Add to starNameLookup.
# Note: This requires usenglish messages to be initialized
# before levels are initialized.
# We could accept star names in other languages besides usenglish, but
# this would only make sense if galaxy names, event names, etc. were
# also accepted in multiple languages...
starName = @starName('usenglish', 'mario')
@constructor.starNameLookup[starName.toLowerCase()] = this
starName = @starName('usenglish', 'luigi')
@constructor.starNameLookup[starName.toLowerCase()] = this
starName: (langCode, character) ->
argSet = {character: character, langCode: langCode}
# Assume a star name message only has 1 box.
box = Message.lookup(@starNameId, langCode).computeBoxes(argSet, null)[0]
return box.text
text: (starCount, character) ->
if not starCount
# Duplicate star (e.g. Bowser's Galaxy Reactor)
return "#{@name} - #{@starName('usenglish', character)}"
return "#{starCount.toString()}. #{@name} - #{@starName('usenglish', character)}"
class Event extends Item
# An Item that doesn't need to be specified in a human readable route.
# For example, an automatically occurring cutscene.
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-event'
text: () ->
return "* #{@name} "
class MessageUtil
@hideMessageDetails: () ->
$('#message-details').hide()
$('#route-table-container').show()
@decodeUTF16BigEndian: (byteArray) ->
# Idea from http://stackoverflow.com/a/14601808
numCodePoints = byteArray.length / 2
codePoints = []
for i in [0..(numCodePoints - 1)]
codePoints.push(
byteArray[i*2]
+ byteArray[i*2 + 1] << 8
)
return String.fromCharCode.apply(String, codePoints)
@bytesStartWith: (bytes, arr2) ->
# bytes is an array of integers. Return true if bytes
# starts with a sub-array equal to arr2.
# Get a byte array from the beginning of bytes, max
# length equal to arr2's length
arr1 = bytes.slice(0, arr2.length)
# See if arr1 and arr2 are equal
if arr1.length isnt arr2.length
return false
return arr1.every((element, index) ->
return element is arr2[index]
)
@processEscapeSequence: (
escapeBytes, boxes, messageId, argSet, messageCase,
displayColors=false, displayFurigana=false) ->
# Add the escape sequence contents to the boxes structure.
escapeBytesStartWith = Util.curry(@bytesStartWith, escapeBytes)
lastBox = boxes[boxes.length-1]
if escapeBytesStartWith [1,0,0,0]
# Text pause - length is either 10, 15, 30, or 60.
pauseLength = escapeBytes[4]
text = "<Text pause, #{pauseLength.toString()}L>"
if 'pauseLength' of lastBox
lastBox.pauseLength += pauseLength
else
lastBox.pauseLength = pauseLength
else if escapeBytesStartWith [1,0,1]
# Message box break.
text = ""
boxes.push({chars: 0, text: ""})
else if escapeBytesStartWith [1,0,2]
text = '<Lower-baseline text>'
else if escapeBytesStartWith [1,0,3]
text = '<Center align>'
else if escapeBytesStartWith [2,0,0,0,0x53]
text = '<Play voice audio>'
else if escapeBytesStartWith [3,0]
# Icon.
iconByte = escapeBytes[2]
iconName = messageLookup.icons[iconByte]
text = "<#{iconName} icon>"
# Any icon counts as one character.
lastBox.chars += 1
else if escapeBytesStartWith [4,0,0]
text = '<Small text>'
else if escapeBytesStartWith [4,0,2]
text = '<Large text>'
else if escapeBytesStartWith [5,0,0,0,0]
# <NAME>'s name or <NAME>'s name.
if messageCase is 'general'
# TODO: Use this case
text = '<Player name>'
else
if argSet.character is 'mario'
textMessageId = 'System_PlayerName000'
else if argSet.character is 'luigi'
textMessageId = 'System_PlayerName100'
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else if escapeBytesStartWith [5,0,0,1,0]
# <NAME>'s name or <NAME>'s name, drawn out excitedly.
if messageCase is 'general'
# TODO: Use this case
text = '<Mr. Plaaayer naaame>'
else
if argSet.character is 'mario'
textMessageId = 'System_PlayerName001'
else if argSet.character is 'luigi'
textMessageId = 'System_PlayerName101'
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else if (escapeBytesStartWith [6]) or (escapeBytesStartWith [7])
# A number or name variable.
# The actual text is message dependent, or even case dependent beyond
# that (e.g. which level a Hungry Luma is in). But we have defined the
# text for the cases that we care about.
if messageId of messageLookup.numbersNames
obj = messageLookup.numbersNames[messageId]
numberNameType = obj._type
if messageCase is 'general'
# TODO: Use this case
text = obj._placeholder
else if numberNameType is 'text'
if messageCase of obj
text = obj[messageCase]
else if argSet.character of obj
text = obj[argSet.character]
lastBox.chars += text.length
else if numberNameType is 'message'
if messageCase of obj
textMessageId = obj[messageCase]
else if argSet.character of obj
textMessageId = obj[argSet.character]
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else
console.log(
"Don't know how to handle number/name variable"
+ "for message: #{messageId}"
)
# TODO: Indicate an error somehow?
else if escapeBytesStartWith [9,0,5]
# Race time (Spooky Sprint, etc.)
text = 'xx:xx:xx'
lastBox.chars += text.length
else if escapeBytesStartWith [0xFF,0,0]
# Signify start or end of text color.
colorByte = escapeBytes[3]
colorType = messageLookup.colors[colorByte]
if displayColors
text = "<#{colorType} color>"
else
text = ""
else if escapeBytesStartWith [0xFF,0,2]
# Japanese furigana (kanji reading help).
kanjiCount = escapeBytes[3]
furiganaBytes = escapeBytes.slice(4)
furiganaStr = @decodeUTF16BigEndian(furiganaBytes)
if displayFurigana
text = "<#{furiganaStr}>"
else
text = ""
else
console.log("Unknown escape sequence: #{escapeBytes}")
# TODO: Indicate an error somehow?
lastBox.text += text
@boxTextDisplayHTML: ($el, box) ->
# Append a display of a box's text to the jQuery element $el.
boxTextLines = box.text.split('\n')
for line, index in boxTextLines
notLastLine = index < boxTextLines.length - 1
# Since the webpage display sometimes has extra linebreaks,
# make it clear where the actual message linebreaks are
if notLastLine
line += '↵'
# Add box text
$el.append document.createTextNode(line)
if notLastLine
# Put a br between text lines
$el.append $('<br>')
# TODO: Make a version of this function (or different argument?) for
# box text display for CSV.
@computeBoxLength: (box, langCode, $el=null) ->
# Compute the length of the box and store the result in box.length.
#
# If a jQuery element $el is given, append an explanation of the
# box length computation to that element.
charAlphaReq = messageLookup.languageSpeeds[langCode].alphaReq
fadeRate = messageLookup.languageSpeeds[langCode].fadeRate
$ul = $('<ul>')
if $el?
$el.append $ul
alphaReq = (box.chars * charAlphaReq) + 1
line = "(#{box.chars} chars * #{charAlphaReq} alpha req per char)
+ 1 extra alpha req = "
result = "#{alphaReq.toFixed(1)} alpha req"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
length = Math.floor(alphaReq / fadeRate)
line = "floor(... / #{fadeRate} fade rate) = "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Confine to float32 precision to see what the game actually computes
f32 = Math.fround
alphaReqF32 = f32(f32(box.chars) * f32(charAlphaReq)) + f32(1)
lengthF32 = Math.floor(f32(f32(alphaReqF32) / f32(fadeRate)))
if length isnt lengthF32
length = lengthF32
line = "Due to 32-bit float imprecision, it's actually "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if 'pauseLength' of box
# Add pause length if applicable.
length += box.pauseLength
line = "... + #{box.pauseLength} pause length = "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Set the computed length in the box object.
box.length = length
# Whatever the final result element was, style it as the final result.
$finalResult = $li.find('span.mid-result')
$finalResult.removeClass('mid-result').addClass('final-result')
@messageFrames: (boxes, messageId, boxEndTimingError, $el=null) ->
boxLengths = (b.length for b in boxes)
# Append a message frames explanation to the jQuery element $el.
$ul = $('<ul>')
if $el?
$el.append $ul
if messageId in messageLookup.forcedSlow
line = "Forced slow text, so 1 frame per length unit"
$ul.append $('<li>').text(line)
frames = 0
for boxLength, index in boxLengths
if index > 0
line = "... + "
else
line = ""
frames += boxLength + 2
line += "(#{boxLength} box length / 1) + 2 box end delay frames = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
else
line = "When holding A, 1 frame per 3 length units"
$ul.append $('<li>').text(line)
if boxLengths.length > 1
line = "When pressing A to end a box, the next box starts with up to
10 frames of slow text because A was re-pressed"
$ul.append $('<li>').text(line)
frames = 0
for boxLength, index in boxLengths
if index == 0
# First box
frames += Math.ceil(boxLength / 3)
line = "ceiling(#{boxLength} box length / 3) "
else
# Second box or later
line = "... "
if boxLength <= 10
# Box is within 10 length
frames += boxLength
line += "+ (#{boxLength} length / 1) "
else
# Longer length
frames += 10 + Math.ceil((boxLength-10) / 3)
line += "+ (10 length / 1) "
line += "+ ceiling((#{boxLength} length - 10) / 3) "
frames += 2
if index == 0
line += "+ 2 box-end delay frames = "
else
line += "+ 2 delay frames = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if boxEndTimingError > 0
# We've specified an average box end timing error of more than 0 frames.
numBoxes = boxLengths.length
frames += (numBoxes * boxEndTimingError)
line = "... + (#{numBoxes} box endings
* #{boxEndTimingError} frames of human timing error) = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if messageId of messageLookup.animationTimes
# There's a cutscene with animations that have to play out entirely before
# advancing, even if the message is done.
animationTime = messageLookup.animationTimes[messageId]
frames = Math.max(frames, animationTime)
line = "max(..., #{animationTime} cutscene animation frames) = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Whatever the final result was, style it as the final result.
$finalResult = $li.find('span.mid-result')
$finalResult.removeClass('mid-result').addClass('final-result')
# Return the computed frame count.
return frames
class Message
@lookupStructure: {}
constructor: (@id, @langCode, @data) ->
# Index into the look up as [idGoesHere/langCodeGoesHere].
# Assumes there are no slashes in message ids or language codes.
@constructor.lookupStructure["#{@id}/#{@langCode}"] = this
@lookup: (id, langCode) ->
return @lookupStructure["#{id}/#{langCode}"]
computeBoxes: (argSet, messageCase) ->
# TODO: Handle @data == null
# TODO: Handle @data == []
boxes = [{chars: 0, text: ""}]
for item in @data
# An item could be a box break which changes the last box, so
# re-set this after every item.
lastBox = boxes[boxes.length-1]
if typeof(item) is "string"
# Text.
# A message box break seems to always be followed by a
# newline character, but in this situation the newline
# doesn't affect the time the box text takes to scroll.
# So we won't count such a newline as a character for our
# purposes.
#
# Box break check: the latest box's text is empty.
# Action: Chop off the leading newline.
newlineAfterBoxBreak = \
item.charAt(0) is '\n' and lastBox.text is ""
if newlineAfterBoxBreak
item = item.slice(1)
lastBox.chars += item.length
lastBox.text += item
else
# Escape sequence.
# This function will add the escape sequence contents
# to the boxes structure.
MessageUtil.processEscapeSequence(
item, boxes, @id, argSet, messageCase
)
# At this point we've got text and chars covered, and pauseLength
# if applicable. Compute the box lengths.
for box in boxes
MessageUtil.computeBoxLength(box, argSet.langCode)
return boxes
frames: (argSet, messageCase) ->
boxes = @computeBoxes(argSet, messageCase)
frames = MessageUtil.messageFrames(boxes, @id, argSet.boxEndTimingError)
return frames
showFrameDetails: (argSet, messageCase) ->
$messageDetails = $('#message-details')
$messageDetails.empty()
# Display a Back button to make the route table viewable again
$backButton = $('<button>')
$backButton.text "Back"
$backButton.click MessageUtil.hideMessageDetails
$messageDetails.append $backButton
# Display the message id and argSet
$h3 = $('<h3>').text("#{@id}, #{argSet.display}")
$messageDetails.append $h3
# Make a box length explanations table
$table = $('<table>')
$tbody = $('<tbody>')
$table.append $tbody
$('#route-table-container').hide()
$messageDetails.show()
boxes = @computeBoxes(argSet, messageCase)
# Display box level frame details
for box in boxes
$tr = $('<tr>')
$tbody.append $tr
# Box text
$td = $('<td>')
$td.addClass 'box-text'
MessageUtil.boxTextDisplayHTML($td, box)
$tr.append $td
# Box length explanation
$td = $('<td>')
$td.addClass 'box-length-explanation'
MessageUtil.computeBoxLength(box, argSet.langCode, $td)
$tr.append $td
# Display message level frame details
MessageUtil.messageFrames(
boxes, @id, argSet.boxEndTimingError, $messageDetails
)
# Append box length explanations
$messageDetails.append $table
class Route
@numAndLevelRegex = /// ^
\d+ # Number
[\.|\)] # . or )
(.+) # 1 or more chars of anything
$ ///
@actionAndParensNoteRegex = /// ^
(.+) # 1 or more chars of anything
\( # Left parens
.+ # 1 or more chars of anything
\) # Right parens
$ ///
# 70 stars, 1 star, etc.
@starsReqRegex = /^(\d+) stars?$/
# Less than 70 stars, Less than 1 star, etc.
@lessThanStarsReqRegex = /^Less than (\d+) stars?$/
# 400 star bits, etc.
@starBitReqRegex = /^(\d+) star bits$/
isComplete: false
constructor: (text, category) ->
@actions = []
# Split text into lines
lines = Util.splitlines(text)
# First line = route name
@name = lines[0]
lines = lines[1..]
$('#route-status').empty()
for line in lines
line = line.trim()
if line is ""
# Blank line
continue
action = @lineToAction(line)
if not action
@addRouteStatus("Could not recognize as a level/action: " + line)
break
else if action is 'comment'
# Just a comment line in the text route; ignore it.
continue
@actions.push(action)
if category is "Any%"
@endItemName = "Bowser's Galaxy Reactor"
@endRequirements = []
else if category is "120 Star"
@endItemName = "Bowser's Galaxy Reactor"
@endRequirements = ["120 stars"]
addRouteStatus: (s) ->
$('#route-status').append(document.createTextNode(s))
$('#route-status').append(document.createElement('br'))
lineToAction: (line) ->
# Make item recognition non-case-sensitive
line = line.toLowerCase()
if line.startsWith '*'
# Assumed to be just a comment, e.g. "* Back to start of observatory"
return 'comment'
if line.startsWith '>'
# Assumed to be an action with an exact name, e.g. "> Luigi letter 2".
line = line.slice(1).trim()
# Check if line begins with a star number like "5." or "17)"
# If so, remove it
match = @constructor.numAndLevelRegex.exec(line)
if match
line = match[1].trim()
# Check if we have an alias match
if line of Action.aliases
return Action.aliases[line]
# Check if line ends with a parenthesized thing like "(skip cutscenes)"
# If so, remove it
match = @constructor.actionAndParensNoteRegex.exec(line)
if match
line = match[1].trim()
# Check again if we have an alias match
if line of Action.aliases
return Action.aliases[line]
# Check for just the star name
if line of Level.starNameLookup
return Level.starNameLookup[line]
# Check if there's a dash, and if so, see if we can find a
# galaxy+number - starname match like "Good Egg 1 - Dino Piranha".
# Either one will do, don't need both correct.
# (e.g. "Good Egg - Dino Piranha" should work fine too.)
# Try all the dashes if there's more than one.
indexOfDash = line.indexOf('-')
while indexOfDash isnt -1
possibleGalaxyAndNum = line.slice(0, indexOfDash).trim()
if possibleGalaxyAndNum of Action.aliases
return Action.aliases[possibleGalaxyAndNum]
possibleStarName = line.slice(indexOfDash+1).trim()
if possibleStarName of Level.starNameLookup
return Level.starNameLookup[possibleStarName]
indexOfDash = line.indexOf('-', indexOfDash+1)
# Tried everything we could think of
return null
fulfilledRequirement: (req, completedItemNames, starCount) ->
# Way 1 to satisfy requirement: req matches name of a completed action
if req in completedItemNames
return true
# Way 2: it's a >= stars req and we've got it
match = @constructor.starsReqRegex.exec(req)
if match
reqStars = Number(match[1].trim())
if starCount >= reqStars
return true
# Way 3: it's a < stars req and we've got it
match = @constructor.lessThanStarsReqRegex.exec(req)
if match
reqLessThanStars = Number(match[1].trim())
if starCount < reqLessThanStars
return true
# Way 4: it's a star bits req
# TODO: Actually check this. For now we have no way of checking possible
# or probable star bit count, so we skip the check.
match = @constructor.starBitReqRegex.exec(req)
if match
return true
return false
isEndOfRoute: (item, completedItemNames, starCount) ->
# If the run only ends on a particular route item, check for that
# route item
if @endItemName
if item.name isnt @endItemName
return false
# Check that other end requirements are met
for req in @endRequirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
return false
return true
checkAndAddEvents: () ->
# Add between-level events to the route.
@isComplete = false
@items = []
starCount = 0
greenStarCount = 0
expectedActionName = null
completedItemNames = []
# luigiStars goes up to 3: Good Egg L, Battlerock L, Honeyhive L
luigiStatus = {talkedAtGarage: false, luigiStars: 0, betweenStars: 0}
for action in @actions
# Check if we are expecting a specific action here at this point in
# the route.
if expectedActionName
if action.name isnt expectedActionName
s = "At this point the route must have: '" \
+ expectedActionName + "' but instead it has: '" \
+ action.name + "'"
@addRouteStatus(s)
expectedActionName = null
# Check requirements for this item.
for req in action.requirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
s = "'" + action.name + "' has an unfulfilled requirement: " + req
@addRouteStatus(s)
return
# Check special requirements for Luigi events.
if action.name is "Luigi letter 2"
if not (luigiStatus.luigiStars is 1 and luigiStatus.betweenStars >= 5)
s = "'" + action.name \
+ "' has an unfulfilled requirement: Must have 1 Luigi star and
5 in-between stars since that Luigi star. Current status: " \
+ luigiStatus.luigiStars.toString() + " Luigi star(s) and " \
+ luigiStatus.betweenStars.toString() + " in-between star(s)."
@addRouteStatus(s)
return
else if action.name is "Luigi letter 3"
if not (luigiStatus.luigiStars is 2 and luigiStatus.betweenStars >= 5)
s = "'" + action.name \
+ "' has an unfulfilled requirement: Must have 2 Luigi stars and
5 in-between stars since that Luigi star. Current status: " \
+ luigiStatus.luigiStars.toString() + " Luigi star(s) and " \
+ luigiStatus.betweenStars.toString() + " in-between star(s)."
@addRouteStatus(s)
return
# Add the action to the route.
followingItems = []
if action instanceof Level
if action.name in completedItemNames
# Duplicate star
@items.push {
item: action
starCount: null
}
else
starCount += 1
@items.push {
item: action
starCount: starCount
}
# Check for "x star(s)" triggers
if starCount is 1
starCountStr = "1 star"
else
starCountStr = "#{starCount} stars"
if starCountStr of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[starCountStr]...)
else
@items.push {
item: action
}
completedItemNames.push action.name
if @isEndOfRoute(action, completedItemNames, starCount)
@isComplete = true
return
# Update Green Star count if applicable
if action.name in ["<NAME> L", "<NAME> G", "<NAME>"]
greenStarCount += 1
# Check for "x green star(s)" triggers
if greenStarCount is 1
starCountStr = "1 green star"
else
starCountStr = "#{greenStarCount} green stars"
if starCountStr of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[starCountStr]...)
# Update Luigi status if applicable
if action.name is "Talk to Luigi at Garage"
luigiStatus.talkedAtGarage = true
else if luigiStatus.talkedAtGarage and action instanceof Level
if action.name in ["Good Egg L", "Battlerock L", "Honeyhive L"]
luigiStatus.luigiStars += 1
luigiStatus.betweenStars = 0
else
luigiStatus.betweenStars += 1
# Check for Luigi letter 1 event
if luigiStatus.luigiStars is 0 and luigiStatus.betweenStars is 1
followingItems.push(Item.idLookup["Luigi letter 1"])
# Items triggered by this action specifically
if action.name of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[action.name]...)
while followingItems.length > 0
followingItem = followingItems.shift()
if followingItem instanceof Action
# By some special case, this following "event" is also considered
# an action of some sort. We'll go to the next iteration to process
# this action, and we'll make a note to check that this action is
# indeed the next item in the route.
expectedActionName = followingItem.name
continue
# Ensure all of this item's trigger requirements are met before
# adding the item. If the requirements aren't met, the item is not
# triggered.
reqFailed = false
for req in followingItem.requirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
reqFailed = true
if reqFailed
continue
# Add the item to the route.
@items.push {
item: followingItem
}
completedItemNames.push followingItem.name
if @isEndOfRoute(followingItem, completedItemNames, starCount)
return
# Check if other items are triggered by this item
if followingItem.name of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[followingItem.name]...)
makeTable: (argSets) ->
$tableContainer = $('#route-table-container')
$table = $('<table>')
$tableContainer.empty().append($table)
$thead = $('<thead>')
$tbody = $('<tbody>')
$table.append $thead
$table.append $tbody
$row = $('<tr>')
$thead.append $row
$row.append $('<th>').text(@name)
for argSet in argSets
$row.append $('<th>').text(argSet.display)
# Determine whether to use Mario or Luigi in star names by seeing if
# Mario or Luigi has more argSets. (If tied, it goes to Mario.)
characterCounts = {mario: 0, luigi: 0}
argSetCharacters = (argSet.character for argSet in argSets)
for character in argSetCharacters
characterCounts[character] += 1
if characterCounts['mario'] >= characterCounts['luigi']
preferredCharacter = 'mario'
else
preferredCharacter = 'luigi'
# Add route items to the table as rows.
textFrameTotals = (0 for argSet in argSets)
for itemObj in @items
item = itemObj.item
if itemObj.starCount
itemText = item.text(itemObj.starCount, preferredCharacter)
else
itemText = item.text()
$row = $('<tr>')
$tbody.append $row
$row.addClass 'route-item'
# Click on a route item row -> show a frames breakdown.
#
# Currying a class function directly doesn't work,
# so we use an intermediate function.
f = (item_, argSets_) -> item_.showFrameDetails(argSets_)
$row.click(Util.curry(f, item, argSets))
# Item name cell
$cell = $('<td>')
$cell.text itemText
$cell.addClass item.nameCellClass
$row.append $cell
for argSet, index in argSets
frames = item.frames argSet
# Frame count cell for each argSet
$cell = $('<td>')
$cell.text frames
$row.append $cell
textFrameTotals[index] += frames
if not @isComplete
# If the route isn't complete, don't do any totals.
return
# Add frame-totals row.
$totalsRow = $('<tr>')
$tbody.append $totalsRow
$cell = $('<td>').text "Total of relative text times"
$totalsRow.append $cell
for total in textFrameTotals
$cell = $('<td>').text total
$totalsRow.append $cell
# Add differences column(s) and summary sentence
# if there are exactly two argSets.
if argSets.length is 2
# Header cells
$headerRow = $thead.find('tr')
$cell = $('<th>').text("Diff (f)")
$headerRow.append $cell
$cell = $('<th>').text("Diff (s)")
$headerRow.append $cell
# Data cells
$rows = $tbody.find('tr')
$rows.each( (_, row) =>
cellTexts = ($(cell).text() for cell in $(row).find('td'))
frameDiff = Number(cellTexts[1]) - Number(cellTexts[2])
# Frames difference
$cell = $('<td>').text frameDiff
$(row).append $cell
# Seconds difference
$cell = $('<td>').text (frameDiff/(60/1.001)).toFixed(2)
$(row).append $cell
)
# Summary sentence
secondsDiff = $totalsRow.find('td')[4].textContent
if secondsDiff.charAt(0) is '-'
# Negative diff
summary = "#{argSets[0].display} is #{secondsDiff.slice(1)} seconds
faster than #{argSets[1].display} for this route"
else
# Positive diff
summary = "#{argSets[1].display} is #{secondsDiff} seconds
faster than #{argSets[0].display} for this route"
$('#route-status').append $('<h3>').text summary
determineArgSets = (languageLookup) ->
# Build sets of text-frame-counting params/arguments from the fields
argSets = []
for set in ['set1', 'set2']
argSet = {}
for fieldName in ['langCode', 'character', 'boxEndTimingError']
$field = $("##{set}-#{fieldName}")
argSet[fieldName] = $field.val()
argSet.boxEndTimingError = Number(argSet.boxEndTimingError)
argSets.push argSet
# Figure out suitable display names based on the argSets' differences
if argSets[0].langCode isnt argSets[1].langCode
lang1 = languageLookup[argSets[0].langCode]
lang2 = languageLookup[argSets[1].langCode]
if lang1.region isnt lang2.region
# Language / region
argSets[0].display = lang1.region
argSets[1].display = lang2.region
else
# Language / language name
argSets[0].display = lang1.language
argSets[1].display = lang2.language
else if argSets[0].character isnt argSets[1].character
# Character
char = argSets[0].character
argSets[0].display = char.slice(0,1).toUpperCase() + char.slice(1)
char = argSets[1].character
argSets[1].display = char.slice(0,1).toUpperCase() + char.slice(1)
else
# Box end timing error
argSets[0].display = argSets[0].boxEndTimingError.toString() + " BTE"
argSets[1].display = argSets[1].boxEndTimingError.toString() + " BTE"
return argSets
addLanguages = (langCodes, callbackAfterInitAllLanguages) ->
# If all requested languages are already loaded, call the passed callback
# and we're done
allLanguagesLoaded = langCodes.every(
(code) -> return (window.messages? and code of window.messages)
)
if allLanguagesLoaded
do callbackAfterInitAllLanguages
return
# Else, we must load at least 1 language first
for langCode in langCodes
# If we've already loaded this language, move onto the next one
if window.messages? and langCode of window.messages
continue
# Callback that runs when this language is loaded
cb = (langCode_, langCodes_, callbackAfterInitAllLanguages_) ->
# Initialize messages for this language
for own messageId, data of window.messages[langCode_]
new Message(messageId, langCode_, data)
# Check if ALL requested languages are loaded (not just this one)
allLanguagesLoaded = langCodes_.every(
(code) -> return (code of window.messages)
)
if allLanguagesLoaded
# Call the passed callback
do callbackAfterInitAllLanguages_
# Load this language
callbackAfterLoadingLanguage = Util.curry(
cb, langCode, langCodes, callbackAfterInitAllLanguages
)
Util.readServerJSFile(
"js/messages/#{langCode}.js", callbackAfterLoadingLanguage
)
class Main
routeTextChanged: false
init: (itemDetails, itemMessages) ->
callback = Util.curry(@init2, itemDetails, itemMessages)
addLanguages(['usenglish'], callback)
init2: (itemDetails, itemMessages) ->
# Initialize possible route items.
for own itemKey, details of itemDetails
args = [itemKey, details, itemMessages[itemKey] ? []]
if details.type is 'Level'
new Level(args...)
else if details.type is 'Action'
new Action(args...)
else if details.type is 'Event'
new Event(args...)
else
console.log(
"Invalid item type: " + details.type
)
# Add text aliases for possible route items.
Action.addAliases()
# Get info on the available languages.
languages = []
languageLookup = {}
for own langCode, _ of messageLookup.languageSpeeds
# The first 2 chars should be the region, rest should be language.
obj = {
code: langCode
region: langCode.slice(0,2).toUpperCase()
language: langCode.slice(2,3).toUpperCase() + langCode.slice(3)
}
obj.display = "#{obj.language} (#{obj.region})"
languages.push obj
languageLookup[langCode] = obj
# The languages array will serve as a way to sort the languages.
sortFunc = (a,b) ->
if a.display < b.display
return -1
else if a.display > b.display
return 1
else
return 0
languages.sort(sortFunc)
# Initialize the language dropdowns
for set in ['set1', 'set2']
$select = $("##{set}-langCode")
# Fill with the ordered languages.
for lang in languages
$select.append(
$('<option>').attr('value', lang.code).text(lang.display)
)
# Initialize with US English for the first, JP Japanese for the second.
if set is 'set1'
$select.val('usenglish')
else
$select.val('jpjapanese')
# Initialize the boxEndTimingError dropdowns
for set in ['set1', 'set2']
$select = $("##{set}-boxEndTimingError")
for num in [0..15]
value = num.toString()
text = num.toString()
if text is "0"
text = "0 (TAS)"
$select.append $('<option>').attr('value', value).text(text)
# Initialize the value.
$select.val("10")
# Initialize the route processing button
document.getElementById('route-button').onclick = (event) =>
$('#route-status').empty()
routeText = document.getElementById('route-textarea').value
category = $('#route-category').val()
route = new Route(routeText, category)
route.checkAndAddEvents()
if not route.isComplete
route.addRouteStatus("Route is incomplete!")
argSets = determineArgSets(languageLookup)
# Get the required languages, then make the route table
callback = () -> route.makeTable argSets
addLanguages((argSet.langCode for argSet in argSets), callback)
# Initialize help button(s)
$('.help-button').each( () ->
buttonIdRegex = /^(.+)-button$/
result = buttonIdRegex.exec(this.id)
helpTextId = result[1]
# When this help button is clicked, open the corresponding
# help text in a modal window.
clickCallback = (helpTextId_, helpButtonE) ->
$helpText = $('#'+helpTextId_)
$helpText.dialog({
modal: true
width: 500
height: 600
position: {
my: "center top"
at: "center bottom"
of: helpButtonE
}
})
# NOTE: The below only applies to the route textarea help, so if
# there's another help button at some point, then this code needs
# to be moved somewhere else.
# Part of the help text involves listing all the non-level actions.
# The first time this help text is opened, fill the list.
$actionList = $('#action-list')
if $actionList.is(':empty')
for id, item of Item.idLookup
# Ensure we're listing non-level actions.
if (item instanceof Action) and not (item instanceof Level)
$actionList.append(
$('<li>').append $('<code>').text('> '+item.name)
)
# Make the dialog's scroll position start at the top. If we don't do
# this, then it starts where the in-dialog button is, for some reason.
$helpText.scrollTop(0)
$(this).click(
Util.curry(clickCallback, helpTextId, this)
)
)
# Initialize fill-with-sample-route buttons
applySampleRoute = (categoryValue, sampleRouteFilename) =>
if @routeTextChanged
message = "This'll overwrite the current route with the" \
+ " Sample " + categoryValue + " route. Are you sure?"
# If user chooses yes, proceed; if chooses no, return
if not confirm(message)
return
# Reset the "route changed" state
@routeTextChanged = false
$('#route-category').val(categoryValue)
callback = (text) ->
document.getElementById('route-textarea').value = text
Util.readServerTextFile(sampleRouteFilename, callback)
$('#sample-any-route-button').click(
Util.curry(applySampleRoute, "Any%", "samplerouteany.txt")
)
$('#sample-120-route-button').click(
Util.curry(applySampleRoute, "120 Star", "sampleroute120.txt")
)
# Watch for route text changes via typing.
# (Precisely: The textarea lost focus and its value changed
# since gaining focus.)
$('#route-textarea').change( () =>
@routeTextChanged = true
)
window.main = new Main | true | class Item
# A level, cutscene, or event. Basically a block of a full game run.
@idLookup: {}
@followingItemsLookup: {}
constructor: (@name, details, messages) ->
@constructor.idLookup[@name] = this
@requirements = details.requirements
@startLocation = details.start_location
@endLocation = details.end_location
for itemName in details.follows
if itemName of @constructor.followingItemsLookup
@constructor.followingItemsLookup[itemName].push(this)
else
@constructor.followingItemsLookup[itemName] = [this]
@messages = []
for message in messages
@messages.push {
id: message['id']
case: message['case'] ? null
skippable: message['skippable'] ? false
}
frames: (argSet) ->
totalFrames = 0
for message in @messages
# Don't include skippable messages in our frame count.
if message.skippable
continue
id = message.id
if typeof id isnt 'string'
# Object containing multiple cases. The only possible factor for
# message id is character.
id = id[argSet.character]
m = Message.lookup(id, argSet.langCode)
messageFrames = m.frames(argSet, message.case)
totalFrames += messageFrames
return totalFrames
showFrameDetails: (argSets) ->
# Show a message by message breakdown of frame counts for a particular
# route item.
$itemDetails = $('#item-details')
$itemDetails.empty()
# Display item name
$h3 = $('<h3>').text(@name)
$itemDetails.append $h3
# Message by message frame breakdown table
$table = $('<table>')
$tbody = $('<tbody>')
$table.append $tbody
$itemDetails.append $table
# Header row
$tr = $('<tr>')
$tr.append $('<td>').text "Message ID"
for argSet in argSets
$tr.append $('<td>').text argSet.display
$tbody.append $tr
for message in @messages
# Create a table row for the message.
$tr = $('<tr>')
$tbody.append $tr
# Display message id (or possible message ids).
$td = $('<td>')
if typeof message.id is 'string'
$td.text message.id
else
# Only other possibility is a map from character to message id.
# If the argSets have the same character, just show that character's
# message id. Otherwise, show both.
if argSets[0].character is argSets[1].character
$td.text message.id[argSets[0].character]
else
$td.append document.createTextNode message.id[argSets[0].character]
$td.append document.createElement 'br'
$td.append document.createTextNode message.id[argSets[1].character]
$td.addClass 'message-id-display'
$tr.append $td
for argSet in argSets
if typeof message.id is 'string'
messageId = message.id
else
messageId = message.id[argSet.character]
messageObj = Message.lookup(messageId, argSet.langCode)
# Display message frames.
framesText = messageObj.frames(argSet, message.case)
$td = $('<td>').text(framesText)
$tr.append $td
# When this cell is clicked, display full frame details for this
# message + argSet.
$td.addClass 'message-frames'
f = (messageObj_, argSet_, messageCase_) ->
messageObj_.showFrameDetails(argSet_, messageCase_)
$td.click(Util.curry(f, messageObj, argSet, message.case))
# Style skippable messages differently.
if message.skippable
$tr.addClass 'skippable'
class Action extends Item
# An Item that needs to be specified in a human readable route.
# It's not an automatically occurring cutscene or anything like that, it's
# something the player needs to know when to do.
# Map/dict from human-readable strings to actions they represent.
# Used when accepting a route as text.
# e.g. either "Good Egg 4" or "Good Egg C" refers to Dino Piranha Speed Run.
@aliases: {}
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-action'
@addAlias(@name)
addAlias: (alias) ->
# Add to the class variable 'aliases'.
# Map from alias to the standard name.
# Make all aliases lowercase, so we can do case insensitive recognition.
@constructor.aliases[alias.toLowerCase()] = this
@addAliases: () ->
# The Level constructor added a basic alias for every level: the level
# name itself.
# Here we add more aliases for various actions (mostly levels).
replaceLastChar = (s1, s2) -> s1.slice(0, s1.length - 1) + s2
# Make a way to filter aliases based on a boolean test.
getAliases = (boolFunc) ->
if not boolFunc?
return Action.aliases
aliasSubset = {}
for alias, action of Action.aliases
if boolFunc(alias)
aliasSubset[alias] = action
return aliasSubset
for alias, action of getAliases((a) -> a.startsWith("bowser's "))
# Can omit this part
action.addAlias alias.replace("bowser's ", "")
for alias, action of getAliases((a) -> a.startsWith("bowser jr.'s "))
# Can omit this part
action.addAlias alias.replace("bowser jr.'s ", "")
# Detect single-star galaxies - easier to do this before we've added
# more star ending possibilities.
starEndings = ['1','2','3','h','g','l','c','p']
for alias, action of getAliases((a) -> not a.endsWith(starEndings))
if action instanceof Level
# This should be a galaxy with only one star.
# Accept an alias ending in " 1".
action.addAlias (alias + " 1")
for alias, action of getAliases((a) -> a.endsWith(" c"))
# Add alias that replaces c with 4, or comet
action.addAlias replaceLastChar(alias, "4")
action.addAlias replaceLastChar(alias, "comet")
for alias, action of getAliases((a) -> a.endsWith(" p"))
action.addAlias replaceLastChar(alias, "100")
action.addAlias replaceLastChar(alias, "purples")
action.addAlias replaceLastChar(alias, "purple coins")
action.addAlias replaceLastChar(alias, "purple comet")
if alias is "gateway p"
action.addAlias replaceLastChar(alias, "2")
else
action.addAlias replaceLastChar(alias, "5")
for alias, action of getAliases()
if alias in ["good egg l", "honeyhive l", "buoy base g"]
action.addAlias replaceLastChar(alias, "h")
if alias in ["battlerock l", "dusty dune g"]
action.addAlias replaceLastChar(alias, "h2")
action.addAlias replaceLastChar(alias, "hidden 2")
action.addAlias replaceLastChar(alias, "hidden star 2")
action.addAlias replaceLastChar(alias, "s2")
action.addAlias replaceLastChar(alias, "secret 2")
action.addAlias replaceLastChar(alias, "secret star 2")
action.addAlias replaceLastChar(alias, "7")
if alias is "battlerock l"
action.addAlias replaceLastChar(alias, "g")
for alias, action of getAliases((a) -> a.endsWith(" h"))
action.addAlias replaceLastChar(alias, "hidden")
action.addAlias replaceLastChar(alias, "hidden star")
action.addAlias replaceLastChar(alias, "s")
action.addAlias replaceLastChar(alias, "secret")
action.addAlias replaceLastChar(alias, "secret star")
if alias is "buoy base h"
action.addAlias replaceLastChar(alias, "2")
else
action.addAlias replaceLastChar(alias, "6")
for alias, action of getAliases((a) -> a.endsWith(" l"))
action.addAlias replaceLastChar(alias, "luigi")
action.addAlias replaceLastChar(alias, "luigi star")
for alias, action of getAliases((a) -> a.endsWith(" g"))
action.addAlias replaceLastChar(alias, "green")
action.addAlias replaceLastChar(alias, "green star")
text: () ->
return "> " + @name
class Level extends Action
# An action that yields a star.
@starNameLookup: {}
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-level'
@starNameId = details.star_name
if @name.endsWith(" C")
@nameCellClass = 'name-level-comet'
if @name.endsWith(" P") and @name isnt "Gateway P"
@nameCellClass = 'name-level-comet'
# Add to starNameLookup.
# Note: This requires usenglish messages to be initialized
# before levels are initialized.
# We could accept star names in other languages besides usenglish, but
# this would only make sense if galaxy names, event names, etc. were
# also accepted in multiple languages...
starName = @starName('usenglish', 'mario')
@constructor.starNameLookup[starName.toLowerCase()] = this
starName = @starName('usenglish', 'luigi')
@constructor.starNameLookup[starName.toLowerCase()] = this
starName: (langCode, character) ->
argSet = {character: character, langCode: langCode}
# Assume a star name message only has 1 box.
box = Message.lookup(@starNameId, langCode).computeBoxes(argSet, null)[0]
return box.text
text: (starCount, character) ->
if not starCount
# Duplicate star (e.g. Bowser's Galaxy Reactor)
return "#{@name} - #{@starName('usenglish', character)}"
return "#{starCount.toString()}. #{@name} - #{@starName('usenglish', character)}"
class Event extends Item
# An Item that doesn't need to be specified in a human readable route.
# For example, an automatically occurring cutscene.
constructor: (@name, details, messages) ->
super(@name, details, messages)
@nameCellClass = 'name-event'
text: () ->
return "* #{@name} "
class MessageUtil
@hideMessageDetails: () ->
$('#message-details').hide()
$('#route-table-container').show()
@decodeUTF16BigEndian: (byteArray) ->
# Idea from http://stackoverflow.com/a/14601808
numCodePoints = byteArray.length / 2
codePoints = []
for i in [0..(numCodePoints - 1)]
codePoints.push(
byteArray[i*2]
+ byteArray[i*2 + 1] << 8
)
return String.fromCharCode.apply(String, codePoints)
@bytesStartWith: (bytes, arr2) ->
# bytes is an array of integers. Return true if bytes
# starts with a sub-array equal to arr2.
# Get a byte array from the beginning of bytes, max
# length equal to arr2's length
arr1 = bytes.slice(0, arr2.length)
# See if arr1 and arr2 are equal
if arr1.length isnt arr2.length
return false
return arr1.every((element, index) ->
return element is arr2[index]
)
@processEscapeSequence: (
escapeBytes, boxes, messageId, argSet, messageCase,
displayColors=false, displayFurigana=false) ->
# Add the escape sequence contents to the boxes structure.
escapeBytesStartWith = Util.curry(@bytesStartWith, escapeBytes)
lastBox = boxes[boxes.length-1]
if escapeBytesStartWith [1,0,0,0]
# Text pause - length is either 10, 15, 30, or 60.
pauseLength = escapeBytes[4]
text = "<Text pause, #{pauseLength.toString()}L>"
if 'pauseLength' of lastBox
lastBox.pauseLength += pauseLength
else
lastBox.pauseLength = pauseLength
else if escapeBytesStartWith [1,0,1]
# Message box break.
text = ""
boxes.push({chars: 0, text: ""})
else if escapeBytesStartWith [1,0,2]
text = '<Lower-baseline text>'
else if escapeBytesStartWith [1,0,3]
text = '<Center align>'
else if escapeBytesStartWith [2,0,0,0,0x53]
text = '<Play voice audio>'
else if escapeBytesStartWith [3,0]
# Icon.
iconByte = escapeBytes[2]
iconName = messageLookup.icons[iconByte]
text = "<#{iconName} icon>"
# Any icon counts as one character.
lastBox.chars += 1
else if escapeBytesStartWith [4,0,0]
text = '<Small text>'
else if escapeBytesStartWith [4,0,2]
text = '<Large text>'
else if escapeBytesStartWith [5,0,0,0,0]
# PI:NAME:<NAME>END_PI's name or PI:NAME:<NAME>END_PI's name.
if messageCase is 'general'
# TODO: Use this case
text = '<Player name>'
else
if argSet.character is 'mario'
textMessageId = 'System_PlayerName000'
else if argSet.character is 'luigi'
textMessageId = 'System_PlayerName100'
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else if escapeBytesStartWith [5,0,0,1,0]
# PI:NAME:<NAME>END_PI's name or PI:NAME:<NAME>END_PI's name, drawn out excitedly.
if messageCase is 'general'
# TODO: Use this case
text = '<Mr. Plaaayer naaame>'
else
if argSet.character is 'mario'
textMessageId = 'System_PlayerName001'
else if argSet.character is 'luigi'
textMessageId = 'System_PlayerName101'
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else if (escapeBytesStartWith [6]) or (escapeBytesStartWith [7])
# A number or name variable.
# The actual text is message dependent, or even case dependent beyond
# that (e.g. which level a Hungry Luma is in). But we have defined the
# text for the cases that we care about.
if messageId of messageLookup.numbersNames
obj = messageLookup.numbersNames[messageId]
numberNameType = obj._type
if messageCase is 'general'
# TODO: Use this case
text = obj._placeholder
else if numberNameType is 'text'
if messageCase of obj
text = obj[messageCase]
else if argSet.character of obj
text = obj[argSet.character]
lastBox.chars += text.length
else if numberNameType is 'message'
if messageCase of obj
textMessageId = obj[messageCase]
else if argSet.character of obj
textMessageId = obj[argSet.character]
textMessage = Message.lookup(textMessageId, argSet.langCode)
text = textMessage.computeBoxes(argSet, messageCase)[0].text
lastBox.chars += text.length
else
console.log(
"Don't know how to handle number/name variable"
+ "for message: #{messageId}"
)
# TODO: Indicate an error somehow?
else if escapeBytesStartWith [9,0,5]
# Race time (Spooky Sprint, etc.)
text = 'xx:xx:xx'
lastBox.chars += text.length
else if escapeBytesStartWith [0xFF,0,0]
# Signify start or end of text color.
colorByte = escapeBytes[3]
colorType = messageLookup.colors[colorByte]
if displayColors
text = "<#{colorType} color>"
else
text = ""
else if escapeBytesStartWith [0xFF,0,2]
# Japanese furigana (kanji reading help).
kanjiCount = escapeBytes[3]
furiganaBytes = escapeBytes.slice(4)
furiganaStr = @decodeUTF16BigEndian(furiganaBytes)
if displayFurigana
text = "<#{furiganaStr}>"
else
text = ""
else
console.log("Unknown escape sequence: #{escapeBytes}")
# TODO: Indicate an error somehow?
lastBox.text += text
@boxTextDisplayHTML: ($el, box) ->
# Append a display of a box's text to the jQuery element $el.
boxTextLines = box.text.split('\n')
for line, index in boxTextLines
notLastLine = index < boxTextLines.length - 1
# Since the webpage display sometimes has extra linebreaks,
# make it clear where the actual message linebreaks are
if notLastLine
line += '↵'
# Add box text
$el.append document.createTextNode(line)
if notLastLine
# Put a br between text lines
$el.append $('<br>')
# TODO: Make a version of this function (or different argument?) for
# box text display for CSV.
@computeBoxLength: (box, langCode, $el=null) ->
# Compute the length of the box and store the result in box.length.
#
# If a jQuery element $el is given, append an explanation of the
# box length computation to that element.
charAlphaReq = messageLookup.languageSpeeds[langCode].alphaReq
fadeRate = messageLookup.languageSpeeds[langCode].fadeRate
$ul = $('<ul>')
if $el?
$el.append $ul
alphaReq = (box.chars * charAlphaReq) + 1
line = "(#{box.chars} chars * #{charAlphaReq} alpha req per char)
+ 1 extra alpha req = "
result = "#{alphaReq.toFixed(1)} alpha req"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
length = Math.floor(alphaReq / fadeRate)
line = "floor(... / #{fadeRate} fade rate) = "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Confine to float32 precision to see what the game actually computes
f32 = Math.fround
alphaReqF32 = f32(f32(box.chars) * f32(charAlphaReq)) + f32(1)
lengthF32 = Math.floor(f32(f32(alphaReqF32) / f32(fadeRate)))
if length isnt lengthF32
length = lengthF32
line = "Due to 32-bit float imprecision, it's actually "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if 'pauseLength' of box
# Add pause length if applicable.
length += box.pauseLength
line = "... + #{box.pauseLength} pause length = "
result = "#{length} length"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Set the computed length in the box object.
box.length = length
# Whatever the final result element was, style it as the final result.
$finalResult = $li.find('span.mid-result')
$finalResult.removeClass('mid-result').addClass('final-result')
@messageFrames: (boxes, messageId, boxEndTimingError, $el=null) ->
boxLengths = (b.length for b in boxes)
# Append a message frames explanation to the jQuery element $el.
$ul = $('<ul>')
if $el?
$el.append $ul
if messageId in messageLookup.forcedSlow
line = "Forced slow text, so 1 frame per length unit"
$ul.append $('<li>').text(line)
frames = 0
for boxLength, index in boxLengths
if index > 0
line = "... + "
else
line = ""
frames += boxLength + 2
line += "(#{boxLength} box length / 1) + 2 box end delay frames = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
else
line = "When holding A, 1 frame per 3 length units"
$ul.append $('<li>').text(line)
if boxLengths.length > 1
line = "When pressing A to end a box, the next box starts with up to
10 frames of slow text because A was re-pressed"
$ul.append $('<li>').text(line)
frames = 0
for boxLength, index in boxLengths
if index == 0
# First box
frames += Math.ceil(boxLength / 3)
line = "ceiling(#{boxLength} box length / 3) "
else
# Second box or later
line = "... "
if boxLength <= 10
# Box is within 10 length
frames += boxLength
line += "+ (#{boxLength} length / 1) "
else
# Longer length
frames += 10 + Math.ceil((boxLength-10) / 3)
line += "+ (10 length / 1) "
line += "+ ceiling((#{boxLength} length - 10) / 3) "
frames += 2
if index == 0
line += "+ 2 box-end delay frames = "
else
line += "+ 2 delay frames = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if boxEndTimingError > 0
# We've specified an average box end timing error of more than 0 frames.
numBoxes = boxLengths.length
frames += (numBoxes * boxEndTimingError)
line = "... + (#{numBoxes} box endings
* #{boxEndTimingError} frames of human timing error) = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
if messageId of messageLookup.animationTimes
# There's a cutscene with animations that have to play out entirely before
# advancing, even if the message is done.
animationTime = messageLookup.animationTimes[messageId]
frames = Math.max(frames, animationTime)
line = "max(..., #{animationTime} cutscene animation frames) = "
result = "#{frames} frames"
$li = $('<li>')
$li.append document.createTextNode(line)
$li.append $('<span>').addClass('mid-result').text(result)
$ul.append $li
# Whatever the final result was, style it as the final result.
$finalResult = $li.find('span.mid-result')
$finalResult.removeClass('mid-result').addClass('final-result')
# Return the computed frame count.
return frames
class Message
@lookupStructure: {}
constructor: (@id, @langCode, @data) ->
# Index into the look up as [idGoesHere/langCodeGoesHere].
# Assumes there are no slashes in message ids or language codes.
@constructor.lookupStructure["#{@id}/#{@langCode}"] = this
@lookup: (id, langCode) ->
return @lookupStructure["#{id}/#{langCode}"]
computeBoxes: (argSet, messageCase) ->
# TODO: Handle @data == null
# TODO: Handle @data == []
boxes = [{chars: 0, text: ""}]
for item in @data
# An item could be a box break which changes the last box, so
# re-set this after every item.
lastBox = boxes[boxes.length-1]
if typeof(item) is "string"
# Text.
# A message box break seems to always be followed by a
# newline character, but in this situation the newline
# doesn't affect the time the box text takes to scroll.
# So we won't count such a newline as a character for our
# purposes.
#
# Box break check: the latest box's text is empty.
# Action: Chop off the leading newline.
newlineAfterBoxBreak = \
item.charAt(0) is '\n' and lastBox.text is ""
if newlineAfterBoxBreak
item = item.slice(1)
lastBox.chars += item.length
lastBox.text += item
else
# Escape sequence.
# This function will add the escape sequence contents
# to the boxes structure.
MessageUtil.processEscapeSequence(
item, boxes, @id, argSet, messageCase
)
# At this point we've got text and chars covered, and pauseLength
# if applicable. Compute the box lengths.
for box in boxes
MessageUtil.computeBoxLength(box, argSet.langCode)
return boxes
frames: (argSet, messageCase) ->
boxes = @computeBoxes(argSet, messageCase)
frames = MessageUtil.messageFrames(boxes, @id, argSet.boxEndTimingError)
return frames
showFrameDetails: (argSet, messageCase) ->
$messageDetails = $('#message-details')
$messageDetails.empty()
# Display a Back button to make the route table viewable again
$backButton = $('<button>')
$backButton.text "Back"
$backButton.click MessageUtil.hideMessageDetails
$messageDetails.append $backButton
# Display the message id and argSet
$h3 = $('<h3>').text("#{@id}, #{argSet.display}")
$messageDetails.append $h3
# Make a box length explanations table
$table = $('<table>')
$tbody = $('<tbody>')
$table.append $tbody
$('#route-table-container').hide()
$messageDetails.show()
boxes = @computeBoxes(argSet, messageCase)
# Display box level frame details
for box in boxes
$tr = $('<tr>')
$tbody.append $tr
# Box text
$td = $('<td>')
$td.addClass 'box-text'
MessageUtil.boxTextDisplayHTML($td, box)
$tr.append $td
# Box length explanation
$td = $('<td>')
$td.addClass 'box-length-explanation'
MessageUtil.computeBoxLength(box, argSet.langCode, $td)
$tr.append $td
# Display message level frame details
MessageUtil.messageFrames(
boxes, @id, argSet.boxEndTimingError, $messageDetails
)
# Append box length explanations
$messageDetails.append $table
class Route
@numAndLevelRegex = /// ^
\d+ # Number
[\.|\)] # . or )
(.+) # 1 or more chars of anything
$ ///
@actionAndParensNoteRegex = /// ^
(.+) # 1 or more chars of anything
\( # Left parens
.+ # 1 or more chars of anything
\) # Right parens
$ ///
# 70 stars, 1 star, etc.
@starsReqRegex = /^(\d+) stars?$/
# Less than 70 stars, Less than 1 star, etc.
@lessThanStarsReqRegex = /^Less than (\d+) stars?$/
# 400 star bits, etc.
@starBitReqRegex = /^(\d+) star bits$/
isComplete: false
constructor: (text, category) ->
@actions = []
# Split text into lines
lines = Util.splitlines(text)
# First line = route name
@name = lines[0]
lines = lines[1..]
$('#route-status').empty()
for line in lines
line = line.trim()
if line is ""
# Blank line
continue
action = @lineToAction(line)
if not action
@addRouteStatus("Could not recognize as a level/action: " + line)
break
else if action is 'comment'
# Just a comment line in the text route; ignore it.
continue
@actions.push(action)
if category is "Any%"
@endItemName = "Bowser's Galaxy Reactor"
@endRequirements = []
else if category is "120 Star"
@endItemName = "Bowser's Galaxy Reactor"
@endRequirements = ["120 stars"]
addRouteStatus: (s) ->
$('#route-status').append(document.createTextNode(s))
$('#route-status').append(document.createElement('br'))
lineToAction: (line) ->
# Make item recognition non-case-sensitive
line = line.toLowerCase()
if line.startsWith '*'
# Assumed to be just a comment, e.g. "* Back to start of observatory"
return 'comment'
if line.startsWith '>'
# Assumed to be an action with an exact name, e.g. "> Luigi letter 2".
line = line.slice(1).trim()
# Check if line begins with a star number like "5." or "17)"
# If so, remove it
match = @constructor.numAndLevelRegex.exec(line)
if match
line = match[1].trim()
# Check if we have an alias match
if line of Action.aliases
return Action.aliases[line]
# Check if line ends with a parenthesized thing like "(skip cutscenes)"
# If so, remove it
match = @constructor.actionAndParensNoteRegex.exec(line)
if match
line = match[1].trim()
# Check again if we have an alias match
if line of Action.aliases
return Action.aliases[line]
# Check for just the star name
if line of Level.starNameLookup
return Level.starNameLookup[line]
# Check if there's a dash, and if so, see if we can find a
# galaxy+number - starname match like "Good Egg 1 - Dino Piranha".
# Either one will do, don't need both correct.
# (e.g. "Good Egg - Dino Piranha" should work fine too.)
# Try all the dashes if there's more than one.
indexOfDash = line.indexOf('-')
while indexOfDash isnt -1
possibleGalaxyAndNum = line.slice(0, indexOfDash).trim()
if possibleGalaxyAndNum of Action.aliases
return Action.aliases[possibleGalaxyAndNum]
possibleStarName = line.slice(indexOfDash+1).trim()
if possibleStarName of Level.starNameLookup
return Level.starNameLookup[possibleStarName]
indexOfDash = line.indexOf('-', indexOfDash+1)
# Tried everything we could think of
return null
fulfilledRequirement: (req, completedItemNames, starCount) ->
# Way 1 to satisfy requirement: req matches name of a completed action
if req in completedItemNames
return true
# Way 2: it's a >= stars req and we've got it
match = @constructor.starsReqRegex.exec(req)
if match
reqStars = Number(match[1].trim())
if starCount >= reqStars
return true
# Way 3: it's a < stars req and we've got it
match = @constructor.lessThanStarsReqRegex.exec(req)
if match
reqLessThanStars = Number(match[1].trim())
if starCount < reqLessThanStars
return true
# Way 4: it's a star bits req
# TODO: Actually check this. For now we have no way of checking possible
# or probable star bit count, so we skip the check.
match = @constructor.starBitReqRegex.exec(req)
if match
return true
return false
isEndOfRoute: (item, completedItemNames, starCount) ->
# If the run only ends on a particular route item, check for that
# route item
if @endItemName
if item.name isnt @endItemName
return false
# Check that other end requirements are met
for req in @endRequirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
return false
return true
checkAndAddEvents: () ->
# Add between-level events to the route.
@isComplete = false
@items = []
starCount = 0
greenStarCount = 0
expectedActionName = null
completedItemNames = []
# luigiStars goes up to 3: Good Egg L, Battlerock L, Honeyhive L
luigiStatus = {talkedAtGarage: false, luigiStars: 0, betweenStars: 0}
for action in @actions
# Check if we are expecting a specific action here at this point in
# the route.
if expectedActionName
if action.name isnt expectedActionName
s = "At this point the route must have: '" \
+ expectedActionName + "' but instead it has: '" \
+ action.name + "'"
@addRouteStatus(s)
expectedActionName = null
# Check requirements for this item.
for req in action.requirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
s = "'" + action.name + "' has an unfulfilled requirement: " + req
@addRouteStatus(s)
return
# Check special requirements for Luigi events.
if action.name is "Luigi letter 2"
if not (luigiStatus.luigiStars is 1 and luigiStatus.betweenStars >= 5)
s = "'" + action.name \
+ "' has an unfulfilled requirement: Must have 1 Luigi star and
5 in-between stars since that Luigi star. Current status: " \
+ luigiStatus.luigiStars.toString() + " Luigi star(s) and " \
+ luigiStatus.betweenStars.toString() + " in-between star(s)."
@addRouteStatus(s)
return
else if action.name is "Luigi letter 3"
if not (luigiStatus.luigiStars is 2 and luigiStatus.betweenStars >= 5)
s = "'" + action.name \
+ "' has an unfulfilled requirement: Must have 2 Luigi stars and
5 in-between stars since that Luigi star. Current status: " \
+ luigiStatus.luigiStars.toString() + " Luigi star(s) and " \
+ luigiStatus.betweenStars.toString() + " in-between star(s)."
@addRouteStatus(s)
return
# Add the action to the route.
followingItems = []
if action instanceof Level
if action.name in completedItemNames
# Duplicate star
@items.push {
item: action
starCount: null
}
else
starCount += 1
@items.push {
item: action
starCount: starCount
}
# Check for "x star(s)" triggers
if starCount is 1
starCountStr = "1 star"
else
starCountStr = "#{starCount} stars"
if starCountStr of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[starCountStr]...)
else
@items.push {
item: action
}
completedItemNames.push action.name
if @isEndOfRoute(action, completedItemNames, starCount)
@isComplete = true
return
# Update Green Star count if applicable
if action.name in ["PI:NAME:<NAME>END_PI L", "PI:NAME:<NAME>END_PI G", "PI:NAME:<NAME>END_PI"]
greenStarCount += 1
# Check for "x green star(s)" triggers
if greenStarCount is 1
starCountStr = "1 green star"
else
starCountStr = "#{greenStarCount} green stars"
if starCountStr of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[starCountStr]...)
# Update Luigi status if applicable
if action.name is "Talk to Luigi at Garage"
luigiStatus.talkedAtGarage = true
else if luigiStatus.talkedAtGarage and action instanceof Level
if action.name in ["Good Egg L", "Battlerock L", "Honeyhive L"]
luigiStatus.luigiStars += 1
luigiStatus.betweenStars = 0
else
luigiStatus.betweenStars += 1
# Check for Luigi letter 1 event
if luigiStatus.luigiStars is 0 and luigiStatus.betweenStars is 1
followingItems.push(Item.idLookup["Luigi letter 1"])
# Items triggered by this action specifically
if action.name of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[action.name]...)
while followingItems.length > 0
followingItem = followingItems.shift()
if followingItem instanceof Action
# By some special case, this following "event" is also considered
# an action of some sort. We'll go to the next iteration to process
# this action, and we'll make a note to check that this action is
# indeed the next item in the route.
expectedActionName = followingItem.name
continue
# Ensure all of this item's trigger requirements are met before
# adding the item. If the requirements aren't met, the item is not
# triggered.
reqFailed = false
for req in followingItem.requirements
if not @fulfilledRequirement(req, completedItemNames, starCount)
reqFailed = true
if reqFailed
continue
# Add the item to the route.
@items.push {
item: followingItem
}
completedItemNames.push followingItem.name
if @isEndOfRoute(followingItem, completedItemNames, starCount)
return
# Check if other items are triggered by this item
if followingItem.name of Item.followingItemsLookup
followingItems.push(Item.followingItemsLookup[followingItem.name]...)
makeTable: (argSets) ->
$tableContainer = $('#route-table-container')
$table = $('<table>')
$tableContainer.empty().append($table)
$thead = $('<thead>')
$tbody = $('<tbody>')
$table.append $thead
$table.append $tbody
$row = $('<tr>')
$thead.append $row
$row.append $('<th>').text(@name)
for argSet in argSets
$row.append $('<th>').text(argSet.display)
# Determine whether to use Mario or Luigi in star names by seeing if
# Mario or Luigi has more argSets. (If tied, it goes to Mario.)
characterCounts = {mario: 0, luigi: 0}
argSetCharacters = (argSet.character for argSet in argSets)
for character in argSetCharacters
characterCounts[character] += 1
if characterCounts['mario'] >= characterCounts['luigi']
preferredCharacter = 'mario'
else
preferredCharacter = 'luigi'
# Add route items to the table as rows.
textFrameTotals = (0 for argSet in argSets)
for itemObj in @items
item = itemObj.item
if itemObj.starCount
itemText = item.text(itemObj.starCount, preferredCharacter)
else
itemText = item.text()
$row = $('<tr>')
$tbody.append $row
$row.addClass 'route-item'
# Click on a route item row -> show a frames breakdown.
#
# Currying a class function directly doesn't work,
# so we use an intermediate function.
f = (item_, argSets_) -> item_.showFrameDetails(argSets_)
$row.click(Util.curry(f, item, argSets))
# Item name cell
$cell = $('<td>')
$cell.text itemText
$cell.addClass item.nameCellClass
$row.append $cell
for argSet, index in argSets
frames = item.frames argSet
# Frame count cell for each argSet
$cell = $('<td>')
$cell.text frames
$row.append $cell
textFrameTotals[index] += frames
if not @isComplete
# If the route isn't complete, don't do any totals.
return
# Add frame-totals row.
$totalsRow = $('<tr>')
$tbody.append $totalsRow
$cell = $('<td>').text "Total of relative text times"
$totalsRow.append $cell
for total in textFrameTotals
$cell = $('<td>').text total
$totalsRow.append $cell
# Add differences column(s) and summary sentence
# if there are exactly two argSets.
if argSets.length is 2
# Header cells
$headerRow = $thead.find('tr')
$cell = $('<th>').text("Diff (f)")
$headerRow.append $cell
$cell = $('<th>').text("Diff (s)")
$headerRow.append $cell
# Data cells
$rows = $tbody.find('tr')
$rows.each( (_, row) =>
cellTexts = ($(cell).text() for cell in $(row).find('td'))
frameDiff = Number(cellTexts[1]) - Number(cellTexts[2])
# Frames difference
$cell = $('<td>').text frameDiff
$(row).append $cell
# Seconds difference
$cell = $('<td>').text (frameDiff/(60/1.001)).toFixed(2)
$(row).append $cell
)
# Summary sentence
secondsDiff = $totalsRow.find('td')[4].textContent
if secondsDiff.charAt(0) is '-'
# Negative diff
summary = "#{argSets[0].display} is #{secondsDiff.slice(1)} seconds
faster than #{argSets[1].display} for this route"
else
# Positive diff
summary = "#{argSets[1].display} is #{secondsDiff} seconds
faster than #{argSets[0].display} for this route"
$('#route-status').append $('<h3>').text summary
determineArgSets = (languageLookup) ->
# Build sets of text-frame-counting params/arguments from the fields
argSets = []
for set in ['set1', 'set2']
argSet = {}
for fieldName in ['langCode', 'character', 'boxEndTimingError']
$field = $("##{set}-#{fieldName}")
argSet[fieldName] = $field.val()
argSet.boxEndTimingError = Number(argSet.boxEndTimingError)
argSets.push argSet
# Figure out suitable display names based on the argSets' differences
if argSets[0].langCode isnt argSets[1].langCode
lang1 = languageLookup[argSets[0].langCode]
lang2 = languageLookup[argSets[1].langCode]
if lang1.region isnt lang2.region
# Language / region
argSets[0].display = lang1.region
argSets[1].display = lang2.region
else
# Language / language name
argSets[0].display = lang1.language
argSets[1].display = lang2.language
else if argSets[0].character isnt argSets[1].character
# Character
char = argSets[0].character
argSets[0].display = char.slice(0,1).toUpperCase() + char.slice(1)
char = argSets[1].character
argSets[1].display = char.slice(0,1).toUpperCase() + char.slice(1)
else
# Box end timing error
argSets[0].display = argSets[0].boxEndTimingError.toString() + " BTE"
argSets[1].display = argSets[1].boxEndTimingError.toString() + " BTE"
return argSets
addLanguages = (langCodes, callbackAfterInitAllLanguages) ->
# If all requested languages are already loaded, call the passed callback
# and we're done
allLanguagesLoaded = langCodes.every(
(code) -> return (window.messages? and code of window.messages)
)
if allLanguagesLoaded
do callbackAfterInitAllLanguages
return
# Else, we must load at least 1 language first
for langCode in langCodes
# If we've already loaded this language, move onto the next one
if window.messages? and langCode of window.messages
continue
# Callback that runs when this language is loaded
cb = (langCode_, langCodes_, callbackAfterInitAllLanguages_) ->
# Initialize messages for this language
for own messageId, data of window.messages[langCode_]
new Message(messageId, langCode_, data)
# Check if ALL requested languages are loaded (not just this one)
allLanguagesLoaded = langCodes_.every(
(code) -> return (code of window.messages)
)
if allLanguagesLoaded
# Call the passed callback
do callbackAfterInitAllLanguages_
# Load this language
callbackAfterLoadingLanguage = Util.curry(
cb, langCode, langCodes, callbackAfterInitAllLanguages
)
Util.readServerJSFile(
"js/messages/#{langCode}.js", callbackAfterLoadingLanguage
)
class Main
routeTextChanged: false
init: (itemDetails, itemMessages) ->
callback = Util.curry(@init2, itemDetails, itemMessages)
addLanguages(['usenglish'], callback)
init2: (itemDetails, itemMessages) ->
# Initialize possible route items.
for own itemKey, details of itemDetails
args = [itemKey, details, itemMessages[itemKey] ? []]
if details.type is 'Level'
new Level(args...)
else if details.type is 'Action'
new Action(args...)
else if details.type is 'Event'
new Event(args...)
else
console.log(
"Invalid item type: " + details.type
)
# Add text aliases for possible route items.
Action.addAliases()
# Get info on the available languages.
languages = []
languageLookup = {}
for own langCode, _ of messageLookup.languageSpeeds
# The first 2 chars should be the region, rest should be language.
obj = {
code: langCode
region: langCode.slice(0,2).toUpperCase()
language: langCode.slice(2,3).toUpperCase() + langCode.slice(3)
}
obj.display = "#{obj.language} (#{obj.region})"
languages.push obj
languageLookup[langCode] = obj
# The languages array will serve as a way to sort the languages.
sortFunc = (a,b) ->
if a.display < b.display
return -1
else if a.display > b.display
return 1
else
return 0
languages.sort(sortFunc)
# Initialize the language dropdowns
for set in ['set1', 'set2']
$select = $("##{set}-langCode")
# Fill with the ordered languages.
for lang in languages
$select.append(
$('<option>').attr('value', lang.code).text(lang.display)
)
# Initialize with US English for the first, JP Japanese for the second.
if set is 'set1'
$select.val('usenglish')
else
$select.val('jpjapanese')
# Initialize the boxEndTimingError dropdowns
for set in ['set1', 'set2']
$select = $("##{set}-boxEndTimingError")
for num in [0..15]
value = num.toString()
text = num.toString()
if text is "0"
text = "0 (TAS)"
$select.append $('<option>').attr('value', value).text(text)
# Initialize the value.
$select.val("10")
# Initialize the route processing button
document.getElementById('route-button').onclick = (event) =>
$('#route-status').empty()
routeText = document.getElementById('route-textarea').value
category = $('#route-category').val()
route = new Route(routeText, category)
route.checkAndAddEvents()
if not route.isComplete
route.addRouteStatus("Route is incomplete!")
argSets = determineArgSets(languageLookup)
# Get the required languages, then make the route table
callback = () -> route.makeTable argSets
addLanguages((argSet.langCode for argSet in argSets), callback)
# Initialize help button(s)
$('.help-button').each( () ->
buttonIdRegex = /^(.+)-button$/
result = buttonIdRegex.exec(this.id)
helpTextId = result[1]
# When this help button is clicked, open the corresponding
# help text in a modal window.
clickCallback = (helpTextId_, helpButtonE) ->
$helpText = $('#'+helpTextId_)
$helpText.dialog({
modal: true
width: 500
height: 600
position: {
my: "center top"
at: "center bottom"
of: helpButtonE
}
})
# NOTE: The below only applies to the route textarea help, so if
# there's another help button at some point, then this code needs
# to be moved somewhere else.
# Part of the help text involves listing all the non-level actions.
# The first time this help text is opened, fill the list.
$actionList = $('#action-list')
if $actionList.is(':empty')
for id, item of Item.idLookup
# Ensure we're listing non-level actions.
if (item instanceof Action) and not (item instanceof Level)
$actionList.append(
$('<li>').append $('<code>').text('> '+item.name)
)
# Make the dialog's scroll position start at the top. If we don't do
# this, then it starts where the in-dialog button is, for some reason.
$helpText.scrollTop(0)
$(this).click(
Util.curry(clickCallback, helpTextId, this)
)
)
# Initialize fill-with-sample-route buttons
applySampleRoute = (categoryValue, sampleRouteFilename) =>
if @routeTextChanged
message = "This'll overwrite the current route with the" \
+ " Sample " + categoryValue + " route. Are you sure?"
# If user chooses yes, proceed; if chooses no, return
if not confirm(message)
return
# Reset the "route changed" state
@routeTextChanged = false
$('#route-category').val(categoryValue)
callback = (text) ->
document.getElementById('route-textarea').value = text
Util.readServerTextFile(sampleRouteFilename, callback)
$('#sample-any-route-button').click(
Util.curry(applySampleRoute, "Any%", "samplerouteany.txt")
)
$('#sample-120-route-button').click(
Util.curry(applySampleRoute, "120 Star", "sampleroute120.txt")
)
# Watch for route text changes via typing.
# (Precisely: The textarea lost focus and its value changed
# since gaining focus.)
$('#route-textarea').change( () =>
@routeTextChanged = true
)
window.main = new Main |
[
{
"context": ", value of disrObj.DISRUPTIONS\n if key == 'DISRUPTION'\n for disrObj in value\n ",
"end": 12851,
"score": 0.7300949096679688,
"start": 12841,
"tag": "KEY",
"value": "DISRUPTION"
}
] | message-sender.coffee | Mankro/navigator-push-server | 1 | #!/usr/bin/env coffee
xml2js = require 'xml2js'
http = require 'http'
https = require 'https'
{dbConnect, Subscription, SentMessageHash} = require './db'
NEWS_URL = 'https://www.hsl.fi/en/newsApi/all'
DISRUPTIONS_URL = 'http://www.poikkeusinfo.fi/xml/v2/en'
PUSH_URL = 'https://android.googleapis.com/gcm/send'
PUSH_HOST = 'android.googleapis.com'
PUSH_URL_PATH = '/gcm/send'
# The interval in milliseconds for fetching updates from HSL servers.
UPDATE_INTERVAL = process.env.UPDATE_INTERVAL ? 1000*60
# API key from Google (Don't save this in the public repo!)
GCM_PUSH_API_KEY =
process.env.GCM_PUSH_API_KEY ?
try
require('./secret_keys').GCM_PUSH_API_KEY
catch
console.error("""
Google Cloud Messaging API key not set. The key can be
given in the environment variable GCM_PUSH_API_KEY or in a
file named secret_keys.js as follows:
module.exports = { GCM_PUSH_API_KEY: "..." };
The file MUST NOT be stored in a public repository!
""")
process.exit 1
# Push a message to the client using Google Cloud Messaging (GCM).
# Parameter msg is a plain JS object with keys:
# clientId, message, lines, category, validThrough
pushToClient = (msg, retryTimeout = 1000) ->
# The message is only pushed to the client if it has not been yet pushed earlier
SentMessageHash.storeHash msg, (err, msgHashDoc) ->
if err
console.error err
else if not msgHashDoc? # if null, the message has already been sent
console.log "GCM request already sent, skipping: %j", msg
else
# Send HTTP POST request to the GCM push server that will
# then send it to the client
# http://developer.android.com/google/gcm/server-ref.html
options =
hostname: PUSH_HOST
path: PUSH_URL_PATH
method: 'POST'
headers:
'Authorization': "key=#{ GCM_PUSH_API_KEY }"
'Content-Type': 'application/json'
timeTillEnd =
if msg.validThrough?
(msg.validThrough.getTime() - new Date().getTime()) / 1000
else
0
timeToLive =
if timeTillEnd > 0
# set time_to_live till the end of the journey in seconds
timeTillEnd
else
60 * 60 * 24 # 24 h
postData =
registration_ids: [msg.clientId] # The clientId is used by GCM to identify the client device.
time_to_live: timeToLive
data: # payload to client, data values should be strings
title: "Traffic disruption"
message: msg.message
disruption_lines: msg.lines.join() # array to comma-separated string
disruption_category: msg.category
console.log "sending GCM request: %j", postData
request = https.request options, (response) ->
# response from GCM push server
response.setEncoding 'utf8'
responseData = ''
# gather the whole response body into one string before parsing JSON
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
try
if response.statusCode == 401
throw "GCM auth error 401"
else if response.statusCode == 400
throw "GCM bad request JSON error"
else if 500 <= response.statusCode <= 599
# GCM server error, retry later
# remove the message hash before trying to push again
msgHashDoc.remove (err) ->
console.error err if err
timeout =
if 'retry-after' of response.headers
parseHttpRetryAfter response.headers['retry-after']
else
retryTimeout
scheduleMessagePush msg, timeout
else if response.statusCode == 200
# success, but nonetheless there may be
# errors in delivering messages to clients
try
jsonObj = JSON.parse responseData
catch
throw "GCM response JSON parse error"
if jsonObj.failure > 0 or jsonObj.canonical_ids > 0
# there were some problems
for resObj in jsonObj.results
if resObj.message_id? and resObj.registration_id?
# must replace the client registration id with
# the new resObj id (canonical id)
console.log "GCM client id changed. Updating database."
# modify database
Subscription.update { clientId: msg.clientId },
{ clientId: resObj.registration_id },
(err) -> console.error err if err
SentMessageHash.update { clientId: msg.clientId },
{ clientId: resObj.registration_id },
(err) -> console.error err if err
# no need to resend, GCM just informed us
# that the registration id was changed
else if resObj.error?
if resObj.error == 'Unavailable'
# GCM server unavailable, retry
# remove the message hash document before trying to push it again
msgHashDoc.remove (err) ->
console.error err if err
timeout =
if 'retry-after' of response.headers
parseHttpRetryAfter response.headers['retry-after']
else
retryTimeout
scheduleMessagePush msg, timeout
else if resObj.error == 'NotRegistered'
Subscription.remove { clientId: msg.clientId },
(err) -> console.error err if err
throw "GCM client not registered,
removing client from database"
else
throw "GCM response error: #{ resObj.error }"
else
throw "unknown GCM response status code: #{response.statusCode}"
catch errMsg
console.error "pushToClient: #{errMsg}"
msgHashDoc.remove (err) -> console.error err if err
return
response.on 'error', (err) -> console.error "pushToClient: #{err}"
request.on 'error', (err) -> console.error "pushToClient: #{err}"
# write data to request body
request.write JSON.stringify postData
request.end()
# Find clients that are using lines (given as array) in the area.
# Push notification messages to the affected clients.
findClients = (lines, areaField, message, disrStartTime, disrEndTime) ->
createMessages = (err, clientIds) ->
if err
console.error err
else
for id in clientIds
pushToClient
clientId: id
message: message # human-readable text
lines: lines
category: areaField
validThrough: disrEndTime
return
criteria = {}
criteria.category = areaField if areaField != 'all'
# if lines[0] == 'all', find clients that are using any line in the area
criteria.line = { $in: lines } if lines[0] != 'all' # add lines criteria if searching only for specific lines
criteria.startTime = { $lt: disrEndTime } if disrEndTime
criteria.endTime = { $gt: disrStartTime } if disrStartTime
Subscription.distinct 'clientId', criteria, createMessages
# Set a message push to occur in millisecs time. The push message will be
# sent to the GCM servers but it is still up to them to decide when
# the message is really sent to client devices.
scheduleMessagePush = (msg, inmillisecs) ->
action = ->
# remove this timeout from list
i = scheduledMessagePushes.indexOf timeout
scheduledMessagePushes.splice(i, 1) if i >= 0
# double the timeout for the possible next retry after this one
# (exponential back-off)
pushToClient msg, 2 * inmillisecs
timeout = setTimeout action, inmillisecs
scheduledMessagePushes.push timeout
scheduledMessagePushes = []
# HTTP retry-after header may be a date string or a decimal integer in seconds.
# Return the timeout in milliseconds from this moment.
parseHttpRetryAfter = (retryAfterValue) ->
if isNaN retryAfterValue
# header contains a date string,
# get time in milliseconds from this moment to that moment
timeout = new Date(retryAfterValue).getTime() - new Date().getTime()
if timeout > 0
timeout
else
5000 # arbitrary default if retry-after header date is in the past
else
# header is integer in seconds
1000 * parseInt retryAfterValue, 10
# Return true if daylight saving is currently in use.
isDstOn = () ->
# Modified from http://javascript.about.com/library/bldst.htm
dateStdTimezoneOffset = (date) ->
jan = new Date date.getFullYear(), 0, 1
jul = new Date date.getFullYear(), 6, 1
Math.max jan.getTimezoneOffset(), jul.getTimezoneOffset()
dateDst = (date) ->
date.getTimezoneOffset() < dateStdTimezoneOffset(date)
dateDst new Date()
# mapping from HSL news API Main category values to the categories we use here
NEWS_API_CATEGORIES =
'Helsinki internal bus': 'helsinkiInternal'
'Espoo internal bus': 'espooInternal'
'Vantaa internal bus': 'vantaaInternal'
'Regional': 'regional'
'Regional night line': 'regional'
'Tram': 'tram'
'Commuter train': 'train'
'Ferry': 'ferry'
'U line': 'Uline'
'Sipoo internal line': 'sipooInternal'
'Kerava internal bus': 'keravaInternal'
# newsObj is the JS object parsed from the HSL news response
parseNewsResponse = (newsObj) ->
for node in newsObj.nodes
node = node.node
lines = node.Lines.split ','
cat = node['Main category']
# the news do not contain easily parsable dates for the validity period
if cat of NEWS_API_CATEGORIES
findClients lines, NEWS_API_CATEGORIES[cat], node.title
else
console.log "parseNewsResponse: unknown Main category: #{ cat }"
return
# mapping from poikkeusinfo linetypes to the categories we use here
DISRUPTION_API_LINETYPES =
'1': 'helsinkiInternal'
'2': 'tram'
'3': 'espooInternal'
'4': 'vantaaInternal'
'5': 'regional'
'6': 'metro'
'7': 'ferry'
'12': 'train' # commuter trains
#'14': 'all' # handled separately
'36': 'kirkkonummiInternal'
'39': 'keravaInternal'
# Parse XML response from poikkeusinfo server.
# Parameter disrObj is a JS object parsed from XML.
parseDisruptionsResponse = (disrObj) ->
# HSL API description in Finnish (no pdf in English)
# http://developer.reittiopas.fi/media/Poikkeusinfo_XML_rajapinta_V2_2_01.pdf
for key, value of disrObj.DISRUPTIONS
if key == 'DISRUPTION'
for disrObj in value
# disrObj is one disruption message (one DISRUPTION element from the original XML)
isValid = false
disrStartTime = null
disrEndTime = null
message = ''
linesByArea = {
# these keys must match the values of the object DISRUPTION_API_LINETYPES
helsinkiInternal: []
espooInternal: []
vantaaInternal: []
regional: []
tram: []
train: []
ferry: []
Uline: []
metro: []
kirkkonummiInternal: []
keravaInternal: []
}
for dkey, dval of disrObj
if dkey == 'VALIDITY'
# the message may be active or cancelled
isValid = true if dval[0]['$'].status == '1'
# the HSL poikkeusinfo server does not have timezones in the date values,
# so we manually set the Finnish timezone here
timezone =
if isDstOn()
'+03:00'
else
'+02:00'
disrStartTime = new Date(dval[0]['$'].from + timezone)
disrEndTime = new Date(dval[0]['$'].to + timezone)
else if dkey == 'INFO'
# human-readable description
englishElemIdx = 0
for textElem, elemIdx in dval[0]['TEXT']
# language attributes fi, se, en
englishElemIdx = elemIdx if textElem['$'].lang == 'en'
message = dval[0]['TEXT'][englishElemIdx]['_'].trim()
# key '_' means the XML element content (normal text)
else if dkey == 'TARGETS'
targets = dval[0] # only one TARGETS element
# TARGETS contains either a LINETYPE or 1-N LINE elements
if targets.LINETYPE?
# all lines within the area/scope/type affected
# assume there is only one LINETYPE element
# linetype numeric id that maps to regions/categories
linetype = targets.LINETYPE[0]['$'].id
if linetype of DISRUPTION_API_LINETYPES
linesByArea[DISRUPTION_API_LINETYPES[linetype]].push 'all'
else if linetype == '14' # all areas
for area, lines of linesByArea
lines.push 'all'
else if targets.LINE?
# list of line elements that specify single affected lines
# parsed XML: $ for attributes, _ for textual element content
for lineElem in targets.LINE
if lineElem['$'].linetype of DISRUPTION_API_LINETYPES
linesByArea[DISRUPTION_API_LINETYPES[lineElem['$'].linetype]].push lineElem['_']
else if lineElem['$'].linetype == '14' # all areas
for area, lines of linesByArea
lines.push lineElem['_']
if isValid
for area, lines of linesByArea
findClients lines, area, message, disrStartTime, disrEndTime if lines.length > 0
return
# Function that fetches disruption news updates from HSL servers, parses them
# and searches the database for affected clients. The clients are sent
# push notifications if necessary. The same message is only sent once to a client.
update = ->
console.log "Fetching news and disruptions updates"
# Abort all scheduled GCM message push retry attempts so that the
# number of requests doesn't keep growing if GCM server is down
for timeout in scheduledMessagePushes
clearTimeout timeout
scheduledMessagePushes = []
request = https.request NEWS_URL, (response) ->
# response from HSL server
response.setEncoding 'utf8'
responseData = ''
# gather the whole response body into one string before parsing JSON
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
# object with key nodes, its value is an array, array contains objects
# with key node, and that is an object with keys title, body, Lines, Main category
try
jsonObj = JSON.parse responseData
parseNewsResponse jsonObj
catch error
console.error "JSON parse error in news response: #{ error }"
response.on 'error', (err) -> console.error err
request.on 'error', (err) -> console.error err
request.end()
requestDisr = http.request DISRUPTIONS_URL, (response) ->
# response from HSL server
response.setEncoding 'utf8' # 'ISO-8859-1' not supported
responseData = ''
# gather the whole response body into one string before parsing XML
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
xml2js.parseString responseData, (err, result) ->
if err
console.error "Error in parsing XML response from #{ DISRUPTIONS_URL }: " + err
else
if not result.DISRUPTIONS.INFO?
# disruptions exist
parseDisruptionsResponse result
response.on 'error', (err) -> console.error err
requestDisr.on 'error', (err) -> console.error err
requestDisr.end()
# Send a test message to all registered clients. Note that messages
# identical to any previously sent message are not sent to clients
# that have already received the message.
sendTestMessage = (message, lines, category) ->
findClients lines ? ['all'], category ? 'all', message
start = ->
console.log "Starting update fetcher, update interval #{ UPDATE_INTERVAL / 1000 }s"
process.nextTick update
setInterval update, UPDATE_INTERVAL
module.exports =
start: start
sendTestMessage: sendTestMessage
if require.main == module
dbConnect()
.onFulfill(start)
.onReject ->
process.exit 2
| 24136 | #!/usr/bin/env coffee
xml2js = require 'xml2js'
http = require 'http'
https = require 'https'
{dbConnect, Subscription, SentMessageHash} = require './db'
NEWS_URL = 'https://www.hsl.fi/en/newsApi/all'
DISRUPTIONS_URL = 'http://www.poikkeusinfo.fi/xml/v2/en'
PUSH_URL = 'https://android.googleapis.com/gcm/send'
PUSH_HOST = 'android.googleapis.com'
PUSH_URL_PATH = '/gcm/send'
# The interval in milliseconds for fetching updates from HSL servers.
UPDATE_INTERVAL = process.env.UPDATE_INTERVAL ? 1000*60
# API key from Google (Don't save this in the public repo!)
GCM_PUSH_API_KEY =
process.env.GCM_PUSH_API_KEY ?
try
require('./secret_keys').GCM_PUSH_API_KEY
catch
console.error("""
Google Cloud Messaging API key not set. The key can be
given in the environment variable GCM_PUSH_API_KEY or in a
file named secret_keys.js as follows:
module.exports = { GCM_PUSH_API_KEY: "..." };
The file MUST NOT be stored in a public repository!
""")
process.exit 1
# Push a message to the client using Google Cloud Messaging (GCM).
# Parameter msg is a plain JS object with keys:
# clientId, message, lines, category, validThrough
pushToClient = (msg, retryTimeout = 1000) ->
# The message is only pushed to the client if it has not been yet pushed earlier
SentMessageHash.storeHash msg, (err, msgHashDoc) ->
if err
console.error err
else if not msgHashDoc? # if null, the message has already been sent
console.log "GCM request already sent, skipping: %j", msg
else
# Send HTTP POST request to the GCM push server that will
# then send it to the client
# http://developer.android.com/google/gcm/server-ref.html
options =
hostname: PUSH_HOST
path: PUSH_URL_PATH
method: 'POST'
headers:
'Authorization': "key=#{ GCM_PUSH_API_KEY }"
'Content-Type': 'application/json'
timeTillEnd =
if msg.validThrough?
(msg.validThrough.getTime() - new Date().getTime()) / 1000
else
0
timeToLive =
if timeTillEnd > 0
# set time_to_live till the end of the journey in seconds
timeTillEnd
else
60 * 60 * 24 # 24 h
postData =
registration_ids: [msg.clientId] # The clientId is used by GCM to identify the client device.
time_to_live: timeToLive
data: # payload to client, data values should be strings
title: "Traffic disruption"
message: msg.message
disruption_lines: msg.lines.join() # array to comma-separated string
disruption_category: msg.category
console.log "sending GCM request: %j", postData
request = https.request options, (response) ->
# response from GCM push server
response.setEncoding 'utf8'
responseData = ''
# gather the whole response body into one string before parsing JSON
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
try
if response.statusCode == 401
throw "GCM auth error 401"
else if response.statusCode == 400
throw "GCM bad request JSON error"
else if 500 <= response.statusCode <= 599
# GCM server error, retry later
# remove the message hash before trying to push again
msgHashDoc.remove (err) ->
console.error err if err
timeout =
if 'retry-after' of response.headers
parseHttpRetryAfter response.headers['retry-after']
else
retryTimeout
scheduleMessagePush msg, timeout
else if response.statusCode == 200
# success, but nonetheless there may be
# errors in delivering messages to clients
try
jsonObj = JSON.parse responseData
catch
throw "GCM response JSON parse error"
if jsonObj.failure > 0 or jsonObj.canonical_ids > 0
# there were some problems
for resObj in jsonObj.results
if resObj.message_id? and resObj.registration_id?
# must replace the client registration id with
# the new resObj id (canonical id)
console.log "GCM client id changed. Updating database."
# modify database
Subscription.update { clientId: msg.clientId },
{ clientId: resObj.registration_id },
(err) -> console.error err if err
SentMessageHash.update { clientId: msg.clientId },
{ clientId: resObj.registration_id },
(err) -> console.error err if err
# no need to resend, GCM just informed us
# that the registration id was changed
else if resObj.error?
if resObj.error == 'Unavailable'
# GCM server unavailable, retry
# remove the message hash document before trying to push it again
msgHashDoc.remove (err) ->
console.error err if err
timeout =
if 'retry-after' of response.headers
parseHttpRetryAfter response.headers['retry-after']
else
retryTimeout
scheduleMessagePush msg, timeout
else if resObj.error == 'NotRegistered'
Subscription.remove { clientId: msg.clientId },
(err) -> console.error err if err
throw "GCM client not registered,
removing client from database"
else
throw "GCM response error: #{ resObj.error }"
else
throw "unknown GCM response status code: #{response.statusCode}"
catch errMsg
console.error "pushToClient: #{errMsg}"
msgHashDoc.remove (err) -> console.error err if err
return
response.on 'error', (err) -> console.error "pushToClient: #{err}"
request.on 'error', (err) -> console.error "pushToClient: #{err}"
# write data to request body
request.write JSON.stringify postData
request.end()
# Find clients that are using lines (given as array) in the area.
# Push notification messages to the affected clients.
findClients = (lines, areaField, message, disrStartTime, disrEndTime) ->
createMessages = (err, clientIds) ->
if err
console.error err
else
for id in clientIds
pushToClient
clientId: id
message: message # human-readable text
lines: lines
category: areaField
validThrough: disrEndTime
return
criteria = {}
criteria.category = areaField if areaField != 'all'
# if lines[0] == 'all', find clients that are using any line in the area
criteria.line = { $in: lines } if lines[0] != 'all' # add lines criteria if searching only for specific lines
criteria.startTime = { $lt: disrEndTime } if disrEndTime
criteria.endTime = { $gt: disrStartTime } if disrStartTime
Subscription.distinct 'clientId', criteria, createMessages
# Set a message push to occur in millisecs time. The push message will be
# sent to the GCM servers but it is still up to them to decide when
# the message is really sent to client devices.
scheduleMessagePush = (msg, inmillisecs) ->
action = ->
# remove this timeout from list
i = scheduledMessagePushes.indexOf timeout
scheduledMessagePushes.splice(i, 1) if i >= 0
# double the timeout for the possible next retry after this one
# (exponential back-off)
pushToClient msg, 2 * inmillisecs
timeout = setTimeout action, inmillisecs
scheduledMessagePushes.push timeout
scheduledMessagePushes = []
# HTTP retry-after header may be a date string or a decimal integer in seconds.
# Return the timeout in milliseconds from this moment.
parseHttpRetryAfter = (retryAfterValue) ->
if isNaN retryAfterValue
# header contains a date string,
# get time in milliseconds from this moment to that moment
timeout = new Date(retryAfterValue).getTime() - new Date().getTime()
if timeout > 0
timeout
else
5000 # arbitrary default if retry-after header date is in the past
else
# header is integer in seconds
1000 * parseInt retryAfterValue, 10
# Return true if daylight saving is currently in use.
isDstOn = () ->
# Modified from http://javascript.about.com/library/bldst.htm
dateStdTimezoneOffset = (date) ->
jan = new Date date.getFullYear(), 0, 1
jul = new Date date.getFullYear(), 6, 1
Math.max jan.getTimezoneOffset(), jul.getTimezoneOffset()
dateDst = (date) ->
date.getTimezoneOffset() < dateStdTimezoneOffset(date)
dateDst new Date()
# mapping from HSL news API Main category values to the categories we use here
NEWS_API_CATEGORIES =
'Helsinki internal bus': 'helsinkiInternal'
'Espoo internal bus': 'espooInternal'
'Vantaa internal bus': 'vantaaInternal'
'Regional': 'regional'
'Regional night line': 'regional'
'Tram': 'tram'
'Commuter train': 'train'
'Ferry': 'ferry'
'U line': 'Uline'
'Sipoo internal line': 'sipooInternal'
'Kerava internal bus': 'keravaInternal'
# newsObj is the JS object parsed from the HSL news response
parseNewsResponse = (newsObj) ->
for node in newsObj.nodes
node = node.node
lines = node.Lines.split ','
cat = node['Main category']
# the news do not contain easily parsable dates for the validity period
if cat of NEWS_API_CATEGORIES
findClients lines, NEWS_API_CATEGORIES[cat], node.title
else
console.log "parseNewsResponse: unknown Main category: #{ cat }"
return
# mapping from poikkeusinfo linetypes to the categories we use here
DISRUPTION_API_LINETYPES =
'1': 'helsinkiInternal'
'2': 'tram'
'3': 'espooInternal'
'4': 'vantaaInternal'
'5': 'regional'
'6': 'metro'
'7': 'ferry'
'12': 'train' # commuter trains
#'14': 'all' # handled separately
'36': 'kirkkonummiInternal'
'39': 'keravaInternal'
# Parse XML response from poikkeusinfo server.
# Parameter disrObj is a JS object parsed from XML.
parseDisruptionsResponse = (disrObj) ->
# HSL API description in Finnish (no pdf in English)
# http://developer.reittiopas.fi/media/Poikkeusinfo_XML_rajapinta_V2_2_01.pdf
for key, value of disrObj.DISRUPTIONS
if key == '<KEY>'
for disrObj in value
# disrObj is one disruption message (one DISRUPTION element from the original XML)
isValid = false
disrStartTime = null
disrEndTime = null
message = ''
linesByArea = {
# these keys must match the values of the object DISRUPTION_API_LINETYPES
helsinkiInternal: []
espooInternal: []
vantaaInternal: []
regional: []
tram: []
train: []
ferry: []
Uline: []
metro: []
kirkkonummiInternal: []
keravaInternal: []
}
for dkey, dval of disrObj
if dkey == 'VALIDITY'
# the message may be active or cancelled
isValid = true if dval[0]['$'].status == '1'
# the HSL poikkeusinfo server does not have timezones in the date values,
# so we manually set the Finnish timezone here
timezone =
if isDstOn()
'+03:00'
else
'+02:00'
disrStartTime = new Date(dval[0]['$'].from + timezone)
disrEndTime = new Date(dval[0]['$'].to + timezone)
else if dkey == 'INFO'
# human-readable description
englishElemIdx = 0
for textElem, elemIdx in dval[0]['TEXT']
# language attributes fi, se, en
englishElemIdx = elemIdx if textElem['$'].lang == 'en'
message = dval[0]['TEXT'][englishElemIdx]['_'].trim()
# key '_' means the XML element content (normal text)
else if dkey == 'TARGETS'
targets = dval[0] # only one TARGETS element
# TARGETS contains either a LINETYPE or 1-N LINE elements
if targets.LINETYPE?
# all lines within the area/scope/type affected
# assume there is only one LINETYPE element
# linetype numeric id that maps to regions/categories
linetype = targets.LINETYPE[0]['$'].id
if linetype of DISRUPTION_API_LINETYPES
linesByArea[DISRUPTION_API_LINETYPES[linetype]].push 'all'
else if linetype == '14' # all areas
for area, lines of linesByArea
lines.push 'all'
else if targets.LINE?
# list of line elements that specify single affected lines
# parsed XML: $ for attributes, _ for textual element content
for lineElem in targets.LINE
if lineElem['$'].linetype of DISRUPTION_API_LINETYPES
linesByArea[DISRUPTION_API_LINETYPES[lineElem['$'].linetype]].push lineElem['_']
else if lineElem['$'].linetype == '14' # all areas
for area, lines of linesByArea
lines.push lineElem['_']
if isValid
for area, lines of linesByArea
findClients lines, area, message, disrStartTime, disrEndTime if lines.length > 0
return
# Function that fetches disruption news updates from HSL servers, parses them
# and searches the database for affected clients. The clients are sent
# push notifications if necessary. The same message is only sent once to a client.
update = ->
console.log "Fetching news and disruptions updates"
# Abort all scheduled GCM message push retry attempts so that the
# number of requests doesn't keep growing if GCM server is down
for timeout in scheduledMessagePushes
clearTimeout timeout
scheduledMessagePushes = []
request = https.request NEWS_URL, (response) ->
# response from HSL server
response.setEncoding 'utf8'
responseData = ''
# gather the whole response body into one string before parsing JSON
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
# object with key nodes, its value is an array, array contains objects
# with key node, and that is an object with keys title, body, Lines, Main category
try
jsonObj = JSON.parse responseData
parseNewsResponse jsonObj
catch error
console.error "JSON parse error in news response: #{ error }"
response.on 'error', (err) -> console.error err
request.on 'error', (err) -> console.error err
request.end()
requestDisr = http.request DISRUPTIONS_URL, (response) ->
# response from HSL server
response.setEncoding 'utf8' # 'ISO-8859-1' not supported
responseData = ''
# gather the whole response body into one string before parsing XML
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
xml2js.parseString responseData, (err, result) ->
if err
console.error "Error in parsing XML response from #{ DISRUPTIONS_URL }: " + err
else
if not result.DISRUPTIONS.INFO?
# disruptions exist
parseDisruptionsResponse result
response.on 'error', (err) -> console.error err
requestDisr.on 'error', (err) -> console.error err
requestDisr.end()
# Send a test message to all registered clients. Note that messages
# identical to any previously sent message are not sent to clients
# that have already received the message.
sendTestMessage = (message, lines, category) ->
findClients lines ? ['all'], category ? 'all', message
start = ->
console.log "Starting update fetcher, update interval #{ UPDATE_INTERVAL / 1000 }s"
process.nextTick update
setInterval update, UPDATE_INTERVAL
module.exports =
start: start
sendTestMessage: sendTestMessage
if require.main == module
dbConnect()
.onFulfill(start)
.onReject ->
process.exit 2
| true | #!/usr/bin/env coffee
xml2js = require 'xml2js'
http = require 'http'
https = require 'https'
{dbConnect, Subscription, SentMessageHash} = require './db'
NEWS_URL = 'https://www.hsl.fi/en/newsApi/all'
DISRUPTIONS_URL = 'http://www.poikkeusinfo.fi/xml/v2/en'
PUSH_URL = 'https://android.googleapis.com/gcm/send'
PUSH_HOST = 'android.googleapis.com'
PUSH_URL_PATH = '/gcm/send'
# The interval in milliseconds for fetching updates from HSL servers.
UPDATE_INTERVAL = process.env.UPDATE_INTERVAL ? 1000*60
# API key from Google (Don't save this in the public repo!)
GCM_PUSH_API_KEY =
process.env.GCM_PUSH_API_KEY ?
try
require('./secret_keys').GCM_PUSH_API_KEY
catch
console.error("""
Google Cloud Messaging API key not set. The key can be
given in the environment variable GCM_PUSH_API_KEY or in a
file named secret_keys.js as follows:
module.exports = { GCM_PUSH_API_KEY: "..." };
The file MUST NOT be stored in a public repository!
""")
process.exit 1
# Push a message to the client using Google Cloud Messaging (GCM).
# Parameter msg is a plain JS object with keys:
# clientId, message, lines, category, validThrough
pushToClient = (msg, retryTimeout = 1000) ->
# The message is only pushed to the client if it has not been yet pushed earlier
SentMessageHash.storeHash msg, (err, msgHashDoc) ->
if err
console.error err
else if not msgHashDoc? # if null, the message has already been sent
console.log "GCM request already sent, skipping: %j", msg
else
# Send HTTP POST request to the GCM push server that will
# then send it to the client
# http://developer.android.com/google/gcm/server-ref.html
options =
hostname: PUSH_HOST
path: PUSH_URL_PATH
method: 'POST'
headers:
'Authorization': "key=#{ GCM_PUSH_API_KEY }"
'Content-Type': 'application/json'
timeTillEnd =
if msg.validThrough?
(msg.validThrough.getTime() - new Date().getTime()) / 1000
else
0
timeToLive =
if timeTillEnd > 0
# set time_to_live till the end of the journey in seconds
timeTillEnd
else
60 * 60 * 24 # 24 h
postData =
registration_ids: [msg.clientId] # The clientId is used by GCM to identify the client device.
time_to_live: timeToLive
data: # payload to client, data values should be strings
title: "Traffic disruption"
message: msg.message
disruption_lines: msg.lines.join() # array to comma-separated string
disruption_category: msg.category
console.log "sending GCM request: %j", postData
request = https.request options, (response) ->
# response from GCM push server
response.setEncoding 'utf8'
responseData = ''
# gather the whole response body into one string before parsing JSON
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
try
if response.statusCode == 401
throw "GCM auth error 401"
else if response.statusCode == 400
throw "GCM bad request JSON error"
else if 500 <= response.statusCode <= 599
# GCM server error, retry later
# remove the message hash before trying to push again
msgHashDoc.remove (err) ->
console.error err if err
timeout =
if 'retry-after' of response.headers
parseHttpRetryAfter response.headers['retry-after']
else
retryTimeout
scheduleMessagePush msg, timeout
else if response.statusCode == 200
# success, but nonetheless there may be
# errors in delivering messages to clients
try
jsonObj = JSON.parse responseData
catch
throw "GCM response JSON parse error"
if jsonObj.failure > 0 or jsonObj.canonical_ids > 0
# there were some problems
for resObj in jsonObj.results
if resObj.message_id? and resObj.registration_id?
# must replace the client registration id with
# the new resObj id (canonical id)
console.log "GCM client id changed. Updating database."
# modify database
Subscription.update { clientId: msg.clientId },
{ clientId: resObj.registration_id },
(err) -> console.error err if err
SentMessageHash.update { clientId: msg.clientId },
{ clientId: resObj.registration_id },
(err) -> console.error err if err
# no need to resend, GCM just informed us
# that the registration id was changed
else if resObj.error?
if resObj.error == 'Unavailable'
# GCM server unavailable, retry
# remove the message hash document before trying to push it again
msgHashDoc.remove (err) ->
console.error err if err
timeout =
if 'retry-after' of response.headers
parseHttpRetryAfter response.headers['retry-after']
else
retryTimeout
scheduleMessagePush msg, timeout
else if resObj.error == 'NotRegistered'
Subscription.remove { clientId: msg.clientId },
(err) -> console.error err if err
throw "GCM client not registered,
removing client from database"
else
throw "GCM response error: #{ resObj.error }"
else
throw "unknown GCM response status code: #{response.statusCode}"
catch errMsg
console.error "pushToClient: #{errMsg}"
msgHashDoc.remove (err) -> console.error err if err
return
response.on 'error', (err) -> console.error "pushToClient: #{err}"
request.on 'error', (err) -> console.error "pushToClient: #{err}"
# write data to request body
request.write JSON.stringify postData
request.end()
# Find clients that are using lines (given as array) in the area.
# Push notification messages to the affected clients.
findClients = (lines, areaField, message, disrStartTime, disrEndTime) ->
createMessages = (err, clientIds) ->
if err
console.error err
else
for id in clientIds
pushToClient
clientId: id
message: message # human-readable text
lines: lines
category: areaField
validThrough: disrEndTime
return
criteria = {}
criteria.category = areaField if areaField != 'all'
# if lines[0] == 'all', find clients that are using any line in the area
criteria.line = { $in: lines } if lines[0] != 'all' # add lines criteria if searching only for specific lines
criteria.startTime = { $lt: disrEndTime } if disrEndTime
criteria.endTime = { $gt: disrStartTime } if disrStartTime
Subscription.distinct 'clientId', criteria, createMessages
# Set a message push to occur in millisecs time. The push message will be
# sent to the GCM servers but it is still up to them to decide when
# the message is really sent to client devices.
scheduleMessagePush = (msg, inmillisecs) ->
action = ->
# remove this timeout from list
i = scheduledMessagePushes.indexOf timeout
scheduledMessagePushes.splice(i, 1) if i >= 0
# double the timeout for the possible next retry after this one
# (exponential back-off)
pushToClient msg, 2 * inmillisecs
timeout = setTimeout action, inmillisecs
scheduledMessagePushes.push timeout
scheduledMessagePushes = []
# HTTP retry-after header may be a date string or a decimal integer in seconds.
# Return the timeout in milliseconds from this moment.
parseHttpRetryAfter = (retryAfterValue) ->
if isNaN retryAfterValue
# header contains a date string,
# get time in milliseconds from this moment to that moment
timeout = new Date(retryAfterValue).getTime() - new Date().getTime()
if timeout > 0
timeout
else
5000 # arbitrary default if retry-after header date is in the past
else
# header is integer in seconds
1000 * parseInt retryAfterValue, 10
# Return true if daylight saving is currently in use.
isDstOn = () ->
# Modified from http://javascript.about.com/library/bldst.htm
dateStdTimezoneOffset = (date) ->
jan = new Date date.getFullYear(), 0, 1
jul = new Date date.getFullYear(), 6, 1
Math.max jan.getTimezoneOffset(), jul.getTimezoneOffset()
dateDst = (date) ->
date.getTimezoneOffset() < dateStdTimezoneOffset(date)
dateDst new Date()
# mapping from HSL news API Main category values to the categories we use here
NEWS_API_CATEGORIES =
'Helsinki internal bus': 'helsinkiInternal'
'Espoo internal bus': 'espooInternal'
'Vantaa internal bus': 'vantaaInternal'
'Regional': 'regional'
'Regional night line': 'regional'
'Tram': 'tram'
'Commuter train': 'train'
'Ferry': 'ferry'
'U line': 'Uline'
'Sipoo internal line': 'sipooInternal'
'Kerava internal bus': 'keravaInternal'
# newsObj is the JS object parsed from the HSL news response
parseNewsResponse = (newsObj) ->
for node in newsObj.nodes
node = node.node
lines = node.Lines.split ','
cat = node['Main category']
# the news do not contain easily parsable dates for the validity period
if cat of NEWS_API_CATEGORIES
findClients lines, NEWS_API_CATEGORIES[cat], node.title
else
console.log "parseNewsResponse: unknown Main category: #{ cat }"
return
# mapping from poikkeusinfo linetypes to the categories we use here
DISRUPTION_API_LINETYPES =
'1': 'helsinkiInternal'
'2': 'tram'
'3': 'espooInternal'
'4': 'vantaaInternal'
'5': 'regional'
'6': 'metro'
'7': 'ferry'
'12': 'train' # commuter trains
#'14': 'all' # handled separately
'36': 'kirkkonummiInternal'
'39': 'keravaInternal'
# Parse XML response from poikkeusinfo server.
# Parameter disrObj is a JS object parsed from XML.
parseDisruptionsResponse = (disrObj) ->
# HSL API description in Finnish (no pdf in English)
# http://developer.reittiopas.fi/media/Poikkeusinfo_XML_rajapinta_V2_2_01.pdf
for key, value of disrObj.DISRUPTIONS
if key == 'PI:KEY:<KEY>END_PI'
for disrObj in value
# disrObj is one disruption message (one DISRUPTION element from the original XML)
isValid = false
disrStartTime = null
disrEndTime = null
message = ''
linesByArea = {
# these keys must match the values of the object DISRUPTION_API_LINETYPES
helsinkiInternal: []
espooInternal: []
vantaaInternal: []
regional: []
tram: []
train: []
ferry: []
Uline: []
metro: []
kirkkonummiInternal: []
keravaInternal: []
}
for dkey, dval of disrObj
if dkey == 'VALIDITY'
# the message may be active or cancelled
isValid = true if dval[0]['$'].status == '1'
# the HSL poikkeusinfo server does not have timezones in the date values,
# so we manually set the Finnish timezone here
timezone =
if isDstOn()
'+03:00'
else
'+02:00'
disrStartTime = new Date(dval[0]['$'].from + timezone)
disrEndTime = new Date(dval[0]['$'].to + timezone)
else if dkey == 'INFO'
# human-readable description
englishElemIdx = 0
for textElem, elemIdx in dval[0]['TEXT']
# language attributes fi, se, en
englishElemIdx = elemIdx if textElem['$'].lang == 'en'
message = dval[0]['TEXT'][englishElemIdx]['_'].trim()
# key '_' means the XML element content (normal text)
else if dkey == 'TARGETS'
targets = dval[0] # only one TARGETS element
# TARGETS contains either a LINETYPE or 1-N LINE elements
if targets.LINETYPE?
# all lines within the area/scope/type affected
# assume there is only one LINETYPE element
# linetype numeric id that maps to regions/categories
linetype = targets.LINETYPE[0]['$'].id
if linetype of DISRUPTION_API_LINETYPES
linesByArea[DISRUPTION_API_LINETYPES[linetype]].push 'all'
else if linetype == '14' # all areas
for area, lines of linesByArea
lines.push 'all'
else if targets.LINE?
# list of line elements that specify single affected lines
# parsed XML: $ for attributes, _ for textual element content
for lineElem in targets.LINE
if lineElem['$'].linetype of DISRUPTION_API_LINETYPES
linesByArea[DISRUPTION_API_LINETYPES[lineElem['$'].linetype]].push lineElem['_']
else if lineElem['$'].linetype == '14' # all areas
for area, lines of linesByArea
lines.push lineElem['_']
if isValid
for area, lines of linesByArea
findClients lines, area, message, disrStartTime, disrEndTime if lines.length > 0
return
# Function that fetches disruption news updates from HSL servers, parses them
# and searches the database for affected clients. The clients are sent
# push notifications if necessary. The same message is only sent once to a client.
update = ->
console.log "Fetching news and disruptions updates"
# Abort all scheduled GCM message push retry attempts so that the
# number of requests doesn't keep growing if GCM server is down
for timeout in scheduledMessagePushes
clearTimeout timeout
scheduledMessagePushes = []
request = https.request NEWS_URL, (response) ->
# response from HSL server
response.setEncoding 'utf8'
responseData = ''
# gather the whole response body into one string before parsing JSON
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
# object with key nodes, its value is an array, array contains objects
# with key node, and that is an object with keys title, body, Lines, Main category
try
jsonObj = JSON.parse responseData
parseNewsResponse jsonObj
catch error
console.error "JSON parse error in news response: #{ error }"
response.on 'error', (err) -> console.error err
request.on 'error', (err) -> console.error err
request.end()
requestDisr = http.request DISRUPTIONS_URL, (response) ->
# response from HSL server
response.setEncoding 'utf8' # 'ISO-8859-1' not supported
responseData = ''
# gather the whole response body into one string before parsing XML
response.on 'data', (chunk) ->
responseData += chunk
response.on 'end', ->
xml2js.parseString responseData, (err, result) ->
if err
console.error "Error in parsing XML response from #{ DISRUPTIONS_URL }: " + err
else
if not result.DISRUPTIONS.INFO?
# disruptions exist
parseDisruptionsResponse result
response.on 'error', (err) -> console.error err
requestDisr.on 'error', (err) -> console.error err
requestDisr.end()
# Send a test message to all registered clients. Note that messages
# identical to any previously sent message are not sent to clients
# that have already received the message.
sendTestMessage = (message, lines, category) ->
findClients lines ? ['all'], category ? 'all', message
start = ->
console.log "Starting update fetcher, update interval #{ UPDATE_INTERVAL / 1000 }s"
process.nextTick update
setInterval update, UPDATE_INTERVAL
module.exports =
start: start
sendTestMessage: sendTestMessage
if require.main == module
dbConnect()
.onFulfill(start)
.onReject ->
process.exit 2
|
[
{
"context": "cument.body.innerHTML = render('index.hbs',{name:'Doug'})\n)\n\ndo =>\n return show_page()\n\n",
"end": 208,
"score": 0.9996700286865234,
"start": 204,
"tag": "NAME",
"value": "Doug"
}
] | client/app/app.iced | tosadvisor/impression-diagnostics | 0 | log = (x...) -> try console.log x...
_ = require 'lodash'
render = require './lib/render.iced'
show_page = (->
require './styl/main.styl'
return document.body.innerHTML = render('index.hbs',{name:'Doug'})
)
do =>
return show_page()
| 197772 | log = (x...) -> try console.log x...
_ = require 'lodash'
render = require './lib/render.iced'
show_page = (->
require './styl/main.styl'
return document.body.innerHTML = render('index.hbs',{name:'<NAME>'})
)
do =>
return show_page()
| true | log = (x...) -> try console.log x...
_ = require 'lodash'
render = require './lib/render.iced'
show_page = (->
require './styl/main.styl'
return document.body.innerHTML = render('index.hbs',{name:'PI:NAME:<NAME>END_PI'})
)
do =>
return show_page()
|
[
{
"context": "tar-1'\n image.alt = ''\n image.name = 'avatar-1'\n image.width = 80\n image.height = 80\n d",
"end": 258,
"score": 0.6493411660194397,
"start": 257,
"tag": "USERNAME",
"value": "1"
},
{
"context": "ess', ->\n avatar = new Avatar(image, email: 'test@... | test/avatar_spec.coffee | websquared/avatar | 0 | describe "Avatar", ->
# Globals
avatar = image = load_spy = error_spy = null
before ->
# DOM Setup
# document.body.innerHTML = ''
image = document.createElement('img')
image.id = 'avatar-1'
image.alt = ''
image.name = 'avatar-1'
image.width = 80
image.height = 80
document.body.appendChild image
image = document.getElementById('avatar-1')
afterEach ->
avatar = null
describe '#constructor', ->
it 'should render', ->
avatar = new Avatar(image)
avatar.settings.useGravatar.should.be.true
it 'should allow options', ->
avatar = new Avatar(image, useGravatar: false)
avatar.settings.useGravatar.should.not.be.true
it 'should render a canvas', ->
avatar = new Avatar(image, initials: 'MC')
avatar.settings.useGravatar.should.be.true
describe '#setSource', ->
it 'should set the src attribute', ->
avatar = new Avatar(image)
avatar.setSource 'data:image/png;'
image.src.should.equal 'data:image/png;'
avatar.setSource 'http://placekitten.com/200/300'
image.src.should.equal 'http://placekitten.com/200/300'
# Setting the source to undefined should return, leaving it untouched.
avatar.setSource()
image.src.should.equal 'http://placekitten.com/200/300'
describe '#initialAvatar', ->
beforeEach ->
avatar = new Avatar(image)
it 'should return a PNG', ->
png = avatar.initialAvatar('MC', avatar.settings)
png.should.match(/^data:image\/png;base64,iV/)
describe '#gravatarUrl', ->
it 'should return a Gravatar URL with an email address', ->
avatar = new Avatar(image, email: 'test@test.com')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452?s=80&d=mm&r=x'
it 'should return a Gravatar URL with an hash', ->
avatar = new Avatar(image, hash: 'b642b4217b34b1e8d3bd915fc65c4452')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452?s=80&d=mm&r=x'
it 'should return a Gravatar URL with nothing', ->
avatar = new Avatar(image)
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=mm&r=x'
it 'should return a Gravatar URL with a custom size', ->
avatar = new Avatar(image, size: 100)
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=100&d=mm&r=x'
avatar = new Avatar(image, size: '100')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=100&d=mm&r=x'
it 'should return a Gravatar URL with a custom fallback', ->
avatar = new Avatar(image, fallback: 'test')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=test&r=x'
it 'should return a Gravatar URL with a custom rating', ->
avatar = new Avatar(image, rating: 'g')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=mm&r=g'
# Spies aren't being called.
# describe '#gravatarValid', ->
# beforeEach ->
# avatar = new Avatar(image, useGravatar: false)
# load_spy = sinon.spy()
# error_spy = sinon.spy()
#
# it 'should return an error for an invalid Gravatar URL', ->
# avatar.gravatarValid('https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&r=x', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar URL', ->
# avatar.gravatarValid('https://secure.gravatar.com/avatar/12929016fffb0b3af98bc440acf0bfe2?s=80&r=x', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
#
# it 'should return an error for an invalid Gravatar hash', ->
# avatar.gravatarValid('00000000000000000000000000000000', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar hash', ->
# avatar.gravatarValid('12929016fffb0b3af98bc440acf0bfe2', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
#
# it 'should return an error for an invalid Gravatar email', ->
# avatar.gravatarValid('test@test.com', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar email', ->
# avatar.gravatarValid('matthew@apptentive.com', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
describe '#merge', ->
it 'should merge objects', ->
avatar = new Avatar(image)
defaults =
useGravatar: true
allowGravatarFallback: false
initials: ''
initial_fg: '#888'
initial_bg: '#f4f6f7'
initial_size: null
initial_weight: 100
initial_font_family: "'Lato', 'Lato-Regular', 'Helvetica Neue'"
hash: '00000000000000000000000000000000'
email: null
size: 80
fallback: 'mm'
rating: 'x'
forcedefault: false
fallbackImage: ''
debug: false
options =
useGravatar: false
allowGravatarFallback: true
initials: 'MDC'
initial_fg: '#111'
initial_bg: '#222'
initial_size: 1
initial_weight: 2
initial_font_family: 'Comic Sans'
hash: '00000000000000000000000000000000'
email: 'matthew@apptentive.com'
size: 120
fallback: 'mm'
rating: 'pg'
forcedefault: true
fallbackImage: 'nah'
debug: false
output = avatar.merge(defaults, options)
output.should.deep.equal options
describe 'jQuery Helper', ->
it 'should create an avatar with options', ->
$('#avatar-1').avatar
useGravatar: false
initials: 'MC'
# Use match because this will very depending on `window.devicePixelRatio`
$('#avatar-1').attr('src').should.match(/^data:image\/png;base64,iV/)
| 160984 | describe "Avatar", ->
# Globals
avatar = image = load_spy = error_spy = null
before ->
# DOM Setup
# document.body.innerHTML = ''
image = document.createElement('img')
image.id = 'avatar-1'
image.alt = ''
image.name = 'avatar-1'
image.width = 80
image.height = 80
document.body.appendChild image
image = document.getElementById('avatar-1')
afterEach ->
avatar = null
describe '#constructor', ->
it 'should render', ->
avatar = new Avatar(image)
avatar.settings.useGravatar.should.be.true
it 'should allow options', ->
avatar = new Avatar(image, useGravatar: false)
avatar.settings.useGravatar.should.not.be.true
it 'should render a canvas', ->
avatar = new Avatar(image, initials: 'MC')
avatar.settings.useGravatar.should.be.true
describe '#setSource', ->
it 'should set the src attribute', ->
avatar = new Avatar(image)
avatar.setSource 'data:image/png;'
image.src.should.equal 'data:image/png;'
avatar.setSource 'http://placekitten.com/200/300'
image.src.should.equal 'http://placekitten.com/200/300'
# Setting the source to undefined should return, leaving it untouched.
avatar.setSource()
image.src.should.equal 'http://placekitten.com/200/300'
describe '#initialAvatar', ->
beforeEach ->
avatar = new Avatar(image)
it 'should return a PNG', ->
png = avatar.initialAvatar('MC', avatar.settings)
png.should.match(/^data:image\/png;base64,iV/)
describe '#gravatarUrl', ->
it 'should return a Gravatar URL with an email address', ->
avatar = new Avatar(image, email: '<EMAIL>')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452?s=80&d=mm&r=x'
it 'should return a Gravatar URL with an hash', ->
avatar = new Avatar(image, hash: 'b642b4217b34b1e8d3bd915fc65c4452')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452?s=80&d=mm&r=x'
it 'should return a Gravatar URL with nothing', ->
avatar = new Avatar(image)
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=mm&r=x'
it 'should return a Gravatar URL with a custom size', ->
avatar = new Avatar(image, size: 100)
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=100&d=mm&r=x'
avatar = new Avatar(image, size: '100')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=100&d=mm&r=x'
it 'should return a Gravatar URL with a custom fallback', ->
avatar = new Avatar(image, fallback: 'test')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=test&r=x'
it 'should return a Gravatar URL with a custom rating', ->
avatar = new Avatar(image, rating: 'g')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=mm&r=g'
# Spies aren't being called.
# describe '#gravatarValid', ->
# beforeEach ->
# avatar = new Avatar(image, useGravatar: false)
# load_spy = sinon.spy()
# error_spy = sinon.spy()
#
# it 'should return an error for an invalid Gravatar URL', ->
# avatar.gravatarValid('https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&r=x', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar URL', ->
# avatar.gravatarValid('https://secure.gravatar.com/avatar/12929016fffb0b3af98bc440acf0bfe2?s=80&r=x', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
#
# it 'should return an error for an invalid Gravatar hash', ->
# avatar.gravatarValid('00000000000000000000000000000000', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar hash', ->
# avatar.gravatarValid('12929016fffb0b3af98bc440acf0bfe2', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
#
# it 'should return an error for an invalid Gravatar email', ->
# avatar.gravatarValid('<EMAIL>', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar email', ->
# avatar.gravatarValid('<EMAIL>', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
describe '#merge', ->
it 'should merge objects', ->
avatar = new Avatar(image)
defaults =
useGravatar: true
allowGravatarFallback: false
initials: ''
initial_fg: '#888'
initial_bg: '#f4f6f7'
initial_size: null
initial_weight: 100
initial_font_family: "'Lato', 'Lato-Regular', 'Helvetica Neue'"
hash: '00000000000000000000000000000000'
email: null
size: 80
fallback: 'mm'
rating: 'x'
forcedefault: false
fallbackImage: ''
debug: false
options =
useGravatar: false
allowGravatarFallback: true
initials: 'MDC'
initial_fg: '#111'
initial_bg: '#222'
initial_size: 1
initial_weight: 2
initial_font_family: 'Comic Sans'
hash: '00000000000000000000000000000000'
email: '<EMAIL>'
size: 120
fallback: 'mm'
rating: 'pg'
forcedefault: true
fallbackImage: 'nah'
debug: false
output = avatar.merge(defaults, options)
output.should.deep.equal options
describe 'jQuery Helper', ->
it 'should create an avatar with options', ->
$('#avatar-1').avatar
useGravatar: false
initials: 'MC'
# Use match because this will very depending on `window.devicePixelRatio`
$('#avatar-1').attr('src').should.match(/^data:image\/png;base64,iV/)
| true | describe "Avatar", ->
# Globals
avatar = image = load_spy = error_spy = null
before ->
# DOM Setup
# document.body.innerHTML = ''
image = document.createElement('img')
image.id = 'avatar-1'
image.alt = ''
image.name = 'avatar-1'
image.width = 80
image.height = 80
document.body.appendChild image
image = document.getElementById('avatar-1')
afterEach ->
avatar = null
describe '#constructor', ->
it 'should render', ->
avatar = new Avatar(image)
avatar.settings.useGravatar.should.be.true
it 'should allow options', ->
avatar = new Avatar(image, useGravatar: false)
avatar.settings.useGravatar.should.not.be.true
it 'should render a canvas', ->
avatar = new Avatar(image, initials: 'MC')
avatar.settings.useGravatar.should.be.true
describe '#setSource', ->
it 'should set the src attribute', ->
avatar = new Avatar(image)
avatar.setSource 'data:image/png;'
image.src.should.equal 'data:image/png;'
avatar.setSource 'http://placekitten.com/200/300'
image.src.should.equal 'http://placekitten.com/200/300'
# Setting the source to undefined should return, leaving it untouched.
avatar.setSource()
image.src.should.equal 'http://placekitten.com/200/300'
describe '#initialAvatar', ->
beforeEach ->
avatar = new Avatar(image)
it 'should return a PNG', ->
png = avatar.initialAvatar('MC', avatar.settings)
png.should.match(/^data:image\/png;base64,iV/)
describe '#gravatarUrl', ->
it 'should return a Gravatar URL with an email address', ->
avatar = new Avatar(image, email: 'PI:EMAIL:<EMAIL>END_PI')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452?s=80&d=mm&r=x'
it 'should return a Gravatar URL with an hash', ->
avatar = new Avatar(image, hash: 'b642b4217b34b1e8d3bd915fc65c4452')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452?s=80&d=mm&r=x'
it 'should return a Gravatar URL with nothing', ->
avatar = new Avatar(image)
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=mm&r=x'
it 'should return a Gravatar URL with a custom size', ->
avatar = new Avatar(image, size: 100)
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=100&d=mm&r=x'
avatar = new Avatar(image, size: '100')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=100&d=mm&r=x'
it 'should return a Gravatar URL with a custom fallback', ->
avatar = new Avatar(image, fallback: 'test')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=test&r=x'
it 'should return a Gravatar URL with a custom rating', ->
avatar = new Avatar(image, rating: 'g')
url = avatar.gravatarUrl(avatar.settings)
url.should.equal 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&d=mm&r=g'
# Spies aren't being called.
# describe '#gravatarValid', ->
# beforeEach ->
# avatar = new Avatar(image, useGravatar: false)
# load_spy = sinon.spy()
# error_spy = sinon.spy()
#
# it 'should return an error for an invalid Gravatar URL', ->
# avatar.gravatarValid('https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=80&r=x', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar URL', ->
# avatar.gravatarValid('https://secure.gravatar.com/avatar/12929016fffb0b3af98bc440acf0bfe2?s=80&r=x', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
#
# it 'should return an error for an invalid Gravatar hash', ->
# avatar.gravatarValid('00000000000000000000000000000000', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar hash', ->
# avatar.gravatarValid('12929016fffb0b3af98bc440acf0bfe2', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
#
# it 'should return an error for an invalid Gravatar email', ->
# avatar.gravatarValid('PI:EMAIL:<EMAIL>END_PI', load_spy, error_spy)
# load_spy.callCount.should.equal 0
# error_spy.callCount.should.equal 1
#
# it 'should not return an error for a valid Gravatar email', ->
# avatar.gravatarValid('PI:EMAIL:<EMAIL>END_PI', load_spy, error_spy)
# load_spy.callCount.should.equal 1
# error_spy.callCount.should.equal 0
describe '#merge', ->
it 'should merge objects', ->
avatar = new Avatar(image)
defaults =
useGravatar: true
allowGravatarFallback: false
initials: ''
initial_fg: '#888'
initial_bg: '#f4f6f7'
initial_size: null
initial_weight: 100
initial_font_family: "'Lato', 'Lato-Regular', 'Helvetica Neue'"
hash: '00000000000000000000000000000000'
email: null
size: 80
fallback: 'mm'
rating: 'x'
forcedefault: false
fallbackImage: ''
debug: false
options =
useGravatar: false
allowGravatarFallback: true
initials: 'MDC'
initial_fg: '#111'
initial_bg: '#222'
initial_size: 1
initial_weight: 2
initial_font_family: 'Comic Sans'
hash: '00000000000000000000000000000000'
email: 'PI:EMAIL:<EMAIL>END_PI'
size: 120
fallback: 'mm'
rating: 'pg'
forcedefault: true
fallbackImage: 'nah'
debug: false
output = avatar.merge(defaults, options)
output.should.deep.equal options
describe 'jQuery Helper', ->
it 'should create an avatar with options', ->
$('#avatar-1').avatar
useGravatar: false
initials: 'MC'
# Use match because this will very depending on `window.devicePixelRatio`
$('#avatar-1').attr('src').should.match(/^data:image\/png;base64,iV/)
|
[
{
"context": "OFTWARE.\n\nangular-google-maps\nhttps://github.com/nlaplante/angular-google-maps\n\n@authors:\n- Nicolas Laplante",
"end": 1154,
"score": 0.6338178515434265,
"start": 1146,
"tag": "USERNAME",
"value": "laplante"
},
{
"context": "hub.com/nlaplante/angular-google-maps\n\... | platforms/ios/www/lib/bower_components/angular-google-maps/src/coffee/directives/search-box.coffee | FirstDateApp/FirstDateApp.github.io | 2 | ###
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/nlaplante/angular-google-maps
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
- Carrie Kengle - http://about.me/carrie
###
###
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
###
angular.module("google-maps".ns())
.directive "SearchBox".ns(), ["GoogleMapApi".ns(), "Logger".ns(), "SearchBoxParentModel".ns(), '$http', '$templateCache',
(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache) ->
class SearchBox
constructor: ->
@$log = Logger
@restrict = "EMA"
@require = '^' + 'GoogleMap'.ns()
@priority = -1
@transclude = true
@template = '<span class=\"angular-google-map-search\" ng-transclude></span>'
@replace = true
@scope =
template: '=template'
position: '=position'
options: '=options'
events: '=events'
parentdiv: '=parentdiv'
link: (scope, element, attrs, mapCtrl) =>
GoogleMapApi.then (maps) =>
$http.get(scope.template, { cache: $templateCache })
.success (template) =>
mapCtrl.getScope().deferred.promise.then (map) =>
ctrlPosition = if angular.isDefined scope.position then scope.position.toUpperCase().replace /-/g, '_' else 'TOP_LEFT'
if not maps.ControlPosition[ctrlPosition]
@$log.error 'searchBox: invalid position property'
return
new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, template)
new SearchBox()
]
| 121903 | ###
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/nlaplante/angular-google-maps
@authors:
- <NAME> https://plus.google.com/108189012221374960701
- <NAME> - https://twitter.com/nmccready
- <NAME> - http://about.me/carrie
###
###
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
###
angular.module("google-maps".ns())
.directive "SearchBox".ns(), ["GoogleMapApi".ns(), "Logger".ns(), "SearchBoxParentModel".ns(), '$http', '$templateCache',
(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache) ->
class SearchBox
constructor: ->
@$log = Logger
@restrict = "EMA"
@require = '^' + 'GoogleMap'.ns()
@priority = -1
@transclude = true
@template = '<span class=\"angular-google-map-search\" ng-transclude></span>'
@replace = true
@scope =
template: '=template'
position: '=position'
options: '=options'
events: '=events'
parentdiv: '=parentdiv'
link: (scope, element, attrs, mapCtrl) =>
GoogleMapApi.then (maps) =>
$http.get(scope.template, { cache: $templateCache })
.success (template) =>
mapCtrl.getScope().deferred.promise.then (map) =>
ctrlPosition = if angular.isDefined scope.position then scope.position.toUpperCase().replace /-/g, '_' else 'TOP_LEFT'
if not maps.ControlPosition[ctrlPosition]
@$log.error 'searchBox: invalid position property'
return
new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, template)
new SearchBox()
]
| true | ###
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/nlaplante/angular-google-maps
@authors:
- PI:NAME:<NAME>END_PI https://plus.google.com/108189012221374960701
- PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
- PI:NAME:<NAME>END_PI - http://about.me/carrie
###
###
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
###
angular.module("google-maps".ns())
.directive "SearchBox".ns(), ["GoogleMapApi".ns(), "Logger".ns(), "SearchBoxParentModel".ns(), '$http', '$templateCache',
(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache) ->
class SearchBox
constructor: ->
@$log = Logger
@restrict = "EMA"
@require = '^' + 'GoogleMap'.ns()
@priority = -1
@transclude = true
@template = '<span class=\"angular-google-map-search\" ng-transclude></span>'
@replace = true
@scope =
template: '=template'
position: '=position'
options: '=options'
events: '=events'
parentdiv: '=parentdiv'
link: (scope, element, attrs, mapCtrl) =>
GoogleMapApi.then (maps) =>
$http.get(scope.template, { cache: $templateCache })
.success (template) =>
mapCtrl.getScope().deferred.promise.then (map) =>
ctrlPosition = if angular.isDefined scope.position then scope.position.toUpperCase().replace /-/g, '_' else 'TOP_LEFT'
if not maps.ControlPosition[ctrlPosition]
@$log.error 'searchBox: invalid position property'
return
new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, template)
new SearchBox()
]
|
[
{
"context": "\n# Copyright (C) 2013 Mikhail Mukovnikov <m.mukovnikov@gmail.com>\n\n# Permission is hereby ",
"end": 40,
"score": 0.999872088432312,
"start": 22,
"tag": "NAME",
"value": "Mikhail Mukovnikov"
},
{
"context": "\n# Copyright (C) 2013 Mikhail Mukovnikov <m.mukovnikov@gmai... | source/frontend.coffee | gema-arta/darkjpeg.github.io | 1 |
# Copyright (C) 2013 Mikhail Mukovnikov <m.mukovnikov@gmail.com>
# 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.
global =
optAction: null, fileData: null, dropDown: null,
optMethod: null, fileJpeg: null, dropTimer: null,
optData: null, prvData: null, dropTarg: null,
optJpeg: null, prvJpeg: null,
optSafe: null,
optPass: null
testBrowser = (error) ->
nav = navigator.appName
ua = navigator.userAgent
ans = ua.match /(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\d+)*)/i
tem = ua.match /version\/([\d]+)/i if ans?
ans[2] = tem[1] if tem?
ans = [ans[1], parseInt ans[2]] if ans?
ans = [nav, navigator.appVersion] if not ans?
if ans[0] == 'Safari' and ans[1] > 5 or
ans[0] == 'Chrome' and ans[1] > 24 or
ans[0] == 'Firefox' and ans[1] > 16
return true
window.location.replace error
eventVoid = (event) ->
event.stopPropagation()
event.preventDefault()
controlAbort = (event) ->
if event.which == 27
eventVoid event
return abort()
controlDrop = (event) ->
eventVoid event
return if global.fileData
dataTransfer = event.dataTransfer
if dataTransfer?.files
for file in dataTransfer.files
global.fileData = file
return $('form').submit()
controlFile = ->
$('<input type="file">').click().change ->
if @files?.length > 0
global.fileData = @files[0]
$('form').submit()
controlPreview = (file, key) -> async ->
global[key] = null
return if not file or not /image/.test file.type
await blobToImageData file, defer ans
[w, h] = probeContainerQuot ans?.width, ans?.height, 150
await imageDataToImageData ans, w, h, defer ans
return if not okay ans
cvs = document.createElement 'canvas'
cvs.width = ans.width
cvs.height = ans.height
ctx = cvs.getContext '2d'
ctx.putImageData ans, 0, 0
await dataURLToImage cvs.toDataURL(), defer image
global[key] = image if okay image
controlColor = (obj, delta) ->
color = obj.css('background-color')
color = color.match /rgb\(([\d]+), ([\d]+), ([\d]+)\)/
return if not color
color[1] = parseInt(color[1]) + delta
color[2] = parseInt(color[2]) + delta
color[3] = parseInt(color[3]) + delta
color = "rgb(#{color[1]}, #{color[2]}, #{color[3]})"
obj.css('background-color', color)
obj.next().css('border-left-color', color) \
if /ctr-from/.test obj.next().attr('class')
obj.prev().css('border-top-color', color)
.css('border-bottom-color', color) \
if /ctr-to/.test obj.prev().attr('class')
controlAdd = (cls, text, cb) ->
return $('<div>').addClass(cls).appendTo('#control') if !text
$('<div>')
.html(text)
.addClass('ctr-float ' + cls)
.appendTo($('#control'))
.mouseenter(-> controlColor $(this), -30)
.mouseleave(-> controlColor $(this), +30)
.click(cb, controlDown)
controlRefresh = ->
offset = $('#control div.ctr-float:last').position()?.left | 0
$('input').css('padding-left', 10 + offset)
$('input').css('width', 410 - offset)
controlInput = (type, val) ->
keypress = (event) ->
input = $(event.target)
if event.which == 13 and type != 'password' and
(input.val() == val or input.val() == '')
controlFile(); return eventVoid event
if input.prop('type') != type
input.removeAttr('type').prop('type', type).val('')
input.focus().select()
blur = (input) ->
if input.val() == ''
input.removeAttr('type').prop('type', 'text').val(val)
paste = (input) ->
if input.prop('type') == 'text'
setTimeout (-> $('form').submit()), 100
$('input')
.clone().val(val).attr('type', 'text')
.keypress(keypress)
.blur(-> blur $(this))
.click(-> $(this).select())
.on('paste', -> paste $(this))
.on('drop', controlDrop)
.insertBefore($('input'))
.focus().select().next().remove()
controlDown = (event) ->
remove = ->
global.dropDown.remove() if global.dropDown
global.dropDown = null
clear = ->
clearTimeout global.dropTimer if global.dropTimer
global.dropTimer = global.dropTarg = null
timeout = ->
clear(); global.dropDown?.fadeOut(200).queue(remove)
set = ->
clear(); global.dropTimer = setTimeout timeout, 3000
return timeout() if global.dropTarg == event.target
return event.data($(event.target)) && timeout() \
if event.data == controlAction
remove() || set()
html = $('<div>').addClass('drop-arrow').add \
$('<div>').addClass('drop-content').html \
event.data $(event.target)
global.dropTarg = event.target
global.dropDown = $('<div>')
.html(html)
.css('position', 'absolute')
.css('top', event.pageY + 20)
.css('left', event.pageX - 75)
.mouseenter(clear).mouseleave(set)
.click(timeout).appendTo('body')
.hide().fadeIn(200)
controlAction = (ctr) ->
set = (action) ->
return if action == global.optAction
if action == 'decode'
$('.ctr-color-3').addClass('ctr-stop')
$('.ctr-color-4').remove()
return $('.ctr-to-4').remove()
$('.ctr-color-3').removeClass('ctr-stop').next().remove()
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
controlAdd 'ctr-float', null, null
return if global.optData != 'file'
action = 'encode' if global.optAction == 'decode'
action = 'decode' if global.optAction == 'encode'
if action == 'encode'
$('.ctr-color-3').removeClass('ctr-stop').next().remove()
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
controlAdd 'ctr-float', null, null
else $('.ctr-color-3').addClass('ctr-stop'); \
$('.ctr-color-4').remove(); $('.ctr-to-4').remove()
global.optAction = action
ctr.html(action); controlRefresh()
controlMethod = (ctr) ->
check = (obj, text) ->
obj.html(text)
'checked' if text == global.optMethod
click = (event) ->
global.optMethod = event.target.textContent
ctr.html event.target.textContent
controlRefresh()
checkS = (obj, text) ->
obj.html(text)
'checked' if not global.optSafe
clickS = (event) ->
global.optSafe = !global.optSafe; true
[a, b, c, d] = [$('<li>'), $('<li>'), $('<li>'), $('<li>')]
a.click(click).addClass(check(a, 'auto'))
b.click(click).addClass(check(b, 'join'))
c.click(click).addClass(check(c, 'steg'))
d.click(clickS).addClass(checkS(d, 'unsafe'))
$('<ul>').append a.add b.add c.add $('<hr>').add d
controlData = (ctr) ->
ul = $('<ul>')
click = -> controlInit controlProcess
if global.prvData
ul.append $(global.prvData)
if global.optData == 'file'
ul.append $('<li>').html(global.fileData.name).add \
$('<li>').html((global.fileData.size >> 10) + " Kb")
else ul.append $('<li>').html(global.fileData)
ul.append $('<hr>').add $('<li>').click(click).html('reset')
controlJpeg = (ctr) ->
check = (obj, text) ->
obj.html(text)
'checked' if text == global.optJpeg
input = '<input type="file" accept="image/*">'
file = -> $(input).click().change ->
return if @files?.length == 0
return if not /image/.test @files[0].type
global.fileJpeg = @files[0]
controlPreview @files[0], 'prvJpeg'
global.optJpeg = 'image'
ctr.html 'image'
controlRefresh()
click = (event) ->
selected = event.target.textContent
selected = 'rand' if selected == 'image'
global.optJpeg = selected
ctr.html selected
controlRefresh()
global.fileJpeg = global.prvJpeg = null
file() if event.target.textContent == 'image'
[a, b, c, ul] = [$('<li>'), $('<li>'), $('<li>'), $('<ul>')]
if global.prvJpeg
ul.append \
$(global.prvJpeg).add \
$('<li>').html(global.fileJpeg.name).add \
$('<li>').html((global.fileJpeg.size >> 10) + ' Kb').add \
$('<hr>')
a.click(click).addClass(check(a, 'rand'))
b.click(click).addClass(check(b, 'grad'))
c.click(click).addClass(check(c, 'image'))
ul.append a.add b.add c
controlInit = (cb) ->
controlDown target: global.dropTarg
for key of global then global[key] = null
$(document).off('keyup').keyup(controlAbort)
document.ondrop = controlDrop; document.onclick = null
document.ondragover = document.ondragenter = eventVoid
$('#control').remove(); $('figure').remove()
$('#progress').remove(); $('form').fadeIn(400)
$('h2').fadeIn(400); $('ul').fadeIn(400)
$('h1').off('click').click(-> controlInit controlProcess)
$('h3').html('').off('click').show()
$('input').prop('disabled', false); abort();
$('input').css('width', 410).css('padding-left', 10)
controlInput 'text', 'Paste a URL or add a file here'
$('<div>').prop('id', 'control').appendTo('form')
$('<div>').prop('id', 'button').addClass('btn-upload')
.appendTo('#control').off('click')
.click(controlFile).hide().fadeIn(400)
$('form').off('submit').submit (event) ->
eventVoid event
controlPreview global.fileData, 'prvData'
pass = -> controlInput 'password', 'Enter password'
done = ->
localStorage.setItem 'method', global.optMethod
localStorage.setItem 'wikisafe', global.optSafe
localStorage.setItem 'container', \
if global.fileJpeg then 'rand' else global.optJpeg
localStorage.setItem 'action', global.optAction \
if global.optData != 'url'
$('h3').html(''); global.optPass = $('input').val() \
if $('input').attr('type') == 'password'
return $('h3').css('opacity', 0) \
.off('click').stop().animate(opacity: 1, 400) \
.html('Empty password not allowed').delay(1000)
.animate(opacity: 0, 400) \
if !global.optPass && global.optMethod != 'join'
$('#control').fadeOut(400).queue ->
controlDown target: global.dropTarg
global.fileJpeg ?= global.optJpeg
$('#control').remove(); global.prvData = null
$('input').css('width', 410).css('padding-left', 10)
controlInput 'password'; global.prvJpeg = null
$('input').prop('disabled', true);
$('<div>').prop('id', 'progress').appendTo('form')
cb $('form').off('submit').submit (e) -> eventVoid e;
global.optAction = localStorage.getItem('action') ? 'encode'
global.optAction = 'decode' if not global.fileData
global.optData = global.fileData && 'file' || 'url'
global.fileData = global.fileData || $('input').val()
global.optMethod = localStorage.getItem('method') ? 'auto'
global.optJpeg = localStorage.getItem('container') ? 'rand'
global.optSafe = localStorage.getItem('wikisafe') ? 'true'
global.optSafe = global.optSafe == 'true'
controlAdd 'ctr-color-1 ctr-start', global.optAction, controlAction
controlAdd 'ctr-from-1 ctr-to-2', null, null
controlAdd 'ctr-color-2', global.optMethod, controlMethod
controlAdd 'ctr-from-2 ctr-to-3', null, null
if global.optAction == 'encode'
controlAdd 'ctr-color-3', global.optData, controlData
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
else controlAdd 'ctr-color-3 ctr-stop', global.optData, controlData
controlAdd 'ctr-float', null, null
$('input').val(''); controlRefresh()
$('#button').removeClass('btn-upload').off('click')
$('#button').addClass('btn-process').click(done)
$('form').off('submit').submit (e) -> eventVoid e; done()
if global.optData == 'file' then pass() else \
setTimeout(pass, 100) && $('#control').hide().fadeIn(400)
controlProgress = (dict) ->
text = dict.name ? dict.type
prog = Math.min(Math.max(dict.progress ? 0, 18), 100) * 4.41 | 0
return $('#progress').html(text) if dict.type != 'progress'
$('#progress').stop().animate(width: prog, 400).html(text)
controlProcess = ->
done = (image, blob) ->
str = blob.name + '<br><span dir="ltr">' +
((blob.size >> 10) + 1) + ' Kb</span>'
$('<figure>').append(image).appendTo('section')
.append($('<figcaption>').html(str)
.css('max-width', $(image).width() - 6))
.click(-> dataURLSave url, blob.name)
.css(opacity: 0).animate(opacity: 1, 400)
error = (url) ->
err = trace(url, true)?.error ? 'Some error occured'
$('h3').stop().css('opacity', 1).html("Oops! #{err} :(")
document.onclick = -> controlInit controlProcess
safari = /^(?!.*Chrome).*Safari.*$/.test navigator.userAgent
dict = action: global.optAction, pass: global.optPass, \
method: global.optMethod, safe: global.optSafe
dict.data = global.fileData if global.optAction == 'decode'
dict.data = global.fileJpeg if global.optAction == 'encode'
dict.hide = global.fileData if global.optAction == 'encode'
await processRequest dict, controlProgress, defer blob
await blobToDataURL blob, safari, defer url
return error url if not okay url
await dataURLToImage url, defer image if /image/.test blob.type
image = $('<div>') if not image? or not okay image
$('h2').fadeOut(400); $('form').fadeOut(400)
$('h3').fadeOut(400); $('ul').fadeOut(400)
setTimeout (-> done image, blob), 450
testBrowser '//browser-update.org/update.html'
jQuery.event.props.push 'dataTransfer'
controlInit controlProcess
console.log """
Privacy is necessary for an open society in the electronic age.
... We cannot expect governments, corporations, or other large,
faceless organizations to grant us privacy ... We must defend
our own privacy if we expect to have any. ... Cypherpunks write
code. We know that someone has to write software to defend
privacy, and ... we're going to write it. (c) Eric Hughes, 1993
"""
| 70203 |
# Copyright (C) 2013 <NAME> <<EMAIL>>
# 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.
global =
optAction: null, fileData: null, dropDown: null,
optMethod: null, fileJpeg: null, dropTimer: null,
optData: null, prvData: null, dropTarg: null,
optJpeg: null, prvJpeg: null,
optSafe: null,
optPass: null
testBrowser = (error) ->
nav = navigator.appName
ua = navigator.userAgent
ans = ua.match /(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\d+)*)/i
tem = ua.match /version\/([\d]+)/i if ans?
ans[2] = tem[1] if tem?
ans = [ans[1], parseInt ans[2]] if ans?
ans = [nav, navigator.appVersion] if not ans?
if ans[0] == 'Safari' and ans[1] > 5 or
ans[0] == 'Chrome' and ans[1] > 24 or
ans[0] == 'Firefox' and ans[1] > 16
return true
window.location.replace error
eventVoid = (event) ->
event.stopPropagation()
event.preventDefault()
controlAbort = (event) ->
if event.which == 27
eventVoid event
return abort()
controlDrop = (event) ->
eventVoid event
return if global.fileData
dataTransfer = event.dataTransfer
if dataTransfer?.files
for file in dataTransfer.files
global.fileData = file
return $('form').submit()
controlFile = ->
$('<input type="file">').click().change ->
if @files?.length > 0
global.fileData = @files[0]
$('form').submit()
controlPreview = (file, key) -> async ->
global[key] = null
return if not file or not /image/.test file.type
await blobToImageData file, defer ans
[w, h] = probeContainerQuot ans?.width, ans?.height, 150
await imageDataToImageData ans, w, h, defer ans
return if not okay ans
cvs = document.createElement 'canvas'
cvs.width = ans.width
cvs.height = ans.height
ctx = cvs.getContext '2d'
ctx.putImageData ans, 0, 0
await dataURLToImage cvs.toDataURL(), defer image
global[key] = image if okay image
controlColor = (obj, delta) ->
color = obj.css('background-color')
color = color.match /rgb\(([\d]+), ([\d]+), ([\d]+)\)/
return if not color
color[1] = parseInt(color[1]) + delta
color[2] = parseInt(color[2]) + delta
color[3] = parseInt(color[3]) + delta
color = "rgb(#{color[1]}, #{color[2]}, #{color[3]})"
obj.css('background-color', color)
obj.next().css('border-left-color', color) \
if /ctr-from/.test obj.next().attr('class')
obj.prev().css('border-top-color', color)
.css('border-bottom-color', color) \
if /ctr-to/.test obj.prev().attr('class')
controlAdd = (cls, text, cb) ->
return $('<div>').addClass(cls).appendTo('#control') if !text
$('<div>')
.html(text)
.addClass('ctr-float ' + cls)
.appendTo($('#control'))
.mouseenter(-> controlColor $(this), -30)
.mouseleave(-> controlColor $(this), +30)
.click(cb, controlDown)
controlRefresh = ->
offset = $('#control div.ctr-float:last').position()?.left | 0
$('input').css('padding-left', 10 + offset)
$('input').css('width', 410 - offset)
controlInput = (type, val) ->
keypress = (event) ->
input = $(event.target)
if event.which == 13 and type != 'password' and
(input.val() == val or input.val() == '')
controlFile(); return eventVoid event
if input.prop('type') != type
input.removeAttr('type').prop('type', type).val('')
input.focus().select()
blur = (input) ->
if input.val() == ''
input.removeAttr('type').prop('type', 'text').val(val)
paste = (input) ->
if input.prop('type') == 'text'
setTimeout (-> $('form').submit()), 100
$('input')
.clone().val(val).attr('type', 'text')
.keypress(keypress)
.blur(-> blur $(this))
.click(-> $(this).select())
.on('paste', -> paste $(this))
.on('drop', controlDrop)
.insertBefore($('input'))
.focus().select().next().remove()
controlDown = (event) ->
remove = ->
global.dropDown.remove() if global.dropDown
global.dropDown = null
clear = ->
clearTimeout global.dropTimer if global.dropTimer
global.dropTimer = global.dropTarg = null
timeout = ->
clear(); global.dropDown?.fadeOut(200).queue(remove)
set = ->
clear(); global.dropTimer = setTimeout timeout, 3000
return timeout() if global.dropTarg == event.target
return event.data($(event.target)) && timeout() \
if event.data == controlAction
remove() || set()
html = $('<div>').addClass('drop-arrow').add \
$('<div>').addClass('drop-content').html \
event.data $(event.target)
global.dropTarg = event.target
global.dropDown = $('<div>')
.html(html)
.css('position', 'absolute')
.css('top', event.pageY + 20)
.css('left', event.pageX - 75)
.mouseenter(clear).mouseleave(set)
.click(timeout).appendTo('body')
.hide().fadeIn(200)
controlAction = (ctr) ->
set = (action) ->
return if action == global.optAction
if action == 'decode'
$('.ctr-color-3').addClass('ctr-stop')
$('.ctr-color-4').remove()
return $('.ctr-to-4').remove()
$('.ctr-color-3').removeClass('ctr-stop').next().remove()
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
controlAdd 'ctr-float', null, null
return if global.optData != 'file'
action = 'encode' if global.optAction == 'decode'
action = 'decode' if global.optAction == 'encode'
if action == 'encode'
$('.ctr-color-3').removeClass('ctr-stop').next().remove()
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
controlAdd 'ctr-float', null, null
else $('.ctr-color-3').addClass('ctr-stop'); \
$('.ctr-color-4').remove(); $('.ctr-to-4').remove()
global.optAction = action
ctr.html(action); controlRefresh()
controlMethod = (ctr) ->
check = (obj, text) ->
obj.html(text)
'checked' if text == global.optMethod
click = (event) ->
global.optMethod = event.target.textContent
ctr.html event.target.textContent
controlRefresh()
checkS = (obj, text) ->
obj.html(text)
'checked' if not global.optSafe
clickS = (event) ->
global.optSafe = !global.optSafe; true
[a, b, c, d] = [$('<li>'), $('<li>'), $('<li>'), $('<li>')]
a.click(click).addClass(check(a, 'auto'))
b.click(click).addClass(check(b, 'join'))
c.click(click).addClass(check(c, 'steg'))
d.click(clickS).addClass(checkS(d, 'unsafe'))
$('<ul>').append a.add b.add c.add $('<hr>').add d
controlData = (ctr) ->
ul = $('<ul>')
click = -> controlInit controlProcess
if global.prvData
ul.append $(global.prvData)
if global.optData == 'file'
ul.append $('<li>').html(global.fileData.name).add \
$('<li>').html((global.fileData.size >> 10) + " Kb")
else ul.append $('<li>').html(global.fileData)
ul.append $('<hr>').add $('<li>').click(click).html('reset')
controlJpeg = (ctr) ->
check = (obj, text) ->
obj.html(text)
'checked' if text == global.optJpeg
input = '<input type="file" accept="image/*">'
file = -> $(input).click().change ->
return if @files?.length == 0
return if not /image/.test @files[0].type
global.fileJpeg = @files[0]
controlPreview @files[0], 'prvJpeg'
global.optJpeg = 'image'
ctr.html 'image'
controlRefresh()
click = (event) ->
selected = event.target.textContent
selected = 'rand' if selected == 'image'
global.optJpeg = selected
ctr.html selected
controlRefresh()
global.fileJpeg = global.prvJpeg = null
file() if event.target.textContent == 'image'
[a, b, c, ul] = [$('<li>'), $('<li>'), $('<li>'), $('<ul>')]
if global.prvJpeg
ul.append \
$(global.prvJpeg).add \
$('<li>').html(global.fileJpeg.name).add \
$('<li>').html((global.fileJpeg.size >> 10) + ' Kb').add \
$('<hr>')
a.click(click).addClass(check(a, 'rand'))
b.click(click).addClass(check(b, 'grad'))
c.click(click).addClass(check(c, 'image'))
ul.append a.add b.add c
controlInit = (cb) ->
controlDown target: global.dropTarg
for key of global then global[key] = null
$(document).off('keyup').keyup(controlAbort)
document.ondrop = controlDrop; document.onclick = null
document.ondragover = document.ondragenter = eventVoid
$('#control').remove(); $('figure').remove()
$('#progress').remove(); $('form').fadeIn(400)
$('h2').fadeIn(400); $('ul').fadeIn(400)
$('h1').off('click').click(-> controlInit controlProcess)
$('h3').html('').off('click').show()
$('input').prop('disabled', false); abort();
$('input').css('width', 410).css('padding-left', 10)
controlInput 'text', 'Paste a URL or add a file here'
$('<div>').prop('id', 'control').appendTo('form')
$('<div>').prop('id', 'button').addClass('btn-upload')
.appendTo('#control').off('click')
.click(controlFile).hide().fadeIn(400)
$('form').off('submit').submit (event) ->
eventVoid event
controlPreview global.fileData, 'prvData'
pass = -> controlInput 'password', 'Enter password'
done = ->
localStorage.setItem 'method', global.optMethod
localStorage.setItem 'wikisafe', global.optSafe
localStorage.setItem 'container', \
if global.fileJpeg then 'rand' else global.optJpeg
localStorage.setItem 'action', global.optAction \
if global.optData != 'url'
$('h3').html(''); global.optPass = $('input').val() \
if $('input').attr('type') == 'password'
return $('h3').css('opacity', 0) \
.off('click').stop().animate(opacity: 1, 400) \
.html('Empty password not allowed').delay(1000)
.animate(opacity: 0, 400) \
if !global.optPass && global.optMethod != 'join'
$('#control').fadeOut(400).queue ->
controlDown target: global.dropTarg
global.fileJpeg ?= global.optJpeg
$('#control').remove(); global.prvData = null
$('input').css('width', 410).css('padding-left', 10)
controlInput 'password'; global.prvJpeg = null
$('input').prop('disabled', true);
$('<div>').prop('id', 'progress').appendTo('form')
cb $('form').off('submit').submit (e) -> eventVoid e;
global.optAction = localStorage.getItem('action') ? 'encode'
global.optAction = 'decode' if not global.fileData
global.optData = global.fileData && 'file' || 'url'
global.fileData = global.fileData || $('input').val()
global.optMethod = localStorage.getItem('method') ? 'auto'
global.optJpeg = localStorage.getItem('container') ? 'rand'
global.optSafe = localStorage.getItem('wikisafe') ? 'true'
global.optSafe = global.optSafe == 'true'
controlAdd 'ctr-color-1 ctr-start', global.optAction, controlAction
controlAdd 'ctr-from-1 ctr-to-2', null, null
controlAdd 'ctr-color-2', global.optMethod, controlMethod
controlAdd 'ctr-from-2 ctr-to-3', null, null
if global.optAction == 'encode'
controlAdd 'ctr-color-3', global.optData, controlData
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
else controlAdd 'ctr-color-3 ctr-stop', global.optData, controlData
controlAdd 'ctr-float', null, null
$('input').val(''); controlRefresh()
$('#button').removeClass('btn-upload').off('click')
$('#button').addClass('btn-process').click(done)
$('form').off('submit').submit (e) -> eventVoid e; done()
if global.optData == 'file' then pass() else \
setTimeout(pass, 100) && $('#control').hide().fadeIn(400)
controlProgress = (dict) ->
text = dict.name ? dict.type
prog = Math.min(Math.max(dict.progress ? 0, 18), 100) * 4.41 | 0
return $('#progress').html(text) if dict.type != 'progress'
$('#progress').stop().animate(width: prog, 400).html(text)
controlProcess = ->
done = (image, blob) ->
str = blob.name + '<br><span dir="ltr">' +
((blob.size >> 10) + 1) + ' Kb</span>'
$('<figure>').append(image).appendTo('section')
.append($('<figcaption>').html(str)
.css('max-width', $(image).width() - 6))
.click(-> dataURLSave url, blob.name)
.css(opacity: 0).animate(opacity: 1, 400)
error = (url) ->
err = trace(url, true)?.error ? 'Some error occured'
$('h3').stop().css('opacity', 1).html("Oops! #{err} :(")
document.onclick = -> controlInit controlProcess
safari = /^(?!.*Chrome).*Safari.*$/.test navigator.userAgent
dict = action: global.optAction, pass: global.optPass, \
method: global.optMethod, safe: global.optSafe
dict.data = global.fileData if global.optAction == 'decode'
dict.data = global.fileJpeg if global.optAction == 'encode'
dict.hide = global.fileData if global.optAction == 'encode'
await processRequest dict, controlProgress, defer blob
await blobToDataURL blob, safari, defer url
return error url if not okay url
await dataURLToImage url, defer image if /image/.test blob.type
image = $('<div>') if not image? or not okay image
$('h2').fadeOut(400); $('form').fadeOut(400)
$('h3').fadeOut(400); $('ul').fadeOut(400)
setTimeout (-> done image, blob), 450
testBrowser '//browser-update.org/update.html'
jQuery.event.props.push 'dataTransfer'
controlInit controlProcess
console.log """
Privacy is necessary for an open society in the electronic age.
... We cannot expect governments, corporations, or other large,
faceless organizations to grant us privacy ... We must defend
our own privacy if we expect to have any. ... Cypherpunks write
code. We know that someone has to write software to defend
privacy, and ... we're going to write it. (c) <NAME>, 1993
"""
| true |
# Copyright (C) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
global =
optAction: null, fileData: null, dropDown: null,
optMethod: null, fileJpeg: null, dropTimer: null,
optData: null, prvData: null, dropTarg: null,
optJpeg: null, prvJpeg: null,
optSafe: null,
optPass: null
testBrowser = (error) ->
nav = navigator.appName
ua = navigator.userAgent
ans = ua.match /(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\d+)*)/i
tem = ua.match /version\/([\d]+)/i if ans?
ans[2] = tem[1] if tem?
ans = [ans[1], parseInt ans[2]] if ans?
ans = [nav, navigator.appVersion] if not ans?
if ans[0] == 'Safari' and ans[1] > 5 or
ans[0] == 'Chrome' and ans[1] > 24 or
ans[0] == 'Firefox' and ans[1] > 16
return true
window.location.replace error
eventVoid = (event) ->
event.stopPropagation()
event.preventDefault()
controlAbort = (event) ->
if event.which == 27
eventVoid event
return abort()
controlDrop = (event) ->
eventVoid event
return if global.fileData
dataTransfer = event.dataTransfer
if dataTransfer?.files
for file in dataTransfer.files
global.fileData = file
return $('form').submit()
controlFile = ->
$('<input type="file">').click().change ->
if @files?.length > 0
global.fileData = @files[0]
$('form').submit()
controlPreview = (file, key) -> async ->
global[key] = null
return if not file or not /image/.test file.type
await blobToImageData file, defer ans
[w, h] = probeContainerQuot ans?.width, ans?.height, 150
await imageDataToImageData ans, w, h, defer ans
return if not okay ans
cvs = document.createElement 'canvas'
cvs.width = ans.width
cvs.height = ans.height
ctx = cvs.getContext '2d'
ctx.putImageData ans, 0, 0
await dataURLToImage cvs.toDataURL(), defer image
global[key] = image if okay image
controlColor = (obj, delta) ->
color = obj.css('background-color')
color = color.match /rgb\(([\d]+), ([\d]+), ([\d]+)\)/
return if not color
color[1] = parseInt(color[1]) + delta
color[2] = parseInt(color[2]) + delta
color[3] = parseInt(color[3]) + delta
color = "rgb(#{color[1]}, #{color[2]}, #{color[3]})"
obj.css('background-color', color)
obj.next().css('border-left-color', color) \
if /ctr-from/.test obj.next().attr('class')
obj.prev().css('border-top-color', color)
.css('border-bottom-color', color) \
if /ctr-to/.test obj.prev().attr('class')
controlAdd = (cls, text, cb) ->
return $('<div>').addClass(cls).appendTo('#control') if !text
$('<div>')
.html(text)
.addClass('ctr-float ' + cls)
.appendTo($('#control'))
.mouseenter(-> controlColor $(this), -30)
.mouseleave(-> controlColor $(this), +30)
.click(cb, controlDown)
controlRefresh = ->
offset = $('#control div.ctr-float:last').position()?.left | 0
$('input').css('padding-left', 10 + offset)
$('input').css('width', 410 - offset)
controlInput = (type, val) ->
keypress = (event) ->
input = $(event.target)
if event.which == 13 and type != 'password' and
(input.val() == val or input.val() == '')
controlFile(); return eventVoid event
if input.prop('type') != type
input.removeAttr('type').prop('type', type).val('')
input.focus().select()
blur = (input) ->
if input.val() == ''
input.removeAttr('type').prop('type', 'text').val(val)
paste = (input) ->
if input.prop('type') == 'text'
setTimeout (-> $('form').submit()), 100
$('input')
.clone().val(val).attr('type', 'text')
.keypress(keypress)
.blur(-> blur $(this))
.click(-> $(this).select())
.on('paste', -> paste $(this))
.on('drop', controlDrop)
.insertBefore($('input'))
.focus().select().next().remove()
controlDown = (event) ->
remove = ->
global.dropDown.remove() if global.dropDown
global.dropDown = null
clear = ->
clearTimeout global.dropTimer if global.dropTimer
global.dropTimer = global.dropTarg = null
timeout = ->
clear(); global.dropDown?.fadeOut(200).queue(remove)
set = ->
clear(); global.dropTimer = setTimeout timeout, 3000
return timeout() if global.dropTarg == event.target
return event.data($(event.target)) && timeout() \
if event.data == controlAction
remove() || set()
html = $('<div>').addClass('drop-arrow').add \
$('<div>').addClass('drop-content').html \
event.data $(event.target)
global.dropTarg = event.target
global.dropDown = $('<div>')
.html(html)
.css('position', 'absolute')
.css('top', event.pageY + 20)
.css('left', event.pageX - 75)
.mouseenter(clear).mouseleave(set)
.click(timeout).appendTo('body')
.hide().fadeIn(200)
controlAction = (ctr) ->
set = (action) ->
return if action == global.optAction
if action == 'decode'
$('.ctr-color-3').addClass('ctr-stop')
$('.ctr-color-4').remove()
return $('.ctr-to-4').remove()
$('.ctr-color-3').removeClass('ctr-stop').next().remove()
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
controlAdd 'ctr-float', null, null
return if global.optData != 'file'
action = 'encode' if global.optAction == 'decode'
action = 'decode' if global.optAction == 'encode'
if action == 'encode'
$('.ctr-color-3').removeClass('ctr-stop').next().remove()
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
controlAdd 'ctr-float', null, null
else $('.ctr-color-3').addClass('ctr-stop'); \
$('.ctr-color-4').remove(); $('.ctr-to-4').remove()
global.optAction = action
ctr.html(action); controlRefresh()
controlMethod = (ctr) ->
check = (obj, text) ->
obj.html(text)
'checked' if text == global.optMethod
click = (event) ->
global.optMethod = event.target.textContent
ctr.html event.target.textContent
controlRefresh()
checkS = (obj, text) ->
obj.html(text)
'checked' if not global.optSafe
clickS = (event) ->
global.optSafe = !global.optSafe; true
[a, b, c, d] = [$('<li>'), $('<li>'), $('<li>'), $('<li>')]
a.click(click).addClass(check(a, 'auto'))
b.click(click).addClass(check(b, 'join'))
c.click(click).addClass(check(c, 'steg'))
d.click(clickS).addClass(checkS(d, 'unsafe'))
$('<ul>').append a.add b.add c.add $('<hr>').add d
controlData = (ctr) ->
ul = $('<ul>')
click = -> controlInit controlProcess
if global.prvData
ul.append $(global.prvData)
if global.optData == 'file'
ul.append $('<li>').html(global.fileData.name).add \
$('<li>').html((global.fileData.size >> 10) + " Kb")
else ul.append $('<li>').html(global.fileData)
ul.append $('<hr>').add $('<li>').click(click).html('reset')
controlJpeg = (ctr) ->
check = (obj, text) ->
obj.html(text)
'checked' if text == global.optJpeg
input = '<input type="file" accept="image/*">'
file = -> $(input).click().change ->
return if @files?.length == 0
return if not /image/.test @files[0].type
global.fileJpeg = @files[0]
controlPreview @files[0], 'prvJpeg'
global.optJpeg = 'image'
ctr.html 'image'
controlRefresh()
click = (event) ->
selected = event.target.textContent
selected = 'rand' if selected == 'image'
global.optJpeg = selected
ctr.html selected
controlRefresh()
global.fileJpeg = global.prvJpeg = null
file() if event.target.textContent == 'image'
[a, b, c, ul] = [$('<li>'), $('<li>'), $('<li>'), $('<ul>')]
if global.prvJpeg
ul.append \
$(global.prvJpeg).add \
$('<li>').html(global.fileJpeg.name).add \
$('<li>').html((global.fileJpeg.size >> 10) + ' Kb').add \
$('<hr>')
a.click(click).addClass(check(a, 'rand'))
b.click(click).addClass(check(b, 'grad'))
c.click(click).addClass(check(c, 'image'))
ul.append a.add b.add c
controlInit = (cb) ->
controlDown target: global.dropTarg
for key of global then global[key] = null
$(document).off('keyup').keyup(controlAbort)
document.ondrop = controlDrop; document.onclick = null
document.ondragover = document.ondragenter = eventVoid
$('#control').remove(); $('figure').remove()
$('#progress').remove(); $('form').fadeIn(400)
$('h2').fadeIn(400); $('ul').fadeIn(400)
$('h1').off('click').click(-> controlInit controlProcess)
$('h3').html('').off('click').show()
$('input').prop('disabled', false); abort();
$('input').css('width', 410).css('padding-left', 10)
controlInput 'text', 'Paste a URL or add a file here'
$('<div>').prop('id', 'control').appendTo('form')
$('<div>').prop('id', 'button').addClass('btn-upload')
.appendTo('#control').off('click')
.click(controlFile).hide().fadeIn(400)
$('form').off('submit').submit (event) ->
eventVoid event
controlPreview global.fileData, 'prvData'
pass = -> controlInput 'password', 'Enter password'
done = ->
localStorage.setItem 'method', global.optMethod
localStorage.setItem 'wikisafe', global.optSafe
localStorage.setItem 'container', \
if global.fileJpeg then 'rand' else global.optJpeg
localStorage.setItem 'action', global.optAction \
if global.optData != 'url'
$('h3').html(''); global.optPass = $('input').val() \
if $('input').attr('type') == 'password'
return $('h3').css('opacity', 0) \
.off('click').stop().animate(opacity: 1, 400) \
.html('Empty password not allowed').delay(1000)
.animate(opacity: 0, 400) \
if !global.optPass && global.optMethod != 'join'
$('#control').fadeOut(400).queue ->
controlDown target: global.dropTarg
global.fileJpeg ?= global.optJpeg
$('#control').remove(); global.prvData = null
$('input').css('width', 410).css('padding-left', 10)
controlInput 'password'; global.prvJpeg = null
$('input').prop('disabled', true);
$('<div>').prop('id', 'progress').appendTo('form')
cb $('form').off('submit').submit (e) -> eventVoid e;
global.optAction = localStorage.getItem('action') ? 'encode'
global.optAction = 'decode' if not global.fileData
global.optData = global.fileData && 'file' || 'url'
global.fileData = global.fileData || $('input').val()
global.optMethod = localStorage.getItem('method') ? 'auto'
global.optJpeg = localStorage.getItem('container') ? 'rand'
global.optSafe = localStorage.getItem('wikisafe') ? 'true'
global.optSafe = global.optSafe == 'true'
controlAdd 'ctr-color-1 ctr-start', global.optAction, controlAction
controlAdd 'ctr-from-1 ctr-to-2', null, null
controlAdd 'ctr-color-2', global.optMethod, controlMethod
controlAdd 'ctr-from-2 ctr-to-3', null, null
if global.optAction == 'encode'
controlAdd 'ctr-color-3', global.optData, controlData
controlAdd 'ctr-from-3 ctr-to-4', null, null
controlAdd 'ctr-color-4 ctr-stop', global.optJpeg, controlJpeg
else controlAdd 'ctr-color-3 ctr-stop', global.optData, controlData
controlAdd 'ctr-float', null, null
$('input').val(''); controlRefresh()
$('#button').removeClass('btn-upload').off('click')
$('#button').addClass('btn-process').click(done)
$('form').off('submit').submit (e) -> eventVoid e; done()
if global.optData == 'file' then pass() else \
setTimeout(pass, 100) && $('#control').hide().fadeIn(400)
controlProgress = (dict) ->
text = dict.name ? dict.type
prog = Math.min(Math.max(dict.progress ? 0, 18), 100) * 4.41 | 0
return $('#progress').html(text) if dict.type != 'progress'
$('#progress').stop().animate(width: prog, 400).html(text)
controlProcess = ->
done = (image, blob) ->
str = blob.name + '<br><span dir="ltr">' +
((blob.size >> 10) + 1) + ' Kb</span>'
$('<figure>').append(image).appendTo('section')
.append($('<figcaption>').html(str)
.css('max-width', $(image).width() - 6))
.click(-> dataURLSave url, blob.name)
.css(opacity: 0).animate(opacity: 1, 400)
error = (url) ->
err = trace(url, true)?.error ? 'Some error occured'
$('h3').stop().css('opacity', 1).html("Oops! #{err} :(")
document.onclick = -> controlInit controlProcess
safari = /^(?!.*Chrome).*Safari.*$/.test navigator.userAgent
dict = action: global.optAction, pass: global.optPass, \
method: global.optMethod, safe: global.optSafe
dict.data = global.fileData if global.optAction == 'decode'
dict.data = global.fileJpeg if global.optAction == 'encode'
dict.hide = global.fileData if global.optAction == 'encode'
await processRequest dict, controlProgress, defer blob
await blobToDataURL blob, safari, defer url
return error url if not okay url
await dataURLToImage url, defer image if /image/.test blob.type
image = $('<div>') if not image? or not okay image
$('h2').fadeOut(400); $('form').fadeOut(400)
$('h3').fadeOut(400); $('ul').fadeOut(400)
setTimeout (-> done image, blob), 450
testBrowser '//browser-update.org/update.html'
jQuery.event.props.push 'dataTransfer'
controlInit controlProcess
console.log """
Privacy is necessary for an open society in the electronic age.
... We cannot expect governments, corporations, or other large,
faceless organizations to grant us privacy ... We must defend
our own privacy if we expect to have any. ... Cypherpunks write
code. We know that someone has to write software to defend
privacy, and ... we're going to write it. (c) PI:NAME:<NAME>END_PI, 1993
"""
|
[
{
"context": "un\")\n\ngenid = (len = 16, prefix = \"\", keyspace = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") ->\n prefix += keyspace.charAt(Math.floor(Math.",
"end": 554,
"score": 0.99964839220047,
"start": 492,
"tag": "KEY",
"value": "ABCDEFGHIJKLMNOPQRSTUVWXYZab... | index.coffee | biomassives/plunker_run | 2 | express = require("express")
nconf = require("nconf")
_ = require("underscore")._
validator = require("json-schema")
mime = require("mime")
url = require("url")
request = require("request")
path = require("path")
#ga = require("node-ga")
genid = require("genid")
lactate = require("lactate")
path = require("path")
fs = require("fs")
# Set defaults in nconf
require "./configure"
app = module.exports = express()
runUrl = nconf.get("url:run")
genid = (len = 16, prefix = "", keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
#app.use ga("UA-28928507-4", safe: false)
#app.use require("./middleware/subdomain").middleware()
app.use require("./middleware/cors").middleware()
app.use express.urlencoded()
app.use express.json()
app.use lactate.static "#{__dirname}/public",
'max age': 'one week'
LRU = require("lru-cache")
previews = LRU(512)
sourcemaps = LRU(512)
apiUrl = nconf.get("url:api")
coffee = require("coffee-script")
livescript = require("LiveScript")
less = require("less")
sass = require("sass")
scss = require("node-sass")
jade = require("jade")
markdown = require("marked")
stylus = require("stylus")
nib = require("nib")
traceur = require("traceur")
TRACEUR_RUNTIME = ""
fs.readFile traceur.RUNTIME_PATH, "utf8", (err, src) ->
unless err then TRACEUR_RUNTIME = src
compilers =
scss:
match: /\.css$/
ext: ['scss']
compile: (path, filename, source, str, plunk, fn) ->
try
scss.render(str, fn)
catch err
fn(err)
sass:
match: /\.css$/
ext: ['sass']
compile: (path, filename, source, str, plunk, fn) ->
try
fn(null, sass.render(str))
catch err
fn(err)
less:
match: /\.css$/
ext: ['less']
compile: (path, filename, source, str, plunk, fn) ->
try
less.render(str, fn)
catch err
fn(err)
stylus:
match: /\.css/
ext: ['styl']
compile: (path, filename, source, str, plunk, fn) ->
try
stylus(str)
.use(nib())
.import("nib")
.render(fn)
catch err
fn(err)
coffeescript:
match: /\.js$/
ext: ['coffee']
compile: (path, filename, source, str, plunk, fn) ->
try
answer = coffee.compile str,
bare: true
returnObject: true
sourceMap: true
filename: source
sourceFiles: [path+source]
generatedFile: path+filename
js = answer.js + "\n//# sourceMappingURL=#{path}#{filename}.map"
smap = answer.v3SourceMap
fn null, js, smap
catch err
fn(err)
traceur:
match: /\.js$/
ext: ['es6.js']
compile: (path, filename, source, str, plunk, fn) ->
try
answer = traceur.compile str,
bare: true
sourceMap: true
experimental: true
filename: source
if answer.errors.length
error = new Error("Error compiling #{filename}")
error.data = answer.errors
fn error
else
js = TRACEUR_RUNTIME + ";\n" + answer.js + "\n//# sourceMappingURL=#{path}#{filename}.map"
smap = answer.sourceMap
fn null, js, smap
catch err
fn(err)
livescript:
match: /\.js$/
ext: ['ls']
compile: (path, filename, source, str, plunk, fn) ->
try
fn(null, livescript.compile(str))
catch err
fn(err)
jade:
match: /\.html$/
ext: ['jade']
compile: (path, filename, source, str, plunk, fn) ->
render = jade.compile(str, pretty: true)
try
fn(null, render({}))
catch err
fn(err)
markdown:
match: /\.html$/
ext: ['md',"markdown"]
compile: (path, filename, source, str, plunk, fn) ->
return fn(null, "") unless source
try
fn null, """
<link rel="stylesheet" href="/markdown.css" type="text/css">
#{markdown(str)}
"""
catch err
fn(err)
typescript: require("./compilers/typescript")
renderPlunkFile = (req, res, next) ->
plunk = req.plunk
filename = req.params[0] or "index.html"
file = plunk.files[filename]
res.set "Cache-Control", "no-cache"
res.set "Expires", 0
if file
file.mime ||= mime.lookup(filename, "text/plain")
res.set("Content-Type": if req.accepts(file.mime) then file.mime else "text/plain")
res.set("ETag", file.etag)
if (etag = req.get("if-none-match")) and etag is file.etag then return res.send(304)
return res.send(200, file.content)
else
render = (filename) ->
extension = "." + path.basename(filename).split(".").slice(1).join(".")
base = path.join path.dirname(filename), path.basename(filename, extension)
type = mime.lookup(filename) or "text/plain"
for name, compiler of compilers when filename.match(compiler.match)
for ext in compiler.ext
if found = plunk.files["#{base}.#{ext}"]
compiler.compile req.dir, filename, found.filename, found.content, plunk, (err, compiled, sourcemap) ->
if err
console.log "[ERR] Compilation error:", err.message
return res.json 500, err.data or "Compilation error"
else
if sourcemap
sourcemapFile = "#{filename}.map"
smap = plunk.files[sourcemapFile] =
filename: sourcemapFile
content: sourcemap
source: "#{base}.#{ext}"
mime: "application/json"
run_url: plunk.run_url + sourcemapFile
etag: genid(16) + plunk.frozen_at
res.set "SourceMap", req.dir + sourcemapFile
file = plunk.files[filename] =
filename: filename
content: compiled
source: "#{base}.#{ext}"
mime: mime.lookup(filename, "text/plain")
run_url: plunk.run_url + filename
etag: genid(16) + plunk.frozen_at
found.children ||= []
found.children.push(file)
found.children.push(smap) if smap
res.set("Content-Type": if req.accepts(file.mime) then file.mime else "text/plain")
res.set("ETag", file.etag)
res.send 200, compiled
return true
test = [filename]
test.push(file) for file in ["index.html", "example.html", "README.html", "demo.html", "readme.html"] when 0 > test.indexOf(file)
for attempt in test
return if render(attempt)
# Control will reach here if no file was found
console.log "[ERR] No suitable source file for: ", filename
res.send(404)
app.get "/plunks/:id/*", (req, res, next) ->
req_url = url.parse(req.url)
unless req.params[0] or /\/$/.test(req_url.pathname)
req_url.pathname += "/"
return res.redirect(301, url.format(req_url))
req.dir = "/plunks/#{req.params.id}/"
request {url: "#{apiUrl}/plunks/#{req.params.id}?nv=1", json: true}, (err, response, body) ->
return res.send(500) if err
return res.send(response.statusCode) if response.statusCode >= 400
req.plunk = body
try
unless req.plunk then res.send(404) # TODO: Better error page
else renderPlunkFile(req, res, next)
catch e
console.trace "[ERR] Error rendering file", e
res.send 500
app.get "/plunks/:id", (req, res) -> res.redirect(301, "/plunks/#{req.params.id}/")
app.post "/:id?", (req, res, next) ->
json = req.body
schema = require("./schema/previews/create")
{valid, errors} = validator.validate(json, schema)
# Despite its awesomeness, validator does not support disallow or additionalProperties; we need to check plunk.files size
if json.files and _.isEmpty(json.files)
valid = false
errors.push
attribute: "minProperties"
property: "files"
message: "A minimum of one file is required"
unless valid then return next(new Error("Invalid json: #{errors}"))
else
id = req.params.id or genid() # Don't care about id clashes. They are disposable anyway
prev = previews.get(req.params.id)
json.id = id
json.run_url = "#{runUrl}/#{id}/"
_.each json.files, (file, filename) ->
if prev && ((prevFile = prev?.files[filename])?.content is file.content)
json.files[filename] = prevFile
json.files[child.filename] = child for child in prevFile.children
else
json.files[filename] =
filename: filename
content: file.content
mime: mime.lookup(filename, "text/plain")
run_url: json.run_url + filename
etag: genid(16)
children: []
previews.set(id, json)
#return res.redirect "/#{id}/"
status = if prev then 200 else 201
req.plunk = json
req.dir = "/#{id}/"
if req.is("application/x-www-form-urlencoded")
res.header "X-XSS-Protection", 0
renderPlunkFile(req, res, next)
else
res.json status, url: json.run_url
app.get "/:id/*", (req, res, next) ->
unless req.plunk = previews.get(req.params.id) then res.send(404) # TODO: Better error page
else
req_url = url.parse(req.url)
unless req.params[0] or /\/$/.test(req_url.pathname)
req_url.pathname += "/"
return res.redirect(301, url.format(req_url))
req.dir = "/#{req.params.id}/"
renderPlunkFile(req, res, next)
app.get "*", (req, res) ->
res.send(404, "Preview does not exist or has expired.") | 83279 | express = require("express")
nconf = require("nconf")
_ = require("underscore")._
validator = require("json-schema")
mime = require("mime")
url = require("url")
request = require("request")
path = require("path")
#ga = require("node-ga")
genid = require("genid")
lactate = require("lactate")
path = require("path")
fs = require("fs")
# Set defaults in nconf
require "./configure"
app = module.exports = express()
runUrl = nconf.get("url:run")
genid = (len = 16, prefix = "", keyspace = "<KEY>") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
#app.use ga("UA-28928507-4", safe: false)
#app.use require("./middleware/subdomain").middleware()
app.use require("./middleware/cors").middleware()
app.use express.urlencoded()
app.use express.json()
app.use lactate.static "#{__dirname}/public",
'max age': 'one week'
LRU = require("lru-cache")
previews = LRU(512)
sourcemaps = LRU(512)
apiUrl = nconf.get("url:api")
coffee = require("coffee-script")
livescript = require("LiveScript")
less = require("less")
sass = require("sass")
scss = require("node-sass")
jade = require("jade")
markdown = require("marked")
stylus = require("stylus")
nib = require("nib")
traceur = require("traceur")
TRACEUR_RUNTIME = ""
fs.readFile traceur.RUNTIME_PATH, "utf8", (err, src) ->
unless err then TRACEUR_RUNTIME = src
compilers =
scss:
match: /\.css$/
ext: ['scss']
compile: (path, filename, source, str, plunk, fn) ->
try
scss.render(str, fn)
catch err
fn(err)
sass:
match: /\.css$/
ext: ['sass']
compile: (path, filename, source, str, plunk, fn) ->
try
fn(null, sass.render(str))
catch err
fn(err)
less:
match: /\.css$/
ext: ['less']
compile: (path, filename, source, str, plunk, fn) ->
try
less.render(str, fn)
catch err
fn(err)
stylus:
match: /\.css/
ext: ['styl']
compile: (path, filename, source, str, plunk, fn) ->
try
stylus(str)
.use(nib())
.import("nib")
.render(fn)
catch err
fn(err)
coffeescript:
match: /\.js$/
ext: ['coffee']
compile: (path, filename, source, str, plunk, fn) ->
try
answer = coffee.compile str,
bare: true
returnObject: true
sourceMap: true
filename: source
sourceFiles: [path+source]
generatedFile: path+filename
js = answer.js + "\n//# sourceMappingURL=#{path}#{filename}.map"
smap = answer.v3SourceMap
fn null, js, smap
catch err
fn(err)
traceur:
match: /\.js$/
ext: ['es6.js']
compile: (path, filename, source, str, plunk, fn) ->
try
answer = traceur.compile str,
bare: true
sourceMap: true
experimental: true
filename: source
if answer.errors.length
error = new Error("Error compiling #{filename}")
error.data = answer.errors
fn error
else
js = TRACEUR_RUNTIME + ";\n" + answer.js + "\n//# sourceMappingURL=#{path}#{filename}.map"
smap = answer.sourceMap
fn null, js, smap
catch err
fn(err)
livescript:
match: /\.js$/
ext: ['ls']
compile: (path, filename, source, str, plunk, fn) ->
try
fn(null, livescript.compile(str))
catch err
fn(err)
jade:
match: /\.html$/
ext: ['jade']
compile: (path, filename, source, str, plunk, fn) ->
render = jade.compile(str, pretty: true)
try
fn(null, render({}))
catch err
fn(err)
markdown:
match: /\.html$/
ext: ['md',"markdown"]
compile: (path, filename, source, str, plunk, fn) ->
return fn(null, "") unless source
try
fn null, """
<link rel="stylesheet" href="/markdown.css" type="text/css">
#{markdown(str)}
"""
catch err
fn(err)
typescript: require("./compilers/typescript")
renderPlunkFile = (req, res, next) ->
plunk = req.plunk
filename = req.params[0] or "index.html"
file = plunk.files[filename]
res.set "Cache-Control", "no-cache"
res.set "Expires", 0
if file
file.mime ||= mime.lookup(filename, "text/plain")
res.set("Content-Type": if req.accepts(file.mime) then file.mime else "text/plain")
res.set("ETag", file.etag)
if (etag = req.get("if-none-match")) and etag is file.etag then return res.send(304)
return res.send(200, file.content)
else
render = (filename) ->
extension = "." + path.basename(filename).split(".").slice(1).join(".")
base = path.join path.dirname(filename), path.basename(filename, extension)
type = mime.lookup(filename) or "text/plain"
for name, compiler of compilers when filename.match(compiler.match)
for ext in compiler.ext
if found = plunk.files["#{base}.#{ext}"]
compiler.compile req.dir, filename, found.filename, found.content, plunk, (err, compiled, sourcemap) ->
if err
console.log "[ERR] Compilation error:", err.message
return res.json 500, err.data or "Compilation error"
else
if sourcemap
sourcemapFile = "#{filename}.map"
smap = plunk.files[sourcemapFile] =
filename: sourcemapFile
content: sourcemap
source: "#{base}.#{ext}"
mime: "application/json"
run_url: plunk.run_url + sourcemapFile
etag: genid(16) + plunk.frozen_at
res.set "SourceMap", req.dir + sourcemapFile
file = plunk.files[filename] =
filename: filename
content: compiled
source: "#{base}.#{ext}"
mime: mime.lookup(filename, "text/plain")
run_url: plunk.run_url + filename
etag: genid(16) + plunk.frozen_at
found.children ||= []
found.children.push(file)
found.children.push(smap) if smap
res.set("Content-Type": if req.accepts(file.mime) then file.mime else "text/plain")
res.set("ETag", file.etag)
res.send 200, compiled
return true
test = [filename]
test.push(file) for file in ["index.html", "example.html", "README.html", "demo.html", "readme.html"] when 0 > test.indexOf(file)
for attempt in test
return if render(attempt)
# Control will reach here if no file was found
console.log "[ERR] No suitable source file for: ", filename
res.send(404)
app.get "/plunks/:id/*", (req, res, next) ->
req_url = url.parse(req.url)
unless req.params[0] or /\/$/.test(req_url.pathname)
req_url.pathname += "/"
return res.redirect(301, url.format(req_url))
req.dir = "/plunks/#{req.params.id}/"
request {url: "#{apiUrl}/plunks/#{req.params.id}?nv=1", json: true}, (err, response, body) ->
return res.send(500) if err
return res.send(response.statusCode) if response.statusCode >= 400
req.plunk = body
try
unless req.plunk then res.send(404) # TODO: Better error page
else renderPlunkFile(req, res, next)
catch e
console.trace "[ERR] Error rendering file", e
res.send 500
app.get "/plunks/:id", (req, res) -> res.redirect(301, "/plunks/#{req.params.id}/")
app.post "/:id?", (req, res, next) ->
json = req.body
schema = require("./schema/previews/create")
{valid, errors} = validator.validate(json, schema)
# Despite its awesomeness, validator does not support disallow or additionalProperties; we need to check plunk.files size
if json.files and _.isEmpty(json.files)
valid = false
errors.push
attribute: "minProperties"
property: "files"
message: "A minimum of one file is required"
unless valid then return next(new Error("Invalid json: #{errors}"))
else
id = req.params.id or genid() # Don't care about id clashes. They are disposable anyway
prev = previews.get(req.params.id)
json.id = id
json.run_url = "#{runUrl}/#{id}/"
_.each json.files, (file, filename) ->
if prev && ((prevFile = prev?.files[filename])?.content is file.content)
json.files[filename] = prevFile
json.files[child.filename] = child for child in prevFile.children
else
json.files[filename] =
filename: filename
content: file.content
mime: mime.lookup(filename, "text/plain")
run_url: json.run_url + filename
etag: genid(16)
children: []
previews.set(id, json)
#return res.redirect "/#{id}/"
status = if prev then 200 else 201
req.plunk = json
req.dir = "/#{id}/"
if req.is("application/x-www-form-urlencoded")
res.header "X-XSS-Protection", 0
renderPlunkFile(req, res, next)
else
res.json status, url: json.run_url
app.get "/:id/*", (req, res, next) ->
unless req.plunk = previews.get(req.params.id) then res.send(404) # TODO: Better error page
else
req_url = url.parse(req.url)
unless req.params[0] or /\/$/.test(req_url.pathname)
req_url.pathname += "/"
return res.redirect(301, url.format(req_url))
req.dir = "/#{req.params.id}/"
renderPlunkFile(req, res, next)
app.get "*", (req, res) ->
res.send(404, "Preview does not exist or has expired.") | true | express = require("express")
nconf = require("nconf")
_ = require("underscore")._
validator = require("json-schema")
mime = require("mime")
url = require("url")
request = require("request")
path = require("path")
#ga = require("node-ga")
genid = require("genid")
lactate = require("lactate")
path = require("path")
fs = require("fs")
# Set defaults in nconf
require "./configure"
app = module.exports = express()
runUrl = nconf.get("url:run")
genid = (len = 16, prefix = "", keyspace = "PI:KEY:<KEY>END_PI") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
#app.use ga("UA-28928507-4", safe: false)
#app.use require("./middleware/subdomain").middleware()
app.use require("./middleware/cors").middleware()
app.use express.urlencoded()
app.use express.json()
app.use lactate.static "#{__dirname}/public",
'max age': 'one week'
LRU = require("lru-cache")
previews = LRU(512)
sourcemaps = LRU(512)
apiUrl = nconf.get("url:api")
coffee = require("coffee-script")
livescript = require("LiveScript")
less = require("less")
sass = require("sass")
scss = require("node-sass")
jade = require("jade")
markdown = require("marked")
stylus = require("stylus")
nib = require("nib")
traceur = require("traceur")
TRACEUR_RUNTIME = ""
fs.readFile traceur.RUNTIME_PATH, "utf8", (err, src) ->
unless err then TRACEUR_RUNTIME = src
compilers =
scss:
match: /\.css$/
ext: ['scss']
compile: (path, filename, source, str, plunk, fn) ->
try
scss.render(str, fn)
catch err
fn(err)
sass:
match: /\.css$/
ext: ['sass']
compile: (path, filename, source, str, plunk, fn) ->
try
fn(null, sass.render(str))
catch err
fn(err)
less:
match: /\.css$/
ext: ['less']
compile: (path, filename, source, str, plunk, fn) ->
try
less.render(str, fn)
catch err
fn(err)
stylus:
match: /\.css/
ext: ['styl']
compile: (path, filename, source, str, plunk, fn) ->
try
stylus(str)
.use(nib())
.import("nib")
.render(fn)
catch err
fn(err)
coffeescript:
match: /\.js$/
ext: ['coffee']
compile: (path, filename, source, str, plunk, fn) ->
try
answer = coffee.compile str,
bare: true
returnObject: true
sourceMap: true
filename: source
sourceFiles: [path+source]
generatedFile: path+filename
js = answer.js + "\n//# sourceMappingURL=#{path}#{filename}.map"
smap = answer.v3SourceMap
fn null, js, smap
catch err
fn(err)
traceur:
match: /\.js$/
ext: ['es6.js']
compile: (path, filename, source, str, plunk, fn) ->
try
answer = traceur.compile str,
bare: true
sourceMap: true
experimental: true
filename: source
if answer.errors.length
error = new Error("Error compiling #{filename}")
error.data = answer.errors
fn error
else
js = TRACEUR_RUNTIME + ";\n" + answer.js + "\n//# sourceMappingURL=#{path}#{filename}.map"
smap = answer.sourceMap
fn null, js, smap
catch err
fn(err)
livescript:
match: /\.js$/
ext: ['ls']
compile: (path, filename, source, str, plunk, fn) ->
try
fn(null, livescript.compile(str))
catch err
fn(err)
jade:
match: /\.html$/
ext: ['jade']
compile: (path, filename, source, str, plunk, fn) ->
render = jade.compile(str, pretty: true)
try
fn(null, render({}))
catch err
fn(err)
markdown:
match: /\.html$/
ext: ['md',"markdown"]
compile: (path, filename, source, str, plunk, fn) ->
return fn(null, "") unless source
try
fn null, """
<link rel="stylesheet" href="/markdown.css" type="text/css">
#{markdown(str)}
"""
catch err
fn(err)
typescript: require("./compilers/typescript")
renderPlunkFile = (req, res, next) ->
plunk = req.plunk
filename = req.params[0] or "index.html"
file = plunk.files[filename]
res.set "Cache-Control", "no-cache"
res.set "Expires", 0
if file
file.mime ||= mime.lookup(filename, "text/plain")
res.set("Content-Type": if req.accepts(file.mime) then file.mime else "text/plain")
res.set("ETag", file.etag)
if (etag = req.get("if-none-match")) and etag is file.etag then return res.send(304)
return res.send(200, file.content)
else
render = (filename) ->
extension = "." + path.basename(filename).split(".").slice(1).join(".")
base = path.join path.dirname(filename), path.basename(filename, extension)
type = mime.lookup(filename) or "text/plain"
for name, compiler of compilers when filename.match(compiler.match)
for ext in compiler.ext
if found = plunk.files["#{base}.#{ext}"]
compiler.compile req.dir, filename, found.filename, found.content, plunk, (err, compiled, sourcemap) ->
if err
console.log "[ERR] Compilation error:", err.message
return res.json 500, err.data or "Compilation error"
else
if sourcemap
sourcemapFile = "#{filename}.map"
smap = plunk.files[sourcemapFile] =
filename: sourcemapFile
content: sourcemap
source: "#{base}.#{ext}"
mime: "application/json"
run_url: plunk.run_url + sourcemapFile
etag: genid(16) + plunk.frozen_at
res.set "SourceMap", req.dir + sourcemapFile
file = plunk.files[filename] =
filename: filename
content: compiled
source: "#{base}.#{ext}"
mime: mime.lookup(filename, "text/plain")
run_url: plunk.run_url + filename
etag: genid(16) + plunk.frozen_at
found.children ||= []
found.children.push(file)
found.children.push(smap) if smap
res.set("Content-Type": if req.accepts(file.mime) then file.mime else "text/plain")
res.set("ETag", file.etag)
res.send 200, compiled
return true
test = [filename]
test.push(file) for file in ["index.html", "example.html", "README.html", "demo.html", "readme.html"] when 0 > test.indexOf(file)
for attempt in test
return if render(attempt)
# Control will reach here if no file was found
console.log "[ERR] No suitable source file for: ", filename
res.send(404)
app.get "/plunks/:id/*", (req, res, next) ->
req_url = url.parse(req.url)
unless req.params[0] or /\/$/.test(req_url.pathname)
req_url.pathname += "/"
return res.redirect(301, url.format(req_url))
req.dir = "/plunks/#{req.params.id}/"
request {url: "#{apiUrl}/plunks/#{req.params.id}?nv=1", json: true}, (err, response, body) ->
return res.send(500) if err
return res.send(response.statusCode) if response.statusCode >= 400
req.plunk = body
try
unless req.plunk then res.send(404) # TODO: Better error page
else renderPlunkFile(req, res, next)
catch e
console.trace "[ERR] Error rendering file", e
res.send 500
app.get "/plunks/:id", (req, res) -> res.redirect(301, "/plunks/#{req.params.id}/")
app.post "/:id?", (req, res, next) ->
json = req.body
schema = require("./schema/previews/create")
{valid, errors} = validator.validate(json, schema)
# Despite its awesomeness, validator does not support disallow or additionalProperties; we need to check plunk.files size
if json.files and _.isEmpty(json.files)
valid = false
errors.push
attribute: "minProperties"
property: "files"
message: "A minimum of one file is required"
unless valid then return next(new Error("Invalid json: #{errors}"))
else
id = req.params.id or genid() # Don't care about id clashes. They are disposable anyway
prev = previews.get(req.params.id)
json.id = id
json.run_url = "#{runUrl}/#{id}/"
_.each json.files, (file, filename) ->
if prev && ((prevFile = prev?.files[filename])?.content is file.content)
json.files[filename] = prevFile
json.files[child.filename] = child for child in prevFile.children
else
json.files[filename] =
filename: filename
content: file.content
mime: mime.lookup(filename, "text/plain")
run_url: json.run_url + filename
etag: genid(16)
children: []
previews.set(id, json)
#return res.redirect "/#{id}/"
status = if prev then 200 else 201
req.plunk = json
req.dir = "/#{id}/"
if req.is("application/x-www-form-urlencoded")
res.header "X-XSS-Protection", 0
renderPlunkFile(req, res, next)
else
res.json status, url: json.run_url
app.get "/:id/*", (req, res, next) ->
unless req.plunk = previews.get(req.params.id) then res.send(404) # TODO: Better error page
else
req_url = url.parse(req.url)
unless req.params[0] or /\/$/.test(req_url.pathname)
req_url.pathname += "/"
return res.redirect(301, url.format(req_url))
req.dir = "/#{req.params.id}/"
renderPlunkFile(req, res, next)
app.get "*", (req, res) ->
res.send(404, "Preview does not exist or has expired.") |
[
{
"context": " document.getElementById('client-id')\nclientId = '1d228d706ce170d61f9368b5967bd7a1641e6ecf742434dc198047f1a36a930a'\nredirect = 'http://localhost:8000/'\nscopes = [\n ",
"end": 364,
"score": 0.9995992183685303,
"start": 300,
"tag": "KEY",
"value": "1d228d706ce170d61f9368b5967b... | test/init.coffee | teamsnap/teamsnap-javascript-sdk | 9 | chai.should()
window.expect = chai.expect
authSection = document.getElementById('auth')
authButton = document.getElementById('auth-button')
apiInput = document.getElementById('api-url')
authInput = document.getElementById('auth-url')
clientIdInput = document.getElementById('client-id')
clientId = '1d228d706ce170d61f9368b5967bd7a1641e6ecf742434dc198047f1a36a930a'
redirect = 'http://localhost:8000/'
scopes = [
'read'
'write'
]
if (url = localStorage.getItem 'teamsnap.apiUrl')
apiInput.value = url if url
if (url = localStorage.getItem 'teamsnap.authUrl')
authInput.value = url if url
id = localStorage.getItem 'teamsnap.clientId'
clientId = id or clientId
clientIdInput.value = clientId
teamsnap.apiUrl = apiInput.value
teamsnap.authUrl = authInput.value
teamsnap.clientId = clientIdInput.value
apiInput.addEventListener 'change', ->
teamsnap.apiUrl = apiInput.value
localStorage.setItem 'teamsnap.apiUrl', apiInput.value
authInput.addEventListener 'change', ->
teamsnap.authUrl = authInput.value
localStorage.setItem 'teamsnap.authUrl', authInput.value
clientIdInput.addEventListener 'change', ->
clientId = clientIdInput.value
teamsnap.init clientId if clientId
localStorage.setItem 'teamsnap.clientId', clientId
whenAuthed = ->
authSection.parentNode.removeChild authSection
sessionStorage.setItem 'collections', JSON.stringify(teamsnap.collections)
mocha.setup('bdd')
window.require.list().filter((_) -> /^test/.test(_)).forEach(require)
mocha.run()
whenAuthFailed = (err) ->
authSection.style.display = ''
authButton.addEventListener 'click', ->
authSection.style.display = 'none'
teamsnap.startBrowserAuth(redirect, scopes)
.then(teamsnap.loadCollections)
.then(whenAuthed, whenAuthFailed)
teamsnap.init clientId
if teamsnap.hasSession()
authSection.style.display = 'none'
try
collections = JSON.parse sessionStorage.getItem 'collections'
teamsnap.auth()
teamsnap.loadCollections(collections).then(whenAuthed, whenAuthFailed)
| 168159 | chai.should()
window.expect = chai.expect
authSection = document.getElementById('auth')
authButton = document.getElementById('auth-button')
apiInput = document.getElementById('api-url')
authInput = document.getElementById('auth-url')
clientIdInput = document.getElementById('client-id')
clientId = '<KEY>'
redirect = 'http://localhost:8000/'
scopes = [
'read'
'write'
]
if (url = localStorage.getItem 'teamsnap.apiUrl')
apiInput.value = url if url
if (url = localStorage.getItem 'teamsnap.authUrl')
authInput.value = url if url
id = localStorage.getItem 'teamsnap.clientId'
clientId = id or clientId
clientIdInput.value = clientId
teamsnap.apiUrl = apiInput.value
teamsnap.authUrl = authInput.value
teamsnap.clientId = clientIdInput.value
apiInput.addEventListener 'change', ->
teamsnap.apiUrl = apiInput.value
localStorage.setItem 'teamsnap.apiUrl', apiInput.value
authInput.addEventListener 'change', ->
teamsnap.authUrl = authInput.value
localStorage.setItem 'teamsnap.authUrl', authInput.value
clientIdInput.addEventListener 'change', ->
clientId = clientIdInput.value
teamsnap.init clientId if clientId
localStorage.setItem 'teamsnap.clientId', clientId
whenAuthed = ->
authSection.parentNode.removeChild authSection
sessionStorage.setItem 'collections', JSON.stringify(teamsnap.collections)
mocha.setup('bdd')
window.require.list().filter((_) -> /^test/.test(_)).forEach(require)
mocha.run()
whenAuthFailed = (err) ->
authSection.style.display = ''
authButton.addEventListener 'click', ->
authSection.style.display = 'none'
teamsnap.startBrowserAuth(redirect, scopes)
.then(teamsnap.loadCollections)
.then(whenAuthed, whenAuthFailed)
teamsnap.init clientId
if teamsnap.hasSession()
authSection.style.display = 'none'
try
collections = JSON.parse sessionStorage.getItem 'collections'
teamsnap.auth()
teamsnap.loadCollections(collections).then(whenAuthed, whenAuthFailed)
| true | chai.should()
window.expect = chai.expect
authSection = document.getElementById('auth')
authButton = document.getElementById('auth-button')
apiInput = document.getElementById('api-url')
authInput = document.getElementById('auth-url')
clientIdInput = document.getElementById('client-id')
clientId = 'PI:KEY:<KEY>END_PI'
redirect = 'http://localhost:8000/'
scopes = [
'read'
'write'
]
if (url = localStorage.getItem 'teamsnap.apiUrl')
apiInput.value = url if url
if (url = localStorage.getItem 'teamsnap.authUrl')
authInput.value = url if url
id = localStorage.getItem 'teamsnap.clientId'
clientId = id or clientId
clientIdInput.value = clientId
teamsnap.apiUrl = apiInput.value
teamsnap.authUrl = authInput.value
teamsnap.clientId = clientIdInput.value
apiInput.addEventListener 'change', ->
teamsnap.apiUrl = apiInput.value
localStorage.setItem 'teamsnap.apiUrl', apiInput.value
authInput.addEventListener 'change', ->
teamsnap.authUrl = authInput.value
localStorage.setItem 'teamsnap.authUrl', authInput.value
clientIdInput.addEventListener 'change', ->
clientId = clientIdInput.value
teamsnap.init clientId if clientId
localStorage.setItem 'teamsnap.clientId', clientId
whenAuthed = ->
authSection.parentNode.removeChild authSection
sessionStorage.setItem 'collections', JSON.stringify(teamsnap.collections)
mocha.setup('bdd')
window.require.list().filter((_) -> /^test/.test(_)).forEach(require)
mocha.run()
whenAuthFailed = (err) ->
authSection.style.display = ''
authButton.addEventListener 'click', ->
authSection.style.display = 'none'
teamsnap.startBrowserAuth(redirect, scopes)
.then(teamsnap.loadCollections)
.then(whenAuthed, whenAuthFailed)
teamsnap.init clientId
if teamsnap.hasSession()
authSection.style.display = 'none'
try
collections = JSON.parse sessionStorage.getItem 'collections'
teamsnap.auth()
teamsnap.loadCollections(collections).then(whenAuthed, whenAuthFailed)
|
[
{
"context": "utConfigs: [\n input 'user.email', 'youremail@somewhere.com', 'email input required'\n input 'user.passwor",
"end": 485,
"score": 0.9999207854270935,
"start": 462,
"tag": "EMAIL",
"value": "youremail@somewhere.com"
},
{
"context": "ut required'\n i... | src/views/screens/payment.coffee | verus-io/crowdstart-checkout | 14 | crowdcontrol = require 'crowdcontrol'
Events = crowdcontrol.Events
Screen = require './screen'
analytics = require '../../utils/analytics'
input = require '../../utils/input'
require 'card/src/coffee/card'
require('style-inject') require 'card/src/scss/card'
class Payment extends Screen
tag: 'payment'
html: require '../../../templates/screens/payment.jade'
title: 'Payment Info'
card: null
inputConfigs: [
input 'user.email', 'youremail@somewhere.com', 'email input required'
input 'user.password', 'Password', 'password'
input 'user.name', 'Full Name', 'input name required'
input 'payment.account.number', 'XXXX XXXX XXXX XXXX', 'cardnumber requiredstripe'
input 'payment.account.expiry', 'MM / YY', 'input requiredstripe expiration'
input 'payment.account.cvc', 'CVC', 'input requiredstripe cvc'
]
events:
"#{ Events.Screen.Payment.ChooseStripe }": ()->
@setSelected 'stripe'
"#{ Events.Screen.Payment.ChoosePaypal }": ()->
@setSelected 'paypal'
hasProcessors: ()->
return @hasPaypal() && @hasStripe()
hasPaypal: ()->
return @model.config.processors.paypal
hasStripe: ()->
return @model.config.processors.stripe
setSelected: (selected)->
@model.order.type = selected
@model.payment.account._type = selected
@fullyValidated = false
riot.update()
show: ()->
analytics.track 'Viewed Checkout Step',
step: 1
_submit: ()->
super()
analytics.track 'Completed Checkout Step',
step: 1
js: ()->
super
@model.payment.account._type = @model.order.type
@on 'updated', ()=>
if !@card?
$card = $(@root).find('.crowdstart-card')
if $card[0]?
@card = new window.Card
form: 'form#payment'
container: '.crowdstart-card'
width: 180
Payment.register()
module.exports = Payment
| 194744 | crowdcontrol = require 'crowdcontrol'
Events = crowdcontrol.Events
Screen = require './screen'
analytics = require '../../utils/analytics'
input = require '../../utils/input'
require 'card/src/coffee/card'
require('style-inject') require 'card/src/scss/card'
class Payment extends Screen
tag: 'payment'
html: require '../../../templates/screens/payment.jade'
title: 'Payment Info'
card: null
inputConfigs: [
input 'user.email', '<EMAIL>', 'email input required'
input 'user.password', '<PASSWORD>', '<PASSWORD>'
input 'user.name', '<NAME>', 'input name required'
input 'payment.account.number', 'XXXX XXXX XXXX XXXX', 'cardnumber requiredstripe'
input 'payment.account.expiry', 'MM / YY', 'input requiredstripe expiration'
input 'payment.account.cvc', 'CVC', 'input requiredstripe cvc'
]
events:
"#{ Events.Screen.Payment.ChooseStripe }": ()->
@setSelected 'stripe'
"#{ Events.Screen.Payment.ChoosePaypal }": ()->
@setSelected 'paypal'
hasProcessors: ()->
return @hasPaypal() && @hasStripe()
hasPaypal: ()->
return @model.config.processors.paypal
hasStripe: ()->
return @model.config.processors.stripe
setSelected: (selected)->
@model.order.type = selected
@model.payment.account._type = selected
@fullyValidated = false
riot.update()
show: ()->
analytics.track 'Viewed Checkout Step',
step: 1
_submit: ()->
super()
analytics.track 'Completed Checkout Step',
step: 1
js: ()->
super
@model.payment.account._type = @model.order.type
@on 'updated', ()=>
if !@card?
$card = $(@root).find('.crowdstart-card')
if $card[0]?
@card = new window.Card
form: 'form#payment'
container: '.crowdstart-card'
width: 180
Payment.register()
module.exports = Payment
| true | crowdcontrol = require 'crowdcontrol'
Events = crowdcontrol.Events
Screen = require './screen'
analytics = require '../../utils/analytics'
input = require '../../utils/input'
require 'card/src/coffee/card'
require('style-inject') require 'card/src/scss/card'
class Payment extends Screen
tag: 'payment'
html: require '../../../templates/screens/payment.jade'
title: 'Payment Info'
card: null
inputConfigs: [
input 'user.email', 'PI:EMAIL:<EMAIL>END_PI', 'email input required'
input 'user.password', 'PI:PASSWORD:<PASSWORD>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI'
input 'user.name', 'PI:NAME:<NAME>END_PI', 'input name required'
input 'payment.account.number', 'XXXX XXXX XXXX XXXX', 'cardnumber requiredstripe'
input 'payment.account.expiry', 'MM / YY', 'input requiredstripe expiration'
input 'payment.account.cvc', 'CVC', 'input requiredstripe cvc'
]
events:
"#{ Events.Screen.Payment.ChooseStripe }": ()->
@setSelected 'stripe'
"#{ Events.Screen.Payment.ChoosePaypal }": ()->
@setSelected 'paypal'
hasProcessors: ()->
return @hasPaypal() && @hasStripe()
hasPaypal: ()->
return @model.config.processors.paypal
hasStripe: ()->
return @model.config.processors.stripe
setSelected: (selected)->
@model.order.type = selected
@model.payment.account._type = selected
@fullyValidated = false
riot.update()
show: ()->
analytics.track 'Viewed Checkout Step',
step: 1
_submit: ()->
super()
analytics.track 'Completed Checkout Step',
step: 1
js: ()->
super
@model.payment.account._type = @model.order.type
@on 'updated', ()=>
if !@card?
$card = $(@root).find('.crowdstart-card')
if $card[0]?
@card = new window.Card
form: 'form#payment'
container: '.crowdstart-card'
width: 180
Payment.register()
module.exports = Payment
|
[
{
"context": "t '/admin/login'\n .send 'alias=fool&password=1234567' \n .expect 303 \n",
"end": 657,
"score": 0.9992937445640564,
"start": 650,
"tag": "PASSWORD",
"value": "1234567"
}
] | coffees/test-with-supertest.coffee | android1and1/tickets | 0 | request = require 'supertest'
assert = require 'assert'
agent = undefined
describe 'project unit test::',->
before ->
agent = request 'http://localhost:3003'
it 'should access first page successfully::',->
agent.get '/'
.then (res)->
assert.notEqual -1,(res.text.indexOf 'placeholder')
describe 'check words::',->
it 'should get 5 alpha::',->
agent.get '/create-check-words'
.expect 200
.expect /\"[0-9a-z]{5}\"/ #期待有一个由数字和字母组成的五位字符并包裹在一对双引号里。
describe 'authenticate test::',->
it 'should be redirected if authenticate successful::',->
agent.post '/admin/login'
.send 'alias=fool&password=1234567'
.expect 303
| 70975 | request = require 'supertest'
assert = require 'assert'
agent = undefined
describe 'project unit test::',->
before ->
agent = request 'http://localhost:3003'
it 'should access first page successfully::',->
agent.get '/'
.then (res)->
assert.notEqual -1,(res.text.indexOf 'placeholder')
describe 'check words::',->
it 'should get 5 alpha::',->
agent.get '/create-check-words'
.expect 200
.expect /\"[0-9a-z]{5}\"/ #期待有一个由数字和字母组成的五位字符并包裹在一对双引号里。
describe 'authenticate test::',->
it 'should be redirected if authenticate successful::',->
agent.post '/admin/login'
.send 'alias=fool&password=<PASSWORD>'
.expect 303
| true | request = require 'supertest'
assert = require 'assert'
agent = undefined
describe 'project unit test::',->
before ->
agent = request 'http://localhost:3003'
it 'should access first page successfully::',->
agent.get '/'
.then (res)->
assert.notEqual -1,(res.text.indexOf 'placeholder')
describe 'check words::',->
it 'should get 5 alpha::',->
agent.get '/create-check-words'
.expect 200
.expect /\"[0-9a-z]{5}\"/ #期待有一个由数字和字母组成的五位字符并包裹在一对双引号里。
describe 'authenticate test::',->
it 'should be redirected if authenticate successful::',->
agent.post '/admin/login'
.send 'alias=fool&password=PI:PASSWORD:<PASSWORD>END_PI'
.expect 303
|
[
{
"context": " options =\n uri: 'https://api.github.com/repos/atom/atom/releases'\n method: 'POST'\n headers: de",
"end": 5592,
"score": 0.6281500458717346,
"start": 5588,
"tag": "USERNAME",
"value": "atom"
},
{
"context": "\n accessKeyId: s3Key\n secretAccessKey: ... | build/tasks/publish-build-task.coffee | chfritz/atom | 7 | child_process = require 'child_process'
path = require 'path'
_ = require 'underscore-plus'
async = require 'async'
fs = require 'fs-plus'
GitHub = require 'github-releases'
request = require 'request'
AWS = require 'aws-sdk'
grunt = null
token = process.env.ATOM_ACCESS_TOKEN
defaultHeaders =
Authorization: "token #{token}"
'User-Agent': 'Atom'
module.exports = (gruntObject) ->
grunt = gruntObject
{cp} = require('./task-helpers')(grunt)
grunt.registerTask 'publish-build', 'Publish the built app', ->
tasks = []
tasks.push('build-docs', 'prepare-docs') if process.platform is 'darwin'
tasks.push('upload-assets')
grunt.task.run(tasks)
grunt.registerTask 'prepare-docs', 'Move api.json to atom-api.json', ->
docsOutputDir = grunt.config.get('docsOutputDir')
buildDir = grunt.config.get('atom.buildDir')
cp path.join(docsOutputDir, 'api.json'), path.join(buildDir, 'atom-api.json')
grunt.registerTask 'upload-assets', 'Upload the assets to a GitHub release', ->
channel = grunt.config.get('atom.channel')
switch channel
when 'stable'
isPrerelease = false
when 'beta'
isPrerelease = true
else
return
doneCallback = @async()
startTime = Date.now()
done = (args...) ->
elapsedTime = Math.round((Date.now() - startTime) / 100) / 10
grunt.log.ok("Upload time: #{elapsedTime}s")
doneCallback(args...)
unless token
return done(new Error('ATOM_ACCESS_TOKEN environment variable not set'))
buildDir = grunt.config.get('atom.buildDir')
assets = getAssets()
zipAssets buildDir, assets, (error) ->
return done(error) if error?
getAtomDraftRelease isPrerelease, channel, (error, release) ->
return done(error) if error?
assetNames = (asset.assetName for asset in assets)
deleteExistingAssets release, assetNames, (error) ->
return done(error) if error?
uploadAssets(release, buildDir, assets, done)
getAssets = ->
{cp} = require('./task-helpers')(grunt)
{version} = grunt.file.readJSON('package.json')
buildDir = grunt.config.get('atom.buildDir')
appName = grunt.config.get('atom.appName')
appFileName = grunt.config.get('atom.appFileName')
switch process.platform
when 'darwin'
[
{assetName: 'atom-mac.zip', sourcePath: appName}
{assetName: 'atom-mac-symbols.zip', sourcePath: 'Atom.breakpad.syms'}
{assetName: 'atom-api.json', sourcePath: 'atom-api.json'}
]
when 'win32'
assets = [{assetName: 'atom-windows.zip', sourcePath: appName}]
for squirrelAsset in ['AtomSetup.exe', 'RELEASES', "atom-#{version}-full.nupkg", "atom-#{version}-delta.nupkg"]
cp path.join(buildDir, 'installer', squirrelAsset), path.join(buildDir, squirrelAsset)
assets.push({assetName: squirrelAsset, sourcePath: assetName})
assets
when 'linux'
if process.arch is 'ia32'
arch = 'i386'
else
arch = 'amd64'
# Check for a Debian build
sourcePath = "#{buildDir}/#{appFileName}-#{version}-#{arch}.deb"
assetName = "atom-#{arch}.deb"
# Check for a Fedora build
unless fs.isFileSync(sourcePath)
rpmName = fs.readdirSync("#{buildDir}/rpm")[0]
sourcePath = "#{buildDir}/rpm/#{rpmName}"
if process.arch is 'ia32'
arch = 'i386'
else
arch = 'x86_64'
assetName = "atom.#{arch}.rpm"
cp sourcePath, path.join(buildDir, assetName)
[
{assetName, sourcePath}
]
logError = (message, error, details) ->
grunt.log.error(message)
grunt.log.error(error.message ? error) if error?
grunt.log.error(require('util').inspect(details)) if details
zipAssets = (buildDir, assets, callback) ->
zip = (directory, sourcePath, assetName, callback) ->
if process.platform is 'win32'
zipCommand = "C:/psmodules/7z.exe a -r #{assetName} \"#{sourcePath}\""
else
zipCommand = "zip -r --symlinks '#{assetName}' '#{sourcePath}'"
options = {cwd: directory, maxBuffer: Infinity}
child_process.exec zipCommand, options, (error, stdout, stderr) ->
logError("Zipping #{sourcePath} failed", error, stderr) if error?
callback(error)
tasks = []
for {assetName, sourcePath} in assets when path.extname(assetName) is '.zip'
fs.removeSync(path.join(buildDir, assetName))
tasks.push(zip.bind(this, buildDir, sourcePath, assetName))
async.parallel(tasks, callback)
getAtomDraftRelease = (isPrerelease, branchName, callback) ->
atomRepo = new GitHub({repo: 'atom/atom', token})
atomRepo.getReleases {prerelease: isPrerelease}, (error, releases=[]) ->
if error?
logError('Fetching atom/atom releases failed', error, releases)
callback(error)
else
[firstDraft] = releases.filter ({draft}) -> draft
if firstDraft?
options =
uri: firstDraft.assets_url
method: 'GET'
headers: defaultHeaders
json: true
request options, (error, response, assets=[]) ->
if error? or response.statusCode isnt 200
logError('Fetching draft release assets failed', error, assets)
callback(error ? new Error(response.statusCode))
else
firstDraft.assets = assets
callback(null, firstDraft)
else
createAtomDraftRelease(isPrerelease, branchName, callback)
createAtomDraftRelease = (isPrerelease, branchName, callback) ->
{version} = require('../../package.json')
options =
uri: 'https://api.github.com/repos/atom/atom/releases'
method: 'POST'
headers: defaultHeaders
json:
tag_name: "v#{version}"
prerelease: isPrerelease
target_commitish: branchName
name: version
draft: true
body: """
### Notable Changes
* Something new
"""
request options, (error, response, body='') ->
if error? or response.statusCode isnt 201
logError("Creating atom/atom draft release failed", error, body)
callback(error ? new Error(response.statusCode))
else
callback(null, body)
deleteRelease = (release) ->
options =
uri: release.url
method: 'DELETE'
headers: defaultHeaders
json: true
request options, (error, response, body='') ->
if error? or response.statusCode isnt 204
logError('Deleting release failed', error, body)
deleteExistingAssets = (release, assetNames, callback) ->
[callback, assetNames] = [assetNames, callback] if not callback?
deleteAsset = (url, callback) ->
options =
uri: url
method: 'DELETE'
headers: defaultHeaders
request options, (error, response, body='') ->
if error? or response.statusCode isnt 204
logError('Deleting existing release asset failed', error, body)
callback(error ? new Error(response.statusCode))
else
callback()
tasks = []
for asset in release.assets when not assetNames? or asset.name in assetNames
tasks.push(deleteAsset.bind(this, asset.url))
async.parallel(tasks, callback)
uploadAssets = (release, buildDir, assets, callback) ->
uploadToReleases = (release, assetName, assetPath, callback) ->
options =
uri: release.upload_url.replace(/\{.*$/, "?name=#{assetName}")
method: 'POST'
headers: _.extend({
'Content-Type': 'application/zip'
'Content-Length': fs.getSizeSync(assetPath)
}, defaultHeaders)
assetRequest = request options, (error, response, body='') ->
if error? or response.statusCode >= 400
logError("Upload release asset #{assetName} to Releases failed", error, body)
callback(error ? new Error(response.statusCode))
else
callback(null, release)
fs.createReadStream(assetPath).pipe(assetRequest)
uploadToS3 = (release, assetName, assetPath, callback) ->
s3Key = process.env.BUILD_ATOM_RELEASES_S3_KEY
s3Secret = process.env.BUILD_ATOM_RELEASES_S3_SECRET
s3Bucket = process.env.BUILD_ATOM_RELEASES_S3_BUCKET
unless s3Key and s3Secret and s3Bucket
callback(new Error('BUILD_ATOM_RELEASES_S3_KEY, BUILD_ATOM_RELEASES_S3_SECRET, and BUILD_ATOM_RELEASES_S3_BUCKET environment variables must be set.'))
return
s3Info =
accessKeyId: s3Key
secretAccessKey: s3Secret
s3 = new AWS.S3 s3Info
key = "releases/#{release.tag_name}/#{assetName}"
uploadParams =
Bucket: s3Bucket
ACL: 'public-read'
Key: key
Body: fs.createReadStream(assetPath)
s3.upload uploadParams, (error, data) ->
if error?
logError("Upload release asset #{assetName} to S3 failed", error)
callback(error)
else
callback(null, release)
tasks = []
for {assetName} in assets
assetPath = path.join(buildDir, assetName)
tasks.push(uploadToReleases.bind(this, release, assetName, assetPath))
tasks.push(uploadToS3.bind(this, release, assetName, assetPath))
async.parallel(tasks, callback)
| 31913 | child_process = require 'child_process'
path = require 'path'
_ = require 'underscore-plus'
async = require 'async'
fs = require 'fs-plus'
GitHub = require 'github-releases'
request = require 'request'
AWS = require 'aws-sdk'
grunt = null
token = process.env.ATOM_ACCESS_TOKEN
defaultHeaders =
Authorization: "token #{token}"
'User-Agent': 'Atom'
module.exports = (gruntObject) ->
grunt = gruntObject
{cp} = require('./task-helpers')(grunt)
grunt.registerTask 'publish-build', 'Publish the built app', ->
tasks = []
tasks.push('build-docs', 'prepare-docs') if process.platform is 'darwin'
tasks.push('upload-assets')
grunt.task.run(tasks)
grunt.registerTask 'prepare-docs', 'Move api.json to atom-api.json', ->
docsOutputDir = grunt.config.get('docsOutputDir')
buildDir = grunt.config.get('atom.buildDir')
cp path.join(docsOutputDir, 'api.json'), path.join(buildDir, 'atom-api.json')
grunt.registerTask 'upload-assets', 'Upload the assets to a GitHub release', ->
channel = grunt.config.get('atom.channel')
switch channel
when 'stable'
isPrerelease = false
when 'beta'
isPrerelease = true
else
return
doneCallback = @async()
startTime = Date.now()
done = (args...) ->
elapsedTime = Math.round((Date.now() - startTime) / 100) / 10
grunt.log.ok("Upload time: #{elapsedTime}s")
doneCallback(args...)
unless token
return done(new Error('ATOM_ACCESS_TOKEN environment variable not set'))
buildDir = grunt.config.get('atom.buildDir')
assets = getAssets()
zipAssets buildDir, assets, (error) ->
return done(error) if error?
getAtomDraftRelease isPrerelease, channel, (error, release) ->
return done(error) if error?
assetNames = (asset.assetName for asset in assets)
deleteExistingAssets release, assetNames, (error) ->
return done(error) if error?
uploadAssets(release, buildDir, assets, done)
getAssets = ->
{cp} = require('./task-helpers')(grunt)
{version} = grunt.file.readJSON('package.json')
buildDir = grunt.config.get('atom.buildDir')
appName = grunt.config.get('atom.appName')
appFileName = grunt.config.get('atom.appFileName')
switch process.platform
when 'darwin'
[
{assetName: 'atom-mac.zip', sourcePath: appName}
{assetName: 'atom-mac-symbols.zip', sourcePath: 'Atom.breakpad.syms'}
{assetName: 'atom-api.json', sourcePath: 'atom-api.json'}
]
when 'win32'
assets = [{assetName: 'atom-windows.zip', sourcePath: appName}]
for squirrelAsset in ['AtomSetup.exe', 'RELEASES', "atom-#{version}-full.nupkg", "atom-#{version}-delta.nupkg"]
cp path.join(buildDir, 'installer', squirrelAsset), path.join(buildDir, squirrelAsset)
assets.push({assetName: squirrelAsset, sourcePath: assetName})
assets
when 'linux'
if process.arch is 'ia32'
arch = 'i386'
else
arch = 'amd64'
# Check for a Debian build
sourcePath = "#{buildDir}/#{appFileName}-#{version}-#{arch}.deb"
assetName = "atom-#{arch}.deb"
# Check for a Fedora build
unless fs.isFileSync(sourcePath)
rpmName = fs.readdirSync("#{buildDir}/rpm")[0]
sourcePath = "#{buildDir}/rpm/#{rpmName}"
if process.arch is 'ia32'
arch = 'i386'
else
arch = 'x86_64'
assetName = "atom.#{arch}.rpm"
cp sourcePath, path.join(buildDir, assetName)
[
{assetName, sourcePath}
]
logError = (message, error, details) ->
grunt.log.error(message)
grunt.log.error(error.message ? error) if error?
grunt.log.error(require('util').inspect(details)) if details
zipAssets = (buildDir, assets, callback) ->
zip = (directory, sourcePath, assetName, callback) ->
if process.platform is 'win32'
zipCommand = "C:/psmodules/7z.exe a -r #{assetName} \"#{sourcePath}\""
else
zipCommand = "zip -r --symlinks '#{assetName}' '#{sourcePath}'"
options = {cwd: directory, maxBuffer: Infinity}
child_process.exec zipCommand, options, (error, stdout, stderr) ->
logError("Zipping #{sourcePath} failed", error, stderr) if error?
callback(error)
tasks = []
for {assetName, sourcePath} in assets when path.extname(assetName) is '.zip'
fs.removeSync(path.join(buildDir, assetName))
tasks.push(zip.bind(this, buildDir, sourcePath, assetName))
async.parallel(tasks, callback)
getAtomDraftRelease = (isPrerelease, branchName, callback) ->
atomRepo = new GitHub({repo: 'atom/atom', token})
atomRepo.getReleases {prerelease: isPrerelease}, (error, releases=[]) ->
if error?
logError('Fetching atom/atom releases failed', error, releases)
callback(error)
else
[firstDraft] = releases.filter ({draft}) -> draft
if firstDraft?
options =
uri: firstDraft.assets_url
method: 'GET'
headers: defaultHeaders
json: true
request options, (error, response, assets=[]) ->
if error? or response.statusCode isnt 200
logError('Fetching draft release assets failed', error, assets)
callback(error ? new Error(response.statusCode))
else
firstDraft.assets = assets
callback(null, firstDraft)
else
createAtomDraftRelease(isPrerelease, branchName, callback)
createAtomDraftRelease = (isPrerelease, branchName, callback) ->
{version} = require('../../package.json')
options =
uri: 'https://api.github.com/repos/atom/atom/releases'
method: 'POST'
headers: defaultHeaders
json:
tag_name: "v#{version}"
prerelease: isPrerelease
target_commitish: branchName
name: version
draft: true
body: """
### Notable Changes
* Something new
"""
request options, (error, response, body='') ->
if error? or response.statusCode isnt 201
logError("Creating atom/atom draft release failed", error, body)
callback(error ? new Error(response.statusCode))
else
callback(null, body)
deleteRelease = (release) ->
options =
uri: release.url
method: 'DELETE'
headers: defaultHeaders
json: true
request options, (error, response, body='') ->
if error? or response.statusCode isnt 204
logError('Deleting release failed', error, body)
deleteExistingAssets = (release, assetNames, callback) ->
[callback, assetNames] = [assetNames, callback] if not callback?
deleteAsset = (url, callback) ->
options =
uri: url
method: 'DELETE'
headers: defaultHeaders
request options, (error, response, body='') ->
if error? or response.statusCode isnt 204
logError('Deleting existing release asset failed', error, body)
callback(error ? new Error(response.statusCode))
else
callback()
tasks = []
for asset in release.assets when not assetNames? or asset.name in assetNames
tasks.push(deleteAsset.bind(this, asset.url))
async.parallel(tasks, callback)
uploadAssets = (release, buildDir, assets, callback) ->
uploadToReleases = (release, assetName, assetPath, callback) ->
options =
uri: release.upload_url.replace(/\{.*$/, "?name=#{assetName}")
method: 'POST'
headers: _.extend({
'Content-Type': 'application/zip'
'Content-Length': fs.getSizeSync(assetPath)
}, defaultHeaders)
assetRequest = request options, (error, response, body='') ->
if error? or response.statusCode >= 400
logError("Upload release asset #{assetName} to Releases failed", error, body)
callback(error ? new Error(response.statusCode))
else
callback(null, release)
fs.createReadStream(assetPath).pipe(assetRequest)
uploadToS3 = (release, assetName, assetPath, callback) ->
s3Key = process.env.BUILD_ATOM_RELEASES_S3_KEY
s3Secret = process.env.BUILD_ATOM_RELEASES_S3_SECRET
s3Bucket = process.env.BUILD_ATOM_RELEASES_S3_BUCKET
unless s3Key and s3Secret and s3Bucket
callback(new Error('BUILD_ATOM_RELEASES_S3_KEY, BUILD_ATOM_RELEASES_S3_SECRET, and BUILD_ATOM_RELEASES_S3_BUCKET environment variables must be set.'))
return
s3Info =
accessKeyId: s3Key
secretAccessKey: s<KEY>
s3 = new AWS.S3 s3Info
key = "releases/<KEY>release.tag_name}/<KEY>assetName<KEY>}"
uploadParams =
Bucket: s3Bucket
ACL: 'public-read'
Key: key
Body: fs.createReadStream(assetPath)
s3.upload uploadParams, (error, data) ->
if error?
logError("Upload release asset #{assetName} to S3 failed", error)
callback(error)
else
callback(null, release)
tasks = []
for {assetName} in assets
assetPath = path.join(buildDir, assetName)
tasks.push(uploadToReleases.bind(this, release, assetName, assetPath))
tasks.push(uploadToS3.bind(this, release, assetName, assetPath))
async.parallel(tasks, callback)
| true | child_process = require 'child_process'
path = require 'path'
_ = require 'underscore-plus'
async = require 'async'
fs = require 'fs-plus'
GitHub = require 'github-releases'
request = require 'request'
AWS = require 'aws-sdk'
grunt = null
token = process.env.ATOM_ACCESS_TOKEN
defaultHeaders =
Authorization: "token #{token}"
'User-Agent': 'Atom'
module.exports = (gruntObject) ->
grunt = gruntObject
{cp} = require('./task-helpers')(grunt)
grunt.registerTask 'publish-build', 'Publish the built app', ->
tasks = []
tasks.push('build-docs', 'prepare-docs') if process.platform is 'darwin'
tasks.push('upload-assets')
grunt.task.run(tasks)
grunt.registerTask 'prepare-docs', 'Move api.json to atom-api.json', ->
docsOutputDir = grunt.config.get('docsOutputDir')
buildDir = grunt.config.get('atom.buildDir')
cp path.join(docsOutputDir, 'api.json'), path.join(buildDir, 'atom-api.json')
grunt.registerTask 'upload-assets', 'Upload the assets to a GitHub release', ->
channel = grunt.config.get('atom.channel')
switch channel
when 'stable'
isPrerelease = false
when 'beta'
isPrerelease = true
else
return
doneCallback = @async()
startTime = Date.now()
done = (args...) ->
elapsedTime = Math.round((Date.now() - startTime) / 100) / 10
grunt.log.ok("Upload time: #{elapsedTime}s")
doneCallback(args...)
unless token
return done(new Error('ATOM_ACCESS_TOKEN environment variable not set'))
buildDir = grunt.config.get('atom.buildDir')
assets = getAssets()
zipAssets buildDir, assets, (error) ->
return done(error) if error?
getAtomDraftRelease isPrerelease, channel, (error, release) ->
return done(error) if error?
assetNames = (asset.assetName for asset in assets)
deleteExistingAssets release, assetNames, (error) ->
return done(error) if error?
uploadAssets(release, buildDir, assets, done)
getAssets = ->
{cp} = require('./task-helpers')(grunt)
{version} = grunt.file.readJSON('package.json')
buildDir = grunt.config.get('atom.buildDir')
appName = grunt.config.get('atom.appName')
appFileName = grunt.config.get('atom.appFileName')
switch process.platform
when 'darwin'
[
{assetName: 'atom-mac.zip', sourcePath: appName}
{assetName: 'atom-mac-symbols.zip', sourcePath: 'Atom.breakpad.syms'}
{assetName: 'atom-api.json', sourcePath: 'atom-api.json'}
]
when 'win32'
assets = [{assetName: 'atom-windows.zip', sourcePath: appName}]
for squirrelAsset in ['AtomSetup.exe', 'RELEASES', "atom-#{version}-full.nupkg", "atom-#{version}-delta.nupkg"]
cp path.join(buildDir, 'installer', squirrelAsset), path.join(buildDir, squirrelAsset)
assets.push({assetName: squirrelAsset, sourcePath: assetName})
assets
when 'linux'
if process.arch is 'ia32'
arch = 'i386'
else
arch = 'amd64'
# Check for a Debian build
sourcePath = "#{buildDir}/#{appFileName}-#{version}-#{arch}.deb"
assetName = "atom-#{arch}.deb"
# Check for a Fedora build
unless fs.isFileSync(sourcePath)
rpmName = fs.readdirSync("#{buildDir}/rpm")[0]
sourcePath = "#{buildDir}/rpm/#{rpmName}"
if process.arch is 'ia32'
arch = 'i386'
else
arch = 'x86_64'
assetName = "atom.#{arch}.rpm"
cp sourcePath, path.join(buildDir, assetName)
[
{assetName, sourcePath}
]
logError = (message, error, details) ->
grunt.log.error(message)
grunt.log.error(error.message ? error) if error?
grunt.log.error(require('util').inspect(details)) if details
zipAssets = (buildDir, assets, callback) ->
zip = (directory, sourcePath, assetName, callback) ->
if process.platform is 'win32'
zipCommand = "C:/psmodules/7z.exe a -r #{assetName} \"#{sourcePath}\""
else
zipCommand = "zip -r --symlinks '#{assetName}' '#{sourcePath}'"
options = {cwd: directory, maxBuffer: Infinity}
child_process.exec zipCommand, options, (error, stdout, stderr) ->
logError("Zipping #{sourcePath} failed", error, stderr) if error?
callback(error)
tasks = []
for {assetName, sourcePath} in assets when path.extname(assetName) is '.zip'
fs.removeSync(path.join(buildDir, assetName))
tasks.push(zip.bind(this, buildDir, sourcePath, assetName))
async.parallel(tasks, callback)
getAtomDraftRelease = (isPrerelease, branchName, callback) ->
atomRepo = new GitHub({repo: 'atom/atom', token})
atomRepo.getReleases {prerelease: isPrerelease}, (error, releases=[]) ->
if error?
logError('Fetching atom/atom releases failed', error, releases)
callback(error)
else
[firstDraft] = releases.filter ({draft}) -> draft
if firstDraft?
options =
uri: firstDraft.assets_url
method: 'GET'
headers: defaultHeaders
json: true
request options, (error, response, assets=[]) ->
if error? or response.statusCode isnt 200
logError('Fetching draft release assets failed', error, assets)
callback(error ? new Error(response.statusCode))
else
firstDraft.assets = assets
callback(null, firstDraft)
else
createAtomDraftRelease(isPrerelease, branchName, callback)
createAtomDraftRelease = (isPrerelease, branchName, callback) ->
{version} = require('../../package.json')
options =
uri: 'https://api.github.com/repos/atom/atom/releases'
method: 'POST'
headers: defaultHeaders
json:
tag_name: "v#{version}"
prerelease: isPrerelease
target_commitish: branchName
name: version
draft: true
body: """
### Notable Changes
* Something new
"""
request options, (error, response, body='') ->
if error? or response.statusCode isnt 201
logError("Creating atom/atom draft release failed", error, body)
callback(error ? new Error(response.statusCode))
else
callback(null, body)
deleteRelease = (release) ->
options =
uri: release.url
method: 'DELETE'
headers: defaultHeaders
json: true
request options, (error, response, body='') ->
if error? or response.statusCode isnt 204
logError('Deleting release failed', error, body)
deleteExistingAssets = (release, assetNames, callback) ->
[callback, assetNames] = [assetNames, callback] if not callback?
deleteAsset = (url, callback) ->
options =
uri: url
method: 'DELETE'
headers: defaultHeaders
request options, (error, response, body='') ->
if error? or response.statusCode isnt 204
logError('Deleting existing release asset failed', error, body)
callback(error ? new Error(response.statusCode))
else
callback()
tasks = []
for asset in release.assets when not assetNames? or asset.name in assetNames
tasks.push(deleteAsset.bind(this, asset.url))
async.parallel(tasks, callback)
uploadAssets = (release, buildDir, assets, callback) ->
uploadToReleases = (release, assetName, assetPath, callback) ->
options =
uri: release.upload_url.replace(/\{.*$/, "?name=#{assetName}")
method: 'POST'
headers: _.extend({
'Content-Type': 'application/zip'
'Content-Length': fs.getSizeSync(assetPath)
}, defaultHeaders)
assetRequest = request options, (error, response, body='') ->
if error? or response.statusCode >= 400
logError("Upload release asset #{assetName} to Releases failed", error, body)
callback(error ? new Error(response.statusCode))
else
callback(null, release)
fs.createReadStream(assetPath).pipe(assetRequest)
uploadToS3 = (release, assetName, assetPath, callback) ->
s3Key = process.env.BUILD_ATOM_RELEASES_S3_KEY
s3Secret = process.env.BUILD_ATOM_RELEASES_S3_SECRET
s3Bucket = process.env.BUILD_ATOM_RELEASES_S3_BUCKET
unless s3Key and s3Secret and s3Bucket
callback(new Error('BUILD_ATOM_RELEASES_S3_KEY, BUILD_ATOM_RELEASES_S3_SECRET, and BUILD_ATOM_RELEASES_S3_BUCKET environment variables must be set.'))
return
s3Info =
accessKeyId: s3Key
secretAccessKey: sPI:KEY:<KEY>END_PI
s3 = new AWS.S3 s3Info
key = "releases/PI:KEY:<KEY>END_PIrelease.tag_name}/PI:KEY:<KEY>END_PIassetNamePI:KEY:<KEY>END_PI}"
uploadParams =
Bucket: s3Bucket
ACL: 'public-read'
Key: key
Body: fs.createReadStream(assetPath)
s3.upload uploadParams, (error, data) ->
if error?
logError("Upload release asset #{assetName} to S3 failed", error)
callback(error)
else
callback(null, release)
tasks = []
for {assetName} in assets
assetPath = path.join(buildDir, assetName)
tasks.push(uploadToReleases.bind(this, release, assetName, assetPath))
tasks.push(uploadToS3.bind(this, release, assetName, assetPath))
async.parallel(tasks, callback)
|
[
{
"context": ".Log.create(@Cypress, @cy)\n\n obj = {name: \"foo\", ctx: @cy, fn: (->), args: [1,2,3], type: \"paren",
"end": 15878,
"score": 0.545401394367218,
"start": 15875,
"tag": "NAME",
"value": "foo"
}
] | packages/driver/test/unit_old/cypress/log_spec.coffee | Everworks/cypress | 3 | { $, _, Promise } = window.testUtils
describe "$Cypress.Log API", ->
describe "instances", ->
beforeEach ->
@Cypress = $Cypress.create()
@Cypress.setConfig({})
@log = new $Cypress.Log @Cypress
it "sets state to pending by default", ->
expect(@log.attributes).to.deep.eq {
id: @log.get("id")
state: "pending"
}
it "#get", ->
@log.set "bar", "baz"
expect(@log.get("bar")).to.eq "baz"
it "#pick", ->
@log.set "one", "one"
@log.set "two", "two"
expect(@log.pick("one", "two")).to.deep.eq {
one: "one"
two: "two"
}
it "#snapshot", ->
createSnapshot = @sandbox.stub(@Cypress, "createSnapshot").returns({})
div = $("<div />")
@log.set "$el", div
@log.snapshot()
expect(createSnapshot).to.be.calledWith div
it "#error", ->
err = new Error
@log.error(err)
expect(@log.get("state")).to.eq "failed"
expect(@log.get("error")).to.eq err
it "#error sets ended true and cannot be set back to passed", ->
err = new Error
@log.error(err)
expect(@log.get("ended")).to.be.true
@log.end()
expect(@log.get("state")).to.eq "failed"
expect(@log.get("error")).to.eq err
it "#error triggers log:state:changed", (done) ->
@Cypress.on "log:state:changed", (attrs) ->
expect(attrs.state).to.eq "failed"
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.error({})
it "#end", ->
@log.end()
expect(@log.get("state")).to.eq "passed"
it "#end triggers log:state:changed", (done) ->
@Cypress.on "log:state:changed", (attrs) ->
expect(attrs.state).to.eq "passed"
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.end()
it "does not emit log:state:changed until after first log event", ->
logged = 0
changed = 0
@log.set("foo", "bar")
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
Promise.delay(30)
.then =>
expect(logged).to.eq(0)
expect(changed).to.eq(0)
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set("bar", "baz")
@log.set("baz", "quux")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
it "only emits log:state:changed when attrs have actually changed", ->
logged = 0
changed = 0
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
@log.set("foo", "bar")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
@log.get("foo", "bar")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
describe "#toJSON", ->
it "serializes to object literal", ->
@log.set({
foo: "bar"
consoleProps: ->
{
a: "b"
}
renderProps: ->
{
c: "d"
}
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { Command: undefined, a: "b" }
renderProps: { c: "d" }
})
it "sets defaults for consoleProps + renderProps", ->
@log.set({
foo: "bar"
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { }
renderProps: { }
})
it "wraps onConsole for legacy purposes", ->
@log.set({
foo: "bar"
onConsole: ->
{
a: "b"
}
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { Command: undefined, a: "b" }
renderProps: { }
})
it "serializes error", ->
err = new Error("foo bar baz")
@log.error(err)
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
state: "failed"
ended: true
err: {
message: err.message
name: err.name
stack: err.stack
}
consoleProps: { }
renderProps: { }
ended: true
})
it "defaults consoleProps with error stack", ->
err = new Error("foo bar baz")
@log.set({
consoleProps: ->
{foo: "bar"}
})
@log.error(err)
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
state: "failed"
ended: true
err: {
message: err.message
name: err.name
stack: err.stack
}
consoleProps: {
Command: undefined
Error: err.stack
foo: "bar"
}
renderProps: { }
ended: true
})
it "sets $el", ->
div = $("<div />")
@log.set("$el", div)
toJSON = @log.toJSON()
expect(toJSON.$el).to.eq(div)
describe "#toSerializedJSON", ->
it "serializes simple properties over the wire", ->
div = $("<div />")
@log.set({
foo: "foo"
bar: true
$el: div
arr: [1,2,3]
snapshots: []
consoleProps: ->
{foo: "bar"}
})
expect(@log.get("snapshots")).to.be.an("array")
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
$el: "<div>"
arr: [1,2,3]
bar: true
consoleProps: {
Command: undefined
foo: "bar"
}
err: null
foo: "foo"
highlightAttr: "data-cypress-el"
id: @log.get("id")
numElements: 1
renderProps: {}
snapshots: null
state: "pending"
visible: false
})
it "serializes window", ->
@log.set({
consoleProps: ->
Yielded: window
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: "<window>"
}
err: null
id: @log.get("id")
renderProps: {}
state: "pending"
})
it "serializes document", ->
@log.set({
consoleProps: ->
Yielded: document
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: "<document>"
}
err: null
id: @log.get("id")
renderProps: {}
state: "pending"
})
it "serializes an array of elements", ->
img1 = $("<img />")
img2 = $("<img />")
imgs = img1.add(img2)
@log.set({
$el: imgs
consoleProps: ->
Yielded: [img1, img2]
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: ["<img>", "<img>"]
}
$el: "[ <img>, 1 more... ]"
err: null
highlightAttr: "data-cypress-el"
id: @log.get("id")
numElements: 2
renderProps: {}
state: "pending"
visible: false
})
describe "#set", ->
it "string", ->
@log.set "foo", "bar"
expect(@log.attributes.foo).to.eq "bar"
it "object", ->
@log.set {foo: "bar", baz: "quux"}
expect(@log.attributes).to.deep.eq {
id: @log.get("id")
foo: "bar"
baz: "quux"
state: "pending"
}
it "triggers log:state:changed with attribues", (done) ->
@Cypress.on "log:state:changed", (attrs, log) =>
expect(attrs.foo).to.eq "bar"
expect(attrs.baz).to.eq "quux"
expect(log).to.eq(@log)
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set({foo: "bar", baz: "quux"})
it "debounces log:state:changed and only fires once", ->
count = 0
@Cypress.on "log:state:changed", (attrs, log) =>
count += 1
expect(attrs.foo).to.eq "quux"
expect(attrs.a).to.eq "b"
expect(attrs.c).to.eq "d"
expect(attrs.e).to.eq "f"
expect(log).to.eq(@log)
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set({foo: "bar", a: "b"})
@log.set({foo: "baz", c: "d"})
@log.set {foo: "quux", e: "f"}
Promise.delay(100)
.then ->
expect(count).to.eq(1)
describe "#setElAttrs", ->
beforeEach ->
@$el = $("<div />").appendTo($("body"))
afterEach ->
@$el.remove()
it "is called if $el is passed during construction", ->
setElAttrs = @sandbox.stub $Cypress.Log.prototype, "setElAttrs"
new $Cypress.Log @Cypress, $el: {}
expect(setElAttrs).to.be.called
it "is called if $el is passed during #set", ->
setElAttrs = @sandbox.stub $Cypress.Log.prototype, "setElAttrs"
log = new $Cypress.Log @Cypress
log.set $el: {}
expect(setElAttrs).to.be.called
it "sets $el", ->
log = new $Cypress.Log @Cypress, $el: @$el
expect(log.get("$el")).to.eq @$el
it "sets highlightAttr", ->
@log.set($el: @$el)
expect(@log.get("highlightAttr")).to.be.ok
expect(@log.get("highlightAttr")).to.eq @Cypress.highlightAttr
it "sets numElements", ->
@log.set($el: @$el)
expect(@log.get("numElements")).to.eq @$el.length
it "sets visible to true", ->
@$el.css({height: 100, width: 100})
@log.set($el: @$el)
expect(@log.get("visible")).to.be.true
it "sets visible to false", ->
@$el.hide()
@log.set($el: @$el)
expect(@log.get("visible")).to.be.false
it "sets visible to false if any $el is not visible", ->
$btn1 = $("<button>one</button>").appendTo($("body"))
$btn2 = $("<button>two</button>").appendTo($("body")).hide()
$el = $btn1.add($btn2)
expect($el.length).to.eq 2
@log.set($el: $el)
expect(@log.get("visible")).to.be.false
$el.remove()
it "converts raw dom elements to jquery instances", ->
el = $("<button>one</button").get(0)
@log.set($el: el)
expect(@log.get("$el")).to.be.an.instanceof($)
expect(@log.get("$el").get(0)).to.eq(el)
describe "#constructor", ->
it "snapshots if snapshot attr is true", ->
createSnapshot = @sandbox.stub(@Cypress, "createSnapshot").returns({})
new $Cypress.Log @Cypress, snapshot: true
expect(createSnapshot).to.be.called
it "ends if end attr is true", ->
end = @sandbox.stub $Cypress.Log.prototype, "end"
new $Cypress.Log @Cypress, end: true
expect(end).to.be.called
it "errors if error attr is defined", ->
error = @sandbox.stub $Cypress.Log.prototype, "error"
err = new Error
new $Cypress.Log(@Cypress, {error: err})
expect(error).to.be.calledWith err
describe "#wrapConsoleProps", ->
it "automatically adds Command with name", ->
@log.set("name", "foo")
@log.set("snapshots", [{name: null, body: {}}])
@log.set("consoleProps", -> {bar: "baz"})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "foo"
bar: "baz"
}
it "automatically adds Event with name", ->
@log.set({name: "foo", event: true, snapshot: {}})
@log.set("consoleProps", -> {bar: "baz"})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps()).to.deep.eq {
Event: "foo"
bar: "baz"
}
it "adds a note when snapshot is missing", ->
@log.set("name", "foo")
@log.set("instrument", "command")
@log.set("consoleProps", -> {})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps().Snapshot).to.eq "The snapshot is missing. Displaying current state of the DOM."
describe "#publicInterface", ->
beforeEach ->
@interface = @log.publicInterface()
it "#get", ->
@log.set "foo", "bar"
expect(@interface.get("foo")).to.eq "bar"
it "#pick", ->
@log.set "bar", "baz"
expect(@interface.pick("bar")).to.deep.eq {bar: "baz"}
it "#on", (done) ->
@log.on "foo", done
@log.trigger "foo"
it "#off", ->
@log.on "foo", ->
expect(@log._events).not.to.be.empty
@interface.off "foo"
expect(@log._events).to.be.empty
describe "#snapshot", ->
beforeEach ->
@sandbox.stub(@Cypress, "createSnapshot").returns({
body: "body"
htmlAttrs: {
class: "foo"
}
headStyles: ["body { background: red }"]
bodyStyles: ["body { margin: 10px }"]
})
it "can set multiple snapshots", ->
@log.snapshot()
@log.snapshot()
expect(@log.get("snapshots").length).to.eq(2)
it "can name the snapshot", ->
@log.snapshot("logging in")
expect(@log.get("snapshots").length).to.eq(1)
expect(@log.get("snapshots")[0].name).to.eq("logging in")
it "can set multiple named snapshots", ->
@log.snapshot("one")
@log.snapshot("two")
snapshots = @log.get("snapshots")
expect(snapshots[0].name).to.eq("one")
expect(snapshots[1].name).to.eq("two")
it "can insert snapshot at specific position", ->
@log.snapshot("one")
@log.snapshot("two")
@log.snapshot("three")
@log.snapshot("replacement", {at: 1})
snapshots = @log.get("snapshots")
expect(snapshots.length).to.eq(3)
expect(snapshots[0].name).to.eq("one")
expect(snapshots[1].name).to.eq("replacement")
expect(snapshots[2].name).to.eq("three")
it "can automatically set the name of the next snapshot", ->
@log.snapshot("before", {next: "after"})
@log.snapshot("asdfasdf") ## should ignore this name
@log.snapshot("third")
snapshots = @log.get("snapshots")
expect(snapshots.length).to.eq(3)
expect(snapshots[0].name).to.eq("before")
expect(snapshots[1].name).to.eq("after")
expect(snapshots[2].name).to.eq("third")
it "includes html attributes", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].htmlAttrs).to.eql({
class: "foo"
})
it "includes head styles", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].headStyles).to.eql(["body { background: red }"])
it "includes body", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].body).to.equal("body")
it "includes body styles", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].bodyStyles).to.eql(["body { margin: 10px }"])
describe "class methods", ->
enterCommandTestingMode()
context ".create", ->
beforeEach ->
@Cypress.Log.create(@Cypress, @cy)
obj = {name: "foo", ctx: @cy, fn: (->), args: [1,2,3], type: "parent"}
@cy.state("current", $Cypress.Command.create(obj))
describe "#command", ->
it "displays a deprecation warning", ->
warn = @sandbox.spy console, "warn"
@Cypress.command({})
expect(warn).to.be.calledWith "Cypress Warning: Cypress.command() is deprecated. Please update and use: Cypress.Log.command()"
describe "#log", ->
it "only emits log:state:changed if attrs have actually changed", (done) ->
logged = 0
changed = 0
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
log = @Cypress.Log.log("command", {})
_.delay ->
expect(logged).to.eq(1)
expect(changed).to.eq(0)
done()
, 30
context "$Log.log", ->
it "displays 0 argument", (done) ->
@Cypress.on "log", (obj) ->
if obj.name is "eq"
expect(obj.message).to.eq "0"
done()
@cy.get("div").eq(0)
it "sets type to 'parent' dual commands when first command", (done) ->
@allowErrors()
@Cypress.on "log", (obj) ->
if obj.name is "then"
expect(obj.type).to.eq "parent"
done()
@cy.then ->
throw new Error("then failure")
it "sets type to 'child' dual commands when first command", (done) ->
@allowErrors()
@Cypress.on "log", (obj) ->
if obj.name is "then"
expect(obj.type).to.eq "child"
done()
@cy.noop({}).then ->
throw new Error("then failure")
describe "defaults", ->
it "sets name to current.name", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.name).to.eq "foo"
done()
@Cypress.Log.command({})
it "sets type to current.type", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.type).to.eq "parent"
done()
@Cypress.Log.command({})
it "sets message to stringified args", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.message).to.deep.eq "1, 2, 3"
done()
@Cypress.Log.command({})
it "omits ctx from current.ctx", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.ctx).not.to.exist
done()
@Cypress.Log.command({})
it "omits fn from current.fn", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.fn).not.to.exist
done()
@Cypress.Log.command({})
it "sets hookName to prop hookName", (done) ->
@cy.state("hookName", "beforeEach")
@Cypress.on "log", (obj) ->
expect(obj.hookName).to.eq "beforeEach"
@state("hookName", null)
done()
@Cypress.Log.command({})
it "sets viewportWidth to private viewportWidth", (done) ->
@Cypress.config("viewportWidth", 999)
@Cypress.on "log", (obj) ->
expect(obj.viewportWidth).to.eq 999
done()
@Cypress.Log.command({})
it "sets viewportHeight to private viewportHeight", (done) ->
@Cypress.config("viewportHeight", 888)
@Cypress.on "log", (obj) ->
expect(obj.viewportHeight).to.eq 888
done()
@Cypress.Log.command({})
it "sets url to private url", (done) ->
@cy.state("url", "www.github.com")
@Cypress.on "log", (obj) ->
expect(obj.url).to.eq "www.github.com"
done()
@Cypress.Log.command({})
it "sets testId to runnable.id", (done) ->
@cy.state("runnable", {id: 123})
@Cypress.on "log", (obj) ->
expect(obj.testId).to.eq 123
@state("runnable", null)
done()
@Cypress.Log.command({})
it "sets numElements if $el", (done) ->
$el = @cy.$$("body")
@Cypress.on "log", (obj) ->
expect(obj.numElements).to.eq 1
done()
@Cypress.Log.command($el: $el)
it "sets highlightAttr if $el", (done) ->
$el = @cy.$$("body")
@Cypress.on "log", (obj) ->
expect(obj.highlightAttr).not.to.be.undefined
expect(obj.highlightAttr).to.eq @Cypress.highlightAttr
done()
@Cypress.Log.command($el: $el)
describe "errors", ->
beforeEach ->
@allowErrors()
@cy.on "command:start", ->
cy.timeout(100)
## prevent accidentally adding a .then to @cy
return null
it "preserves errors", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.get("name")).to.eq "get"
expect(@log.get("message")).to.eq "foo"
expect(@log.get("error")).to.eq err
done()
@cy.get("foo")
it "#consoleProps for parent commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "get"
Selector: "foo"
Elements: 0
Yielded: undefined
Error: err.toString()
}
done()
@cy.get("foo")
it "#consoleProps for dual commands as a parent", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "wait"
Error: err.toString()
}
done()
@cy.wait ->
expect(true).to.be.false
it "#consoleProps for dual commands as a child", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "wait"
btns = getFirstSubjectByName.call(@, "get")
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "wait"
"Applied To": $Cypress.utils.getDomElements(btns)
Error: err.toString()
}
done()
@cy.get("button").wait ->
expect(true).to.be.false
it "#consoleProps for children commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "contains"
btns = getFirstSubjectByName.call(@, "get")
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "contains"
Content: "asdfasdfasdfasdf"
Elements: 0
Yielded: undefined
"Applied To": $Cypress.utils.getDomElements(btns)
Error: err.toString()
}
done()
@cy.get("button").contains("asdfasdfasdfasdf")
## FIXME: timed out once on full run
it "#consoleProps for nested children commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "contains"
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "contains"
Content: "asdfasdfasdfasdf"
Elements: 0
Yielded: undefined
"Applied To": getFirstSubjectByName.call(@, "eq").get(0)
Error: err.toString()
}
done()
@cy.get("button").eq(0).contains("asdfasdfasdfasdf")
| 36442 | { $, _, Promise } = window.testUtils
describe "$Cypress.Log API", ->
describe "instances", ->
beforeEach ->
@Cypress = $Cypress.create()
@Cypress.setConfig({})
@log = new $Cypress.Log @Cypress
it "sets state to pending by default", ->
expect(@log.attributes).to.deep.eq {
id: @log.get("id")
state: "pending"
}
it "#get", ->
@log.set "bar", "baz"
expect(@log.get("bar")).to.eq "baz"
it "#pick", ->
@log.set "one", "one"
@log.set "two", "two"
expect(@log.pick("one", "two")).to.deep.eq {
one: "one"
two: "two"
}
it "#snapshot", ->
createSnapshot = @sandbox.stub(@Cypress, "createSnapshot").returns({})
div = $("<div />")
@log.set "$el", div
@log.snapshot()
expect(createSnapshot).to.be.calledWith div
it "#error", ->
err = new Error
@log.error(err)
expect(@log.get("state")).to.eq "failed"
expect(@log.get("error")).to.eq err
it "#error sets ended true and cannot be set back to passed", ->
err = new Error
@log.error(err)
expect(@log.get("ended")).to.be.true
@log.end()
expect(@log.get("state")).to.eq "failed"
expect(@log.get("error")).to.eq err
it "#error triggers log:state:changed", (done) ->
@Cypress.on "log:state:changed", (attrs) ->
expect(attrs.state).to.eq "failed"
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.error({})
it "#end", ->
@log.end()
expect(@log.get("state")).to.eq "passed"
it "#end triggers log:state:changed", (done) ->
@Cypress.on "log:state:changed", (attrs) ->
expect(attrs.state).to.eq "passed"
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.end()
it "does not emit log:state:changed until after first log event", ->
logged = 0
changed = 0
@log.set("foo", "bar")
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
Promise.delay(30)
.then =>
expect(logged).to.eq(0)
expect(changed).to.eq(0)
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set("bar", "baz")
@log.set("baz", "quux")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
it "only emits log:state:changed when attrs have actually changed", ->
logged = 0
changed = 0
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
@log.set("foo", "bar")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
@log.get("foo", "bar")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
describe "#toJSON", ->
it "serializes to object literal", ->
@log.set({
foo: "bar"
consoleProps: ->
{
a: "b"
}
renderProps: ->
{
c: "d"
}
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { Command: undefined, a: "b" }
renderProps: { c: "d" }
})
it "sets defaults for consoleProps + renderProps", ->
@log.set({
foo: "bar"
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { }
renderProps: { }
})
it "wraps onConsole for legacy purposes", ->
@log.set({
foo: "bar"
onConsole: ->
{
a: "b"
}
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { Command: undefined, a: "b" }
renderProps: { }
})
it "serializes error", ->
err = new Error("foo bar baz")
@log.error(err)
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
state: "failed"
ended: true
err: {
message: err.message
name: err.name
stack: err.stack
}
consoleProps: { }
renderProps: { }
ended: true
})
it "defaults consoleProps with error stack", ->
err = new Error("foo bar baz")
@log.set({
consoleProps: ->
{foo: "bar"}
})
@log.error(err)
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
state: "failed"
ended: true
err: {
message: err.message
name: err.name
stack: err.stack
}
consoleProps: {
Command: undefined
Error: err.stack
foo: "bar"
}
renderProps: { }
ended: true
})
it "sets $el", ->
div = $("<div />")
@log.set("$el", div)
toJSON = @log.toJSON()
expect(toJSON.$el).to.eq(div)
describe "#toSerializedJSON", ->
it "serializes simple properties over the wire", ->
div = $("<div />")
@log.set({
foo: "foo"
bar: true
$el: div
arr: [1,2,3]
snapshots: []
consoleProps: ->
{foo: "bar"}
})
expect(@log.get("snapshots")).to.be.an("array")
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
$el: "<div>"
arr: [1,2,3]
bar: true
consoleProps: {
Command: undefined
foo: "bar"
}
err: null
foo: "foo"
highlightAttr: "data-cypress-el"
id: @log.get("id")
numElements: 1
renderProps: {}
snapshots: null
state: "pending"
visible: false
})
it "serializes window", ->
@log.set({
consoleProps: ->
Yielded: window
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: "<window>"
}
err: null
id: @log.get("id")
renderProps: {}
state: "pending"
})
it "serializes document", ->
@log.set({
consoleProps: ->
Yielded: document
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: "<document>"
}
err: null
id: @log.get("id")
renderProps: {}
state: "pending"
})
it "serializes an array of elements", ->
img1 = $("<img />")
img2 = $("<img />")
imgs = img1.add(img2)
@log.set({
$el: imgs
consoleProps: ->
Yielded: [img1, img2]
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: ["<img>", "<img>"]
}
$el: "[ <img>, 1 more... ]"
err: null
highlightAttr: "data-cypress-el"
id: @log.get("id")
numElements: 2
renderProps: {}
state: "pending"
visible: false
})
describe "#set", ->
it "string", ->
@log.set "foo", "bar"
expect(@log.attributes.foo).to.eq "bar"
it "object", ->
@log.set {foo: "bar", baz: "quux"}
expect(@log.attributes).to.deep.eq {
id: @log.get("id")
foo: "bar"
baz: "quux"
state: "pending"
}
it "triggers log:state:changed with attribues", (done) ->
@Cypress.on "log:state:changed", (attrs, log) =>
expect(attrs.foo).to.eq "bar"
expect(attrs.baz).to.eq "quux"
expect(log).to.eq(@log)
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set({foo: "bar", baz: "quux"})
it "debounces log:state:changed and only fires once", ->
count = 0
@Cypress.on "log:state:changed", (attrs, log) =>
count += 1
expect(attrs.foo).to.eq "quux"
expect(attrs.a).to.eq "b"
expect(attrs.c).to.eq "d"
expect(attrs.e).to.eq "f"
expect(log).to.eq(@log)
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set({foo: "bar", a: "b"})
@log.set({foo: "baz", c: "d"})
@log.set {foo: "quux", e: "f"}
Promise.delay(100)
.then ->
expect(count).to.eq(1)
describe "#setElAttrs", ->
beforeEach ->
@$el = $("<div />").appendTo($("body"))
afterEach ->
@$el.remove()
it "is called if $el is passed during construction", ->
setElAttrs = @sandbox.stub $Cypress.Log.prototype, "setElAttrs"
new $Cypress.Log @Cypress, $el: {}
expect(setElAttrs).to.be.called
it "is called if $el is passed during #set", ->
setElAttrs = @sandbox.stub $Cypress.Log.prototype, "setElAttrs"
log = new $Cypress.Log @Cypress
log.set $el: {}
expect(setElAttrs).to.be.called
it "sets $el", ->
log = new $Cypress.Log @Cypress, $el: @$el
expect(log.get("$el")).to.eq @$el
it "sets highlightAttr", ->
@log.set($el: @$el)
expect(@log.get("highlightAttr")).to.be.ok
expect(@log.get("highlightAttr")).to.eq @Cypress.highlightAttr
it "sets numElements", ->
@log.set($el: @$el)
expect(@log.get("numElements")).to.eq @$el.length
it "sets visible to true", ->
@$el.css({height: 100, width: 100})
@log.set($el: @$el)
expect(@log.get("visible")).to.be.true
it "sets visible to false", ->
@$el.hide()
@log.set($el: @$el)
expect(@log.get("visible")).to.be.false
it "sets visible to false if any $el is not visible", ->
$btn1 = $("<button>one</button>").appendTo($("body"))
$btn2 = $("<button>two</button>").appendTo($("body")).hide()
$el = $btn1.add($btn2)
expect($el.length).to.eq 2
@log.set($el: $el)
expect(@log.get("visible")).to.be.false
$el.remove()
it "converts raw dom elements to jquery instances", ->
el = $("<button>one</button").get(0)
@log.set($el: el)
expect(@log.get("$el")).to.be.an.instanceof($)
expect(@log.get("$el").get(0)).to.eq(el)
describe "#constructor", ->
it "snapshots if snapshot attr is true", ->
createSnapshot = @sandbox.stub(@Cypress, "createSnapshot").returns({})
new $Cypress.Log @Cypress, snapshot: true
expect(createSnapshot).to.be.called
it "ends if end attr is true", ->
end = @sandbox.stub $Cypress.Log.prototype, "end"
new $Cypress.Log @Cypress, end: true
expect(end).to.be.called
it "errors if error attr is defined", ->
error = @sandbox.stub $Cypress.Log.prototype, "error"
err = new Error
new $Cypress.Log(@Cypress, {error: err})
expect(error).to.be.calledWith err
describe "#wrapConsoleProps", ->
it "automatically adds Command with name", ->
@log.set("name", "foo")
@log.set("snapshots", [{name: null, body: {}}])
@log.set("consoleProps", -> {bar: "baz"})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "foo"
bar: "baz"
}
it "automatically adds Event with name", ->
@log.set({name: "foo", event: true, snapshot: {}})
@log.set("consoleProps", -> {bar: "baz"})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps()).to.deep.eq {
Event: "foo"
bar: "baz"
}
it "adds a note when snapshot is missing", ->
@log.set("name", "foo")
@log.set("instrument", "command")
@log.set("consoleProps", -> {})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps().Snapshot).to.eq "The snapshot is missing. Displaying current state of the DOM."
describe "#publicInterface", ->
beforeEach ->
@interface = @log.publicInterface()
it "#get", ->
@log.set "foo", "bar"
expect(@interface.get("foo")).to.eq "bar"
it "#pick", ->
@log.set "bar", "baz"
expect(@interface.pick("bar")).to.deep.eq {bar: "baz"}
it "#on", (done) ->
@log.on "foo", done
@log.trigger "foo"
it "#off", ->
@log.on "foo", ->
expect(@log._events).not.to.be.empty
@interface.off "foo"
expect(@log._events).to.be.empty
describe "#snapshot", ->
beforeEach ->
@sandbox.stub(@Cypress, "createSnapshot").returns({
body: "body"
htmlAttrs: {
class: "foo"
}
headStyles: ["body { background: red }"]
bodyStyles: ["body { margin: 10px }"]
})
it "can set multiple snapshots", ->
@log.snapshot()
@log.snapshot()
expect(@log.get("snapshots").length).to.eq(2)
it "can name the snapshot", ->
@log.snapshot("logging in")
expect(@log.get("snapshots").length).to.eq(1)
expect(@log.get("snapshots")[0].name).to.eq("logging in")
it "can set multiple named snapshots", ->
@log.snapshot("one")
@log.snapshot("two")
snapshots = @log.get("snapshots")
expect(snapshots[0].name).to.eq("one")
expect(snapshots[1].name).to.eq("two")
it "can insert snapshot at specific position", ->
@log.snapshot("one")
@log.snapshot("two")
@log.snapshot("three")
@log.snapshot("replacement", {at: 1})
snapshots = @log.get("snapshots")
expect(snapshots.length).to.eq(3)
expect(snapshots[0].name).to.eq("one")
expect(snapshots[1].name).to.eq("replacement")
expect(snapshots[2].name).to.eq("three")
it "can automatically set the name of the next snapshot", ->
@log.snapshot("before", {next: "after"})
@log.snapshot("asdfasdf") ## should ignore this name
@log.snapshot("third")
snapshots = @log.get("snapshots")
expect(snapshots.length).to.eq(3)
expect(snapshots[0].name).to.eq("before")
expect(snapshots[1].name).to.eq("after")
expect(snapshots[2].name).to.eq("third")
it "includes html attributes", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].htmlAttrs).to.eql({
class: "foo"
})
it "includes head styles", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].headStyles).to.eql(["body { background: red }"])
it "includes body", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].body).to.equal("body")
it "includes body styles", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].bodyStyles).to.eql(["body { margin: 10px }"])
describe "class methods", ->
enterCommandTestingMode()
context ".create", ->
beforeEach ->
@Cypress.Log.create(@Cypress, @cy)
obj = {name: "<NAME>", ctx: @cy, fn: (->), args: [1,2,3], type: "parent"}
@cy.state("current", $Cypress.Command.create(obj))
describe "#command", ->
it "displays a deprecation warning", ->
warn = @sandbox.spy console, "warn"
@Cypress.command({})
expect(warn).to.be.calledWith "Cypress Warning: Cypress.command() is deprecated. Please update and use: Cypress.Log.command()"
describe "#log", ->
it "only emits log:state:changed if attrs have actually changed", (done) ->
logged = 0
changed = 0
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
log = @Cypress.Log.log("command", {})
_.delay ->
expect(logged).to.eq(1)
expect(changed).to.eq(0)
done()
, 30
context "$Log.log", ->
it "displays 0 argument", (done) ->
@Cypress.on "log", (obj) ->
if obj.name is "eq"
expect(obj.message).to.eq "0"
done()
@cy.get("div").eq(0)
it "sets type to 'parent' dual commands when first command", (done) ->
@allowErrors()
@Cypress.on "log", (obj) ->
if obj.name is "then"
expect(obj.type).to.eq "parent"
done()
@cy.then ->
throw new Error("then failure")
it "sets type to 'child' dual commands when first command", (done) ->
@allowErrors()
@Cypress.on "log", (obj) ->
if obj.name is "then"
expect(obj.type).to.eq "child"
done()
@cy.noop({}).then ->
throw new Error("then failure")
describe "defaults", ->
it "sets name to current.name", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.name).to.eq "foo"
done()
@Cypress.Log.command({})
it "sets type to current.type", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.type).to.eq "parent"
done()
@Cypress.Log.command({})
it "sets message to stringified args", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.message).to.deep.eq "1, 2, 3"
done()
@Cypress.Log.command({})
it "omits ctx from current.ctx", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.ctx).not.to.exist
done()
@Cypress.Log.command({})
it "omits fn from current.fn", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.fn).not.to.exist
done()
@Cypress.Log.command({})
it "sets hookName to prop hookName", (done) ->
@cy.state("hookName", "beforeEach")
@Cypress.on "log", (obj) ->
expect(obj.hookName).to.eq "beforeEach"
@state("hookName", null)
done()
@Cypress.Log.command({})
it "sets viewportWidth to private viewportWidth", (done) ->
@Cypress.config("viewportWidth", 999)
@Cypress.on "log", (obj) ->
expect(obj.viewportWidth).to.eq 999
done()
@Cypress.Log.command({})
it "sets viewportHeight to private viewportHeight", (done) ->
@Cypress.config("viewportHeight", 888)
@Cypress.on "log", (obj) ->
expect(obj.viewportHeight).to.eq 888
done()
@Cypress.Log.command({})
it "sets url to private url", (done) ->
@cy.state("url", "www.github.com")
@Cypress.on "log", (obj) ->
expect(obj.url).to.eq "www.github.com"
done()
@Cypress.Log.command({})
it "sets testId to runnable.id", (done) ->
@cy.state("runnable", {id: 123})
@Cypress.on "log", (obj) ->
expect(obj.testId).to.eq 123
@state("runnable", null)
done()
@Cypress.Log.command({})
it "sets numElements if $el", (done) ->
$el = @cy.$$("body")
@Cypress.on "log", (obj) ->
expect(obj.numElements).to.eq 1
done()
@Cypress.Log.command($el: $el)
it "sets highlightAttr if $el", (done) ->
$el = @cy.$$("body")
@Cypress.on "log", (obj) ->
expect(obj.highlightAttr).not.to.be.undefined
expect(obj.highlightAttr).to.eq @Cypress.highlightAttr
done()
@Cypress.Log.command($el: $el)
describe "errors", ->
beforeEach ->
@allowErrors()
@cy.on "command:start", ->
cy.timeout(100)
## prevent accidentally adding a .then to @cy
return null
it "preserves errors", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.get("name")).to.eq "get"
expect(@log.get("message")).to.eq "foo"
expect(@log.get("error")).to.eq err
done()
@cy.get("foo")
it "#consoleProps for parent commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "get"
Selector: "foo"
Elements: 0
Yielded: undefined
Error: err.toString()
}
done()
@cy.get("foo")
it "#consoleProps for dual commands as a parent", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "wait"
Error: err.toString()
}
done()
@cy.wait ->
expect(true).to.be.false
it "#consoleProps for dual commands as a child", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "wait"
btns = getFirstSubjectByName.call(@, "get")
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "wait"
"Applied To": $Cypress.utils.getDomElements(btns)
Error: err.toString()
}
done()
@cy.get("button").wait ->
expect(true).to.be.false
it "#consoleProps for children commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "contains"
btns = getFirstSubjectByName.call(@, "get")
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "contains"
Content: "asdfasdfasdfasdf"
Elements: 0
Yielded: undefined
"Applied To": $Cypress.utils.getDomElements(btns)
Error: err.toString()
}
done()
@cy.get("button").contains("asdfasdfasdfasdf")
## FIXME: timed out once on full run
it "#consoleProps for nested children commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "contains"
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "contains"
Content: "asdfasdfasdfasdf"
Elements: 0
Yielded: undefined
"Applied To": getFirstSubjectByName.call(@, "eq").get(0)
Error: err.toString()
}
done()
@cy.get("button").eq(0).contains("asdfasdfasdfasdf")
| true | { $, _, Promise } = window.testUtils
describe "$Cypress.Log API", ->
describe "instances", ->
beforeEach ->
@Cypress = $Cypress.create()
@Cypress.setConfig({})
@log = new $Cypress.Log @Cypress
it "sets state to pending by default", ->
expect(@log.attributes).to.deep.eq {
id: @log.get("id")
state: "pending"
}
it "#get", ->
@log.set "bar", "baz"
expect(@log.get("bar")).to.eq "baz"
it "#pick", ->
@log.set "one", "one"
@log.set "two", "two"
expect(@log.pick("one", "two")).to.deep.eq {
one: "one"
two: "two"
}
it "#snapshot", ->
createSnapshot = @sandbox.stub(@Cypress, "createSnapshot").returns({})
div = $("<div />")
@log.set "$el", div
@log.snapshot()
expect(createSnapshot).to.be.calledWith div
it "#error", ->
err = new Error
@log.error(err)
expect(@log.get("state")).to.eq "failed"
expect(@log.get("error")).to.eq err
it "#error sets ended true and cannot be set back to passed", ->
err = new Error
@log.error(err)
expect(@log.get("ended")).to.be.true
@log.end()
expect(@log.get("state")).to.eq "failed"
expect(@log.get("error")).to.eq err
it "#error triggers log:state:changed", (done) ->
@Cypress.on "log:state:changed", (attrs) ->
expect(attrs.state).to.eq "failed"
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.error({})
it "#end", ->
@log.end()
expect(@log.get("state")).to.eq "passed"
it "#end triggers log:state:changed", (done) ->
@Cypress.on "log:state:changed", (attrs) ->
expect(attrs.state).to.eq "passed"
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.end()
it "does not emit log:state:changed until after first log event", ->
logged = 0
changed = 0
@log.set("foo", "bar")
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
Promise.delay(30)
.then =>
expect(logged).to.eq(0)
expect(changed).to.eq(0)
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set("bar", "baz")
@log.set("baz", "quux")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
it "only emits log:state:changed when attrs have actually changed", ->
logged = 0
changed = 0
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
@log.set("foo", "bar")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
@log.get("foo", "bar")
Promise.delay(30)
.then =>
expect(changed).to.eq(1)
describe "#toJSON", ->
it "serializes to object literal", ->
@log.set({
foo: "bar"
consoleProps: ->
{
a: "b"
}
renderProps: ->
{
c: "d"
}
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { Command: undefined, a: "b" }
renderProps: { c: "d" }
})
it "sets defaults for consoleProps + renderProps", ->
@log.set({
foo: "bar"
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { }
renderProps: { }
})
it "wraps onConsole for legacy purposes", ->
@log.set({
foo: "bar"
onConsole: ->
{
a: "b"
}
})
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
foo: "bar"
state: "pending"
err: null
consoleProps: { Command: undefined, a: "b" }
renderProps: { }
})
it "serializes error", ->
err = new Error("foo bar baz")
@log.error(err)
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
state: "failed"
ended: true
err: {
message: err.message
name: err.name
stack: err.stack
}
consoleProps: { }
renderProps: { }
ended: true
})
it "defaults consoleProps with error stack", ->
err = new Error("foo bar baz")
@log.set({
consoleProps: ->
{foo: "bar"}
})
@log.error(err)
expect(@log.toJSON()).to.deep.eq({
id: @log.get("id")
state: "failed"
ended: true
err: {
message: err.message
name: err.name
stack: err.stack
}
consoleProps: {
Command: undefined
Error: err.stack
foo: "bar"
}
renderProps: { }
ended: true
})
it "sets $el", ->
div = $("<div />")
@log.set("$el", div)
toJSON = @log.toJSON()
expect(toJSON.$el).to.eq(div)
describe "#toSerializedJSON", ->
it "serializes simple properties over the wire", ->
div = $("<div />")
@log.set({
foo: "foo"
bar: true
$el: div
arr: [1,2,3]
snapshots: []
consoleProps: ->
{foo: "bar"}
})
expect(@log.get("snapshots")).to.be.an("array")
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
$el: "<div>"
arr: [1,2,3]
bar: true
consoleProps: {
Command: undefined
foo: "bar"
}
err: null
foo: "foo"
highlightAttr: "data-cypress-el"
id: @log.get("id")
numElements: 1
renderProps: {}
snapshots: null
state: "pending"
visible: false
})
it "serializes window", ->
@log.set({
consoleProps: ->
Yielded: window
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: "<window>"
}
err: null
id: @log.get("id")
renderProps: {}
state: "pending"
})
it "serializes document", ->
@log.set({
consoleProps: ->
Yielded: document
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: "<document>"
}
err: null
id: @log.get("id")
renderProps: {}
state: "pending"
})
it "serializes an array of elements", ->
img1 = $("<img />")
img2 = $("<img />")
imgs = img1.add(img2)
@log.set({
$el: imgs
consoleProps: ->
Yielded: [img1, img2]
})
expect(@Cypress.Log.toSerializedJSON(@log.toJSON())).to.deep.eq({
consoleProps: {
Command: undefined
Yielded: ["<img>", "<img>"]
}
$el: "[ <img>, 1 more... ]"
err: null
highlightAttr: "data-cypress-el"
id: @log.get("id")
numElements: 2
renderProps: {}
state: "pending"
visible: false
})
describe "#set", ->
it "string", ->
@log.set "foo", "bar"
expect(@log.attributes.foo).to.eq "bar"
it "object", ->
@log.set {foo: "bar", baz: "quux"}
expect(@log.attributes).to.deep.eq {
id: @log.get("id")
foo: "bar"
baz: "quux"
state: "pending"
}
it "triggers log:state:changed with attribues", (done) ->
@Cypress.on "log:state:changed", (attrs, log) =>
expect(attrs.foo).to.eq "bar"
expect(attrs.baz).to.eq "quux"
expect(log).to.eq(@log)
done()
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set({foo: "bar", baz: "quux"})
it "debounces log:state:changed and only fires once", ->
count = 0
@Cypress.on "log:state:changed", (attrs, log) =>
count += 1
expect(attrs.foo).to.eq "quux"
expect(attrs.a).to.eq "b"
expect(attrs.c).to.eq "d"
expect(attrs.e).to.eq "f"
expect(log).to.eq(@log)
$Cypress.Log.addToLogs(@log)
@log._hasInitiallyLogged = true
@log.set({foo: "bar", a: "b"})
@log.set({foo: "baz", c: "d"})
@log.set {foo: "quux", e: "f"}
Promise.delay(100)
.then ->
expect(count).to.eq(1)
describe "#setElAttrs", ->
beforeEach ->
@$el = $("<div />").appendTo($("body"))
afterEach ->
@$el.remove()
it "is called if $el is passed during construction", ->
setElAttrs = @sandbox.stub $Cypress.Log.prototype, "setElAttrs"
new $Cypress.Log @Cypress, $el: {}
expect(setElAttrs).to.be.called
it "is called if $el is passed during #set", ->
setElAttrs = @sandbox.stub $Cypress.Log.prototype, "setElAttrs"
log = new $Cypress.Log @Cypress
log.set $el: {}
expect(setElAttrs).to.be.called
it "sets $el", ->
log = new $Cypress.Log @Cypress, $el: @$el
expect(log.get("$el")).to.eq @$el
it "sets highlightAttr", ->
@log.set($el: @$el)
expect(@log.get("highlightAttr")).to.be.ok
expect(@log.get("highlightAttr")).to.eq @Cypress.highlightAttr
it "sets numElements", ->
@log.set($el: @$el)
expect(@log.get("numElements")).to.eq @$el.length
it "sets visible to true", ->
@$el.css({height: 100, width: 100})
@log.set($el: @$el)
expect(@log.get("visible")).to.be.true
it "sets visible to false", ->
@$el.hide()
@log.set($el: @$el)
expect(@log.get("visible")).to.be.false
it "sets visible to false if any $el is not visible", ->
$btn1 = $("<button>one</button>").appendTo($("body"))
$btn2 = $("<button>two</button>").appendTo($("body")).hide()
$el = $btn1.add($btn2)
expect($el.length).to.eq 2
@log.set($el: $el)
expect(@log.get("visible")).to.be.false
$el.remove()
it "converts raw dom elements to jquery instances", ->
el = $("<button>one</button").get(0)
@log.set($el: el)
expect(@log.get("$el")).to.be.an.instanceof($)
expect(@log.get("$el").get(0)).to.eq(el)
describe "#constructor", ->
it "snapshots if snapshot attr is true", ->
createSnapshot = @sandbox.stub(@Cypress, "createSnapshot").returns({})
new $Cypress.Log @Cypress, snapshot: true
expect(createSnapshot).to.be.called
it "ends if end attr is true", ->
end = @sandbox.stub $Cypress.Log.prototype, "end"
new $Cypress.Log @Cypress, end: true
expect(end).to.be.called
it "errors if error attr is defined", ->
error = @sandbox.stub $Cypress.Log.prototype, "error"
err = new Error
new $Cypress.Log(@Cypress, {error: err})
expect(error).to.be.calledWith err
describe "#wrapConsoleProps", ->
it "automatically adds Command with name", ->
@log.set("name", "foo")
@log.set("snapshots", [{name: null, body: {}}])
@log.set("consoleProps", -> {bar: "baz"})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "foo"
bar: "baz"
}
it "automatically adds Event with name", ->
@log.set({name: "foo", event: true, snapshot: {}})
@log.set("consoleProps", -> {bar: "baz"})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps()).to.deep.eq {
Event: "foo"
bar: "baz"
}
it "adds a note when snapshot is missing", ->
@log.set("name", "foo")
@log.set("instrument", "command")
@log.set("consoleProps", -> {})
@log.wrapConsoleProps()
expect(@log.attributes.consoleProps().Snapshot).to.eq "The snapshot is missing. Displaying current state of the DOM."
describe "#publicInterface", ->
beforeEach ->
@interface = @log.publicInterface()
it "#get", ->
@log.set "foo", "bar"
expect(@interface.get("foo")).to.eq "bar"
it "#pick", ->
@log.set "bar", "baz"
expect(@interface.pick("bar")).to.deep.eq {bar: "baz"}
it "#on", (done) ->
@log.on "foo", done
@log.trigger "foo"
it "#off", ->
@log.on "foo", ->
expect(@log._events).not.to.be.empty
@interface.off "foo"
expect(@log._events).to.be.empty
describe "#snapshot", ->
beforeEach ->
@sandbox.stub(@Cypress, "createSnapshot").returns({
body: "body"
htmlAttrs: {
class: "foo"
}
headStyles: ["body { background: red }"]
bodyStyles: ["body { margin: 10px }"]
})
it "can set multiple snapshots", ->
@log.snapshot()
@log.snapshot()
expect(@log.get("snapshots").length).to.eq(2)
it "can name the snapshot", ->
@log.snapshot("logging in")
expect(@log.get("snapshots").length).to.eq(1)
expect(@log.get("snapshots")[0].name).to.eq("logging in")
it "can set multiple named snapshots", ->
@log.snapshot("one")
@log.snapshot("two")
snapshots = @log.get("snapshots")
expect(snapshots[0].name).to.eq("one")
expect(snapshots[1].name).to.eq("two")
it "can insert snapshot at specific position", ->
@log.snapshot("one")
@log.snapshot("two")
@log.snapshot("three")
@log.snapshot("replacement", {at: 1})
snapshots = @log.get("snapshots")
expect(snapshots.length).to.eq(3)
expect(snapshots[0].name).to.eq("one")
expect(snapshots[1].name).to.eq("replacement")
expect(snapshots[2].name).to.eq("three")
it "can automatically set the name of the next snapshot", ->
@log.snapshot("before", {next: "after"})
@log.snapshot("asdfasdf") ## should ignore this name
@log.snapshot("third")
snapshots = @log.get("snapshots")
expect(snapshots.length).to.eq(3)
expect(snapshots[0].name).to.eq("before")
expect(snapshots[1].name).to.eq("after")
expect(snapshots[2].name).to.eq("third")
it "includes html attributes", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].htmlAttrs).to.eql({
class: "foo"
})
it "includes head styles", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].headStyles).to.eql(["body { background: red }"])
it "includes body", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].body).to.equal("body")
it "includes body styles", ->
@log.snapshot()
snapshots = @log.get("snapshots")
expect(snapshots[0].bodyStyles).to.eql(["body { margin: 10px }"])
describe "class methods", ->
enterCommandTestingMode()
context ".create", ->
beforeEach ->
@Cypress.Log.create(@Cypress, @cy)
obj = {name: "PI:NAME:<NAME>END_PI", ctx: @cy, fn: (->), args: [1,2,3], type: "parent"}
@cy.state("current", $Cypress.Command.create(obj))
describe "#command", ->
it "displays a deprecation warning", ->
warn = @sandbox.spy console, "warn"
@Cypress.command({})
expect(warn).to.be.calledWith "Cypress Warning: Cypress.command() is deprecated. Please update and use: Cypress.Log.command()"
describe "#log", ->
it "only emits log:state:changed if attrs have actually changed", (done) ->
logged = 0
changed = 0
@Cypress.on "log", ->
logged += 1
@Cypress.on "log:state:changed", ->
changed += 1
log = @Cypress.Log.log("command", {})
_.delay ->
expect(logged).to.eq(1)
expect(changed).to.eq(0)
done()
, 30
context "$Log.log", ->
it "displays 0 argument", (done) ->
@Cypress.on "log", (obj) ->
if obj.name is "eq"
expect(obj.message).to.eq "0"
done()
@cy.get("div").eq(0)
it "sets type to 'parent' dual commands when first command", (done) ->
@allowErrors()
@Cypress.on "log", (obj) ->
if obj.name is "then"
expect(obj.type).to.eq "parent"
done()
@cy.then ->
throw new Error("then failure")
it "sets type to 'child' dual commands when first command", (done) ->
@allowErrors()
@Cypress.on "log", (obj) ->
if obj.name is "then"
expect(obj.type).to.eq "child"
done()
@cy.noop({}).then ->
throw new Error("then failure")
describe "defaults", ->
it "sets name to current.name", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.name).to.eq "foo"
done()
@Cypress.Log.command({})
it "sets type to current.type", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.type).to.eq "parent"
done()
@Cypress.Log.command({})
it "sets message to stringified args", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.message).to.deep.eq "1, 2, 3"
done()
@Cypress.Log.command({})
it "omits ctx from current.ctx", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.ctx).not.to.exist
done()
@Cypress.Log.command({})
it "omits fn from current.fn", (done) ->
@Cypress.on "log", (obj) ->
expect(obj.fn).not.to.exist
done()
@Cypress.Log.command({})
it "sets hookName to prop hookName", (done) ->
@cy.state("hookName", "beforeEach")
@Cypress.on "log", (obj) ->
expect(obj.hookName).to.eq "beforeEach"
@state("hookName", null)
done()
@Cypress.Log.command({})
it "sets viewportWidth to private viewportWidth", (done) ->
@Cypress.config("viewportWidth", 999)
@Cypress.on "log", (obj) ->
expect(obj.viewportWidth).to.eq 999
done()
@Cypress.Log.command({})
it "sets viewportHeight to private viewportHeight", (done) ->
@Cypress.config("viewportHeight", 888)
@Cypress.on "log", (obj) ->
expect(obj.viewportHeight).to.eq 888
done()
@Cypress.Log.command({})
it "sets url to private url", (done) ->
@cy.state("url", "www.github.com")
@Cypress.on "log", (obj) ->
expect(obj.url).to.eq "www.github.com"
done()
@Cypress.Log.command({})
it "sets testId to runnable.id", (done) ->
@cy.state("runnable", {id: 123})
@Cypress.on "log", (obj) ->
expect(obj.testId).to.eq 123
@state("runnable", null)
done()
@Cypress.Log.command({})
it "sets numElements if $el", (done) ->
$el = @cy.$$("body")
@Cypress.on "log", (obj) ->
expect(obj.numElements).to.eq 1
done()
@Cypress.Log.command($el: $el)
it "sets highlightAttr if $el", (done) ->
$el = @cy.$$("body")
@Cypress.on "log", (obj) ->
expect(obj.highlightAttr).not.to.be.undefined
expect(obj.highlightAttr).to.eq @Cypress.highlightAttr
done()
@Cypress.Log.command($el: $el)
describe "errors", ->
beforeEach ->
@allowErrors()
@cy.on "command:start", ->
cy.timeout(100)
## prevent accidentally adding a .then to @cy
return null
it "preserves errors", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.get("name")).to.eq "get"
expect(@log.get("message")).to.eq "foo"
expect(@log.get("error")).to.eq err
done()
@cy.get("foo")
it "#consoleProps for parent commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "get"
Selector: "foo"
Elements: 0
Yielded: undefined
Error: err.toString()
}
done()
@cy.get("foo")
it "#consoleProps for dual commands as a parent", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "wait"
Error: err.toString()
}
done()
@cy.wait ->
expect(true).to.be.false
it "#consoleProps for dual commands as a child", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "wait"
btns = getFirstSubjectByName.call(@, "get")
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "wait"
"Applied To": $Cypress.utils.getDomElements(btns)
Error: err.toString()
}
done()
@cy.get("button").wait ->
expect(true).to.be.false
it "#consoleProps for children commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "contains"
btns = getFirstSubjectByName.call(@, "get")
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "contains"
Content: "asdfasdfasdfasdf"
Elements: 0
Yielded: undefined
"Applied To": $Cypress.utils.getDomElements(btns)
Error: err.toString()
}
done()
@cy.get("button").contains("asdfasdfasdfasdf")
## FIXME: timed out once on full run
it "#consoleProps for nested children commands", (done) ->
@Cypress.on "log", (attrs, @log) =>
@cy.on "fail", (err) =>
if @log.get("name") is "contains"
expect(@log.attributes.consoleProps()).to.deep.eq {
Command: "contains"
Content: "asdfasdfasdfasdf"
Elements: 0
Yielded: undefined
"Applied To": getFirstSubjectByName.call(@, "eq").get(0)
Error: err.toString()
}
done()
@cy.get("button").eq(0).contains("asdfasdfasdfasdf")
|
[
{
"context": "s = require '../'\n\nconsole.log utils.isPrivateIp('192.168.1.1') # true\nconsole.log utils.isPrivateIp('172.168.1",
"end": 65,
"score": 0.999643087387085,
"start": 54,
"tag": "IP_ADDRESS",
"value": "192.168.1.1"
},
{
"context": "2.168.1.1') # true\nconsole.log utils.is... | example/ip.coffee | restman/restman-utils | 0 | utils = require '../'
console.log utils.isPrivateIp('192.168.1.1') # true
console.log utils.isPrivateIp('172.168.1.1') # false | 87851 | utils = require '../'
console.log utils.isPrivateIp('192.168.1.1') # true
console.log utils.isPrivateIp('172.16.17.32') # false | true | utils = require '../'
console.log utils.isPrivateIp('192.168.1.1') # true
console.log utils.isPrivateIp('PI:IP_ADDRESS:172.16.17.32END_PI') # false |
[
{
"context": "bark', ->\n beforeEach ->\n @room.user.say 'briancoia', 'bark'\n\n it 'should reply bark(s) to",
"end": 375,
"score": 0.7175812721252441,
"start": 374,
"tag": "USERNAME",
"value": "b"
},
{
"context": "ark', ->\n beforeEach ->\n @room.user.say 'brianco... | tests/scripts/test_bark.coffee | fangamer/ibizan | 0 |
Helper = require('hubot-test-helper')
expect = require('chai').expect
http = require('http')
# helper loads a specific script if it's a file
helper = new Helper('../../src/scripts/bark.coffee')
describe 'bark', ->
beforeEach ->
@room = helper.createRoom()
afterEach ->
@room.destroy()
context 'user says: bark', ->
beforeEach ->
@room.user.say 'briancoia', 'bark'
it 'should reply bark(s) to user', ->
expect(@room.messages[0]).to.eql(['briancoia', 'bark'])
expect(@room.messages[1][1]).to.include('bark')
context 'user says: hubot tell me a story', ->
beforeEach ->
@room.user.say 'briancoia', 'hubot tell me a story'
it 'should tell a story to user', ->
expect(@room.messages[0]).to.eql(['briancoia', 'hubot tell me a story'])
expect(@room.messages[1][1]).to.include('w')
context 'user says: good (dog|boy|pup|puppy|ibizan|ibi)', ->
beforeEach ->
@room.user.say 'briancoia', 'good boy'
it 'should display the ultimate seal of gratitude', ->
expect(@room.messages).to.eql [
['briancoia', 'good boy']
['hubot', ':ok_hand:']
]
context 'user says: hubot fetch', ->
beforeEach ->
@room.user.say 'briancoia', 'hubot fetch'
it 'should get impatient', ->
expect(@room.messages[0]).to.eql(['briancoia', 'hubot fetch'])
expect(@room.messages[1][1]).to.include('impatient')
context 'user says: hubot fetch thing', ->
beforeEach ->
@room.user.say 'briancoia', 'hubot fetch thing'
it 'should fetch thing', ->
expect(@room.messages[0]).to.eql(['briancoia', 'hubot fetch thing'])
expect(@room.messages[1][1]).to.include('runs to fetch')
context 'GET /', ->
beforeEach (done) ->
http.get 'http://localhost:8080/', (@response) => done()
.on 'error', done
it 'responds with status 200', ->
expect(@response.statusCode).to.equal 200
| 506 |
Helper = require('hubot-test-helper')
expect = require('chai').expect
http = require('http')
# helper loads a specific script if it's a file
helper = new Helper('../../src/scripts/bark.coffee')
describe 'bark', ->
beforeEach ->
@room = helper.createRoom()
afterEach ->
@room.destroy()
context 'user says: bark', ->
beforeEach ->
@room.user.say 'b<NAME>', 'bark'
it 'should reply bark(s) to user', ->
expect(@room.messages[0]).to.eql(['briancoia', 'bark'])
expect(@room.messages[1][1]).to.include('bark')
context 'user says: hubot tell me a story', ->
beforeEach ->
@room.user.say '<NAME>', 'hubot tell me a story'
it 'should tell a story to user', ->
expect(@room.messages[0]).to.eql(['bri<NAME>ia', 'hubot tell me a story'])
expect(@room.messages[1][1]).to.include('w')
context 'user says: good (dog|boy|pup|puppy|ibizan|ibi)', ->
beforeEach ->
@room.user.say '<NAME>', 'good boy'
it 'should display the ultimate seal of gratitude', ->
expect(@room.messages).to.eql [
['bri<NAME>', 'good boy']
['hubot', ':ok_hand:']
]
context 'user says: hubot fetch', ->
beforeEach ->
@room.user.say 'b<NAME>anco<NAME>', 'hubot fetch'
it 'should get impatient', ->
expect(@room.messages[0]).to.eql(['b<NAME>', 'hubot fetch'])
expect(@room.messages[1][1]).to.include('impatient')
context 'user says: hubot fetch thing', ->
beforeEach ->
@room.user.say '<NAME>', 'hubot fetch thing'
it 'should fetch thing', ->
expect(@room.messages[0]).to.eql(['briancoia', 'hubot fetch thing'])
expect(@room.messages[1][1]).to.include('runs to fetch')
context 'GET /', ->
beforeEach (done) ->
http.get 'http://localhost:8080/', (@response) => done()
.on 'error', done
it 'responds with status 200', ->
expect(@response.statusCode).to.equal 200
| true |
Helper = require('hubot-test-helper')
expect = require('chai').expect
http = require('http')
# helper loads a specific script if it's a file
helper = new Helper('../../src/scripts/bark.coffee')
describe 'bark', ->
beforeEach ->
@room = helper.createRoom()
afterEach ->
@room.destroy()
context 'user says: bark', ->
beforeEach ->
@room.user.say 'bPI:NAME:<NAME>END_PI', 'bark'
it 'should reply bark(s) to user', ->
expect(@room.messages[0]).to.eql(['briancoia', 'bark'])
expect(@room.messages[1][1]).to.include('bark')
context 'user says: hubot tell me a story', ->
beforeEach ->
@room.user.say 'PI:NAME:<NAME>END_PI', 'hubot tell me a story'
it 'should tell a story to user', ->
expect(@room.messages[0]).to.eql(['briPI:NAME:<NAME>END_PIia', 'hubot tell me a story'])
expect(@room.messages[1][1]).to.include('w')
context 'user says: good (dog|boy|pup|puppy|ibizan|ibi)', ->
beforeEach ->
@room.user.say 'PI:NAME:<NAME>END_PI', 'good boy'
it 'should display the ultimate seal of gratitude', ->
expect(@room.messages).to.eql [
['briPI:NAME:<NAME>END_PI', 'good boy']
['hubot', ':ok_hand:']
]
context 'user says: hubot fetch', ->
beforeEach ->
@room.user.say 'bPI:NAME:<NAME>END_PIancoPI:NAME:<NAME>END_PI', 'hubot fetch'
it 'should get impatient', ->
expect(@room.messages[0]).to.eql(['bPI:NAME:<NAME>END_PI', 'hubot fetch'])
expect(@room.messages[1][1]).to.include('impatient')
context 'user says: hubot fetch thing', ->
beforeEach ->
@room.user.say 'PI:NAME:<NAME>END_PI', 'hubot fetch thing'
it 'should fetch thing', ->
expect(@room.messages[0]).to.eql(['briancoia', 'hubot fetch thing'])
expect(@room.messages[1][1]).to.include('runs to fetch')
context 'GET /', ->
beforeEach (done) ->
http.get 'http://localhost:8080/', (@response) => done()
.on 'error', done
it 'responds with status 200', ->
expect(@response.statusCode).to.equal 200
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.5491939187049866,
"start": 33,
"tag": "NAME",
"value": "Technology"
}
] | community/server/src/main/coffeescript/neo4j/webadmin/modules/databrowser/visualization/NodeStyler.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['neo4j/webadmin/utils/ItemUrlResolver'],
(ItemUrlResolver) ->
class NodeStyler
defaultExploredStyle :
nodeStyle :
fill : "#000000"
alpha : 0.9
labelStyle :
color : "white"
font : "12px Helvetica"
defaultUnexploredStyle :
nodeStyle :
fill : "#000000"
alpha : 0.2
labelStyle :
color : "rgba(255, 255, 255, 0.4)"
font : "12px Helvetica"
defaultGroupStyle :
nodeStyle :
shape : "dot"
fill : "#000000"
alpha : 0.8
labelStyle :
color : "white"
font : "10px Helvetica"
constructor : () ->
@labelProperties = []
@itemUrlUtils = new ItemUrlResolver()
getStyleFor : (visualNode) ->
type = visualNode.data.type
if type is "group"
nodeStyle = @defaultGroupStyle.nodeStyle
labelStyle = @defaultGroupStyle.labelStyle
labelText = visualNode.data.group.nodeCount
else
if visualNode.data.neoNode?
node = visualNode.data.neoNode
id = @itemUrlUtils.extractNodeId(node.getSelf())
labelText = id
propList = []
for prop in @labelProperties
if node.hasProperty(prop)
propList.push node.getProperty(prop)
propertiesText = propList.join ", "
if propertiesText
labelText = labelText + ": " + propertiesText
labelText ?= id
else
labelText = "?"
if type is "explored"
nodeStyle = @defaultExploredStyle.nodeStyle
labelStyle = @defaultExploredStyle.labelStyle
else
nodeStyle = @defaultUnexploredStyle.nodeStyle
labelStyle = @defaultUnexploredStyle.labelStyle
return { nodeStyle:nodeStyle, labelStyle:labelStyle, labelText:labelText }
setLabelProperties : (labelProperties) ->
@labelProperties = labelProperties
)
| 80332 | ###
Copyright (c) 2002-2013 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['neo4j/webadmin/utils/ItemUrlResolver'],
(ItemUrlResolver) ->
class NodeStyler
defaultExploredStyle :
nodeStyle :
fill : "#000000"
alpha : 0.9
labelStyle :
color : "white"
font : "12px Helvetica"
defaultUnexploredStyle :
nodeStyle :
fill : "#000000"
alpha : 0.2
labelStyle :
color : "rgba(255, 255, 255, 0.4)"
font : "12px Helvetica"
defaultGroupStyle :
nodeStyle :
shape : "dot"
fill : "#000000"
alpha : 0.8
labelStyle :
color : "white"
font : "10px Helvetica"
constructor : () ->
@labelProperties = []
@itemUrlUtils = new ItemUrlResolver()
getStyleFor : (visualNode) ->
type = visualNode.data.type
if type is "group"
nodeStyle = @defaultGroupStyle.nodeStyle
labelStyle = @defaultGroupStyle.labelStyle
labelText = visualNode.data.group.nodeCount
else
if visualNode.data.neoNode?
node = visualNode.data.neoNode
id = @itemUrlUtils.extractNodeId(node.getSelf())
labelText = id
propList = []
for prop in @labelProperties
if node.hasProperty(prop)
propList.push node.getProperty(prop)
propertiesText = propList.join ", "
if propertiesText
labelText = labelText + ": " + propertiesText
labelText ?= id
else
labelText = "?"
if type is "explored"
nodeStyle = @defaultExploredStyle.nodeStyle
labelStyle = @defaultExploredStyle.labelStyle
else
nodeStyle = @defaultUnexploredStyle.nodeStyle
labelStyle = @defaultUnexploredStyle.labelStyle
return { nodeStyle:nodeStyle, labelStyle:labelStyle, labelText:labelText }
setLabelProperties : (labelProperties) ->
@labelProperties = labelProperties
)
| true | ###
Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['neo4j/webadmin/utils/ItemUrlResolver'],
(ItemUrlResolver) ->
class NodeStyler
defaultExploredStyle :
nodeStyle :
fill : "#000000"
alpha : 0.9
labelStyle :
color : "white"
font : "12px Helvetica"
defaultUnexploredStyle :
nodeStyle :
fill : "#000000"
alpha : 0.2
labelStyle :
color : "rgba(255, 255, 255, 0.4)"
font : "12px Helvetica"
defaultGroupStyle :
nodeStyle :
shape : "dot"
fill : "#000000"
alpha : 0.8
labelStyle :
color : "white"
font : "10px Helvetica"
constructor : () ->
@labelProperties = []
@itemUrlUtils = new ItemUrlResolver()
getStyleFor : (visualNode) ->
type = visualNode.data.type
if type is "group"
nodeStyle = @defaultGroupStyle.nodeStyle
labelStyle = @defaultGroupStyle.labelStyle
labelText = visualNode.data.group.nodeCount
else
if visualNode.data.neoNode?
node = visualNode.data.neoNode
id = @itemUrlUtils.extractNodeId(node.getSelf())
labelText = id
propList = []
for prop in @labelProperties
if node.hasProperty(prop)
propList.push node.getProperty(prop)
propertiesText = propList.join ", "
if propertiesText
labelText = labelText + ": " + propertiesText
labelText ?= id
else
labelText = "?"
if type is "explored"
nodeStyle = @defaultExploredStyle.nodeStyle
labelStyle = @defaultExploredStyle.labelStyle
else
nodeStyle = @defaultUnexploredStyle.nodeStyle
labelStyle = @defaultUnexploredStyle.labelStyle
return { nodeStyle:nodeStyle, labelStyle:labelStyle, labelText:labelText }
setLabelProperties : (labelProperties) ->
@labelProperties = labelProperties
)
|
[
{
"context": " fritzBoxPro for Übersicht\n# Created April 2020 by Johannes Hubig\n\n# Position of the widget on your screen\npos_top\t",
"end": 140,
"score": 0.9998595714569092,
"start": 126,
"tag": "NAME",
"value": "Johannes Hubig"
}
] | fritzBoxPro.widget/index.coffee | jhubig/uebersicht-widget-fritzBoxPro | 3 | #-----------------------------------------------------------------------#
# fritzBoxPro for Übersicht
# Created April 2020 by Johannes Hubig
# Position of the widget on your screen
pos_top = '120px'
pos_left = '370px'
#-----------------------------------------------------------------------#
command: "fritzBoxPro.widget/fritzBoxShell.sh"
# Update every 60 seconds (don't put higher refresh rate than 20 seconds - There seems to be a limit by the TR064 protocol requests)
refreshFrequency: 30000
style: """
top: #{pos_top}
left: #{pos_left}
font-family: Avenir Next
.container
width: 90%
margin: auto
.mobile-wrapper
background: rgba(255, 255, 255, 0.7)
position: relative
width: 360px
min-height: 100%
margin: auto
padding: 10px 0 20px
border-radius: 10px
box-shadow: 0px 10px 30px -10px #000
overflow: hidden
.header-box
background: linear-gradient(to left, #485fed, rgba(255, 255, 255, .2)), #485fed
color: #FFF
padding: 4px 15px
position: relative
box-shadow: 0px 0px 20px -7px #485fed
.header-subtitle
font-weight: 400
position: relative
font-size: 12px
text-shadow: 0px 0px 5px rgba(#000, 0.5)
.header-title
font-size: 20px
margin: 3px 0 0 0
letter-spacing: 1px
font-weight: 600
text-shadow: 0px 0px 5px rgba(#000, 0.5)
.header-icon
position: absolute
top: 48%
transform: translateY(-50%)
right: 20px
.data-section
margin-top: -8px
.container
h3
color: #333
font-size: 15px
padding-top: 7px
margin-bottom: 8px
margin-left: -8px
position: relative
&::before // for horizontal line at section title
content: ""
display: block
width: 78%
height: 2px
background-color: #999
position: absolute
top: 60%
right: 0
.data-wrapper
margin-bottom: -10px
.data-item
position: relative
margin-bottom: 5px
padding-left: 30px
cursor: pointer
.data__point
margin: 0
color: #333
font-size: 14px
font-weight: 500
letter-spacing: 0.5px
.data__title
position: absolute
top: 0px
right: 0
color: #666
font-size: 11px
font-weight: 600
font-style: italic
.data_point_sublabel
position: relative
top: -1px
left: 5px
color: #666
font-size: 10px
font-weight: 500
font-style: italic
// CSS for ICONS
.icon
width: auto
position: absolute
left: 0px
top: -1px
.icon_pulsing
width: auto
position: absolute
left: 0px
top: -1px
.icon_pulsing:before
position: absolute
top: 3px
left: 3px
width: 14px
height: 14px
border-radius: 50%
content: ''
box-shadow: inset 0 0 0 6px #f00
transition: transform 0.2s, opacity 0.2s
animation: pulsing 2.1s infinite
z-index: -1
@keyframes pulsing
0%
transform: scale(1)
opacity: 1
50%
transform: scale(2)
opacity: 1
100%
transform: scale(1)
opacity: 0
"""
render: -> """
<div class="mobile-wrapper">
<section class="header-box" id="header-box">
<h3 class="header-title">My Fritz!Box</h3>
<span class="header-subtitle" id="model">N/A</span>
<div class="header-icon">
<img style='vertical-align:middle; margin-top: 0px' src='fritzBoxPro.widget/FritzLogo70px.png'/>
</div>
</section>
<!--======= Data section General =======-->
<section class="data-section">
<div class="container">
<h3>
General
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon" id="firmware_div"><img id="firmware_icon" src='fritzBoxPro.widget/icons/accept_database.svg' height="20px;"/></div>
<h4 class="data__point" id='firmwareVersion'>N/A</h4>
<div class="data_point_sublabel" id="firmwareUpdateAvailable" style="display:none">N/A</div>
<span class="data__title">Firmware</span>
</div>
<div class="data-item">
<div class="icon"><img id="provider_icon" src='fritzBoxPro.widget/icons/filing_cabinet.svg' height="20px;"/></div>
<h4 class="data__point" id='providerName'>N/A</h4>
<span class="data__title">Provider</span>
</div>
<div class="data-item">
<div class="icon"><img id="uptime_icon" src='fritzBoxPro.widget/icons/clock.svg' height="20px;"/></div>
<h4 class="data__point" id='uptime'>N/A</h4>
<span class="data__title">Uptime</span>
</div>
<!--
<div class="data-item">
<h4 class="data__point" id='errorLog'>N/A</h4>
<span class="data__title">errorLog</span>
</div>
-->
</div>
</section>
<!--======= Data section Network =======-->
<section class="data-section">
<div class="container">
<h3>
Network
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon"><img id="externalIP" src='fritzBoxPro.widget/icons/link.svg' height="20px;"/></div>
<h4 class="data__point" id='ipAddress'>N/A</h4>
<span class="data__title">Ext. IP Address</span>
</div>
<div class="data-item">
<!--<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="wifi2gswitch" checked>
<label class="onoffswitch-label" for="wifi2gswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>-->
<div class="icon"><img id="wifi2gswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='2g_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="2g_connectedDevices">N/A</div>
<span class="data__title">2.4 Ghz WiFi</span>
</div>
<div class="data-item">
<div class="icon"><img id="wifi5gswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='5g_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="5g_connectedDevices">N/A</div>
<span class="data__title">5 Ghz WiFI</span>
</div>
<div class="data-item">
<div class="icon"><img id="wifiguestswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='guest_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="guest_connectedDevices">N/A</div>
<span class="data__title">Guest WiFI</span>
</div>
</div>
</section>
<!--======= Data section TAM (Answering machine) =======-->
<section class="data-section">
<div class="container">
<h3>
TAM
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon"><img id="tamswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point"><span id='nameTAM'> N/A</span></h4>
<span class="data__title">Name</span>
</div>
<div class="data-item">
<div class="icon" id="voicemail_div"><img id="voicemail" src='fritzBoxPro.widget/icons/voicemail.svg' height="20px;"/></div>
<h4 class="data__point"><span id='nbOfCallsNew'> N/A</span> / <span id='nbOfCallsTotal'> N/A</span></h4>
<span class="data__title">New / Total calls</span>
</div>
</div>
</section>
</div>
"""
update: (output,domEl) ->
values = output.split("\n")
div = $(domEl)
# ----------- For 2.4 Ghz WiFi display ------------
values2G = values[0].split(";")
if (values2G[1] != "")
div.find('#2g_SSID').html(values2G[1])
if (values2G[3] != "")
div.find('#2g_connectedDevices').html(values2G[3] + " devices connected")
if (parseInt(values2G[2]) == 1)
#div.find('#wifi2gswitch').attr("checked", true)
div.find('#wifi2gswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values2G[2]) == 0)
div.find('#wifi2gswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ------------ For 5 Ghz WiFi display -------------
values5G = values[1].split(";")
if (values5G[1] != "")
div.find('#5g_SSID').html(values5G[1])
if (values5G[3] != "")
div.find('#5g_connectedDevices').html(values5G[3] + " devices connected")
if (parseInt(values5G[2]) == 1)
div.find('#wifi5gswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values5G[2]) == 0)
div.find('#wifi5gswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ------------ For Guest WiFi display -------------
valuesGuest = values[2].split(";")
if (valuesGuest[1] != "")
div.find('#guest_SSID').html(valuesGuest[1])
if (valuesGuest[3] != "")
div.find('#guest_connectedDevices').html(valuesGuest[3] + " devices connected")
if (parseInt(valuesGuest[2]) == 1)
div.find('#wifiguestswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(valuesGuest[2]) == 0)
div.find('#wifiguestswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ---------- External IP Address display ----------
if (values[3] != "")
div.find('#ipAddress').html(values[3])
# ------------ Fritz!Box model display ------------
if (values[4] != "")
div.find('#model').html(values[4])
# ---------- Firmware version display ---------q----
if (values[5] != "")
div.find('#firmwareVersion').html("v" + values[5].split(".")[1] + "." + values[5].split(".")[2])
if (parseInt(values[12]) == 1)
div.find('#firmware_icon').attr("src", "fritzBoxPro.widget/icons/data_backup.svg")
div.find('#firmwareUpdateAvailable').html("Firmware update available. Visit http://fritz.box")
div.find('#firmwareUpdateAvailable').attr("style", "display:block")
div.find('#firmware_div').attr("class", "icon_pulsing")
else if (parseInt(values[12]) == 0)
div.find('#firmware_icon').attr("src", "fritzBoxPro.widget/icons/accept_database.svg")
div.find('#firmwareUpdateAvailable').attr("style", "display:none")
div.find('#firmware_div').attr("class", "icon")
# --------------- Uptime display ------------------
if (values[6] != "")
div.find('#uptime').html(values[6].split(":")[0] + " d, " + values[6].split(":")[1] + " h, " + values[6].split(":")[2] + " m")
# ------- Answering machine (TAM) display ---------
if (values[7] != "")
div.find('#nameTAM').html(values[7].split(" ")[1])
if (parseInt(values[8].split(" ")[1]) == 1)
div.find('#tamswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values[8].split(" ")[1]) == 0)
div.find('#tamswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
if (values[9] != "")
div.find('#nbOfCallsNew').html(values[9])
if(parseInt(values[9]) >= 1)
div.find('#voicemail_div').attr("class", "icon_pulsing")
div.find('#nbOfCallsNew').attr("style", "color:red")
else if(parseInt(values[9]) == 0)
div.find('#voicemail_div').attr("class", "icon")
div.find('#nbOfCallsNew').attr("style", "color:#333")
if (values[10] != "")
div.find('#nbOfCallsTotal').html(values[10].split(":")[1])
# --------------- Provider name display ------------------
if (values[11] != "")
div.find('#providerName').html(values[11])
| 75454 | #-----------------------------------------------------------------------#
# fritzBoxPro for Übersicht
# Created April 2020 by <NAME>
# Position of the widget on your screen
pos_top = '120px'
pos_left = '370px'
#-----------------------------------------------------------------------#
command: "fritzBoxPro.widget/fritzBoxShell.sh"
# Update every 60 seconds (don't put higher refresh rate than 20 seconds - There seems to be a limit by the TR064 protocol requests)
refreshFrequency: 30000
style: """
top: #{pos_top}
left: #{pos_left}
font-family: Avenir Next
.container
width: 90%
margin: auto
.mobile-wrapper
background: rgba(255, 255, 255, 0.7)
position: relative
width: 360px
min-height: 100%
margin: auto
padding: 10px 0 20px
border-radius: 10px
box-shadow: 0px 10px 30px -10px #000
overflow: hidden
.header-box
background: linear-gradient(to left, #485fed, rgba(255, 255, 255, .2)), #485fed
color: #FFF
padding: 4px 15px
position: relative
box-shadow: 0px 0px 20px -7px #485fed
.header-subtitle
font-weight: 400
position: relative
font-size: 12px
text-shadow: 0px 0px 5px rgba(#000, 0.5)
.header-title
font-size: 20px
margin: 3px 0 0 0
letter-spacing: 1px
font-weight: 600
text-shadow: 0px 0px 5px rgba(#000, 0.5)
.header-icon
position: absolute
top: 48%
transform: translateY(-50%)
right: 20px
.data-section
margin-top: -8px
.container
h3
color: #333
font-size: 15px
padding-top: 7px
margin-bottom: 8px
margin-left: -8px
position: relative
&::before // for horizontal line at section title
content: ""
display: block
width: 78%
height: 2px
background-color: #999
position: absolute
top: 60%
right: 0
.data-wrapper
margin-bottom: -10px
.data-item
position: relative
margin-bottom: 5px
padding-left: 30px
cursor: pointer
.data__point
margin: 0
color: #333
font-size: 14px
font-weight: 500
letter-spacing: 0.5px
.data__title
position: absolute
top: 0px
right: 0
color: #666
font-size: 11px
font-weight: 600
font-style: italic
.data_point_sublabel
position: relative
top: -1px
left: 5px
color: #666
font-size: 10px
font-weight: 500
font-style: italic
// CSS for ICONS
.icon
width: auto
position: absolute
left: 0px
top: -1px
.icon_pulsing
width: auto
position: absolute
left: 0px
top: -1px
.icon_pulsing:before
position: absolute
top: 3px
left: 3px
width: 14px
height: 14px
border-radius: 50%
content: ''
box-shadow: inset 0 0 0 6px #f00
transition: transform 0.2s, opacity 0.2s
animation: pulsing 2.1s infinite
z-index: -1
@keyframes pulsing
0%
transform: scale(1)
opacity: 1
50%
transform: scale(2)
opacity: 1
100%
transform: scale(1)
opacity: 0
"""
render: -> """
<div class="mobile-wrapper">
<section class="header-box" id="header-box">
<h3 class="header-title">My Fritz!Box</h3>
<span class="header-subtitle" id="model">N/A</span>
<div class="header-icon">
<img style='vertical-align:middle; margin-top: 0px' src='fritzBoxPro.widget/FritzLogo70px.png'/>
</div>
</section>
<!--======= Data section General =======-->
<section class="data-section">
<div class="container">
<h3>
General
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon" id="firmware_div"><img id="firmware_icon" src='fritzBoxPro.widget/icons/accept_database.svg' height="20px;"/></div>
<h4 class="data__point" id='firmwareVersion'>N/A</h4>
<div class="data_point_sublabel" id="firmwareUpdateAvailable" style="display:none">N/A</div>
<span class="data__title">Firmware</span>
</div>
<div class="data-item">
<div class="icon"><img id="provider_icon" src='fritzBoxPro.widget/icons/filing_cabinet.svg' height="20px;"/></div>
<h4 class="data__point" id='providerName'>N/A</h4>
<span class="data__title">Provider</span>
</div>
<div class="data-item">
<div class="icon"><img id="uptime_icon" src='fritzBoxPro.widget/icons/clock.svg' height="20px;"/></div>
<h4 class="data__point" id='uptime'>N/A</h4>
<span class="data__title">Uptime</span>
</div>
<!--
<div class="data-item">
<h4 class="data__point" id='errorLog'>N/A</h4>
<span class="data__title">errorLog</span>
</div>
-->
</div>
</section>
<!--======= Data section Network =======-->
<section class="data-section">
<div class="container">
<h3>
Network
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon"><img id="externalIP" src='fritzBoxPro.widget/icons/link.svg' height="20px;"/></div>
<h4 class="data__point" id='ipAddress'>N/A</h4>
<span class="data__title">Ext. IP Address</span>
</div>
<div class="data-item">
<!--<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="wifi2gswitch" checked>
<label class="onoffswitch-label" for="wifi2gswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>-->
<div class="icon"><img id="wifi2gswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='2g_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="2g_connectedDevices">N/A</div>
<span class="data__title">2.4 Ghz WiFi</span>
</div>
<div class="data-item">
<div class="icon"><img id="wifi5gswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='5g_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="5g_connectedDevices">N/A</div>
<span class="data__title">5 Ghz WiFI</span>
</div>
<div class="data-item">
<div class="icon"><img id="wifiguestswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='guest_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="guest_connectedDevices">N/A</div>
<span class="data__title">Guest WiFI</span>
</div>
</div>
</section>
<!--======= Data section TAM (Answering machine) =======-->
<section class="data-section">
<div class="container">
<h3>
TAM
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon"><img id="tamswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point"><span id='nameTAM'> N/A</span></h4>
<span class="data__title">Name</span>
</div>
<div class="data-item">
<div class="icon" id="voicemail_div"><img id="voicemail" src='fritzBoxPro.widget/icons/voicemail.svg' height="20px;"/></div>
<h4 class="data__point"><span id='nbOfCallsNew'> N/A</span> / <span id='nbOfCallsTotal'> N/A</span></h4>
<span class="data__title">New / Total calls</span>
</div>
</div>
</section>
</div>
"""
update: (output,domEl) ->
values = output.split("\n")
div = $(domEl)
# ----------- For 2.4 Ghz WiFi display ------------
values2G = values[0].split(";")
if (values2G[1] != "")
div.find('#2g_SSID').html(values2G[1])
if (values2G[3] != "")
div.find('#2g_connectedDevices').html(values2G[3] + " devices connected")
if (parseInt(values2G[2]) == 1)
#div.find('#wifi2gswitch').attr("checked", true)
div.find('#wifi2gswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values2G[2]) == 0)
div.find('#wifi2gswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ------------ For 5 Ghz WiFi display -------------
values5G = values[1].split(";")
if (values5G[1] != "")
div.find('#5g_SSID').html(values5G[1])
if (values5G[3] != "")
div.find('#5g_connectedDevices').html(values5G[3] + " devices connected")
if (parseInt(values5G[2]) == 1)
div.find('#wifi5gswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values5G[2]) == 0)
div.find('#wifi5gswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ------------ For Guest WiFi display -------------
valuesGuest = values[2].split(";")
if (valuesGuest[1] != "")
div.find('#guest_SSID').html(valuesGuest[1])
if (valuesGuest[3] != "")
div.find('#guest_connectedDevices').html(valuesGuest[3] + " devices connected")
if (parseInt(valuesGuest[2]) == 1)
div.find('#wifiguestswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(valuesGuest[2]) == 0)
div.find('#wifiguestswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ---------- External IP Address display ----------
if (values[3] != "")
div.find('#ipAddress').html(values[3])
# ------------ Fritz!Box model display ------------
if (values[4] != "")
div.find('#model').html(values[4])
# ---------- Firmware version display ---------q----
if (values[5] != "")
div.find('#firmwareVersion').html("v" + values[5].split(".")[1] + "." + values[5].split(".")[2])
if (parseInt(values[12]) == 1)
div.find('#firmware_icon').attr("src", "fritzBoxPro.widget/icons/data_backup.svg")
div.find('#firmwareUpdateAvailable').html("Firmware update available. Visit http://fritz.box")
div.find('#firmwareUpdateAvailable').attr("style", "display:block")
div.find('#firmware_div').attr("class", "icon_pulsing")
else if (parseInt(values[12]) == 0)
div.find('#firmware_icon').attr("src", "fritzBoxPro.widget/icons/accept_database.svg")
div.find('#firmwareUpdateAvailable').attr("style", "display:none")
div.find('#firmware_div').attr("class", "icon")
# --------------- Uptime display ------------------
if (values[6] != "")
div.find('#uptime').html(values[6].split(":")[0] + " d, " + values[6].split(":")[1] + " h, " + values[6].split(":")[2] + " m")
# ------- Answering machine (TAM) display ---------
if (values[7] != "")
div.find('#nameTAM').html(values[7].split(" ")[1])
if (parseInt(values[8].split(" ")[1]) == 1)
div.find('#tamswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values[8].split(" ")[1]) == 0)
div.find('#tamswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
if (values[9] != "")
div.find('#nbOfCallsNew').html(values[9])
if(parseInt(values[9]) >= 1)
div.find('#voicemail_div').attr("class", "icon_pulsing")
div.find('#nbOfCallsNew').attr("style", "color:red")
else if(parseInt(values[9]) == 0)
div.find('#voicemail_div').attr("class", "icon")
div.find('#nbOfCallsNew').attr("style", "color:#333")
if (values[10] != "")
div.find('#nbOfCallsTotal').html(values[10].split(":")[1])
# --------------- Provider name display ------------------
if (values[11] != "")
div.find('#providerName').html(values[11])
| true | #-----------------------------------------------------------------------#
# fritzBoxPro for Übersicht
# Created April 2020 by PI:NAME:<NAME>END_PI
# Position of the widget on your screen
pos_top = '120px'
pos_left = '370px'
#-----------------------------------------------------------------------#
command: "fritzBoxPro.widget/fritzBoxShell.sh"
# Update every 60 seconds (don't put higher refresh rate than 20 seconds - There seems to be a limit by the TR064 protocol requests)
refreshFrequency: 30000
style: """
top: #{pos_top}
left: #{pos_left}
font-family: Avenir Next
.container
width: 90%
margin: auto
.mobile-wrapper
background: rgba(255, 255, 255, 0.7)
position: relative
width: 360px
min-height: 100%
margin: auto
padding: 10px 0 20px
border-radius: 10px
box-shadow: 0px 10px 30px -10px #000
overflow: hidden
.header-box
background: linear-gradient(to left, #485fed, rgba(255, 255, 255, .2)), #485fed
color: #FFF
padding: 4px 15px
position: relative
box-shadow: 0px 0px 20px -7px #485fed
.header-subtitle
font-weight: 400
position: relative
font-size: 12px
text-shadow: 0px 0px 5px rgba(#000, 0.5)
.header-title
font-size: 20px
margin: 3px 0 0 0
letter-spacing: 1px
font-weight: 600
text-shadow: 0px 0px 5px rgba(#000, 0.5)
.header-icon
position: absolute
top: 48%
transform: translateY(-50%)
right: 20px
.data-section
margin-top: -8px
.container
h3
color: #333
font-size: 15px
padding-top: 7px
margin-bottom: 8px
margin-left: -8px
position: relative
&::before // for horizontal line at section title
content: ""
display: block
width: 78%
height: 2px
background-color: #999
position: absolute
top: 60%
right: 0
.data-wrapper
margin-bottom: -10px
.data-item
position: relative
margin-bottom: 5px
padding-left: 30px
cursor: pointer
.data__point
margin: 0
color: #333
font-size: 14px
font-weight: 500
letter-spacing: 0.5px
.data__title
position: absolute
top: 0px
right: 0
color: #666
font-size: 11px
font-weight: 600
font-style: italic
.data_point_sublabel
position: relative
top: -1px
left: 5px
color: #666
font-size: 10px
font-weight: 500
font-style: italic
// CSS for ICONS
.icon
width: auto
position: absolute
left: 0px
top: -1px
.icon_pulsing
width: auto
position: absolute
left: 0px
top: -1px
.icon_pulsing:before
position: absolute
top: 3px
left: 3px
width: 14px
height: 14px
border-radius: 50%
content: ''
box-shadow: inset 0 0 0 6px #f00
transition: transform 0.2s, opacity 0.2s
animation: pulsing 2.1s infinite
z-index: -1
@keyframes pulsing
0%
transform: scale(1)
opacity: 1
50%
transform: scale(2)
opacity: 1
100%
transform: scale(1)
opacity: 0
"""
render: -> """
<div class="mobile-wrapper">
<section class="header-box" id="header-box">
<h3 class="header-title">My Fritz!Box</h3>
<span class="header-subtitle" id="model">N/A</span>
<div class="header-icon">
<img style='vertical-align:middle; margin-top: 0px' src='fritzBoxPro.widget/FritzLogo70px.png'/>
</div>
</section>
<!--======= Data section General =======-->
<section class="data-section">
<div class="container">
<h3>
General
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon" id="firmware_div"><img id="firmware_icon" src='fritzBoxPro.widget/icons/accept_database.svg' height="20px;"/></div>
<h4 class="data__point" id='firmwareVersion'>N/A</h4>
<div class="data_point_sublabel" id="firmwareUpdateAvailable" style="display:none">N/A</div>
<span class="data__title">Firmware</span>
</div>
<div class="data-item">
<div class="icon"><img id="provider_icon" src='fritzBoxPro.widget/icons/filing_cabinet.svg' height="20px;"/></div>
<h4 class="data__point" id='providerName'>N/A</h4>
<span class="data__title">Provider</span>
</div>
<div class="data-item">
<div class="icon"><img id="uptime_icon" src='fritzBoxPro.widget/icons/clock.svg' height="20px;"/></div>
<h4 class="data__point" id='uptime'>N/A</h4>
<span class="data__title">Uptime</span>
</div>
<!--
<div class="data-item">
<h4 class="data__point" id='errorLog'>N/A</h4>
<span class="data__title">errorLog</span>
</div>
-->
</div>
</section>
<!--======= Data section Network =======-->
<section class="data-section">
<div class="container">
<h3>
Network
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon"><img id="externalIP" src='fritzBoxPro.widget/icons/link.svg' height="20px;"/></div>
<h4 class="data__point" id='ipAddress'>N/A</h4>
<span class="data__title">Ext. IP Address</span>
</div>
<div class="data-item">
<!--<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="wifi2gswitch" checked>
<label class="onoffswitch-label" for="wifi2gswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>-->
<div class="icon"><img id="wifi2gswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='2g_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="2g_connectedDevices">N/A</div>
<span class="data__title">2.4 Ghz WiFi</span>
</div>
<div class="data-item">
<div class="icon"><img id="wifi5gswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='5g_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="5g_connectedDevices">N/A</div>
<span class="data__title">5 Ghz WiFI</span>
</div>
<div class="data-item">
<div class="icon"><img id="wifiguestswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point">SSID: <span id='guest_SSID'> N/A</span></h4>
<div class="data_point_sublabel" id="guest_connectedDevices">N/A</div>
<span class="data__title">Guest WiFI</span>
</div>
</div>
</section>
<!--======= Data section TAM (Answering machine) =======-->
<section class="data-section">
<div class="container">
<h3>
TAM
</h3>
<div class="data-wrapper">
<div class="data-item">
<div class="icon"><img id="tamswitch" src='fritzBoxPro.widget/icons/cancel.svg' height="20px;"/></div>
<h4 class="data__point"><span id='nameTAM'> N/A</span></h4>
<span class="data__title">Name</span>
</div>
<div class="data-item">
<div class="icon" id="voicemail_div"><img id="voicemail" src='fritzBoxPro.widget/icons/voicemail.svg' height="20px;"/></div>
<h4 class="data__point"><span id='nbOfCallsNew'> N/A</span> / <span id='nbOfCallsTotal'> N/A</span></h4>
<span class="data__title">New / Total calls</span>
</div>
</div>
</section>
</div>
"""
update: (output,domEl) ->
values = output.split("\n")
div = $(domEl)
# ----------- For 2.4 Ghz WiFi display ------------
values2G = values[0].split(";")
if (values2G[1] != "")
div.find('#2g_SSID').html(values2G[1])
if (values2G[3] != "")
div.find('#2g_connectedDevices').html(values2G[3] + " devices connected")
if (parseInt(values2G[2]) == 1)
#div.find('#wifi2gswitch').attr("checked", true)
div.find('#wifi2gswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values2G[2]) == 0)
div.find('#wifi2gswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ------------ For 5 Ghz WiFi display -------------
values5G = values[1].split(";")
if (values5G[1] != "")
div.find('#5g_SSID').html(values5G[1])
if (values5G[3] != "")
div.find('#5g_connectedDevices').html(values5G[3] + " devices connected")
if (parseInt(values5G[2]) == 1)
div.find('#wifi5gswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values5G[2]) == 0)
div.find('#wifi5gswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ------------ For Guest WiFi display -------------
valuesGuest = values[2].split(";")
if (valuesGuest[1] != "")
div.find('#guest_SSID').html(valuesGuest[1])
if (valuesGuest[3] != "")
div.find('#guest_connectedDevices').html(valuesGuest[3] + " devices connected")
if (parseInt(valuesGuest[2]) == 1)
div.find('#wifiguestswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(valuesGuest[2]) == 0)
div.find('#wifiguestswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
# ---------- External IP Address display ----------
if (values[3] != "")
div.find('#ipAddress').html(values[3])
# ------------ Fritz!Box model display ------------
if (values[4] != "")
div.find('#model').html(values[4])
# ---------- Firmware version display ---------q----
if (values[5] != "")
div.find('#firmwareVersion').html("v" + values[5].split(".")[1] + "." + values[5].split(".")[2])
if (parseInt(values[12]) == 1)
div.find('#firmware_icon').attr("src", "fritzBoxPro.widget/icons/data_backup.svg")
div.find('#firmwareUpdateAvailable').html("Firmware update available. Visit http://fritz.box")
div.find('#firmwareUpdateAvailable').attr("style", "display:block")
div.find('#firmware_div').attr("class", "icon_pulsing")
else if (parseInt(values[12]) == 0)
div.find('#firmware_icon').attr("src", "fritzBoxPro.widget/icons/accept_database.svg")
div.find('#firmwareUpdateAvailable').attr("style", "display:none")
div.find('#firmware_div').attr("class", "icon")
# --------------- Uptime display ------------------
if (values[6] != "")
div.find('#uptime').html(values[6].split(":")[0] + " d, " + values[6].split(":")[1] + " h, " + values[6].split(":")[2] + " m")
# ------- Answering machine (TAM) display ---------
if (values[7] != "")
div.find('#nameTAM').html(values[7].split(" ")[1])
if (parseInt(values[8].split(" ")[1]) == 1)
div.find('#tamswitch').attr("src", "fritzBoxPro.widget/icons/ok.svg")
else if (parseInt(values[8].split(" ")[1]) == 0)
div.find('#tamswitch').attr("src", "fritzBoxPro.widget/icons/cancel.svg")
if (values[9] != "")
div.find('#nbOfCallsNew').html(values[9])
if(parseInt(values[9]) >= 1)
div.find('#voicemail_div').attr("class", "icon_pulsing")
div.find('#nbOfCallsNew').attr("style", "color:red")
else if(parseInt(values[9]) == 0)
div.find('#voicemail_div').attr("class", "icon")
div.find('#nbOfCallsNew').attr("style", "color:#333")
if (values[10] != "")
div.find('#nbOfCallsTotal').html(values[10].split(":")[1])
# --------------- Provider name display ------------------
if (values[11] != "")
div.find('#providerName').html(values[11])
|
[
{
"context": "ions' mixin unit-tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\neval(Test.bu",
"end": 80,
"score": 0.9998878240585327,
"start": 63,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/core/test/options_test.coffee | lovely-io/lovely.io-stl | 2 | #
# The 'Options' mixin unit-tests
#
# Copyright (C) 2011-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
describe 'Options', ->
Class = Lovely.Class
Options = Lovely.Options
# a simple options module usage
Simple = new Class
include: Options
extend:
Options:
one: 'thing'
another: 'one'
constructor: (options) ->
this.setOptions options
# a subclass options usage
SubSimple = new Class Simple,
constructor: (options) ->
this.$super(options)
# deep options merge check
Deep = new Class
include: Options
extend:
Options:
one: 'thing'
another:
one: 1
two: 2
constructor: (options) ->
this.setOptions options
describe 'simple case', ->
it 'should use defaults without options', ->
new Simple().options.should.eql one: 'thing', another: 'one'
it 'should overwrite defaults with custom options', ->
new Simple(one: 'new').options.should.eql one: 'new', another: 'one'
it "should not screw with the Lovely.Class instances", ->
Klass = new Class()
klass = new Klass()
new Simple(one: klass).options.one.should.equal klass
describe 'with inheritance', ->
it 'should find the defaults in super classes', ->
new SubSimple(one: 'new').options.should.eql one: 'new', another: 'one'
describe 'nested options', ->
it 'should deep-merge nested options', ->
new Deep(one: 'new', another: one: 3).options.should.eql one: 'new', another: one: 3, two: 2
| 98419 | #
# The 'Options' mixin unit-tests
#
# Copyright (C) 2011-2013 <NAME>
#
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
describe 'Options', ->
Class = Lovely.Class
Options = Lovely.Options
# a simple options module usage
Simple = new Class
include: Options
extend:
Options:
one: 'thing'
another: 'one'
constructor: (options) ->
this.setOptions options
# a subclass options usage
SubSimple = new Class Simple,
constructor: (options) ->
this.$super(options)
# deep options merge check
Deep = new Class
include: Options
extend:
Options:
one: 'thing'
another:
one: 1
two: 2
constructor: (options) ->
this.setOptions options
describe 'simple case', ->
it 'should use defaults without options', ->
new Simple().options.should.eql one: 'thing', another: 'one'
it 'should overwrite defaults with custom options', ->
new Simple(one: 'new').options.should.eql one: 'new', another: 'one'
it "should not screw with the Lovely.Class instances", ->
Klass = new Class()
klass = new Klass()
new Simple(one: klass).options.one.should.equal klass
describe 'with inheritance', ->
it 'should find the defaults in super classes', ->
new SubSimple(one: 'new').options.should.eql one: 'new', another: 'one'
describe 'nested options', ->
it 'should deep-merge nested options', ->
new Deep(one: 'new', another: one: 3).options.should.eql one: 'new', another: one: 3, two: 2
| true | #
# The 'Options' mixin unit-tests
#
# Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
describe 'Options', ->
Class = Lovely.Class
Options = Lovely.Options
# a simple options module usage
Simple = new Class
include: Options
extend:
Options:
one: 'thing'
another: 'one'
constructor: (options) ->
this.setOptions options
# a subclass options usage
SubSimple = new Class Simple,
constructor: (options) ->
this.$super(options)
# deep options merge check
Deep = new Class
include: Options
extend:
Options:
one: 'thing'
another:
one: 1
two: 2
constructor: (options) ->
this.setOptions options
describe 'simple case', ->
it 'should use defaults without options', ->
new Simple().options.should.eql one: 'thing', another: 'one'
it 'should overwrite defaults with custom options', ->
new Simple(one: 'new').options.should.eql one: 'new', another: 'one'
it "should not screw with the Lovely.Class instances", ->
Klass = new Class()
klass = new Klass()
new Simple(one: klass).options.one.should.equal klass
describe 'with inheritance', ->
it 'should find the defaults in super classes', ->
new SubSimple(one: 'new').options.should.eql one: 'new', another: 'one'
describe 'nested options', ->
it 'should deep-merge nested options', ->
new Deep(one: 'new', another: one: 3).options.should.eql one: 'new', another: one: 3, two: 2
|
[
{
"context": " like below:\n # \"params\": {\n # \"keywords\": \"rainbow\",\n # \"limit\": \"25\",\n # \"offset\": \"1\",\n",
"end": 375,
"score": 0.4364684820175171,
"start": 371,
"tag": "PASSWORD",
"value": "rain"
}
] | src/etsyjs/search.coffee | madajaju/etsy-js | 2 | class Search
# An odd thing I found out about the Etsy API is that it returns differnt types in param
# depending on whether you set the limit and offset values or not.
# If none are specified then limit and offset are returned as int's, but if they are specified
# due to pagination, they the API returns strings like below:
# "params": {
# "keywords": "rainbow",
# "limit": "25",
# "offset": "1",
# "page": null
# },
constructor: (@client) ->
# Finds all Users whose name or username match the keywords parameter
# '/users' GET
findAllUsers: (params, cb) ->
@client.get "/users", params, (err, status, body, headers) ->
return cb(err) if err
if status isnt 200
cb(new Error('Search users error'))
else
cb null, body, headers
# Finds all listings whose id match the params
# '/listings' GET
findAllListings: (params, cb) ->
@client.get "/listings", params, (err, status, body, headers) ->
return cb(err) if err
if status isnt 200
cb(new Error('Search listings error'))
else
cb null, body, headers
module.exports = Search | 64852 | class Search
# An odd thing I found out about the Etsy API is that it returns differnt types in param
# depending on whether you set the limit and offset values or not.
# If none are specified then limit and offset are returned as int's, but if they are specified
# due to pagination, they the API returns strings like below:
# "params": {
# "keywords": "<PASSWORD>bow",
# "limit": "25",
# "offset": "1",
# "page": null
# },
constructor: (@client) ->
# Finds all Users whose name or username match the keywords parameter
# '/users' GET
findAllUsers: (params, cb) ->
@client.get "/users", params, (err, status, body, headers) ->
return cb(err) if err
if status isnt 200
cb(new Error('Search users error'))
else
cb null, body, headers
# Finds all listings whose id match the params
# '/listings' GET
findAllListings: (params, cb) ->
@client.get "/listings", params, (err, status, body, headers) ->
return cb(err) if err
if status isnt 200
cb(new Error('Search listings error'))
else
cb null, body, headers
module.exports = Search | true | class Search
# An odd thing I found out about the Etsy API is that it returns differnt types in param
# depending on whether you set the limit and offset values or not.
# If none are specified then limit and offset are returned as int's, but if they are specified
# due to pagination, they the API returns strings like below:
# "params": {
# "keywords": "PI:PASSWORD:<PASSWORD>END_PIbow",
# "limit": "25",
# "offset": "1",
# "page": null
# },
constructor: (@client) ->
# Finds all Users whose name or username match the keywords parameter
# '/users' GET
findAllUsers: (params, cb) ->
@client.get "/users", params, (err, status, body, headers) ->
return cb(err) if err
if status isnt 200
cb(new Error('Search users error'))
else
cb null, body, headers
# Finds all listings whose id match the params
# '/listings' GET
findAllListings: (params, cb) ->
@client.get "/listings", params, (err, status, body, headers) ->
return cb(err) if err
if status isnt 200
cb(new Error('Search listings error'))
else
cb null, body, headers
module.exports = Search |
[
{
"context": "# Droplet JavaScript mode\n#\n# Copyright (c) 2015 Anthony Bau (dab1998@gmail.com)\n# MIT License.\n\nhelper = requ",
"end": 60,
"score": 0.9998623132705688,
"start": 49,
"tag": "NAME",
"value": "Anthony Bau"
},
{
"context": "vaScript mode\n#\n# Copyright (c) 2015 Antho... | src/languages/javascript.coffee | cacticouncil/droplet | 3 | # Droplet JavaScript mode
#
# Copyright (c) 2015 Anthony Bau (dab1998@gmail.com)
# MIT License.
helper = require '../helper.coffee'
model = require '../model.coffee'
parser = require '../parser.coffee'
acorn = require '../../vendor/acorn'
STATEMENT_NODE_TYPES = [
'ExpressionStatement'
'ReturnStatement'
'BreakStatement'
'ThrowStatement'
]
NEVER_PAREN = 100
KNOWN_FUNCTIONS =
'alert' : {}
'prompt' : {}
'console.log' : {}
'*.toString' : {value: true}
'Math.abs' : {value: true}
'Math.acos' : {value: true}
'Math.asin' : {value: true}
'Math.atan' : {value: true}
'Math.atan2' : {value: true}
'Math.cos' : {value: true}
'Math.sin' : {value: true}
'Math.tan' : {value: true}
'Math.ceil' : {value: true}
'Math.floor' : {value: true}
'Math.round' : {value: true}
'Math.exp' : {value: true}
'Math.ln' : {value: true}
'Math.log10' : {value: true}
'Math.pow' : {value: true}
'Math.sqrt' : {value: true}
'Math.max' : {value: true}
'Math.min' : {value: true}
'Math.random' : {value: true}
CATEGORIES = {
functions: {color: 'class_body'}
returns: {color: 'statement'}
comments: {color: 'comment'}
arithmetic: {color: 'arithmetic'}
logic: {color: 'loop_logic'}
containers: {color: 'teal'}
assignments: {color: 'statement'}
loops: {color: 'control'}
conditionals: {color: 'control'}
value: {color: 'statement'}
command: {color: 'statement'}
errors: {color: '#f00'}
}
LOGICAL_OPERATORS = {
'==': true
'!=': true
'===': true
'!==': true
'<': true
'<=': true
'>': true
'>=': true
'in': true
'instanceof': true
'||': true
'&&': true
'!': true
}
NODE_CATEGORIES = {
'BinaryExpression': 'arithmetic' # actually, some are logic
'UnaryExpression': 'arithmetic' # actually, some are logic
'ConditionalExpression': 'arithmetic'
'LogicalExpression': 'logic'
'FunctionExpression': 'functions'
'FunctionDeclaration': 'functions'
'AssignmentExpression': 'assignments'
'UpdateExpression': 'assignments'
'VariableDeclaration': 'assignments'
'ReturnStatement': 'returns'
'IfStatement': 'conditionals'
'SwitchStatement': 'conditionals'
'ForStatement': 'loops'
'ForInStatement': 'loops'
'WhileStatement': 'loops'
'DoWhileStatement': 'loops'
'NewExpression': 'containers'
'ObjectExpression': 'containers'
'ArrayExpression': 'containers'
'MemberExpression': 'containers'
'BreakStatement': 'returns'
'ThrowStatement': 'returns'
'TryStatement': 'returns'
'CallExpression': 'command'
'SequenceExpression': 'command'
'Identifier': 'value'
}
# See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
# These numbers are "19 - x" so that the lowest numbers bind most tightly.
OPERATOR_PRECEDENCES = {
'++': 3
'--': 3
'!': 4
'~': 4
'*': 5
'/': 5
'%': 5
'+': 6
'-': 6
'<<': 7
'>>': 7
'>>>': 7
'<': 8
'>': 8
'>=': 8
'in': 8
'instanceof': 8
'==': 9
'!=': 9
'===': 9
'!==': 9
'&': 10
'^': 11
'|': 12
'&&': 13
'||': 14
}
PRECEDENCE = {
'AssignStatement': 16
'CallExpression': 2
'NewExpression': 2
'MemberExpression': 1
'Expression': NEVER_PAREN
'Lvalue': NEVER_PAREN
'IfTest': NEVER_PAREN
'ForEachLHS': NEVER_PAREN
'ForEachRHS': 10
'ForInit': NEVER_PAREN
'ForUpdate': 10
'Callee': NEVER_PAREN # Actually so?
'CalleeObject': NEVER_PAREN # Actually so?
}
for operator, precedence of OPERATOR_PRECEDENCES
PRECEDENCE['Operator' + operator] = precedence
getPrecedence = (type) ->
PRECEDENCE[type] ? 0
SEMICOLON_EXCEPTIONS = {
'ForStatement': true
'FunctionDeclaration': true
'IfStatement': true
'WhileStatement': true
'DoWhileStatement': true
'SwitchStatement': true
}
DEFAULT_INDENT_DEPTH = ' '
exports.JavaScriptParser = class JavaScriptParser extends parser.Parser
constructor: (@text, opts) ->
super
@opts.functions ?= KNOWN_FUNCTIONS
@opts.categories = helper.extend({}, CATEGORIES, @opts.categories)
@lines = @text.split '\n'
markRoot: ->
# Socket reparse of `{a: 1}` should be treated as ObjectExpression.
@text = "(#{@text})" if @text[0] == '{'
tree = acorn.parse(@text, {
locations: true
line: 0
allowReturnOutsideFunction: true
})
@mark 0, tree, 0, null
fullNameArray: (obj) ->
props = []
while obj.type is 'MemberExpression'
props.unshift obj.property.name
obj = obj.object
if obj.type is 'Identifier'
props.unshift obj.name
else
props.unshift '*'
props
lookupKnownName: (node) ->
if node.type is 'CallExpression' or node.type is 'NewExpression'
identifier = false
else if node.type is 'Identifier' or node.type is 'MemberExpression'
identifier = true
else
throw new Error
fname = @fullNameArray if identifier then node else node.callee
full = fname.join '.'
fn = @opts.functions[full]
if fn and ((identifier and fn.property) || (not identifier and not fn.property))
return name: full, anyobj: false, fn: @opts.functions[full]
last = fname[fname.length - 1]
if fname.length > 1 and (wildcard = '*.' + last) not of @opts.functions
wildcard = null # no match for '*.foo'
if not wildcard and (wildcard = '?.' + last) not of @opts.functions
wildcard = null # no match for '?.foo'
if wildcard isnt null
fn = @opts.functions[wildcard]
if fn and ((identifier and fn.property) || (not identifier and not fn.property))
return name: last, anyobj: true, fn: @opts.functions[wildcard]
return null
getAcceptsRule: (node) -> default: helper.NORMAL
getShape: (node) ->
if node.type is 'CallExpression' or node.type is 'NewExpression' or node.type is 'Identifier'
known = @lookupKnownName node
if not known or (known.fn.value and known.fn.command)
return helper.ANY_DROP
if known.fn.value
return helper.MOSTLY_VALUE
else
return helper.MOSTLY_BLOCK
else if node.type in ['ForStatement', 'FunctionDeclaration', 'IfStatement', 'WhileStatement', 'DoWhileStatement', 'SwitchStatement']
return helper.BLOCK_ONLY
else if node.type is 'AssignExpression'
return helper.MOSTLY_BLOCK
else if node.type.match(/Expression$/)?
return helper.MOSTLY_VALUE
else if node.type.match(/Declaration$/)?
return helper.BLOCK_ONLY
else if node.type.match(/Statement$/)?
return helper.MOSTLY_BLOCK
else
return helper.ANY_DROP
lookupCategory: (node) ->
switch node.type
when 'BinaryExpression', 'UnaryExpression'
if LOGICAL_OPERATORS.hasOwnProperty node.operator
category = 'logic'
else
category = 'arithmetic'
else
category = NODE_CATEGORIES[node.type]
return @opts.categories[category]
getColor: (node) ->
switch node.type
when 'ExpressionStatement'
return @getColor node.expression
when 'CallExpression', 'NewExpression', 'MemberExpression', 'Identifier'
known = @lookupKnownName node
if known
if known.fn.color
return known.fn.color
else if known.fn.value and not known.fn.command
return @opts.categories.value.color
category = @lookupCategory node
return category?.color or 'command'
getBounds: (node) ->
# If we are a statement, scan
# to find the semicolon
if node.type is 'BlockStatement'
bounds = {
start: {
line: node.loc.start.line
column: node.loc.start.column + 1
}
end: {
line: node.loc.end.line
column: node.loc.end.column - 1
}
}
bounds.start.column += (@lines[bounds.start.line][bounds.start.column..].match(/^\s*/) ? [''])[0].length
if @lines[bounds.end.line][...bounds.end.column].trim().length is 0
bounds.end.line -= 1
bounds.end.column = @lines[bounds.end.line].length
return bounds
else if node.type in STATEMENT_NODE_TYPES
line = @lines[node.loc.end.line]
semicolon = @lines[node.loc.end.line][node.loc.end.column - 1..].indexOf ';'
if semicolon >= 0
semicolonLength = @lines[node.loc.end.line][node.loc.end.column - 1..].match(/;\s*/)[0].length
return {
start: {
line: node.loc.start.line
column: node.loc.start.column
}
end: {
line: node.loc.end.line
column: node.loc.end.column + semicolon + semicolonLength - 1
}
}
return {
start: {
line: node.loc.start.line
column: node.loc.start.column
}
end: {
line: node.loc.end.line
column: node.loc.end.column
}
}
getCaseIndentBounds: (node) ->
bounds = {
start: @getBounds(node.consequent[0]).start
end: @getBounds(node.consequent[node.consequent.length - 1]).end
}
if @lines[bounds.start.line][...bounds.start.column].trim().length is 0
bounds.start.line -= 1
bounds.start.column = @lines[bounds.start.line].length
if @lines[bounds.end.line][...bounds.end.column].trim().length is 0
bounds.end.line -= 1
bounds.end.column = @lines[bounds.end.line].length
return bounds
getIndentPrefix: (bounds, indentDepth) ->
if bounds.end.line - bounds.start.line < 1
return DEFAULT_INDENT_DEPTH
else
line = @lines[bounds.start.line + 1]
return line[indentDepth...(line.length - line.trimLeft().length)]
isComment: (text) ->
text.match(/^\s*\/\/.*$/)?
parseComment: (text) ->
{
sockets: [[text.match(/^\s*\/\//)[0].length, text.length]]
}
handleButton: (text, button, oldBlock) ->
if button is 'add-button' and oldBlock.nodeContext.type is 'IfStatement'
# Parse to find the last "else" or "else if"
node = acorn.parse(text, {
locations: true
line: 0
allowReturnOutsideFunction: true
}).body[0]
currentElif = node
elseLocation = null
while true
if currentElif.type is 'IfStatement'
if currentElif.alternate?
elseLocation = {
line: currentElif.alternate.loc.start.line
column: currentElif.alternate.loc.start.column
}
currentElif = currentElif.alternate
else
elseLocation = null
break
else
break
if elseLocation?
lines = text.split('\n')
elseLocation = lines[...elseLocation.line].join('\n').length + elseLocation.column + 1
return text[...elseLocation].trimRight() + ' if (__) ' + text[elseLocation..].trimLeft() + ''' else {
__
}'''
else
return text + ''' else {
__
}'''
else if oldBlock.nodeContext.type is 'CallExpression'
# Parse to find the last "else" or "else if"
node = acorn.parse(text, {
line: 0
allowReturnOutsideFunction: true
}).body[0]
known = @lookupKnownName node.expression
argCount = node.expression.arguments.length
if button is 'add-button'
maxArgs = known?.fn.maxArgs
maxArgs ?= Infinity
if argCount >= maxArgs
return
if argCount
lastArgPosition = node.expression.arguments[argCount - 1].end
return text[...lastArgPosition].trimRight() + ', __' + text[lastArgPosition..].trimLeft()
else
lastArgPosition = node.expression.end - 1
return text[...lastArgPosition].trimRight() + '__' + text[lastArgPosition..].trimLeft()
else if button is 'subtract-button'
minArgs = known?.fn.minArgs
minArgs ?= 0
if argCount <= minArgs
return
if argCount > 0
lastArgPosition = node.expression.arguments[argCount - 1].end
if argCount is 1
newLastArgPosition = node.expression.arguments[0].start
else
newLastArgPosition = node.expression.arguments[argCount - 2].end
return text[...newLastArgPosition].trimRight() + text[lastArgPosition..].trimLeft()
mark: (indentDepth, node, depth, bounds) ->
switch node.type
when 'Program'
for statement in node.body
@mark indentDepth, statement, depth + 1, null
when 'Function'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
when 'SequenceExpression'
@jsBlock node, depth, bounds
for expression in node.expressions
@jsSocketAndMark indentDepth, expression, depth + 1, null
when 'FunctionDeclaration'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
@jsSocketAndMark indentDepth, node.id, depth + 1, 'Identifier', null
if node.params.length > 0
@addSocket {
bounds: {
start: @getBounds(node.params[0]).start
end: @getBounds(node.params[node.params.length - 1]).end
}
depth: depth + 1
parseContext: '__comment__'
dropdown: null
empty: ''
}
else unless @opts.lockZeroParamFunctions
nodeBoundsStart = @getBounds(node.id).end
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*\()(\s*)\)/)
if match?
@addSocket {
bounds: {
start: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length
}
end: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length + match[2].length
}
},
depth,
parseContext: '__comment__'
dropdown: null,
empty: ''
}
when 'FunctionExpression'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
if node.id?
@jsSocketAndMark indentDepth, node.id, depth + 1, 'Identifier', null
if node.params.length > 0
@addSocket {
bounds: {
start: @getBounds(node.params[0]).start
end: @getBounds(node.params[node.params.length - 1]).end
}
depth: depth + 1
parseContext: '__comment__'
empty: ''
}
else unless @opts.lockZeroParamFunctions
if node.id?
nodeBoundsStart = @getBounds(node.id).end
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*\()(\s*)\)/)
else
nodeBoundsStart = @getBounds(node).start
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*function\s*\()(\s*)\)/)
if match?
position =
@addSocket {
bounds: {
start: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length
}
end: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length + match[2].length
}
},
depth,
precedence: 0,
dropdown: null,
parseContext: '__comment__'
empty: ''
}
when 'AssignmentExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Lvalue'
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Expression'
when 'ReturnStatement'
@jsBlock node, depth, bounds
if node.argument?
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'IfStatement', 'ConditionalExpression'
@jsBlock node, depth, bounds, {addButton: '+'}
@jsSocketAndMark indentDepth, node.test, depth + 1, 'Expression'
@jsSocketAndMark indentDepth, node.consequent, depth + 1, null
# As long as the else fits the "else-if" pattern,
# don't mark a new block. Instead, mark the condition
# and body and continue down the elseif chain.
currentElif = node.alternate
while currentElif?
if currentElif.type is 'IfStatement'
@jsSocketAndMark indentDepth, currentElif.test, depth + 1, null
@jsSocketAndMark indentDepth, currentElif.consequent, depth + 1, null
currentElif = currentElif.alternate
else
@jsSocketAndMark indentDepth, currentElif, depth + 1, 10
currentElif = null
when 'ForInStatement'
@jsBlock node, depth, bounds
if node.left?
@jsSocketAndMark indentDepth, node.left, depth + 1, 'ForEachLHS', null, ['foreach-lhs']
if node.right?
@jsSocketAndMark indentDepth, node.right, depth + 1, 'ForEachRHS'
@mark indentDepth, node.body, depth + 1
when 'BreakStatement', 'ContinueStatement'
@jsBlock node, depth, bounds
if node.label?
@jsSocketAndMark indentDepth, node.label, depth + 1, null
when 'ThrowStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'ForStatement'
@jsBlock node, depth, bounds
# If we are in beginner mode, check to see if the for loop
# matches the "standard" way, and if so only mark the loop
# limit (the "b" in "for (...;a < b;...)").
if @opts.categories.loops.beginner and isStandardForLoop(node)
@jsSocketAndMark indentDepth, node.test.right
else
if node.init?
@jsSocketAndMark indentDepth, node.init, depth + 1, 'ForInit', null, ['for-statement-init']
if node.test?
@jsSocketAndMark indentDepth, node.test, depth + 1, 'Expression'
if node.update?
@jsSocketAndMark indentDepth, node.update, depth + 1, 'ForUpdate', null, ['for-statement-update']
@mark indentDepth, node.body, depth + 1
when 'BlockStatement'
prefix = @getIndentPrefix(@getBounds(node), indentDepth)
indentDepth += prefix.length
@addIndent
bounds: @getBounds node
depth: depth
prefix: prefix
for statement in node.body
@mark indentDepth, statement, depth + 1, null
when 'BinaryExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Operator' + node.operator
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Operator' + node.operator
when 'UnaryExpression'
unless node.operator in ['-', '+'] and
node.argument.type in ['Identifier', 'Literal']
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'ExpressionStatement'
@mark indentDepth, node.expression, depth + 1, @getBounds node
when 'Identifier'
if node.name is '__'
block = @jsBlock node, depth, bounds
block.flagToRemove = true
else if @lookupKnownName node
@jsBlock node, depth, bounds
when 'CallExpression', 'NewExpression'
known = @lookupKnownName node
blockOpts = {}
argCount = node.arguments.length
if known?.fn
showButtons = known.fn.minArgs? or known.fn.maxArgs?
minArgs = known.fn.minArgs ? 0
maxArgs = known.fn.maxArgs ? Infinity
else
showButtons = @opts.paramButtonsForUnknownFunctions and
(argCount isnt 0 or not @opts.lockZeroParamFunctions)
minArgs = 0
maxArgs = Infinity
if showButtons
if argCount < maxArgs
blockOpts.addButton = '\u21A0'
if argCount > minArgs
blockOpts.subtractButton = '\u219E'
@jsBlock node, depth, bounds, blockOpts
if not known
@jsSocketAndMark indentDepth, node.callee, depth + 1, 'Callee'
else if known.anyobj and node.callee.type is 'MemberExpression'
@jsSocketAndMark indentDepth, node.callee.object, depth + 1, 'CalleeObject', null, null, known?.fn?.objectDropdown
for argument, i in node.arguments
@jsSocketAndMark indentDepth, argument, depth + 1, 'Expression', null, null, known?.fn?.dropdown?[i]
if not known and argCount is 0 and not @opts.lockZeroParamFunctions
# Create a special socket that can be used for inserting the first parameter
# (NOTE: this socket may not be visible if the bounds start/end are the same)
position = {
line: node.callee.loc.end.line
column: node.callee.loc.end.column
}
string = @lines[position.line][position.column..].match(/^\s*\(/)[0]
position.column += string.length
endPosition = {
line: position.line
column: position.column
}
space = @lines[position.line][position.column..].match(/^(\s*)\)/)
if space?
endPosition.column += space[1].length
@addSocket {
bounds: {
start: position
end: endPosition
}
depth: depth + 1
dropdown: null
parseContext: 'Expression'
empty: ''
}
when 'MemberExpression'
@jsBlock node, depth, bounds
known = @lookupKnownName node
if not known
@jsSocketAndMark indentDepth, node.property, depth + 1
if not known or known.anyobj
@jsSocketAndMark indentDepth, node.object, depth + 1
when 'UpdateExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1
when 'VariableDeclaration'
@jsBlock node, depth, bounds
for declaration in node.declarations
@mark indentDepth, declaration, depth + 1
when 'VariableDeclarator'
@jsSocketAndMark indentDepth, node.id, depth, 'Lvalue'
if node.init?
@jsSocketAndMark indentDepth, node.init, depth, 'Expression'
when 'LogicalExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Operator' + node.operator
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Operator' + node.operator
when 'WhileStatement', 'DoWhileStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.body, depth + 1
@jsSocketAndMark indentDepth, node.test, depth + 1
when 'ObjectExpression'
@jsBlock node, depth, bounds
for property in node.properties
@jsSocketAndMark indentDepth, property.key, depth + 1
@jsSocketAndMark indentDepth, property.value, depth + 1
when 'SwitchStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.discriminant, depth + 1
for switchCase in node.cases
@mark indentDepth, switchCase, depth + 1, null
when 'SwitchCase'
if node.test?
@jsSocketAndMark indentDepth, node.test, depth + 1
if node.consequent.length > 0
bounds = @getCaseIndentBounds node
prefix = @getIndentPrefix(@getBounds(node), indentDepth)
indentDepth += prefix.length
@addIndent
bounds: bounds
depth: depth + 1
prefix: prefix
for statement in node.consequent
@mark indentDepth, statement, depth + 2
when 'TryStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.block, depth + 1, null
if node.handler?
if node.handler.guard?
@jsSocketAndMark indentDepth, node.handler.guard, depth + 1, null
if node.handler.param?
@jsSocketAndMark indentDepth, node.handler.param, depth + 1, null
@jsSocketAndMark indentDepth, node.handler.body, depth + 1, null
if node.finalizer?
@jsSocketAndMark indentDepth, node.finalizer, depth + 1, null
when 'ArrayExpression'
@jsBlock node, depth, bounds
for element in node.elements
if element?
@jsSocketAndMark indentDepth, element, depth + 1, null
when 'Literal'
null
else
console.log 'Unrecognized', node
jsBlock: (node, depth, bounds, buttons) ->
bounds ?= @getBounds node
@addBlock
bounds: bounds
depth: depth
color: @getColor node
shape: @getShape node
buttons: buttons
parseContext: 'program'
nodeContext: @getNodeContext node, bounds
getType: (node) ->
if node.type in ['BinaryExpression', 'LogicalExpression', 'UnaryExpression', 'UpdateExpression']
return 'Operator' + node.operator
else
return node.type
getNodeContext: (node, bounds, type) ->
type ?= @getType node
innerBounds = @getBounds node
prefix = helper.clipLines @lines, bounds.start, innerBounds.start
suffix = helper.clipLines @lines, innerBounds.end, bounds.end
return new parser.PreNodeContext type, prefix.length, suffix.length
jsSocketAndMark: (indentDepth, node, depth, type, bounds, classes, dropdown, empty) ->
unless node.type is 'BlockStatement'
bounds ?= @getBounds node
@addSocket
bounds: bounds
depth: depth
parseContext: type ? 'program'
dropdown: dropdown
empty: empty
@mark indentDepth, node, depth + 1, bounds
JavaScriptParser.parens = (leading, trailing, node, context) ->
# Don't attempt to paren wrap comments
return if '__comment__' is node.parseContext
if context?.type is 'socket' or
(not context? and helper.MOSTLY_VALUE is node.shape or helper.VALUE_ONLY is node.shape) or
SEMICOLON_EXCEPTIONS[node.nodeContext.type] or
node.type is 'document'
trailing trailing().replace(/;?\s*$/, '')
else
trailing trailing().replace(/;?\s*$/, ';')
while true
if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)?
leading leading().replace(/^\s*\(\s*/, '')
trailing trailing().replace(/\s*\)\s*$/, '')
else
break
unless context is null or context.type isnt 'socket' or
getPrecedence(context.parseContext) > getPrecedence(node.nodeContext.type)
console.log context.parseContext, node.nodeContext.type, getPrecedence(context.parseContext), getPrecedence(node.nodeContext.type)
leading '(' + leading()
trailing trailing() + ')'
JavaScriptParser.drop = (block, context, pred) ->
if context.parseContext is '__comment__'
return helper.FORBID
if context.type is 'socket'
if context.parseContext is 'Identifier'
return helper.FORBID
else if context.parseContext in ['Lvalue', 'ForEachLHS']
if block.nodeContext.type is 'ObjectExpression'
return helper.ENCOURAGE
else
return helper.FORBID
else if block.shape in [helper.VALUE_ONLY, helper.MOSTLY_VALUE, helper.ANY_DROP] or
context.parseContext is 'ForInit' or
(block.shape is helper.MOSTLY_BLOCK and
context.parseContext is 'ForUpdate')
return helper.ENCOURAGE
else if block.shape is helper.MOSTLY_BLOCK
return helper.DISCOURAGE
else if context.type in ['indent', 'document']
if block.shape in [helper.BLOCK_ONLY, helper.MOSTLY_BLOCK, helper.ANY_DROP] or
block.type is 'document'
return helper.ENCOURAGE
else if block.shape is helper.MOSTLY_VALUE
return helper.DISCOURAGE
return helper.DISCOURAGE
# Check to see if a "for" loop is standard, for beginner mode.
# We will simplify any loop of the form:
# ```
# for (var i = X; i < Y; i++) {
# // etc...
# }
# `
# Where "var" is optional and "i++" can be pre- or postincrement.
isStandardForLoop = (node) ->
unless node.init? and node.test? and node.update?
return false
# A standard for loop starts with "var a =" or "a = ".
# Determine the variable name so that we can check against it
# in the other two expression.
if node.init.type is 'VariableDeclaration'
variableName = node.init.declarations[0].id.name
else if node.init.type is 'AssignmentExpression' and
node.operator is '=' and
node.left.type is 'Identifier'
variableName = node.left.name
else
return false
return (node.test.type is 'BinaryExpression' and
node.test.operator is '<' and
node.test.left.type is 'Identifier' and
node.test.left.name is variableName and
node.test.right.type in ['Literal', 'Identifier'] and
node.update.type is 'UpdateExpression' and
node.update.operator is '++' and
node.update.argument.type is 'Identifier' and
node.update.argument.name is variableName)
JavaScriptParser.empty = "__"
JavaScriptParser.emptyIndent = ""
JavaScriptParser.startComment = '/*'
JavaScriptParser.endComment = '*/'
JavaScriptParser.startSingleLineComment = '//'
JavaScriptParser.getDefaultSelectionRange = (string) ->
start = 0; end = string.length
if string[0] is string[string.length - 1] and string[0] in ['"', '\'', '/']
start += 1; end -= 1
return {start, end}
module.exports = parser.wrapParser JavaScriptParser
| 72272 | # Droplet JavaScript mode
#
# Copyright (c) 2015 <NAME> (<EMAIL>)
# MIT License.
helper = require '../helper.coffee'
model = require '../model.coffee'
parser = require '../parser.coffee'
acorn = require '../../vendor/acorn'
STATEMENT_NODE_TYPES = [
'ExpressionStatement'
'ReturnStatement'
'BreakStatement'
'ThrowStatement'
]
NEVER_PAREN = 100
KNOWN_FUNCTIONS =
'alert' : {}
'prompt' : {}
'console.log' : {}
'*.toString' : {value: true}
'Math.abs' : {value: true}
'Math.acos' : {value: true}
'Math.asin' : {value: true}
'Math.atan' : {value: true}
'Math.atan2' : {value: true}
'Math.cos' : {value: true}
'Math.sin' : {value: true}
'Math.tan' : {value: true}
'Math.ceil' : {value: true}
'Math.floor' : {value: true}
'Math.round' : {value: true}
'Math.exp' : {value: true}
'Math.ln' : {value: true}
'Math.log10' : {value: true}
'Math.pow' : {value: true}
'Math.sqrt' : {value: true}
'Math.max' : {value: true}
'Math.min' : {value: true}
'Math.random' : {value: true}
CATEGORIES = {
functions: {color: 'class_body'}
returns: {color: 'statement'}
comments: {color: 'comment'}
arithmetic: {color: 'arithmetic'}
logic: {color: 'loop_logic'}
containers: {color: 'teal'}
assignments: {color: 'statement'}
loops: {color: 'control'}
conditionals: {color: 'control'}
value: {color: 'statement'}
command: {color: 'statement'}
errors: {color: '#f00'}
}
LOGICAL_OPERATORS = {
'==': true
'!=': true
'===': true
'!==': true
'<': true
'<=': true
'>': true
'>=': true
'in': true
'instanceof': true
'||': true
'&&': true
'!': true
}
NODE_CATEGORIES = {
'BinaryExpression': 'arithmetic' # actually, some are logic
'UnaryExpression': 'arithmetic' # actually, some are logic
'ConditionalExpression': 'arithmetic'
'LogicalExpression': 'logic'
'FunctionExpression': 'functions'
'FunctionDeclaration': 'functions'
'AssignmentExpression': 'assignments'
'UpdateExpression': 'assignments'
'VariableDeclaration': 'assignments'
'ReturnStatement': 'returns'
'IfStatement': 'conditionals'
'SwitchStatement': 'conditionals'
'ForStatement': 'loops'
'ForInStatement': 'loops'
'WhileStatement': 'loops'
'DoWhileStatement': 'loops'
'NewExpression': 'containers'
'ObjectExpression': 'containers'
'ArrayExpression': 'containers'
'MemberExpression': 'containers'
'BreakStatement': 'returns'
'ThrowStatement': 'returns'
'TryStatement': 'returns'
'CallExpression': 'command'
'SequenceExpression': 'command'
'Identifier': 'value'
}
# See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
# These numbers are "19 - x" so that the lowest numbers bind most tightly.
OPERATOR_PRECEDENCES = {
'++': 3
'--': 3
'!': 4
'~': 4
'*': 5
'/': 5
'%': 5
'+': 6
'-': 6
'<<': 7
'>>': 7
'>>>': 7
'<': 8
'>': 8
'>=': 8
'in': 8
'instanceof': 8
'==': 9
'!=': 9
'===': 9
'!==': 9
'&': 10
'^': 11
'|': 12
'&&': 13
'||': 14
}
PRECEDENCE = {
'AssignStatement': 16
'CallExpression': 2
'NewExpression': 2
'MemberExpression': 1
'Expression': NEVER_PAREN
'Lvalue': NEVER_PAREN
'IfTest': NEVER_PAREN
'ForEachLHS': NEVER_PAREN
'ForEachRHS': 10
'ForInit': NEVER_PAREN
'ForUpdate': 10
'Callee': NEVER_PAREN # Actually so?
'CalleeObject': NEVER_PAREN # Actually so?
}
for operator, precedence of OPERATOR_PRECEDENCES
PRECEDENCE['Operator' + operator] = precedence
getPrecedence = (type) ->
PRECEDENCE[type] ? 0
SEMICOLON_EXCEPTIONS = {
'ForStatement': true
'FunctionDeclaration': true
'IfStatement': true
'WhileStatement': true
'DoWhileStatement': true
'SwitchStatement': true
}
DEFAULT_INDENT_DEPTH = ' '
exports.JavaScriptParser = class JavaScriptParser extends parser.Parser
constructor: (@text, opts) ->
super
@opts.functions ?= KNOWN_FUNCTIONS
@opts.categories = helper.extend({}, CATEGORIES, @opts.categories)
@lines = @text.split '\n'
markRoot: ->
# Socket reparse of `{a: 1}` should be treated as ObjectExpression.
@text = "(#{@text})" if @text[0] == '{'
tree = acorn.parse(@text, {
locations: true
line: 0
allowReturnOutsideFunction: true
})
@mark 0, tree, 0, null
fullNameArray: (obj) ->
props = []
while obj.type is 'MemberExpression'
props.unshift obj.property.name
obj = obj.object
if obj.type is 'Identifier'
props.unshift obj.name
else
props.unshift '*'
props
lookupKnownName: (node) ->
if node.type is 'CallExpression' or node.type is 'NewExpression'
identifier = false
else if node.type is 'Identifier' or node.type is 'MemberExpression'
identifier = true
else
throw new Error
fname = @fullNameArray if identifier then node else node.callee
full = fname.join '.'
fn = @opts.functions[full]
if fn and ((identifier and fn.property) || (not identifier and not fn.property))
return name: full, anyobj: false, fn: @opts.functions[full]
last = fname[fname.length - 1]
if fname.length > 1 and (wildcard = '*.' + last) not of @opts.functions
wildcard = null # no match for '*.foo'
if not wildcard and (wildcard = '?.' + last) not of @opts.functions
wildcard = null # no match for '?.foo'
if wildcard isnt null
fn = @opts.functions[wildcard]
if fn and ((identifier and fn.property) || (not identifier and not fn.property))
return name: last, anyobj: true, fn: @opts.functions[wildcard]
return null
getAcceptsRule: (node) -> default: helper.NORMAL
getShape: (node) ->
if node.type is 'CallExpression' or node.type is 'NewExpression' or node.type is 'Identifier'
known = @lookupKnownName node
if not known or (known.fn.value and known.fn.command)
return helper.ANY_DROP
if known.fn.value
return helper.MOSTLY_VALUE
else
return helper.MOSTLY_BLOCK
else if node.type in ['ForStatement', 'FunctionDeclaration', 'IfStatement', 'WhileStatement', 'DoWhileStatement', 'SwitchStatement']
return helper.BLOCK_ONLY
else if node.type is 'AssignExpression'
return helper.MOSTLY_BLOCK
else if node.type.match(/Expression$/)?
return helper.MOSTLY_VALUE
else if node.type.match(/Declaration$/)?
return helper.BLOCK_ONLY
else if node.type.match(/Statement$/)?
return helper.MOSTLY_BLOCK
else
return helper.ANY_DROP
lookupCategory: (node) ->
switch node.type
when 'BinaryExpression', 'UnaryExpression'
if LOGICAL_OPERATORS.hasOwnProperty node.operator
category = 'logic'
else
category = 'arithmetic'
else
category = NODE_CATEGORIES[node.type]
return @opts.categories[category]
getColor: (node) ->
switch node.type
when 'ExpressionStatement'
return @getColor node.expression
when 'CallExpression', 'NewExpression', 'MemberExpression', 'Identifier'
known = @lookupKnownName node
if known
if known.fn.color
return known.fn.color
else if known.fn.value and not known.fn.command
return @opts.categories.value.color
category = @lookupCategory node
return category?.color or 'command'
getBounds: (node) ->
# If we are a statement, scan
# to find the semicolon
if node.type is 'BlockStatement'
bounds = {
start: {
line: node.loc.start.line
column: node.loc.start.column + 1
}
end: {
line: node.loc.end.line
column: node.loc.end.column - 1
}
}
bounds.start.column += (@lines[bounds.start.line][bounds.start.column..].match(/^\s*/) ? [''])[0].length
if @lines[bounds.end.line][...bounds.end.column].trim().length is 0
bounds.end.line -= 1
bounds.end.column = @lines[bounds.end.line].length
return bounds
else if node.type in STATEMENT_NODE_TYPES
line = @lines[node.loc.end.line]
semicolon = @lines[node.loc.end.line][node.loc.end.column - 1..].indexOf ';'
if semicolon >= 0
semicolonLength = @lines[node.loc.end.line][node.loc.end.column - 1..].match(/;\s*/)[0].length
return {
start: {
line: node.loc.start.line
column: node.loc.start.column
}
end: {
line: node.loc.end.line
column: node.loc.end.column + semicolon + semicolonLength - 1
}
}
return {
start: {
line: node.loc.start.line
column: node.loc.start.column
}
end: {
line: node.loc.end.line
column: node.loc.end.column
}
}
getCaseIndentBounds: (node) ->
bounds = {
start: @getBounds(node.consequent[0]).start
end: @getBounds(node.consequent[node.consequent.length - 1]).end
}
if @lines[bounds.start.line][...bounds.start.column].trim().length is 0
bounds.start.line -= 1
bounds.start.column = @lines[bounds.start.line].length
if @lines[bounds.end.line][...bounds.end.column].trim().length is 0
bounds.end.line -= 1
bounds.end.column = @lines[bounds.end.line].length
return bounds
getIndentPrefix: (bounds, indentDepth) ->
if bounds.end.line - bounds.start.line < 1
return DEFAULT_INDENT_DEPTH
else
line = @lines[bounds.start.line + 1]
return line[indentDepth...(line.length - line.trimLeft().length)]
isComment: (text) ->
text.match(/^\s*\/\/.*$/)?
parseComment: (text) ->
{
sockets: [[text.match(/^\s*\/\//)[0].length, text.length]]
}
handleButton: (text, button, oldBlock) ->
if button is 'add-button' and oldBlock.nodeContext.type is 'IfStatement'
# Parse to find the last "else" or "else if"
node = acorn.parse(text, {
locations: true
line: 0
allowReturnOutsideFunction: true
}).body[0]
currentElif = node
elseLocation = null
while true
if currentElif.type is 'IfStatement'
if currentElif.alternate?
elseLocation = {
line: currentElif.alternate.loc.start.line
column: currentElif.alternate.loc.start.column
}
currentElif = currentElif.alternate
else
elseLocation = null
break
else
break
if elseLocation?
lines = text.split('\n')
elseLocation = lines[...elseLocation.line].join('\n').length + elseLocation.column + 1
return text[...elseLocation].trimRight() + ' if (__) ' + text[elseLocation..].trimLeft() + ''' else {
__
}'''
else
return text + ''' else {
__
}'''
else if oldBlock.nodeContext.type is 'CallExpression'
# Parse to find the last "else" or "else if"
node = acorn.parse(text, {
line: 0
allowReturnOutsideFunction: true
}).body[0]
known = @lookupKnownName node.expression
argCount = node.expression.arguments.length
if button is 'add-button'
maxArgs = known?.fn.maxArgs
maxArgs ?= Infinity
if argCount >= maxArgs
return
if argCount
lastArgPosition = node.expression.arguments[argCount - 1].end
return text[...lastArgPosition].trimRight() + ', __' + text[lastArgPosition..].trimLeft()
else
lastArgPosition = node.expression.end - 1
return text[...lastArgPosition].trimRight() + '__' + text[lastArgPosition..].trimLeft()
else if button is 'subtract-button'
minArgs = known?.fn.minArgs
minArgs ?= 0
if argCount <= minArgs
return
if argCount > 0
lastArgPosition = node.expression.arguments[argCount - 1].end
if argCount is 1
newLastArgPosition = node.expression.arguments[0].start
else
newLastArgPosition = node.expression.arguments[argCount - 2].end
return text[...newLastArgPosition].trimRight() + text[lastArgPosition..].trimLeft()
mark: (indentDepth, node, depth, bounds) ->
switch node.type
when 'Program'
for statement in node.body
@mark indentDepth, statement, depth + 1, null
when 'Function'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
when 'SequenceExpression'
@jsBlock node, depth, bounds
for expression in node.expressions
@jsSocketAndMark indentDepth, expression, depth + 1, null
when 'FunctionDeclaration'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
@jsSocketAndMark indentDepth, node.id, depth + 1, 'Identifier', null
if node.params.length > 0
@addSocket {
bounds: {
start: @getBounds(node.params[0]).start
end: @getBounds(node.params[node.params.length - 1]).end
}
depth: depth + 1
parseContext: '__comment__'
dropdown: null
empty: ''
}
else unless @opts.lockZeroParamFunctions
nodeBoundsStart = @getBounds(node.id).end
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*\()(\s*)\)/)
if match?
@addSocket {
bounds: {
start: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length
}
end: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length + match[2].length
}
},
depth,
parseContext: '__comment__'
dropdown: null,
empty: ''
}
when 'FunctionExpression'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
if node.id?
@jsSocketAndMark indentDepth, node.id, depth + 1, 'Identifier', null
if node.params.length > 0
@addSocket {
bounds: {
start: @getBounds(node.params[0]).start
end: @getBounds(node.params[node.params.length - 1]).end
}
depth: depth + 1
parseContext: '__comment__'
empty: ''
}
else unless @opts.lockZeroParamFunctions
if node.id?
nodeBoundsStart = @getBounds(node.id).end
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*\()(\s*)\)/)
else
nodeBoundsStart = @getBounds(node).start
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*function\s*\()(\s*)\)/)
if match?
position =
@addSocket {
bounds: {
start: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length
}
end: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length + match[2].length
}
},
depth,
precedence: 0,
dropdown: null,
parseContext: '__comment__'
empty: ''
}
when 'AssignmentExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Lvalue'
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Expression'
when 'ReturnStatement'
@jsBlock node, depth, bounds
if node.argument?
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'IfStatement', 'ConditionalExpression'
@jsBlock node, depth, bounds, {addButton: '+'}
@jsSocketAndMark indentDepth, node.test, depth + 1, 'Expression'
@jsSocketAndMark indentDepth, node.consequent, depth + 1, null
# As long as the else fits the "else-if" pattern,
# don't mark a new block. Instead, mark the condition
# and body and continue down the elseif chain.
currentElif = node.alternate
while currentElif?
if currentElif.type is 'IfStatement'
@jsSocketAndMark indentDepth, currentElif.test, depth + 1, null
@jsSocketAndMark indentDepth, currentElif.consequent, depth + 1, null
currentElif = currentElif.alternate
else
@jsSocketAndMark indentDepth, currentElif, depth + 1, 10
currentElif = null
when 'ForInStatement'
@jsBlock node, depth, bounds
if node.left?
@jsSocketAndMark indentDepth, node.left, depth + 1, 'ForEachLHS', null, ['foreach-lhs']
if node.right?
@jsSocketAndMark indentDepth, node.right, depth + 1, 'ForEachRHS'
@mark indentDepth, node.body, depth + 1
when 'BreakStatement', 'ContinueStatement'
@jsBlock node, depth, bounds
if node.label?
@jsSocketAndMark indentDepth, node.label, depth + 1, null
when 'ThrowStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'ForStatement'
@jsBlock node, depth, bounds
# If we are in beginner mode, check to see if the for loop
# matches the "standard" way, and if so only mark the loop
# limit (the "b" in "for (...;a < b;...)").
if @opts.categories.loops.beginner and isStandardForLoop(node)
@jsSocketAndMark indentDepth, node.test.right
else
if node.init?
@jsSocketAndMark indentDepth, node.init, depth + 1, 'ForInit', null, ['for-statement-init']
if node.test?
@jsSocketAndMark indentDepth, node.test, depth + 1, 'Expression'
if node.update?
@jsSocketAndMark indentDepth, node.update, depth + 1, 'ForUpdate', null, ['for-statement-update']
@mark indentDepth, node.body, depth + 1
when 'BlockStatement'
prefix = @getIndentPrefix(@getBounds(node), indentDepth)
indentDepth += prefix.length
@addIndent
bounds: @getBounds node
depth: depth
prefix: prefix
for statement in node.body
@mark indentDepth, statement, depth + 1, null
when 'BinaryExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Operator' + node.operator
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Operator' + node.operator
when 'UnaryExpression'
unless node.operator in ['-', '+'] and
node.argument.type in ['Identifier', 'Literal']
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'ExpressionStatement'
@mark indentDepth, node.expression, depth + 1, @getBounds node
when 'Identifier'
if node.name is '__'
block = @jsBlock node, depth, bounds
block.flagToRemove = true
else if @lookupKnownName node
@jsBlock node, depth, bounds
when 'CallExpression', 'NewExpression'
known = @lookupKnownName node
blockOpts = {}
argCount = node.arguments.length
if known?.fn
showButtons = known.fn.minArgs? or known.fn.maxArgs?
minArgs = known.fn.minArgs ? 0
maxArgs = known.fn.maxArgs ? Infinity
else
showButtons = @opts.paramButtonsForUnknownFunctions and
(argCount isnt 0 or not @opts.lockZeroParamFunctions)
minArgs = 0
maxArgs = Infinity
if showButtons
if argCount < maxArgs
blockOpts.addButton = '\u21A0'
if argCount > minArgs
blockOpts.subtractButton = '\u219E'
@jsBlock node, depth, bounds, blockOpts
if not known
@jsSocketAndMark indentDepth, node.callee, depth + 1, 'Callee'
else if known.anyobj and node.callee.type is 'MemberExpression'
@jsSocketAndMark indentDepth, node.callee.object, depth + 1, 'CalleeObject', null, null, known?.fn?.objectDropdown
for argument, i in node.arguments
@jsSocketAndMark indentDepth, argument, depth + 1, 'Expression', null, null, known?.fn?.dropdown?[i]
if not known and argCount is 0 and not @opts.lockZeroParamFunctions
# Create a special socket that can be used for inserting the first parameter
# (NOTE: this socket may not be visible if the bounds start/end are the same)
position = {
line: node.callee.loc.end.line
column: node.callee.loc.end.column
}
string = @lines[position.line][position.column..].match(/^\s*\(/)[0]
position.column += string.length
endPosition = {
line: position.line
column: position.column
}
space = @lines[position.line][position.column..].match(/^(\s*)\)/)
if space?
endPosition.column += space[1].length
@addSocket {
bounds: {
start: position
end: endPosition
}
depth: depth + 1
dropdown: null
parseContext: 'Expression'
empty: ''
}
when 'MemberExpression'
@jsBlock node, depth, bounds
known = @lookupKnownName node
if not known
@jsSocketAndMark indentDepth, node.property, depth + 1
if not known or known.anyobj
@jsSocketAndMark indentDepth, node.object, depth + 1
when 'UpdateExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1
when 'VariableDeclaration'
@jsBlock node, depth, bounds
for declaration in node.declarations
@mark indentDepth, declaration, depth + 1
when 'VariableDeclarator'
@jsSocketAndMark indentDepth, node.id, depth, 'Lvalue'
if node.init?
@jsSocketAndMark indentDepth, node.init, depth, 'Expression'
when 'LogicalExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Operator' + node.operator
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Operator' + node.operator
when 'WhileStatement', 'DoWhileStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.body, depth + 1
@jsSocketAndMark indentDepth, node.test, depth + 1
when 'ObjectExpression'
@jsBlock node, depth, bounds
for property in node.properties
@jsSocketAndMark indentDepth, property.key, depth + 1
@jsSocketAndMark indentDepth, property.value, depth + 1
when 'SwitchStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.discriminant, depth + 1
for switchCase in node.cases
@mark indentDepth, switchCase, depth + 1, null
when 'SwitchCase'
if node.test?
@jsSocketAndMark indentDepth, node.test, depth + 1
if node.consequent.length > 0
bounds = @getCaseIndentBounds node
prefix = @getIndentPrefix(@getBounds(node), indentDepth)
indentDepth += prefix.length
@addIndent
bounds: bounds
depth: depth + 1
prefix: prefix
for statement in node.consequent
@mark indentDepth, statement, depth + 2
when 'TryStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.block, depth + 1, null
if node.handler?
if node.handler.guard?
@jsSocketAndMark indentDepth, node.handler.guard, depth + 1, null
if node.handler.param?
@jsSocketAndMark indentDepth, node.handler.param, depth + 1, null
@jsSocketAndMark indentDepth, node.handler.body, depth + 1, null
if node.finalizer?
@jsSocketAndMark indentDepth, node.finalizer, depth + 1, null
when 'ArrayExpression'
@jsBlock node, depth, bounds
for element in node.elements
if element?
@jsSocketAndMark indentDepth, element, depth + 1, null
when 'Literal'
null
else
console.log 'Unrecognized', node
jsBlock: (node, depth, bounds, buttons) ->
bounds ?= @getBounds node
@addBlock
bounds: bounds
depth: depth
color: @getColor node
shape: @getShape node
buttons: buttons
parseContext: 'program'
nodeContext: @getNodeContext node, bounds
getType: (node) ->
if node.type in ['BinaryExpression', 'LogicalExpression', 'UnaryExpression', 'UpdateExpression']
return 'Operator' + node.operator
else
return node.type
getNodeContext: (node, bounds, type) ->
type ?= @getType node
innerBounds = @getBounds node
prefix = helper.clipLines @lines, bounds.start, innerBounds.start
suffix = helper.clipLines @lines, innerBounds.end, bounds.end
return new parser.PreNodeContext type, prefix.length, suffix.length
jsSocketAndMark: (indentDepth, node, depth, type, bounds, classes, dropdown, empty) ->
unless node.type is 'BlockStatement'
bounds ?= @getBounds node
@addSocket
bounds: bounds
depth: depth
parseContext: type ? 'program'
dropdown: dropdown
empty: empty
@mark indentDepth, node, depth + 1, bounds
JavaScriptParser.parens = (leading, trailing, node, context) ->
# Don't attempt to paren wrap comments
return if '__comment__' is node.parseContext
if context?.type is 'socket' or
(not context? and helper.MOSTLY_VALUE is node.shape or helper.VALUE_ONLY is node.shape) or
SEMICOLON_EXCEPTIONS[node.nodeContext.type] or
node.type is 'document'
trailing trailing().replace(/;?\s*$/, '')
else
trailing trailing().replace(/;?\s*$/, ';')
while true
if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)?
leading leading().replace(/^\s*\(\s*/, '')
trailing trailing().replace(/\s*\)\s*$/, '')
else
break
unless context is null or context.type isnt 'socket' or
getPrecedence(context.parseContext) > getPrecedence(node.nodeContext.type)
console.log context.parseContext, node.nodeContext.type, getPrecedence(context.parseContext), getPrecedence(node.nodeContext.type)
leading '(' + leading()
trailing trailing() + ')'
JavaScriptParser.drop = (block, context, pred) ->
if context.parseContext is '__comment__'
return helper.FORBID
if context.type is 'socket'
if context.parseContext is 'Identifier'
return helper.FORBID
else if context.parseContext in ['Lvalue', 'ForEachLHS']
if block.nodeContext.type is 'ObjectExpression'
return helper.ENCOURAGE
else
return helper.FORBID
else if block.shape in [helper.VALUE_ONLY, helper.MOSTLY_VALUE, helper.ANY_DROP] or
context.parseContext is 'ForInit' or
(block.shape is helper.MOSTLY_BLOCK and
context.parseContext is 'ForUpdate')
return helper.ENCOURAGE
else if block.shape is helper.MOSTLY_BLOCK
return helper.DISCOURAGE
else if context.type in ['indent', 'document']
if block.shape in [helper.BLOCK_ONLY, helper.MOSTLY_BLOCK, helper.ANY_DROP] or
block.type is 'document'
return helper.ENCOURAGE
else if block.shape is helper.MOSTLY_VALUE
return helper.DISCOURAGE
return helper.DISCOURAGE
# Check to see if a "for" loop is standard, for beginner mode.
# We will simplify any loop of the form:
# ```
# for (var i = X; i < Y; i++) {
# // etc...
# }
# `
# Where "var" is optional and "i++" can be pre- or postincrement.
isStandardForLoop = (node) ->
unless node.init? and node.test? and node.update?
return false
# A standard for loop starts with "var a =" or "a = ".
# Determine the variable name so that we can check against it
# in the other two expression.
if node.init.type is 'VariableDeclaration'
variableName = node.init.declarations[0].id.name
else if node.init.type is 'AssignmentExpression' and
node.operator is '=' and
node.left.type is 'Identifier'
variableName = node.left.name
else
return false
return (node.test.type is 'BinaryExpression' and
node.test.operator is '<' and
node.test.left.type is 'Identifier' and
node.test.left.name is variableName and
node.test.right.type in ['Literal', 'Identifier'] and
node.update.type is 'UpdateExpression' and
node.update.operator is '++' and
node.update.argument.type is 'Identifier' and
node.update.argument.name is variableName)
JavaScriptParser.empty = "__"
JavaScriptParser.emptyIndent = ""
JavaScriptParser.startComment = '/*'
JavaScriptParser.endComment = '*/'
JavaScriptParser.startSingleLineComment = '//'
JavaScriptParser.getDefaultSelectionRange = (string) ->
start = 0; end = string.length
if string[0] is string[string.length - 1] and string[0] in ['"', '\'', '/']
start += 1; end -= 1
return {start, end}
module.exports = parser.wrapParser JavaScriptParser
| true | # Droplet JavaScript mode
#
# Copyright (c) 2015 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT License.
helper = require '../helper.coffee'
model = require '../model.coffee'
parser = require '../parser.coffee'
acorn = require '../../vendor/acorn'
STATEMENT_NODE_TYPES = [
'ExpressionStatement'
'ReturnStatement'
'BreakStatement'
'ThrowStatement'
]
NEVER_PAREN = 100
KNOWN_FUNCTIONS =
'alert' : {}
'prompt' : {}
'console.log' : {}
'*.toString' : {value: true}
'Math.abs' : {value: true}
'Math.acos' : {value: true}
'Math.asin' : {value: true}
'Math.atan' : {value: true}
'Math.atan2' : {value: true}
'Math.cos' : {value: true}
'Math.sin' : {value: true}
'Math.tan' : {value: true}
'Math.ceil' : {value: true}
'Math.floor' : {value: true}
'Math.round' : {value: true}
'Math.exp' : {value: true}
'Math.ln' : {value: true}
'Math.log10' : {value: true}
'Math.pow' : {value: true}
'Math.sqrt' : {value: true}
'Math.max' : {value: true}
'Math.min' : {value: true}
'Math.random' : {value: true}
CATEGORIES = {
functions: {color: 'class_body'}
returns: {color: 'statement'}
comments: {color: 'comment'}
arithmetic: {color: 'arithmetic'}
logic: {color: 'loop_logic'}
containers: {color: 'teal'}
assignments: {color: 'statement'}
loops: {color: 'control'}
conditionals: {color: 'control'}
value: {color: 'statement'}
command: {color: 'statement'}
errors: {color: '#f00'}
}
LOGICAL_OPERATORS = {
'==': true
'!=': true
'===': true
'!==': true
'<': true
'<=': true
'>': true
'>=': true
'in': true
'instanceof': true
'||': true
'&&': true
'!': true
}
NODE_CATEGORIES = {
'BinaryExpression': 'arithmetic' # actually, some are logic
'UnaryExpression': 'arithmetic' # actually, some are logic
'ConditionalExpression': 'arithmetic'
'LogicalExpression': 'logic'
'FunctionExpression': 'functions'
'FunctionDeclaration': 'functions'
'AssignmentExpression': 'assignments'
'UpdateExpression': 'assignments'
'VariableDeclaration': 'assignments'
'ReturnStatement': 'returns'
'IfStatement': 'conditionals'
'SwitchStatement': 'conditionals'
'ForStatement': 'loops'
'ForInStatement': 'loops'
'WhileStatement': 'loops'
'DoWhileStatement': 'loops'
'NewExpression': 'containers'
'ObjectExpression': 'containers'
'ArrayExpression': 'containers'
'MemberExpression': 'containers'
'BreakStatement': 'returns'
'ThrowStatement': 'returns'
'TryStatement': 'returns'
'CallExpression': 'command'
'SequenceExpression': 'command'
'Identifier': 'value'
}
# See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
# These numbers are "19 - x" so that the lowest numbers bind most tightly.
OPERATOR_PRECEDENCES = {
'++': 3
'--': 3
'!': 4
'~': 4
'*': 5
'/': 5
'%': 5
'+': 6
'-': 6
'<<': 7
'>>': 7
'>>>': 7
'<': 8
'>': 8
'>=': 8
'in': 8
'instanceof': 8
'==': 9
'!=': 9
'===': 9
'!==': 9
'&': 10
'^': 11
'|': 12
'&&': 13
'||': 14
}
PRECEDENCE = {
'AssignStatement': 16
'CallExpression': 2
'NewExpression': 2
'MemberExpression': 1
'Expression': NEVER_PAREN
'Lvalue': NEVER_PAREN
'IfTest': NEVER_PAREN
'ForEachLHS': NEVER_PAREN
'ForEachRHS': 10
'ForInit': NEVER_PAREN
'ForUpdate': 10
'Callee': NEVER_PAREN # Actually so?
'CalleeObject': NEVER_PAREN # Actually so?
}
for operator, precedence of OPERATOR_PRECEDENCES
PRECEDENCE['Operator' + operator] = precedence
getPrecedence = (type) ->
PRECEDENCE[type] ? 0
SEMICOLON_EXCEPTIONS = {
'ForStatement': true
'FunctionDeclaration': true
'IfStatement': true
'WhileStatement': true
'DoWhileStatement': true
'SwitchStatement': true
}
DEFAULT_INDENT_DEPTH = ' '
exports.JavaScriptParser = class JavaScriptParser extends parser.Parser
constructor: (@text, opts) ->
super
@opts.functions ?= KNOWN_FUNCTIONS
@opts.categories = helper.extend({}, CATEGORIES, @opts.categories)
@lines = @text.split '\n'
markRoot: ->
# Socket reparse of `{a: 1}` should be treated as ObjectExpression.
@text = "(#{@text})" if @text[0] == '{'
tree = acorn.parse(@text, {
locations: true
line: 0
allowReturnOutsideFunction: true
})
@mark 0, tree, 0, null
fullNameArray: (obj) ->
props = []
while obj.type is 'MemberExpression'
props.unshift obj.property.name
obj = obj.object
if obj.type is 'Identifier'
props.unshift obj.name
else
props.unshift '*'
props
lookupKnownName: (node) ->
if node.type is 'CallExpression' or node.type is 'NewExpression'
identifier = false
else if node.type is 'Identifier' or node.type is 'MemberExpression'
identifier = true
else
throw new Error
fname = @fullNameArray if identifier then node else node.callee
full = fname.join '.'
fn = @opts.functions[full]
if fn and ((identifier and fn.property) || (not identifier and not fn.property))
return name: full, anyobj: false, fn: @opts.functions[full]
last = fname[fname.length - 1]
if fname.length > 1 and (wildcard = '*.' + last) not of @opts.functions
wildcard = null # no match for '*.foo'
if not wildcard and (wildcard = '?.' + last) not of @opts.functions
wildcard = null # no match for '?.foo'
if wildcard isnt null
fn = @opts.functions[wildcard]
if fn and ((identifier and fn.property) || (not identifier and not fn.property))
return name: last, anyobj: true, fn: @opts.functions[wildcard]
return null
getAcceptsRule: (node) -> default: helper.NORMAL
getShape: (node) ->
if node.type is 'CallExpression' or node.type is 'NewExpression' or node.type is 'Identifier'
known = @lookupKnownName node
if not known or (known.fn.value and known.fn.command)
return helper.ANY_DROP
if known.fn.value
return helper.MOSTLY_VALUE
else
return helper.MOSTLY_BLOCK
else if node.type in ['ForStatement', 'FunctionDeclaration', 'IfStatement', 'WhileStatement', 'DoWhileStatement', 'SwitchStatement']
return helper.BLOCK_ONLY
else if node.type is 'AssignExpression'
return helper.MOSTLY_BLOCK
else if node.type.match(/Expression$/)?
return helper.MOSTLY_VALUE
else if node.type.match(/Declaration$/)?
return helper.BLOCK_ONLY
else if node.type.match(/Statement$/)?
return helper.MOSTLY_BLOCK
else
return helper.ANY_DROP
lookupCategory: (node) ->
switch node.type
when 'BinaryExpression', 'UnaryExpression'
if LOGICAL_OPERATORS.hasOwnProperty node.operator
category = 'logic'
else
category = 'arithmetic'
else
category = NODE_CATEGORIES[node.type]
return @opts.categories[category]
getColor: (node) ->
switch node.type
when 'ExpressionStatement'
return @getColor node.expression
when 'CallExpression', 'NewExpression', 'MemberExpression', 'Identifier'
known = @lookupKnownName node
if known
if known.fn.color
return known.fn.color
else if known.fn.value and not known.fn.command
return @opts.categories.value.color
category = @lookupCategory node
return category?.color or 'command'
getBounds: (node) ->
# If we are a statement, scan
# to find the semicolon
if node.type is 'BlockStatement'
bounds = {
start: {
line: node.loc.start.line
column: node.loc.start.column + 1
}
end: {
line: node.loc.end.line
column: node.loc.end.column - 1
}
}
bounds.start.column += (@lines[bounds.start.line][bounds.start.column..].match(/^\s*/) ? [''])[0].length
if @lines[bounds.end.line][...bounds.end.column].trim().length is 0
bounds.end.line -= 1
bounds.end.column = @lines[bounds.end.line].length
return bounds
else if node.type in STATEMENT_NODE_TYPES
line = @lines[node.loc.end.line]
semicolon = @lines[node.loc.end.line][node.loc.end.column - 1..].indexOf ';'
if semicolon >= 0
semicolonLength = @lines[node.loc.end.line][node.loc.end.column - 1..].match(/;\s*/)[0].length
return {
start: {
line: node.loc.start.line
column: node.loc.start.column
}
end: {
line: node.loc.end.line
column: node.loc.end.column + semicolon + semicolonLength - 1
}
}
return {
start: {
line: node.loc.start.line
column: node.loc.start.column
}
end: {
line: node.loc.end.line
column: node.loc.end.column
}
}
getCaseIndentBounds: (node) ->
bounds = {
start: @getBounds(node.consequent[0]).start
end: @getBounds(node.consequent[node.consequent.length - 1]).end
}
if @lines[bounds.start.line][...bounds.start.column].trim().length is 0
bounds.start.line -= 1
bounds.start.column = @lines[bounds.start.line].length
if @lines[bounds.end.line][...bounds.end.column].trim().length is 0
bounds.end.line -= 1
bounds.end.column = @lines[bounds.end.line].length
return bounds
getIndentPrefix: (bounds, indentDepth) ->
if bounds.end.line - bounds.start.line < 1
return DEFAULT_INDENT_DEPTH
else
line = @lines[bounds.start.line + 1]
return line[indentDepth...(line.length - line.trimLeft().length)]
isComment: (text) ->
text.match(/^\s*\/\/.*$/)?
parseComment: (text) ->
{
sockets: [[text.match(/^\s*\/\//)[0].length, text.length]]
}
handleButton: (text, button, oldBlock) ->
if button is 'add-button' and oldBlock.nodeContext.type is 'IfStatement'
# Parse to find the last "else" or "else if"
node = acorn.parse(text, {
locations: true
line: 0
allowReturnOutsideFunction: true
}).body[0]
currentElif = node
elseLocation = null
while true
if currentElif.type is 'IfStatement'
if currentElif.alternate?
elseLocation = {
line: currentElif.alternate.loc.start.line
column: currentElif.alternate.loc.start.column
}
currentElif = currentElif.alternate
else
elseLocation = null
break
else
break
if elseLocation?
lines = text.split('\n')
elseLocation = lines[...elseLocation.line].join('\n').length + elseLocation.column + 1
return text[...elseLocation].trimRight() + ' if (__) ' + text[elseLocation..].trimLeft() + ''' else {
__
}'''
else
return text + ''' else {
__
}'''
else if oldBlock.nodeContext.type is 'CallExpression'
# Parse to find the last "else" or "else if"
node = acorn.parse(text, {
line: 0
allowReturnOutsideFunction: true
}).body[0]
known = @lookupKnownName node.expression
argCount = node.expression.arguments.length
if button is 'add-button'
maxArgs = known?.fn.maxArgs
maxArgs ?= Infinity
if argCount >= maxArgs
return
if argCount
lastArgPosition = node.expression.arguments[argCount - 1].end
return text[...lastArgPosition].trimRight() + ', __' + text[lastArgPosition..].trimLeft()
else
lastArgPosition = node.expression.end - 1
return text[...lastArgPosition].trimRight() + '__' + text[lastArgPosition..].trimLeft()
else if button is 'subtract-button'
minArgs = known?.fn.minArgs
minArgs ?= 0
if argCount <= minArgs
return
if argCount > 0
lastArgPosition = node.expression.arguments[argCount - 1].end
if argCount is 1
newLastArgPosition = node.expression.arguments[0].start
else
newLastArgPosition = node.expression.arguments[argCount - 2].end
return text[...newLastArgPosition].trimRight() + text[lastArgPosition..].trimLeft()
mark: (indentDepth, node, depth, bounds) ->
switch node.type
when 'Program'
for statement in node.body
@mark indentDepth, statement, depth + 1, null
when 'Function'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
when 'SequenceExpression'
@jsBlock node, depth, bounds
for expression in node.expressions
@jsSocketAndMark indentDepth, expression, depth + 1, null
when 'FunctionDeclaration'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
@jsSocketAndMark indentDepth, node.id, depth + 1, 'Identifier', null
if node.params.length > 0
@addSocket {
bounds: {
start: @getBounds(node.params[0]).start
end: @getBounds(node.params[node.params.length - 1]).end
}
depth: depth + 1
parseContext: '__comment__'
dropdown: null
empty: ''
}
else unless @opts.lockZeroParamFunctions
nodeBoundsStart = @getBounds(node.id).end
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*\()(\s*)\)/)
if match?
@addSocket {
bounds: {
start: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length
}
end: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length + match[2].length
}
},
depth,
parseContext: '__comment__'
dropdown: null,
empty: ''
}
when 'FunctionExpression'
@jsBlock node, depth, bounds
@mark indentDepth, node.body, depth + 1, null
if node.id?
@jsSocketAndMark indentDepth, node.id, depth + 1, 'Identifier', null
if node.params.length > 0
@addSocket {
bounds: {
start: @getBounds(node.params[0]).start
end: @getBounds(node.params[node.params.length - 1]).end
}
depth: depth + 1
parseContext: '__comment__'
empty: ''
}
else unless @opts.lockZeroParamFunctions
if node.id?
nodeBoundsStart = @getBounds(node.id).end
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*\()(\s*)\)/)
else
nodeBoundsStart = @getBounds(node).start
match = @lines[nodeBoundsStart.line][nodeBoundsStart.column..].match(/^(\s*function\s*\()(\s*)\)/)
if match?
position =
@addSocket {
bounds: {
start: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length
}
end: {
line: nodeBoundsStart.line
column: nodeBoundsStart.column + match[1].length + match[2].length
}
},
depth,
precedence: 0,
dropdown: null,
parseContext: '__comment__'
empty: ''
}
when 'AssignmentExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Lvalue'
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Expression'
when 'ReturnStatement'
@jsBlock node, depth, bounds
if node.argument?
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'IfStatement', 'ConditionalExpression'
@jsBlock node, depth, bounds, {addButton: '+'}
@jsSocketAndMark indentDepth, node.test, depth + 1, 'Expression'
@jsSocketAndMark indentDepth, node.consequent, depth + 1, null
# As long as the else fits the "else-if" pattern,
# don't mark a new block. Instead, mark the condition
# and body and continue down the elseif chain.
currentElif = node.alternate
while currentElif?
if currentElif.type is 'IfStatement'
@jsSocketAndMark indentDepth, currentElif.test, depth + 1, null
@jsSocketAndMark indentDepth, currentElif.consequent, depth + 1, null
currentElif = currentElif.alternate
else
@jsSocketAndMark indentDepth, currentElif, depth + 1, 10
currentElif = null
when 'ForInStatement'
@jsBlock node, depth, bounds
if node.left?
@jsSocketAndMark indentDepth, node.left, depth + 1, 'ForEachLHS', null, ['foreach-lhs']
if node.right?
@jsSocketAndMark indentDepth, node.right, depth + 1, 'ForEachRHS'
@mark indentDepth, node.body, depth + 1
when 'BreakStatement', 'ContinueStatement'
@jsBlock node, depth, bounds
if node.label?
@jsSocketAndMark indentDepth, node.label, depth + 1, null
when 'ThrowStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'ForStatement'
@jsBlock node, depth, bounds
# If we are in beginner mode, check to see if the for loop
# matches the "standard" way, and if so only mark the loop
# limit (the "b" in "for (...;a < b;...)").
if @opts.categories.loops.beginner and isStandardForLoop(node)
@jsSocketAndMark indentDepth, node.test.right
else
if node.init?
@jsSocketAndMark indentDepth, node.init, depth + 1, 'ForInit', null, ['for-statement-init']
if node.test?
@jsSocketAndMark indentDepth, node.test, depth + 1, 'Expression'
if node.update?
@jsSocketAndMark indentDepth, node.update, depth + 1, 'ForUpdate', null, ['for-statement-update']
@mark indentDepth, node.body, depth + 1
when 'BlockStatement'
prefix = @getIndentPrefix(@getBounds(node), indentDepth)
indentDepth += prefix.length
@addIndent
bounds: @getBounds node
depth: depth
prefix: prefix
for statement in node.body
@mark indentDepth, statement, depth + 1, null
when 'BinaryExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Operator' + node.operator
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Operator' + node.operator
when 'UnaryExpression'
unless node.operator in ['-', '+'] and
node.argument.type in ['Identifier', 'Literal']
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1, null
when 'ExpressionStatement'
@mark indentDepth, node.expression, depth + 1, @getBounds node
when 'Identifier'
if node.name is '__'
block = @jsBlock node, depth, bounds
block.flagToRemove = true
else if @lookupKnownName node
@jsBlock node, depth, bounds
when 'CallExpression', 'NewExpression'
known = @lookupKnownName node
blockOpts = {}
argCount = node.arguments.length
if known?.fn
showButtons = known.fn.minArgs? or known.fn.maxArgs?
minArgs = known.fn.minArgs ? 0
maxArgs = known.fn.maxArgs ? Infinity
else
showButtons = @opts.paramButtonsForUnknownFunctions and
(argCount isnt 0 or not @opts.lockZeroParamFunctions)
minArgs = 0
maxArgs = Infinity
if showButtons
if argCount < maxArgs
blockOpts.addButton = '\u21A0'
if argCount > minArgs
blockOpts.subtractButton = '\u219E'
@jsBlock node, depth, bounds, blockOpts
if not known
@jsSocketAndMark indentDepth, node.callee, depth + 1, 'Callee'
else if known.anyobj and node.callee.type is 'MemberExpression'
@jsSocketAndMark indentDepth, node.callee.object, depth + 1, 'CalleeObject', null, null, known?.fn?.objectDropdown
for argument, i in node.arguments
@jsSocketAndMark indentDepth, argument, depth + 1, 'Expression', null, null, known?.fn?.dropdown?[i]
if not known and argCount is 0 and not @opts.lockZeroParamFunctions
# Create a special socket that can be used for inserting the first parameter
# (NOTE: this socket may not be visible if the bounds start/end are the same)
position = {
line: node.callee.loc.end.line
column: node.callee.loc.end.column
}
string = @lines[position.line][position.column..].match(/^\s*\(/)[0]
position.column += string.length
endPosition = {
line: position.line
column: position.column
}
space = @lines[position.line][position.column..].match(/^(\s*)\)/)
if space?
endPosition.column += space[1].length
@addSocket {
bounds: {
start: position
end: endPosition
}
depth: depth + 1
dropdown: null
parseContext: 'Expression'
empty: ''
}
when 'MemberExpression'
@jsBlock node, depth, bounds
known = @lookupKnownName node
if not known
@jsSocketAndMark indentDepth, node.property, depth + 1
if not known or known.anyobj
@jsSocketAndMark indentDepth, node.object, depth + 1
when 'UpdateExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.argument, depth + 1
when 'VariableDeclaration'
@jsBlock node, depth, bounds
for declaration in node.declarations
@mark indentDepth, declaration, depth + 1
when 'VariableDeclarator'
@jsSocketAndMark indentDepth, node.id, depth, 'Lvalue'
if node.init?
@jsSocketAndMark indentDepth, node.init, depth, 'Expression'
when 'LogicalExpression'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.left, depth + 1, 'Operator' + node.operator
@jsSocketAndMark indentDepth, node.right, depth + 1, 'Operator' + node.operator
when 'WhileStatement', 'DoWhileStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.body, depth + 1
@jsSocketAndMark indentDepth, node.test, depth + 1
when 'ObjectExpression'
@jsBlock node, depth, bounds
for property in node.properties
@jsSocketAndMark indentDepth, property.key, depth + 1
@jsSocketAndMark indentDepth, property.value, depth + 1
when 'SwitchStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.discriminant, depth + 1
for switchCase in node.cases
@mark indentDepth, switchCase, depth + 1, null
when 'SwitchCase'
if node.test?
@jsSocketAndMark indentDepth, node.test, depth + 1
if node.consequent.length > 0
bounds = @getCaseIndentBounds node
prefix = @getIndentPrefix(@getBounds(node), indentDepth)
indentDepth += prefix.length
@addIndent
bounds: bounds
depth: depth + 1
prefix: prefix
for statement in node.consequent
@mark indentDepth, statement, depth + 2
when 'TryStatement'
@jsBlock node, depth, bounds
@jsSocketAndMark indentDepth, node.block, depth + 1, null
if node.handler?
if node.handler.guard?
@jsSocketAndMark indentDepth, node.handler.guard, depth + 1, null
if node.handler.param?
@jsSocketAndMark indentDepth, node.handler.param, depth + 1, null
@jsSocketAndMark indentDepth, node.handler.body, depth + 1, null
if node.finalizer?
@jsSocketAndMark indentDepth, node.finalizer, depth + 1, null
when 'ArrayExpression'
@jsBlock node, depth, bounds
for element in node.elements
if element?
@jsSocketAndMark indentDepth, element, depth + 1, null
when 'Literal'
null
else
console.log 'Unrecognized', node
jsBlock: (node, depth, bounds, buttons) ->
bounds ?= @getBounds node
@addBlock
bounds: bounds
depth: depth
color: @getColor node
shape: @getShape node
buttons: buttons
parseContext: 'program'
nodeContext: @getNodeContext node, bounds
getType: (node) ->
if node.type in ['BinaryExpression', 'LogicalExpression', 'UnaryExpression', 'UpdateExpression']
return 'Operator' + node.operator
else
return node.type
getNodeContext: (node, bounds, type) ->
type ?= @getType node
innerBounds = @getBounds node
prefix = helper.clipLines @lines, bounds.start, innerBounds.start
suffix = helper.clipLines @lines, innerBounds.end, bounds.end
return new parser.PreNodeContext type, prefix.length, suffix.length
jsSocketAndMark: (indentDepth, node, depth, type, bounds, classes, dropdown, empty) ->
unless node.type is 'BlockStatement'
bounds ?= @getBounds node
@addSocket
bounds: bounds
depth: depth
parseContext: type ? 'program'
dropdown: dropdown
empty: empty
@mark indentDepth, node, depth + 1, bounds
JavaScriptParser.parens = (leading, trailing, node, context) ->
# Don't attempt to paren wrap comments
return if '__comment__' is node.parseContext
if context?.type is 'socket' or
(not context? and helper.MOSTLY_VALUE is node.shape or helper.VALUE_ONLY is node.shape) or
SEMICOLON_EXCEPTIONS[node.nodeContext.type] or
node.type is 'document'
trailing trailing().replace(/;?\s*$/, '')
else
trailing trailing().replace(/;?\s*$/, ';')
while true
if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)?
leading leading().replace(/^\s*\(\s*/, '')
trailing trailing().replace(/\s*\)\s*$/, '')
else
break
unless context is null or context.type isnt 'socket' or
getPrecedence(context.parseContext) > getPrecedence(node.nodeContext.type)
console.log context.parseContext, node.nodeContext.type, getPrecedence(context.parseContext), getPrecedence(node.nodeContext.type)
leading '(' + leading()
trailing trailing() + ')'
JavaScriptParser.drop = (block, context, pred) ->
if context.parseContext is '__comment__'
return helper.FORBID
if context.type is 'socket'
if context.parseContext is 'Identifier'
return helper.FORBID
else if context.parseContext in ['Lvalue', 'ForEachLHS']
if block.nodeContext.type is 'ObjectExpression'
return helper.ENCOURAGE
else
return helper.FORBID
else if block.shape in [helper.VALUE_ONLY, helper.MOSTLY_VALUE, helper.ANY_DROP] or
context.parseContext is 'ForInit' or
(block.shape is helper.MOSTLY_BLOCK and
context.parseContext is 'ForUpdate')
return helper.ENCOURAGE
else if block.shape is helper.MOSTLY_BLOCK
return helper.DISCOURAGE
else if context.type in ['indent', 'document']
if block.shape in [helper.BLOCK_ONLY, helper.MOSTLY_BLOCK, helper.ANY_DROP] or
block.type is 'document'
return helper.ENCOURAGE
else if block.shape is helper.MOSTLY_VALUE
return helper.DISCOURAGE
return helper.DISCOURAGE
# Check to see if a "for" loop is standard, for beginner mode.
# We will simplify any loop of the form:
# ```
# for (var i = X; i < Y; i++) {
# // etc...
# }
# `
# Where "var" is optional and "i++" can be pre- or postincrement.
isStandardForLoop = (node) ->
unless node.init? and node.test? and node.update?
return false
# A standard for loop starts with "var a =" or "a = ".
# Determine the variable name so that we can check against it
# in the other two expression.
if node.init.type is 'VariableDeclaration'
variableName = node.init.declarations[0].id.name
else if node.init.type is 'AssignmentExpression' and
node.operator is '=' and
node.left.type is 'Identifier'
variableName = node.left.name
else
return false
return (node.test.type is 'BinaryExpression' and
node.test.operator is '<' and
node.test.left.type is 'Identifier' and
node.test.left.name is variableName and
node.test.right.type in ['Literal', 'Identifier'] and
node.update.type is 'UpdateExpression' and
node.update.operator is '++' and
node.update.argument.type is 'Identifier' and
node.update.argument.name is variableName)
JavaScriptParser.empty = "__"
JavaScriptParser.emptyIndent = ""
JavaScriptParser.startComment = '/*'
JavaScriptParser.endComment = '*/'
JavaScriptParser.startSingleLineComment = '//'
JavaScriptParser.getDefaultSelectionRange = (string) ->
start = 0; end = string.length
if string[0] is string[string.length - 1] and string[0] in ['"', '\'', '/']
start += 1; end -= 1
return {start, end}
module.exports = parser.wrapParser JavaScriptParser
|
[
{
"context": "uest\n\t\t@project_id = \"3213213kl12j\"\n\t\t@user_id = \"2k3jlkjs9\"\n\t\t@messageContent = \"my message here\"\n\n\t",
"end": 611,
"score": 0.7727916240692139,
"start": 610,
"tag": "USERNAME",
"value": "2"
},
{
"context": "est\n\t\t@project_id = \"3213213kl12j\"\n\t\... | test/UnitTests/coffee/Chat/ChatHandlerTests.coffee | mickaobrien/web-sharelatex | 1 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Chat/ChatHandler"
expect = require("chai").expect
describe "ChatHandler", ->
beforeEach ->
@settings =
apis:
chat:
internal_url:"chat.sharelatex.env"
@request = sinon.stub()
@ChatHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"request": @request
@project_id = "3213213kl12j"
@user_id = "2k3jlkjs9"
@messageContent = "my message here"
describe "sending message", ->
beforeEach ->
@messageResponse =
message:"Details"
@request.callsArgWith(1, null, null, @messageResponse)
it "should post the data to the chat api", (done)->
@ChatHandler.sendMessage @project_id, @user_id, @messageContent, (err)=>
@opts =
method:"post"
json:
content:@messageContent
user_id:@user_id
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
@request.calledWith(@opts).should.equal true
done()
it "should return the message from the post", (done)->
@ChatHandler.sendMessage @project_id, @user_id, @messageContent, (err, returnedMessage)=>
returnedMessage.should.equal @messageResponse
done()
describe "get messages", ->
beforeEach ->
@returnedMessages = [{content:"hello world"}]
@request.callsArgWith(1, null, null, @returnedMessages)
@query = {}
it "should make get request for room to chat api", (done)->
@ChatHandler.getMessages @project_id, @query, (err)=>
@opts =
method:"get"
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
qs:{}
@request.calledWith(@opts).should.equal true
done()
it "should make get request for room to chat api with query string", (done)->
@query = {limit:5, before:12345, ignore:"this"}
@ChatHandler.getMessages @project_id, @query, (err)=>
@opts =
method:"get"
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
qs:
limit:5
before:12345
@request.calledWith(@opts).should.equal true
done()
it "should return the messages from the request", (done)->
@ChatHandler.getMessages @project_id, @query, (err, returnedMessages)=>
returnedMessages.should.equal @returnedMessages
done()
| 205808 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Chat/ChatHandler"
expect = require("chai").expect
describe "ChatHandler", ->
beforeEach ->
@settings =
apis:
chat:
internal_url:"chat.sharelatex.env"
@request = sinon.stub()
@ChatHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"request": @request
@project_id = "3213213kl12j"
@user_id = "2<PASSWORD>3jl<PASSWORD>js9"
@messageContent = "my message here"
describe "sending message", ->
beforeEach ->
@messageResponse =
message:"Details"
@request.callsArgWith(1, null, null, @messageResponse)
it "should post the data to the chat api", (done)->
@ChatHandler.sendMessage @project_id, @user_id, @messageContent, (err)=>
@opts =
method:"post"
json:
content:@messageContent
user_id:@user_id
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
@request.calledWith(@opts).should.equal true
done()
it "should return the message from the post", (done)->
@ChatHandler.sendMessage @project_id, @user_id, @messageContent, (err, returnedMessage)=>
returnedMessage.should.equal @messageResponse
done()
describe "get messages", ->
beforeEach ->
@returnedMessages = [{content:"hello world"}]
@request.callsArgWith(1, null, null, @returnedMessages)
@query = {}
it "should make get request for room to chat api", (done)->
@ChatHandler.getMessages @project_id, @query, (err)=>
@opts =
method:"get"
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
qs:{}
@request.calledWith(@opts).should.equal true
done()
it "should make get request for room to chat api with query string", (done)->
@query = {limit:5, before:12345, ignore:"this"}
@ChatHandler.getMessages @project_id, @query, (err)=>
@opts =
method:"get"
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
qs:
limit:5
before:12345
@request.calledWith(@opts).should.equal true
done()
it "should return the messages from the request", (done)->
@ChatHandler.getMessages @project_id, @query, (err, returnedMessages)=>
returnedMessages.should.equal @returnedMessages
done()
| true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Chat/ChatHandler"
expect = require("chai").expect
describe "ChatHandler", ->
beforeEach ->
@settings =
apis:
chat:
internal_url:"chat.sharelatex.env"
@request = sinon.stub()
@ChatHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"request": @request
@project_id = "3213213kl12j"
@user_id = "2PI:PASSWORD:<PASSWORD>END_PI3jlPI:PASSWORD:<PASSWORD>END_PIjs9"
@messageContent = "my message here"
describe "sending message", ->
beforeEach ->
@messageResponse =
message:"Details"
@request.callsArgWith(1, null, null, @messageResponse)
it "should post the data to the chat api", (done)->
@ChatHandler.sendMessage @project_id, @user_id, @messageContent, (err)=>
@opts =
method:"post"
json:
content:@messageContent
user_id:@user_id
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
@request.calledWith(@opts).should.equal true
done()
it "should return the message from the post", (done)->
@ChatHandler.sendMessage @project_id, @user_id, @messageContent, (err, returnedMessage)=>
returnedMessage.should.equal @messageResponse
done()
describe "get messages", ->
beforeEach ->
@returnedMessages = [{content:"hello world"}]
@request.callsArgWith(1, null, null, @returnedMessages)
@query = {}
it "should make get request for room to chat api", (done)->
@ChatHandler.getMessages @project_id, @query, (err)=>
@opts =
method:"get"
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
qs:{}
@request.calledWith(@opts).should.equal true
done()
it "should make get request for room to chat api with query string", (done)->
@query = {limit:5, before:12345, ignore:"this"}
@ChatHandler.getMessages @project_id, @query, (err)=>
@opts =
method:"get"
uri:"#{@settings.apis.chat.internal_url}/room/#{@project_id}/messages"
qs:
limit:5
before:12345
@request.calledWith(@opts).should.equal true
done()
it "should return the messages from the request", (done)->
@ChatHandler.getMessages @project_id, @query, (err, returnedMessages)=>
returnedMessages.should.equal @returnedMessages
done()
|
[
{
"context": "qual(\"<Asset><Attribute name=\\\"Name\\\" act=\\\"set\\\">Bobby</Attribute><Attribute name=\\\"Nickname\\\" act=\\\"set",
"end": 1068,
"score": 0.9044599533081055,
"start": 1063,
"tag": "NAME",
"value": "Bobby"
},
{
"context": "ttribute><Attribute name=\\\"Nickname\\\"... | tests/Backbone.sync.update.coffee | versionone/V1.Backbone | 1 | V1 = require('../V1.Backbone')
expect = require('chai').expect
deferred = require('JQDeferred')
describe "Updating model", ->
createPersister = (fn) ->
persisterOptions =
url: "/VersionOne/rest-1.v1/Data"
post: ->
fn.apply(this, arguments)
deferred().resolve()
new V1.Backbone.RestPersister(persisterOptions)
getModel = (persister) ->
V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [V1.Backbone.alias("Name").as("name"), "Nickname", "Email"]
persister: persister
it "should try to post to the correct url", (done) ->
persister = createPersister (url, data) ->
expect(url).to.equal("/VersionOne/rest-1.v1/Data/Member/1234")
Member = getModel(persister)
model = new Member()
model.id = "Member:1234"
model.save().done(done)
it "should send all the properties on save", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal("<Asset><Attribute name=\"Name\" act=\"set\">Bobby</Attribute><Attribute name=\"Nickname\" act=\"set\">Bob</Attribute><Attribute name=\"Email\" act=\"set\">who@where.com</Attribute></Asset>")
Member = getModel(persister)
model = new Member()
model.id = "Member:1234"
model.set("name", "Bobby")
model.set("Nickname", "Bob")
model.set("Email", "who@where.com")
model.save().done(done)
it "should send changed properties on patch", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Name" act="set">Robert</Attribute></Asset>')
Member = getModel(persister)
model = new Member({_cid:"Member:1234", name:"Bobby", Nickname: "Bob"})
model.save({"name": "Robert"}, {patch: true}).done(done)
it "should send empty string properties on patch", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Email" act="set"></Attribute></Asset>')
Member = getModel(persister)
model = new Member({_cid:"Member:1234", name:"Bobby", Nickname: "Bob", Email: "who@where.com"})
model.save({Email: ""}, {patch: true}).done(done)
it "should send empty string properties on save", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Name" act="set">Bobby</Attribute><Attribute name="Nickname" act="set">Bob</Attribute><Attribute name="Email" act="set"></Attribute></Asset>')
Member = getModel(persister)
model = new Member()
model.id = "Member:1234";
model.set("name","Bobby");
model.set("Nickname", "Bob");
model.set("Email", undefined);
model.save().done(done)
| 164860 | V1 = require('../V1.Backbone')
expect = require('chai').expect
deferred = require('JQDeferred')
describe "Updating model", ->
createPersister = (fn) ->
persisterOptions =
url: "/VersionOne/rest-1.v1/Data"
post: ->
fn.apply(this, arguments)
deferred().resolve()
new V1.Backbone.RestPersister(persisterOptions)
getModel = (persister) ->
V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [V1.Backbone.alias("Name").as("name"), "Nickname", "Email"]
persister: persister
it "should try to post to the correct url", (done) ->
persister = createPersister (url, data) ->
expect(url).to.equal("/VersionOne/rest-1.v1/Data/Member/1234")
Member = getModel(persister)
model = new Member()
model.id = "Member:1234"
model.save().done(done)
it "should send all the properties on save", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal("<Asset><Attribute name=\"Name\" act=\"set\"><NAME></Attribute><Attribute name=\"Nickname\" act=\"set\"><NAME></Attribute><Attribute name=\"Email\" act=\"set\"><EMAIL></Attribute></Asset>")
Member = getModel(persister)
model = new Member()
model.id = "Member:1234"
model.set("name", "<NAME>")
model.set("Nickname", "<NAME>")
model.set("Email", "<EMAIL>")
model.save().done(done)
it "should send changed properties on patch", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Name" act="set"><NAME></Attribute></Asset>')
Member = getModel(persister)
model = new Member({_cid:"Member:1234", name:"<NAME>", Nickname: "<NAME>"})
model.save({"name": "<NAME>"}, {patch: true}).done(done)
it "should send empty string properties on patch", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Email" act="set"></Attribute></Asset>')
Member = getModel(persister)
model = new Member({_cid:"Member:1234", name:"<NAME>", Nickname: "<NAME>", Email: "<EMAIL>"})
model.save({Email: ""}, {patch: true}).done(done)
it "should send empty string properties on save", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Name" act="set"><NAME></Attribute><Attribute name="Nickname" act="set"><NAME></Attribute><Attribute name="Email" act="set"></Attribute></Asset>')
Member = getModel(persister)
model = new Member()
model.id = "Member:1234";
model.set("name","<NAME>");
model.set("Nickname", "<NAME>");
model.set("Email", undefined);
model.save().done(done)
| true | V1 = require('../V1.Backbone')
expect = require('chai').expect
deferred = require('JQDeferred')
describe "Updating model", ->
createPersister = (fn) ->
persisterOptions =
url: "/VersionOne/rest-1.v1/Data"
post: ->
fn.apply(this, arguments)
deferred().resolve()
new V1.Backbone.RestPersister(persisterOptions)
getModel = (persister) ->
V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [V1.Backbone.alias("Name").as("name"), "Nickname", "Email"]
persister: persister
it "should try to post to the correct url", (done) ->
persister = createPersister (url, data) ->
expect(url).to.equal("/VersionOne/rest-1.v1/Data/Member/1234")
Member = getModel(persister)
model = new Member()
model.id = "Member:1234"
model.save().done(done)
it "should send all the properties on save", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal("<Asset><Attribute name=\"Name\" act=\"set\">PI:NAME:<NAME>END_PI</Attribute><Attribute name=\"Nickname\" act=\"set\">PI:NAME:<NAME>END_PI</Attribute><Attribute name=\"Email\" act=\"set\">PI:EMAIL:<EMAIL>END_PI</Attribute></Asset>")
Member = getModel(persister)
model = new Member()
model.id = "Member:1234"
model.set("name", "PI:NAME:<NAME>END_PI")
model.set("Nickname", "PI:NAME:<NAME>END_PI")
model.set("Email", "PI:EMAIL:<EMAIL>END_PI")
model.save().done(done)
it "should send changed properties on patch", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Name" act="set">PI:NAME:<NAME>END_PI</Attribute></Asset>')
Member = getModel(persister)
model = new Member({_cid:"Member:1234", name:"PI:NAME:<NAME>END_PI", Nickname: "PI:NAME:<NAME>END_PI"})
model.save({"name": "PI:NAME:<NAME>END_PI"}, {patch: true}).done(done)
it "should send empty string properties on patch", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Email" act="set"></Attribute></Asset>')
Member = getModel(persister)
model = new Member({_cid:"Member:1234", name:"PI:NAME:<NAME>END_PI", Nickname: "PI:NAME:<NAME>END_PI", Email: "PI:EMAIL:<EMAIL>END_PI"})
model.save({Email: ""}, {patch: true}).done(done)
it "should send empty string properties on save", (done) ->
persister = createPersister (url, data) ->
expect(data).to.equal('<Asset><Attribute name="Name" act="set">PI:NAME:<NAME>END_PI</Attribute><Attribute name="Nickname" act="set">PI:NAME:<NAME>END_PI</Attribute><Attribute name="Email" act="set"></Attribute></Asset>')
Member = getModel(persister)
model = new Member()
model.id = "Member:1234";
model.set("name","PI:NAME:<NAME>END_PI");
model.set("Nickname", "PI:NAME:<NAME>END_PI");
model.set("Email", undefined);
model.save().done(done)
|
[
{
"context": "t: null\n standalone: true\n annotation_key: 'value'\n focus: true\n\n componentWillReceiveProps: ->",
"end": 1422,
"score": 0.5382892489433289,
"start": 1417,
"tag": "KEY",
"value": "value"
}
] | app/assets/javascripts/components/transcribe/tools/text-area-tool/index_old.cjsx | ogugugugugua/PRED-Crowdsourcing-2020 | 88 | # @cjsx React.DOM
React = require 'react'
Draggable = require '../../../../lib/draggable'
DoneButton = require './done-button'
PrevButton = require './prev-button'
TextAreaTool = React.createClass
displayName: 'TextAreaTool'
handleInitStart: (e) ->
@setState preventDrag: false
if e.target.nodeName is "INPUT" or e.target.nodeName is "TEXTAREA"
@setState preventDrag: true
@setState
xClick: e.pageX - $('.transcribe-tool').offset().left
yClick: e.pageY - $('.transcribe-tool').offset().top
handleInitDrag: (e, delta) ->
return if @state.preventDrag # not too happy about this one
dx = e.pageX - @state.xClick - window.scrollX
dy = e.pageY - @state.yClick # + window.scrollY
@setState
dx: dx
dy: dy #, =>
dragged: true
getInitialState: ->
# compute component location
{x,y} = @getPosition @props.subject.data
dx: x
dy: y
viewerSize: @props.viewerSize
annotation:
value: ''
getPosition: (data) ->
switch data.toolName
when 'rectangleTool'
x = data.x
y = parseFloat(data.y) + parseFloat(data.height)
when 'textRowTool'
x = data.x
y = data.yLower
else # default for pointTool
x = data.x
y = data.y
return {x,y}
getDefaultProps: ->
annotation: {}
task: null
subject: null
standalone: true
annotation_key: 'value'
focus: true
componentWillReceiveProps: ->
@refs.input0.getDOMNode().focus() if @props.focus
{x,y} = @getPosition @props.subject.data
@setState
dx: x
dy: y
annotation: @props.annotation
, => @forceUpdate() # updates component position on new subject
componentWillMount: ->
# currently does nothing
componentWillUnmount: ->
if @props.task.tool_config.suggest == 'common'
el = $(@refs.input0.getDOMNode())
el.autocomplete 'destroy'
componentDidMount: ->
@updatePosition()
@refs.input0.getDOMNode().focus() if @props.focus
if @props.task.tool_config.suggest == 'common'
el = $(@refs.input0.getDOMNode())
el.autocomplete
source: (request, response) =>
$.ajax
url: "/classifications/terms/#{@props.workflow.id}/#{@props.key}"
dataType: "json"
data:
q: request.term
success: ( data ) =>
response( data )
minLength: 3
# Expects size hash with:
# w: [viewer width]
# h: [viewer height]
# scale:
# horizontal: [horiz scaling of image to fit within above vals]
# vertical: [vert scaling of image..]
onViewerResize: (size) ->
@setState
viewerSize: size
@updatePosition()
updatePosition: ->
if @state.viewerSize? && ! @state.dragged
dy = (parseFloat(@props.subject.data.y) + parseFloat(@props.subject.data.height)) * @state.viewerSize.scale.vertical
@setState
dx: @props.subject.data.x * @state.viewerSize.scale.horizontal
dy: dy
commitAnnotation: ->
@props.onComplete @state.annotation
handleChange: (e) ->
@state.annotation[@props.annotation_key] = e.target.value
@forceUpdate()
handleKeyPress: (e) ->
if [13].indexOf(e.keyCode) >= 0 # ENTER
@commitAnnotation()
e.preventDefault()
render: ->
# get component position
style =
left: "#{@state.dx*@props.scale.horizontal}px"
top: "#{@state.dy*@props.scale.vertical}px"
val = @state.annotation[@props.annotation_key] ? ''
unless @props.standalone
label = @props.label ? ''
else
label = @props.task.instruction
# create component input field(s)
tool_content =
<div className="input-field active">
<label>{label}</label>
<textarea
ref="input0"
data-task_key={@props.task.key}
onChange={@handleChange}
value={val}
placeholder={"This is some placeholder text."}
/>
</div>
if @props.standalone # 'standalone' true if component handles own mouse events
tool_content =
<Draggable
onStart={@handleInitStart}
onDrag={@handleInitDrag}
onEnd={@handleInitRelease}
ref="inputWrapper0"
x={@state.dx*@props.scale.horizontal}
y={@state.dy*@props.scale.vertical}>
<div className="transcribe-tool" style={style}>
<div className="left">
{tool_content}
</div>
<div className="right">
<PrevButton onClick={=> console.log "Prev button clicked!"} />
<DoneButton onClick={@commitAnnotation} />
</div>
</div>
</Draggable>
else return tool_content # render input fields without Draggable
module.exports = TextAreaTool
| 75080 | # @cjsx React.DOM
React = require 'react'
Draggable = require '../../../../lib/draggable'
DoneButton = require './done-button'
PrevButton = require './prev-button'
TextAreaTool = React.createClass
displayName: 'TextAreaTool'
handleInitStart: (e) ->
@setState preventDrag: false
if e.target.nodeName is "INPUT" or e.target.nodeName is "TEXTAREA"
@setState preventDrag: true
@setState
xClick: e.pageX - $('.transcribe-tool').offset().left
yClick: e.pageY - $('.transcribe-tool').offset().top
handleInitDrag: (e, delta) ->
return if @state.preventDrag # not too happy about this one
dx = e.pageX - @state.xClick - window.scrollX
dy = e.pageY - @state.yClick # + window.scrollY
@setState
dx: dx
dy: dy #, =>
dragged: true
getInitialState: ->
# compute component location
{x,y} = @getPosition @props.subject.data
dx: x
dy: y
viewerSize: @props.viewerSize
annotation:
value: ''
getPosition: (data) ->
switch data.toolName
when 'rectangleTool'
x = data.x
y = parseFloat(data.y) + parseFloat(data.height)
when 'textRowTool'
x = data.x
y = data.yLower
else # default for pointTool
x = data.x
y = data.y
return {x,y}
getDefaultProps: ->
annotation: {}
task: null
subject: null
standalone: true
annotation_key: '<KEY>'
focus: true
componentWillReceiveProps: ->
@refs.input0.getDOMNode().focus() if @props.focus
{x,y} = @getPosition @props.subject.data
@setState
dx: x
dy: y
annotation: @props.annotation
, => @forceUpdate() # updates component position on new subject
componentWillMount: ->
# currently does nothing
componentWillUnmount: ->
if @props.task.tool_config.suggest == 'common'
el = $(@refs.input0.getDOMNode())
el.autocomplete 'destroy'
componentDidMount: ->
@updatePosition()
@refs.input0.getDOMNode().focus() if @props.focus
if @props.task.tool_config.suggest == 'common'
el = $(@refs.input0.getDOMNode())
el.autocomplete
source: (request, response) =>
$.ajax
url: "/classifications/terms/#{@props.workflow.id}/#{@props.key}"
dataType: "json"
data:
q: request.term
success: ( data ) =>
response( data )
minLength: 3
# Expects size hash with:
# w: [viewer width]
# h: [viewer height]
# scale:
# horizontal: [horiz scaling of image to fit within above vals]
# vertical: [vert scaling of image..]
onViewerResize: (size) ->
@setState
viewerSize: size
@updatePosition()
updatePosition: ->
if @state.viewerSize? && ! @state.dragged
dy = (parseFloat(@props.subject.data.y) + parseFloat(@props.subject.data.height)) * @state.viewerSize.scale.vertical
@setState
dx: @props.subject.data.x * @state.viewerSize.scale.horizontal
dy: dy
commitAnnotation: ->
@props.onComplete @state.annotation
handleChange: (e) ->
@state.annotation[@props.annotation_key] = e.target.value
@forceUpdate()
handleKeyPress: (e) ->
if [13].indexOf(e.keyCode) >= 0 # ENTER
@commitAnnotation()
e.preventDefault()
render: ->
# get component position
style =
left: "#{@state.dx*@props.scale.horizontal}px"
top: "#{@state.dy*@props.scale.vertical}px"
val = @state.annotation[@props.annotation_key] ? ''
unless @props.standalone
label = @props.label ? ''
else
label = @props.task.instruction
# create component input field(s)
tool_content =
<div className="input-field active">
<label>{label}</label>
<textarea
ref="input0"
data-task_key={@props.task.key}
onChange={@handleChange}
value={val}
placeholder={"This is some placeholder text."}
/>
</div>
if @props.standalone # 'standalone' true if component handles own mouse events
tool_content =
<Draggable
onStart={@handleInitStart}
onDrag={@handleInitDrag}
onEnd={@handleInitRelease}
ref="inputWrapper0"
x={@state.dx*@props.scale.horizontal}
y={@state.dy*@props.scale.vertical}>
<div className="transcribe-tool" style={style}>
<div className="left">
{tool_content}
</div>
<div className="right">
<PrevButton onClick={=> console.log "Prev button clicked!"} />
<DoneButton onClick={@commitAnnotation} />
</div>
</div>
</Draggable>
else return tool_content # render input fields without Draggable
module.exports = TextAreaTool
| true | # @cjsx React.DOM
React = require 'react'
Draggable = require '../../../../lib/draggable'
DoneButton = require './done-button'
PrevButton = require './prev-button'
TextAreaTool = React.createClass
displayName: 'TextAreaTool'
handleInitStart: (e) ->
@setState preventDrag: false
if e.target.nodeName is "INPUT" or e.target.nodeName is "TEXTAREA"
@setState preventDrag: true
@setState
xClick: e.pageX - $('.transcribe-tool').offset().left
yClick: e.pageY - $('.transcribe-tool').offset().top
handleInitDrag: (e, delta) ->
return if @state.preventDrag # not too happy about this one
dx = e.pageX - @state.xClick - window.scrollX
dy = e.pageY - @state.yClick # + window.scrollY
@setState
dx: dx
dy: dy #, =>
dragged: true
getInitialState: ->
# compute component location
{x,y} = @getPosition @props.subject.data
dx: x
dy: y
viewerSize: @props.viewerSize
annotation:
value: ''
getPosition: (data) ->
switch data.toolName
when 'rectangleTool'
x = data.x
y = parseFloat(data.y) + parseFloat(data.height)
when 'textRowTool'
x = data.x
y = data.yLower
else # default for pointTool
x = data.x
y = data.y
return {x,y}
getDefaultProps: ->
annotation: {}
task: null
subject: null
standalone: true
annotation_key: 'PI:KEY:<KEY>END_PI'
focus: true
componentWillReceiveProps: ->
@refs.input0.getDOMNode().focus() if @props.focus
{x,y} = @getPosition @props.subject.data
@setState
dx: x
dy: y
annotation: @props.annotation
, => @forceUpdate() # updates component position on new subject
componentWillMount: ->
# currently does nothing
componentWillUnmount: ->
if @props.task.tool_config.suggest == 'common'
el = $(@refs.input0.getDOMNode())
el.autocomplete 'destroy'
componentDidMount: ->
@updatePosition()
@refs.input0.getDOMNode().focus() if @props.focus
if @props.task.tool_config.suggest == 'common'
el = $(@refs.input0.getDOMNode())
el.autocomplete
source: (request, response) =>
$.ajax
url: "/classifications/terms/#{@props.workflow.id}/#{@props.key}"
dataType: "json"
data:
q: request.term
success: ( data ) =>
response( data )
minLength: 3
# Expects size hash with:
# w: [viewer width]
# h: [viewer height]
# scale:
# horizontal: [horiz scaling of image to fit within above vals]
# vertical: [vert scaling of image..]
onViewerResize: (size) ->
@setState
viewerSize: size
@updatePosition()
updatePosition: ->
if @state.viewerSize? && ! @state.dragged
dy = (parseFloat(@props.subject.data.y) + parseFloat(@props.subject.data.height)) * @state.viewerSize.scale.vertical
@setState
dx: @props.subject.data.x * @state.viewerSize.scale.horizontal
dy: dy
commitAnnotation: ->
@props.onComplete @state.annotation
handleChange: (e) ->
@state.annotation[@props.annotation_key] = e.target.value
@forceUpdate()
handleKeyPress: (e) ->
if [13].indexOf(e.keyCode) >= 0 # ENTER
@commitAnnotation()
e.preventDefault()
render: ->
# get component position
style =
left: "#{@state.dx*@props.scale.horizontal}px"
top: "#{@state.dy*@props.scale.vertical}px"
val = @state.annotation[@props.annotation_key] ? ''
unless @props.standalone
label = @props.label ? ''
else
label = @props.task.instruction
# create component input field(s)
tool_content =
<div className="input-field active">
<label>{label}</label>
<textarea
ref="input0"
data-task_key={@props.task.key}
onChange={@handleChange}
value={val}
placeholder={"This is some placeholder text."}
/>
</div>
if @props.standalone # 'standalone' true if component handles own mouse events
tool_content =
<Draggable
onStart={@handleInitStart}
onDrag={@handleInitDrag}
onEnd={@handleInitRelease}
ref="inputWrapper0"
x={@state.dx*@props.scale.horizontal}
y={@state.dy*@props.scale.vertical}>
<div className="transcribe-tool" style={style}>
<div className="left">
{tool_content}
</div>
<div className="right">
<PrevButton onClick={=> console.log "Prev button clicked!"} />
<DoneButton onClick={@commitAnnotation} />
</div>
</div>
</Draggable>
else return tool_content # render input fields without Draggable
module.exports = TextAreaTool
|
[
{
"context": " =\n '<!DOCTYPE html>' + # doctype\n '<h1>Willow ' + # Tag containing chars\n '<EM ID=h1 CLA",
"end": 252,
"score": 0.9978001117706299,
"start": 246,
"tag": "NAME",
"value": "Willow"
},
{
"context": " html']\n ['start', 'h1', {}]\n ['text', 'W... | test/parse.mocha.coffee | kantele/k-html-util | 86 | expect = require 'expect.js'
html = require '../lib'
describe 'parse', ->
it 'should parse with no handlers', ->
html.parse '<p id=stuff>Heyo</p>'
it 'should parse basic HTML', ->
s =
'<!DOCTYPE html>' + # doctype
'<h1>Willow ' + # Tag containing chars
'<EM ID=h1 CLASS=head>' + # Nested tag, attributes, uppercase
'tree' +
'</em>' +
'</h1>' +
'<script>' + # Scripts should be passed through as rawText
'<b></b>' +
'</script>' +
'<!-- here is a comment\n cool beans!-->\n\t ' +
'<b><b><b></b></b></b>' + # Nested tags, no contents
'<form action= \'javascript:alert("cows")\' >' + # Single quote attr
'<input type = "checkbox" disabled data-stuff=hey>' + # double quotes attr, empty attr, and data attribute
'<input type="submit" value=>' + # While invalid HTML, value should be an empty string
'</FORM>' + # Uppercase end
'<img src=/img/stuff.png alt=""/>' + # Don't choke on void element with slash
'<p>Flowers ' + # Trailing whitespace on implicitly closed tag
'<p>Flight</p>\n' + # Explicitly closed tag
' \t<p>Fight</p>\t \n' + # New line and leading whitespace
'<p>Blight\nSight</p> <p / >' # Whitespace between tags
expected = [
['other', '!DOCTYPE html']
['start', 'h1', {}]
['text', 'Willow ']
['start', 'em', { id: 'h1', 'class': 'head' }]
['text', 'tree']
['end', 'em']
['end', 'h1']
['start', 'script', {}]
['text', '<b></b>']
['end', 'script']
['comment', ' here is a comment\n cool beans!']
['text', '\n\t ']
['start', 'b', {}]
['start', 'b', {}]
['start', 'b', {}]
['end', 'b']
['end', 'b']
['end', 'b']
['start', 'form', {action: 'javascript:alert("cows")'}]
['start', 'input', {type: 'checkbox', disabled: null, 'data-stuff': 'hey'}]
['start', 'input', {type: 'submit', value: ''}]
['end', 'form']
['start', 'img', {src: '/img/stuff.png', alt: ''}]
['start', 'p', {}]
['text', 'Flowers ']
['start', 'p', {}]
['text', 'Flight']
['end', 'p']
['text', '\n \t']
['start', 'p', {}]
['text', 'Fight']
['end', 'p']
['text', '\t \n']
['start', 'p', {}]
['text', 'Blight\nSight']
['end', 'p']
['text', ' ']
['start', 'p', {}]
]
stack = []
html.parse s,
start: (tag, tagName, attrs) -> stack.push ['start', tagName, attrs]
end: (tag, tagName) -> stack.push ['end', tagName]
text: (text) -> stack.push ['text', text]
comment: (tag, data) -> stack.push ['comment', data]
other: (tag, data) -> stack.push ['other', data]
for item, index in expected
expect(stack[index]).to.eql item
expect(stack.length).to.equal expected.length
| 159896 | expect = require 'expect.js'
html = require '../lib'
describe 'parse', ->
it 'should parse with no handlers', ->
html.parse '<p id=stuff>Heyo</p>'
it 'should parse basic HTML', ->
s =
'<!DOCTYPE html>' + # doctype
'<h1><NAME> ' + # Tag containing chars
'<EM ID=h1 CLASS=head>' + # Nested tag, attributes, uppercase
'tree' +
'</em>' +
'</h1>' +
'<script>' + # Scripts should be passed through as rawText
'<b></b>' +
'</script>' +
'<!-- here is a comment\n cool beans!-->\n\t ' +
'<b><b><b></b></b></b>' + # Nested tags, no contents
'<form action= \'javascript:alert("cows")\' >' + # Single quote attr
'<input type = "checkbox" disabled data-stuff=hey>' + # double quotes attr, empty attr, and data attribute
'<input type="submit" value=>' + # While invalid HTML, value should be an empty string
'</FORM>' + # Uppercase end
'<img src=/img/stuff.png alt=""/>' + # Don't choke on void element with slash
'<p>Flowers ' + # Trailing whitespace on implicitly closed tag
'<p>Flight</p>\n' + # Explicitly closed tag
' \t<p>Fight</p>\t \n' + # New line and leading whitespace
'<p>Blight\nSight</p> <p / >' # Whitespace between tags
expected = [
['other', '!DOCTYPE html']
['start', 'h1', {}]
['text', '<NAME> ']
['start', 'em', { id: 'h1', 'class': 'head' }]
['text', 'tree']
['end', 'em']
['end', 'h1']
['start', 'script', {}]
['text', '<b></b>']
['end', 'script']
['comment', ' here is a comment\n cool beans!']
['text', '\n\t ']
['start', 'b', {}]
['start', 'b', {}]
['start', 'b', {}]
['end', 'b']
['end', 'b']
['end', 'b']
['start', 'form', {action: 'javascript:alert("cows")'}]
['start', 'input', {type: 'checkbox', disabled: null, 'data-stuff': 'hey'}]
['start', 'input', {type: 'submit', value: ''}]
['end', 'form']
['start', 'img', {src: '/img/stuff.png', alt: ''}]
['start', 'p', {}]
['text', 'Flowers ']
['start', 'p', {}]
['text', 'Flight']
['end', 'p']
['text', '\n \t']
['start', 'p', {}]
['text', 'Fight']
['end', 'p']
['text', '\t \n']
['start', 'p', {}]
['text', 'Blight\nSight']
['end', 'p']
['text', ' ']
['start', 'p', {}]
]
stack = []
html.parse s,
start: (tag, tagName, attrs) -> stack.push ['start', tagName, attrs]
end: (tag, tagName) -> stack.push ['end', tagName]
text: (text) -> stack.push ['text', text]
comment: (tag, data) -> stack.push ['comment', data]
other: (tag, data) -> stack.push ['other', data]
for item, index in expected
expect(stack[index]).to.eql item
expect(stack.length).to.equal expected.length
| true | expect = require 'expect.js'
html = require '../lib'
describe 'parse', ->
it 'should parse with no handlers', ->
html.parse '<p id=stuff>Heyo</p>'
it 'should parse basic HTML', ->
s =
'<!DOCTYPE html>' + # doctype
'<h1>PI:NAME:<NAME>END_PI ' + # Tag containing chars
'<EM ID=h1 CLASS=head>' + # Nested tag, attributes, uppercase
'tree' +
'</em>' +
'</h1>' +
'<script>' + # Scripts should be passed through as rawText
'<b></b>' +
'</script>' +
'<!-- here is a comment\n cool beans!-->\n\t ' +
'<b><b><b></b></b></b>' + # Nested tags, no contents
'<form action= \'javascript:alert("cows")\' >' + # Single quote attr
'<input type = "checkbox" disabled data-stuff=hey>' + # double quotes attr, empty attr, and data attribute
'<input type="submit" value=>' + # While invalid HTML, value should be an empty string
'</FORM>' + # Uppercase end
'<img src=/img/stuff.png alt=""/>' + # Don't choke on void element with slash
'<p>Flowers ' + # Trailing whitespace on implicitly closed tag
'<p>Flight</p>\n' + # Explicitly closed tag
' \t<p>Fight</p>\t \n' + # New line and leading whitespace
'<p>Blight\nSight</p> <p / >' # Whitespace between tags
expected = [
['other', '!DOCTYPE html']
['start', 'h1', {}]
['text', 'PI:NAME:<NAME>END_PI ']
['start', 'em', { id: 'h1', 'class': 'head' }]
['text', 'tree']
['end', 'em']
['end', 'h1']
['start', 'script', {}]
['text', '<b></b>']
['end', 'script']
['comment', ' here is a comment\n cool beans!']
['text', '\n\t ']
['start', 'b', {}]
['start', 'b', {}]
['start', 'b', {}]
['end', 'b']
['end', 'b']
['end', 'b']
['start', 'form', {action: 'javascript:alert("cows")'}]
['start', 'input', {type: 'checkbox', disabled: null, 'data-stuff': 'hey'}]
['start', 'input', {type: 'submit', value: ''}]
['end', 'form']
['start', 'img', {src: '/img/stuff.png', alt: ''}]
['start', 'p', {}]
['text', 'Flowers ']
['start', 'p', {}]
['text', 'Flight']
['end', 'p']
['text', '\n \t']
['start', 'p', {}]
['text', 'Fight']
['end', 'p']
['text', '\t \n']
['start', 'p', {}]
['text', 'Blight\nSight']
['end', 'p']
['text', ' ']
['start', 'p', {}]
]
stack = []
html.parse s,
start: (tag, tagName, attrs) -> stack.push ['start', tagName, attrs]
end: (tag, tagName) -> stack.push ['end', tagName]
text: (text) -> stack.push ['text', text]
comment: (tag, data) -> stack.push ['comment', data]
other: (tag, data) -> stack.push ['other', data]
for item, index in expected
expect(stack[index]).to.eql item
expect(stack.length).to.equal expected.length
|
[
{
"context": " node = new Node\n node.mx_hash.hash_key = 'indent'\n ret_value.push [node]\n last_space += ",
"end": 773,
"score": 0.4964137077331543,
"start": 767,
"tag": "KEY",
"value": "indent"
},
{
"context": " node = new Node\n node.mx_hash.hash_key = 'ded... | src/tokenizer.coffee | hu2prod/scriptscript | 1 | require 'fy'
{Token_parser, Tokenizer, Node} = require 'gram2'
module = @
# ###################################################################################################
# specific
# ###################################################################################################
# API should be async by default in case we make some optimizations in future
last_space = 0
tokenizer = new Tokenizer
tokenizer.parser_list.push (new Token_parser 'Xdent', /^\n/, (_this, ret_value, q)->
_this.text = _this.text.substr 1 # \n
tail_space_len = /^[ \t]*/.exec(_this.text)[0].length
_this.text = _this.text.substr tail_space_len
if tail_space_len != last_space
while last_space < tail_space_len
node = new Node
node.mx_hash.hash_key = 'indent'
ret_value.push [node]
last_space += 2
while last_space > tail_space_len
indent_change_present = true
node = new Node
node.mx_hash.hash_key = 'dedent'
ret_value.push [node]
last_space -= 2
else
return if _this.ret_access.last()?[0].mx_hash.hash_key == 'eol' # do not duplicate
node = new Node
node.mx_hash.hash_key = 'eol'
ret_value.push [node]
last_space = tail_space_len
)
tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/)
tokenizer.parser_list.push (new Token_parser 'decimal_literal', /^(0|[1-9][0-9]*)/)
tokenizer.parser_list.push (new Token_parser 'octal_literal', /^0o?[0-7]+/i)
tokenizer.parser_list.push (new Token_parser 'hexadecimal_literal', /^0x[0-9a-f]+/i)
tokenizer.parser_list.push (new Token_parser 'binary_literal', /^0b[01]+/i)
# .123 syntax must be enabled by option
# tokenizer.parser_list.push (new Token_parser 'float_literal', ///
# ^ (?:
# (?:
# \d+\.\d* |
# \.\d+
# ) (?:e[+-]?\d+)? |
# \d+(?:e[+-]?\d+)
# )
# ///i)
tokenizer.parser_list.push (new Token_parser 'float_literal', ///
^ (?:
(?:
\d+\.(?!\.)\d*
) (?:e[+-]?\d+)? |
\d+(?:e[+-]?\d+)
)
///i)
tokenizer.parser_list.push (new Token_parser 'this', /^@/)
tokenizer.parser_list.push (new Token_parser 'comma', /^,/)
tokenizer.parser_list.push (new Token_parser 'pair_separator', /^:/)
tokenizer.parser_list.push (new Token_parser 'unary_operator', /// ^ (
(--?|\+\+?)|
[~!]|
not|
typeof|
void|
new|
delete
) ///)
tokenizer.parser_list.push (new Token_parser 'binary_operator', /// ^ (
\.\.\.?|
\??(::|\.)|
(\*\*?|//?|%%?|<<|>>>?|&&?|\|\|?|\^\^?|[-+?]|and|or|xor)=?|
instanceof|in|of|isnt|is|
[<>!=]=|<|>|
=
) ///)
tokenizer.parser_list.push (new Token_parser 'identifier', /^[_\$a-z][_\$a-z0-9]*/i)
tokenizer.parser_list.push (new Token_parser 'arrow_function', /^[-=]>/)
# Version from the CoffeeScript source code: /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/
tokenizer.parser_list.push (new Token_parser 'comment', /^(###[^#][^]*###|#.*)/)
string_regex_craft = ///
\\[^xu] | # x and u are case sensitive while hex letters are not
\\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence
\\u(?:
[0-9a-fA-F]{4} | # Unicode escape sequence
\{(?:
[0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF
10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF
)\}
)
///.toString().replace(/\//g,'')
single_quoted_regex_craft = ///
(?:
[^\\] |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///)
tokenizer.parser_list.push (new Token_parser 'block_string_literal_singleq', /// ^''' #{single_quoted_regex_craft} ''' ///)
double_quoted_regexp_craft = ///
(?:
[^\\#] |
\#(?!\{) |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'block_string_literal_doubleq', /// ^""" #{double_quoted_regexp_craft} """ ///)
tokenizer.parser_list.push (new Token_parser 'inline_string_template_start', /// ^"(?!"") #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'inline_string_template_end' , /// ^ } #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'string_template_mid' , /// ^ } #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'block_string_template_start' , /// ^""" #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'block_string_template_end' , /// ^ } #{double_quoted_regexp_craft} """ ///)
# NOTE don't check flags. Because of reasons
tokenizer.parser_list.push (new Token_parser 'regexp_literal', ///
^/(?!\s) (?:
(?: [^ [ / \n \\ ] # every other thing
| \\[^\n] # anything but newlines escaped
| \[ # character class
(?: \\[^\n] | [^ \] \n \\ ] )*
\]
)+) /[imgy]*
///)
regexp_template_craft = ///
(?:
[^\\#] |
\#(?!{) |
\\#
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'here_regexp_literal', /// ^\/\/\/ #{regexp_template_craft} \/\/\/[imgy]* ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_start', /// ^\/\/\/ #{regexp_template_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_mid', /// ^} #{regexp_template_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_end', /// ^} #{regexp_template_craft} \/\/\/[imgy]* ///)
@_tokenizer = tokenizer
@_tokenize = (str, opt={})->
# reset
last_space = 0
# TODO later better replace policy/heur
str = str.replace /\t/, ' '
str += "\n" # dedent fix
res = tokenizer.go str
while res.length && res.last()[0].mx_hash.hash_key == 'eol'
res.pop()
# Fix for an empty input:
if res.length == 0
node = new Node
node.mx_hash.hash_key = 'empty'
res.push [node]
res
@tokenize = (str, opt, on_end)->
try
res = module._tokenize str, opt
catch e
return on_end e
on_end null, res | 154141 | require 'fy'
{Token_parser, Tokenizer, Node} = require 'gram2'
module = @
# ###################################################################################################
# specific
# ###################################################################################################
# API should be async by default in case we make some optimizations in future
last_space = 0
tokenizer = new Tokenizer
tokenizer.parser_list.push (new Token_parser 'Xdent', /^\n/, (_this, ret_value, q)->
_this.text = _this.text.substr 1 # \n
tail_space_len = /^[ \t]*/.exec(_this.text)[0].length
_this.text = _this.text.substr tail_space_len
if tail_space_len != last_space
while last_space < tail_space_len
node = new Node
node.mx_hash.hash_key = '<KEY>'
ret_value.push [node]
last_space += 2
while last_space > tail_space_len
indent_change_present = true
node = new Node
node.mx_hash.hash_key = '<KEY>'
ret_value.push [node]
last_space -= 2
else
return if _this.ret_access.last()?[0].mx_hash.hash_key == 'eol' # do not duplicate
node = new Node
node.mx_hash.hash_key = 'eol'
ret_value.push [node]
last_space = tail_space_len
)
tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/)
tokenizer.parser_list.push (new Token_parser 'decimal_literal', /^(0|[1-9][0-9]*)/)
tokenizer.parser_list.push (new Token_parser 'octal_literal', /^0o?[0-7]+/i)
tokenizer.parser_list.push (new Token_parser 'hexadecimal_literal', /^0x[0-9a-f]+/i)
tokenizer.parser_list.push (new Token_parser 'binary_literal', /^0b[01]+/i)
# .123 syntax must be enabled by option
# tokenizer.parser_list.push (new Token_parser 'float_literal', ///
# ^ (?:
# (?:
# \d+\.\d* |
# \.\d+
# ) (?:e[+-]?\d+)? |
# \d+(?:e[+-]?\d+)
# )
# ///i)
tokenizer.parser_list.push (new Token_parser 'float_literal', ///
^ (?:
(?:
\d+\.(?!\.)\d*
) (?:e[+-]?\d+)? |
\d+(?:e[+-]?\d+)
)
///i)
tokenizer.parser_list.push (new Token_parser 'this', /^@/)
tokenizer.parser_list.push (new Token_parser 'comma', /^,/)
tokenizer.parser_list.push (new Token_parser 'pair_separator', /^:/)
tokenizer.parser_list.push (new Token_parser 'unary_operator', /// ^ (
(--?|\+\+?)|
[~!]|
not|
typeof|
void|
new|
delete
) ///)
tokenizer.parser_list.push (new Token_parser 'binary_operator', /// ^ (
\.\.\.?|
\??(::|\.)|
(\*\*?|//?|%%?|<<|>>>?|&&?|\|\|?|\^\^?|[-+?]|and|or|xor)=?|
instanceof|in|of|isnt|is|
[<>!=]=|<|>|
=
) ///)
tokenizer.parser_list.push (new Token_parser 'identifier', /^[_\$a-z][_\$a-z0-9]*/i)
tokenizer.parser_list.push (new Token_parser 'arrow_function', /^[-=]>/)
# Version from the CoffeeScript source code: /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/
tokenizer.parser_list.push (new Token_parser 'comment', /^(###[^#][^]*###|#.*)/)
string_regex_craft = ///
\\[^xu] | # x and u are case sensitive while hex letters are not
\\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence
\\u(?:
[0-9a-fA-F]{4} | # Unicode escape sequence
\{(?:
[0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF
10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF
)\}
)
///.toString().replace(/\//g,'')
single_quoted_regex_craft = ///
(?:
[^\\] |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///)
tokenizer.parser_list.push (new Token_parser 'block_string_literal_singleq', /// ^''' #{single_quoted_regex_craft} ''' ///)
double_quoted_regexp_craft = ///
(?:
[^\\#] |
\#(?!\{) |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'block_string_literal_doubleq', /// ^""" #{double_quoted_regexp_craft} """ ///)
tokenizer.parser_list.push (new Token_parser 'inline_string_template_start', /// ^"(?!"") #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'inline_string_template_end' , /// ^ } #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'string_template_mid' , /// ^ } #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'block_string_template_start' , /// ^""" #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'block_string_template_end' , /// ^ } #{double_quoted_regexp_craft} """ ///)
# NOTE don't check flags. Because of reasons
tokenizer.parser_list.push (new Token_parser 'regexp_literal', ///
^/(?!\s) (?:
(?: [^ [ / \n \\ ] # every other thing
| \\[^\n] # anything but newlines escaped
| \[ # character class
(?: \\[^\n] | [^ \] \n \\ ] )*
\]
)+) /[imgy]*
///)
regexp_template_craft = ///
(?:
[^\\#] |
\#(?!{) |
\\#
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'here_regexp_literal', /// ^\/\/\/ #{regexp_template_craft} \/\/\/[imgy]* ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_start', /// ^\/\/\/ #{regexp_template_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_mid', /// ^} #{regexp_template_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_end', /// ^} #{regexp_template_craft} \/\/\/[imgy]* ///)
@_tokenizer = tokenizer
@_tokenize = (str, opt={})->
# reset
last_space = 0
# TODO later better replace policy/heur
str = str.replace /\t/, ' '
str += "\n" # dedent fix
res = tokenizer.go str
while res.length && res.last()[0].mx_hash.hash_key == 'eol'
res.pop()
# Fix for an empty input:
if res.length == 0
node = new Node
node.mx_hash.hash_key = 'empty'
res.push [node]
res
@tokenize = (str, opt, on_end)->
try
res = module._tokenize str, opt
catch e
return on_end e
on_end null, res | true | require 'fy'
{Token_parser, Tokenizer, Node} = require 'gram2'
module = @
# ###################################################################################################
# specific
# ###################################################################################################
# API should be async by default in case we make some optimizations in future
last_space = 0
tokenizer = new Tokenizer
tokenizer.parser_list.push (new Token_parser 'Xdent', /^\n/, (_this, ret_value, q)->
_this.text = _this.text.substr 1 # \n
tail_space_len = /^[ \t]*/.exec(_this.text)[0].length
_this.text = _this.text.substr tail_space_len
if tail_space_len != last_space
while last_space < tail_space_len
node = new Node
node.mx_hash.hash_key = 'PI:KEY:<KEY>END_PI'
ret_value.push [node]
last_space += 2
while last_space > tail_space_len
indent_change_present = true
node = new Node
node.mx_hash.hash_key = 'PI:KEY:<KEY>END_PI'
ret_value.push [node]
last_space -= 2
else
return if _this.ret_access.last()?[0].mx_hash.hash_key == 'eol' # do not duplicate
node = new Node
node.mx_hash.hash_key = 'eol'
ret_value.push [node]
last_space = tail_space_len
)
tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/)
tokenizer.parser_list.push (new Token_parser 'decimal_literal', /^(0|[1-9][0-9]*)/)
tokenizer.parser_list.push (new Token_parser 'octal_literal', /^0o?[0-7]+/i)
tokenizer.parser_list.push (new Token_parser 'hexadecimal_literal', /^0x[0-9a-f]+/i)
tokenizer.parser_list.push (new Token_parser 'binary_literal', /^0b[01]+/i)
# .123 syntax must be enabled by option
# tokenizer.parser_list.push (new Token_parser 'float_literal', ///
# ^ (?:
# (?:
# \d+\.\d* |
# \.\d+
# ) (?:e[+-]?\d+)? |
# \d+(?:e[+-]?\d+)
# )
# ///i)
tokenizer.parser_list.push (new Token_parser 'float_literal', ///
^ (?:
(?:
\d+\.(?!\.)\d*
) (?:e[+-]?\d+)? |
\d+(?:e[+-]?\d+)
)
///i)
tokenizer.parser_list.push (new Token_parser 'this', /^@/)
tokenizer.parser_list.push (new Token_parser 'comma', /^,/)
tokenizer.parser_list.push (new Token_parser 'pair_separator', /^:/)
tokenizer.parser_list.push (new Token_parser 'unary_operator', /// ^ (
(--?|\+\+?)|
[~!]|
not|
typeof|
void|
new|
delete
) ///)
tokenizer.parser_list.push (new Token_parser 'binary_operator', /// ^ (
\.\.\.?|
\??(::|\.)|
(\*\*?|//?|%%?|<<|>>>?|&&?|\|\|?|\^\^?|[-+?]|and|or|xor)=?|
instanceof|in|of|isnt|is|
[<>!=]=|<|>|
=
) ///)
tokenizer.parser_list.push (new Token_parser 'identifier', /^[_\$a-z][_\$a-z0-9]*/i)
tokenizer.parser_list.push (new Token_parser 'arrow_function', /^[-=]>/)
# Version from the CoffeeScript source code: /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/
tokenizer.parser_list.push (new Token_parser 'comment', /^(###[^#][^]*###|#.*)/)
string_regex_craft = ///
\\[^xu] | # x and u are case sensitive while hex letters are not
\\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence
\\u(?:
[0-9a-fA-F]{4} | # Unicode escape sequence
\{(?:
[0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF
10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF
)\}
)
///.toString().replace(/\//g,'')
single_quoted_regex_craft = ///
(?:
[^\\] |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///)
tokenizer.parser_list.push (new Token_parser 'block_string_literal_singleq', /// ^''' #{single_quoted_regex_craft} ''' ///)
double_quoted_regexp_craft = ///
(?:
[^\\#] |
\#(?!\{) |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'block_string_literal_doubleq', /// ^""" #{double_quoted_regexp_craft} """ ///)
tokenizer.parser_list.push (new Token_parser 'inline_string_template_start', /// ^"(?!"") #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'inline_string_template_end' , /// ^ } #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'string_template_mid' , /// ^ } #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'block_string_template_start' , /// ^""" #{double_quoted_regexp_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'block_string_template_end' , /// ^ } #{double_quoted_regexp_craft} """ ///)
# NOTE don't check flags. Because of reasons
tokenizer.parser_list.push (new Token_parser 'regexp_literal', ///
^/(?!\s) (?:
(?: [^ [ / \n \\ ] # every other thing
| \\[^\n] # anything but newlines escaped
| \[ # character class
(?: \\[^\n] | [^ \] \n \\ ] )*
\]
)+) /[imgy]*
///)
regexp_template_craft = ///
(?:
[^\\#] |
\#(?!{) |
\\#
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'here_regexp_literal', /// ^\/\/\/ #{regexp_template_craft} \/\/\/[imgy]* ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_start', /// ^\/\/\/ #{regexp_template_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_mid', /// ^} #{regexp_template_craft} \#\{ ///)
tokenizer.parser_list.push (new Token_parser 'regexp_template_end', /// ^} #{regexp_template_craft} \/\/\/[imgy]* ///)
@_tokenizer = tokenizer
@_tokenize = (str, opt={})->
# reset
last_space = 0
# TODO later better replace policy/heur
str = str.replace /\t/, ' '
str += "\n" # dedent fix
res = tokenizer.go str
while res.length && res.last()[0].mx_hash.hash_key == 'eol'
res.pop()
# Fix for an empty input:
if res.length == 0
node = new Node
node.mx_hash.hash_key = 'empty'
res.push [node]
res
@tokenize = (str, opt, on_end)->
try
res = module._tokenize str, opt
catch e
return on_end e
on_end null, res |
[
{
"context": "id\n api_key: Evercam.User.api_key\n name: name\n before: $(\"#compare_before\").attr(\"timestam",
"end": 9730,
"score": 0.9032946825027466,
"start": 9726,
"tag": "NAME",
"value": "name"
}
] | data/coffeescript/ce20e6a00f89c28c2e9984ea6411656e_compare.js.coffee | maxim5/code-inspector | 5 | imagesCompare = undefined
clearTimeOut = null
xhrChangeMonth = null
window.sendRequest = (settings) ->
token = $('meta[name="csrf-token"]')
if token.size() > 0
headers =
"X-CSRF-Token": token.attr("content")
settings.headers = headers
xhrChangeMonth = $.ajax(settings)
initCompare = ->
imagesCompareElement = $('.js-img-compare').imagesCompare()
imagesCompare = imagesCompareElement.data('imagesCompare')
events = imagesCompare.events()
imagesCompare.on events.changed, (event) ->
true
getFirstLastImages = (image_id, query_string, reload, setDate) ->
data =
api_id: Evercam.User.api_id
api_key: Evercam.User.api_key
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
snapshot = response
if query_string.indexOf("nearest") > 0 && response.snapshots.length > 0
snapshot = response.snapshots[0]
if snapshot.data isnt undefined
$("##{image_id}").attr("src", snapshot.data)
$("##{image_id}").attr("timestamp", snapshot.created_at)
if setDate is true && query_string.indexOf("nearest") < 0
d = new Date(snapshot.created_at*1000)
before_month = d.getUTCMonth()+1
before_year = d.getUTCFullYear()
camera_created_date = new Date(Evercam.Camera.created_at*1000)
camera_created_month = camera_created_date.getUTCMonth()+1
camera_created_year = camera_created_date.getUTCFullYear()
string_date = "#{before_month}/#{d.getUTCDate()}/#{before_year}"
camera_created_at = "#{camera_created_year}/#{camera_created_month}/#{camera_created_date.getUTCDate()}"
$('#calendar-before').datetimepicker({value: string_date, minDate: camera_created_at, yearStart: camera_created_year})
$('#calendar-after').datetimepicker({minDate: camera_created_at, yearStart: camera_created_year})
if setDate is false && query_string.indexOf("nearest") < 0
date_after = new Date(snapshot.created_at*1000)
after_month = date_after.getUTCMonth()+1
after_year = date_after.getUTCFullYear()
string_after_date = "#{after_year}/#{after_month}/#{date_after.getUTCDate()}"
$('#calendar-before').datetimepicker({maxDate: string_after_date, yearEnd: after_year})
$('#calendar-after').datetimepicker({maxDate: string_after_date, yearEnd: after_year})
initCompare() if reload
else
Notification.show("No image found")
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
type: 'GET'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots#{query_string}"
sendRequest(settings)
handleTabOpen = ->
$('.nav-tab-compare').on 'shown.bs.tab', ->
initCompare()
updateURL()
updateURL = ->
url = "#{Evercam.request.rootpath}/compare"
query_string = ""
if $("#txtbefore").val() isnt ""
query_string = "?before=#{moment.utc($("#txtbefore").val()).toISOString()}"
if $("#txtafter").val() isnt ""
if query_string is ""
query_string = "?after=#{moment.utc($("#txtafter").val()).toISOString()}"
else
query_string = "#{query_string}&after=#{moment.utc($("#txtafter").val()).toISOString()}"
url = "#{url}#{query_string}"
if history.replaceState
window.history.replaceState({}, '', url)
getQueryStringByName = (name) ->
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
results = regex.exec(location.search)
if results == null
null
else
decodeURIComponent(results[1].replace(/\+/g, ' '))
clickToCopy = ->
clipboard = new Clipboard('.copy-url-icon')
clipboard.on 'success', (e) ->
$('.bb-alert').width '100px'
Notification.show 'Copied!'
copyToClipboard = (elem) ->
targetId = '_hiddenCopyText_'
isInput = elem.tagName == 'INPUT' or elem.tagName == 'TEXTAREA'
origSelectionStart = undefined
origSelectionEnd = undefined
if isInput
target = elem
origSelectionStart = elem.selectionStart
origSelectionEnd = elem.selectionEnd
else
target = document.getElementById(targetId)
if !target
target = document.createElement('textarea')
target.style.position = 'absolute'
target.style.left = '-9999px'
target.style.top = '0'
target.id = targetId
document.body.appendChild target
target.textContent = elem.textContent
currentFocus = document.activeElement
target.focus()
target.setSelectionRange 0, target.value.length
succeed = undefined
try
succeed = document.execCommand('copy')
catch e
succeed = false
if currentFocus and typeof currentFocus.focus == 'function'
currentFocus.focus()
if isInput
elem.setSelectionRange origSelectionStart, origSelectionEnd
else
target.textContent = ''
succeed
HighlightDaysInMonth = (query_string, year, month) ->
data = {}
data.api_id = Evercam.User.api_id
data.api_key = Evercam.User.api_key
onError = (response, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
removeCurrentDateHighlight(query_string)
removeCurrentHourHighlight(query_string)
hideBeforeAfterLoadingAnimation(query_string)
for day in response.days
HighlightBeforeAfterDay(query_string, year, month, day)
settings =
cache: true
data: data
dataType: 'json'
error: onError
success: onSuccess
contentType: "application/json charset=utf-8"
type: 'GET'
url: "#{Evercam.MEDIA_API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots/#{year}/#{month}/days"
sendRequest(settings)
HighlightBeforeAfterDay = (query_string, before_year, before_month, before_day) ->
beforeDays = $("##{query_string} .xdsoft_datepicker table td[class*='xdsoft_date'] div")
beforeDays.each ->
beforeDay = $(this)
if !beforeDay.parent().hasClass('xdsoft_other_month')
iDay = parseInt(beforeDay.text())
if before_day == iDay
beforeDay.parent().addClass 'xdsoft_current'
HighlightSnapshotHour = (query_string, year, month, date) ->
data = {}
data.api_id = Evercam.User.api_id
data.api_key = Evercam.User.api_key
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
removeCurrentHourHighlight(query_string)
hideBeforeAfterLoadingAnimation(query_string)
for hour in response.hours
HighlightBeforeAfterHour(query_string, year, month, date, hour)
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
contentType: "application/json charset=utf-8"
type: 'GET'
timeout: 15000
url: "#{Evercam.MEDIA_API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots/#{year}/#{(month)}/#{date}/hours"
sendRequest(settings)
HighlightBeforeAfterHour = (query_string, before_year, before_month, before_day, before_hour) ->
beforeHours = $("##{query_string} .xdsoft_timepicker [class*='xdsoft_time']")
beforeHours.each ->
beforeHour = $(this)
iHour = parseInt(beforeHour.text())
if before_hour == iHour
beforeHour.addClass 'xdsoft_current'
removeCurrentHourHighlight = (query_string) ->
beforeHours = $("##{query_string} .xdsoft_timepicker [class*='xdsoft_time']")
beforeHours.removeClass 'xdsoft_current'
removeCurrentDateHighlight = (query_string) ->
beforeDays = $("##{query_string} .xdsoft_datepicker table td[class*='xdsoft_date']")
beforeDays.removeClass 'xdsoft_current'
showBeforeAfterLoadingAnimation = (query_string) ->
$("##{query_string} .xdsoft_datepicker").addClass 'opacitypoint5'
$("##{query_string} .xdsoft_timepicker").addClass 'opacitypoint5'
hideBeforeAfterLoadingAnimation = (query_string) ->
$("##{query_string} .xdsoft_datepicker").removeClass 'opacitypoint5'
$("##{query_string} .xdsoft_timepicker").removeClass 'opacitypoint5'
setCompareEmbedCodeTitle = ->
$("#div-embed-code").on "click", (e)->
$(".export-buttons #cancel_export").html 'Close'
after_image_time = $("#compare_after").attr("timestamp")
before_image_time = $("#compare_before").attr("timestamp")
if after_image_time && before_image_time isnt undefined
day_before = moment.utc(before_image_time*1000).format("Do")
day_after = moment.utc(after_image_time*1000).format("Do")
month_before = moment.utc(before_image_time*1000).format("MMM")
month_after = moment.utc(after_image_time*1000).format("MMM")
$("#export-compare-title").val("#{day_before} #{month_before} to #{day_after} #{month_after}")
e.stopPropagation()
$('#export-compare-modal').modal 'show'
else
e.stopPropagation()
$(".bb-alert").removeClass("alert-info").addClass("alert-danger")
$(".bb-alert").css "width", "410px"
Notification.show("Unable to export compare, before/after image is not available.")
export_compare = ->
$("#export_compare_button").on "click", ->
$("#spn-success-export").removeClass("alert-info").addClass("alert-danger")
name = $("#export-compare-title").val()
if name is ""
$("#spn-success-export").text("Please enter export name.").removeClass("hide")
return false
button = $(this)
button.prop("disabled", true)
$("#row-animation").removeClass("hide")
after = " #{convert_timestamp_to_path($("#compare_after").attr("timestamp"))}"
before = " #{convert_timestamp_to_path($("#compare_before").attr("timestamp"))}"
embed_code = "<div id='evercam-compare'></div><script src='#{window.location.origin}/assets/evercam_compare.js' class='#{Evercam.Camera.id}#{before}#{after} autoplay'></script>"
$("#txtEmbedCode").val(embed_code)
data =
api_id: Evercam.User.api_id
api_key: Evercam.User.api_key
name: name
before: $("#compare_before").attr("timestamp")
before_image: $("#compare_before").attr("src")
after: $("#compare_after").attr("timestamp")
after_image: $("#compare_after").attr("src")
embed: embed_code
create_animation: true
onError = (jqXHR, status, error) ->
$("#spn-success-export").text("Failed to export compare.").removeClass("hide")
$("#row-animation").addClass("hide")
button.prop("disabled", false)
onSuccess = (response, status, jqXHR) ->
button.hide()
$(".export-buttons #cancel_export").html 'Ok'
$("#row-animation").addClass("hide")
$("#row-textarea").removeClass("hide")
$("#row-message").removeClass("hide")
$("#spn-success-export").addClass("alert-info").removeClass("alert-danger").addClass("hide")
$("#gif_url").val(response.compares[0].gif_url.replace("media.evercam.io", "api.evercam.io"))
$("#mp4_url").val(response.compares[0].mp4_url.replace("media.evercam.io", "api.evercam.io"))
window.on_export_compare()
clearTimeOut = setTimeout( ->
auto_check_compare_status(response.compares[0].id, 0)
, 10000)
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
type: 'POST'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/compares"
sendRequest(settings)
convert_timestamp_to_path = (timestamp) ->
timestamp_to_int = parseInt(timestamp)
moment.utc(timestamp_to_int*1000).format('YYYY/MM/DD/HH_mm_ss')
cancelForm = ->
$('#export-compare-modal').on 'hide.bs.modal', ->
clean_form()
$('#export-compare-modal').on 'show.bs.modal', ->
clean_form()
clean_form = ->
$("#txtEmbedCode").val("")
$("#row-textarea").addClass("hide")
$("#spn-success-export").addClass("hide")
$("#export_compare_button").prop("disabled", false)
$("#export_compare_button").show()
$("#row-gif-url").addClass("hide")
$("#row-mp4-url").addClass("hide")
$("#cancel_export").show()
$("#row-message").addClass("hide")
clearTimeout(clearTimeOut)
download_animation = ->
$(".download-animation").on "click", ->
src_id = $(this).attr("data-download-target")
NProgress.start()
download($("#{src_id}").val())
setTimeout( ->
NProgress.done()
, 4000)
switch_to_archive_tab = ->
$("#switch_archive").on "click", ->
$(".nav-tab-archives").tab('show')
auto_check_compare_status = (compare_id, tries) ->
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
if response.compares[0].status is "Completed"
$("#row-gif-url").removeClass("hide")
$("#row-mp4-url").removeClass("hide")
$("#row-message").addClass("hide")
else if response.compares[0].status is "Processing" && tries < 10
clearTimeOut = setTimeout( ->
auto_check_compare_status(response.compares[0].id, tries++)
, 10000)
settings =
cache: false
data: {}
dataType: 'json'
error: onError
success: onSuccess
type: 'GET'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/compares/#{compare_id}?api_id=#{Evercam.User.api_id}&api_key=#{Evercam.User.api_key}"
sendRequest(settings)
window.initializeCompareTab = ->
getFirstLastImages("compare_before", "/oldest", false, true)
getFirstLastImages("compare_after", "/latest", false, false)
handleTabOpen()
removeCurrentDateHighlight()
export_compare()
cancelForm()
clickToCopy()
download_animation()
switch_to_archive_tab()
setCompareEmbedCodeTitle()
$('#calendar-before').datetimepicker
format: 'm/d/Y H:m'
id: 'before-calendar'
onSelectTime: (dp, $input) ->
$("#txtbefore").val($input.val())
val = getQueryStringByName("after")
url = "#{Evercam.request.rootpath}/compare?before=#{moment.utc($input.val()).toISOString()}"
if val isnt null
url = "#{url}&after=#{val}"
if history.replaceState
window.history.replaceState({}, '', url)
getFirstLastImages("compare_before", "/#{(new Date($input.val())) / 1000}/nearest", true, false)
onChangeMonth: (dp, $input) ->
xhrChangeMonth.abort()
month = dp.getMonth() + 1
year = dp.getFullYear()
HighlightDaysInMonth("before-calendar", year, month)
removeCurrentHourHighlight("before-calendar")
showBeforeAfterLoadingAnimation("before-calendar")
onSelectDate: (ct, $i) ->
month = ct.getMonth() + 1
year = ct.getFullYear()
date = ct.getDate()
HighlightSnapshotHour("before-calendar", year, month, date)
HighlightDaysInMonth("before-calendar", year, month)
onShow: (current_time, $input) ->
month = current_time.getMonth() + 1
year = current_time.getFullYear()
removeCurrentHourHighlight("before-calendar")
HighlightDaysInMonth("before-calendar", year, month)
showBeforeAfterLoadingAnimation("before-calendar")
$('#calendar-after').datetimepicker
format: 'm/d/Y H:m'
id: 'after-calendar'
onSelectTime: (dp, $input) ->
$("#txtafter").val($input.val())
val = getQueryStringByName("before")
url = "#{Evercam.request.rootpath}/compare"
if val isnt null
url = "#{url}?before=#{val}&after=#{moment.utc($input.val()).toISOString()}"
else
url = "#{url}?after=#{moment.utc($input.val()).toISOString()}"
if history.replaceState
window.history.replaceState({}, '', url)
getFirstLastImages("compare_after", "/#{(new Date($input.val())) / 1000}/nearest", true, false)
onChangeMonth: (dp, $input) ->
xhrChangeMonth.abort()
month = dp.getMonth() + 1
year = dp.getFullYear()
removeCurrentHourHighlight("after-calendar")
HighlightDaysInMonth("after-calendar", year, month)
showBeforeAfterLoadingAnimation("after-calendar")
onSelectDate: (ct, $i) ->
month = ct.getMonth() + 1
year = ct.getFullYear()
date = ct.getDate()
HighlightSnapshotHour("after-calendar", year, month, date)
HighlightDaysInMonth("after-calendar", year, month)
onShow: (current_time, $input) ->
month = current_time.getMonth() + 1
year = current_time.getFullYear()
removeCurrentHourHighlight("after-calendar")
HighlightDaysInMonth("after-calendar", year, month)
showBeforeAfterLoadingAnimation("after-calendar")
| 143027 | imagesCompare = undefined
clearTimeOut = null
xhrChangeMonth = null
window.sendRequest = (settings) ->
token = $('meta[name="csrf-token"]')
if token.size() > 0
headers =
"X-CSRF-Token": token.attr("content")
settings.headers = headers
xhrChangeMonth = $.ajax(settings)
initCompare = ->
imagesCompareElement = $('.js-img-compare').imagesCompare()
imagesCompare = imagesCompareElement.data('imagesCompare')
events = imagesCompare.events()
imagesCompare.on events.changed, (event) ->
true
getFirstLastImages = (image_id, query_string, reload, setDate) ->
data =
api_id: Evercam.User.api_id
api_key: Evercam.User.api_key
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
snapshot = response
if query_string.indexOf("nearest") > 0 && response.snapshots.length > 0
snapshot = response.snapshots[0]
if snapshot.data isnt undefined
$("##{image_id}").attr("src", snapshot.data)
$("##{image_id}").attr("timestamp", snapshot.created_at)
if setDate is true && query_string.indexOf("nearest") < 0
d = new Date(snapshot.created_at*1000)
before_month = d.getUTCMonth()+1
before_year = d.getUTCFullYear()
camera_created_date = new Date(Evercam.Camera.created_at*1000)
camera_created_month = camera_created_date.getUTCMonth()+1
camera_created_year = camera_created_date.getUTCFullYear()
string_date = "#{before_month}/#{d.getUTCDate()}/#{before_year}"
camera_created_at = "#{camera_created_year}/#{camera_created_month}/#{camera_created_date.getUTCDate()}"
$('#calendar-before').datetimepicker({value: string_date, minDate: camera_created_at, yearStart: camera_created_year})
$('#calendar-after').datetimepicker({minDate: camera_created_at, yearStart: camera_created_year})
if setDate is false && query_string.indexOf("nearest") < 0
date_after = new Date(snapshot.created_at*1000)
after_month = date_after.getUTCMonth()+1
after_year = date_after.getUTCFullYear()
string_after_date = "#{after_year}/#{after_month}/#{date_after.getUTCDate()}"
$('#calendar-before').datetimepicker({maxDate: string_after_date, yearEnd: after_year})
$('#calendar-after').datetimepicker({maxDate: string_after_date, yearEnd: after_year})
initCompare() if reload
else
Notification.show("No image found")
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
type: 'GET'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots#{query_string}"
sendRequest(settings)
handleTabOpen = ->
$('.nav-tab-compare').on 'shown.bs.tab', ->
initCompare()
updateURL()
updateURL = ->
url = "#{Evercam.request.rootpath}/compare"
query_string = ""
if $("#txtbefore").val() isnt ""
query_string = "?before=#{moment.utc($("#txtbefore").val()).toISOString()}"
if $("#txtafter").val() isnt ""
if query_string is ""
query_string = "?after=#{moment.utc($("#txtafter").val()).toISOString()}"
else
query_string = "#{query_string}&after=#{moment.utc($("#txtafter").val()).toISOString()}"
url = "#{url}#{query_string}"
if history.replaceState
window.history.replaceState({}, '', url)
getQueryStringByName = (name) ->
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
results = regex.exec(location.search)
if results == null
null
else
decodeURIComponent(results[1].replace(/\+/g, ' '))
clickToCopy = ->
clipboard = new Clipboard('.copy-url-icon')
clipboard.on 'success', (e) ->
$('.bb-alert').width '100px'
Notification.show 'Copied!'
copyToClipboard = (elem) ->
targetId = '_hiddenCopyText_'
isInput = elem.tagName == 'INPUT' or elem.tagName == 'TEXTAREA'
origSelectionStart = undefined
origSelectionEnd = undefined
if isInput
target = elem
origSelectionStart = elem.selectionStart
origSelectionEnd = elem.selectionEnd
else
target = document.getElementById(targetId)
if !target
target = document.createElement('textarea')
target.style.position = 'absolute'
target.style.left = '-9999px'
target.style.top = '0'
target.id = targetId
document.body.appendChild target
target.textContent = elem.textContent
currentFocus = document.activeElement
target.focus()
target.setSelectionRange 0, target.value.length
succeed = undefined
try
succeed = document.execCommand('copy')
catch e
succeed = false
if currentFocus and typeof currentFocus.focus == 'function'
currentFocus.focus()
if isInput
elem.setSelectionRange origSelectionStart, origSelectionEnd
else
target.textContent = ''
succeed
HighlightDaysInMonth = (query_string, year, month) ->
data = {}
data.api_id = Evercam.User.api_id
data.api_key = Evercam.User.api_key
onError = (response, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
removeCurrentDateHighlight(query_string)
removeCurrentHourHighlight(query_string)
hideBeforeAfterLoadingAnimation(query_string)
for day in response.days
HighlightBeforeAfterDay(query_string, year, month, day)
settings =
cache: true
data: data
dataType: 'json'
error: onError
success: onSuccess
contentType: "application/json charset=utf-8"
type: 'GET'
url: "#{Evercam.MEDIA_API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots/#{year}/#{month}/days"
sendRequest(settings)
HighlightBeforeAfterDay = (query_string, before_year, before_month, before_day) ->
beforeDays = $("##{query_string} .xdsoft_datepicker table td[class*='xdsoft_date'] div")
beforeDays.each ->
beforeDay = $(this)
if !beforeDay.parent().hasClass('xdsoft_other_month')
iDay = parseInt(beforeDay.text())
if before_day == iDay
beforeDay.parent().addClass 'xdsoft_current'
HighlightSnapshotHour = (query_string, year, month, date) ->
data = {}
data.api_id = Evercam.User.api_id
data.api_key = Evercam.User.api_key
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
removeCurrentHourHighlight(query_string)
hideBeforeAfterLoadingAnimation(query_string)
for hour in response.hours
HighlightBeforeAfterHour(query_string, year, month, date, hour)
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
contentType: "application/json charset=utf-8"
type: 'GET'
timeout: 15000
url: "#{Evercam.MEDIA_API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots/#{year}/#{(month)}/#{date}/hours"
sendRequest(settings)
HighlightBeforeAfterHour = (query_string, before_year, before_month, before_day, before_hour) ->
beforeHours = $("##{query_string} .xdsoft_timepicker [class*='xdsoft_time']")
beforeHours.each ->
beforeHour = $(this)
iHour = parseInt(beforeHour.text())
if before_hour == iHour
beforeHour.addClass 'xdsoft_current'
removeCurrentHourHighlight = (query_string) ->
beforeHours = $("##{query_string} .xdsoft_timepicker [class*='xdsoft_time']")
beforeHours.removeClass 'xdsoft_current'
removeCurrentDateHighlight = (query_string) ->
beforeDays = $("##{query_string} .xdsoft_datepicker table td[class*='xdsoft_date']")
beforeDays.removeClass 'xdsoft_current'
showBeforeAfterLoadingAnimation = (query_string) ->
$("##{query_string} .xdsoft_datepicker").addClass 'opacitypoint5'
$("##{query_string} .xdsoft_timepicker").addClass 'opacitypoint5'
hideBeforeAfterLoadingAnimation = (query_string) ->
$("##{query_string} .xdsoft_datepicker").removeClass 'opacitypoint5'
$("##{query_string} .xdsoft_timepicker").removeClass 'opacitypoint5'
setCompareEmbedCodeTitle = ->
$("#div-embed-code").on "click", (e)->
$(".export-buttons #cancel_export").html 'Close'
after_image_time = $("#compare_after").attr("timestamp")
before_image_time = $("#compare_before").attr("timestamp")
if after_image_time && before_image_time isnt undefined
day_before = moment.utc(before_image_time*1000).format("Do")
day_after = moment.utc(after_image_time*1000).format("Do")
month_before = moment.utc(before_image_time*1000).format("MMM")
month_after = moment.utc(after_image_time*1000).format("MMM")
$("#export-compare-title").val("#{day_before} #{month_before} to #{day_after} #{month_after}")
e.stopPropagation()
$('#export-compare-modal').modal 'show'
else
e.stopPropagation()
$(".bb-alert").removeClass("alert-info").addClass("alert-danger")
$(".bb-alert").css "width", "410px"
Notification.show("Unable to export compare, before/after image is not available.")
export_compare = ->
$("#export_compare_button").on "click", ->
$("#spn-success-export").removeClass("alert-info").addClass("alert-danger")
name = $("#export-compare-title").val()
if name is ""
$("#spn-success-export").text("Please enter export name.").removeClass("hide")
return false
button = $(this)
button.prop("disabled", true)
$("#row-animation").removeClass("hide")
after = " #{convert_timestamp_to_path($("#compare_after").attr("timestamp"))}"
before = " #{convert_timestamp_to_path($("#compare_before").attr("timestamp"))}"
embed_code = "<div id='evercam-compare'></div><script src='#{window.location.origin}/assets/evercam_compare.js' class='#{Evercam.Camera.id}#{before}#{after} autoplay'></script>"
$("#txtEmbedCode").val(embed_code)
data =
api_id: Evercam.User.api_id
api_key: Evercam.User.api_key
name: <NAME>
before: $("#compare_before").attr("timestamp")
before_image: $("#compare_before").attr("src")
after: $("#compare_after").attr("timestamp")
after_image: $("#compare_after").attr("src")
embed: embed_code
create_animation: true
onError = (jqXHR, status, error) ->
$("#spn-success-export").text("Failed to export compare.").removeClass("hide")
$("#row-animation").addClass("hide")
button.prop("disabled", false)
onSuccess = (response, status, jqXHR) ->
button.hide()
$(".export-buttons #cancel_export").html 'Ok'
$("#row-animation").addClass("hide")
$("#row-textarea").removeClass("hide")
$("#row-message").removeClass("hide")
$("#spn-success-export").addClass("alert-info").removeClass("alert-danger").addClass("hide")
$("#gif_url").val(response.compares[0].gif_url.replace("media.evercam.io", "api.evercam.io"))
$("#mp4_url").val(response.compares[0].mp4_url.replace("media.evercam.io", "api.evercam.io"))
window.on_export_compare()
clearTimeOut = setTimeout( ->
auto_check_compare_status(response.compares[0].id, 0)
, 10000)
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
type: 'POST'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/compares"
sendRequest(settings)
convert_timestamp_to_path = (timestamp) ->
timestamp_to_int = parseInt(timestamp)
moment.utc(timestamp_to_int*1000).format('YYYY/MM/DD/HH_mm_ss')
cancelForm = ->
$('#export-compare-modal').on 'hide.bs.modal', ->
clean_form()
$('#export-compare-modal').on 'show.bs.modal', ->
clean_form()
clean_form = ->
$("#txtEmbedCode").val("")
$("#row-textarea").addClass("hide")
$("#spn-success-export").addClass("hide")
$("#export_compare_button").prop("disabled", false)
$("#export_compare_button").show()
$("#row-gif-url").addClass("hide")
$("#row-mp4-url").addClass("hide")
$("#cancel_export").show()
$("#row-message").addClass("hide")
clearTimeout(clearTimeOut)
download_animation = ->
$(".download-animation").on "click", ->
src_id = $(this).attr("data-download-target")
NProgress.start()
download($("#{src_id}").val())
setTimeout( ->
NProgress.done()
, 4000)
switch_to_archive_tab = ->
$("#switch_archive").on "click", ->
$(".nav-tab-archives").tab('show')
auto_check_compare_status = (compare_id, tries) ->
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
if response.compares[0].status is "Completed"
$("#row-gif-url").removeClass("hide")
$("#row-mp4-url").removeClass("hide")
$("#row-message").addClass("hide")
else if response.compares[0].status is "Processing" && tries < 10
clearTimeOut = setTimeout( ->
auto_check_compare_status(response.compares[0].id, tries++)
, 10000)
settings =
cache: false
data: {}
dataType: 'json'
error: onError
success: onSuccess
type: 'GET'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/compares/#{compare_id}?api_id=#{Evercam.User.api_id}&api_key=#{Evercam.User.api_key}"
sendRequest(settings)
window.initializeCompareTab = ->
getFirstLastImages("compare_before", "/oldest", false, true)
getFirstLastImages("compare_after", "/latest", false, false)
handleTabOpen()
removeCurrentDateHighlight()
export_compare()
cancelForm()
clickToCopy()
download_animation()
switch_to_archive_tab()
setCompareEmbedCodeTitle()
$('#calendar-before').datetimepicker
format: 'm/d/Y H:m'
id: 'before-calendar'
onSelectTime: (dp, $input) ->
$("#txtbefore").val($input.val())
val = getQueryStringByName("after")
url = "#{Evercam.request.rootpath}/compare?before=#{moment.utc($input.val()).toISOString()}"
if val isnt null
url = "#{url}&after=#{val}"
if history.replaceState
window.history.replaceState({}, '', url)
getFirstLastImages("compare_before", "/#{(new Date($input.val())) / 1000}/nearest", true, false)
onChangeMonth: (dp, $input) ->
xhrChangeMonth.abort()
month = dp.getMonth() + 1
year = dp.getFullYear()
HighlightDaysInMonth("before-calendar", year, month)
removeCurrentHourHighlight("before-calendar")
showBeforeAfterLoadingAnimation("before-calendar")
onSelectDate: (ct, $i) ->
month = ct.getMonth() + 1
year = ct.getFullYear()
date = ct.getDate()
HighlightSnapshotHour("before-calendar", year, month, date)
HighlightDaysInMonth("before-calendar", year, month)
onShow: (current_time, $input) ->
month = current_time.getMonth() + 1
year = current_time.getFullYear()
removeCurrentHourHighlight("before-calendar")
HighlightDaysInMonth("before-calendar", year, month)
showBeforeAfterLoadingAnimation("before-calendar")
$('#calendar-after').datetimepicker
format: 'm/d/Y H:m'
id: 'after-calendar'
onSelectTime: (dp, $input) ->
$("#txtafter").val($input.val())
val = getQueryStringByName("before")
url = "#{Evercam.request.rootpath}/compare"
if val isnt null
url = "#{url}?before=#{val}&after=#{moment.utc($input.val()).toISOString()}"
else
url = "#{url}?after=#{moment.utc($input.val()).toISOString()}"
if history.replaceState
window.history.replaceState({}, '', url)
getFirstLastImages("compare_after", "/#{(new Date($input.val())) / 1000}/nearest", true, false)
onChangeMonth: (dp, $input) ->
xhrChangeMonth.abort()
month = dp.getMonth() + 1
year = dp.getFullYear()
removeCurrentHourHighlight("after-calendar")
HighlightDaysInMonth("after-calendar", year, month)
showBeforeAfterLoadingAnimation("after-calendar")
onSelectDate: (ct, $i) ->
month = ct.getMonth() + 1
year = ct.getFullYear()
date = ct.getDate()
HighlightSnapshotHour("after-calendar", year, month, date)
HighlightDaysInMonth("after-calendar", year, month)
onShow: (current_time, $input) ->
month = current_time.getMonth() + 1
year = current_time.getFullYear()
removeCurrentHourHighlight("after-calendar")
HighlightDaysInMonth("after-calendar", year, month)
showBeforeAfterLoadingAnimation("after-calendar")
| true | imagesCompare = undefined
clearTimeOut = null
xhrChangeMonth = null
window.sendRequest = (settings) ->
token = $('meta[name="csrf-token"]')
if token.size() > 0
headers =
"X-CSRF-Token": token.attr("content")
settings.headers = headers
xhrChangeMonth = $.ajax(settings)
initCompare = ->
imagesCompareElement = $('.js-img-compare').imagesCompare()
imagesCompare = imagesCompareElement.data('imagesCompare')
events = imagesCompare.events()
imagesCompare.on events.changed, (event) ->
true
getFirstLastImages = (image_id, query_string, reload, setDate) ->
data =
api_id: Evercam.User.api_id
api_key: Evercam.User.api_key
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
snapshot = response
if query_string.indexOf("nearest") > 0 && response.snapshots.length > 0
snapshot = response.snapshots[0]
if snapshot.data isnt undefined
$("##{image_id}").attr("src", snapshot.data)
$("##{image_id}").attr("timestamp", snapshot.created_at)
if setDate is true && query_string.indexOf("nearest") < 0
d = new Date(snapshot.created_at*1000)
before_month = d.getUTCMonth()+1
before_year = d.getUTCFullYear()
camera_created_date = new Date(Evercam.Camera.created_at*1000)
camera_created_month = camera_created_date.getUTCMonth()+1
camera_created_year = camera_created_date.getUTCFullYear()
string_date = "#{before_month}/#{d.getUTCDate()}/#{before_year}"
camera_created_at = "#{camera_created_year}/#{camera_created_month}/#{camera_created_date.getUTCDate()}"
$('#calendar-before').datetimepicker({value: string_date, minDate: camera_created_at, yearStart: camera_created_year})
$('#calendar-after').datetimepicker({minDate: camera_created_at, yearStart: camera_created_year})
if setDate is false && query_string.indexOf("nearest") < 0
date_after = new Date(snapshot.created_at*1000)
after_month = date_after.getUTCMonth()+1
after_year = date_after.getUTCFullYear()
string_after_date = "#{after_year}/#{after_month}/#{date_after.getUTCDate()}"
$('#calendar-before').datetimepicker({maxDate: string_after_date, yearEnd: after_year})
$('#calendar-after').datetimepicker({maxDate: string_after_date, yearEnd: after_year})
initCompare() if reload
else
Notification.show("No image found")
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
type: 'GET'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots#{query_string}"
sendRequest(settings)
handleTabOpen = ->
$('.nav-tab-compare').on 'shown.bs.tab', ->
initCompare()
updateURL()
updateURL = ->
url = "#{Evercam.request.rootpath}/compare"
query_string = ""
if $("#txtbefore").val() isnt ""
query_string = "?before=#{moment.utc($("#txtbefore").val()).toISOString()}"
if $("#txtafter").val() isnt ""
if query_string is ""
query_string = "?after=#{moment.utc($("#txtafter").val()).toISOString()}"
else
query_string = "#{query_string}&after=#{moment.utc($("#txtafter").val()).toISOString()}"
url = "#{url}#{query_string}"
if history.replaceState
window.history.replaceState({}, '', url)
getQueryStringByName = (name) ->
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
results = regex.exec(location.search)
if results == null
null
else
decodeURIComponent(results[1].replace(/\+/g, ' '))
clickToCopy = ->
clipboard = new Clipboard('.copy-url-icon')
clipboard.on 'success', (e) ->
$('.bb-alert').width '100px'
Notification.show 'Copied!'
copyToClipboard = (elem) ->
targetId = '_hiddenCopyText_'
isInput = elem.tagName == 'INPUT' or elem.tagName == 'TEXTAREA'
origSelectionStart = undefined
origSelectionEnd = undefined
if isInput
target = elem
origSelectionStart = elem.selectionStart
origSelectionEnd = elem.selectionEnd
else
target = document.getElementById(targetId)
if !target
target = document.createElement('textarea')
target.style.position = 'absolute'
target.style.left = '-9999px'
target.style.top = '0'
target.id = targetId
document.body.appendChild target
target.textContent = elem.textContent
currentFocus = document.activeElement
target.focus()
target.setSelectionRange 0, target.value.length
succeed = undefined
try
succeed = document.execCommand('copy')
catch e
succeed = false
if currentFocus and typeof currentFocus.focus == 'function'
currentFocus.focus()
if isInput
elem.setSelectionRange origSelectionStart, origSelectionEnd
else
target.textContent = ''
succeed
HighlightDaysInMonth = (query_string, year, month) ->
data = {}
data.api_id = Evercam.User.api_id
data.api_key = Evercam.User.api_key
onError = (response, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
removeCurrentDateHighlight(query_string)
removeCurrentHourHighlight(query_string)
hideBeforeAfterLoadingAnimation(query_string)
for day in response.days
HighlightBeforeAfterDay(query_string, year, month, day)
settings =
cache: true
data: data
dataType: 'json'
error: onError
success: onSuccess
contentType: "application/json charset=utf-8"
type: 'GET'
url: "#{Evercam.MEDIA_API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots/#{year}/#{month}/days"
sendRequest(settings)
HighlightBeforeAfterDay = (query_string, before_year, before_month, before_day) ->
beforeDays = $("##{query_string} .xdsoft_datepicker table td[class*='xdsoft_date'] div")
beforeDays.each ->
beforeDay = $(this)
if !beforeDay.parent().hasClass('xdsoft_other_month')
iDay = parseInt(beforeDay.text())
if before_day == iDay
beforeDay.parent().addClass 'xdsoft_current'
HighlightSnapshotHour = (query_string, year, month, date) ->
data = {}
data.api_id = Evercam.User.api_id
data.api_key = Evercam.User.api_key
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
removeCurrentHourHighlight(query_string)
hideBeforeAfterLoadingAnimation(query_string)
for hour in response.hours
HighlightBeforeAfterHour(query_string, year, month, date, hour)
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
contentType: "application/json charset=utf-8"
type: 'GET'
timeout: 15000
url: "#{Evercam.MEDIA_API_URL}cameras/#{Evercam.Camera.id}/recordings/snapshots/#{year}/#{(month)}/#{date}/hours"
sendRequest(settings)
HighlightBeforeAfterHour = (query_string, before_year, before_month, before_day, before_hour) ->
beforeHours = $("##{query_string} .xdsoft_timepicker [class*='xdsoft_time']")
beforeHours.each ->
beforeHour = $(this)
iHour = parseInt(beforeHour.text())
if before_hour == iHour
beforeHour.addClass 'xdsoft_current'
removeCurrentHourHighlight = (query_string) ->
beforeHours = $("##{query_string} .xdsoft_timepicker [class*='xdsoft_time']")
beforeHours.removeClass 'xdsoft_current'
removeCurrentDateHighlight = (query_string) ->
beforeDays = $("##{query_string} .xdsoft_datepicker table td[class*='xdsoft_date']")
beforeDays.removeClass 'xdsoft_current'
showBeforeAfterLoadingAnimation = (query_string) ->
$("##{query_string} .xdsoft_datepicker").addClass 'opacitypoint5'
$("##{query_string} .xdsoft_timepicker").addClass 'opacitypoint5'
hideBeforeAfterLoadingAnimation = (query_string) ->
$("##{query_string} .xdsoft_datepicker").removeClass 'opacitypoint5'
$("##{query_string} .xdsoft_timepicker").removeClass 'opacitypoint5'
setCompareEmbedCodeTitle = ->
$("#div-embed-code").on "click", (e)->
$(".export-buttons #cancel_export").html 'Close'
after_image_time = $("#compare_after").attr("timestamp")
before_image_time = $("#compare_before").attr("timestamp")
if after_image_time && before_image_time isnt undefined
day_before = moment.utc(before_image_time*1000).format("Do")
day_after = moment.utc(after_image_time*1000).format("Do")
month_before = moment.utc(before_image_time*1000).format("MMM")
month_after = moment.utc(after_image_time*1000).format("MMM")
$("#export-compare-title").val("#{day_before} #{month_before} to #{day_after} #{month_after}")
e.stopPropagation()
$('#export-compare-modal').modal 'show'
else
e.stopPropagation()
$(".bb-alert").removeClass("alert-info").addClass("alert-danger")
$(".bb-alert").css "width", "410px"
Notification.show("Unable to export compare, before/after image is not available.")
export_compare = ->
$("#export_compare_button").on "click", ->
$("#spn-success-export").removeClass("alert-info").addClass("alert-danger")
name = $("#export-compare-title").val()
if name is ""
$("#spn-success-export").text("Please enter export name.").removeClass("hide")
return false
button = $(this)
button.prop("disabled", true)
$("#row-animation").removeClass("hide")
after = " #{convert_timestamp_to_path($("#compare_after").attr("timestamp"))}"
before = " #{convert_timestamp_to_path($("#compare_before").attr("timestamp"))}"
embed_code = "<div id='evercam-compare'></div><script src='#{window.location.origin}/assets/evercam_compare.js' class='#{Evercam.Camera.id}#{before}#{after} autoplay'></script>"
$("#txtEmbedCode").val(embed_code)
data =
api_id: Evercam.User.api_id
api_key: Evercam.User.api_key
name: PI:NAME:<NAME>END_PI
before: $("#compare_before").attr("timestamp")
before_image: $("#compare_before").attr("src")
after: $("#compare_after").attr("timestamp")
after_image: $("#compare_after").attr("src")
embed: embed_code
create_animation: true
onError = (jqXHR, status, error) ->
$("#spn-success-export").text("Failed to export compare.").removeClass("hide")
$("#row-animation").addClass("hide")
button.prop("disabled", false)
onSuccess = (response, status, jqXHR) ->
button.hide()
$(".export-buttons #cancel_export").html 'Ok'
$("#row-animation").addClass("hide")
$("#row-textarea").removeClass("hide")
$("#row-message").removeClass("hide")
$("#spn-success-export").addClass("alert-info").removeClass("alert-danger").addClass("hide")
$("#gif_url").val(response.compares[0].gif_url.replace("media.evercam.io", "api.evercam.io"))
$("#mp4_url").val(response.compares[0].mp4_url.replace("media.evercam.io", "api.evercam.io"))
window.on_export_compare()
clearTimeOut = setTimeout( ->
auto_check_compare_status(response.compares[0].id, 0)
, 10000)
settings =
cache: false
data: data
dataType: 'json'
error: onError
success: onSuccess
type: 'POST'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/compares"
sendRequest(settings)
convert_timestamp_to_path = (timestamp) ->
timestamp_to_int = parseInt(timestamp)
moment.utc(timestamp_to_int*1000).format('YYYY/MM/DD/HH_mm_ss')
cancelForm = ->
$('#export-compare-modal').on 'hide.bs.modal', ->
clean_form()
$('#export-compare-modal').on 'show.bs.modal', ->
clean_form()
clean_form = ->
$("#txtEmbedCode").val("")
$("#row-textarea").addClass("hide")
$("#spn-success-export").addClass("hide")
$("#export_compare_button").prop("disabled", false)
$("#export_compare_button").show()
$("#row-gif-url").addClass("hide")
$("#row-mp4-url").addClass("hide")
$("#cancel_export").show()
$("#row-message").addClass("hide")
clearTimeout(clearTimeOut)
download_animation = ->
$(".download-animation").on "click", ->
src_id = $(this).attr("data-download-target")
NProgress.start()
download($("#{src_id}").val())
setTimeout( ->
NProgress.done()
, 4000)
switch_to_archive_tab = ->
$("#switch_archive").on "click", ->
$(".nav-tab-archives").tab('show')
auto_check_compare_status = (compare_id, tries) ->
onError = (jqXHR, status, error) ->
false
onSuccess = (response, status, jqXHR) ->
if response.compares[0].status is "Completed"
$("#row-gif-url").removeClass("hide")
$("#row-mp4-url").removeClass("hide")
$("#row-message").addClass("hide")
else if response.compares[0].status is "Processing" && tries < 10
clearTimeOut = setTimeout( ->
auto_check_compare_status(response.compares[0].id, tries++)
, 10000)
settings =
cache: false
data: {}
dataType: 'json'
error: onError
success: onSuccess
type: 'GET'
url: "#{Evercam.API_URL}cameras/#{Evercam.Camera.id}/compares/#{compare_id}?api_id=#{Evercam.User.api_id}&api_key=#{Evercam.User.api_key}"
sendRequest(settings)
window.initializeCompareTab = ->
getFirstLastImages("compare_before", "/oldest", false, true)
getFirstLastImages("compare_after", "/latest", false, false)
handleTabOpen()
removeCurrentDateHighlight()
export_compare()
cancelForm()
clickToCopy()
download_animation()
switch_to_archive_tab()
setCompareEmbedCodeTitle()
$('#calendar-before').datetimepicker
format: 'm/d/Y H:m'
id: 'before-calendar'
onSelectTime: (dp, $input) ->
$("#txtbefore").val($input.val())
val = getQueryStringByName("after")
url = "#{Evercam.request.rootpath}/compare?before=#{moment.utc($input.val()).toISOString()}"
if val isnt null
url = "#{url}&after=#{val}"
if history.replaceState
window.history.replaceState({}, '', url)
getFirstLastImages("compare_before", "/#{(new Date($input.val())) / 1000}/nearest", true, false)
onChangeMonth: (dp, $input) ->
xhrChangeMonth.abort()
month = dp.getMonth() + 1
year = dp.getFullYear()
HighlightDaysInMonth("before-calendar", year, month)
removeCurrentHourHighlight("before-calendar")
showBeforeAfterLoadingAnimation("before-calendar")
onSelectDate: (ct, $i) ->
month = ct.getMonth() + 1
year = ct.getFullYear()
date = ct.getDate()
HighlightSnapshotHour("before-calendar", year, month, date)
HighlightDaysInMonth("before-calendar", year, month)
onShow: (current_time, $input) ->
month = current_time.getMonth() + 1
year = current_time.getFullYear()
removeCurrentHourHighlight("before-calendar")
HighlightDaysInMonth("before-calendar", year, month)
showBeforeAfterLoadingAnimation("before-calendar")
$('#calendar-after').datetimepicker
format: 'm/d/Y H:m'
id: 'after-calendar'
onSelectTime: (dp, $input) ->
$("#txtafter").val($input.val())
val = getQueryStringByName("before")
url = "#{Evercam.request.rootpath}/compare"
if val isnt null
url = "#{url}?before=#{val}&after=#{moment.utc($input.val()).toISOString()}"
else
url = "#{url}?after=#{moment.utc($input.val()).toISOString()}"
if history.replaceState
window.history.replaceState({}, '', url)
getFirstLastImages("compare_after", "/#{(new Date($input.val())) / 1000}/nearest", true, false)
onChangeMonth: (dp, $input) ->
xhrChangeMonth.abort()
month = dp.getMonth() + 1
year = dp.getFullYear()
removeCurrentHourHighlight("after-calendar")
HighlightDaysInMonth("after-calendar", year, month)
showBeforeAfterLoadingAnimation("after-calendar")
onSelectDate: (ct, $i) ->
month = ct.getMonth() + 1
year = ct.getFullYear()
date = ct.getDate()
HighlightSnapshotHour("after-calendar", year, month, date)
HighlightDaysInMonth("after-calendar", year, month)
onShow: (current_time, $input) ->
month = current_time.getMonth() + 1
year = current_time.getFullYear()
removeCurrentHourHighlight("after-calendar")
HighlightDaysInMonth("after-calendar", year, month)
showBeforeAfterLoadingAnimation("after-calendar")
|
[
{
"context": "# @file hslToRgb.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice",
"end": 60,
"score": 0.9998040199279785,
"start": 46,
"tag": "NAME",
"value": "Taylor Siviter"
},
{
"context": "B.\n# Code adapted from:\n# @see https://git... | src/util/hslToRgb.coffee | siviter-t/lampyridae.coffee | 4 | # @file hslToRgb.coffee
# @Copyright (c) 2016 Taylor Siviter
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'lampyridae'
### Converts HSL colour to RGB.
# Code adapted from:
# @see https://github.com/bgrins/TinyColor
# @see http://serennu.com/colour/rgbtohsl.php
#
# @param h [Number] The hue [0, 360]
# @param s [Number] The saturation [0, 100]%
# @param l [Number] The lightness [0, 100]%
# @return [Array] The RGB representation [0, 255]
###
Lampyridae.hslToRgb = (h, s, l) ->
h = parseFloat(h) / 360.0
s = parseFloat(s) / 100.0
l = parseFloat(l) / 100.0
if s == 0 then r = g = b = l
else
hueToRgb = (p, q, t) ->
if t < 0 then t += 1
if t > 1 then t -= 1
if t < 1 / 6 then return p + (q - p) * 6.0 * t
if t < 1 / 2 then return q
if t < 2 / 3 then return p + (q - p) * (4 - 6.0 * t)
return p
q = if l < 0.5 then l * (1 + s) else l + s - (l * s)
p = 2 * l - q
r = hueToRgb p, q, h + 1 / 3
g = hueToRgb p, q, h
b = hueToRgb p, q, h - 1 / 3
return [Math.round(255 * r), Math.round(255 * g), Math.round(255 * b)]
# end function Lampyridae.hslToRgb
module.exports = Lampyridae.hslToRgb | 91637 | # @file hslToRgb.coffee
# @Copyright (c) 2016 <NAME>
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'lampyridae'
### Converts HSL colour to RGB.
# Code adapted from:
# @see https://github.com/bgrins/TinyColor
# @see http://serennu.com/colour/rgbtohsl.php
#
# @param h [Number] The hue [0, 360]
# @param s [Number] The saturation [0, 100]%
# @param l [Number] The lightness [0, 100]%
# @return [Array] The RGB representation [0, 255]
###
Lampyridae.hslToRgb = (h, s, l) ->
h = parseFloat(h) / 360.0
s = parseFloat(s) / 100.0
l = parseFloat(l) / 100.0
if s == 0 then r = g = b = l
else
hueToRgb = (p, q, t) ->
if t < 0 then t += 1
if t > 1 then t -= 1
if t < 1 / 6 then return p + (q - p) * 6.0 * t
if t < 1 / 2 then return q
if t < 2 / 3 then return p + (q - p) * (4 - 6.0 * t)
return p
q = if l < 0.5 then l * (1 + s) else l + s - (l * s)
p = 2 * l - q
r = hueToRgb p, q, h + 1 / 3
g = hueToRgb p, q, h
b = hueToRgb p, q, h - 1 / 3
return [Math.round(255 * r), Math.round(255 * g), Math.round(255 * b)]
# end function Lampyridae.hslToRgb
module.exports = Lampyridae.hslToRgb | true | # @file hslToRgb.coffee
# @Copyright (c) 2016 PI:NAME:<NAME>END_PI
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'lampyridae'
### Converts HSL colour to RGB.
# Code adapted from:
# @see https://github.com/bgrins/TinyColor
# @see http://serennu.com/colour/rgbtohsl.php
#
# @param h [Number] The hue [0, 360]
# @param s [Number] The saturation [0, 100]%
# @param l [Number] The lightness [0, 100]%
# @return [Array] The RGB representation [0, 255]
###
Lampyridae.hslToRgb = (h, s, l) ->
h = parseFloat(h) / 360.0
s = parseFloat(s) / 100.0
l = parseFloat(l) / 100.0
if s == 0 then r = g = b = l
else
hueToRgb = (p, q, t) ->
if t < 0 then t += 1
if t > 1 then t -= 1
if t < 1 / 6 then return p + (q - p) * 6.0 * t
if t < 1 / 2 then return q
if t < 2 / 3 then return p + (q - p) * (4 - 6.0 * t)
return p
q = if l < 0.5 then l * (1 + s) else l + s - (l * s)
p = 2 * l - q
r = hueToRgb p, q, h + 1 / 3
g = hueToRgb p, q, h
b = hueToRgb p, q, h - 1 / 3
return [Math.round(255 * r), Math.round(255 * g), Math.round(255 * b)]
# end function Lampyridae.hslToRgb
module.exports = Lampyridae.hslToRgb |
[
{
"context": "<query> against docs.couchbase.com\n#\n# Author:\n# Brian Shumate <brian@couchbase.com>\n\nmodule.exports = (robot) -",
"end": 247,
"score": 0.999872088432312,
"start": 234,
"tag": "NAME",
"value": "Brian Shumate"
},
{
"context": "docs.couchbase.com\n#\n# Author:\n# ... | hubot-scripts/docme.coffee | balanced-ops/wubot | 0 | # Description:
# Returns URL to first Google hit on docs site for the query
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot doc me <query> - Googles <query> against docs.couchbase.com
#
# Author:
# Brian Shumate <brian@couchbase.com>
module.exports = (robot) ->
robot.respond /(doc)( me)? (.*)/i, (msg) ->
googleMe msg, msg.match[3], (url) ->
msg.send url
googleMe = (msg, query, cb) ->
site = 'site:+docs.couchbase.com+'
msg.http('http://www.google.com/search')
.query(q: site + query)
.get() (err, res, body) ->
cb body.match(/class="r"><a href="\/url\?q=([^"]*)(&sa.*)">/)?[1] || "Sorry, no results for '#{query}'"
| 11330 | # Description:
# Returns URL to first Google hit on docs site for the query
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot doc me <query> - Googles <query> against docs.couchbase.com
#
# Author:
# <NAME> <<EMAIL>>
module.exports = (robot) ->
robot.respond /(doc)( me)? (.*)/i, (msg) ->
googleMe msg, msg.match[3], (url) ->
msg.send url
googleMe = (msg, query, cb) ->
site = 'site:+docs.couchbase.com+'
msg.http('http://www.google.com/search')
.query(q: site + query)
.get() (err, res, body) ->
cb body.match(/class="r"><a href="\/url\?q=([^"]*)(&sa.*)">/)?[1] || "Sorry, no results for '#{query}'"
| true | # Description:
# Returns URL to first Google hit on docs site for the query
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot doc me <query> - Googles <query> against docs.couchbase.com
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
robot.respond /(doc)( me)? (.*)/i, (msg) ->
googleMe msg, msg.match[3], (url) ->
msg.send url
googleMe = (msg, query, cb) ->
site = 'site:+docs.couchbase.com+'
msg.http('http://www.google.com/search')
.query(q: site + query)
.get() (err, res, body) ->
cb body.match(/class="r"><a href="\/url\?q=([^"]*)(&sa.*)">/)?[1] || "Sorry, no results for '#{query}'"
|
[
{
"context": "Welcome:\n tabTitle: \"Benvenuto\"\n subtitle: {\n text1: \"Un editor di test hack",
"end": 31,
"score": 0.8217002153396606,
"start": 22,
"tag": "NAME",
"value": "Benvenuto"
}
] | def/it/welcome.cson | dominicus75/atom-i18n | 1 | Welcome:
tabTitle: "Benvenuto"
subtitle: {
text1: "Un editor di test hackerabile per il 21"
superscript: "o"
text2: " secolo"
}
help: {
forHelpVisit: "Per supporto, visita"
atomDocs: {
text1: "La "
link: "documentazione di Atom"
text2: " per Guide e consultazione delle API."
_template: "${text1}<a>${link}</a>${text2}"
}
atomForum: {
text1: "Il forum di Atom su "
link: "discuss.atom.io"
text2: "" # optional
_template: "${text1}<a>${link}</a>${text2}"
}
atomOrg: {
text1: "Il sito "
link: "Atom org"
text2: ". Dove si possono trovare tutti i pacchetti per Atom creati con GitHub."
_template: "${text1}<a>${link}</a>${text2}"
}
}
showWelcomeGuide: "Mostra la Guida di benvenuto all'avvio di Atom"
| 163591 | Welcome:
tabTitle: "<NAME>"
subtitle: {
text1: "Un editor di test hackerabile per il 21"
superscript: "o"
text2: " secolo"
}
help: {
forHelpVisit: "Per supporto, visita"
atomDocs: {
text1: "La "
link: "documentazione di Atom"
text2: " per Guide e consultazione delle API."
_template: "${text1}<a>${link}</a>${text2}"
}
atomForum: {
text1: "Il forum di Atom su "
link: "discuss.atom.io"
text2: "" # optional
_template: "${text1}<a>${link}</a>${text2}"
}
atomOrg: {
text1: "Il sito "
link: "Atom org"
text2: ". Dove si possono trovare tutti i pacchetti per Atom creati con GitHub."
_template: "${text1}<a>${link}</a>${text2}"
}
}
showWelcomeGuide: "Mostra la Guida di benvenuto all'avvio di Atom"
| true | Welcome:
tabTitle: "PI:NAME:<NAME>END_PI"
subtitle: {
text1: "Un editor di test hackerabile per il 21"
superscript: "o"
text2: " secolo"
}
help: {
forHelpVisit: "Per supporto, visita"
atomDocs: {
text1: "La "
link: "documentazione di Atom"
text2: " per Guide e consultazione delle API."
_template: "${text1}<a>${link}</a>${text2}"
}
atomForum: {
text1: "Il forum di Atom su "
link: "discuss.atom.io"
text2: "" # optional
_template: "${text1}<a>${link}</a>${text2}"
}
atomOrg: {
text1: "Il sito "
link: "Atom org"
text2: ". Dove si possono trovare tutti i pacchetti per Atom creati con GitHub."
_template: "${text1}<a>${link}</a>${text2}"
}
}
showWelcomeGuide: "Mostra la Guida di benvenuto all'avvio di Atom"
|
[
{
"context": "a\n songs = [\n {\n artist:\n alias: 'Aygahzu'\n avatar: 'https://d1hmps6uc7xmb3.cloudfro",
"end": 295,
"score": 0.9965378046035767,
"start": 288,
"tag": "NAME",
"value": "Aygahzu"
},
{
"context": "mments: [\n {\n 'author': 'alias'... | app/js/features/songs/song_service.coffee | 17thDimension/ionic-song-a-day | 0 | ###
A simple example service that returns some data.
###
angular.module("ionicstarter")
.factory "SongService", ->
# Might use a resource here that returns a JSON array
# coffeelint: disable=max_line_length
# Some fake testing data
songs = [
{
artist:
alias: 'Aygahzu'
avatar: 'https://d1hmps6uc7xmb3.cloudfront.net/1422500290650-4wy6hFh9nIt2q0m0.jpg'
id: 0
comments: [
{
'author': 'alias': 'Wally'
'comment': 'This is incredible. Feels like I\'m walking on clouds underground'
'timestamp': '2014-07-05T20:58:03.090410'
}
{
'author': 'alias': 'archiecarey4'
'comment': 'mmmmmmmmm\n'
'timestamp': '2014-07-05T21:31:23.623360'
}
]
info: 'Amor'
key: 523
media:
src: 'http://audio.chirbit.com/songaday_1404583242.mp3'
type: 'audio/mpeg'
timestamp: '2014-07-05T07:12:54.666980'
title: 'Yurhn'
user_id: 'google:107994261263995453602'
}
{
artist:
alias: 'Aygahzu'
avatar: 'https://d1hmps6uc7xmb3.cloudfront.net/1422500290650-4wy6hFh9nIt2q0m0.jpg'
id: 1
comments: [
{
'author': 'alias': 'Wally'
'comment': 'This is incredible. Feels like I\'m walking on clouds underground'
'timestamp': '2014-07-05T20:58:03.090410'
}
{
'author': 'alias': 'archiecarey4'
'comment': 'mmmmmmmmm\n'
'timestamp': '2014-07-05T21:31:23.623360'
}
]
info: 'viento'
key: 523
media:
src: 'http://audio.chirbit.com/songaday_1404583242.mp3'
type: 'audio/mpeg'
timestamp: '2014-07-05T07:12:54.666980'
title: 'sauce'
user_id: 'google:107994261263995453602'
}
]
all: ->
songs
get: (songId) ->
# Simple index lookup
songs[songId]
| 160094 | ###
A simple example service that returns some data.
###
angular.module("ionicstarter")
.factory "SongService", ->
# Might use a resource here that returns a JSON array
# coffeelint: disable=max_line_length
# Some fake testing data
songs = [
{
artist:
alias: '<NAME>'
avatar: 'https://d1hmps6uc7xmb3.cloudfront.net/1422500290650-4wy6hFh9nIt2q0m0.jpg'
id: 0
comments: [
{
'author': 'alias': '<NAME>'
'comment': 'This is incredible. Feels like I\'m walking on clouds underground'
'timestamp': '2014-07-05T20:58:03.090410'
}
{
'author': 'alias': 'archiecarey4'
'comment': 'mmmmmmmmm\n'
'timestamp': '2014-07-05T21:31:23.623360'
}
]
info: 'Amor'
key: <KEY>
media:
src: 'http://audio.chirbit.com/songaday_1404583242.mp3'
type: 'audio/mpeg'
timestamp: '2014-07-05T07:12:54.666980'
title: 'Yurhn'
user_id: 'google:107994261263995453602'
}
{
artist:
alias: '<NAME>'
avatar: 'https://d1hmps6uc7xmb3.cloudfront.net/1422500290650-4wy6hFh9nIt2q0m0.jpg'
id: 1
comments: [
{
'author': 'alias': '<NAME>'
'comment': 'This is incredible. Feels like I\'m walking on clouds underground'
'timestamp': '2014-07-05T20:58:03.090410'
}
{
'author': 'alias': 'archiecarey4'
'comment': 'mmmmmmmmm\n'
'timestamp': '2014-07-05T21:31:23.623360'
}
]
info: 'viento'
key: <KEY>
media:
src: 'http://audio.chirbit.com/songaday_1404583242.mp3'
type: 'audio/mpeg'
timestamp: '2014-07-05T07:12:54.666980'
title: 'sauce'
user_id: 'google:107994261263995453602'
}
]
all: ->
songs
get: (songId) ->
# Simple index lookup
songs[songId]
| true | ###
A simple example service that returns some data.
###
angular.module("ionicstarter")
.factory "SongService", ->
# Might use a resource here that returns a JSON array
# coffeelint: disable=max_line_length
# Some fake testing data
songs = [
{
artist:
alias: 'PI:NAME:<NAME>END_PI'
avatar: 'https://d1hmps6uc7xmb3.cloudfront.net/1422500290650-4wy6hFh9nIt2q0m0.jpg'
id: 0
comments: [
{
'author': 'alias': 'PI:NAME:<NAME>END_PI'
'comment': 'This is incredible. Feels like I\'m walking on clouds underground'
'timestamp': '2014-07-05T20:58:03.090410'
}
{
'author': 'alias': 'archiecarey4'
'comment': 'mmmmmmmmm\n'
'timestamp': '2014-07-05T21:31:23.623360'
}
]
info: 'Amor'
key: PI:KEY:<KEY>END_PI
media:
src: 'http://audio.chirbit.com/songaday_1404583242.mp3'
type: 'audio/mpeg'
timestamp: '2014-07-05T07:12:54.666980'
title: 'Yurhn'
user_id: 'google:107994261263995453602'
}
{
artist:
alias: 'PI:NAME:<NAME>END_PI'
avatar: 'https://d1hmps6uc7xmb3.cloudfront.net/1422500290650-4wy6hFh9nIt2q0m0.jpg'
id: 1
comments: [
{
'author': 'alias': 'PI:NAME:<NAME>END_PI'
'comment': 'This is incredible. Feels like I\'m walking on clouds underground'
'timestamp': '2014-07-05T20:58:03.090410'
}
{
'author': 'alias': 'archiecarey4'
'comment': 'mmmmmmmmm\n'
'timestamp': '2014-07-05T21:31:23.623360'
}
]
info: 'viento'
key: PI:KEY:<KEY>END_PI
media:
src: 'http://audio.chirbit.com/songaday_1404583242.mp3'
type: 'audio/mpeg'
timestamp: '2014-07-05T07:12:54.666980'
title: 'sauce'
user_id: 'google:107994261263995453602'
}
]
all: ->
songs
get: (songId) ->
# Simple index lookup
songs[songId]
|
[
{
"context": "el.coffee: Github label class\n#\n# Copyright © 2014 Matthew Taylor. All rights reserved\n#\n\n# Initiate class\nclass La",
"end": 72,
"score": 0.9997609257698059,
"start": 58,
"tag": "NAME",
"value": "Matthew Taylor"
}
] | src/octonode/label.coffee | noblejasper/octonode | 0 | #
# label.coffee: Github label class
#
# Copyright © 2014 Matthew Taylor. All rights reserved
#
# Initiate class
class Label
constructor: (@repo, @name, @client) ->
# Get a single label
# '/repos/pksunkara/hub/labels/todo' GET
info: (cb) ->
@client.get encodeURI("/repos/#{@repo}/labels/#{@name}"), (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Label info error")) else cb null, b, h
# Edit a label for a repository
# '/repos/pksunkara/hub/labels/todo' PATCH
update: (obj, cb) ->
@client.post "/repos/#{@repo}/labels/#{@name}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Label update error")) else cb null, b, h
# Delete a label for a repository
# '/repos/pksunkara/hub/labels/todo' DELETE
delete: (cb) ->
@client.del encodeURI("/repos/#{@repo}/labels/#{@name}"), {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Label delete error")) else cb null, b, h
# Export module
module.exports = Label
| 74837 | #
# label.coffee: Github label class
#
# Copyright © 2014 <NAME>. All rights reserved
#
# Initiate class
class Label
constructor: (@repo, @name, @client) ->
# Get a single label
# '/repos/pksunkara/hub/labels/todo' GET
info: (cb) ->
@client.get encodeURI("/repos/#{@repo}/labels/#{@name}"), (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Label info error")) else cb null, b, h
# Edit a label for a repository
# '/repos/pksunkara/hub/labels/todo' PATCH
update: (obj, cb) ->
@client.post "/repos/#{@repo}/labels/#{@name}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Label update error")) else cb null, b, h
# Delete a label for a repository
# '/repos/pksunkara/hub/labels/todo' DELETE
delete: (cb) ->
@client.del encodeURI("/repos/#{@repo}/labels/#{@name}"), {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Label delete error")) else cb null, b, h
# Export module
module.exports = Label
| true | #
# label.coffee: Github label class
#
# Copyright © 2014 PI:NAME:<NAME>END_PI. All rights reserved
#
# Initiate class
class Label
constructor: (@repo, @name, @client) ->
# Get a single label
# '/repos/pksunkara/hub/labels/todo' GET
info: (cb) ->
@client.get encodeURI("/repos/#{@repo}/labels/#{@name}"), (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Label info error")) else cb null, b, h
# Edit a label for a repository
# '/repos/pksunkara/hub/labels/todo' PATCH
update: (obj, cb) ->
@client.post "/repos/#{@repo}/labels/#{@name}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Label update error")) else cb null, b, h
# Delete a label for a repository
# '/repos/pksunkara/hub/labels/todo' DELETE
delete: (cb) ->
@client.del encodeURI("/repos/#{@repo}/labels/#{@name}"), {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Label delete error")) else cb null, b, h
# Export module
module.exports = Label
|
[
{
"context": " cb = cb or ->\n voice_map =\n male: 'Alex'\n female: 'Kathy'\n voice = voice_map[",
"end": 269,
"score": 0.9996880888938904,
"start": 265,
"tag": "NAME",
"value": "Alex"
},
{
"context": "voice_map =\n male: 'Alex'\n female: 'Kath... | lib/notifiers/voice.coffee | hybridknight/notifyme | 1 | say = require 'say'
Notifer = require './notifier'
module.exports = do ->
return class VoiceNotifier extends Notifer
name: 'voice'
should_be_used: (argv)-> argv.voice
notify: (argv, message, cb)->
cb = cb or ->
voice_map =
male: 'Alex'
female: 'Kathy'
voice = voice_map[argv.voice] || 'Kathy'
say.speak voice, message, cb
| 15895 | say = require 'say'
Notifer = require './notifier'
module.exports = do ->
return class VoiceNotifier extends Notifer
name: 'voice'
should_be_used: (argv)-> argv.voice
notify: (argv, message, cb)->
cb = cb or ->
voice_map =
male: '<NAME>'
female: '<NAME>'
voice = voice_map[argv.voice] || '<NAME>'
say.speak voice, message, cb
| true | say = require 'say'
Notifer = require './notifier'
module.exports = do ->
return class VoiceNotifier extends Notifer
name: 'voice'
should_be_used: (argv)-> argv.voice
notify: (argv, message, cb)->
cb = cb or ->
voice_map =
male: 'PI:NAME:<NAME>END_PI'
female: 'PI:NAME:<NAME>END_PI'
voice = voice_map[argv.voice] || 'PI:NAME:<NAME>END_PI'
say.speak voice, message, cb
|
[
{
"context": "o effect on the front end.\n\t\t# https://github.com/paramander/contentful-rich-text-vue-renderer/issues/29\n\t\t# h",
"end": 3644,
"score": 0.9996505975723267,
"start": 3634,
"tag": "USERNAME",
"value": "paramander"
},
{
"context": "Node, value: v }\n\t\t\t\t\t\t\t\t{ ... | components/rich-text/rich-text.coffee | BKWLD/cloak-copy | 0 | # Render rich text content from Contentful
import RichTextRenderer from 'contentful-rich-text-vue-renderer'
import { INLINES, BLOCKS } from '@contentful/rich-text-types'
# ContentfulVisual used to render image assets
import ContentfulVisual from '@bkwld/cloak/components/contentful-visual.coffee'
# Query to get embedded assets
import getEmbeddedAsset from './embedded-asset.gql'
export default
# Pass the JSON in
props:
content: Object
# Support passing in the query and renderer for embedded entries
embededEntriesQuery: String
embededEntriesRenderer: Function
# Enable these directives. They are expected to already be globally
# imported
unorphan: Boolean
balanceText: Boolean
# Optional. For manually setting the fetchKey to something unique
# to each component instance. Use this if you're getting Nuxt fetch key
# conflicts. This can happen after client-side navigation in static mode.
# Can cause your rich-text 'links' to get nulled out, or the message
# to appear: "Missing renderer for undefined".
fetchKey: String
data: -> links: {}
fetchKey: (getCounter) -> @fetchKey or getCounter()
# Fetch linked entries
fetch: ->
# Get every linked entry's id for rich text block
linkedEntries = @getLinkedEntries @docJson
return unless linkedEntries?.length
# Query Contentful for embeddable entries based off id
fetchedLinks = await Promise.all linkedEntries.map ({id, nodeType}) =>
switch nodeType
# Embedded entries
when 'embedded-entry-block', 'embedded-entry-inline'
@$contentful.getEntry
query: @embededEntriesQuery
variables: { id }
# Query for embedded assets since assets aren't "entry" types
when "embedded-asset-block"
@$contentful.getEntry
query: getEmbeddedAsset
variables: { id }
# Create an object of all links
@links = fetchedLinks.reduce (links, link) ->
links[link.id] = link if link?.id
return links
, {}
computed:
# Get the JSON from the passed in field data
docJson: -> @content?.json || @content
methods:
# Node renderer schema
renderNodes: ->
[INLINES.EMBEDDED_ENTRY]: @renderEmbedded
[BLOCKS.EMBEDDED_ENTRY]: @renderEmbedded
[BLOCKS.EMBEDDED_ASSET]: @renderAsset
break: (_node, key, create) -> create('br', {key}, {})
# Use renderTextBlock() for elements that should convert \n to <br>
[BLOCKS.HEADING_1]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h1')
[BLOCKS.HEADING_2]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h2')
[BLOCKS.HEADING_3]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h3')
[BLOCKS.HEADING_4]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h4')
[BLOCKS.HEADING_5]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h5')
[BLOCKS.HEADING_6]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h6')
[BLOCKS.PARAGRAPH]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'p')
# Render function for text blocks
renderTextBlock: (node, key, create, next, element) ->
# Convert \n to <br>
content = @getNodeContentWithNewline({ node, key })
# Render it
return create(element, { key }, next(content, key, create, next))
# Convert "\n" strings into <br> nodes
# If `node` arg is a text node that contains instances of "\n",
# convert it to an array of text nodes with "br" nodes in between.
# Fixes behavior where adding soft return in Contentful (shift + enter)
# had no effect on the front end.
# https://github.com/paramander/contentful-rich-text-vue-renderer/issues/29
# https://codesandbox.io/s/delicate-shadow-81xs7?file=/src/App.vue
getNodeContentWithNewline: ({ node, key }) ->
nodeContentWithNewlineBr = node.content.map (childNode) ->
if childNode.nodeType == "text"
splittedValue = childNode.value.split "\n"
return splittedValue
.reduce(
(aggregate, v, i) -> [
...aggregate
{ ...childNode, value: v }
{ nodeType: "break", key: "#{key}-br-#{i}" },
],
[]
)
.slice(0, -1)
return childNode
return [].concat.apply([], nodeContentWithNewlineBr);
# Renderer function for embedded blocks
renderEmbedded: (node, key, create) ->
return if not targetId = node?.data?.target?.sys?.id
# Get target data from links query
entry = @links[targetId]
contentType = entry?.__typename
# Try to render the emebdded entry
if vm = @embededEntriesRenderer { create, contentType, entry, key }
then return vm
# Otherwise, render a span with a warning message
create 'span', {}, "Missing renderer for #{contentType}"
# Renderer function for embedded assets
renderAsset: (node, key, create) ->
return if not targetId = node?.data?.target?.sys?.id
# Get target data from links query
image = @links[targetId]
# Make the visual instance, using Natural because the expectation is
# that this is used to render logos.
create ContentfulVisual, {
key,
props:
image: image
natural: true
}
# Reduce the doc to just linked entry ids and node types for querying
getLinkedEntries: (entry) ->
return if not content = entry?.content
content.reduce (entries, listedEntry) =>
# Add the type and id to the list
id = listedEntry?.data?.target?.sys?.id
nodeType = listedEntry?.nodeType
entries.push({ id, nodeType }) if id
# Recurse though children
if listedEntry?.content?.length
sublinks = @getLinkedEntries listedEntry
entries.push(...sublinks)
# Return the entries we've discovered
return entries
, []
# Render the rich text document
render: (create) ->
# Don't render until fetch has resolved
return if @$fetchState.pending
# Wrap in a div to apply containing functionality
create 'div', {
# Automatically add directives
directives: [
{ name: 'parse-anchors' }
{ name: 'unorphan' } if @unorphan
{ name: 'balance-text', modifiers: children: true } if @balanceText
].filter (val) -> !!val
# Append the WYSIWYG class
class: ['wysiwyg']
# Nest the rich text component
}, create RichTextRenderer,
props:
nodeRenderers: @renderNodes()
document: @docJson
| 22650 | # Render rich text content from Contentful
import RichTextRenderer from 'contentful-rich-text-vue-renderer'
import { INLINES, BLOCKS } from '@contentful/rich-text-types'
# ContentfulVisual used to render image assets
import ContentfulVisual from '@bkwld/cloak/components/contentful-visual.coffee'
# Query to get embedded assets
import getEmbeddedAsset from './embedded-asset.gql'
export default
# Pass the JSON in
props:
content: Object
# Support passing in the query and renderer for embedded entries
embededEntriesQuery: String
embededEntriesRenderer: Function
# Enable these directives. They are expected to already be globally
# imported
unorphan: Boolean
balanceText: Boolean
# Optional. For manually setting the fetchKey to something unique
# to each component instance. Use this if you're getting Nuxt fetch key
# conflicts. This can happen after client-side navigation in static mode.
# Can cause your rich-text 'links' to get nulled out, or the message
# to appear: "Missing renderer for undefined".
fetchKey: String
data: -> links: {}
fetchKey: (getCounter) -> @fetchKey or getCounter()
# Fetch linked entries
fetch: ->
# Get every linked entry's id for rich text block
linkedEntries = @getLinkedEntries @docJson
return unless linkedEntries?.length
# Query Contentful for embeddable entries based off id
fetchedLinks = await Promise.all linkedEntries.map ({id, nodeType}) =>
switch nodeType
# Embedded entries
when 'embedded-entry-block', 'embedded-entry-inline'
@$contentful.getEntry
query: @embededEntriesQuery
variables: { id }
# Query for embedded assets since assets aren't "entry" types
when "embedded-asset-block"
@$contentful.getEntry
query: getEmbeddedAsset
variables: { id }
# Create an object of all links
@links = fetchedLinks.reduce (links, link) ->
links[link.id] = link if link?.id
return links
, {}
computed:
# Get the JSON from the passed in field data
docJson: -> @content?.json || @content
methods:
# Node renderer schema
renderNodes: ->
[INLINES.EMBEDDED_ENTRY]: @renderEmbedded
[BLOCKS.EMBEDDED_ENTRY]: @renderEmbedded
[BLOCKS.EMBEDDED_ASSET]: @renderAsset
break: (_node, key, create) -> create('br', {key}, {})
# Use renderTextBlock() for elements that should convert \n to <br>
[BLOCKS.HEADING_1]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h1')
[BLOCKS.HEADING_2]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h2')
[BLOCKS.HEADING_3]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h3')
[BLOCKS.HEADING_4]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h4')
[BLOCKS.HEADING_5]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h5')
[BLOCKS.HEADING_6]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h6')
[BLOCKS.PARAGRAPH]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'p')
# Render function for text blocks
renderTextBlock: (node, key, create, next, element) ->
# Convert \n to <br>
content = @getNodeContentWithNewline({ node, key })
# Render it
return create(element, { key }, next(content, key, create, next))
# Convert "\n" strings into <br> nodes
# If `node` arg is a text node that contains instances of "\n",
# convert it to an array of text nodes with "br" nodes in between.
# Fixes behavior where adding soft return in Contentful (shift + enter)
# had no effect on the front end.
# https://github.com/paramander/contentful-rich-text-vue-renderer/issues/29
# https://codesandbox.io/s/delicate-shadow-81xs7?file=/src/App.vue
getNodeContentWithNewline: ({ node, key }) ->
nodeContentWithNewlineBr = node.content.map (childNode) ->
if childNode.nodeType == "text"
splittedValue = childNode.value.split "\n"
return splittedValue
.reduce(
(aggregate, v, i) -> [
...aggregate
{ ...childNode, value: v }
{ nodeType: "break", key: <KEY> },
],
[]
)
.slice(0, -1)
return childNode
return [].concat.apply([], nodeContentWithNewlineBr);
# Renderer function for embedded blocks
renderEmbedded: (node, key, create) ->
return if not targetId = node?.data?.target?.sys?.id
# Get target data from links query
entry = @links[targetId]
contentType = entry?.__typename
# Try to render the emebdded entry
if vm = @embededEntriesRenderer { create, contentType, entry, key }
then return vm
# Otherwise, render a span with a warning message
create 'span', {}, "Missing renderer for #{contentType}"
# Renderer function for embedded assets
renderAsset: (node, key, create) ->
return if not targetId = node?.data?.target?.sys?.id
# Get target data from links query
image = @links[targetId]
# Make the visual instance, using Natural because the expectation is
# that this is used to render logos.
create ContentfulVisual, {
key,
props:
image: image
natural: true
}
# Reduce the doc to just linked entry ids and node types for querying
getLinkedEntries: (entry) ->
return if not content = entry?.content
content.reduce (entries, listedEntry) =>
# Add the type and id to the list
id = listedEntry?.data?.target?.sys?.id
nodeType = listedEntry?.nodeType
entries.push({ id, nodeType }) if id
# Recurse though children
if listedEntry?.content?.length
sublinks = @getLinkedEntries listedEntry
entries.push(...sublinks)
# Return the entries we've discovered
return entries
, []
# Render the rich text document
render: (create) ->
# Don't render until fetch has resolved
return if @$fetchState.pending
# Wrap in a div to apply containing functionality
create 'div', {
# Automatically add directives
directives: [
{ name: 'parse-anchors' }
{ name: 'unorphan' } if @unorphan
{ name: 'balance-text', modifiers: children: true } if @balanceText
].filter (val) -> !!val
# Append the WYSIWYG class
class: ['wysiwyg']
# Nest the rich text component
}, create RichTextRenderer,
props:
nodeRenderers: @renderNodes()
document: @docJson
| true | # Render rich text content from Contentful
import RichTextRenderer from 'contentful-rich-text-vue-renderer'
import { INLINES, BLOCKS } from '@contentful/rich-text-types'
# ContentfulVisual used to render image assets
import ContentfulVisual from '@bkwld/cloak/components/contentful-visual.coffee'
# Query to get embedded assets
import getEmbeddedAsset from './embedded-asset.gql'
export default
# Pass the JSON in
props:
content: Object
# Support passing in the query and renderer for embedded entries
embededEntriesQuery: String
embededEntriesRenderer: Function
# Enable these directives. They are expected to already be globally
# imported
unorphan: Boolean
balanceText: Boolean
# Optional. For manually setting the fetchKey to something unique
# to each component instance. Use this if you're getting Nuxt fetch key
# conflicts. This can happen after client-side navigation in static mode.
# Can cause your rich-text 'links' to get nulled out, or the message
# to appear: "Missing renderer for undefined".
fetchKey: String
data: -> links: {}
fetchKey: (getCounter) -> @fetchKey or getCounter()
# Fetch linked entries
fetch: ->
# Get every linked entry's id for rich text block
linkedEntries = @getLinkedEntries @docJson
return unless linkedEntries?.length
# Query Contentful for embeddable entries based off id
fetchedLinks = await Promise.all linkedEntries.map ({id, nodeType}) =>
switch nodeType
# Embedded entries
when 'embedded-entry-block', 'embedded-entry-inline'
@$contentful.getEntry
query: @embededEntriesQuery
variables: { id }
# Query for embedded assets since assets aren't "entry" types
when "embedded-asset-block"
@$contentful.getEntry
query: getEmbeddedAsset
variables: { id }
# Create an object of all links
@links = fetchedLinks.reduce (links, link) ->
links[link.id] = link if link?.id
return links
, {}
computed:
# Get the JSON from the passed in field data
docJson: -> @content?.json || @content
methods:
# Node renderer schema
renderNodes: ->
[INLINES.EMBEDDED_ENTRY]: @renderEmbedded
[BLOCKS.EMBEDDED_ENTRY]: @renderEmbedded
[BLOCKS.EMBEDDED_ASSET]: @renderAsset
break: (_node, key, create) -> create('br', {key}, {})
# Use renderTextBlock() for elements that should convert \n to <br>
[BLOCKS.HEADING_1]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h1')
[BLOCKS.HEADING_2]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h2')
[BLOCKS.HEADING_3]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h3')
[BLOCKS.HEADING_4]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h4')
[BLOCKS.HEADING_5]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h5')
[BLOCKS.HEADING_6]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'h6')
[BLOCKS.PARAGRAPH]: (node, key, create, next) => @renderTextBlock(node, key, create, next, 'p')
# Render function for text blocks
renderTextBlock: (node, key, create, next, element) ->
# Convert \n to <br>
content = @getNodeContentWithNewline({ node, key })
# Render it
return create(element, { key }, next(content, key, create, next))
# Convert "\n" strings into <br> nodes
# If `node` arg is a text node that contains instances of "\n",
# convert it to an array of text nodes with "br" nodes in between.
# Fixes behavior where adding soft return in Contentful (shift + enter)
# had no effect on the front end.
# https://github.com/paramander/contentful-rich-text-vue-renderer/issues/29
# https://codesandbox.io/s/delicate-shadow-81xs7?file=/src/App.vue
getNodeContentWithNewline: ({ node, key }) ->
nodeContentWithNewlineBr = node.content.map (childNode) ->
if childNode.nodeType == "text"
splittedValue = childNode.value.split "\n"
return splittedValue
.reduce(
(aggregate, v, i) -> [
...aggregate
{ ...childNode, value: v }
{ nodeType: "break", key: PI:KEY:<KEY>END_PI },
],
[]
)
.slice(0, -1)
return childNode
return [].concat.apply([], nodeContentWithNewlineBr);
# Renderer function for embedded blocks
renderEmbedded: (node, key, create) ->
return if not targetId = node?.data?.target?.sys?.id
# Get target data from links query
entry = @links[targetId]
contentType = entry?.__typename
# Try to render the emebdded entry
if vm = @embededEntriesRenderer { create, contentType, entry, key }
then return vm
# Otherwise, render a span with a warning message
create 'span', {}, "Missing renderer for #{contentType}"
# Renderer function for embedded assets
renderAsset: (node, key, create) ->
return if not targetId = node?.data?.target?.sys?.id
# Get target data from links query
image = @links[targetId]
# Make the visual instance, using Natural because the expectation is
# that this is used to render logos.
create ContentfulVisual, {
key,
props:
image: image
natural: true
}
# Reduce the doc to just linked entry ids and node types for querying
getLinkedEntries: (entry) ->
return if not content = entry?.content
content.reduce (entries, listedEntry) =>
# Add the type and id to the list
id = listedEntry?.data?.target?.sys?.id
nodeType = listedEntry?.nodeType
entries.push({ id, nodeType }) if id
# Recurse though children
if listedEntry?.content?.length
sublinks = @getLinkedEntries listedEntry
entries.push(...sublinks)
# Return the entries we've discovered
return entries
, []
# Render the rich text document
render: (create) ->
# Don't render until fetch has resolved
return if @$fetchState.pending
# Wrap in a div to apply containing functionality
create 'div', {
# Automatically add directives
directives: [
{ name: 'parse-anchors' }
{ name: 'unorphan' } if @unorphan
{ name: 'balance-text', modifiers: children: true } if @balanceText
].filter (val) -> !!val
# Append the WYSIWYG class
class: ['wysiwyg']
# Nest the rich text component
}, create RichTextRenderer,
props:
nodeRenderers: @renderNodes()
document: @docJson
|
[
{
"context": "s.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYXRvbmV2c2tpIiwiYSI6ImNpdzBndWY0azAwMXoyb3BqYXU2NDhoajEifQ.ESeiramSy2FmzU_XyIT6IQ', {\n maxZoom: 18\n id: 'mapbox.streets'\n }\n",
"end": 393,
"score": 0.9993910789489746,
"start": 301,
"tag": "KEY",
"value": "... | www/coffee/map.coffee | atonevski/pos | 0 | #
# map.coffee
# POS
#
angular.module 'app.map', []
.controller 'MapCurrentPosition', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('mapid').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYXRvbmV2c2tpIiwiYSI6ImNpdzBndWY0azAwMXoyb3BqYXU2NDhoajEifQ.ESeiramSy2FmzU_XyIT6IQ', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
$scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#mapid'
offset = $ionicPosition.offset el
console.log 'mapid offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("mapid")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("mapid")
.style.height = $window.innerHeight - offset.top + 'px'
$scope.map.setView [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], 15
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
.addTo $scope.map
.openPopup()
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
</address>
"""
.addTo $scope.map
$scope.$on '$ionicView.enter', () ->
if $scope.position?
# center around current position
$scope.map.setView [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], 15
# and popUp marker
$scope.positionMarker.openPopup()
.controller 'MapCities', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('cities-map-id').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYXRvbmV2c2tpIiwiYSI6ImNpdzBndWY0azAwMXoyb3BqYXU2NDhoajEifQ.ESeiramSy2FmzU_XyIT6IQ', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.on 'locationfound', (e) ->
console.log 'Location found: ', e
# alert "Location found @: #{ e.latitude }, #{ e.longitude }"
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
$scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#cities-map-id'
offset = $ionicPosition.offset el
console.log 'cities-map-id offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("cities-map-id")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("cities-map-id")
.style.height = $window.innerHeight - offset.top + 'px'
# $scope.map.setView [
# $scope.position.coords.latitude,
# $scope.position.coords.longitude,
# ], 15
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.addTo $scope.map
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.addTo $scope.map
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
"""
$scope.newSelection = (c) ->
console.log 'New selection: ', c
$scope.map.setView [
c.latitude,
c.longitude,
], c.zoomLevel
.controller 'MapSearch', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('search-map-id').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYXRvbmV2c2tpIiwiYSI6ImNpdzBndWY0azAwMXoyb3BqYXU2NDhoajEifQ.ESeiramSy2FmzU_XyIT6IQ', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.on 'locationfound', (e) ->
console.log 'Location found: ', e
alert "Location found @: #{ e.latitude }, #{ e.longitude }"
$scope.searchResults =
hide: no
pos: null
$scope.selectTerminal = (id) ->
return unless id
id = parseInt id
console.log "Terminal #{ id } selected"
$scope.searchResults.hide = yes
$scope.searchResults.pos = (pos for pos in $scope.poses when pos.id is id)[0]
$scope.map.setView [
$scope.searchResults.pos.latitude,
$scope.searchResults.pos.longitude
], 15
$scope.searchResults.pos.marker.openPopup()
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
# $scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#search-map-id'
offset = $ionicPosition.offset el
console.log 'search-map-id offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("cities-map-id")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("search-map-id")
.style.height = $window.innerHeight - offset.top + 'px'
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.addTo $scope.map
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
marker = L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.addTo $scope.map
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
"""
pos.marker = marker
| 10819 | #
# map.coffee
# POS
#
angular.module 'app.map', []
.controller 'MapCurrentPosition', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('mapid').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=<KEY>', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
$scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#mapid'
offset = $ionicPosition.offset el
console.log 'mapid offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("mapid")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("mapid")
.style.height = $window.innerHeight - offset.top + 'px'
$scope.map.setView [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], 15
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
.addTo $scope.map
.openPopup()
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
</address>
"""
.addTo $scope.map
$scope.$on '$ionicView.enter', () ->
if $scope.position?
# center around current position
$scope.map.setView [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], 15
# and popUp marker
$scope.positionMarker.openPopup()
.controller 'MapCities', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('cities-map-id').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=<KEY>', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.on 'locationfound', (e) ->
console.log 'Location found: ', e
# alert "Location found @: #{ e.latitude }, #{ e.longitude }"
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
$scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#cities-map-id'
offset = $ionicPosition.offset el
console.log 'cities-map-id offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("cities-map-id")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("cities-map-id")
.style.height = $window.innerHeight - offset.top + 'px'
# $scope.map.setView [
# $scope.position.coords.latitude,
# $scope.position.coords.longitude,
# ], 15
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.addTo $scope.map
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.addTo $scope.map
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
"""
$scope.newSelection = (c) ->
console.log 'New selection: ', c
$scope.map.setView [
c.latitude,
c.longitude,
], c.zoomLevel
.controller 'MapSearch', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('search-map-id').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=<KEY>', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.on 'locationfound', (e) ->
console.log 'Location found: ', e
alert "Location found @: #{ e.latitude }, #{ e.longitude }"
$scope.searchResults =
hide: no
pos: null
$scope.selectTerminal = (id) ->
return unless id
id = parseInt id
console.log "Terminal #{ id } selected"
$scope.searchResults.hide = yes
$scope.searchResults.pos = (pos for pos in $scope.poses when pos.id is id)[0]
$scope.map.setView [
$scope.searchResults.pos.latitude,
$scope.searchResults.pos.longitude
], 15
$scope.searchResults.pos.marker.openPopup()
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
# $scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#search-map-id'
offset = $ionicPosition.offset el
console.log 'search-map-id offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("cities-map-id")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("search-map-id")
.style.height = $window.innerHeight - offset.top + 'px'
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.addTo $scope.map
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
marker = L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.addTo $scope.map
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
"""
pos.marker = marker
| true | #
# map.coffee
# POS
#
angular.module 'app.map', []
.controller 'MapCurrentPosition', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('mapid').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=PI:KEY:<KEY>END_PI', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
$scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#mapid'
offset = $ionicPosition.offset el
console.log 'mapid offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("mapid")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("mapid")
.style.height = $window.innerHeight - offset.top + 'px'
$scope.map.setView [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], 15
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
.addTo $scope.map
.openPopup()
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
</address>
"""
.addTo $scope.map
$scope.$on '$ionicView.enter', () ->
if $scope.position?
# center around current position
$scope.map.setView [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], 15
# and popUp marker
$scope.positionMarker.openPopup()
.controller 'MapCities', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('cities-map-id').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=PI:KEY:<KEY>END_PI', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.on 'locationfound', (e) ->
console.log 'Location found: ', e
# alert "Location found @: #{ e.latitude }, #{ e.longitude }"
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
$scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#cities-map-id'
offset = $ionicPosition.offset el
console.log 'cities-map-id offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("cities-map-id")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("cities-map-id")
.style.height = $window.innerHeight - offset.top + 'px'
# $scope.map.setView [
# $scope.position.coords.latitude,
# $scope.position.coords.longitude,
# ], 15
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.addTo $scope.map
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.addTo $scope.map
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
"""
$scope.newSelection = (c) ->
console.log 'New selection: ', c
$scope.map.setView [
c.latitude,
c.longitude,
], c.zoomLevel
.controller 'MapSearch', ($scope, $rootScope, $window
, $ionicScrollDelegate, $ionicPosition, $cordovaVibration) ->
$scope.map = L.map('search-map-id').fitWorld()
L.tileLayer 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=PI:KEY:<KEY>END_PI', {
maxZoom: 18
id: 'mapbox.streets'
}
.addTo $scope.map
$scope.map.on 'locationerror', (e) -> console.log "Leaflet loc err: ", e
$scope.map.on 'locationfound', (e) ->
console.log 'Location found: ', e
alert "Location found @: #{ e.latitude }, #{ e.longitude }"
$scope.searchResults =
hide: no
pos: null
$scope.selectTerminal = (id) ->
return unless id
id = parseInt id
console.log "Terminal #{ id } selected"
$scope.searchResults.hide = yes
$scope.searchResults.pos = (pos for pos in $scope.poses when pos.id is id)[0]
$scope.map.setView [
$scope.searchResults.pos.latitude,
$scope.searchResults.pos.longitude
], 15
$scope.searchResults.pos.marker.openPopup()
$scope.map.setView [
41.997346199999996, 21.4279956
], 15
# $scope.map.locate { setView: yes, maxZoom: 16 }
redIcon = new L.Icon { iconUrl: 'img/red-marker-icon.png' }
greenIcon = new L.Icon { iconUrl: 'img/green-marker-icon.png' }
# resize map div
el = angular.element document.querySelector '#search-map-id'
offset = $ionicPosition.offset el
console.log 'search-map-id offset (top, left): ', offset.top, offset.left
console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }"
# setting map's height
el[0].style.height = window.innerHeight - offset.top + 'px'
# or alternativelly:
# document
# .getElementById("cities-map-id")
# .style.height = window.innerHeight - offset.top + 'px'
#
$scope.map.on 'click', (e) ->
alert "Покажа на позиција " + e.latlng
$cordovaVibration.vibrate 250
# detect window size change
angular
.element $window
.bind 'resize', () ->
console.log 'Window size changed: ', "#{ $window.innerWidth }x#{ $window.innerHeight }"
document
.getElementById("search-map-id")
.style.height = $window.innerHeight - offset.top + 'px'
# watch position change/ready
$scope.$watch 'position', (n, o) ->
return unless n?
if $scope.positionMarker?
$scope.map.removeLayer $scope.positionMarker
$scope.positionMarker = L.marker [
$scope.position.coords.latitude,
$scope.position.coords.longitude,
], { icon: redIcon }
.addTo $scope.map
.bindPopup """
Ова е твојата тековна позиција:<br />
<strong>#{ $scope.position.coords.latitude.toFixed 6 },
#{ $scope.position.coords.longitude.toFixed 6 }</strong>
"""
# watch poses change
$scope.$watch 'poses', (n, o) ->
return unless n?
console.log "We have #{ $scope.poses.length } poses to add"
for pos in $scope.poses
marker = L.marker [
pos.latitude,
pos.longitude,
], { icon: greenIcon }
.addTo $scope.map
.bindPopup """
<strong>#{ pos.name }</strong> (#{ pos.id })<br />
<hr />
<address>
#{ pos.address } <br />
#{ pos.city } <br />
тел.: #{ pos.telephone } <br />
</address>
"""
pos.marker = marker
|
[
{
"context": "て言葉足らずにしてあるので、研修生に対してきちんとフォローすること。\n#\n# Author:\n# miura-simpline <miura.daisuke@simpline.co.jp>\n\nmodule.exports = ",
"end": 371,
"score": 0.9786186218261719,
"start": 357,
"tag": "USERNAME",
"value": "miura-simpline"
},
{
"context": "に対してきちんとフォローすること。\n#\n# Author... | scripts/training2nd.coffee | simpline/TrainingBotCustomer | 0 | # Description:
# The 2nd day of Training - 研修2日目
#
# Commands:
# customer ご用件を伺いに来ました。
# customer Wordpressを立てたことを報告しに来ました。
# customer MovableTypeに変更したことを報告しに来ました。
# customer Wordpressに戻したことを報告しに来ました。
# customer 障害とその原因について報告しに来ました。{障害内容と原因}
# customer 復旧したことを報告しに来ました。
#
# Notes:
# この内容はあえて言葉足らずにしてあるので、研修生に対してきちんとフォローすること。
#
# Author:
# miura-simpline <miura.daisuke@simpline.co.jp>
module.exports = (robot) ->
robot.respond /ご用件を伺いに来ました。/i, (res) ->
res.reply """
実は最近会社でもブログを使っている所が増えていると聞いてね。
そこで当社もブログを使って、当社の良さを宣伝したいと思っているんだ。
なので、早速なんだけど、Wordpressがいいらしいので、それをひとつ用意してくれるかね。
上長に「お客様からWordpressを立ててほしいと頼まれました。」と相談してください。
"""
robot.respond /Wordpressを立てたことを報告しに来ました。/i, (res) ->
res.reply """
ありがたいのですが、昨日Wordpressでブログを書いてほしいと社員に伝えたら、
MovableTypeの方がいいと言い出す社員がいましてね。
そちらのが慣れているから楽だという話なんですよ。
私としては書いてもらえば、どちらでもいいのでMovableTypeにしてもらえますか。
上長に「お客様からMovableTypeに変更してほしいと頼まれました。」と相談してください。
"""
robot.respond /MovableTypeに変更したことを報告しに来ました。/i, (res) ->
res.reply """
いやー、変えてもらったところを申し訳ないんだけどね。
やはりWordpressのがよさそうで、Wordpressにしてほしいんだよ。
MovableTypeがいいと言っていた社員もブログを書くだけでサーバを運用するわけじゃないから、
口出さないように言っておいたよ。それでは、よろしく。
上長に「お客様からWordpressに戻して100万PVに耐えられるようにしてほしいと頼まれました。」と
相談してください。
"""
robot.respond /Wordpressに戻したことを報告しに来ました。/i, (res) ->
res.reply """
じゃあ、早速使ってみますよ。
それと、せっかく書いたのに消えてしまってはいやだから、
バックアップをとるようにしておいてください。
上長に「お客様からバックアップを取るように頼まれました。」と相談してください。
"""
robot.respond /障害内容とその原因について報告しに来ました。.*/i, (res) ->
res.reply """
そういうことですか。バックアップを取ってあるので、すぐ戻せますよね。
すぐに取りかかってください。
戻ったら、私に「復旧したことを報告しに来ました。」と言いに来てください。
"""
robot.respond /復旧したことを報告しに来ました。.*/i, (res) ->
res.reply """
ご苦労様です。復旧したことですし、とりあえずよしとしましょう。
ただ、こちらが気づく前に、そちらで気づかないようでは困りますね。
あらかじめそちらで気づくような仕組みを作っておいてください。
上長に「お客様から壊れたことを気づく仕組みを作ってほしいと頼まれました。」と
相談してください。
"""
| 51091 | # Description:
# The 2nd day of Training - 研修2日目
#
# Commands:
# customer ご用件を伺いに来ました。
# customer Wordpressを立てたことを報告しに来ました。
# customer MovableTypeに変更したことを報告しに来ました。
# customer Wordpressに戻したことを報告しに来ました。
# customer 障害とその原因について報告しに来ました。{障害内容と原因}
# customer 復旧したことを報告しに来ました。
#
# Notes:
# この内容はあえて言葉足らずにしてあるので、研修生に対してきちんとフォローすること。
#
# Author:
# miura-simpline <<EMAIL>>
module.exports = (robot) ->
robot.respond /ご用件を伺いに来ました。/i, (res) ->
res.reply """
実は最近会社でもブログを使っている所が増えていると聞いてね。
そこで当社もブログを使って、当社の良さを宣伝したいと思っているんだ。
なので、早速なんだけど、Wordpressがいいらしいので、それをひとつ用意してくれるかね。
上長に「お客様からWordpressを立ててほしいと頼まれました。」と相談してください。
"""
robot.respond /Wordpressを立てたことを報告しに来ました。/i, (res) ->
res.reply """
ありがたいのですが、昨日Wordpressでブログを書いてほしいと社員に伝えたら、
MovableTypeの方がいいと言い出す社員がいましてね。
そちらのが慣れているから楽だという話なんですよ。
私としては書いてもらえば、どちらでもいいのでMovableTypeにしてもらえますか。
上長に「お客様からMovableTypeに変更してほしいと頼まれました。」と相談してください。
"""
robot.respond /MovableTypeに変更したことを報告しに来ました。/i, (res) ->
res.reply """
いやー、変えてもらったところを申し訳ないんだけどね。
やはりWordpressのがよさそうで、Wordpressにしてほしいんだよ。
MovableTypeがいいと言っていた社員もブログを書くだけでサーバを運用するわけじゃないから、
口出さないように言っておいたよ。それでは、よろしく。
上長に「お客様からWordpressに戻して100万PVに耐えられるようにしてほしいと頼まれました。」と
相談してください。
"""
robot.respond /Wordpressに戻したことを報告しに来ました。/i, (res) ->
res.reply """
じゃあ、早速使ってみますよ。
それと、せっかく書いたのに消えてしまってはいやだから、
バックアップをとるようにしておいてください。
上長に「お客様からバックアップを取るように頼まれました。」と相談してください。
"""
robot.respond /障害内容とその原因について報告しに来ました。.*/i, (res) ->
res.reply """
そういうことですか。バックアップを取ってあるので、すぐ戻せますよね。
すぐに取りかかってください。
戻ったら、私に「復旧したことを報告しに来ました。」と言いに来てください。
"""
robot.respond /復旧したことを報告しに来ました。.*/i, (res) ->
res.reply """
ご苦労様です。復旧したことですし、とりあえずよしとしましょう。
ただ、こちらが気づく前に、そちらで気づかないようでは困りますね。
あらかじめそちらで気づくような仕組みを作っておいてください。
上長に「お客様から壊れたことを気づく仕組みを作ってほしいと頼まれました。」と
相談してください。
"""
| true | # Description:
# The 2nd day of Training - 研修2日目
#
# Commands:
# customer ご用件を伺いに来ました。
# customer Wordpressを立てたことを報告しに来ました。
# customer MovableTypeに変更したことを報告しに来ました。
# customer Wordpressに戻したことを報告しに来ました。
# customer 障害とその原因について報告しに来ました。{障害内容と原因}
# customer 復旧したことを報告しに来ました。
#
# Notes:
# この内容はあえて言葉足らずにしてあるので、研修生に対してきちんとフォローすること。
#
# Author:
# miura-simpline <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
robot.respond /ご用件を伺いに来ました。/i, (res) ->
res.reply """
実は最近会社でもブログを使っている所が増えていると聞いてね。
そこで当社もブログを使って、当社の良さを宣伝したいと思っているんだ。
なので、早速なんだけど、Wordpressがいいらしいので、それをひとつ用意してくれるかね。
上長に「お客様からWordpressを立ててほしいと頼まれました。」と相談してください。
"""
robot.respond /Wordpressを立てたことを報告しに来ました。/i, (res) ->
res.reply """
ありがたいのですが、昨日Wordpressでブログを書いてほしいと社員に伝えたら、
MovableTypeの方がいいと言い出す社員がいましてね。
そちらのが慣れているから楽だという話なんですよ。
私としては書いてもらえば、どちらでもいいのでMovableTypeにしてもらえますか。
上長に「お客様からMovableTypeに変更してほしいと頼まれました。」と相談してください。
"""
robot.respond /MovableTypeに変更したことを報告しに来ました。/i, (res) ->
res.reply """
いやー、変えてもらったところを申し訳ないんだけどね。
やはりWordpressのがよさそうで、Wordpressにしてほしいんだよ。
MovableTypeがいいと言っていた社員もブログを書くだけでサーバを運用するわけじゃないから、
口出さないように言っておいたよ。それでは、よろしく。
上長に「お客様からWordpressに戻して100万PVに耐えられるようにしてほしいと頼まれました。」と
相談してください。
"""
robot.respond /Wordpressに戻したことを報告しに来ました。/i, (res) ->
res.reply """
じゃあ、早速使ってみますよ。
それと、せっかく書いたのに消えてしまってはいやだから、
バックアップをとるようにしておいてください。
上長に「お客様からバックアップを取るように頼まれました。」と相談してください。
"""
robot.respond /障害内容とその原因について報告しに来ました。.*/i, (res) ->
res.reply """
そういうことですか。バックアップを取ってあるので、すぐ戻せますよね。
すぐに取りかかってください。
戻ったら、私に「復旧したことを報告しに来ました。」と言いに来てください。
"""
robot.respond /復旧したことを報告しに来ました。.*/i, (res) ->
res.reply """
ご苦労様です。復旧したことですし、とりあえずよしとしましょう。
ただ、こちらが気づく前に、そちらで気づかないようでは困りますね。
あらかじめそちらで気づくような仕組みを作っておいてください。
上長に「お客様から壊れたことを気づく仕組みを作ってほしいと頼まれました。」と
相談してください。
"""
|
[
{
"context": "# -*- coding: utf-8 -*-\n#\n# Copyright 2015 Roy Liu\n#\n# Licensed under the Apache License, Version 2.",
"end": 50,
"score": 0.9996296167373657,
"start": 43,
"tag": "NAME",
"value": "Roy Liu"
}
] | app/assets/javascripts/models/all.coffee | carsomyr/nurf-stats | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2015 Roy Liu
#
# 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.
((factory) ->
if typeof define is "function" and define.amd?
define ["ember",
"application-base",
"./champion",
"./champion_duo_stat",
"./champion_lane_stat",
"./champion_stat",
"./item",
"./item_stat",
"./mastery",
"./polymorphic",
"./rune",
"./spell",
"./stat",
"./static_entity",
"./useless_rune_mastery_stat"], factory
).call(@, (Ember, #
app, #
Champion, #
ChampionDuoStat, #
ChampionLaneStat, #
ChampionStat, #
Item, #
ItemStat, #
Mastery, #
Polymorphic, #
Rune, #
Spell, #
Stat, #
StaticEntity, #
UselessRuneMasteryStat) ->
app
)
| 124463 | # -*- coding: utf-8 -*-
#
# Copyright 2015 <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.
((factory) ->
if typeof define is "function" and define.amd?
define ["ember",
"application-base",
"./champion",
"./champion_duo_stat",
"./champion_lane_stat",
"./champion_stat",
"./item",
"./item_stat",
"./mastery",
"./polymorphic",
"./rune",
"./spell",
"./stat",
"./static_entity",
"./useless_rune_mastery_stat"], factory
).call(@, (Ember, #
app, #
Champion, #
ChampionDuoStat, #
ChampionLaneStat, #
ChampionStat, #
Item, #
ItemStat, #
Mastery, #
Polymorphic, #
Rune, #
Spell, #
Stat, #
StaticEntity, #
UselessRuneMasteryStat) ->
app
)
| true | # -*- coding: utf-8 -*-
#
# Copyright 2015 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.
((factory) ->
if typeof define is "function" and define.amd?
define ["ember",
"application-base",
"./champion",
"./champion_duo_stat",
"./champion_lane_stat",
"./champion_stat",
"./item",
"./item_stat",
"./mastery",
"./polymorphic",
"./rune",
"./spell",
"./stat",
"./static_entity",
"./useless_rune_mastery_stat"], factory
).call(@, (Ember, #
app, #
Champion, #
ChampionDuoStat, #
ChampionLaneStat, #
ChampionStat, #
Item, #
ItemStat, #
Mastery, #
Polymorphic, #
Rune, #
Spell, #
Stat, #
StaticEntity, #
UselessRuneMasteryStat) ->
app
)
|
[
{
"context": " expect(result.resultTree).toEqual\n name: 'test-name'\n children: [\n {name: 'a', value: 'a'",
"end": 404,
"score": 0.9321354031562805,
"start": 395,
"tag": "NAME",
"value": "test-name"
},
{
"context": " expect(result.resultTree).toEqual\n nam... | web/spec/result/result-view-spec.coffee | ebakke/grails-console | 54 | describe 'App.Result.ResultView', ->
beforeEach ->
@model = new App.Result.Result
@view = new App.Result.ResultView
model: @model
afterEach ->
it 'should convertTreeNode', ->
@model.set
result: 'test-name'
resultTree:
a: 'a'
b: 'b'
input: 'test'
result = @view.serializeData()
expect(result.resultTree).toEqual
name: 'test-name'
children: [
{name: 'a', value: 'a'}
{name: 'b', value: 'b'}
]
@model.set
result: 'test-name'
resultTree: ['aaa', 'bbb', 'ccc']
input: 'test'
result = @view.serializeData()
expect(result.resultTree).toEqual
name: 'test-name'
children: [
{name: 'aaa'}
{name: 'bbb'}
{name: 'ccc'}
] | 164560 | describe 'App.Result.ResultView', ->
beforeEach ->
@model = new App.Result.Result
@view = new App.Result.ResultView
model: @model
afterEach ->
it 'should convertTreeNode', ->
@model.set
result: 'test-name'
resultTree:
a: 'a'
b: 'b'
input: 'test'
result = @view.serializeData()
expect(result.resultTree).toEqual
name: '<NAME>'
children: [
{name: 'a', value: 'a'}
{name: 'b', value: 'b'}
]
@model.set
result: 'test-name'
resultTree: ['aaa', 'bbb', 'ccc']
input: 'test'
result = @view.serializeData()
expect(result.resultTree).toEqual
name: '<NAME>'
children: [
{name: 'aaa'}
{name: 'bbb'}
{name: 'ccc'}
] | true | describe 'App.Result.ResultView', ->
beforeEach ->
@model = new App.Result.Result
@view = new App.Result.ResultView
model: @model
afterEach ->
it 'should convertTreeNode', ->
@model.set
result: 'test-name'
resultTree:
a: 'a'
b: 'b'
input: 'test'
result = @view.serializeData()
expect(result.resultTree).toEqual
name: 'PI:NAME:<NAME>END_PI'
children: [
{name: 'a', value: 'a'}
{name: 'b', value: 'b'}
]
@model.set
result: 'test-name'
resultTree: ['aaa', 'bbb', 'ccc']
input: 'test'
result = @view.serializeData()
expect(result.resultTree).toEqual
name: 'PI:NAME:<NAME>END_PI'
children: [
{name: 'aaa'}
{name: 'bbb'}
{name: 'ccc'}
] |
[
{
"context": "describe 'model', ->\n user = 'test@abc.com'\n key = null\n csr = null\n crt = null\n\n it 'cr",
"end": 43,
"score": 0.9998891949653625,
"start": 31,
"tag": "EMAIL",
"value": "test@abc.com"
}
] | backend/test/unit/1-model/cert.coffee | twhtanghk/ca | 0 | describe 'model', ->
user = 'test@abc.com'
key = null
csr = null
crt = null
it 'create user', ->
sails.models.user
.findOrCreate {email: user}, {email: user}
it 'create private key', ->
sails.models.cert.createPrivateKey()
.then (newkey) ->
key = newkey
it 'create csr', ->
sails.models.cert
.createCSR
clientkey: key
commonName: user
.then (newcsr) ->
csr = newcsr
it 'create certificate', ->
sails.models.cert.create createdBy: user
.then (newcrt) ->
crt = newcrt
it 'get public key', ->
sails.models.user.findOne email: user
.populateAll()
.then (user) ->
sails.models.cert.publicKey user?.certs[0]
it 'get cert info', ->
sails.models.user.findOne email: user
.populateAll()
.then (user) ->
sails.models.cert.info user?.certs[0]
it 'destroy cert', ->
sails.models.cert.destroy createdBy: user
| 15694 | describe 'model', ->
user = '<EMAIL>'
key = null
csr = null
crt = null
it 'create user', ->
sails.models.user
.findOrCreate {email: user}, {email: user}
it 'create private key', ->
sails.models.cert.createPrivateKey()
.then (newkey) ->
key = newkey
it 'create csr', ->
sails.models.cert
.createCSR
clientkey: key
commonName: user
.then (newcsr) ->
csr = newcsr
it 'create certificate', ->
sails.models.cert.create createdBy: user
.then (newcrt) ->
crt = newcrt
it 'get public key', ->
sails.models.user.findOne email: user
.populateAll()
.then (user) ->
sails.models.cert.publicKey user?.certs[0]
it 'get cert info', ->
sails.models.user.findOne email: user
.populateAll()
.then (user) ->
sails.models.cert.info user?.certs[0]
it 'destroy cert', ->
sails.models.cert.destroy createdBy: user
| true | describe 'model', ->
user = 'PI:EMAIL:<EMAIL>END_PI'
key = null
csr = null
crt = null
it 'create user', ->
sails.models.user
.findOrCreate {email: user}, {email: user}
it 'create private key', ->
sails.models.cert.createPrivateKey()
.then (newkey) ->
key = newkey
it 'create csr', ->
sails.models.cert
.createCSR
clientkey: key
commonName: user
.then (newcsr) ->
csr = newcsr
it 'create certificate', ->
sails.models.cert.create createdBy: user
.then (newcrt) ->
crt = newcrt
it 'get public key', ->
sails.models.user.findOne email: user
.populateAll()
.then (user) ->
sails.models.cert.publicKey user?.certs[0]
it 'get cert info', ->
sails.models.user.findOne email: user
.populateAll()
.then (user) ->
sails.models.cert.info user?.certs[0]
it 'destroy cert', ->
sails.models.cert.destroy createdBy: user
|
[
{
"context": "root'\n password: process.env.EPX_DB_PASS or '1tism0db'\n host: process.env.EPX_DB_HOST or 'localhos",
"end": 569,
"score": 0.999223530292511,
"start": 561,
"tag": "PASSWORD",
"value": "1tism0db"
},
{
"context": "t '/user/create/'\n .send\n ema... | tests/core.coffee | evanhuang8/teresa | 0 | ###
Core tests
###
require 'co-mocha'
_ = require 'lodash'
chai = require 'chai'
chai.config.includeStack = true
should = chai.should()
supertest = require 'co-supertest'
request = supertest.agent
moment = require 'moment-timezone'
Q = require 'q'
xml2js = require 'xml2js'
parseXML = Q.denodeify xml2js.parseString
MessageTests = require './libs/messenger'
describe 'Teresa', ->
before (done) ->
mysql = require 'mysql'
connection = mysql.createConnection
user: process.env.EPX_DB_USER or 'root'
password: process.env.EPX_DB_PASS or '1tism0db'
host: process.env.EPX_DB_HOST or 'localhost'
connection.connect()
connection.query 'DROP DATABASE IF EXISTS Teresa', (err) ->
connection.query 'CREATE DATABASE Teresa', (err) ->
done err
return
return
return
gb = {}
authedRequest = null
describe 'Server', ->
it 'should exist', ->
@timeout 10000
gb.Server = require '../src/teresa'
should.exist gb.Server
gb.db = require '../src/db'
return
it 'should start', ->
gb.server = new gb.Server()
gb.app = yield gb.server.init()
return
describe 'Authentication', ->
it '#create', ->
res = yield request gb.app
.post '/user/create/'
.send
email: 'user@example.com'
password: 'password1'
.expect 201
.end()
res.body.status.should.equal 'OK'
gb.User = gb.db.model 'User'
user = yield gb.User.findOne
where:
email: 'user@example.com'
should.exist user
(yield user.verifyPassword('password1')).should.be.true
return
it '#auth', ->
authedRequest = request gb.app
res = yield authedRequest
.post '/user/auth/'
.send
email: 'user@example.com'
password: 'password1'
.expect 200
.end()
res.body.status.should.equal 'OK'
should.exist res.headers['set-cookie']
return
describe 'CURD', ->
describe 'Community', ->
before ->
gb.Community = gb.db.model 'Community'
return
it '#create', ->
res = yield authedRequest
.post '/community/create/'
.send
name: 'STL CoC'
description: 'The Community of Care of the greater St. Louis region.'
.expect 201
.end()
res.body.status.should.equal 'OK'
community = yield gb.Community.findById res.body.obj.id
should.exist community
community.name.should.equal 'STL CoC'
community.description.should.equal 'The Community of Care of the greater St. Louis region.'
gb.community = community
return
it '#edit', ->
res = yield authedRequest
.post '/community/edit/'
.send
id: gb.community.id
name: 'St. Louis CoC'
description: 'The Continuum of Care of the greater St. Louis region.'
.expect 200
.end()
res.body.status.should.equal 'OK'
community = yield gb.Community.findById res.body.obj.id
should.exist community
community.name.should.equal 'St. Louis CoC'
community.description.should.equal 'The Continuum of Care of the greater St. Louis region.'
gb.community = community
return
describe 'Organization', ->
before ->
gb.Organization = gb.db.model 'Organization'
return
after ->
yield gb.Organization.destroy
where: {}
force: true
orgA = yield gb.Organization.create
name: 'St. Patrick Center'
description: 'We do good things.'
communityId: gb.community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Central'
orgB = yield gb.Organization.create
name: 'Mercy Ministries'
description: 'We do good things.'
communityId: gb.community.id
address: '655 Maryville Centre Dr, St. Louis, MO 63141'
lat: 38.644379
lng: -90.495485
tz: 'US/Central'
orgC = yield gb.Organization.create
name: 'Evanston'
description: 'Ahhhhhhhhhh'
communityId: gb.community.id
address: '4476 Barat Hall Dr, St. Louis, MO 63108'
lat: 38.6440
lng: -90.2574
tz: 'US/Central'
gb.organization = orgA
gb.organizations = [orgA, orgB, orgC]
return
it '#create', ->
params =
name: 'St. Patrick'
description: 'We do good things.'
communityId: gb.community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Pacific'
res = yield authedRequest
.post '/organization/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
organization = yield gb.Organization.findById res.body.obj.id
should.exist organization
for key, val of params
organization[key].should.equal val
gb.organization = organization
return
it '#edit', ->
params =
id: gb.organization.id
name: 'St. Patrick Center'
description: 'We do good things together.'
communityId: gb.community.id
address: '800 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.6333972
lng: -90.195599
tz: 'US/Central'
res = yield authedRequest
.post '/organization/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
organization = yield gb.Organization.findById res.body.obj.id
should.exist organization
for key, val of params
organization[key].should.equal val
gb.organization = organization
return
describe 'Client', ->
before ->
gb.Client = gb.db.model 'Client'
return
it '#create', ->
params =
firstName: 'Julio'
middleName: 'J'
lastName: 'Jones'
phone: '6613177375'
dob: '1947-09-18'
stage: 'emergent'
res = yield authedRequest
.post '/client/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
client = yield gb.Client.findById res.body.obj.id
should.exist client
for key, val of params
client[key].should.equal val
gb.client = client
return
it '#edit', ->
params =
id: gb.client.id
firstName: 'Marty'
middleName: 'K'
lastName: 'Mack'
phone: '3140010002'
dob: '1940-03-12'
stage: 'homeless'
res = yield authedRequest
.post '/client/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
client = yield gb.Client.findById res.body.obj.id
should.exist client
for key, val of params
client[key].should.equal val
gb.client = client
return
it '#fetch', ->
# First Name Search
params =
keyword: 'Mar'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 1
# Last Name Search
params =
keyword: 'ack'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 1
# No Results
params =
keyword: 'Jon Bon Jovi'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 0
return
describe 'Location', ->
before ->
gb.LocationUtils = require '../src/utils/location'
return
it '#geocode', ->
@timeout 5000
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
should.exist result.lat
should.exist result.lng
parseInt(result.lat * 1000).should.equal 38643
parseInt(result.lng * 1000).should.equal -90257
return
it '#direction', ->
@timeout 5000
yield gb.LocationUtils.directions
origin:
lat: 38.6440
lng: -90.2574
destination:
lat: 38.633397
lng: -90.19559
return
describe 'Service', ->
before ->
gb.Service = gb.db.model 'Service'
gb.ServiceUtils = require '../src/controllers/service/utils'
return
after ->
hours = []
for i in [0...7]
hours.push
always: true
yield gb.Service.destroy
where: {}
force: true
serviceA = yield gb.Service.create
type: 'shelter'
name: 'St. Patrick Shelter'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: gb.organizations[0].id
serviceB = yield gb.Service.create
type: 'shelter'
name: 'Mercy Shelter'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: gb.organizations[1].id
gb.services = [serviceA, serviceB]
return
it '#create', ->
hours = []
for i in [0...7]
hours.push
always: true
params =
type: 'shelter'
name: 'St. Paddy Shelter'
description: 'Welcome to my house - Flo.Rider'
businessHours: hours
maxCapacity: 190
openCapacity: 100
organizationId: gb.organization.id
res = yield authedRequest
.post '/service/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
service = yield gb.Service.findById res.body.obj.id
should.exist service
for key, val of params
service[key].should.deep.equal val
gb.service = service
return
it '#edit', ->
hours = []
for i in [0...7]
if i in [2, 4]
hours.push
start: '05:00PM'
end: '9:00AM'
overnight: true
else
hours.push
always: true
params =
id: gb.service.id
name: 'St. Patrick Shelter'
description: 'Welcome to my house'
businessHours: hours
maxCapacity: 200
openCapacity: 200
res = yield authedRequest
.post '/service/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
service = yield gb.Service.findById res.body.obj.id
should.exist service
for key, val of params
service[key].should.deep.equal val
gb.service = service
return
it 'should be able to return nearest open service', ->
@timeout 5000
hours = []
for i in [0...7]
hours.push
always: true
yield gb.Service.destroy
where: {}
force: true
serviceA = yield gb.Service.create
type: 'shelter'
name: 'St. Patrick Service'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: gb.organizations[0].id
serviceB = yield gb.Service.create
type: 'shelter'
name: 'Mercy Service'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: gb.organizations[1].id
serviceC = yield gb.Service.create
type: 'shelter'
name: 'My Crib'
description: 'Great'
businessHours: hours
maxCapacity: 100
openCapacity: 0
organizationId: gb.organizations[2].id
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
services = yield gb.ServiceUtils.nearestServices
type: 'shelter'
lat: result.lat
lng: result.lng
isAvailable: true
services[0].id.should.equal serviceA.id
gb.services = [serviceA, serviceB, serviceC]
return
it 'should be able to return the nearest service', ->
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
services = yield gb.ServiceUtils.nearestServices
type: 'shelter'
lat: result.lat
lng: result.lng
services[0].id.should.equal gb.services[2].id
return
describe 'Interpreter', ->
before ->
gb.interpreter = require '../src/utils/interpreter'
return
it 'should interpret string', ->
result = yield gb.interpreter.interpret 'I want to find a place to sleep near University City'
result.intent.should.equal 'shelter'
result.location.should.equal 'University City'
return
describe 'Self-initiated referral (help line)', ->
before ->
gb.Referral = gb.db.model 'Referral'
gb.Intent = gb.db.model 'Intent'
gb.messenger = require '../src/controllers/referral/messenger'
gb._phone = '+16623177375'
return
beforeEach ->
yield gb.Referral.destroy
where: {}
yield gb.Client.destroy
where:
phone: gb._phone
return
it 'should handle incoming message #1', ->
steps = [
input: 'i need shelter'
expect: gb.messenger.address()
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
yield messenger.run()
client = yield gb.Client.findOne
where:
phone: gb._phone
should.exist client
referral = yield gb.Referral.findOne
where:
clientId: client.id
should.exist referral
referral.type.should.equal 'shelter'
referral.isInitialized.should.be.true
code = null
steps = [
input: 'Maryland St. & Taylor St.'
assert:
referral:
values:
serviceId: gb.services[0].id
refereeId: gb.services[0].organizationId
exists: ['address', 'lat', 'lng']
test: ->
intent = yield gb.Intent.findOne
where:
referralId: referral.id
should.exist intent
code = intent.code
return
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
assert:
referral: referral
yield messenger.run()
referral = yield gb.Referral.findById referral.id
steps = [
input: 'yes'
expect: gb.messenger.confirmed code
assert:
referral:
values:
isReserved: true
isConfirmed: true
,
input: 'no'
expect: gb.messenger.end()
assert:
referral:
values:
isDirectionSent: false
,
input: 'direction'
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
assert:
referral: referral
yield messenger.run()
return
after ->
gb.app?.close()
return | 141589 | ###
Core tests
###
require 'co-mocha'
_ = require 'lodash'
chai = require 'chai'
chai.config.includeStack = true
should = chai.should()
supertest = require 'co-supertest'
request = supertest.agent
moment = require 'moment-timezone'
Q = require 'q'
xml2js = require 'xml2js'
parseXML = Q.denodeify xml2js.parseString
MessageTests = require './libs/messenger'
describe 'Teresa', ->
before (done) ->
mysql = require 'mysql'
connection = mysql.createConnection
user: process.env.EPX_DB_USER or 'root'
password: process.env.EPX_DB_PASS or '<PASSWORD>'
host: process.env.EPX_DB_HOST or 'localhost'
connection.connect()
connection.query 'DROP DATABASE IF EXISTS Teresa', (err) ->
connection.query 'CREATE DATABASE Teresa', (err) ->
done err
return
return
return
gb = {}
authedRequest = null
describe 'Server', ->
it 'should exist', ->
@timeout 10000
gb.Server = require '../src/teresa'
should.exist gb.Server
gb.db = require '../src/db'
return
it 'should start', ->
gb.server = new gb.Server()
gb.app = yield gb.server.init()
return
describe 'Authentication', ->
it '#create', ->
res = yield request gb.app
.post '/user/create/'
.send
email: '<EMAIL>'
password: '<PASSWORD>'
.expect 201
.end()
res.body.status.should.equal 'OK'
gb.User = gb.db.model 'User'
user = yield gb.User.findOne
where:
email: '<EMAIL>'
should.exist user
(yield user.verifyPassword('<PASSWORD>')).should.be.true
return
it '#auth', ->
authedRequest = request gb.app
res = yield authedRequest
.post '/user/auth/'
.send
email: 'user<EMAIL>'
password: '<PASSWORD>'
.expect 200
.end()
res.body.status.should.equal 'OK'
should.exist res.headers['set-cookie']
return
describe 'CURD', ->
describe 'Community', ->
before ->
gb.Community = gb.db.model 'Community'
return
it '#create', ->
res = yield authedRequest
.post '/community/create/'
.send
name: 'STL CoC'
description: 'The Community of Care of the greater St. Louis region.'
.expect 201
.end()
res.body.status.should.equal 'OK'
community = yield gb.Community.findById res.body.obj.id
should.exist community
community.name.should.equal 'STL CoC'
community.description.should.equal 'The Community of Care of the greater St. Louis region.'
gb.community = community
return
it '#edit', ->
res = yield authedRequest
.post '/community/edit/'
.send
id: gb.community.id
name: 'St. Louis CoC'
description: 'The Continuum of Care of the greater St. Louis region.'
.expect 200
.end()
res.body.status.should.equal 'OK'
community = yield gb.Community.findById res.body.obj.id
should.exist community
community.name.should.equal 'St. Louis CoC'
community.description.should.equal 'The Continuum of Care of the greater St. Louis region.'
gb.community = community
return
describe 'Organization', ->
before ->
gb.Organization = gb.db.model 'Organization'
return
after ->
yield gb.Organization.destroy
where: {}
force: true
orgA = yield gb.Organization.create
name: '<NAME>. <NAME>'
description: 'We do good things.'
communityId: gb.community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Central'
orgB = yield gb.Organization.create
name: '<NAME>'
description: 'We do good things.'
communityId: gb.community.id
address: '655 Maryville Centre Dr, St. Louis, MO 63141'
lat: 38.644379
lng: -90.495485
tz: 'US/Central'
orgC = yield gb.Organization.create
name: '<NAME>'
description: 'Ahhhhhhhhhh'
communityId: gb.community.id
address: '4476 Barat Hall Dr, St. Louis, MO 63108'
lat: 38.6440
lng: -90.2574
tz: 'US/Central'
gb.organization = orgA
gb.organizations = [orgA, orgB, orgC]
return
it '#create', ->
params =
name: '<NAME>'
description: 'We do good things.'
communityId: gb.community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Pacific'
res = yield authedRequest
.post '/organization/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
organization = yield gb.Organization.findById res.body.obj.id
should.exist organization
for key, val of params
organization[key].should.equal val
gb.organization = organization
return
it '#edit', ->
params =
id: gb.organization.id
name: '<NAME>'
description: 'We do good things together.'
communityId: gb.community.id
address: '800 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.6333972
lng: -90.195599
tz: 'US/Central'
res = yield authedRequest
.post '/organization/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
organization = yield gb.Organization.findById res.body.obj.id
should.exist organization
for key, val of params
organization[key].should.equal val
gb.organization = organization
return
describe 'Client', ->
before ->
gb.Client = gb.db.model 'Client'
return
it '#create', ->
params =
firstName: '<NAME>'
middleName: '<NAME>'
lastName: '<NAME>'
phone: '6613177375'
dob: '1947-09-18'
stage: 'emergent'
res = yield authedRequest
.post '/client/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
client = yield gb.Client.findById res.body.obj.id
should.exist client
for key, val of params
client[key].should.equal val
gb.client = client
return
it '#edit', ->
params =
id: gb.client.id
firstName: '<NAME>'
middleName: '<NAME>'
lastName: '<NAME>'
phone: '3140010002'
dob: '1940-03-12'
stage: 'homeless'
res = yield authedRequest
.post '/client/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
client = yield gb.Client.findById res.body.obj.id
should.exist client
for key, val of params
client[key].should.equal val
gb.client = client
return
it '#fetch', ->
# First Name Search
params =
keyword: '<NAME>'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 1
# Last Name Search
params =
keyword: '<NAME>'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 1
# No Results
params =
keyword: '<NAME>'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 0
return
describe 'Location', ->
before ->
gb.LocationUtils = require '../src/utils/location'
return
it '#geocode', ->
@timeout 5000
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
should.exist result.lat
should.exist result.lng
parseInt(result.lat * 1000).should.equal 38643
parseInt(result.lng * 1000).should.equal -90257
return
it '#direction', ->
@timeout 5000
yield gb.LocationUtils.directions
origin:
lat: 38.6440
lng: -90.2574
destination:
lat: 38.633397
lng: -90.19559
return
describe 'Service', ->
before ->
gb.Service = gb.db.model 'Service'
gb.ServiceUtils = require '../src/controllers/service/utils'
return
after ->
hours = []
for i in [0...7]
hours.push
always: true
yield gb.Service.destroy
where: {}
force: true
serviceA = yield gb.Service.create
type: 'shelter'
name: '<NAME>. <NAME>'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: gb.organizations[0].id
serviceB = yield gb.Service.create
type: 'shelter'
name: '<NAME>'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: gb.organizations[1].id
gb.services = [serviceA, serviceB]
return
it '#create', ->
hours = []
for i in [0...7]
hours.push
always: true
params =
type: 'shelter'
name: '<NAME>'
description: 'Welcome to my house - Flo.Rider'
businessHours: hours
maxCapacity: 190
openCapacity: 100
organizationId: gb.organization.id
res = yield authedRequest
.post '/service/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
service = yield gb.Service.findById res.body.obj.id
should.exist service
for key, val of params
service[key].should.deep.equal val
gb.service = service
return
it '#edit', ->
hours = []
for i in [0...7]
if i in [2, 4]
hours.push
start: '05:00PM'
end: '9:00AM'
overnight: true
else
hours.push
always: true
params =
id: gb.service.id
name: '<NAME>. <NAME>'
description: 'Welcome to my house'
businessHours: hours
maxCapacity: 200
openCapacity: 200
res = yield authedRequest
.post '/service/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
service = yield gb.Service.findById res.body.obj.id
should.exist service
for key, val of params
service[key].should.deep.equal val
gb.service = service
return
it 'should be able to return nearest open service', ->
@timeout 5000
hours = []
for i in [0...7]
hours.push
always: true
yield gb.Service.destroy
where: {}
force: true
serviceA = yield gb.Service.create
type: 'shelter'
name: '<NAME>'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: gb.organizations[0].id
serviceB = yield gb.Service.create
type: 'shelter'
name: '<NAME>'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: gb.organizations[1].id
serviceC = yield gb.Service.create
type: 'shelter'
name: '<NAME>'
description: 'Great'
businessHours: hours
maxCapacity: 100
openCapacity: 0
organizationId: gb.organizations[2].id
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
services = yield gb.ServiceUtils.nearestServices
type: 'shelter'
lat: result.lat
lng: result.lng
isAvailable: true
services[0].id.should.equal serviceA.id
gb.services = [serviceA, serviceB, serviceC]
return
it 'should be able to return the nearest service', ->
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
services = yield gb.ServiceUtils.nearestServices
type: 'shelter'
lat: result.lat
lng: result.lng
services[0].id.should.equal gb.services[2].id
return
describe 'Interpreter', ->
before ->
gb.interpreter = require '../src/utils/interpreter'
return
it 'should interpret string', ->
result = yield gb.interpreter.interpret 'I want to find a place to sleep near University City'
result.intent.should.equal 'shelter'
result.location.should.equal 'University City'
return
describe 'Self-initiated referral (help line)', ->
before ->
gb.Referral = gb.db.model 'Referral'
gb.Intent = gb.db.model 'Intent'
gb.messenger = require '../src/controllers/referral/messenger'
gb._phone = '+16623177375'
return
beforeEach ->
yield gb.Referral.destroy
where: {}
yield gb.Client.destroy
where:
phone: gb._phone
return
it 'should handle incoming message #1', ->
steps = [
input: 'i need shelter'
expect: gb.messenger.address()
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
yield messenger.run()
client = yield gb.Client.findOne
where:
phone: gb._phone
should.exist client
referral = yield gb.Referral.findOne
where:
clientId: client.id
should.exist referral
referral.type.should.equal 'shelter'
referral.isInitialized.should.be.true
code = null
steps = [
input: 'Maryland St. & <NAME>aylor St.'
assert:
referral:
values:
serviceId: gb.services[0].id
refereeId: gb.services[0].organizationId
exists: ['address', 'lat', 'lng']
test: ->
intent = yield gb.Intent.findOne
where:
referralId: referral.id
should.exist intent
code = intent.code
return
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
assert:
referral: referral
yield messenger.run()
referral = yield gb.Referral.findById referral.id
steps = [
input: 'yes'
expect: gb.messenger.confirmed code
assert:
referral:
values:
isReserved: true
isConfirmed: true
,
input: 'no'
expect: gb.messenger.end()
assert:
referral:
values:
isDirectionSent: false
,
input: 'direction'
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
assert:
referral: referral
yield messenger.run()
return
after ->
gb.app?.close()
return | true | ###
Core tests
###
require 'co-mocha'
_ = require 'lodash'
chai = require 'chai'
chai.config.includeStack = true
should = chai.should()
supertest = require 'co-supertest'
request = supertest.agent
moment = require 'moment-timezone'
Q = require 'q'
xml2js = require 'xml2js'
parseXML = Q.denodeify xml2js.parseString
MessageTests = require './libs/messenger'
describe 'Teresa', ->
before (done) ->
mysql = require 'mysql'
connection = mysql.createConnection
user: process.env.EPX_DB_USER or 'root'
password: process.env.EPX_DB_PASS or 'PI:PASSWORD:<PASSWORD>END_PI'
host: process.env.EPX_DB_HOST or 'localhost'
connection.connect()
connection.query 'DROP DATABASE IF EXISTS Teresa', (err) ->
connection.query 'CREATE DATABASE Teresa', (err) ->
done err
return
return
return
gb = {}
authedRequest = null
describe 'Server', ->
it 'should exist', ->
@timeout 10000
gb.Server = require '../src/teresa'
should.exist gb.Server
gb.db = require '../src/db'
return
it 'should start', ->
gb.server = new gb.Server()
gb.app = yield gb.server.init()
return
describe 'Authentication', ->
it '#create', ->
res = yield request gb.app
.post '/user/create/'
.send
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
.expect 201
.end()
res.body.status.should.equal 'OK'
gb.User = gb.db.model 'User'
user = yield gb.User.findOne
where:
email: 'PI:EMAIL:<EMAIL>END_PI'
should.exist user
(yield user.verifyPassword('PI:PASSWORD:<PASSWORD>END_PI')).should.be.true
return
it '#auth', ->
authedRequest = request gb.app
res = yield authedRequest
.post '/user/auth/'
.send
email: 'userPI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
.expect 200
.end()
res.body.status.should.equal 'OK'
should.exist res.headers['set-cookie']
return
describe 'CURD', ->
describe 'Community', ->
before ->
gb.Community = gb.db.model 'Community'
return
it '#create', ->
res = yield authedRequest
.post '/community/create/'
.send
name: 'STL CoC'
description: 'The Community of Care of the greater St. Louis region.'
.expect 201
.end()
res.body.status.should.equal 'OK'
community = yield gb.Community.findById res.body.obj.id
should.exist community
community.name.should.equal 'STL CoC'
community.description.should.equal 'The Community of Care of the greater St. Louis region.'
gb.community = community
return
it '#edit', ->
res = yield authedRequest
.post '/community/edit/'
.send
id: gb.community.id
name: 'St. Louis CoC'
description: 'The Continuum of Care of the greater St. Louis region.'
.expect 200
.end()
res.body.status.should.equal 'OK'
community = yield gb.Community.findById res.body.obj.id
should.exist community
community.name.should.equal 'St. Louis CoC'
community.description.should.equal 'The Continuum of Care of the greater St. Louis region.'
gb.community = community
return
describe 'Organization', ->
before ->
gb.Organization = gb.db.model 'Organization'
return
after ->
yield gb.Organization.destroy
where: {}
force: true
orgA = yield gb.Organization.create
name: 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI'
description: 'We do good things.'
communityId: gb.community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Central'
orgB = yield gb.Organization.create
name: 'PI:NAME:<NAME>END_PI'
description: 'We do good things.'
communityId: gb.community.id
address: '655 Maryville Centre Dr, St. Louis, MO 63141'
lat: 38.644379
lng: -90.495485
tz: 'US/Central'
orgC = yield gb.Organization.create
name: 'PI:NAME:<NAME>END_PI'
description: 'Ahhhhhhhhhh'
communityId: gb.community.id
address: '4476 Barat Hall Dr, St. Louis, MO 63108'
lat: 38.6440
lng: -90.2574
tz: 'US/Central'
gb.organization = orgA
gb.organizations = [orgA, orgB, orgC]
return
it '#create', ->
params =
name: 'PI:NAME:<NAME>END_PI'
description: 'We do good things.'
communityId: gb.community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Pacific'
res = yield authedRequest
.post '/organization/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
organization = yield gb.Organization.findById res.body.obj.id
should.exist organization
for key, val of params
organization[key].should.equal val
gb.organization = organization
return
it '#edit', ->
params =
id: gb.organization.id
name: 'PI:NAME:<NAME>END_PI'
description: 'We do good things together.'
communityId: gb.community.id
address: '800 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.6333972
lng: -90.195599
tz: 'US/Central'
res = yield authedRequest
.post '/organization/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
organization = yield gb.Organization.findById res.body.obj.id
should.exist organization
for key, val of params
organization[key].should.equal val
gb.organization = organization
return
describe 'Client', ->
before ->
gb.Client = gb.db.model 'Client'
return
it '#create', ->
params =
firstName: 'PI:NAME:<NAME>END_PI'
middleName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
phone: '6613177375'
dob: '1947-09-18'
stage: 'emergent'
res = yield authedRequest
.post '/client/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
client = yield gb.Client.findById res.body.obj.id
should.exist client
for key, val of params
client[key].should.equal val
gb.client = client
return
it '#edit', ->
params =
id: gb.client.id
firstName: 'PI:NAME:<NAME>END_PI'
middleName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
phone: '3140010002'
dob: '1940-03-12'
stage: 'homeless'
res = yield authedRequest
.post '/client/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
client = yield gb.Client.findById res.body.obj.id
should.exist client
for key, val of params
client[key].should.equal val
gb.client = client
return
it '#fetch', ->
# First Name Search
params =
keyword: 'PI:NAME:<NAME>END_PI'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 1
# Last Name Search
params =
keyword: 'PI:NAME:<NAME>END_PI'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 1
# No Results
params =
keyword: 'PI:NAME:<NAME>END_PI'
res = yield authedRequest
.post '/client/fetch/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
res.body.clients.length.should.equal 0
return
describe 'Location', ->
before ->
gb.LocationUtils = require '../src/utils/location'
return
it '#geocode', ->
@timeout 5000
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
should.exist result.lat
should.exist result.lng
parseInt(result.lat * 1000).should.equal 38643
parseInt(result.lng * 1000).should.equal -90257
return
it '#direction', ->
@timeout 5000
yield gb.LocationUtils.directions
origin:
lat: 38.6440
lng: -90.2574
destination:
lat: 38.633397
lng: -90.19559
return
describe 'Service', ->
before ->
gb.Service = gb.db.model 'Service'
gb.ServiceUtils = require '../src/controllers/service/utils'
return
after ->
hours = []
for i in [0...7]
hours.push
always: true
yield gb.Service.destroy
where: {}
force: true
serviceA = yield gb.Service.create
type: 'shelter'
name: 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: gb.organizations[0].id
serviceB = yield gb.Service.create
type: 'shelter'
name: 'PI:NAME:<NAME>END_PI'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: gb.organizations[1].id
gb.services = [serviceA, serviceB]
return
it '#create', ->
hours = []
for i in [0...7]
hours.push
always: true
params =
type: 'shelter'
name: 'PI:NAME:<NAME>END_PI'
description: 'Welcome to my house - Flo.Rider'
businessHours: hours
maxCapacity: 190
openCapacity: 100
organizationId: gb.organization.id
res = yield authedRequest
.post '/service/create/'
.send params
.expect 201
.end()
res.body.status.should.equal 'OK'
service = yield gb.Service.findById res.body.obj.id
should.exist service
for key, val of params
service[key].should.deep.equal val
gb.service = service
return
it '#edit', ->
hours = []
for i in [0...7]
if i in [2, 4]
hours.push
start: '05:00PM'
end: '9:00AM'
overnight: true
else
hours.push
always: true
params =
id: gb.service.id
name: 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI'
description: 'Welcome to my house'
businessHours: hours
maxCapacity: 200
openCapacity: 200
res = yield authedRequest
.post '/service/edit/'
.send params
.expect 200
.end()
res.body.status.should.equal 'OK'
service = yield gb.Service.findById res.body.obj.id
should.exist service
for key, val of params
service[key].should.deep.equal val
gb.service = service
return
it 'should be able to return nearest open service', ->
@timeout 5000
hours = []
for i in [0...7]
hours.push
always: true
yield gb.Service.destroy
where: {}
force: true
serviceA = yield gb.Service.create
type: 'shelter'
name: 'PI:NAME:<NAME>END_PI'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: gb.organizations[0].id
serviceB = yield gb.Service.create
type: 'shelter'
name: 'PI:NAME:<NAME>END_PI'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: gb.organizations[1].id
serviceC = yield gb.Service.create
type: 'shelter'
name: 'PI:NAME:<NAME>END_PI'
description: 'Great'
businessHours: hours
maxCapacity: 100
openCapacity: 0
organizationId: gb.organizations[2].id
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
services = yield gb.ServiceUtils.nearestServices
type: 'shelter'
lat: result.lat
lng: result.lng
isAvailable: true
services[0].id.should.equal serviceA.id
gb.services = [serviceA, serviceB, serviceC]
return
it 'should be able to return the nearest service', ->
result = yield gb.LocationUtils.geocode
keyword: 'maryland and taylor'
near:
lat: 38.6333972
lng: -90.195599
services = yield gb.ServiceUtils.nearestServices
type: 'shelter'
lat: result.lat
lng: result.lng
services[0].id.should.equal gb.services[2].id
return
describe 'Interpreter', ->
before ->
gb.interpreter = require '../src/utils/interpreter'
return
it 'should interpret string', ->
result = yield gb.interpreter.interpret 'I want to find a place to sleep near University City'
result.intent.should.equal 'shelter'
result.location.should.equal 'University City'
return
describe 'Self-initiated referral (help line)', ->
before ->
gb.Referral = gb.db.model 'Referral'
gb.Intent = gb.db.model 'Intent'
gb.messenger = require '../src/controllers/referral/messenger'
gb._phone = '+16623177375'
return
beforeEach ->
yield gb.Referral.destroy
where: {}
yield gb.Client.destroy
where:
phone: gb._phone
return
it 'should handle incoming message #1', ->
steps = [
input: 'i need shelter'
expect: gb.messenger.address()
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
yield messenger.run()
client = yield gb.Client.findOne
where:
phone: gb._phone
should.exist client
referral = yield gb.Referral.findOne
where:
clientId: client.id
should.exist referral
referral.type.should.equal 'shelter'
referral.isInitialized.should.be.true
code = null
steps = [
input: 'Maryland St. & PI:NAME:<NAME>END_PIaylor St.'
assert:
referral:
values:
serviceId: gb.services[0].id
refereeId: gb.services[0].organizationId
exists: ['address', 'lat', 'lng']
test: ->
intent = yield gb.Intent.findOne
where:
referralId: referral.id
should.exist intent
code = intent.code
return
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
assert:
referral: referral
yield messenger.run()
referral = yield gb.Referral.findById referral.id
steps = [
input: 'yes'
expect: gb.messenger.confirmed code
assert:
referral:
values:
isReserved: true
isConfirmed: true
,
input: 'no'
expect: gb.messenger.end()
assert:
referral:
values:
isDirectionSent: false
,
input: 'direction'
]
messenger = new MessageTests
app: gb.app
from: gb._phone
url: '/referral/message/'
steps: steps
assert:
referral: referral
yield messenger.run()
return
after ->
gb.app?.close()
return |
[
{
"context": "r\"\n assert.equal tl[3][0].mx_hash.hash_key, \"dedent\"\n \n describe \"Comments\", ()->\n it \"should to",
"end": 7915,
"score": 0.9753457903862,
"start": 7909,
"tag": "KEY",
"value": "dedent"
},
{
"context": "r\"\n assert.equal tl[3][0].mx_hash.hash_ke... | test/tokenizer.coffee | hu2prod/scriptscript | 1 | assert = require 'assert'
util = require 'fy/test_util'
fs = require 'fs'
path = require 'path'
g = require '../src/tokenizer'
pub = require '../src/index'
describe 'tokenizer section', ()->
it "public endpoint should works", (done)->
await pub.tokenize "id", {}, defer(err, v)
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "identifier"
await pub.tokenize "wtf кирилица", {}, defer(err, v)
assert err?
done()
describe "identifier", ()->
sample_list = "
qwerty
myvar123
someCamelCase
some_snake_case
CAPSLOCK
$
$scope
".split " "
for sample in sample_list
do (sample)->
it "should tokenize '#{sample}' as identifier", ()->
v = g._tokenize sample
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "identifier"
describe "integer literals", ()->
it "should tokenize '142857' as decimal_literal", ()->
v = g._tokenize "142857"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '0' as decimal_literal", ()->
v = g._tokenize "0"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '0777' as octal_literal", ()->
v = g._tokenize "0777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0o777' as octal_literal", ()->
v = g._tokenize "0o777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0O777' as octal_literal", ()->
v = g._tokenize "0O777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0xabcd8' as hexadecimal_literal", ()->
v = g._tokenize "0xabcd8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0XABCD8' as hexadecimal_literal", ()->
v = g._tokenize "0XABCD8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0xAbCd8' as hexadecimal_literal", ()->
v = g._tokenize "0xAbCd8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0b10101' as binary_literal", ()->
v = g._tokenize "0b10101"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_literal"
it "should tokenize '0B10101' as binary_literal", ()->
v = g._tokenize "0B10101"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_literal"
it "should tokenize '-1' as 2 tokens", ()->
v = g._tokenize "-1"
assert.equal v.length, 2
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
assert.equal v[1][0].mx_hash.hash_key, "decimal_literal"
describe "mixed operators", ()->
for v in "+ -".split " "
# for v in "+ - ?".split " "
do (v)->
it "should tokenize '#{v}' as unary_operator and binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
assert.equal v[0][1].mx_hash.hash_key, "binary_operator"
describe "unary operators", ()->
for v in "~ ! ++ -- not typeof void new delete".split " "
do (v)->
it "should tokenize '#{v}' as unary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
describe "binary operators", ()->
for v in "* / % ** // %% << >> >>> & | ^ && || ^^ and or xor instanceof in of is isnt ? . ?. :: ?:: .. ...".split " "
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "binary operators assign", ()->
for v in "+ - * / % ** // %% << >> >>> & | ^ && || ^^ and or xor ?".split " "
v += "="
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "binary operators compare", ()->
# !== ===
for v in "< > <= >= == !=".split " "
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "function", ()->
for v in "-> =>".split " "
do (v)->
it "should tokenize '#{v}' as arrow_function", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "arrow_function"
describe "this", ()->
it "should tokenize '@' as this", ()->
v = g._tokenize "@"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "this"
it "should tokenize '@a' as this and identifier", ()->
v = g._tokenize "@a"
assert.equal v.length, 2
assert.equal v[0][0].mx_hash.hash_key, "this"
assert.equal v[1][0].mx_hash.hash_key, "identifier"
describe "brackets", ()->
for v in "()[]{}"
do (v)->
it "should tokenize '#{v} as bracket", ()->
tl = g._tokenize v
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "bracket"
it "should tokenize '(a)->a' as 5 tokens", ()->
tl = g._tokenize "(a)->a"
assert.equal tl.length, 5
assert.equal tl[0][0].mx_hash.hash_key, "bracket"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
assert.equal tl[2][0].mx_hash.hash_key, "bracket"
assert.equal tl[3][0].mx_hash.hash_key, "arrow_function"
assert.equal tl[4][0].mx_hash.hash_key, "identifier"
describe "floats", ()->
# TEMP disabled
# .1
# .1e10
list = """
1.
1.1
1.e10
1.e+10
1.e-10
1.1e10
1e10
1e+10
1e-10
""".split /\n/g
for v in list
do (v)->
it "should tokenize '#{v}' as float_literal", ()->
tl = g._tokenize v
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "float_literal"
it "should tokenize '1.1+1' as 3 tokens", ()->
tl = g._tokenize "1.1+1"
assert.equal tl.length, 3
assert.equal tl[0][0].mx_hash.hash_key, "float_literal"
assert.equal tl[1][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[1][1].mx_hash.hash_key, "binary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '1e+' as 3 tokens", ()->
tl = g._tokenize "1e+"
assert.equal tl.length, 3
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
assert.equal tl[2][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[2][1].mx_hash.hash_key, "binary_operator"
it "should tokenize '1e' as 2 tokens", ()->
tl = g._tokenize "1e"
assert.equal tl.length, 2
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
describe "Multiline", ()->
it "should tokenize 'a\\n b' as a indent b dedent", ()->
tl = g._tokenize """
a
b
"""
assert.equal tl.length, 4
assert.equal tl[0][0].mx_hash.hash_key, "identifier"
assert.equal tl[1][0].mx_hash.hash_key, "indent"
assert.equal tl[2][0].mx_hash.hash_key, "identifier"
assert.equal tl[3][0].mx_hash.hash_key, "dedent"
describe "Comments", ()->
it "should tokenize '# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ ' as comment", ()->
tl = g._tokenize "# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ "
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
assert.equal tl[0][0].value, "# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ "
it "should tokenize '2+2#=4\\n4+4#=8' as 9 tokens including comments", ()->
tl = g._tokenize "2+2#=4\n4+4#=8"
assert.equal tl.length, 9
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[3][0].mx_hash.hash_key, "comment"
assert.equal tl[4][0].mx_hash.hash_key, "eol"
assert.equal tl[5][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[6][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[7][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[8][0].mx_hash.hash_key, "comment"
it "should tokenize '### 2 + 2 = 4\\n4 + 4 = 8\\n###' as comment", ()->
tl = g._tokenize "### 2 + 2 = 4\n4 + 4 = 8\n###"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
it "should tokenize '####################### COMMENT' as comment", ()->
tl = g._tokenize "####################### COMMENT"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
assert.equal tl[0][0].value, "####################### COMMENT"
describe "Whitespace", ()->
it "should tokenize \\n as empty", ()->
tl = g._tokenize "\n"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "empty"
it "should tokenize \\n1 as 2 tokens", ()->
tl = g._tokenize "\n1"
assert.equal tl.length, 2
it "should tokenize \\n\\n1 as 2 tokens", ()->
tl = g._tokenize "\n\n1"
assert.equal tl.length, 2
it "should tokenize \\n\\n\\n1 as 2 tokens", ()->
tl = g._tokenize "\n\n\n1"
assert.equal tl.length, 2
it "should tokenize 'a + b' as 'a', '+', 'b' with tail_space 1 1 0", ()->
tl = g._tokenize "a + b"
assert.equal tl.length, 3
assert.equal tl[0][0].value, "a"
assert.equal tl[0][0].mx_hash.tail_space, "1"
assert.equal tl[1][0].value, "+"
assert.equal tl[1][0].mx_hash.tail_space, "1"
assert.equal tl[2][0].value, "b"
assert.equal tl[2][0].mx_hash.tail_space, "0"
it "should tokenize 'a / b / c' as 5 tokens (not regexp!)", ()->
tl = g._tokenize "a / b / c"
assert.equal tl.length, 5
assert.equal tl[0][0].mx_hash.hash_key, "identifier"
assert.equal tl[1][0].mx_hash.hash_key, "binary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "identifier"
assert.equal tl[3][0].mx_hash.hash_key, "binary_operator"
assert.equal tl[4][0].mx_hash.hash_key, "identifier"
describe "Double quoted strings", ()->
describe "valid inline strings", ()->
sample_list = """
""
"Some text"
"'"
"Alice's Adventures in Wonderland"
"''"
"\\""
"\\\\"
"\\0"
"\\r"
"\\v"
"\\t"
"\\b"
"\\f"
"\\a"
"\\ "
"\\xFF"
"\\xFf"
"\\xff"
"\\u20FF"
"\\u20ff"
"\\u20fF"
"\\u{25}"
"\\u{10FFFF}"
"\\u{10ffff}"
"\\u{10fFFf}"
"# {a}"
"English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺"
""".split /\n/ # "
sample_list.push '"\\n"'
sample_list.push '"\\\n"'
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as string_literal_doubleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "string_literal_doubleq"
describe "valid block strings", ()->
sample_list = [
'"""English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺"""',
'"""\n heredoc\n """',
'"""\n heredoc with escapes \\n\\r\\t\\b\\f\\0\\\\\\"\\\'\\xFF\\uFFFF\\u{25}\\u{10FFFF}\n"""'
]
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as block_string_literal_doubleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "block_string_literal_doubleq"
describe "invalid", ()->
wrong_string_list = """
"'
'"
"abcd'
'abcd"
"a"a"
"\\u"
"\\u1"
"\\u{}"
"\\u{123456}"
"\\u{i}"
"\\x"
"\\x1"
""".split /\n/ #'
for sample in wrong_string_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
g._tokenize sample
, /Error: can't tokenize /
describe "Interpolated double quoted string", ()->
sample_list = '''
"#{a}"
---
" #{a} "
---
" #{a} #{b} "
---
" #{a} #{b}
"
---
""" #{a} """
---
""" #{a} #{b} """
---
""" #{a} #{b}
"""
'''.split /\n?---\n?/ # "
for sample in sample_list
do (sample)->
it "should tokenize #{sample}", ()->
ret = g._tokenize sample
for v in ret
for v2 in ret
if v2[0].value == '""'
throw new Error "\"\" parsed"
describe "Single quoted strings", ()->
describe "valid inline strings", ()->
sample_list = """
''
'Some text'
'"'
'""'
'"The Silmarillion" by J.R.R. Tolkien'
'\\''
'\\xff'
'\\u20fF'
'\\u{25}'
'\\u{10ffff}'
'\#{a}'
'\\\#{a}'
'English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺'
""".split /\n/ #"
sample_list.push "'\\\n'"
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as string_literal_singleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "string_literal_singleq"
describe "valid block strings", ()->
sample_list = [
"'''English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺'''",
"'''\n heredoc\n '''"
]
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as block_string_literal_singleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "block_string_literal_singleq"
describe "invalid", ()->
wrong_string_list = """
"'
'"
"abcd'
'abcd"
"a"a"
'a'a'
"\\u"
"\\u1"
"\\u{}"
"\\u{123456}"
"\\u{i}"
"\\x"
"\\x1"
""".split /\n/ #"
for sample in wrong_string_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
g._tokenize sample
, /Error: can't tokenize /
describe "Big List of Naughty Strings", ()->
# https://github.com/minimaxir/big-list-of-naughty-strings
# helper
test = (sample, i, token_name) ->
try
tl = g._tokenize sample
catch e
throw new Error """The tokenizer fails to process the string number #{i}: #{sample}
due to this error:
#{e}"""
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, token_name
it "BLNS double quoted via readFileSync", ()->
path_to_blns = path.join (path.dirname require.resolve "blns"), "resources", "blns.json"
blns_raw = fs.readFileSync path_to_blns, "utf8"
blns = (blns_raw.split /[\[,\]]\s*\n\s*/)[1...-1]
for sample, i in blns
test sample, i, "string_literal_doubleq"
blns = require "blns"
it "BLNS double quoted via require", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /"/g, '\\"'
sample = "\"#{sample}\""
test sample, i, "string_literal_doubleq"
it "BLNS single quoted", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /'/g, "\\'"
sample = "'#{sample}'"
test sample, i, "string_literal_singleq"
it "BLNS double quoted block (heredoc)", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /"""/g, '""\\"'
sample = sample.replace /"$/, '\\"'
sample = "\"\"\"#{sample}\"\"\""
test sample, i, "block_string_literal_doubleq"
it "BLNS single quoted block (heredoc)", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /'''/g, "''\\'"
sample = sample.replace /'$/, "\\'"
sample = "'''#{sample}'''"
test sample, i, "block_string_literal_singleq"
describe "Regexp", ()->
it "should tokenize 'a/b/c' as 3 tokens with regexp in the middle", ()->
tl = g._tokenize "a/b/c"
assert.equal tl.length, 3
assert.equal tl[1][0].mx_hash.hash_key, "regexp_literal"
it "should tokenize 'a/b' as 3 tokens without regexp", ()->
tl = g._tokenize "a/b"
assert.equal tl.length, 3
assert.notEqual tl[1][0].mx_hash.hash_key, "regexp_literal"
it "should tokenize 'a//b' as 3 tokens without regexp", ()->
tl = g._tokenize "a//b"
assert.equal tl.length, 3
assert.notEqual tl[1][0].mx_hash.hash_key, "regexp_literal"
# regexp must contain at least one symbol excluding whitespace
# escape policy for string constant should apply for regex
sample_list = """
/ab+c/
/ab+c/i
/ab+c/igmy
/ab+c/ymgi
/a/ii
/]/
/(/
/)/
""".split /\n/
# NOTE bad samples
for sample in sample_list
do (sample)->
it "should tokenize #{JSON.stringify sample} as regexp_literal", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "regexp_literal"
# /[/
sample_list = """
//
/
/ a/
""".split /\n/
for sample in sample_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
tl = g._tokenize sample
if tl[0][0].mx_hash.hash_key == "binary_operator"
assert.equal tl[0][1].mx_hash.hash_key, "regexp_literal"
else
assert.equal tl[0][0].mx_hash.hash_key, "regexp_literal"
describe "Here regexp", ()->
sample_list = """
///ab+c///
---
///ab+c///i
---
///ab+c///igmy
---
///ab+c///ymgi
---
///a///ii
---
///]///
---
///(///
---
///)///
---
///
///
---
///
a
///
---
///
/
///
""".split /\n?---\n?/
# NOTE bad samples
for sample in sample_list
do (sample)->
it "should tokenize #{JSON.stringify sample} as regexp_literal", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "here_regexp_literal"
describe "Pipes", ()->
it "should tokenize 'a | b | c' as 5 tokens", ()->
tl = g._tokenize "a | b | c"
assert.equal tl.length, 5
describe "TODO", ()->
| 149742 | assert = require 'assert'
util = require 'fy/test_util'
fs = require 'fs'
path = require 'path'
g = require '../src/tokenizer'
pub = require '../src/index'
describe 'tokenizer section', ()->
it "public endpoint should works", (done)->
await pub.tokenize "id", {}, defer(err, v)
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "identifier"
await pub.tokenize "wtf кирилица", {}, defer(err, v)
assert err?
done()
describe "identifier", ()->
sample_list = "
qwerty
myvar123
someCamelCase
some_snake_case
CAPSLOCK
$
$scope
".split " "
for sample in sample_list
do (sample)->
it "should tokenize '#{sample}' as identifier", ()->
v = g._tokenize sample
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "identifier"
describe "integer literals", ()->
it "should tokenize '142857' as decimal_literal", ()->
v = g._tokenize "142857"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '0' as decimal_literal", ()->
v = g._tokenize "0"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '0777' as octal_literal", ()->
v = g._tokenize "0777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0o777' as octal_literal", ()->
v = g._tokenize "0o777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0O777' as octal_literal", ()->
v = g._tokenize "0O777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0xabcd8' as hexadecimal_literal", ()->
v = g._tokenize "0xabcd8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0XABCD8' as hexadecimal_literal", ()->
v = g._tokenize "0XABCD8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0xAbCd8' as hexadecimal_literal", ()->
v = g._tokenize "0xAbCd8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0b10101' as binary_literal", ()->
v = g._tokenize "0b10101"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_literal"
it "should tokenize '0B10101' as binary_literal", ()->
v = g._tokenize "0B10101"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_literal"
it "should tokenize '-1' as 2 tokens", ()->
v = g._tokenize "-1"
assert.equal v.length, 2
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
assert.equal v[1][0].mx_hash.hash_key, "decimal_literal"
describe "mixed operators", ()->
for v in "+ -".split " "
# for v in "+ - ?".split " "
do (v)->
it "should tokenize '#{v}' as unary_operator and binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
assert.equal v[0][1].mx_hash.hash_key, "binary_operator"
describe "unary operators", ()->
for v in "~ ! ++ -- not typeof void new delete".split " "
do (v)->
it "should tokenize '#{v}' as unary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
describe "binary operators", ()->
for v in "* / % ** // %% << >> >>> & | ^ && || ^^ and or xor instanceof in of is isnt ? . ?. :: ?:: .. ...".split " "
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "binary operators assign", ()->
for v in "+ - * / % ** // %% << >> >>> & | ^ && || ^^ and or xor ?".split " "
v += "="
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "binary operators compare", ()->
# !== ===
for v in "< > <= >= == !=".split " "
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "function", ()->
for v in "-> =>".split " "
do (v)->
it "should tokenize '#{v}' as arrow_function", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "arrow_function"
describe "this", ()->
it "should tokenize '@' as this", ()->
v = g._tokenize "@"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "this"
it "should tokenize '@a' as this and identifier", ()->
v = g._tokenize "@a"
assert.equal v.length, 2
assert.equal v[0][0].mx_hash.hash_key, "this"
assert.equal v[1][0].mx_hash.hash_key, "identifier"
describe "brackets", ()->
for v in "()[]{}"
do (v)->
it "should tokenize '#{v} as bracket", ()->
tl = g._tokenize v
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "bracket"
it "should tokenize '(a)->a' as 5 tokens", ()->
tl = g._tokenize "(a)->a"
assert.equal tl.length, 5
assert.equal tl[0][0].mx_hash.hash_key, "bracket"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
assert.equal tl[2][0].mx_hash.hash_key, "bracket"
assert.equal tl[3][0].mx_hash.hash_key, "arrow_function"
assert.equal tl[4][0].mx_hash.hash_key, "identifier"
describe "floats", ()->
# TEMP disabled
# .1
# .1e10
list = """
1.
1.1
1.e10
1.e+10
1.e-10
1.1e10
1e10
1e+10
1e-10
""".split /\n/g
for v in list
do (v)->
it "should tokenize '#{v}' as float_literal", ()->
tl = g._tokenize v
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "float_literal"
it "should tokenize '1.1+1' as 3 tokens", ()->
tl = g._tokenize "1.1+1"
assert.equal tl.length, 3
assert.equal tl[0][0].mx_hash.hash_key, "float_literal"
assert.equal tl[1][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[1][1].mx_hash.hash_key, "binary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '1e+' as 3 tokens", ()->
tl = g._tokenize "1e+"
assert.equal tl.length, 3
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
assert.equal tl[2][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[2][1].mx_hash.hash_key, "binary_operator"
it "should tokenize '1e' as 2 tokens", ()->
tl = g._tokenize "1e"
assert.equal tl.length, 2
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
describe "Multiline", ()->
it "should tokenize 'a\\n b' as a indent b dedent", ()->
tl = g._tokenize """
a
b
"""
assert.equal tl.length, 4
assert.equal tl[0][0].mx_hash.hash_key, "identifier"
assert.equal tl[1][0].mx_hash.hash_key, "indent"
assert.equal tl[2][0].mx_hash.hash_key, "identifier"
assert.equal tl[3][0].mx_hash.hash_key, "<KEY>"
describe "Comments", ()->
it "should tokenize '# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ ' as comment", ()->
tl = g._tokenize "# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ "
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
assert.equal tl[0][0].value, "# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ "
it "should tokenize '2+2#=4\\n4+4#=8' as 9 tokens including comments", ()->
tl = g._tokenize "2+2#=4\n4+4#=8"
assert.equal tl.length, 9
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[3][0].mx_hash.hash_key, "comment"
assert.equal tl[4][0].mx_hash.hash_key, "eol"
assert.equal tl[5][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[6][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[7][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[8][0].mx_hash.hash_key, "comment"
it "should tokenize '### 2 + 2 = 4\\n4 + 4 = 8\\n###' as comment", ()->
tl = g._tokenize "### 2 + 2 = 4\n4 + 4 = 8\n###"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
it "should tokenize '####################### COMMENT' as comment", ()->
tl = g._tokenize "####################### COMMENT"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
assert.equal tl[0][0].value, "####################### COMMENT"
describe "Whitespace", ()->
it "should tokenize \\n as empty", ()->
tl = g._tokenize "\n"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "empty"
it "should tokenize \\n1 as 2 tokens", ()->
tl = g._tokenize "\n1"
assert.equal tl.length, 2
it "should tokenize \\n\\n1 as 2 tokens", ()->
tl = g._tokenize "\n\n1"
assert.equal tl.length, 2
it "should tokenize \\n\\n\\n1 as 2 tokens", ()->
tl = g._tokenize "\n\n\n1"
assert.equal tl.length, 2
it "should tokenize 'a + b' as 'a', '+', 'b' with tail_space 1 1 0", ()->
tl = g._tokenize "a + b"
assert.equal tl.length, 3
assert.equal tl[0][0].value, "a"
assert.equal tl[0][0].mx_hash.tail_space, "1"
assert.equal tl[1][0].value, "+"
assert.equal tl[1][0].mx_hash.tail_space, "1"
assert.equal tl[2][0].value, "b"
assert.equal tl[2][0].mx_hash.tail_space, "0"
it "should tokenize 'a / b / c' as 5 tokens (not regexp!)", ()->
tl = g._tokenize "a / b / c"
assert.equal tl.length, 5
assert.equal tl[0][0].mx_hash.hash_key, "identifier"
assert.equal tl[1][0].mx_hash.hash_key, "binary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "identifier"
assert.equal tl[3][0].mx_hash.hash_key, "<KEY>_operator"
assert.equal tl[4][0].mx_hash.hash_key, "identifier"
describe "Double quoted strings", ()->
describe "valid inline strings", ()->
sample_list = """
""
"Some text"
"'"
"<NAME>'s Adventures in Wonderland"
"''"
"\\""
"\\\\"
"\\0"
"\\r"
"\\v"
"\\t"
"\\b"
"\\f"
"\\a"
"\\ "
"\\xFF"
"\\xFf"
"\\xff"
"\\u20FF"
"\\u20ff"
"\\u20fF"
"\\u{25}"
"\\u{10FFFF}"
"\\u{10ffff}"
"\\u{10fFFf}"
"# {a}"
"English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺"
""".split /\n/ # "
sample_list.push '"\\n"'
sample_list.push '"\\\n"'
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as string_literal_doubleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "string_literal_doubleq"
describe "valid block strings", ()->
sample_list = [
'"""English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺"""',
'"""\n heredoc\n """',
'"""\n heredoc with escapes \\n\\r\\t\\b\\f\\0\\\\\\"\\\'\\xFF\\uFFFF\\u{25}\\u{10FFFF}\n"""'
]
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as block_string_literal_doubleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "block_string_literal_doubleq"
describe "invalid", ()->
wrong_string_list = """
"'
'"
"abcd'
'abcd"
"a"a"
"\\u"
"\\u1"
"\\u{}"
"\\u{123456}"
"\\u{i}"
"\\x"
"\\x1"
""".split /\n/ #'
for sample in wrong_string_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
g._tokenize sample
, /Error: can't tokenize /
describe "Interpolated double quoted string", ()->
sample_list = '''
"#{a}"
---
" #{a} "
---
" #{a} #{b} "
---
" #{a} #{b}
"
---
""" #{a} """
---
""" #{a} #{b} """
---
""" #{a} #{b}
"""
'''.split /\n?---\n?/ # "
for sample in sample_list
do (sample)->
it "should tokenize #{sample}", ()->
ret = g._tokenize sample
for v in ret
for v2 in ret
if v2[0].value == '""'
throw new Error "\"\" parsed"
describe "Single quoted strings", ()->
describe "valid inline strings", ()->
sample_list = """
''
'Some text'
'"'
'""'
'"The Silmarillion" by <NAME>'
'\\''
'\\xff'
'\\u20fF'
'\\u{25}'
'\\u{10ffff}'
'\#{a}'
'\\\#{a}'
'English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺'
""".split /\n/ #"
sample_list.push "'\\\n'"
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as string_literal_singleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "string_literal_singleq"
describe "valid block strings", ()->
sample_list = [
"'''English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺'''",
"'''\n heredoc\n '''"
]
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as block_string_literal_singleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "block_string_literal_singleq"
describe "invalid", ()->
wrong_string_list = """
"'
'"
"abcd'
'abcd"
"a"a"
'a'a'
"\\u"
"\\u1"
"\\u{}"
"\\u{123456}"
"\\u{i}"
"\\x"
"\\x1"
""".split /\n/ #"
for sample in wrong_string_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
g._tokenize sample
, /Error: can't tokenize /
describe "Big List of Naughty Strings", ()->
# https://github.com/minimaxir/big-list-of-naughty-strings
# helper
test = (sample, i, token_name) ->
try
tl = g._tokenize sample
catch e
throw new Error """The tokenizer fails to process the string number #{i}: #{sample}
due to this error:
#{e}"""
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, token_name
it "BLNS double quoted via readFileSync", ()->
path_to_blns = path.join (path.dirname require.resolve "blns"), "resources", "blns.json"
blns_raw = fs.readFileSync path_to_blns, "utf8"
blns = (blns_raw.split /[\[,\]]\s*\n\s*/)[1...-1]
for sample, i in blns
test sample, i, "string_literal_doubleq"
blns = require "blns"
it "BLNS double quoted via require", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /"/g, '\\"'
sample = "\"#{sample}\""
test sample, i, "string_literal_doubleq"
it "BLNS single quoted", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /'/g, "\\'"
sample = "'#{sample}'"
test sample, i, "string_literal_singleq"
it "BLNS double quoted block (heredoc)", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /"""/g, '""\\"'
sample = sample.replace /"$/, '\\"'
sample = "\"\"\"#{sample}\"\"\""
test sample, i, "block_string_literal_doubleq"
it "BLNS single quoted block (heredoc)", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /'''/g, "''\\'"
sample = sample.replace /'$/, "\\'"
sample = "'''#{sample}'''"
test sample, i, "block_string_literal_singleq"
describe "Regexp", ()->
it "should tokenize 'a/b/c' as 3 tokens with regexp in the middle", ()->
tl = g._tokenize "a/b/c"
assert.equal tl.length, 3
assert.equal tl[1][0].mx_hash.hash_key, "regexp_literal"
it "should tokenize 'a/b' as 3 tokens without regexp", ()->
tl = g._tokenize "a/b"
assert.equal tl.length, 3
assert.notEqual tl[1][0].mx_hash.hash_key, "regexp_literal"
it "should tokenize 'a//b' as 3 tokens without regexp", ()->
tl = g._tokenize "a//b"
assert.equal tl.length, 3
assert.notEqual tl[1][0].mx_hash.hash_key, "regexp_literal"
# regexp must contain at least one symbol excluding whitespace
# escape policy for string constant should apply for regex
sample_list = """
/ab+c/
/ab+c/i
/ab+c/igmy
/ab+c/ymgi
/a/ii
/]/
/(/
/)/
""".split /\n/
# NOTE bad samples
for sample in sample_list
do (sample)->
it "should tokenize #{JSON.stringify sample} as regexp_literal", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "regexp_literal"
# /[/
sample_list = """
//
/
/ a/
""".split /\n/
for sample in sample_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
tl = g._tokenize sample
if tl[0][0].mx_hash.hash_key == "<KEY>"
assert.equal tl[0][1].mx_hash.hash_key, "regexp_literal"
else
assert.equal tl[0][0].mx_hash.hash_key, "regexp_literal"
describe "Here regexp", ()->
sample_list = """
///ab+c///
---
///ab+c///i
---
///ab+c///igmy
---
///ab+c///ymgi
---
///a///ii
---
///]///
---
///(///
---
///)///
---
///
///
---
///
a
///
---
///
/
///
""".split /\n?---\n?/
# NOTE bad samples
for sample in sample_list
do (sample)->
it "should tokenize #{JSON.stringify sample} as regexp_literal", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "here_regexp_literal"
describe "Pipes", ()->
it "should tokenize 'a | b | c' as 5 tokens", ()->
tl = g._tokenize "a | b | c"
assert.equal tl.length, 5
describe "TODO", ()->
| true | assert = require 'assert'
util = require 'fy/test_util'
fs = require 'fs'
path = require 'path'
g = require '../src/tokenizer'
pub = require '../src/index'
describe 'tokenizer section', ()->
it "public endpoint should works", (done)->
await pub.tokenize "id", {}, defer(err, v)
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "identifier"
await pub.tokenize "wtf кирилица", {}, defer(err, v)
assert err?
done()
describe "identifier", ()->
sample_list = "
qwerty
myvar123
someCamelCase
some_snake_case
CAPSLOCK
$
$scope
".split " "
for sample in sample_list
do (sample)->
it "should tokenize '#{sample}' as identifier", ()->
v = g._tokenize sample
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "identifier"
describe "integer literals", ()->
it "should tokenize '142857' as decimal_literal", ()->
v = g._tokenize "142857"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '0' as decimal_literal", ()->
v = g._tokenize "0"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '0777' as octal_literal", ()->
v = g._tokenize "0777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0o777' as octal_literal", ()->
v = g._tokenize "0o777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0O777' as octal_literal", ()->
v = g._tokenize "0O777"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "octal_literal"
it "should tokenize '0xabcd8' as hexadecimal_literal", ()->
v = g._tokenize "0xabcd8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0XABCD8' as hexadecimal_literal", ()->
v = g._tokenize "0XABCD8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0xAbCd8' as hexadecimal_literal", ()->
v = g._tokenize "0xAbCd8"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "hexadecimal_literal"
it "should tokenize '0b10101' as binary_literal", ()->
v = g._tokenize "0b10101"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_literal"
it "should tokenize '0B10101' as binary_literal", ()->
v = g._tokenize "0B10101"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_literal"
it "should tokenize '-1' as 2 tokens", ()->
v = g._tokenize "-1"
assert.equal v.length, 2
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
assert.equal v[1][0].mx_hash.hash_key, "decimal_literal"
describe "mixed operators", ()->
for v in "+ -".split " "
# for v in "+ - ?".split " "
do (v)->
it "should tokenize '#{v}' as unary_operator and binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
assert.equal v[0][1].mx_hash.hash_key, "binary_operator"
describe "unary operators", ()->
for v in "~ ! ++ -- not typeof void new delete".split " "
do (v)->
it "should tokenize '#{v}' as unary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "unary_operator"
describe "binary operators", ()->
for v in "* / % ** // %% << >> >>> & | ^ && || ^^ and or xor instanceof in of is isnt ? . ?. :: ?:: .. ...".split " "
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "binary operators assign", ()->
for v in "+ - * / % ** // %% << >> >>> & | ^ && || ^^ and or xor ?".split " "
v += "="
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "binary operators compare", ()->
# !== ===
for v in "< > <= >= == !=".split " "
do (v)->
it "should tokenize '#{v}' as binary_operator", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "binary_operator"
describe "function", ()->
for v in "-> =>".split " "
do (v)->
it "should tokenize '#{v}' as arrow_function", ()->
v = g._tokenize v
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "arrow_function"
describe "this", ()->
it "should tokenize '@' as this", ()->
v = g._tokenize "@"
assert.equal v.length, 1
assert.equal v[0][0].mx_hash.hash_key, "this"
it "should tokenize '@a' as this and identifier", ()->
v = g._tokenize "@a"
assert.equal v.length, 2
assert.equal v[0][0].mx_hash.hash_key, "this"
assert.equal v[1][0].mx_hash.hash_key, "identifier"
describe "brackets", ()->
for v in "()[]{}"
do (v)->
it "should tokenize '#{v} as bracket", ()->
tl = g._tokenize v
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "bracket"
it "should tokenize '(a)->a' as 5 tokens", ()->
tl = g._tokenize "(a)->a"
assert.equal tl.length, 5
assert.equal tl[0][0].mx_hash.hash_key, "bracket"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
assert.equal tl[2][0].mx_hash.hash_key, "bracket"
assert.equal tl[3][0].mx_hash.hash_key, "arrow_function"
assert.equal tl[4][0].mx_hash.hash_key, "identifier"
describe "floats", ()->
# TEMP disabled
# .1
# .1e10
list = """
1.
1.1
1.e10
1.e+10
1.e-10
1.1e10
1e10
1e+10
1e-10
""".split /\n/g
for v in list
do (v)->
it "should tokenize '#{v}' as float_literal", ()->
tl = g._tokenize v
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "float_literal"
it "should tokenize '1.1+1' as 3 tokens", ()->
tl = g._tokenize "1.1+1"
assert.equal tl.length, 3
assert.equal tl[0][0].mx_hash.hash_key, "float_literal"
assert.equal tl[1][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[1][1].mx_hash.hash_key, "binary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "decimal_literal"
it "should tokenize '1e+' as 3 tokens", ()->
tl = g._tokenize "1e+"
assert.equal tl.length, 3
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
assert.equal tl[2][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[2][1].mx_hash.hash_key, "binary_operator"
it "should tokenize '1e' as 2 tokens", ()->
tl = g._tokenize "1e"
assert.equal tl.length, 2
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "identifier"
describe "Multiline", ()->
it "should tokenize 'a\\n b' as a indent b dedent", ()->
tl = g._tokenize """
a
b
"""
assert.equal tl.length, 4
assert.equal tl[0][0].mx_hash.hash_key, "identifier"
assert.equal tl[1][0].mx_hash.hash_key, "indent"
assert.equal tl[2][0].mx_hash.hash_key, "identifier"
assert.equal tl[3][0].mx_hash.hash_key, "PI:KEY:<KEY>END_PI"
describe "Comments", ()->
it "should tokenize '# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ ' as comment", ()->
tl = g._tokenize "# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ "
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
assert.equal tl[0][0].value, "# wpe ri32p q92p 4rpu34iqwr349i+-+-*/*/ "
it "should tokenize '2+2#=4\\n4+4#=8' as 9 tokens including comments", ()->
tl = g._tokenize "2+2#=4\n4+4#=8"
assert.equal tl.length, 9
assert.equal tl[0][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[1][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[3][0].mx_hash.hash_key, "comment"
assert.equal tl[4][0].mx_hash.hash_key, "eol"
assert.equal tl[5][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[6][0].mx_hash.hash_key, "unary_operator"
assert.equal tl[7][0].mx_hash.hash_key, "decimal_literal"
assert.equal tl[8][0].mx_hash.hash_key, "comment"
it "should tokenize '### 2 + 2 = 4\\n4 + 4 = 8\\n###' as comment", ()->
tl = g._tokenize "### 2 + 2 = 4\n4 + 4 = 8\n###"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
it "should tokenize '####################### COMMENT' as comment", ()->
tl = g._tokenize "####################### COMMENT"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "comment"
assert.equal tl[0][0].value, "####################### COMMENT"
describe "Whitespace", ()->
it "should tokenize \\n as empty", ()->
tl = g._tokenize "\n"
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "empty"
it "should tokenize \\n1 as 2 tokens", ()->
tl = g._tokenize "\n1"
assert.equal tl.length, 2
it "should tokenize \\n\\n1 as 2 tokens", ()->
tl = g._tokenize "\n\n1"
assert.equal tl.length, 2
it "should tokenize \\n\\n\\n1 as 2 tokens", ()->
tl = g._tokenize "\n\n\n1"
assert.equal tl.length, 2
it "should tokenize 'a + b' as 'a', '+', 'b' with tail_space 1 1 0", ()->
tl = g._tokenize "a + b"
assert.equal tl.length, 3
assert.equal tl[0][0].value, "a"
assert.equal tl[0][0].mx_hash.tail_space, "1"
assert.equal tl[1][0].value, "+"
assert.equal tl[1][0].mx_hash.tail_space, "1"
assert.equal tl[2][0].value, "b"
assert.equal tl[2][0].mx_hash.tail_space, "0"
it "should tokenize 'a / b / c' as 5 tokens (not regexp!)", ()->
tl = g._tokenize "a / b / c"
assert.equal tl.length, 5
assert.equal tl[0][0].mx_hash.hash_key, "identifier"
assert.equal tl[1][0].mx_hash.hash_key, "binary_operator"
assert.equal tl[2][0].mx_hash.hash_key, "identifier"
assert.equal tl[3][0].mx_hash.hash_key, "PI:KEY:<KEY>END_PI_operator"
assert.equal tl[4][0].mx_hash.hash_key, "identifier"
describe "Double quoted strings", ()->
describe "valid inline strings", ()->
sample_list = """
""
"Some text"
"'"
"PI:NAME:<NAME>END_PI's Adventures in Wonderland"
"''"
"\\""
"\\\\"
"\\0"
"\\r"
"\\v"
"\\t"
"\\b"
"\\f"
"\\a"
"\\ "
"\\xFF"
"\\xFf"
"\\xff"
"\\u20FF"
"\\u20ff"
"\\u20fF"
"\\u{25}"
"\\u{10FFFF}"
"\\u{10ffff}"
"\\u{10fFFf}"
"# {a}"
"English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺"
""".split /\n/ # "
sample_list.push '"\\n"'
sample_list.push '"\\\n"'
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as string_literal_doubleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "string_literal_doubleq"
describe "valid block strings", ()->
sample_list = [
'"""English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺"""',
'"""\n heredoc\n """',
'"""\n heredoc with escapes \\n\\r\\t\\b\\f\\0\\\\\\"\\\'\\xFF\\uFFFF\\u{25}\\u{10FFFF}\n"""'
]
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as block_string_literal_doubleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "block_string_literal_doubleq"
describe "invalid", ()->
wrong_string_list = """
"'
'"
"abcd'
'abcd"
"a"a"
"\\u"
"\\u1"
"\\u{}"
"\\u{123456}"
"\\u{i}"
"\\x"
"\\x1"
""".split /\n/ #'
for sample in wrong_string_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
g._tokenize sample
, /Error: can't tokenize /
describe "Interpolated double quoted string", ()->
sample_list = '''
"#{a}"
---
" #{a} "
---
" #{a} #{b} "
---
" #{a} #{b}
"
---
""" #{a} """
---
""" #{a} #{b} """
---
""" #{a} #{b}
"""
'''.split /\n?---\n?/ # "
for sample in sample_list
do (sample)->
it "should tokenize #{sample}", ()->
ret = g._tokenize sample
for v in ret
for v2 in ret
if v2[0].value == '""'
throw new Error "\"\" parsed"
describe "Single quoted strings", ()->
describe "valid inline strings", ()->
sample_list = """
''
'Some text'
'"'
'""'
'"The Silmarillion" by PI:NAME:<NAME>END_PI'
'\\''
'\\xff'
'\\u20fF'
'\\u{25}'
'\\u{10ffff}'
'\#{a}'
'\\\#{a}'
'English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺'
""".split /\n/ #"
sample_list.push "'\\\n'"
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as string_literal_singleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "string_literal_singleq"
describe "valid block strings", ()->
sample_list = [
"'''English Français Українська Ελληνικά ქართული עברית العربية 日本語 中文 한국어 हिन्दी བོད་སྐད रोमानी 𐌲𐌿𐍄𐌹𐍃𐌺'''",
"'''\n heredoc\n '''"
]
for sample in sample_list
do (sample)->
it "should tokenize #{sample} as block_string_literal_singleq", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "block_string_literal_singleq"
describe "invalid", ()->
wrong_string_list = """
"'
'"
"abcd'
'abcd"
"a"a"
'a'a'
"\\u"
"\\u1"
"\\u{}"
"\\u{123456}"
"\\u{i}"
"\\x"
"\\x1"
""".split /\n/ #"
for sample in wrong_string_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
g._tokenize sample
, /Error: can't tokenize /
describe "Big List of Naughty Strings", ()->
# https://github.com/minimaxir/big-list-of-naughty-strings
# helper
test = (sample, i, token_name) ->
try
tl = g._tokenize sample
catch e
throw new Error """The tokenizer fails to process the string number #{i}: #{sample}
due to this error:
#{e}"""
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, token_name
it "BLNS double quoted via readFileSync", ()->
path_to_blns = path.join (path.dirname require.resolve "blns"), "resources", "blns.json"
blns_raw = fs.readFileSync path_to_blns, "utf8"
blns = (blns_raw.split /[\[,\]]\s*\n\s*/)[1...-1]
for sample, i in blns
test sample, i, "string_literal_doubleq"
blns = require "blns"
it "BLNS double quoted via require", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /"/g, '\\"'
sample = "\"#{sample}\""
test sample, i, "string_literal_doubleq"
it "BLNS single quoted", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /'/g, "\\'"
sample = "'#{sample}'"
test sample, i, "string_literal_singleq"
it "BLNS double quoted block (heredoc)", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /"""/g, '""\\"'
sample = sample.replace /"$/, '\\"'
sample = "\"\"\"#{sample}\"\"\""
test sample, i, "block_string_literal_doubleq"
it "BLNS single quoted block (heredoc)", ()->
for sample, i in blns
continue if sample.includes "\u0007" # FUCK DAT BEEP
sample = sample.replace /\\/g, "\\\\"
sample = sample.replace /'''/g, "''\\'"
sample = sample.replace /'$/, "\\'"
sample = "'''#{sample}'''"
test sample, i, "block_string_literal_singleq"
describe "Regexp", ()->
it "should tokenize 'a/b/c' as 3 tokens with regexp in the middle", ()->
tl = g._tokenize "a/b/c"
assert.equal tl.length, 3
assert.equal tl[1][0].mx_hash.hash_key, "regexp_literal"
it "should tokenize 'a/b' as 3 tokens without regexp", ()->
tl = g._tokenize "a/b"
assert.equal tl.length, 3
assert.notEqual tl[1][0].mx_hash.hash_key, "regexp_literal"
it "should tokenize 'a//b' as 3 tokens without regexp", ()->
tl = g._tokenize "a//b"
assert.equal tl.length, 3
assert.notEqual tl[1][0].mx_hash.hash_key, "regexp_literal"
# regexp must contain at least one symbol excluding whitespace
# escape policy for string constant should apply for regex
sample_list = """
/ab+c/
/ab+c/i
/ab+c/igmy
/ab+c/ymgi
/a/ii
/]/
/(/
/)/
""".split /\n/
# NOTE bad samples
for sample in sample_list
do (sample)->
it "should tokenize #{JSON.stringify sample} as regexp_literal", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "regexp_literal"
# /[/
sample_list = """
//
/
/ a/
""".split /\n/
for sample in sample_list
do (sample)->
it "should not tokenize #{sample}", ()->
assert.throws ()->
tl = g._tokenize sample
if tl[0][0].mx_hash.hash_key == "PI:KEY:<KEY>END_PI"
assert.equal tl[0][1].mx_hash.hash_key, "regexp_literal"
else
assert.equal tl[0][0].mx_hash.hash_key, "regexp_literal"
describe "Here regexp", ()->
sample_list = """
///ab+c///
---
///ab+c///i
---
///ab+c///igmy
---
///ab+c///ymgi
---
///a///ii
---
///]///
---
///(///
---
///)///
---
///
///
---
///
a
///
---
///
/
///
""".split /\n?---\n?/
# NOTE bad samples
for sample in sample_list
do (sample)->
it "should tokenize #{JSON.stringify sample} as regexp_literal", ()->
tl = g._tokenize sample
assert.equal tl.length, 1
assert.equal tl[0][0].mx_hash.hash_key, "here_regexp_literal"
describe "Pipes", ()->
it "should tokenize 'a | b | c' as 5 tokens", ()->
tl = g._tokenize "a | b | c"
assert.equal tl.length, 5
describe "TODO", ()->
|
[
{
"context": ".findOne({ space: space, user: this.userId, key: 'start_flows' }, { fields: { value: 1 } })\n\n\t\tstart_flows = ke",
"end": 149,
"score": 0.8935408592224121,
"start": 138,
"tag": "KEY",
"value": "start_flows"
},
{
"context": " }, { space: space, user: this.userId, key:... | creator/packages/steedos-workflow/server/methods/start_flow.coffee | yicone/steedos-platform | 42 | Meteor.methods
start_flow: (space, flowId, start) ->
keyValue = db.steedos_keyvalues.findOne({ space: space, user: this.userId, key: 'start_flows' }, { fields: { value: 1 } })
start_flows = keyValue?.value || []
if start
start_flows.push(flowId)
start_flows = _.uniq(start_flows)
else
start_flows.remove(start_flows.indexOf(flowId))
if keyValue
db.steedos_keyvalues.update({ _id: keyValue._id }, { space: space, user: this.userId, key: 'start_flows', value: start_flows })
else
db.steedos_keyvalues.insert({ space: space, user: this.userId, key: 'start_flows', value: start_flows })
| 55524 | Meteor.methods
start_flow: (space, flowId, start) ->
keyValue = db.steedos_keyvalues.findOne({ space: space, user: this.userId, key: '<KEY>' }, { fields: { value: 1 } })
start_flows = keyValue?.value || []
if start
start_flows.push(flowId)
start_flows = _.uniq(start_flows)
else
start_flows.remove(start_flows.indexOf(flowId))
if keyValue
db.steedos_keyvalues.update({ _id: keyValue._id }, { space: space, user: this.userId, key: 'start<KEY>_flows', value: start_flows })
else
db.steedos_keyvalues.insert({ space: space, user: this.userId, key: 'start_<KEY>', value: start_flows })
| true | Meteor.methods
start_flow: (space, flowId, start) ->
keyValue = db.steedos_keyvalues.findOne({ space: space, user: this.userId, key: 'PI:KEY:<KEY>END_PI' }, { fields: { value: 1 } })
start_flows = keyValue?.value || []
if start
start_flows.push(flowId)
start_flows = _.uniq(start_flows)
else
start_flows.remove(start_flows.indexOf(flowId))
if keyValue
db.steedos_keyvalues.update({ _id: keyValue._id }, { space: space, user: this.userId, key: 'startPI:KEY:<KEY>END_PI_flows', value: start_flows })
else
db.steedos_keyvalues.insert({ space: space, user: this.userId, key: 'start_PI:KEY:<KEY>END_PI', value: start_flows })
|
[
{
"context": "cape(body.email).trim().toLowerCase()\n\t\tpassword = body.password\n\t\tusername = email.match(/^[^@]*/)\n\t\tif @hasZeroL",
"end": 835,
"score": 0.9989154934883118,
"start": 822,
"tag": "PASSWORD",
"value": "body.password"
}
] | app/coffee/Features/User/UserRegistrationHandler.coffee | sandstormports/web-sharelatex | 1 | sanitize = require('sanitizer')
User = require("../../models/User").User
UserCreator = require("./UserCreator")
AuthenticationManager = require("../Authentication/AuthenticationManager")
NewsLetterManager = require("../Newsletter/NewsletterManager")
async = require("async")
logger = require("logger-sharelatex")
module.exports =
validateEmail : (email) ->
re = /^(([^<>()[\]\\.,;:\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,}))$/
return re.test(email)
hasZeroLengths : (props) ->
hasZeroLength = false
props.forEach (prop) ->
if prop.length == 0
hasZeroLength = true
return hasZeroLength
_registrationRequestIsValid : (body, callback)->
email = sanitize.escape(body.email).trim().toLowerCase()
password = body.password
username = email.match(/^[^@]*/)
if @hasZeroLengths([password, email])
return false
else if !@validateEmail(email)
return false
else
return true
_createNewUserIfRequired: (user, userDetails, callback)->
if !user?
UserCreator.createNewUser {holdingAccount:false, email:userDetails.email}, callback
else
callback null, user
registerNewUser: (userDetails, callback)->
self = @
requestIsValid = @_registrationRequestIsValid userDetails
if !requestIsValid
return callback(new Error("request is not valid"))
userDetails.email = userDetails.email?.trim()?.toLowerCase()
User.findOne email:userDetails.email, (err, user)->
if err?
return callback err
if user?.holdingAccount == false
return callback("EmailAlreadyRegisterd")
self._createNewUserIfRequired user, userDetails, (err, user)->
if err?
return callback(err)
async.series [
(cb)-> User.update {_id: user._id}, {"$set":{holdingAccount:false}}, cb
(cb)-> AuthenticationManager.setUserPassword user._id, userDetails.password, cb
(cb)-> NewsLetterManager.subscribe user, cb
(cb)->
emailOpts =
first_name:user.first_name
to: user.email
EmailHandler.sendEmail "welcome", emailOpts, cb
], (err)->
logger.log user: user, "registered"
callback(err, user)
registerNewUserIfRequired: (userDetails, callback)->
self = @
User.findOne email:userDetails.email, (err, user)->
if err?
return callback err
if user?
return callback(err, user)
user = new User()
user.email = userDetails.email
user.first_name = userDetails.name
user.last_name = ""
user.save (err)->
callback(err, user)
| 172192 | sanitize = require('sanitizer')
User = require("../../models/User").User
UserCreator = require("./UserCreator")
AuthenticationManager = require("../Authentication/AuthenticationManager")
NewsLetterManager = require("../Newsletter/NewsletterManager")
async = require("async")
logger = require("logger-sharelatex")
module.exports =
validateEmail : (email) ->
re = /^(([^<>()[\]\\.,;:\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,}))$/
return re.test(email)
hasZeroLengths : (props) ->
hasZeroLength = false
props.forEach (prop) ->
if prop.length == 0
hasZeroLength = true
return hasZeroLength
_registrationRequestIsValid : (body, callback)->
email = sanitize.escape(body.email).trim().toLowerCase()
password = <PASSWORD>
username = email.match(/^[^@]*/)
if @hasZeroLengths([password, email])
return false
else if !@validateEmail(email)
return false
else
return true
_createNewUserIfRequired: (user, userDetails, callback)->
if !user?
UserCreator.createNewUser {holdingAccount:false, email:userDetails.email}, callback
else
callback null, user
registerNewUser: (userDetails, callback)->
self = @
requestIsValid = @_registrationRequestIsValid userDetails
if !requestIsValid
return callback(new Error("request is not valid"))
userDetails.email = userDetails.email?.trim()?.toLowerCase()
User.findOne email:userDetails.email, (err, user)->
if err?
return callback err
if user?.holdingAccount == false
return callback("EmailAlreadyRegisterd")
self._createNewUserIfRequired user, userDetails, (err, user)->
if err?
return callback(err)
async.series [
(cb)-> User.update {_id: user._id}, {"$set":{holdingAccount:false}}, cb
(cb)-> AuthenticationManager.setUserPassword user._id, userDetails.password, cb
(cb)-> NewsLetterManager.subscribe user, cb
(cb)->
emailOpts =
first_name:user.first_name
to: user.email
EmailHandler.sendEmail "welcome", emailOpts, cb
], (err)->
logger.log user: user, "registered"
callback(err, user)
registerNewUserIfRequired: (userDetails, callback)->
self = @
User.findOne email:userDetails.email, (err, user)->
if err?
return callback err
if user?
return callback(err, user)
user = new User()
user.email = userDetails.email
user.first_name = userDetails.name
user.last_name = ""
user.save (err)->
callback(err, user)
| true | sanitize = require('sanitizer')
User = require("../../models/User").User
UserCreator = require("./UserCreator")
AuthenticationManager = require("../Authentication/AuthenticationManager")
NewsLetterManager = require("../Newsletter/NewsletterManager")
async = require("async")
logger = require("logger-sharelatex")
module.exports =
validateEmail : (email) ->
re = /^(([^<>()[\]\\.,;:\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,}))$/
return re.test(email)
hasZeroLengths : (props) ->
hasZeroLength = false
props.forEach (prop) ->
if prop.length == 0
hasZeroLength = true
return hasZeroLength
_registrationRequestIsValid : (body, callback)->
email = sanitize.escape(body.email).trim().toLowerCase()
password = PI:PASSWORD:<PASSWORD>END_PI
username = email.match(/^[^@]*/)
if @hasZeroLengths([password, email])
return false
else if !@validateEmail(email)
return false
else
return true
_createNewUserIfRequired: (user, userDetails, callback)->
if !user?
UserCreator.createNewUser {holdingAccount:false, email:userDetails.email}, callback
else
callback null, user
registerNewUser: (userDetails, callback)->
self = @
requestIsValid = @_registrationRequestIsValid userDetails
if !requestIsValid
return callback(new Error("request is not valid"))
userDetails.email = userDetails.email?.trim()?.toLowerCase()
User.findOne email:userDetails.email, (err, user)->
if err?
return callback err
if user?.holdingAccount == false
return callback("EmailAlreadyRegisterd")
self._createNewUserIfRequired user, userDetails, (err, user)->
if err?
return callback(err)
async.series [
(cb)-> User.update {_id: user._id}, {"$set":{holdingAccount:false}}, cb
(cb)-> AuthenticationManager.setUserPassword user._id, userDetails.password, cb
(cb)-> NewsLetterManager.subscribe user, cb
(cb)->
emailOpts =
first_name:user.first_name
to: user.email
EmailHandler.sendEmail "welcome", emailOpts, cb
], (err)->
logger.log user: user, "registered"
callback(err, user)
registerNewUserIfRequired: (userDetails, callback)->
self = @
User.findOne email:userDetails.email, (err, user)->
if err?
return callback err
if user?
return callback(err, user)
user = new User()
user.email = userDetails.email
user.first_name = userDetails.name
user.last_name = ""
user.save (err)->
callback(err, user)
|
[
{
"context": "ription Main module of the application.\n# @author Michael Lin, Snaphappi Inc.\n###\nangular\n.module('starter', [\n",
"end": 122,
"score": 0.9996417760848999,
"start": 111,
"tag": "NAME",
"value": "Michael Lin"
}
] | app/js/app.coffee | mixersoft/ionic-parse-facebook-scaffold | 5 | 'use strict'
###*
# @ngdoc overview
# @name starter
# @description Main module of the application.
# @author Michael Lin, Snaphappi Inc.
###
angular
.module('starter', [
'ionic',
'ngCordova',
'ngStorage'
'partials'
'snappi.util'
'parse.backend'
'parse.push'
'ionic.deploy'
# 'ionic.push'
'auth'
'ngOpenFB'
])
.constant( 'CHECK_DEPLOYED', false) # $ionicDeploy: check for updates on bootstrap
.value( 'exportDebug', {} ) # methods to exportDebug to JS global
.config [
'$ionicAppProvider', 'auth.KEYS'
($ionicAppProvider, KEYS)->
$ionicAppProvider.identify {
app_id: KEYS.ionic.app_id
api_key: KEYS.ionic.api_key
dev_push: false
}
return
]
.config ['$ionicConfigProvider',
($ionicConfigProvider)->
return
]
.run [
'ionicDeploy', '$rootScope'
'CHECK_DEPLOYED', 'exportDebug'
(ionicDeploy, $rootScope, CHECK_DEPLOYED, exportDebug)->
$rootScope['deploy'] = ionicDeploy
exportDebug['CHECK_DEPLOYED'] = CHECK_DEPLOYED
exportDebug['ionicDeploy'] = ionicDeploy
return if CHECK_DEPLOYED == false
# NOTE: $ionicDeploy is still loading the latest deployed image from app.ionic.io
# so you won't get the latest code from `ionic build ios`
# However, the ionic team is working on a fix to allow DEV deployments.
# for now, the `cordova.js` hack in index.html seems to work
ionicDeploy.check()
return
]
.run [
'$ionicPlatform', '$rootScope', 'deviceReady', 'exportDebug', 'auth.KEYS', 'ngFB', 'appProfile'
($ionicPlatform, $rootScope, deviceReady, exportDebug, KEYS, ngFB, appProfile)->
window.debug = exportDebug
ngFB.init( { appId: KEYS.facebook.app_id })
Parse.initialize( KEYS.parse.APP_ID, KEYS.parse.JS_KEY )
$rootScope.parseUser = Parse.User.current()
$ionicPlatform.ready ()->
# Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
# for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true) if window.cordova?.plugins.Keyboard
# org.apache.cordova.statusbar required
StatusBar.styleDefault() if window.StatusBar?
return
]
.config [
'$stateProvider',
'$urlRouterProvider',
($stateProvider, $urlRouterProvider)->
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "/partials/templates/menu.html",
controller: 'AppCtrl'
})
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "/partials/home.html"
controller: 'HomeCtrl'
}
}
})
.state('app.profile', {
url: "/profile",
views: {
'menuContent': {
templateUrl: "/partials/profile.html"
controller: 'UserCtrl'
}
}
})
.state('app.profile.sign-in', {
url: "/sign-in",
# views: {
# 'menuContent': {
# templateUrl: "/partials/templates/sign-in.html"
# controller: 'UserCtrl'
# }
# }
})
# // if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
]
.controller 'AppCtrl', [
'$scope'
'$rootScope' , '$state'
'$timeout'
'$ionicLoading'
'deviceReady', 'exportDebug'
'$localStorage'
'parsePush'
# 'ionicPush'
'appProfile', 'appFacebook'
($scope, $rootScope, $state, $timeout, $ionicLoading, deviceReady, exportDebug, $localStorage, parsePush, appProfile, appFacebook)->
$scope.deviceReady = deviceReady
_.extend $rootScope, {
$state : $state
'user' : $rootScope.parseUser?.toJSON() || {}
device : null # deviceReady.device(platform)
}
$scope.showLoading = (value = true, timeout=5000)->
return $ionicLoading.hide() if !value
$ionicLoading.show({
template: '<ion-spinner class="spinner-light" icon="lines"></ion-spinner>'
duration: timeout
})
$scope.hideLoading = (delay=0)->
$timeout ()->
$ionicLoading.hide();
, delay
$scope.$on 'user:sign-in', (args)->
console.log "$broadcast user:sign-in received"
parsePush.registerP()
$scope.$on 'user:sign-out', (args)->
console.log "$broadcast user:sign-out received"
parsePush.registerP()
$rootScope.localStorage = $localStorage
if $rootScope.localStorage['device']?
platform = $rootScope.localStorage['device']
parsePush.initialize( platform )
exportDebug['$platform'] = $rootScope['device'] = deviceReady.device(platform)
console.log 'localStorage $platform=' + JSON.stringify exportDebug['$platform']
else
# platform
deviceReady.waitP().then (platform)->
exportDebug['$platform'] = $rootScope['device'] = $rootScope.localStorage['device'] = platform
console.log 'deviceReady $platform=' + JSON.stringify platform
parsePush.initialize( platform ).registerP()
return
, (err)->
console.warn err
# load FB profile if available
if !_.isEmpty $rootScope.user
appFacebook.checkLoginP($rootScope.user)
.then (status)->
# only if logged in
$rootScope.user['fbProfile'] = $localStorage['fbProfile']
# update fbProfile
return appFacebook.getMeP().then (resp)->
return 'done'
exportDebug['ls'] = $localStorage
exportDebug['$root'] = $rootScope
return
]
| 137877 | 'use strict'
###*
# @ngdoc overview
# @name starter
# @description Main module of the application.
# @author <NAME>, Snaphappi Inc.
###
angular
.module('starter', [
'ionic',
'ngCordova',
'ngStorage'
'partials'
'snappi.util'
'parse.backend'
'parse.push'
'ionic.deploy'
# 'ionic.push'
'auth'
'ngOpenFB'
])
.constant( 'CHECK_DEPLOYED', false) # $ionicDeploy: check for updates on bootstrap
.value( 'exportDebug', {} ) # methods to exportDebug to JS global
.config [
'$ionicAppProvider', 'auth.KEYS'
($ionicAppProvider, KEYS)->
$ionicAppProvider.identify {
app_id: KEYS.ionic.app_id
api_key: KEYS.ionic.api_key
dev_push: false
}
return
]
.config ['$ionicConfigProvider',
($ionicConfigProvider)->
return
]
.run [
'ionicDeploy', '$rootScope'
'CHECK_DEPLOYED', 'exportDebug'
(ionicDeploy, $rootScope, CHECK_DEPLOYED, exportDebug)->
$rootScope['deploy'] = ionicDeploy
exportDebug['CHECK_DEPLOYED'] = CHECK_DEPLOYED
exportDebug['ionicDeploy'] = ionicDeploy
return if CHECK_DEPLOYED == false
# NOTE: $ionicDeploy is still loading the latest deployed image from app.ionic.io
# so you won't get the latest code from `ionic build ios`
# However, the ionic team is working on a fix to allow DEV deployments.
# for now, the `cordova.js` hack in index.html seems to work
ionicDeploy.check()
return
]
.run [
'$ionicPlatform', '$rootScope', 'deviceReady', 'exportDebug', 'auth.KEYS', 'ngFB', 'appProfile'
($ionicPlatform, $rootScope, deviceReady, exportDebug, KEYS, ngFB, appProfile)->
window.debug = exportDebug
ngFB.init( { appId: KEYS.facebook.app_id })
Parse.initialize( KEYS.parse.APP_ID, KEYS.parse.JS_KEY )
$rootScope.parseUser = Parse.User.current()
$ionicPlatform.ready ()->
# Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
# for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true) if window.cordova?.plugins.Keyboard
# org.apache.cordova.statusbar required
StatusBar.styleDefault() if window.StatusBar?
return
]
.config [
'$stateProvider',
'$urlRouterProvider',
($stateProvider, $urlRouterProvider)->
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "/partials/templates/menu.html",
controller: 'AppCtrl'
})
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "/partials/home.html"
controller: 'HomeCtrl'
}
}
})
.state('app.profile', {
url: "/profile",
views: {
'menuContent': {
templateUrl: "/partials/profile.html"
controller: 'UserCtrl'
}
}
})
.state('app.profile.sign-in', {
url: "/sign-in",
# views: {
# 'menuContent': {
# templateUrl: "/partials/templates/sign-in.html"
# controller: 'UserCtrl'
# }
# }
})
# // if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
]
.controller 'AppCtrl', [
'$scope'
'$rootScope' , '$state'
'$timeout'
'$ionicLoading'
'deviceReady', 'exportDebug'
'$localStorage'
'parsePush'
# 'ionicPush'
'appProfile', 'appFacebook'
($scope, $rootScope, $state, $timeout, $ionicLoading, deviceReady, exportDebug, $localStorage, parsePush, appProfile, appFacebook)->
$scope.deviceReady = deviceReady
_.extend $rootScope, {
$state : $state
'user' : $rootScope.parseUser?.toJSON() || {}
device : null # deviceReady.device(platform)
}
$scope.showLoading = (value = true, timeout=5000)->
return $ionicLoading.hide() if !value
$ionicLoading.show({
template: '<ion-spinner class="spinner-light" icon="lines"></ion-spinner>'
duration: timeout
})
$scope.hideLoading = (delay=0)->
$timeout ()->
$ionicLoading.hide();
, delay
$scope.$on 'user:sign-in', (args)->
console.log "$broadcast user:sign-in received"
parsePush.registerP()
$scope.$on 'user:sign-out', (args)->
console.log "$broadcast user:sign-out received"
parsePush.registerP()
$rootScope.localStorage = $localStorage
if $rootScope.localStorage['device']?
platform = $rootScope.localStorage['device']
parsePush.initialize( platform )
exportDebug['$platform'] = $rootScope['device'] = deviceReady.device(platform)
console.log 'localStorage $platform=' + JSON.stringify exportDebug['$platform']
else
# platform
deviceReady.waitP().then (platform)->
exportDebug['$platform'] = $rootScope['device'] = $rootScope.localStorage['device'] = platform
console.log 'deviceReady $platform=' + JSON.stringify platform
parsePush.initialize( platform ).registerP()
return
, (err)->
console.warn err
# load FB profile if available
if !_.isEmpty $rootScope.user
appFacebook.checkLoginP($rootScope.user)
.then (status)->
# only if logged in
$rootScope.user['fbProfile'] = $localStorage['fbProfile']
# update fbProfile
return appFacebook.getMeP().then (resp)->
return 'done'
exportDebug['ls'] = $localStorage
exportDebug['$root'] = $rootScope
return
]
| true | 'use strict'
###*
# @ngdoc overview
# @name starter
# @description Main module of the application.
# @author PI:NAME:<NAME>END_PI, Snaphappi Inc.
###
angular
.module('starter', [
'ionic',
'ngCordova',
'ngStorage'
'partials'
'snappi.util'
'parse.backend'
'parse.push'
'ionic.deploy'
# 'ionic.push'
'auth'
'ngOpenFB'
])
.constant( 'CHECK_DEPLOYED', false) # $ionicDeploy: check for updates on bootstrap
.value( 'exportDebug', {} ) # methods to exportDebug to JS global
.config [
'$ionicAppProvider', 'auth.KEYS'
($ionicAppProvider, KEYS)->
$ionicAppProvider.identify {
app_id: KEYS.ionic.app_id
api_key: KEYS.ionic.api_key
dev_push: false
}
return
]
.config ['$ionicConfigProvider',
($ionicConfigProvider)->
return
]
.run [
'ionicDeploy', '$rootScope'
'CHECK_DEPLOYED', 'exportDebug'
(ionicDeploy, $rootScope, CHECK_DEPLOYED, exportDebug)->
$rootScope['deploy'] = ionicDeploy
exportDebug['CHECK_DEPLOYED'] = CHECK_DEPLOYED
exportDebug['ionicDeploy'] = ionicDeploy
return if CHECK_DEPLOYED == false
# NOTE: $ionicDeploy is still loading the latest deployed image from app.ionic.io
# so you won't get the latest code from `ionic build ios`
# However, the ionic team is working on a fix to allow DEV deployments.
# for now, the `cordova.js` hack in index.html seems to work
ionicDeploy.check()
return
]
.run [
'$ionicPlatform', '$rootScope', 'deviceReady', 'exportDebug', 'auth.KEYS', 'ngFB', 'appProfile'
($ionicPlatform, $rootScope, deviceReady, exportDebug, KEYS, ngFB, appProfile)->
window.debug = exportDebug
ngFB.init( { appId: KEYS.facebook.app_id })
Parse.initialize( KEYS.parse.APP_ID, KEYS.parse.JS_KEY )
$rootScope.parseUser = Parse.User.current()
$ionicPlatform.ready ()->
# Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
# for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true) if window.cordova?.plugins.Keyboard
# org.apache.cordova.statusbar required
StatusBar.styleDefault() if window.StatusBar?
return
]
.config [
'$stateProvider',
'$urlRouterProvider',
($stateProvider, $urlRouterProvider)->
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "/partials/templates/menu.html",
controller: 'AppCtrl'
})
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "/partials/home.html"
controller: 'HomeCtrl'
}
}
})
.state('app.profile', {
url: "/profile",
views: {
'menuContent': {
templateUrl: "/partials/profile.html"
controller: 'UserCtrl'
}
}
})
.state('app.profile.sign-in', {
url: "/sign-in",
# views: {
# 'menuContent': {
# templateUrl: "/partials/templates/sign-in.html"
# controller: 'UserCtrl'
# }
# }
})
# // if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
]
.controller 'AppCtrl', [
'$scope'
'$rootScope' , '$state'
'$timeout'
'$ionicLoading'
'deviceReady', 'exportDebug'
'$localStorage'
'parsePush'
# 'ionicPush'
'appProfile', 'appFacebook'
($scope, $rootScope, $state, $timeout, $ionicLoading, deviceReady, exportDebug, $localStorage, parsePush, appProfile, appFacebook)->
$scope.deviceReady = deviceReady
_.extend $rootScope, {
$state : $state
'user' : $rootScope.parseUser?.toJSON() || {}
device : null # deviceReady.device(platform)
}
$scope.showLoading = (value = true, timeout=5000)->
return $ionicLoading.hide() if !value
$ionicLoading.show({
template: '<ion-spinner class="spinner-light" icon="lines"></ion-spinner>'
duration: timeout
})
$scope.hideLoading = (delay=0)->
$timeout ()->
$ionicLoading.hide();
, delay
$scope.$on 'user:sign-in', (args)->
console.log "$broadcast user:sign-in received"
parsePush.registerP()
$scope.$on 'user:sign-out', (args)->
console.log "$broadcast user:sign-out received"
parsePush.registerP()
$rootScope.localStorage = $localStorage
if $rootScope.localStorage['device']?
platform = $rootScope.localStorage['device']
parsePush.initialize( platform )
exportDebug['$platform'] = $rootScope['device'] = deviceReady.device(platform)
console.log 'localStorage $platform=' + JSON.stringify exportDebug['$platform']
else
# platform
deviceReady.waitP().then (platform)->
exportDebug['$platform'] = $rootScope['device'] = $rootScope.localStorage['device'] = platform
console.log 'deviceReady $platform=' + JSON.stringify platform
parsePush.initialize( platform ).registerP()
return
, (err)->
console.warn err
# load FB profile if available
if !_.isEmpty $rootScope.user
appFacebook.checkLoginP($rootScope.user)
.then (status)->
# only if logged in
$rootScope.user['fbProfile'] = $localStorage['fbProfile']
# update fbProfile
return appFacebook.getMeP().then (resp)->
return 'done'
exportDebug['ls'] = $localStorage
exportDebug['$root'] = $rootScope
return
]
|
[
{
"context": " create user with specific role: create nexus user testuser1 with any-all-view role\n#to get details of user: p",
"end": 1041,
"score": 0.9994681477546692,
"start": 1032,
"tag": "USERNAME",
"value": "testuser1"
},
{
"context": "iew role\n#to get details of user: print n... | scripts/nexus/scripts-mattermost/Nexus.coffee | akash1233/OnBot_Demo | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
#Set of bot commands for nexus
#to create new nexus repository: create nexus repo test1
#to get details of repository: print nexus repo test1
#to get list of all repositories: list nexus repos
#to create user with specific role: create nexus user testuser1 with any-all-view role
#to get details of user: print nexus user testuser1@cognizant.com
#to get list of all users: list nexus users
#to delete a nexus user: delete nexus user testuser1@cognizant.com
#to delete a nexus repository: delete nexus repo test1
#Env variables to set:
# NEXUS_URL
# NEXUS_USER_ID
# NEXUS_PASSWORD
# HUBOT_NAME
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
nexus_url = process.env.NEXUS_URL
nexus_user_id = process.env.NEXUS_USER_ID
nexus_password = process.env.NEXUS_PASSWORD
botname = process.HUBOT_NAME
pod_ip = process.env.MY_POD_IP;
create_repo = require('./create_repo.js');
delete_repo = require('./delete_repo.js');
create_user = require('./create_user.js');
get_all_repo = require('./get_all_repo.js');
get_given_repo = require('./get_given_repo.js');
get_all_user = require('./get_all_user.js');
get_all_privileges = require('./get_all_privileges.js');
get_given_privileges = require('./get_given_privileges.js');
create_privilege = require('./create_privilege.js');
get_privileges_details = require('./get_privileges_details.js');
get_given_user = require('./get_given_user.js');
delete_user = require('./delete_user.js');
request = require('request');
readjson = require './readjson.js'
generate_id = require('./mongoConnt')
index = require('./index.js')
uniqueId = (length=8) ->
id = ""
id += Math.random().toString(36).substr(2) while id.length < length
id.substr 0, length
module.exports = (robot) ->
cmd = new RegExp('@' + process.env.HUBOT_NAME + ' help')
robot.hear cmd, (msg) ->
dt = 'list nexus repos\nlist nexus users\nlist nexus repo <repo-id>\nlist nexus user <user-id>\ncreate nexus repo <repo-name>\ndelete nexus repo <repo-id>\ncreate nexus user <user-name> with <role-name> role\nshow artifacts in <groupId>\ndelete nexus user <user-id>\nlist nexus privileges\ncreate privilege <privilege name> <tagged repo id>';
msg.send dt
setTimeout (->index.passData dt),1000
robot.router.post '/createnexusrepo', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_repo.repo_create nexus_url, nexus_user_id, nexus_password, data_http.repoid, data_http.repo_name, (error, stdout, stderr) ->
if error == null
dt = 'Nexus repo created with ID : '.concat(data_http.repoid)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus repo created with ID : '.concat(data_http.repoid);
statusmsg = 'Success'
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, dt
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreate = new RegExp('@' + process.env.HUBOT_NAME + ' create nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreate
(msg) ->
message = "Nexus repo created"
actionmsg = ""
statusmsg = ""
repoid = msg.match[1]
repo_name = repoid
unique_id = uniqueId(5);
repoid = repoid.concat(unique_id);
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexusrepo.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusrepo.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repoid:repoid,repo_name:repo_name,callback_id: 'createnexusrepo',tckid:tckid};
data = {"channel": stdout.createnexusrepo.admin,"text":"Approve Request for create nexus repo","message":"Approve Request for create nexus repo",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '.concat(stdout.createnexusrepo.admin);
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_repo.repo_create nexus_url, nexus_user_id, nexus_password, repoid, repo_name, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo created with ID : '.concat(repoid);
statusmsg= 'Success';
msg.send 'Nexus repo created with ID : '.concat(repoid);
setTimeout (->index.passData actionmsg),1000
index.wallData botname, message, actionmsg, statusmsg;
else
msg.send error + "from repo";
setTimeout (->index.passData message2),1000
)
robot.router.post '/deletenexusrepo', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo deleted with ID : '.concat(data_http.repoid);
statusmsg = 'Success';
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, 'Nexus repo deleted with ID : '.concat(data_http.repoid);
setTimeout (->index.passData actionmsg),1000
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmddelete = new RegExp('@' + process.env.HUBOT_NAME + ' delete nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmddelete
(msg) ->
message = "Nexus repo deleted"
actionmsg = ""
statusmsg = ""
repoid = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.deletenexusrepo.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexusrepo.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repoid:repoid,callback_id: 'deletenexusrepo',tckid:tckid};
data = {"channel": stdout.deletenexusrepo.admin,"text":"Approve Request for deleting nexus repo","message":"Request to delete nexus repo with ID: "+payload.repoid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'deletenexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.deletenexusrepo.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo deleted with ID : '.concat(repoid);
statusmsg= 'Success';
msg.send actionmsg
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData actionmsg),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusreposome', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdprint = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdprint
(msg) ->
repoid = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusreposome.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusreposome.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,tckid:tckid,callback_id:"listnexusreposome"}
data={"channel": stdout.listnexusreposome.admin,"text":"Approve Request for accessing nexus repo details","message":"Request to give details of nexus repo with ID: "+payload.repoid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusreposome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexusreposome.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusrepos', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlist = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus repos')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlist
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusrepos.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexusrepos.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusrepos',tckid:tckid};
data = {"channel": stdout.listnexusrepos.admin,"text":"Approve Request for listing nexus repos","message":"Request to list details of all nexus repos",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusrepos',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your approval request is waiting from '.concat(stdout.listnexusrepos.admin);
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexususersome', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, data_http.userid_nexus, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdprintuser = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus user (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdprintuser
(msg) ->
userid_nexus = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexususersome.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususersome.admin,podIp:pod_ip,message:msg.message.text,userid_nexus:userid_nexus,callback_id: 'listnexususersome',tckid:tckid};
data = {"channel": stdout.listnexususersome.admin,"text":"Approve Request for accessing nexus user details","message":"Request to list details of nexus user with ID: "+payload.userid_nexus,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexususersome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexususersome.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, userid_nexus, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlistuser = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus users')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlistuser
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususer.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexususer',tckid:tckid};
data = {"channel": stdout.listnexususer.admin,"text":"Approve Request for accessing nexus user details","message":"Request to list details of all nexus users",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/createnexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_user.create_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, data_http.roleid, data_http.password, (error, stdout, stderr) ->
if error == null
dt = 'Nexus user created with password : '.concat(data_http.password)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus user created';
statusmsg = 'Success';
robot.messageRoom data_http.userid, 'Nexus user created with password : '.concat(data_http.password);
setTimeout (->index.passData dt),1000
index.wallData botname, data_http.message, actionmsg, statusmsg;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreateuser = new RegExp('@' + process.env.HUBOT_NAME + ' create nexus user (.*) with (.*) role')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreateuser
(msg) ->
message = "Nexus user created"
actionmsg = ""
statusmsg = ""
user_id = msg.match[1]
roleid = msg.match[2]
password = uniqueId(8);
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexususer.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,user_id:user_id,roleid:roleid,password:password,callback_id: 'createnexususer',tckid:tckid};
data = {"channel": stdout.createnexususer.admin,"text":"Request from "+payload.username+" to create nexus user","message":"Request to create nexus user with role: "+payload.roleid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.createnexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_user.create_user nexus_url, nexus_user_id, nexus_password, user_id, roleid, password, (error, stdout, stderr) ->
if error == null
dt = 'Nexus user created with password : '.concat(stdout.password)
actionmsg = 'Nexus user created';
statusmsg= 'Success';
robot.messageRoom msg.message.user.id, dt
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData dt),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/deletenexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
delete_user.delete_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus user deleted'
statusmsg = 'Success';
dt='Nexus user deleted with ID : '.concat(data_http.user_id)
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
index.wallData botname, data_http.message, actionmsg, statusmsg;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmddeleteuser = new RegExp('@' + process.env.HUBOT_NAME + ' delete nexus user (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmddeleteuser
(msg) ->
message = "Nexus user deleted"
actionmsg = ""
statusmsg = ""
user_id = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.deletenexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexususer.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,user_id:user_id,callback_id: 'deletenexususer',tckid:tckid};
data = {"channel": stdout.deletenexususer.admin,"text":"Approve Request for deleting nexus user","message":"Request to delete nexus user with name: "+payload.user_id,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'deletenexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.deletenexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
delete_user.delete_user nexus_url, nexus_user_id, nexus_password, user_id, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus user deleted'
statusmsg= 'Success';
dt='Nexus user deleted with ID : '.concat(user_id);
msg.send dt
setTimeout (->index.passData dt),1000
index.wallData botname, message, actionmsg, statusmsg;
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusprivilege', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlistpriv = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus privileges')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlistpriv
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusprivilege.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusprivilege',tckid:tckid};
data = {"channel": stdout.listnexusprivilege.admin,"text":"Approve Request for accessing nexus privilege details","message":"Request to access all nexus privilege details",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexusprivilege.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
cmdgetpriv = new RegExp('@' + process.env.HUBOT_NAME + ' get nexus privilege (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdgetpriv
(msg) ->
userid = msg.match[1]
get_given_privileges.get_given_privileges nexus_url, nexus_user_id, nexus_password, userid, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
msg.send stdout;
else
setTimeout (->index.passData error),1000
msg.send error;
)
cmdsearch = new RegExp('@' + process.env.HUBOT_NAME + ' search pri name (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdsearch
(msg) ->
name = msg.match[1]
msg.send name
get_privileges_details.get_privileges_details nexus_url, nexus_user_id, nexus_password, name, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
msg.send stdout;
else
setTimeout (->index.passData error),1000
msg.send error;
)
robot.router.post '/createnexusprivilege', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, data_http.pri_name, data_http.repo_id, (error, stdout, stderr) ->
if error == null
dt = stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus privilege(s) created'
statusmsg = 'Success'
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id);
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreatepriv = new RegExp('@' + process.env.HUBOT_NAME + ' create privilege (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreatepriv
(msg) ->
array_command = msg.match[1].split " ", 2
pri_name = array_command[0]
repo_id = array_command[1]
message = "Nexus privilege(s) created"
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexusprivilege.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusprivilege.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repo_id:repo_id,pri_name:pri_name,callback_id: 'createnexusprivilege',tckid:tckid};
data = {"channel": stdout.createnexusprivilege.admin,"text":"Approve Request for creating nexus privilege","message":"Request to create nexus privilege with name: "+payload.pri_name,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.createnexusprivilege.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, pri_name, repo_id, (error, stdout, stderr) ->
if error == null
dt = stdout.concat(' with name : ').concat(pri_name).concat(' tagged with repo : ').concat(repo_id);
msg.send dt
actionmsg = 'Nexus privilege(s) created'
statusmsg = 'Success'
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData dt),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
cmdartifacts = new RegExp('@' + process.env.HUBOT_NAME + ' show artifacts in (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdartifacts
(msg) ->
url=nexus_url+'/service/local/lucene/search?g='+msg.match[1]+''
options = {
auth: {
'user': nexus_user_id,
'pass': nexus_password
},
method: 'GET',
url: url
}
request options, (error, response, body) ->
result = body.split('<artifact>')
if(result.length==1)
dt = 'No artifacts found for groupId: '+msg.match[1]
else
dt = '*No.*\t\t\t*Group Id*\t\t\t*Artifact Id*\t\t\t*Version*\t\t\t\t*RepoId*\n'
for i in [1...result.length]
if(result[i].indexOf('latestReleaseRepositoryId')!=-1)
dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestReleaseRepositoryId>')[1].split('</latestReleaseRepositoryId>')[0]+'\n'
else
dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestSnapshotRepositoryId>')[1].split('</latestSnapshotRepositoryId>')[0]+'\n'
msg.send dt
setTimeout (->index.passData dt),1000
)
| 11451 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
#Set of bot commands for nexus
#to create new nexus repository: create nexus repo test1
#to get details of repository: print nexus repo test1
#to get list of all repositories: list nexus repos
#to create user with specific role: create nexus user testuser1 with any-all-view role
#to get details of user: print nexus user <EMAIL>
#to get list of all users: list nexus users
#to delete a nexus user: delete nexus user <EMAIL>
#to delete a nexus repository: delete nexus repo test1
#Env variables to set:
# NEXUS_URL
# NEXUS_USER_ID
# NEXUS_PASSWORD
# HUBOT_NAME
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
nexus_url = process.env.NEXUS_URL
nexus_user_id = process.env.NEXUS_USER_ID
nexus_password = <PASSWORD>
botname = process.HUBOT_NAME
pod_ip = process.env.MY_POD_IP;
create_repo = require('./create_repo.js');
delete_repo = require('./delete_repo.js');
create_user = require('./create_user.js');
get_all_repo = require('./get_all_repo.js');
get_given_repo = require('./get_given_repo.js');
get_all_user = require('./get_all_user.js');
get_all_privileges = require('./get_all_privileges.js');
get_given_privileges = require('./get_given_privileges.js');
create_privilege = require('./create_privilege.js');
get_privileges_details = require('./get_privileges_details.js');
get_given_user = require('./get_given_user.js');
delete_user = require('./delete_user.js');
request = require('request');
readjson = require './readjson.js'
generate_id = require('./mongoConnt')
index = require('./index.js')
uniqueId = (length=8) ->
id = ""
id += Math.random().toString(36).substr(2) while id.length < length
id.substr 0, length
module.exports = (robot) ->
cmd = new RegExp('@' + process.env.HUBOT_NAME + ' help')
robot.hear cmd, (msg) ->
dt = 'list nexus repos\nlist nexus users\nlist nexus repo <repo-id>\nlist nexus user <user-id>\ncreate nexus repo <repo-name>\ndelete nexus repo <repo-id>\ncreate nexus user <user-name> with <role-name> role\nshow artifacts in <groupId>\ndelete nexus user <user-id>\nlist nexus privileges\ncreate privilege <privilege name> <tagged repo id>';
msg.send dt
setTimeout (->index.passData dt),1000
robot.router.post '/createnexusrepo', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_repo.repo_create nexus_url, nexus_user_id, nexus_password, data_http.repoid, data_http.repo_name, (error, stdout, stderr) ->
if error == null
dt = 'Nexus repo created with ID : '.concat(data_http.repoid)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus repo created with ID : '.concat(data_http.repoid);
statusmsg = 'Success'
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, dt
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreate = new RegExp('@' + process.env.HUBOT_NAME + ' create nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreate
(msg) ->
message = "Nexus repo created"
actionmsg = ""
statusmsg = ""
repoid = msg.match[1]
repo_name = repoid
unique_id = uniqueId(5);
repoid = repoid.concat(unique_id);
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexusrepo.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusrepo.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repoid:repoid,repo_name:repo_name,callback_id: 'createnexusrepo',tckid:tckid};
data = {"channel": stdout.createnexusrepo.admin,"text":"Approve Request for create nexus repo","message":"Approve Request for create nexus repo",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '.concat(stdout.createnexusrepo.admin);
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_repo.repo_create nexus_url, nexus_user_id, nexus_password, repoid, repo_name, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo created with ID : '.concat(repoid);
statusmsg= 'Success';
msg.send 'Nexus repo created with ID : '.concat(repoid);
setTimeout (->index.passData actionmsg),1000
index.wallData botname, message, actionmsg, statusmsg;
else
msg.send error + "from repo";
setTimeout (->index.passData message2),1000
)
robot.router.post '/deletenexusrepo', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo deleted with ID : '.concat(data_http.repoid);
statusmsg = 'Success';
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, 'Nexus repo deleted with ID : '.concat(data_http.repoid);
setTimeout (->index.passData actionmsg),1000
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmddelete = new RegExp('@' + process.env.HUBOT_NAME + ' delete nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmddelete
(msg) ->
message = "Nexus repo deleted"
actionmsg = ""
statusmsg = ""
repoid = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.deletenexusrepo.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexusrepo.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repoid:repoid,callback_id: 'deletenexusrepo',tckid:tckid};
data = {"channel": stdout.deletenexusrepo.admin,"text":"Approve Request for deleting nexus repo","message":"Request to delete nexus repo with ID: "+payload.repoid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'deletenexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.deletenexusrepo.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo deleted with ID : '.concat(repoid);
statusmsg= 'Success';
msg.send actionmsg
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData actionmsg),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusreposome', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdprint = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdprint
(msg) ->
repoid = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusreposome.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusreposome.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,tckid:tckid,callback_id:"listnexusreposome"}
data={"channel": stdout.listnexusreposome.admin,"text":"Approve Request for accessing nexus repo details","message":"Request to give details of nexus repo with ID: "+payload.repoid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusreposome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexusreposome.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusrepos', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlist = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus repos')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlist
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusrepos.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexusrepos.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusrepos',tckid:tckid};
data = {"channel": stdout.listnexusrepos.admin,"text":"Approve Request for listing nexus repos","message":"Request to list details of all nexus repos",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusrepos',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your approval request is waiting from '.concat(stdout.listnexusrepos.admin);
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexususersome', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, data_http.userid_nexus, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdprintuser = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus user (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdprintuser
(msg) ->
userid_nexus = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexususersome.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususersome.admin,podIp:pod_ip,message:msg.message.text,userid_nexus:userid_nexus,callback_id: 'listnexususersome',tckid:tckid};
data = {"channel": stdout.listnexususersome.admin,"text":"Approve Request for accessing nexus user details","message":"Request to list details of nexus user with ID: "+payload.userid_nexus,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexususersome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexususersome.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, userid_nexus, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlistuser = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus users')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlistuser
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususer.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexususer',tckid:tckid};
data = {"channel": stdout.listnexususer.admin,"text":"Approve Request for accessing nexus user details","message":"Request to list details of all nexus users",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/createnexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_user.create_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, data_http.roleid, data_http.password, (error, stdout, stderr) ->
if error == null
dt = 'Nexus user created with password : '.concat(data_http.password)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus user created';
statusmsg = 'Success';
robot.messageRoom data_http.userid, 'Nexus user created with password : '.concat(data_http.password);
setTimeout (->index.passData dt),1000
index.wallData botname, data_http.message, actionmsg, statusmsg;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreateuser = new RegExp('@' + process.env.HUBOT_NAME + ' create nexus user (.*) with (.*) role')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreateuser
(msg) ->
message = "Nexus user created"
actionmsg = ""
statusmsg = ""
user_id = msg.match[1]
roleid = msg.match[2]
password = <PASSWORD>);
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexususer.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,user_id:user_id,roleid:roleid,password:<PASSWORD>,callback_id: 'createnexususer',tckid:tckid};
data = {"channel": stdout.createnexususer.admin,"text":"Request from "+payload.username+" to create nexus user","message":"Request to create nexus user with role: "+payload.roleid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.createnexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_user.create_user nexus_url, nexus_user_id, nexus_password, user_id, roleid, password, (error, stdout, stderr) ->
if error == null
dt = 'Nexus user created with password : '.concat(stdout.password)
actionmsg = 'Nexus user created';
statusmsg= 'Success';
robot.messageRoom msg.message.user.id, dt
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData dt),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/deletenexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
delete_user.delete_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus user deleted'
statusmsg = 'Success';
dt='Nexus user deleted with ID : '.concat(data_http.user_id)
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
index.wallData botname, data_http.message, actionmsg, statusmsg;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmddeleteuser = new RegExp('@' + process.env.HUBOT_NAME + ' delete nexus user (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmddeleteuser
(msg) ->
message = "Nexus user deleted"
actionmsg = ""
statusmsg = ""
user_id = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.deletenexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexususer.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,user_id:user_id,callback_id: 'deletenexususer',tckid:tckid};
data = {"channel": stdout.deletenexususer.admin,"text":"Approve Request for deleting nexus user","message":"Request to delete nexus user with name: "+payload.user_id,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'deletenexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.deletenexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
delete_user.delete_user nexus_url, nexus_user_id, nexus_password, user_id, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus user deleted'
statusmsg= 'Success';
dt='Nexus user deleted with ID : '.concat(user_id);
msg.send dt
setTimeout (->index.passData dt),1000
index.wallData botname, message, actionmsg, statusmsg;
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusprivilege', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlistpriv = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus privileges')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlistpriv
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusprivilege.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusprivilege',tckid:tckid};
data = {"channel": stdout.listnexusprivilege.admin,"text":"Approve Request for accessing nexus privilege details","message":"Request to access all nexus privilege details",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexusprivilege.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
cmdgetpriv = new RegExp('@' + process.env.HUBOT_NAME + ' get nexus privilege (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdgetpriv
(msg) ->
userid = msg.match[1]
get_given_privileges.get_given_privileges nexus_url, nexus_user_id, nexus_password, userid, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
msg.send stdout;
else
setTimeout (->index.passData error),1000
msg.send error;
)
cmdsearch = new RegExp('@' + process.env.HUBOT_NAME + ' search pri name (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdsearch
(msg) ->
name = msg.match[1]
msg.send name
get_privileges_details.get_privileges_details nexus_url, nexus_user_id, nexus_password, name, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
msg.send stdout;
else
setTimeout (->index.passData error),1000
msg.send error;
)
robot.router.post '/createnexusprivilege', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, data_http.pri_name, data_http.repo_id, (error, stdout, stderr) ->
if error == null
dt = stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus privilege(s) created'
statusmsg = 'Success'
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id);
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreatepriv = new RegExp('@' + process.env.HUBOT_NAME + ' create privilege (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreatepriv
(msg) ->
array_command = msg.match[1].split " ", 2
pri_name = array_command[0]
repo_id = array_command[1]
message = "Nexus privilege(s) created"
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexusprivilege.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusprivilege.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repo_id:repo_id,pri_name:pri_name,callback_id: 'createnexusprivilege',tckid:tckid};
data = {"channel": stdout.createnexusprivilege.admin,"text":"Approve Request for creating nexus privilege","message":"Request to create nexus privilege with name: "+payload.pri_name,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.createnexusprivilege.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, pri_name, repo_id, (error, stdout, stderr) ->
if error == null
dt = stdout.concat(' with name : ').concat(pri_name).concat(' tagged with repo : ').concat(repo_id);
msg.send dt
actionmsg = 'Nexus privilege(s) created'
statusmsg = 'Success'
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData dt),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
cmdartifacts = new RegExp('@' + process.env.HUBOT_NAME + ' show artifacts in (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdartifacts
(msg) ->
url=nexus_url+'/service/local/lucene/search?g='+msg.match[1]+''
options = {
auth: {
'user': nexus_user_id,
'pass': <PASSWORD>
},
method: 'GET',
url: url
}
request options, (error, response, body) ->
result = body.split('<artifact>')
if(result.length==1)
dt = 'No artifacts found for groupId: '+msg.match[1]
else
dt = '*No.*\t\t\t*Group Id*\t\t\t*Artifact Id*\t\t\t*Version*\t\t\t\t*RepoId*\n'
for i in [1...result.length]
if(result[i].indexOf('latestReleaseRepositoryId')!=-1)
dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestReleaseRepositoryId>')[1].split('</latestReleaseRepositoryId>')[0]+'\n'
else
dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestSnapshotRepositoryId>')[1].split('</latestSnapshotRepositoryId>')[0]+'\n'
msg.send dt
setTimeout (->index.passData dt),1000
)
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
#Set of bot commands for nexus
#to create new nexus repository: create nexus repo test1
#to get details of repository: print nexus repo test1
#to get list of all repositories: list nexus repos
#to create user with specific role: create nexus user testuser1 with any-all-view role
#to get details of user: print nexus user PI:EMAIL:<EMAIL>END_PI
#to get list of all users: list nexus users
#to delete a nexus user: delete nexus user PI:EMAIL:<EMAIL>END_PI
#to delete a nexus repository: delete nexus repo test1
#Env variables to set:
# NEXUS_URL
# NEXUS_USER_ID
# NEXUS_PASSWORD
# HUBOT_NAME
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
nexus_url = process.env.NEXUS_URL
nexus_user_id = process.env.NEXUS_USER_ID
nexus_password = PI:PASSWORD:<PASSWORD>END_PI
botname = process.HUBOT_NAME
pod_ip = process.env.MY_POD_IP;
create_repo = require('./create_repo.js');
delete_repo = require('./delete_repo.js');
create_user = require('./create_user.js');
get_all_repo = require('./get_all_repo.js');
get_given_repo = require('./get_given_repo.js');
get_all_user = require('./get_all_user.js');
get_all_privileges = require('./get_all_privileges.js');
get_given_privileges = require('./get_given_privileges.js');
create_privilege = require('./create_privilege.js');
get_privileges_details = require('./get_privileges_details.js');
get_given_user = require('./get_given_user.js');
delete_user = require('./delete_user.js');
request = require('request');
readjson = require './readjson.js'
generate_id = require('./mongoConnt')
index = require('./index.js')
uniqueId = (length=8) ->
id = ""
id += Math.random().toString(36).substr(2) while id.length < length
id.substr 0, length
module.exports = (robot) ->
cmd = new RegExp('@' + process.env.HUBOT_NAME + ' help')
robot.hear cmd, (msg) ->
dt = 'list nexus repos\nlist nexus users\nlist nexus repo <repo-id>\nlist nexus user <user-id>\ncreate nexus repo <repo-name>\ndelete nexus repo <repo-id>\ncreate nexus user <user-name> with <role-name> role\nshow artifacts in <groupId>\ndelete nexus user <user-id>\nlist nexus privileges\ncreate privilege <privilege name> <tagged repo id>';
msg.send dt
setTimeout (->index.passData dt),1000
robot.router.post '/createnexusrepo', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_repo.repo_create nexus_url, nexus_user_id, nexus_password, data_http.repoid, data_http.repo_name, (error, stdout, stderr) ->
if error == null
dt = 'Nexus repo created with ID : '.concat(data_http.repoid)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus repo created with ID : '.concat(data_http.repoid);
statusmsg = 'Success'
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, dt
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreate = new RegExp('@' + process.env.HUBOT_NAME + ' create nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreate
(msg) ->
message = "Nexus repo created"
actionmsg = ""
statusmsg = ""
repoid = msg.match[1]
repo_name = repoid
unique_id = uniqueId(5);
repoid = repoid.concat(unique_id);
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexusrepo.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusrepo.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repoid:repoid,repo_name:repo_name,callback_id: 'createnexusrepo',tckid:tckid};
data = {"channel": stdout.createnexusrepo.admin,"text":"Approve Request for create nexus repo","message":"Approve Request for create nexus repo",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '.concat(stdout.createnexusrepo.admin);
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_repo.repo_create nexus_url, nexus_user_id, nexus_password, repoid, repo_name, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo created with ID : '.concat(repoid);
statusmsg= 'Success';
msg.send 'Nexus repo created with ID : '.concat(repoid);
setTimeout (->index.passData actionmsg),1000
index.wallData botname, message, actionmsg, statusmsg;
else
msg.send error + "from repo";
setTimeout (->index.passData message2),1000
)
robot.router.post '/deletenexusrepo', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo deleted with ID : '.concat(data_http.repoid);
statusmsg = 'Success';
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, 'Nexus repo deleted with ID : '.concat(data_http.repoid);
setTimeout (->index.passData actionmsg),1000
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmddelete = new RegExp('@' + process.env.HUBOT_NAME + ' delete nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmddelete
(msg) ->
message = "Nexus repo deleted"
actionmsg = ""
statusmsg = ""
repoid = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.deletenexusrepo.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexusrepo.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repoid:repoid,callback_id: 'deletenexusrepo',tckid:tckid};
data = {"channel": stdout.deletenexusrepo.admin,"text":"Approve Request for deleting nexus repo","message":"Request to delete nexus repo with ID: "+payload.repoid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'deletenexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.deletenexusrepo.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus repo deleted with ID : '.concat(repoid);
statusmsg= 'Success';
msg.send actionmsg
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData actionmsg),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusreposome', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdprint = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus repo (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdprint
(msg) ->
repoid = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusreposome.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusreposome.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,tckid:tckid,callback_id:"listnexusreposome"}
data={"channel": stdout.listnexusreposome.admin,"text":"Approve Request for accessing nexus repo details","message":"Request to give details of nexus repo with ID: "+payload.repoid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusreposome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexusreposome.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusrepos', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlist = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus repos')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlist
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusrepos.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexusrepos.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusrepos',tckid:tckid};
data = {"channel": stdout.listnexusrepos.admin,"text":"Approve Request for listing nexus repos","message":"Request to list details of all nexus repos",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusrepos',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your approval request is waiting from '.concat(stdout.listnexusrepos.admin);
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexususersome', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, data_http.userid_nexus, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdprintuser = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus user (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdprintuser
(msg) ->
userid_nexus = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexususersome.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususersome.admin,podIp:pod_ip,message:msg.message.text,userid_nexus:userid_nexus,callback_id: 'listnexususersome',tckid:tckid};
data = {"channel": stdout.listnexususersome.admin,"text":"Approve Request for accessing nexus user details","message":"Request to list details of nexus user with ID: "+payload.userid_nexus,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexususersome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexususersome.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, userid_nexus, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlistuser = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus users')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlistuser
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususer.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexususer',tckid:tckid};
data = {"channel": stdout.listnexususer.admin,"text":"Approve Request for accessing nexus user details","message":"Request to list details of all nexus users",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/createnexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_user.create_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, data_http.roleid, data_http.password, (error, stdout, stderr) ->
if error == null
dt = 'Nexus user created with password : '.concat(data_http.password)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus user created';
statusmsg = 'Success';
robot.messageRoom data_http.userid, 'Nexus user created with password : '.concat(data_http.password);
setTimeout (->index.passData dt),1000
index.wallData botname, data_http.message, actionmsg, statusmsg;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreateuser = new RegExp('@' + process.env.HUBOT_NAME + ' create nexus user (.*) with (.*) role')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreateuser
(msg) ->
message = "Nexus user created"
actionmsg = ""
statusmsg = ""
user_id = msg.match[1]
roleid = msg.match[2]
password = PI:PASSWORD:<PASSWORD>END_PI);
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexususer.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,user_id:user_id,roleid:roleid,password:PI:PASSWORD:<PASSWORD>END_PI,callback_id: 'createnexususer',tckid:tckid};
data = {"channel": stdout.createnexususer.admin,"text":"Request from "+payload.username+" to create nexus user","message":"Request to create nexus user with role: "+payload.roleid,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.createnexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_user.create_user nexus_url, nexus_user_id, nexus_password, user_id, roleid, password, (error, stdout, stderr) ->
if error == null
dt = 'Nexus user created with password : '.concat(stdout.password)
actionmsg = 'Nexus user created';
statusmsg= 'Success';
robot.messageRoom msg.message.user.id, dt
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData dt),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/deletenexususer', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
delete_user.delete_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus user deleted'
statusmsg = 'Success';
dt='Nexus user deleted with ID : '.concat(data_http.user_id)
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
index.wallData botname, data_http.message, actionmsg, statusmsg;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmddeleteuser = new RegExp('@' + process.env.HUBOT_NAME + ' delete nexus user (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmddeleteuser
(msg) ->
message = "Nexus user deleted"
actionmsg = ""
statusmsg = ""
user_id = msg.match[1]
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.deletenexususer.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexususer.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,user_id:user_id,callback_id: 'deletenexususer',tckid:tckid};
data = {"channel": stdout.deletenexususer.admin,"text":"Approve Request for deleting nexus user","message":"Request to delete nexus user with name: "+payload.user_id,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'deletenexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.deletenexususer.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
delete_user.delete_user nexus_url, nexus_user_id, nexus_password, user_id, (error, stdout, stderr) ->
if error == null
actionmsg = 'Nexus user deleted'
statusmsg= 'Success';
dt='Nexus user deleted with ID : '.concat(user_id);
msg.send dt
setTimeout (->index.passData dt),1000
index.wallData botname, message, actionmsg, statusmsg;
else
msg.send error;
setTimeout (->index.passData error),1000
)
robot.router.post '/listnexusprivilege', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
robot.messageRoom data_http.userid, stdout;
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
robot.messageRoom data_http.userid, 'You are not authorized.';
cmdlistpriv = new RegExp('@' + process.env.HUBOT_NAME + ' list nexus privileges')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdlistpriv
(msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.listnexusprivilege.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusprivilege',tckid:tckid};
data = {"channel": stdout.listnexusprivilege.admin,"text":"Approve Request for accessing nexus privilege details","message":"Request to access all nexus privilege details",attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'listnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval by '+stdout.listnexusprivilege.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) ->
if error == null
msg.send stdout;
setTimeout (->index.passData stdout),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
cmdgetpriv = new RegExp('@' + process.env.HUBOT_NAME + ' get nexus privilege (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdgetpriv
(msg) ->
userid = msg.match[1]
get_given_privileges.get_given_privileges nexus_url, nexus_user_id, nexus_password, userid, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
msg.send stdout;
else
setTimeout (->index.passData error),1000
msg.send error;
)
cmdsearch = new RegExp('@' + process.env.HUBOT_NAME + ' search pri name (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdsearch
(msg) ->
name = msg.match[1]
msg.send name
get_privileges_details.get_privileges_details nexus_url, nexus_user_id, nexus_password, name, (error, stdout, stderr) ->
if error == null
setTimeout (->index.passData stdout),1000
msg.send stdout;
else
setTimeout (->index.passData error),1000
msg.send error;
)
robot.router.post '/createnexusprivilege', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == 'Approve'
create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, data_http.pri_name, data_http.repo_id, (error, stdout, stderr) ->
if error == null
dt = stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id)
setTimeout (->index.passData dt),1000
actionmsg = 'Nexus privilege(s) created'
statusmsg = 'Success'
index.wallData botname, data_http.message, actionmsg, statusmsg;
robot.messageRoom data_http.userid, stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id);
else
setTimeout (->index.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt = 'You are not authorized.'
robot.messageRoom data_http.userid, dt;
setTimeout (->index.passData dt),1000
cmdcreatepriv = new RegExp('@' + process.env.HUBOT_NAME + ' create privilege (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdcreatepriv
(msg) ->
array_command = msg.match[1].split " ", 2
pri_name = array_command[0]
repo_id = array_command[1]
message = "Nexus privilege(s) created"
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.createnexusprivilege.workflowflag == true
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusprivilege.admin,podIp:process.env.MY_POD_IP,message:msg.message.text,repo_id:repo_id,pri_name:pri_name,callback_id: 'createnexusprivilege',tckid:tckid};
data = {"channel": stdout.createnexusprivilege.admin,"text":"Approve Request for creating nexus privilege","message":"Request to create nexus privilege with name: "+payload.pri_name,attachments: [{text: 'click approve or reject',fallback: 'Yes or No?',callback_id: 'createnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button',"integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Approve",value: tckid}}},{ name: 'Reject', text: 'Reject', type: 'button', "integration": {"url": process.env.APPROVAL_APP_URL,"context": {"action": "Reject",value: tckid}}}]}]}
options = {
url: process.env.MATTERMOST_INCOME_URL,
method: "POST",
header: {"Content-type":"application/json"},
json: data
}
request.post options, (err,response,body) ->
console.log response.body
msg.send 'Your request is waiting for approval from '+stdout.createnexusprivilege.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
generate_id.add_in_mongo dataToInsert
else
create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, pri_name, repo_id, (error, stdout, stderr) ->
if error == null
dt = stdout.concat(' with name : ').concat(pri_name).concat(' tagged with repo : ').concat(repo_id);
msg.send dt
actionmsg = 'Nexus privilege(s) created'
statusmsg = 'Success'
index.wallData botname, message, actionmsg, statusmsg;
setTimeout (->index.passData dt),1000
else
msg.send error;
setTimeout (->index.passData error),1000
)
cmdartifacts = new RegExp('@' + process.env.HUBOT_NAME + ' show artifacts in (.*)')
robot.listen(
(message) ->
return unless message.text
message.text.match cmdartifacts
(msg) ->
url=nexus_url+'/service/local/lucene/search?g='+msg.match[1]+''
options = {
auth: {
'user': nexus_user_id,
'pass': PI:PASSWORD:<PASSWORD>END_PI
},
method: 'GET',
url: url
}
request options, (error, response, body) ->
result = body.split('<artifact>')
if(result.length==1)
dt = 'No artifacts found for groupId: '+msg.match[1]
else
dt = '*No.*\t\t\t*Group Id*\t\t\t*Artifact Id*\t\t\t*Version*\t\t\t\t*RepoId*\n'
for i in [1...result.length]
if(result[i].indexOf('latestReleaseRepositoryId')!=-1)
dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestReleaseRepositoryId>')[1].split('</latestReleaseRepositoryId>')[0]+'\n'
else
dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestSnapshotRepositoryId>')[1].split('</latestSnapshotRepositoryId>')[0]+'\n'
msg.send dt
setTimeout (->index.passData dt),1000
)
|
[
{
"context": " - list of all available algorithm\n#\n# Author:\n# knjcode <knjcode@gmail.com>\n\ncodec = require 'string-code",
"end": 654,
"score": 0.9996924996376038,
"start": 647,
"tag": "USERNAME",
"value": "knjcode"
},
{
"context": " all available algorithm\n#\n# Author:\n# ... | src/string-codec.coffee | prototype-cafe/hubot-string-codec | 0 | # Description
# A hubot script that encode/decode string
#
# Configuration:
# None
#
# Commands:
# hubot enc <string> - list various encoded strings
# hubot enc:[algo] <string> - display string encode with specified algorithm
# hubot enc:all <string> - list strings encode with all available algorithm
# hubot enc:list - list of all available algorithm
#
# hubot dec <string> - list various decoded strings
# hubot dec:[algo] <string> - display string decode with specified algorithm
# hubot dec:all <string> - list strings decode with all available algorithm
# hubot dec:list - list of all available algorithm
#
# Author:
# knjcode <knjcode@gmail.com>
codec = require 'string-codec'
enchashes = ['md4', 'md5', 'sha', 'sha1', 'sha224', 'sha256', 'sha384',
'sha512', 'rmd160', 'whirlpool']
ENC_DEFAULT = codec.ENC_ALGOS.concat(enchashes)
module.exports = (robot) ->
robot.respond /enc(:\w*)? (.*)?/i, (msg) ->
algo = if msg.match[1] isnt undefined then msg.match[1] else ''
str = if msg.match[2] isnt undefined then msg.match[2] else ''
algo = algo[1..] if algo
switch algo
when 'all'
replies = [ 'all encodings of ' + str ]
for algo in codec.ENC_ALL
replies.push algo + ': ' + codec.encoder(str, algo)
msg.send replies.join '\n'
else
if algo in codec.ENC_ALL
msg.send codec.encoder(str, algo)
else if algo is ''
replies = [ 'encodings of ' + str ]
for algo in ENC_DEFAULT
replies.push algo + ': ' + codec.encoder(str, algo)
msg.send replies.join '\n'
else
msg.send algo + 'unknown algorithm'
robot.respond /dec(:\w*)? (.*)?/i, (msg) ->
algo = if msg.match[1] isnt undefined then msg.match[1] else ''
str = if msg.match[2] isnt undefined then msg.match[2] else ''
algo = algo[1..] if algo
switch algo
when 'all'
replies = [ 'all decodings of ' + str ]
for algo in codec.DEC_ALL
replies.push algo + ': ' + codec.decoder(str, algo)
msg.send replies.join '\n'
else
if algo in codec.DEC_ALL
msg.send codec.decoder(str, algo)
else if algo is ''
replies = [ 'decodings of ' + str ]
for algo in codec.DEC_ALL
replies.push algo + ': ' + codec.decoder(str, algo)
msg.send replies.join '\n'
else
msg.send algo + 'unknown algorithm'
robot.respond /enc:list/i, (msg) ->
msg.send codec.ENC_ALL.toString()
robot.respond /dec:list/i, (msg) ->
msg.send codec.DEC_ALL.toString()
| 92566 | # Description
# A hubot script that encode/decode string
#
# Configuration:
# None
#
# Commands:
# hubot enc <string> - list various encoded strings
# hubot enc:[algo] <string> - display string encode with specified algorithm
# hubot enc:all <string> - list strings encode with all available algorithm
# hubot enc:list - list of all available algorithm
#
# hubot dec <string> - list various decoded strings
# hubot dec:[algo] <string> - display string decode with specified algorithm
# hubot dec:all <string> - list strings decode with all available algorithm
# hubot dec:list - list of all available algorithm
#
# Author:
# knjcode <<EMAIL>>
codec = require 'string-codec'
enchashes = ['md4', 'md5', 'sha', 'sha1', 'sha224', 'sha256', 'sha384',
'sha512', 'rmd160', 'whirlpool']
ENC_DEFAULT = codec.ENC_ALGOS.concat(enchashes)
module.exports = (robot) ->
robot.respond /enc(:\w*)? (.*)?/i, (msg) ->
algo = if msg.match[1] isnt undefined then msg.match[1] else ''
str = if msg.match[2] isnt undefined then msg.match[2] else ''
algo = algo[1..] if algo
switch algo
when 'all'
replies = [ 'all encodings of ' + str ]
for algo in codec.ENC_ALL
replies.push algo + ': ' + codec.encoder(str, algo)
msg.send replies.join '\n'
else
if algo in codec.ENC_ALL
msg.send codec.encoder(str, algo)
else if algo is ''
replies = [ 'encodings of ' + str ]
for algo in ENC_DEFAULT
replies.push algo + ': ' + codec.encoder(str, algo)
msg.send replies.join '\n'
else
msg.send algo + 'unknown algorithm'
robot.respond /dec(:\w*)? (.*)?/i, (msg) ->
algo = if msg.match[1] isnt undefined then msg.match[1] else ''
str = if msg.match[2] isnt undefined then msg.match[2] else ''
algo = algo[1..] if algo
switch algo
when 'all'
replies = [ 'all decodings of ' + str ]
for algo in codec.DEC_ALL
replies.push algo + ': ' + codec.decoder(str, algo)
msg.send replies.join '\n'
else
if algo in codec.DEC_ALL
msg.send codec.decoder(str, algo)
else if algo is ''
replies = [ 'decodings of ' + str ]
for algo in codec.DEC_ALL
replies.push algo + ': ' + codec.decoder(str, algo)
msg.send replies.join '\n'
else
msg.send algo + 'unknown algorithm'
robot.respond /enc:list/i, (msg) ->
msg.send codec.ENC_ALL.toString()
robot.respond /dec:list/i, (msg) ->
msg.send codec.DEC_ALL.toString()
| true | # Description
# A hubot script that encode/decode string
#
# Configuration:
# None
#
# Commands:
# hubot enc <string> - list various encoded strings
# hubot enc:[algo] <string> - display string encode with specified algorithm
# hubot enc:all <string> - list strings encode with all available algorithm
# hubot enc:list - list of all available algorithm
#
# hubot dec <string> - list various decoded strings
# hubot dec:[algo] <string> - display string decode with specified algorithm
# hubot dec:all <string> - list strings decode with all available algorithm
# hubot dec:list - list of all available algorithm
#
# Author:
# knjcode <PI:EMAIL:<EMAIL>END_PI>
codec = require 'string-codec'
enchashes = ['md4', 'md5', 'sha', 'sha1', 'sha224', 'sha256', 'sha384',
'sha512', 'rmd160', 'whirlpool']
ENC_DEFAULT = codec.ENC_ALGOS.concat(enchashes)
module.exports = (robot) ->
robot.respond /enc(:\w*)? (.*)?/i, (msg) ->
algo = if msg.match[1] isnt undefined then msg.match[1] else ''
str = if msg.match[2] isnt undefined then msg.match[2] else ''
algo = algo[1..] if algo
switch algo
when 'all'
replies = [ 'all encodings of ' + str ]
for algo in codec.ENC_ALL
replies.push algo + ': ' + codec.encoder(str, algo)
msg.send replies.join '\n'
else
if algo in codec.ENC_ALL
msg.send codec.encoder(str, algo)
else if algo is ''
replies = [ 'encodings of ' + str ]
for algo in ENC_DEFAULT
replies.push algo + ': ' + codec.encoder(str, algo)
msg.send replies.join '\n'
else
msg.send algo + 'unknown algorithm'
robot.respond /dec(:\w*)? (.*)?/i, (msg) ->
algo = if msg.match[1] isnt undefined then msg.match[1] else ''
str = if msg.match[2] isnt undefined then msg.match[2] else ''
algo = algo[1..] if algo
switch algo
when 'all'
replies = [ 'all decodings of ' + str ]
for algo in codec.DEC_ALL
replies.push algo + ': ' + codec.decoder(str, algo)
msg.send replies.join '\n'
else
if algo in codec.DEC_ALL
msg.send codec.decoder(str, algo)
else if algo is ''
replies = [ 'decodings of ' + str ]
for algo in codec.DEC_ALL
replies.push algo + ': ' + codec.decoder(str, algo)
msg.send replies.join '\n'
else
msg.send algo + 'unknown algorithm'
robot.respond /enc:list/i, (msg) ->
msg.send codec.ENC_ALL.toString()
robot.respond /dec:list/i, (msg) ->
msg.send codec.DEC_ALL.toString()
|
[
{
"context": "\n\n test_extra_url_vars =\n test_key : 'test_value'\n test_key2 : 'test_value2'\n\n image_o",
"end": 685,
"score": 0.9918453097343445,
"start": 675,
"tag": "KEY",
"value": "test_value"
},
{
"context": " test_key : 'test_value'\n test_... | bokehjs/test/models/tiles/dynamic_image_renderer.coffee | azjps/bokeh | 1 | _ = require "underscore"
{expect} = require "chai"
utils = require "../../utils"
{ImageSource} = utils.require "models/tiles/image_source"
describe "dynamic image renderer", ->
describe "image source", ->
it "should handle case-insensitive url parameters (template url)", ->
image_options =
url : 'http://test/{height}/{width}/{xmin}/{ymin}/{xmax}/{ymax}.png'
expect_url = 'http://test/5/6/1/2/3/4.png'
image_source = new ImageSource(image_options)
expect(image_source.get_image_url(1,2,3,4,5,6)).to.be.equal(expect_url)
it "should successfully set extra_url_vars property", ->
test_extra_url_vars =
test_key : 'test_value'
test_key2 : 'test_value2'
image_options =
url : 'http://{test_key}/{test_key2}/{XMIN}/{YMIN}/{XMAX}/{YMAX}.png'
extra_url_vars : test_extra_url_vars
image_source = new ImageSource(image_options)
expect_url = 'http://test_value/test_value2/0/0/0/0.png'
expect(image_source.extra_url_vars).to.have.any.keys('test_key')
expect(image_source.extra_url_vars).to.have.any.keys('test_key2')
formatted_url = image_source.get_image_url(0,0,0,0,0,0)
expect(formatted_url).to.be.equal(expect_url)
| 195976 | _ = require "underscore"
{expect} = require "chai"
utils = require "../../utils"
{ImageSource} = utils.require "models/tiles/image_source"
describe "dynamic image renderer", ->
describe "image source", ->
it "should handle case-insensitive url parameters (template url)", ->
image_options =
url : 'http://test/{height}/{width}/{xmin}/{ymin}/{xmax}/{ymax}.png'
expect_url = 'http://test/5/6/1/2/3/4.png'
image_source = new ImageSource(image_options)
expect(image_source.get_image_url(1,2,3,4,5,6)).to.be.equal(expect_url)
it "should successfully set extra_url_vars property", ->
test_extra_url_vars =
test_key : '<KEY>'
test_key2 : '<KEY>'
image_options =
url : 'http://{test_key}/{test_key2}/{XMIN}/{YMIN}/{XMAX}/{YMAX}.png'
extra_url_vars : test_extra_url_vars
image_source = new ImageSource(image_options)
expect_url = 'http://test_value/test_value2/0/0/0/0.png'
expect(image_source.extra_url_vars).to.have.any.keys('test_key')
expect(image_source.extra_url_vars).to.have.any.keys('test_key2')
formatted_url = image_source.get_image_url(0,0,0,0,0,0)
expect(formatted_url).to.be.equal(expect_url)
| true | _ = require "underscore"
{expect} = require "chai"
utils = require "../../utils"
{ImageSource} = utils.require "models/tiles/image_source"
describe "dynamic image renderer", ->
describe "image source", ->
it "should handle case-insensitive url parameters (template url)", ->
image_options =
url : 'http://test/{height}/{width}/{xmin}/{ymin}/{xmax}/{ymax}.png'
expect_url = 'http://test/5/6/1/2/3/4.png'
image_source = new ImageSource(image_options)
expect(image_source.get_image_url(1,2,3,4,5,6)).to.be.equal(expect_url)
it "should successfully set extra_url_vars property", ->
test_extra_url_vars =
test_key : 'PI:KEY:<KEY>END_PI'
test_key2 : 'PI:KEY:<KEY>END_PI'
image_options =
url : 'http://{test_key}/{test_key2}/{XMIN}/{YMIN}/{XMAX}/{YMAX}.png'
extra_url_vars : test_extra_url_vars
image_source = new ImageSource(image_options)
expect_url = 'http://test_value/test_value2/0/0/0/0.png'
expect(image_source.extra_url_vars).to.have.any.keys('test_key')
expect(image_source.extra_url_vars).to.have.any.keys('test_key2')
formatted_url = image_source.get_image_url(0,0,0,0,0,0)
expect(formatted_url).to.be.equal(expect_url)
|
[
{
"context": " constructor: ->\n super()\n @name = \"Noble\"\n receiveDamage: (dmg) ->\n if @blocking",
"end": 350,
"score": 0.9775194525718689,
"start": 345,
"tag": "NAME",
"value": "Noble"
}
] | src/entity/player/swordsman.coffee | zekoff/1gam-battle | 0 | BasePlayer = require './base'
abilityList = [
require '../../ability/player/attack'
require '../../ability/player/defend'
require '../../ability/player/heal'
require '../../ability/player/riposte'
require '../../ability/player/feint'
]
class Swordsman extends BasePlayer
constructor: ->
super()
@name = "Noble"
receiveDamage: (dmg) ->
if @blocking
dmg *= (1 - @blocking.power) if @blocking
@hp -= dmg
else if @riposte
game.enemy.receiveDamage dmg *= @riposte.power
else
@hp -= dmg
getRandomAbility: ->
new (game.rnd.pick abilityList)
endTurn: ->
super()
@riposte = null
getStanceInfo: ->
if @stance > 100
{name:"Patient",description:"+50% power to Riposte",color:0x0000FF}
else if @stance < -100
{name:"Aggressive",description:"+50% power to non-Riposte actions",color:0xFF0000}
else
{name:"Balanced",description:"+10% power to all actions",color:0xFFFFFF}
applyStanceEffect: (ability) ->
switch @getStanceInfo().name
when "Patient"
if ability.name is "Riposte"
ability.power *= 1.5
when "Aggressive"
unless ability.name is "Riposte"
ability.power *= 1.5
when "Balanced"
ability.power *= 1.1
module.exports = Swordsman | 121413 | BasePlayer = require './base'
abilityList = [
require '../../ability/player/attack'
require '../../ability/player/defend'
require '../../ability/player/heal'
require '../../ability/player/riposte'
require '../../ability/player/feint'
]
class Swordsman extends BasePlayer
constructor: ->
super()
@name = "<NAME>"
receiveDamage: (dmg) ->
if @blocking
dmg *= (1 - @blocking.power) if @blocking
@hp -= dmg
else if @riposte
game.enemy.receiveDamage dmg *= @riposte.power
else
@hp -= dmg
getRandomAbility: ->
new (game.rnd.pick abilityList)
endTurn: ->
super()
@riposte = null
getStanceInfo: ->
if @stance > 100
{name:"Patient",description:"+50% power to Riposte",color:0x0000FF}
else if @stance < -100
{name:"Aggressive",description:"+50% power to non-Riposte actions",color:0xFF0000}
else
{name:"Balanced",description:"+10% power to all actions",color:0xFFFFFF}
applyStanceEffect: (ability) ->
switch @getStanceInfo().name
when "Patient"
if ability.name is "Riposte"
ability.power *= 1.5
when "Aggressive"
unless ability.name is "Riposte"
ability.power *= 1.5
when "Balanced"
ability.power *= 1.1
module.exports = Swordsman | true | BasePlayer = require './base'
abilityList = [
require '../../ability/player/attack'
require '../../ability/player/defend'
require '../../ability/player/heal'
require '../../ability/player/riposte'
require '../../ability/player/feint'
]
class Swordsman extends BasePlayer
constructor: ->
super()
@name = "PI:NAME:<NAME>END_PI"
receiveDamage: (dmg) ->
if @blocking
dmg *= (1 - @blocking.power) if @blocking
@hp -= dmg
else if @riposte
game.enemy.receiveDamage dmg *= @riposte.power
else
@hp -= dmg
getRandomAbility: ->
new (game.rnd.pick abilityList)
endTurn: ->
super()
@riposte = null
getStanceInfo: ->
if @stance > 100
{name:"Patient",description:"+50% power to Riposte",color:0x0000FF}
else if @stance < -100
{name:"Aggressive",description:"+50% power to non-Riposte actions",color:0xFF0000}
else
{name:"Balanced",description:"+10% power to all actions",color:0xFFFFFF}
applyStanceEffect: (ability) ->
switch @getStanceInfo().name
when "Patient"
if ability.name is "Riposte"
ability.power *= 1.5
when "Aggressive"
unless ability.name is "Riposte"
ability.power *= 1.5
when "Balanced"
ability.power *= 1.1
module.exports = Swordsman |
[
{
"context": " if key.type is 'radio'\n # key=@R_dompathUpdate(key)\n # @submitArray.push key\n\n #",
"end": 8259,
"score": 0.6369964480400085,
"start": 8244,
"tag": "KEY",
"value": "R_dompathUpdate"
}
] | client/views/searchView/searchView.coffee | lvyachao/Timbr_V1 | 77 | Template.searchView.rendered = ->
Vue.component 't-Search-Action-List', template: '#t-Search-Action-List-Template'
window.searchVM = new Vue
el: '.t-Search'
ready: ->
console.log @urlArray
self= @
document.getElementById('t-Modal-Text-Tabpanel-MulUpload-File').addEventListener('change', @T_MulUploadChange, false)
data:
tabCount: -1
tabStatus: 0
indexcount: 0
urlArray: []
urlContent: ''
urlInput: ''
# clickDataArray: []
S_Mul_Array: []
submitArray: []
buttonObject: {}
Modals:
T_Mul:
type:'text'
value: ''
valuelist: []
computed:
currentTab: ->
# console.log @tabStatus
return @urlArray[@tabStatus]
methods:
addUrlContent: (e) ->
url = @urlInput
@tabCount++
NProgress.start()
e.preventDefault()
Meteor.call 'getPhContent', url, 'injectSearch', '', (error, result) =>
# @urlContent = result
@urlArray.push
urlInput: @urlInput,
urlContent: result,
clickDataArray: []
NProgress.done()
templength=@urlArray.length
$("#t-Search-Iframe-Tab"+templength).tab 'show'
whetherText: (type, timbr_clicked) ->
if (type is 'text') and (timbr_clicked)
return true
else
return false
whetherCheckbox: (type, checked) ->
if (type is 'checkbox') and (checked)
return true
else
return false
whetherRadio: (type, timbr_clicked) ->
if (type is 'radio') and (timbr_clicked)
return true
else
return false
whetherSelect: (type, timbr_clicked) ->
if (type is 'select') and (timbr_clicked)
return true
else
return false
whetherSubmit: (type, timbr_clicked) ->
if (type is 'submit') and (timbr_clicked)
return true
else
return false
onClickExampleBtn: (e) ->
url = $(e.target).data().url
@urlInput = url
# onClickCustomize: (e)->
# _button = $(e.target)
# @indexcount=_button.data('count')
# if @clickDataArray[_button.data('count')].type=='text'
# @Modals.T_Mul.value=''
# @Modals.T_Mul.valuelist.length=0
# $('#t-ModaL-Text').modal()
# if @clickDataArray[_button.data('count')].type=='checkbox'
# $('#t-ModaL-Checkbox').modal()
# if @clickDataArray[_button.data('count')].type=='radio'
# @S_Mul_Array.length=0
# for key of @clickDataArray[_button.data("count")].valueandlabel
# tempvalue = key
# templabel = @clickDataArray[_button.data("count")].valueandlabel[key]
# @S_Mul_Array.push
# value: tempvalue
# label: templabel
# # console.log @S_Mul_Array
# $('#t-ModaL-Radio').modal()
# toastr.warning 'Choose this Advance Multiple Result will let out indepent Multiple Results!!'
# if @clickDataArray[_button.data('count')].type=='select'
# @S_Mul_Array.length=0
# for key of @clickDataArray[_button.data("count")].valueandlabel
# tempvalue = key
# templabel = @clickDataArray[_button.data("count")].valueandlabel[key]
# @S_Mul_Array.push
# value: tempvalue
# label: templabel
# $('#t-ModaL-Select').modal()
# toastr.warning 'Choose this Advance Multiple Result will let out indepent Multiple Results!!'
# return
# onClickDelete: (e) ->
# _button = $(e.target)
# @clickDataArray[_button.data('count')].timbr_clicked=false
# if @clickDataArray[_button.data('count')].value !=""
# @clickDataArray[_button.data('count')].value =""
# if @clickDataArray[_button.data('count')].valuelist
# delete @clickDataArray[_button.data('count')].valuelist
# if @clickDataArray[_button.data('count')].mulmodel =true
# @clickDataArray[_button.data('count')].mulmodel=false
# return
# T_MulInputInsert:(type)->
# self=@
# if type is "AtoZ"
# self.Modals.T_Mul.value= "A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z"
# if type is "1to9"
# self.Modals.T_Mul.value= "1, 2, 3, 4, 5, 6, 7, 8, 9"
# T_MulInputSubmit: (count)->
# self=@
# if self.Modals.T_Mul.value
# self.Modals.T_Mul.valuelist= self.Modals.T_Mul.value.split ", "
# else
# toastr.error "Please provide values"
# # console.log self.Modals.T_Mul.valuelist
# if self.Modals.T_Mul.valuelist.length >=1
# @clickDataArray[count].MulMode=true
# @clickDataArray[count].Mulvaluelist=self.Modals.T_Mul.valuelist
# @clickDataArray[count].value=self.Modals.T_Mul.valuelist[0]
# $("#t-ModaL-Text").modal 'toggle'
# else
# toastr.error "Please provide values"
# T_MulUploadChange :(e)->
# self=@
# console.log "file change"
# files=document.getElementById 't-Modal-Text-Tabpanel-MulUpload-File'
# file=files.files[0]
# if file.type.match(/text.*/)
# console.log "file success"
# reader = new FileReader
# reader.onload = (e) ->
# self.Modals.T_Mul.value=reader.result
# self.Modals.T_Mul.valuelist=self.Modals.T_Mul.value.split ", "
# reader.readAsText file
# else
# toastr.error "This file of type is not support yet"
# T_MulUploadSubmit :(count)->
# self=@
# if self.Modals.T_Mul.valuelist.length >=1
# @clickDataArray[count].MulMode=true
# @clickDataArray[count].Mulvaluelist=self.Modals.T_Mul.valuelist
# @clickDataArray[count].value= self.Modals.T_Mul.valuelist[0]
# $("#t-ModaL-Text").modal 'toggle'
# else
# toastr.error "Please provide values"
# R_dompathUpdate:(obj)->
# obj.dompath+= "[value='"+obj.picked+"']"
# return obj
# initializeClickArray : (array) ->
# for key in array
# if key.type is 'submit'
# index=array.indexOf(key)
# array.splice(index,1)
# return array
openNewTabFromChildren : (dompath)->
@urlArray[@tabStatus].clickDataArray.push
type: 'submit'
dompath: dompath
timbr_clicked: true
@openNewTabFromPhantom(dompath)
openNewTabFromPhantom: (dompath) ->
tempSubmitArray = []
tempSortedArray = []
for key in @urlArray[@tabStatus].clickDataArray
if key.type is 'checkbox' and key.checked is true
tempSubmitArray.push key
else if key.type is 'text' and key.timbr_clicked is true
tempSubmitArray.push key
else if key.type is 'radio' and key.timbr_clicked is true
key = @R_dompathUpdate(key)
tempSubmitArray.push key
else if key.type is 'select' and key.timbr_clicked is true
tempSubmitArray.push key
else if key.type is 'submit'
if key.dompath is dompath
tempSubmitArray.push key
else
tempSortedArray = tempSubmitArray.sort (a , b) ->
a.timbr_clickedcount - b.timbr_clickedcount
NProgress.start()
console.log tempSortedArray
Meteor.call 'getSearchContent', @urlInput, tempSortedArray, 'injectSearch', (error, result) =>
@urlArray.push
urlInput: result.url
urlContent: result.html
clickDataArray: []
actionArray: tempSortedArray
NProgress.done()
changeTabStatus:(number)->
@tabStatus= number
synchronousDatafromChildren : (object)->
self =@
self.urlArray[self.tabStatus].clickDataArray=object
# @enableTabs()
# submitTest:()->
# for key in @clickDataArray
# if key.timbr_clicked is true
# if key.type is 'radio'
# key=@R_dompathUpdate(key)
# @submitArray.push key
# @buttonObject.type="button"
# @buttonObject.timbr_clickedcount=999
# @submitArray.push @buttonObject
# sortedArray=[]
# sortedArray=@submitArray.sort (a, b) ->
# a.timbr_clickedcount - b.timbr_clickedcount
# console.log sortedArray
# Meteor.call 'getSearchContent', @urlInput, sortedArray, 'injectSearch', (error, result) =>
# @urlContent = result.html
# searchViewJson =
# urlContent: result.html
# urlLoaded: result.url
# Router.go 'resultView'
# Meteor.setTimeout ->
# resultVM?.setUrlContentFromSearch searchViewJson
# , 0
# enableTabs: ()->
# if $("#t-Search-Tab-Step2").hasClass("disabledTab")
# $("#t-Search-Tab-Step2").removeClass("disabled")
# $("#t-Search-Tab-Step2").removeClass("disabledTab")
# $("#t-Search-Main-Panel a[href='#t-Search-Input-Element-Collect']").tab('show')
# toastr.success 'Now You just click and input anything you want to search as usual in right page!'
# if $("#t-Search-Tab-Step3").hasClass("disabledTab")
# $("#t-Search-Tab-Step3").removeClass("disabled")
# $("#t-Search-Tab-Step3").removeClass("disabledTab")
# submitReady: ()->
# @UrlContent= "<h1>Please wait......</h1>"
# toastr.success "Please wait!"
# $("#t-Search-Main-Panel a[href='#t-Search-Form-Submit']").tab('show')
# $("#submitTest").click()
| 58634 | Template.searchView.rendered = ->
Vue.component 't-Search-Action-List', template: '#t-Search-Action-List-Template'
window.searchVM = new Vue
el: '.t-Search'
ready: ->
console.log @urlArray
self= @
document.getElementById('t-Modal-Text-Tabpanel-MulUpload-File').addEventListener('change', @T_MulUploadChange, false)
data:
tabCount: -1
tabStatus: 0
indexcount: 0
urlArray: []
urlContent: ''
urlInput: ''
# clickDataArray: []
S_Mul_Array: []
submitArray: []
buttonObject: {}
Modals:
T_Mul:
type:'text'
value: ''
valuelist: []
computed:
currentTab: ->
# console.log @tabStatus
return @urlArray[@tabStatus]
methods:
addUrlContent: (e) ->
url = @urlInput
@tabCount++
NProgress.start()
e.preventDefault()
Meteor.call 'getPhContent', url, 'injectSearch', '', (error, result) =>
# @urlContent = result
@urlArray.push
urlInput: @urlInput,
urlContent: result,
clickDataArray: []
NProgress.done()
templength=@urlArray.length
$("#t-Search-Iframe-Tab"+templength).tab 'show'
whetherText: (type, timbr_clicked) ->
if (type is 'text') and (timbr_clicked)
return true
else
return false
whetherCheckbox: (type, checked) ->
if (type is 'checkbox') and (checked)
return true
else
return false
whetherRadio: (type, timbr_clicked) ->
if (type is 'radio') and (timbr_clicked)
return true
else
return false
whetherSelect: (type, timbr_clicked) ->
if (type is 'select') and (timbr_clicked)
return true
else
return false
whetherSubmit: (type, timbr_clicked) ->
if (type is 'submit') and (timbr_clicked)
return true
else
return false
onClickExampleBtn: (e) ->
url = $(e.target).data().url
@urlInput = url
# onClickCustomize: (e)->
# _button = $(e.target)
# @indexcount=_button.data('count')
# if @clickDataArray[_button.data('count')].type=='text'
# @Modals.T_Mul.value=''
# @Modals.T_Mul.valuelist.length=0
# $('#t-ModaL-Text').modal()
# if @clickDataArray[_button.data('count')].type=='checkbox'
# $('#t-ModaL-Checkbox').modal()
# if @clickDataArray[_button.data('count')].type=='radio'
# @S_Mul_Array.length=0
# for key of @clickDataArray[_button.data("count")].valueandlabel
# tempvalue = key
# templabel = @clickDataArray[_button.data("count")].valueandlabel[key]
# @S_Mul_Array.push
# value: tempvalue
# label: templabel
# # console.log @S_Mul_Array
# $('#t-ModaL-Radio').modal()
# toastr.warning 'Choose this Advance Multiple Result will let out indepent Multiple Results!!'
# if @clickDataArray[_button.data('count')].type=='select'
# @S_Mul_Array.length=0
# for key of @clickDataArray[_button.data("count")].valueandlabel
# tempvalue = key
# templabel = @clickDataArray[_button.data("count")].valueandlabel[key]
# @S_Mul_Array.push
# value: tempvalue
# label: templabel
# $('#t-ModaL-Select').modal()
# toastr.warning 'Choose this Advance Multiple Result will let out indepent Multiple Results!!'
# return
# onClickDelete: (e) ->
# _button = $(e.target)
# @clickDataArray[_button.data('count')].timbr_clicked=false
# if @clickDataArray[_button.data('count')].value !=""
# @clickDataArray[_button.data('count')].value =""
# if @clickDataArray[_button.data('count')].valuelist
# delete @clickDataArray[_button.data('count')].valuelist
# if @clickDataArray[_button.data('count')].mulmodel =true
# @clickDataArray[_button.data('count')].mulmodel=false
# return
# T_MulInputInsert:(type)->
# self=@
# if type is "AtoZ"
# self.Modals.T_Mul.value= "A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z"
# if type is "1to9"
# self.Modals.T_Mul.value= "1, 2, 3, 4, 5, 6, 7, 8, 9"
# T_MulInputSubmit: (count)->
# self=@
# if self.Modals.T_Mul.value
# self.Modals.T_Mul.valuelist= self.Modals.T_Mul.value.split ", "
# else
# toastr.error "Please provide values"
# # console.log self.Modals.T_Mul.valuelist
# if self.Modals.T_Mul.valuelist.length >=1
# @clickDataArray[count].MulMode=true
# @clickDataArray[count].Mulvaluelist=self.Modals.T_Mul.valuelist
# @clickDataArray[count].value=self.Modals.T_Mul.valuelist[0]
# $("#t-ModaL-Text").modal 'toggle'
# else
# toastr.error "Please provide values"
# T_MulUploadChange :(e)->
# self=@
# console.log "file change"
# files=document.getElementById 't-Modal-Text-Tabpanel-MulUpload-File'
# file=files.files[0]
# if file.type.match(/text.*/)
# console.log "file success"
# reader = new FileReader
# reader.onload = (e) ->
# self.Modals.T_Mul.value=reader.result
# self.Modals.T_Mul.valuelist=self.Modals.T_Mul.value.split ", "
# reader.readAsText file
# else
# toastr.error "This file of type is not support yet"
# T_MulUploadSubmit :(count)->
# self=@
# if self.Modals.T_Mul.valuelist.length >=1
# @clickDataArray[count].MulMode=true
# @clickDataArray[count].Mulvaluelist=self.Modals.T_Mul.valuelist
# @clickDataArray[count].value= self.Modals.T_Mul.valuelist[0]
# $("#t-ModaL-Text").modal 'toggle'
# else
# toastr.error "Please provide values"
# R_dompathUpdate:(obj)->
# obj.dompath+= "[value='"+obj.picked+"']"
# return obj
# initializeClickArray : (array) ->
# for key in array
# if key.type is 'submit'
# index=array.indexOf(key)
# array.splice(index,1)
# return array
openNewTabFromChildren : (dompath)->
@urlArray[@tabStatus].clickDataArray.push
type: 'submit'
dompath: dompath
timbr_clicked: true
@openNewTabFromPhantom(dompath)
openNewTabFromPhantom: (dompath) ->
tempSubmitArray = []
tempSortedArray = []
for key in @urlArray[@tabStatus].clickDataArray
if key.type is 'checkbox' and key.checked is true
tempSubmitArray.push key
else if key.type is 'text' and key.timbr_clicked is true
tempSubmitArray.push key
else if key.type is 'radio' and key.timbr_clicked is true
key = @R_dompathUpdate(key)
tempSubmitArray.push key
else if key.type is 'select' and key.timbr_clicked is true
tempSubmitArray.push key
else if key.type is 'submit'
if key.dompath is dompath
tempSubmitArray.push key
else
tempSortedArray = tempSubmitArray.sort (a , b) ->
a.timbr_clickedcount - b.timbr_clickedcount
NProgress.start()
console.log tempSortedArray
Meteor.call 'getSearchContent', @urlInput, tempSortedArray, 'injectSearch', (error, result) =>
@urlArray.push
urlInput: result.url
urlContent: result.html
clickDataArray: []
actionArray: tempSortedArray
NProgress.done()
changeTabStatus:(number)->
@tabStatus= number
synchronousDatafromChildren : (object)->
self =@
self.urlArray[self.tabStatus].clickDataArray=object
# @enableTabs()
# submitTest:()->
# for key in @clickDataArray
# if key.timbr_clicked is true
# if key.type is 'radio'
# key=@<KEY>(key)
# @submitArray.push key
# @buttonObject.type="button"
# @buttonObject.timbr_clickedcount=999
# @submitArray.push @buttonObject
# sortedArray=[]
# sortedArray=@submitArray.sort (a, b) ->
# a.timbr_clickedcount - b.timbr_clickedcount
# console.log sortedArray
# Meteor.call 'getSearchContent', @urlInput, sortedArray, 'injectSearch', (error, result) =>
# @urlContent = result.html
# searchViewJson =
# urlContent: result.html
# urlLoaded: result.url
# Router.go 'resultView'
# Meteor.setTimeout ->
# resultVM?.setUrlContentFromSearch searchViewJson
# , 0
# enableTabs: ()->
# if $("#t-Search-Tab-Step2").hasClass("disabledTab")
# $("#t-Search-Tab-Step2").removeClass("disabled")
# $("#t-Search-Tab-Step2").removeClass("disabledTab")
# $("#t-Search-Main-Panel a[href='#t-Search-Input-Element-Collect']").tab('show')
# toastr.success 'Now You just click and input anything you want to search as usual in right page!'
# if $("#t-Search-Tab-Step3").hasClass("disabledTab")
# $("#t-Search-Tab-Step3").removeClass("disabled")
# $("#t-Search-Tab-Step3").removeClass("disabledTab")
# submitReady: ()->
# @UrlContent= "<h1>Please wait......</h1>"
# toastr.success "Please wait!"
# $("#t-Search-Main-Panel a[href='#t-Search-Form-Submit']").tab('show')
# $("#submitTest").click()
| true | Template.searchView.rendered = ->
Vue.component 't-Search-Action-List', template: '#t-Search-Action-List-Template'
window.searchVM = new Vue
el: '.t-Search'
ready: ->
console.log @urlArray
self= @
document.getElementById('t-Modal-Text-Tabpanel-MulUpload-File').addEventListener('change', @T_MulUploadChange, false)
data:
tabCount: -1
tabStatus: 0
indexcount: 0
urlArray: []
urlContent: ''
urlInput: ''
# clickDataArray: []
S_Mul_Array: []
submitArray: []
buttonObject: {}
Modals:
T_Mul:
type:'text'
value: ''
valuelist: []
computed:
currentTab: ->
# console.log @tabStatus
return @urlArray[@tabStatus]
methods:
addUrlContent: (e) ->
url = @urlInput
@tabCount++
NProgress.start()
e.preventDefault()
Meteor.call 'getPhContent', url, 'injectSearch', '', (error, result) =>
# @urlContent = result
@urlArray.push
urlInput: @urlInput,
urlContent: result,
clickDataArray: []
NProgress.done()
templength=@urlArray.length
$("#t-Search-Iframe-Tab"+templength).tab 'show'
whetherText: (type, timbr_clicked) ->
if (type is 'text') and (timbr_clicked)
return true
else
return false
whetherCheckbox: (type, checked) ->
if (type is 'checkbox') and (checked)
return true
else
return false
whetherRadio: (type, timbr_clicked) ->
if (type is 'radio') and (timbr_clicked)
return true
else
return false
whetherSelect: (type, timbr_clicked) ->
if (type is 'select') and (timbr_clicked)
return true
else
return false
whetherSubmit: (type, timbr_clicked) ->
if (type is 'submit') and (timbr_clicked)
return true
else
return false
onClickExampleBtn: (e) ->
url = $(e.target).data().url
@urlInput = url
# onClickCustomize: (e)->
# _button = $(e.target)
# @indexcount=_button.data('count')
# if @clickDataArray[_button.data('count')].type=='text'
# @Modals.T_Mul.value=''
# @Modals.T_Mul.valuelist.length=0
# $('#t-ModaL-Text').modal()
# if @clickDataArray[_button.data('count')].type=='checkbox'
# $('#t-ModaL-Checkbox').modal()
# if @clickDataArray[_button.data('count')].type=='radio'
# @S_Mul_Array.length=0
# for key of @clickDataArray[_button.data("count")].valueandlabel
# tempvalue = key
# templabel = @clickDataArray[_button.data("count")].valueandlabel[key]
# @S_Mul_Array.push
# value: tempvalue
# label: templabel
# # console.log @S_Mul_Array
# $('#t-ModaL-Radio').modal()
# toastr.warning 'Choose this Advance Multiple Result will let out indepent Multiple Results!!'
# if @clickDataArray[_button.data('count')].type=='select'
# @S_Mul_Array.length=0
# for key of @clickDataArray[_button.data("count")].valueandlabel
# tempvalue = key
# templabel = @clickDataArray[_button.data("count")].valueandlabel[key]
# @S_Mul_Array.push
# value: tempvalue
# label: templabel
# $('#t-ModaL-Select').modal()
# toastr.warning 'Choose this Advance Multiple Result will let out indepent Multiple Results!!'
# return
# onClickDelete: (e) ->
# _button = $(e.target)
# @clickDataArray[_button.data('count')].timbr_clicked=false
# if @clickDataArray[_button.data('count')].value !=""
# @clickDataArray[_button.data('count')].value =""
# if @clickDataArray[_button.data('count')].valuelist
# delete @clickDataArray[_button.data('count')].valuelist
# if @clickDataArray[_button.data('count')].mulmodel =true
# @clickDataArray[_button.data('count')].mulmodel=false
# return
# T_MulInputInsert:(type)->
# self=@
# if type is "AtoZ"
# self.Modals.T_Mul.value= "A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z"
# if type is "1to9"
# self.Modals.T_Mul.value= "1, 2, 3, 4, 5, 6, 7, 8, 9"
# T_MulInputSubmit: (count)->
# self=@
# if self.Modals.T_Mul.value
# self.Modals.T_Mul.valuelist= self.Modals.T_Mul.value.split ", "
# else
# toastr.error "Please provide values"
# # console.log self.Modals.T_Mul.valuelist
# if self.Modals.T_Mul.valuelist.length >=1
# @clickDataArray[count].MulMode=true
# @clickDataArray[count].Mulvaluelist=self.Modals.T_Mul.valuelist
# @clickDataArray[count].value=self.Modals.T_Mul.valuelist[0]
# $("#t-ModaL-Text").modal 'toggle'
# else
# toastr.error "Please provide values"
# T_MulUploadChange :(e)->
# self=@
# console.log "file change"
# files=document.getElementById 't-Modal-Text-Tabpanel-MulUpload-File'
# file=files.files[0]
# if file.type.match(/text.*/)
# console.log "file success"
# reader = new FileReader
# reader.onload = (e) ->
# self.Modals.T_Mul.value=reader.result
# self.Modals.T_Mul.valuelist=self.Modals.T_Mul.value.split ", "
# reader.readAsText file
# else
# toastr.error "This file of type is not support yet"
# T_MulUploadSubmit :(count)->
# self=@
# if self.Modals.T_Mul.valuelist.length >=1
# @clickDataArray[count].MulMode=true
# @clickDataArray[count].Mulvaluelist=self.Modals.T_Mul.valuelist
# @clickDataArray[count].value= self.Modals.T_Mul.valuelist[0]
# $("#t-ModaL-Text").modal 'toggle'
# else
# toastr.error "Please provide values"
# R_dompathUpdate:(obj)->
# obj.dompath+= "[value='"+obj.picked+"']"
# return obj
# initializeClickArray : (array) ->
# for key in array
# if key.type is 'submit'
# index=array.indexOf(key)
# array.splice(index,1)
# return array
openNewTabFromChildren : (dompath)->
@urlArray[@tabStatus].clickDataArray.push
type: 'submit'
dompath: dompath
timbr_clicked: true
@openNewTabFromPhantom(dompath)
openNewTabFromPhantom: (dompath) ->
tempSubmitArray = []
tempSortedArray = []
for key in @urlArray[@tabStatus].clickDataArray
if key.type is 'checkbox' and key.checked is true
tempSubmitArray.push key
else if key.type is 'text' and key.timbr_clicked is true
tempSubmitArray.push key
else if key.type is 'radio' and key.timbr_clicked is true
key = @R_dompathUpdate(key)
tempSubmitArray.push key
else if key.type is 'select' and key.timbr_clicked is true
tempSubmitArray.push key
else if key.type is 'submit'
if key.dompath is dompath
tempSubmitArray.push key
else
tempSortedArray = tempSubmitArray.sort (a , b) ->
a.timbr_clickedcount - b.timbr_clickedcount
NProgress.start()
console.log tempSortedArray
Meteor.call 'getSearchContent', @urlInput, tempSortedArray, 'injectSearch', (error, result) =>
@urlArray.push
urlInput: result.url
urlContent: result.html
clickDataArray: []
actionArray: tempSortedArray
NProgress.done()
changeTabStatus:(number)->
@tabStatus= number
synchronousDatafromChildren : (object)->
self =@
self.urlArray[self.tabStatus].clickDataArray=object
# @enableTabs()
# submitTest:()->
# for key in @clickDataArray
# if key.timbr_clicked is true
# if key.type is 'radio'
# key=@PI:KEY:<KEY>END_PI(key)
# @submitArray.push key
# @buttonObject.type="button"
# @buttonObject.timbr_clickedcount=999
# @submitArray.push @buttonObject
# sortedArray=[]
# sortedArray=@submitArray.sort (a, b) ->
# a.timbr_clickedcount - b.timbr_clickedcount
# console.log sortedArray
# Meteor.call 'getSearchContent', @urlInput, sortedArray, 'injectSearch', (error, result) =>
# @urlContent = result.html
# searchViewJson =
# urlContent: result.html
# urlLoaded: result.url
# Router.go 'resultView'
# Meteor.setTimeout ->
# resultVM?.setUrlContentFromSearch searchViewJson
# , 0
# enableTabs: ()->
# if $("#t-Search-Tab-Step2").hasClass("disabledTab")
# $("#t-Search-Tab-Step2").removeClass("disabled")
# $("#t-Search-Tab-Step2").removeClass("disabledTab")
# $("#t-Search-Main-Panel a[href='#t-Search-Input-Element-Collect']").tab('show')
# toastr.success 'Now You just click and input anything you want to search as usual in right page!'
# if $("#t-Search-Tab-Step3").hasClass("disabledTab")
# $("#t-Search-Tab-Step3").removeClass("disabled")
# $("#t-Search-Tab-Step3").removeClass("disabledTab")
# submitReady: ()->
# @UrlContent= "<h1>Please wait......</h1>"
# toastr.success "Please wait!"
# $("#t-Search-Main-Panel a[href='#t-Search-Form-Submit']").tab('show')
# $("#submitTest").click()
|
[
{
"context": "enemy' }\n { eid: 'e2', type: 'character', name: 'Tektike' }\n { eid: 'e2', type: 'bbox', shape: [3,4,5,6] ",
"end": 831,
"score": 0.873255729675293,
"start": 824,
"tag": "NAME",
"value": "Tektike"
},
{
"context": " filter = imm\n match:\n name: 'T... | spec/search/mutable_object_finder_spec.coffee | dcrosby42/metroid-clone | 5 | Finder = require '../../src/javascript/search/mutable_object_finder'
Immutable = require 'immutable'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
# expectArray = (actual,expected) ->
# if !Immutable.is(actual,expected)
# assert.fail(actual,expected,"Immutable structures not equal.\nExpected: #{expected.toString()}\n Actual: #{actual.toString()}")
expectArray = (got,expected) ->
expect(got.length).to.eq expected.length
expect(got).to.deep.include.members(expected)
zeldaObjects = [
{ eid: 'e1', type: 'tag', value: 'hero' }
{ eid: 'e1', type: 'character', name: 'Link' }
{ eid: 'e1', type: 'bbox', shape: [1,2,3,4] }
{ eid: 'e1', type: 'inventory', stuff: 'items' }
{ eid: 'e1', type: 'tag', value: 'enemy' }
{ eid: 'e2', type: 'character', name: 'Tektike' }
{ eid: 'e2', type: 'bbox', shape: [3,4,5,6] }
{ eid: 'e2', type: 'digger', status: 'burrowing' }
]
searchZelda = (filters) -> Finder.search zeldaObjects, imm(filters)
typeFilter = (t) -> { match: { type: t } }
describe 'MutableObjectFinder.search', ->
it 'can match on a single criteria', ->
charFilter =
match: { type: 'character' }
as: 'char'
expectArray searchZelda([charFilter]), [
{ char: zeldaObjects[1] }
{ char: zeldaObjects[5] }
]
it 'can match on multiple criteria', ->
linkFilter =
match: { type: 'character', name: 'Link' }
as: 'linkChar'
expectArray searchZelda([linkFilter]), [
{ linkChar: zeldaObjects[1] }
]
describe 'when filters omit "as"', ->
it 'labels results based on first matcher value', ->
filter = imm
match:
name: 'Tektike'
expectArray searchZelda([filter]), [
{ "Tektike": zeldaObjects[5] }
]
filter2 = imm
match:
type: 'digger'
expectArray searchZelda([filter2]), [
{ digger: zeldaObjects[7] }
]
describe 'with multiple filters', ->
it 'permutes the combinations of objects', ->
cf = typeFilter 'character'
bf = typeFilter 'bbox'
expectArray searchZelda([cf,bf]), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2] }
{ character: zeldaObjects[1], bbox: zeldaObjects[6] }
{ character: zeldaObjects[5], bbox: zeldaObjects[2] }
{ character: zeldaObjects[5], bbox: zeldaObjects[6] }
]
describe 'with joins', ->
charFilter =
match: { type: 'character' }
boxFilter =
match: { type: 'bbox' }
join: 'character.eid'
heroTagFilter =
match:
type: 'tag'
value: 'hero'
join: 'character.eid'
it 'constrains results by matching joined attributes', ->
expectArray searchZelda([charFilter, boxFilter]), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2] }
{ character: zeldaObjects[5], bbox: zeldaObjects[6] }
]
it 'joins and filters on multiple components', ->
filters = [
charFilter
boxFilter
heroTagFilter
]
expectArray searchZelda(filters), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2], tag: zeldaObjects[0] }
]
it 'does nothing with superfluous joins', ->
f =
match: { type: 'character' }
join: 'super.fluous'
expectArray searchZelda([f]), [
{ character: zeldaObjects[1] }
{ character: zeldaObjects[5] }
]
| 90193 | Finder = require '../../src/javascript/search/mutable_object_finder'
Immutable = require 'immutable'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
# expectArray = (actual,expected) ->
# if !Immutable.is(actual,expected)
# assert.fail(actual,expected,"Immutable structures not equal.\nExpected: #{expected.toString()}\n Actual: #{actual.toString()}")
expectArray = (got,expected) ->
expect(got.length).to.eq expected.length
expect(got).to.deep.include.members(expected)
zeldaObjects = [
{ eid: 'e1', type: 'tag', value: 'hero' }
{ eid: 'e1', type: 'character', name: 'Link' }
{ eid: 'e1', type: 'bbox', shape: [1,2,3,4] }
{ eid: 'e1', type: 'inventory', stuff: 'items' }
{ eid: 'e1', type: 'tag', value: 'enemy' }
{ eid: 'e2', type: 'character', name: '<NAME>' }
{ eid: 'e2', type: 'bbox', shape: [3,4,5,6] }
{ eid: 'e2', type: 'digger', status: 'burrowing' }
]
searchZelda = (filters) -> Finder.search zeldaObjects, imm(filters)
typeFilter = (t) -> { match: { type: t } }
describe 'MutableObjectFinder.search', ->
it 'can match on a single criteria', ->
charFilter =
match: { type: 'character' }
as: 'char'
expectArray searchZelda([charFilter]), [
{ char: zeldaObjects[1] }
{ char: zeldaObjects[5] }
]
it 'can match on multiple criteria', ->
linkFilter =
match: { type: 'character', name: 'Link' }
as: 'linkChar'
expectArray searchZelda([linkFilter]), [
{ linkChar: zeldaObjects[1] }
]
describe 'when filters omit "as"', ->
it 'labels results based on first matcher value', ->
filter = imm
match:
name: '<NAME>'
expectArray searchZelda([filter]), [
{ "<NAME>": zeldaObjects[5] }
]
filter2 = imm
match:
type: 'digger'
expectArray searchZelda([filter2]), [
{ digger: zeldaObjects[7] }
]
describe 'with multiple filters', ->
it 'permutes the combinations of objects', ->
cf = typeFilter 'character'
bf = typeFilter 'bbox'
expectArray searchZelda([cf,bf]), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2] }
{ character: zeldaObjects[1], bbox: zeldaObjects[6] }
{ character: zeldaObjects[5], bbox: zeldaObjects[2] }
{ character: zeldaObjects[5], bbox: zeldaObjects[6] }
]
describe 'with joins', ->
charFilter =
match: { type: 'character' }
boxFilter =
match: { type: 'bbox' }
join: 'character.eid'
heroTagFilter =
match:
type: 'tag'
value: 'hero'
join: 'character.eid'
it 'constrains results by matching joined attributes', ->
expectArray searchZelda([charFilter, boxFilter]), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2] }
{ character: zeldaObjects[5], bbox: zeldaObjects[6] }
]
it 'joins and filters on multiple components', ->
filters = [
charFilter
boxFilter
heroTagFilter
]
expectArray searchZelda(filters), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2], tag: zeldaObjects[0] }
]
it 'does nothing with superfluous joins', ->
f =
match: { type: 'character' }
join: 'super.fluous'
expectArray searchZelda([f]), [
{ character: zeldaObjects[1] }
{ character: zeldaObjects[5] }
]
| true | Finder = require '../../src/javascript/search/mutable_object_finder'
Immutable = require 'immutable'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
# expectArray = (actual,expected) ->
# if !Immutable.is(actual,expected)
# assert.fail(actual,expected,"Immutable structures not equal.\nExpected: #{expected.toString()}\n Actual: #{actual.toString()}")
expectArray = (got,expected) ->
expect(got.length).to.eq expected.length
expect(got).to.deep.include.members(expected)
zeldaObjects = [
{ eid: 'e1', type: 'tag', value: 'hero' }
{ eid: 'e1', type: 'character', name: 'Link' }
{ eid: 'e1', type: 'bbox', shape: [1,2,3,4] }
{ eid: 'e1', type: 'inventory', stuff: 'items' }
{ eid: 'e1', type: 'tag', value: 'enemy' }
{ eid: 'e2', type: 'character', name: 'PI:NAME:<NAME>END_PI' }
{ eid: 'e2', type: 'bbox', shape: [3,4,5,6] }
{ eid: 'e2', type: 'digger', status: 'burrowing' }
]
searchZelda = (filters) -> Finder.search zeldaObjects, imm(filters)
typeFilter = (t) -> { match: { type: t } }
describe 'MutableObjectFinder.search', ->
it 'can match on a single criteria', ->
charFilter =
match: { type: 'character' }
as: 'char'
expectArray searchZelda([charFilter]), [
{ char: zeldaObjects[1] }
{ char: zeldaObjects[5] }
]
it 'can match on multiple criteria', ->
linkFilter =
match: { type: 'character', name: 'Link' }
as: 'linkChar'
expectArray searchZelda([linkFilter]), [
{ linkChar: zeldaObjects[1] }
]
describe 'when filters omit "as"', ->
it 'labels results based on first matcher value', ->
filter = imm
match:
name: 'PI:NAME:<NAME>END_PI'
expectArray searchZelda([filter]), [
{ "PI:NAME:<NAME>END_PI": zeldaObjects[5] }
]
filter2 = imm
match:
type: 'digger'
expectArray searchZelda([filter2]), [
{ digger: zeldaObjects[7] }
]
describe 'with multiple filters', ->
it 'permutes the combinations of objects', ->
cf = typeFilter 'character'
bf = typeFilter 'bbox'
expectArray searchZelda([cf,bf]), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2] }
{ character: zeldaObjects[1], bbox: zeldaObjects[6] }
{ character: zeldaObjects[5], bbox: zeldaObjects[2] }
{ character: zeldaObjects[5], bbox: zeldaObjects[6] }
]
describe 'with joins', ->
charFilter =
match: { type: 'character' }
boxFilter =
match: { type: 'bbox' }
join: 'character.eid'
heroTagFilter =
match:
type: 'tag'
value: 'hero'
join: 'character.eid'
it 'constrains results by matching joined attributes', ->
expectArray searchZelda([charFilter, boxFilter]), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2] }
{ character: zeldaObjects[5], bbox: zeldaObjects[6] }
]
it 'joins and filters on multiple components', ->
filters = [
charFilter
boxFilter
heroTagFilter
]
expectArray searchZelda(filters), [
{ character: zeldaObjects[1], bbox: zeldaObjects[2], tag: zeldaObjects[0] }
]
it 'does nothing with superfluous joins', ->
f =
match: { type: 'character' }
join: 'super.fluous'
expectArray searchZelda([f]), [
{ character: zeldaObjects[1] }
{ character: zeldaObjects[5] }
]
|
[
{
"context": "eds\"\nphase: \"beta\"\nphase_modifier: \"Public\"\nsro: \"Hugh Pullinger\"\nservice_man: \"Daniel McLaughlin\"\nphase_history:\n",
"end": 416,
"score": 0.999861478805542,
"start": 402,
"tag": "NAME",
"value": "Hugh Pullinger"
},
{
"context": "ier: \"Public\"\nsro: \"Hu... | app/data/projects/access-to-work.cson | tsmorgan/dwp-ux-work | 0 | id: 5
name: "Apply for an Access to Work Grant"
aka: [ "Access To Work", "ATW" ]
description: "Lets users who are disabled or have a long-term health condition that makes their work life difficult, get a grant to pay for adjustments to their workplace, transport or support so that they can carry on working."
theme: "Health & Disability"
location: "Leeds"
phase: "beta"
phase_modifier: "Public"
sro: "Hugh Pullinger"
service_man: "Daniel McLaughlin"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2015"
}
]
alpha: [
{
label: "Completed"
date: "October 2015"
}
]
beta: [
{
label: "Started"
date: "November 2015"
}
{
label: "Private beta completed"
date: "July 2016"
}
{
label: "Public beta started"
date: "August 2016"
}
]
user_needs:[
{
asa: "someone with a disability or long-term health condition"
ineed: "the right support"
so: "I can continue to work"
}
{
asa: "someone who can't apply for or manage my access to work grant"
ineed: "someone to represent me"
so: "I get the support I need to work"
}
{
asa: "person who needs support"
ineed: "to know the status of my grant"
so: "that I'll know if and when I'll get the support I need"
}
{
asa: "person re-applying for support"
ineed: "information I've already given to be reused"
so: "I don't waste time repeating information"
}
{
asa: "person with a condition my colleagues are unaware of"
ineed: "to get support discreetly"
so: "I can do my work without my condition becoming more widely known than I want"
}
{
asa: "person with an access to work grant"
ineed: "invoices for support to be paid promptly"
so: "I'm not out of pocket or blamed for non-payment"
}
{
asa: "person applying for support to work"
ineed: "to only give relevant information"
so: "I don't waste my time"
}
{
asa: "an employer"
ineed: "support for my employees with long term conditions or disabilities"
so: "they can do their jobs"
}
{
asa: "a citizen"
ineed: "flexibility in how I interact with Government"
so: "I can choose the most suitable method of communication for my personal needs and condition"
}
]
priority: "Medium"
prototype: "http://accesstowork.herokuapp.com/application/"
showntells: [
"11 October 2016, 13:00"
"8 November 2016, 13:00"
"6 December 2016, 13:00"
]
| 75216 | id: 5
name: "Apply for an Access to Work Grant"
aka: [ "Access To Work", "ATW" ]
description: "Lets users who are disabled or have a long-term health condition that makes their work life difficult, get a grant to pay for adjustments to their workplace, transport or support so that they can carry on working."
theme: "Health & Disability"
location: "Leeds"
phase: "beta"
phase_modifier: "Public"
sro: "<NAME>"
service_man: "<NAME>"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2015"
}
]
alpha: [
{
label: "Completed"
date: "October 2015"
}
]
beta: [
{
label: "Started"
date: "November 2015"
}
{
label: "Private beta completed"
date: "July 2016"
}
{
label: "Public beta started"
date: "August 2016"
}
]
user_needs:[
{
asa: "someone with a disability or long-term health condition"
ineed: "the right support"
so: "I can continue to work"
}
{
asa: "someone who can't apply for or manage my access to work grant"
ineed: "someone to represent me"
so: "I get the support I need to work"
}
{
asa: "person who needs support"
ineed: "to know the status of my grant"
so: "that I'll know if and when I'll get the support I need"
}
{
asa: "person re-applying for support"
ineed: "information I've already given to be reused"
so: "I don't waste time repeating information"
}
{
asa: "person with a condition my colleagues are unaware of"
ineed: "to get support discreetly"
so: "I can do my work without my condition becoming more widely known than I want"
}
{
asa: "person with an access to work grant"
ineed: "invoices for support to be paid promptly"
so: "I'm not out of pocket or blamed for non-payment"
}
{
asa: "person applying for support to work"
ineed: "to only give relevant information"
so: "I don't waste my time"
}
{
asa: "an employer"
ineed: "support for my employees with long term conditions or disabilities"
so: "they can do their jobs"
}
{
asa: "a citizen"
ineed: "flexibility in how I interact with Government"
so: "I can choose the most suitable method of communication for my personal needs and condition"
}
]
priority: "Medium"
prototype: "http://accesstowork.herokuapp.com/application/"
showntells: [
"11 October 2016, 13:00"
"8 November 2016, 13:00"
"6 December 2016, 13:00"
]
| true | id: 5
name: "Apply for an Access to Work Grant"
aka: [ "Access To Work", "ATW" ]
description: "Lets users who are disabled or have a long-term health condition that makes their work life difficult, get a grant to pay for adjustments to their workplace, transport or support so that they can carry on working."
theme: "Health & Disability"
location: "Leeds"
phase: "beta"
phase_modifier: "Public"
sro: "PI:NAME:<NAME>END_PI"
service_man: "PI:NAME:<NAME>END_PI"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2015"
}
]
alpha: [
{
label: "Completed"
date: "October 2015"
}
]
beta: [
{
label: "Started"
date: "November 2015"
}
{
label: "Private beta completed"
date: "July 2016"
}
{
label: "Public beta started"
date: "August 2016"
}
]
user_needs:[
{
asa: "someone with a disability or long-term health condition"
ineed: "the right support"
so: "I can continue to work"
}
{
asa: "someone who can't apply for or manage my access to work grant"
ineed: "someone to represent me"
so: "I get the support I need to work"
}
{
asa: "person who needs support"
ineed: "to know the status of my grant"
so: "that I'll know if and when I'll get the support I need"
}
{
asa: "person re-applying for support"
ineed: "information I've already given to be reused"
so: "I don't waste time repeating information"
}
{
asa: "person with a condition my colleagues are unaware of"
ineed: "to get support discreetly"
so: "I can do my work without my condition becoming more widely known than I want"
}
{
asa: "person with an access to work grant"
ineed: "invoices for support to be paid promptly"
so: "I'm not out of pocket or blamed for non-payment"
}
{
asa: "person applying for support to work"
ineed: "to only give relevant information"
so: "I don't waste my time"
}
{
asa: "an employer"
ineed: "support for my employees with long term conditions or disabilities"
so: "they can do their jobs"
}
{
asa: "a citizen"
ineed: "flexibility in how I interact with Government"
so: "I can choose the most suitable method of communication for my personal needs and condition"
}
]
priority: "Medium"
prototype: "http://accesstowork.herokuapp.com/application/"
showntells: [
"11 October 2016, 13:00"
"8 November 2016, 13:00"
"6 December 2016, 13:00"
]
|
[
{
"context": "romise'\nWP = require 'wpapi' # https://github.com/WP-API/node-wpapi\nEntities = require('html-entities').Al",
"end": 210,
"score": 0.8352982997894287,
"start": 204,
"tag": "USERNAME",
"value": "WP-API"
},
{
"context": "endpoint: 'http://squishle.me/wp-json'\n username... | lib/pegg-squishle.coffee | Gratzi/pegg-squishle-parse | 0 | { fail, pretty, debug, log, errorLog } = require '../lib/common'
_ = require 'lodash'
Promise = require('parse/node').Promise
request = require 'request-promise'
WP = require 'wpapi' # https://github.com/WP-API/node-wpapi
Entities = require('html-entities').AllHtmlEntities # https://www.npmjs.com/package/html-entities
parse = require '../lib/pegg-parse'
AWS = require 'aws-sdk'
entities = new Entities()
SQUISHLE_USERNAME = process.env.SQUISHLE_USERNAME or fail "cannot have an empty SQUISHLE_USERNAME"
SQUISHLE_PASSWORD = process.env.SQUISHLE_PASSWORD or fail "cannot have an empty SQUISHLE_PASSWORD"
wp = new WP (
endpoint: 'http://squishle.me/wp-json'
username: SQUISHLE_USERNAME
password: SQUISHLE_PASSWORD
auth: true
)
gifIdPattern = /[\/-]([^\/?-]+)($|\?)/
class PeggSquishle
#card =
# question: 'Some question'
# deck: 'Throwback'
# choices: [
# {text: "first choice", image: {source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text: "second choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text:"third choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text:"fourth choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}}
# ]
processCard: (postId, categories) =>
log "creating card from post: #{postId}"
post = null
@fetchPostData postId
.then (_post) => post = _post
.then @fetchImageData
.catch (errors) =>
errorLog errors.toString()
content = post.content
if content?.choices?
if errors.isArray
for error in errors
if error?.choice?.num?
squishleChoice = _.find content.choices, (c) -> c.num is error.choice.num
squishleChoice.error = error.message
else
content.error = errors.toString()
else
content = error: errors.toString()
debug "updating post with error", content
@updatePost postId, JSON.stringify content
throw errors
.then (card) =>
if categories?
card.deck = JSON.parse(categories)?[0]
if card.id?
@updateCard card
.then (result) =>
log "card updated: ", pretty result
@updatePost postId, JSON.stringify result
@backupImages card.choices
else
@createCard card
.then (result) =>
log "card created: ", pretty result
@updatePost postId, JSON.stringify result
@backupImages card.choices
@incrementDeck card.deck
backupImages: (choices) =>
s3 = new AWS.S3()
for own id, choice of choices
do (id, choice) =>
# download image to buffer
request.get uri: choice.image.url, encoding: null
.then (body) =>
log "downloaded image for choice", choice.id
# upload to s3
s3.putObject {
Bucket: 'images.pegg.us'
Key: choice.id + '.mp4'
Metadata:
sourceUrl: choice.image.url
Body: body
}, (error, data) =>
if error? then errorLog "aws error", error, error.stack
else log "aws success", data
.catch errorLog
fetchPostData: (postId) =>
log "fetching squishle post details for #{postId}"
wp.posts().id(postId).get()
.catch (err) => console.log err
.then (result) =>
console.log result
post = {}
post.choices = []
post.post = postId
post.question = entities.decode result.title.rendered
unless _.isEmpty result.content?.rendered
defuckedRenderedContent = entities.decode(result.content.rendered.replace(/<(?:.|\n)*?>/gm, '')).replace(/[“”″]/gm, '"')
content = JSON.parse(defuckedRenderedContent)
if content?
post.content = content
if content?.cardId?
post.id = content.cardId
if content?.choices?
content.choices = _.sortBy content.choices, 'num'
_.each content.choices, (c) -> delete c.error if c.error
for i in [1..4]
choice = {}
choice.gifUrl = result["gif#{i}"]
choice.text = result["answer#{i}"]
choice.num = i
if content?.choices?[i-1]?.id?
choice.id = content.choices[i-1].id
post.choices.push choice
console.log JSON.stringify post
return post
fetchImageData: (card) =>
Promise.when(
for choice in card.choices then do (choice) =>
if choice.gifUrl.indexOf("imgur.com/a/") > -1
@fetchImgurAlbumData choice
else if choice.gifUrl.indexOf("imgur.com/gallery/") > -1
@fetchImgurGalleryData choice
else if choice.gifUrl.indexOf("imgur.com/") > -1
@fetchImgurImageData choice
else
error = new Error "Invalid URL for gif #{choice.gifUrl}"
errorLog error
error.choice = choice
throw error
).then (choices) =>
console.log pretty choices
card.choices = choices
card
fetchImgurAlbumData: (choice) =>
log "fetching imgur details for album #{choice.gifUrl}"
albumId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "albumId: #{albumId}"
props =
url: 'https://api.imgur.com/3/album/' + albumId
headers:
Authorization: 'Client-ID f2400da11df9695'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?.data?.images?[0]?
error = new Error "No result from imgur for album [#{albumId}]"
errorLog error
error.choice = choice
throw error
choice.image =
url: result.data.images[0].mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
fetchImgurGalleryData: (choice) =>
log "fetching imgur details for gallery image #{choice.gifUrl}"
imageOrAlbumId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "imageOrAlbumId: #{imageOrAlbumId}"
props =
url: 'https://api.imgur.com/3/gallery/' + imageOrAlbumId
headers:
Authorization: 'Client-ID f2400da11df9695'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?
error = new Error "No result from imgur for gif [#{imageOrAlbumId}]"
errorLog error
error.choice = choice
throw error
if result.data.is_album
choice.image =
url: result.data.images[0].mp4
source: choice.gifUrl
else
choice.image =
url: result.data.mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
fetchImgurImageData: (choice) =>
log "fetching imgur details for image #{choice.gifUrl}"
imageId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "imageId: #{imageId}"
props =
url: 'https://api.imgur.com/3/image/' + imageId
headers:
Authorization: 'Client-ID f2400da11df9695'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?.data?
error = new Error "No result from imgur for album [#{imageId}]"
errorLog error
error.choice = choice
throw error
choice.image =
url: result.data.mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
# fetchGiphyData: (choice) =>
# log "fetching giphy details for #{choice.gifId}"
# props =
# url: 'http://api.giphy.com/v1/gifs/' + choice.gifId
# qs:
# api_key: 'dc6zaTOxFJmzC'
# json: true
# request props
# .catch (error) => errorLog error
# .then (result) =>
# choice.image =
# url: result.data.images.original.url
# source: result.data.source_post_url
# choice
incrementDeck: (deck) =>
parse.getBy {type: "Deck", field: "name", value: deck}
.then (parseDeck) =>
parse.increment {type: "Deck", id: parseDeck.id, field: "count", num: 1}
.then (result) =>
console.log "#{deck} deck incremented"
createCard: (post) =>
card = {}
cardId = null
parseCard = null
card.choices = undefined
card.deck = post.deck
card.question = post.question
card.ACL = "*": read: true
card.publishDate = new Date()
parse.create type: 'Card', object: card
.then (result) =>
parseCard = result
cardId = parseCard.id
Promise.when(
for choice in post.choices then do (choice, cardId) =>
choice.card = parse.pointer type: 'Card', id: cardId
choice.ACL = "*": read: true
parse.create type: 'Choice', object: choice
)
.then (parseChoices) =>
for choice, i in post.choices
choice.id = parseChoices[i].id
choice.cardId = cardId
choice.card = undefined
choice.ACL = undefined
card.choices = _.keyBy post.choices, 'id'
prunedChoices = _.cloneDeep card.choices
for own id, choice of prunedChoices
if _.isEmpty choice.text
delete prunedChoices[id]
parseCard.set 'choices', prunedChoices
parseCard.save null, { useMasterKey: true }
.then =>
debug pretty parseCard
result =
cardId: cardId
choices: _.map card.choices, (choice) => id: choice.id, num: choice.num
result
updatePost: (postId, content) =>
log "updating post: #{postId} #{content}"
wp.posts().id(postId).update(content: content)
.catch (err) => console.log err
.then (result) =>
console.log result
updateCard: (card) =>
cardId = card.id
console.log "updating card #{cardId}"
debug pretty card
choices = card.choices
Promise.when(
for choice, i in choices then do (choice, i, cardId) =>
choice.card = parse.pointer type: 'Card', id: cardId
choice.ACL = "*": read: true
# if _.isEmpty choice.id
# parse.create type: 'Choice', object: choice
# .then (result) =>
# choice.id = result.id
# choice.cardId = cardId
# choice.card = undefined
# choice.ACL = undefined
# else if _.isEmpty choice.text
# delete choices[i]
# parse.delete type: 'Choice', id: choice.id
# else
parse.update type: 'Choice', id: choice.id, object: choice
.then (result) =>
choice.cardId = cardId
choice.card = undefined
choice.ACL = undefined
).then =>
card.choices = _.keyBy choices, 'id'
card.ACL = "*": read: true
parse.update type: 'Card', id: cardId, object: card
.then =>
result =
cardId: cardId
choices: _.map card.choices, (choice) => id: choice.id, num: choice.num
result
module.exports = new PeggSquishle
| 57099 | { fail, pretty, debug, log, errorLog } = require '../lib/common'
_ = require 'lodash'
Promise = require('parse/node').Promise
request = require 'request-promise'
WP = require 'wpapi' # https://github.com/WP-API/node-wpapi
Entities = require('html-entities').AllHtmlEntities # https://www.npmjs.com/package/html-entities
parse = require '../lib/pegg-parse'
AWS = require 'aws-sdk'
entities = new Entities()
SQUISHLE_USERNAME = process.env.SQUISHLE_USERNAME or fail "cannot have an empty SQUISHLE_USERNAME"
SQUISHLE_PASSWORD = process.env.SQUISHLE_PASSWORD or fail "cannot have an empty SQUISHLE_PASSWORD"
wp = new WP (
endpoint: 'http://squishle.me/wp-json'
username: SQUISHLE_USERNAME
password: <PASSWORD>
auth: true
)
gifIdPattern = /[\/-]([^\/?-]+)($|\?)/
class PeggSquishle
#card =
# question: 'Some question'
# deck: 'Throwback'
# choices: [
# {text: "first choice", image: {source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text: "second choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text:"third choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text:"fourth choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}}
# ]
processCard: (postId, categories) =>
log "creating card from post: #{postId}"
post = null
@fetchPostData postId
.then (_post) => post = _post
.then @fetchImageData
.catch (errors) =>
errorLog errors.toString()
content = post.content
if content?.choices?
if errors.isArray
for error in errors
if error?.choice?.num?
squishleChoice = _.find content.choices, (c) -> c.num is error.choice.num
squishleChoice.error = error.message
else
content.error = errors.toString()
else
content = error: errors.toString()
debug "updating post with error", content
@updatePost postId, JSON.stringify content
throw errors
.then (card) =>
if categories?
card.deck = JSON.parse(categories)?[0]
if card.id?
@updateCard card
.then (result) =>
log "card updated: ", pretty result
@updatePost postId, JSON.stringify result
@backupImages card.choices
else
@createCard card
.then (result) =>
log "card created: ", pretty result
@updatePost postId, JSON.stringify result
@backupImages card.choices
@incrementDeck card.deck
backupImages: (choices) =>
s3 = new AWS.S3()
for own id, choice of choices
do (id, choice) =>
# download image to buffer
request.get uri: choice.image.url, encoding: null
.then (body) =>
log "downloaded image for choice", choice.id
# upload to s3
s3.putObject {
Bucket: 'images.pegg.us'
Key: choice.id + '.mp4'
Metadata:
sourceUrl: choice.image.url
Body: body
}, (error, data) =>
if error? then errorLog "aws error", error, error.stack
else log "aws success", data
.catch errorLog
fetchPostData: (postId) =>
log "fetching squishle post details for #{postId}"
wp.posts().id(postId).get()
.catch (err) => console.log err
.then (result) =>
console.log result
post = {}
post.choices = []
post.post = postId
post.question = entities.decode result.title.rendered
unless _.isEmpty result.content?.rendered
defuckedRenderedContent = entities.decode(result.content.rendered.replace(/<(?:.|\n)*?>/gm, '')).replace(/[“”″]/gm, '"')
content = JSON.parse(defuckedRenderedContent)
if content?
post.content = content
if content?.cardId?
post.id = content.cardId
if content?.choices?
content.choices = _.sortBy content.choices, 'num'
_.each content.choices, (c) -> delete c.error if c.error
for i in [1..4]
choice = {}
choice.gifUrl = result["gif#{i}"]
choice.text = result["answer#{i}"]
choice.num = i
if content?.choices?[i-1]?.id?
choice.id = content.choices[i-1].id
post.choices.push choice
console.log JSON.stringify post
return post
fetchImageData: (card) =>
Promise.when(
for choice in card.choices then do (choice) =>
if choice.gifUrl.indexOf("imgur.com/a/") > -1
@fetchImgurAlbumData choice
else if choice.gifUrl.indexOf("imgur.com/gallery/") > -1
@fetchImgurGalleryData choice
else if choice.gifUrl.indexOf("imgur.com/") > -1
@fetchImgurImageData choice
else
error = new Error "Invalid URL for gif #{choice.gifUrl}"
errorLog error
error.choice = choice
throw error
).then (choices) =>
console.log pretty choices
card.choices = choices
card
fetchImgurAlbumData: (choice) =>
log "fetching imgur details for album #{choice.gifUrl}"
albumId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "albumId: #{albumId}"
props =
url: 'https://api.imgur.com/3/album/' + albumId
headers:
Authorization: 'Client-ID f2400da11df9695'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?.data?.images?[0]?
error = new Error "No result from imgur for album [#{albumId}]"
errorLog error
error.choice = choice
throw error
choice.image =
url: result.data.images[0].mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
fetchImgurGalleryData: (choice) =>
log "fetching imgur details for gallery image #{choice.gifUrl}"
imageOrAlbumId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "imageOrAlbumId: #{imageOrAlbumId}"
props =
url: 'https://api.imgur.com/3/gallery/' + imageOrAlbumId
headers:
Authorization: 'Client-ID f<PASSWORD>'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?
error = new Error "No result from imgur for gif [#{imageOrAlbumId}]"
errorLog error
error.choice = choice
throw error
if result.data.is_album
choice.image =
url: result.data.images[0].mp4
source: choice.gifUrl
else
choice.image =
url: result.data.mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
fetchImgurImageData: (choice) =>
log "fetching imgur details for image #{choice.gifUrl}"
imageId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "imageId: #{imageId}"
props =
url: 'https://api.imgur.com/3/image/' + imageId
headers:
Authorization: 'Client-ID <KEY> <PASSWORD>'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?.data?
error = new Error "No result from imgur for album [#{imageId}]"
errorLog error
error.choice = choice
throw error
choice.image =
url: result.data.mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
# fetchGiphyData: (choice) =>
# log "fetching giphy details for #{choice.gifId}"
# props =
# url: 'http://api.giphy.com/v1/gifs/' + choice.gifId
# qs:
# api_key: '<KEY>'
# json: true
# request props
# .catch (error) => errorLog error
# .then (result) =>
# choice.image =
# url: result.data.images.original.url
# source: result.data.source_post_url
# choice
incrementDeck: (deck) =>
parse.getBy {type: "Deck", field: "name", value: deck}
.then (parseDeck) =>
parse.increment {type: "Deck", id: parseDeck.id, field: "count", num: 1}
.then (result) =>
console.log "#{deck} deck incremented"
createCard: (post) =>
card = {}
cardId = null
parseCard = null
card.choices = undefined
card.deck = post.deck
card.question = post.question
card.ACL = "*": read: true
card.publishDate = new Date()
parse.create type: 'Card', object: card
.then (result) =>
parseCard = result
cardId = parseCard.id
Promise.when(
for choice in post.choices then do (choice, cardId) =>
choice.card = parse.pointer type: 'Card', id: cardId
choice.ACL = "*": read: true
parse.create type: 'Choice', object: choice
)
.then (parseChoices) =>
for choice, i in post.choices
choice.id = parseChoices[i].id
choice.cardId = cardId
choice.card = undefined
choice.ACL = undefined
card.choices = _.keyBy post.choices, 'id'
prunedChoices = _.cloneDeep card.choices
for own id, choice of prunedChoices
if _.isEmpty choice.text
delete prunedChoices[id]
parseCard.set 'choices', prunedChoices
parseCard.save null, { useMasterKey: true }
.then =>
debug pretty parseCard
result =
cardId: cardId
choices: _.map card.choices, (choice) => id: choice.id, num: choice.num
result
updatePost: (postId, content) =>
log "updating post: #{postId} #{content}"
wp.posts().id(postId).update(content: content)
.catch (err) => console.log err
.then (result) =>
console.log result
updateCard: (card) =>
cardId = card.id
console.log "updating card #{cardId}"
debug pretty card
choices = card.choices
Promise.when(
for choice, i in choices then do (choice, i, cardId) =>
choice.card = parse.pointer type: 'Card', id: cardId
choice.ACL = "*": read: true
# if _.isEmpty choice.id
# parse.create type: 'Choice', object: choice
# .then (result) =>
# choice.id = result.id
# choice.cardId = cardId
# choice.card = undefined
# choice.ACL = undefined
# else if _.isEmpty choice.text
# delete choices[i]
# parse.delete type: 'Choice', id: choice.id
# else
parse.update type: 'Choice', id: choice.id, object: choice
.then (result) =>
choice.cardId = cardId
choice.card = undefined
choice.ACL = undefined
).then =>
card.choices = _.keyBy choices, 'id'
card.ACL = "*": read: true
parse.update type: 'Card', id: cardId, object: card
.then =>
result =
cardId: cardId
choices: _.map card.choices, (choice) => id: choice.id, num: choice.num
result
module.exports = new PeggSquishle
| true | { fail, pretty, debug, log, errorLog } = require '../lib/common'
_ = require 'lodash'
Promise = require('parse/node').Promise
request = require 'request-promise'
WP = require 'wpapi' # https://github.com/WP-API/node-wpapi
Entities = require('html-entities').AllHtmlEntities # https://www.npmjs.com/package/html-entities
parse = require '../lib/pegg-parse'
AWS = require 'aws-sdk'
entities = new Entities()
SQUISHLE_USERNAME = process.env.SQUISHLE_USERNAME or fail "cannot have an empty SQUISHLE_USERNAME"
SQUISHLE_PASSWORD = process.env.SQUISHLE_PASSWORD or fail "cannot have an empty SQUISHLE_PASSWORD"
wp = new WP (
endpoint: 'http://squishle.me/wp-json'
username: SQUISHLE_USERNAME
password: PI:PASSWORD:<PASSWORD>END_PI
auth: true
)
gifIdPattern = /[\/-]([^\/?-]+)($|\?)/
class PeggSquishle
#card =
# question: 'Some question'
# deck: 'Throwback'
# choices: [
# {text: "first choice", image: {source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text: "second choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text:"third choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}},
# {text:"fourth choice", image:{source:"https://media1.giphy.com/media/lppjX4teaSUnu/giphy.gif", url:""}}
# ]
processCard: (postId, categories) =>
log "creating card from post: #{postId}"
post = null
@fetchPostData postId
.then (_post) => post = _post
.then @fetchImageData
.catch (errors) =>
errorLog errors.toString()
content = post.content
if content?.choices?
if errors.isArray
for error in errors
if error?.choice?.num?
squishleChoice = _.find content.choices, (c) -> c.num is error.choice.num
squishleChoice.error = error.message
else
content.error = errors.toString()
else
content = error: errors.toString()
debug "updating post with error", content
@updatePost postId, JSON.stringify content
throw errors
.then (card) =>
if categories?
card.deck = JSON.parse(categories)?[0]
if card.id?
@updateCard card
.then (result) =>
log "card updated: ", pretty result
@updatePost postId, JSON.stringify result
@backupImages card.choices
else
@createCard card
.then (result) =>
log "card created: ", pretty result
@updatePost postId, JSON.stringify result
@backupImages card.choices
@incrementDeck card.deck
backupImages: (choices) =>
s3 = new AWS.S3()
for own id, choice of choices
do (id, choice) =>
# download image to buffer
request.get uri: choice.image.url, encoding: null
.then (body) =>
log "downloaded image for choice", choice.id
# upload to s3
s3.putObject {
Bucket: 'images.pegg.us'
Key: choice.id + '.mp4'
Metadata:
sourceUrl: choice.image.url
Body: body
}, (error, data) =>
if error? then errorLog "aws error", error, error.stack
else log "aws success", data
.catch errorLog
fetchPostData: (postId) =>
log "fetching squishle post details for #{postId}"
wp.posts().id(postId).get()
.catch (err) => console.log err
.then (result) =>
console.log result
post = {}
post.choices = []
post.post = postId
post.question = entities.decode result.title.rendered
unless _.isEmpty result.content?.rendered
defuckedRenderedContent = entities.decode(result.content.rendered.replace(/<(?:.|\n)*?>/gm, '')).replace(/[“”″]/gm, '"')
content = JSON.parse(defuckedRenderedContent)
if content?
post.content = content
if content?.cardId?
post.id = content.cardId
if content?.choices?
content.choices = _.sortBy content.choices, 'num'
_.each content.choices, (c) -> delete c.error if c.error
for i in [1..4]
choice = {}
choice.gifUrl = result["gif#{i}"]
choice.text = result["answer#{i}"]
choice.num = i
if content?.choices?[i-1]?.id?
choice.id = content.choices[i-1].id
post.choices.push choice
console.log JSON.stringify post
return post
fetchImageData: (card) =>
Promise.when(
for choice in card.choices then do (choice) =>
if choice.gifUrl.indexOf("imgur.com/a/") > -1
@fetchImgurAlbumData choice
else if choice.gifUrl.indexOf("imgur.com/gallery/") > -1
@fetchImgurGalleryData choice
else if choice.gifUrl.indexOf("imgur.com/") > -1
@fetchImgurImageData choice
else
error = new Error "Invalid URL for gif #{choice.gifUrl}"
errorLog error
error.choice = choice
throw error
).then (choices) =>
console.log pretty choices
card.choices = choices
card
fetchImgurAlbumData: (choice) =>
log "fetching imgur details for album #{choice.gifUrl}"
albumId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "albumId: #{albumId}"
props =
url: 'https://api.imgur.com/3/album/' + albumId
headers:
Authorization: 'Client-ID f2400da11df9695'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?.data?.images?[0]?
error = new Error "No result from imgur for album [#{albumId}]"
errorLog error
error.choice = choice
throw error
choice.image =
url: result.data.images[0].mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
fetchImgurGalleryData: (choice) =>
log "fetching imgur details for gallery image #{choice.gifUrl}"
imageOrAlbumId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "imageOrAlbumId: #{imageOrAlbumId}"
props =
url: 'https://api.imgur.com/3/gallery/' + imageOrAlbumId
headers:
Authorization: 'Client-ID fPI:PASSWORD:<PASSWORD>END_PI'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?
error = new Error "No result from imgur for gif [#{imageOrAlbumId}]"
errorLog error
error.choice = choice
throw error
if result.data.is_album
choice.image =
url: result.data.images[0].mp4
source: choice.gifUrl
else
choice.image =
url: result.data.mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
fetchImgurImageData: (choice) =>
log "fetching imgur details for image #{choice.gifUrl}"
imageId = gifIdPattern.exec(choice.gifUrl)?[1]
console.log "imageId: #{imageId}"
props =
url: 'https://api.imgur.com/3/image/' + imageId
headers:
Authorization: 'Client-ID PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
json: true
request props
.catch (error) => errorLog error
.then (result) =>
debug "IMGUR: " + pretty result
unless result?.data?
error = new Error "No result from imgur for album [#{imageId}]"
errorLog error
error.choice = choice
throw error
choice.image =
url: result.data.mp4
source: choice.gifUrl
unless choice.image.url?
error = new Error "Invalid Imgur URL for gif #{choice.image.source}"
errorLog error
error.choice = choice
throw error
choice
# fetchGiphyData: (choice) =>
# log "fetching giphy details for #{choice.gifId}"
# props =
# url: 'http://api.giphy.com/v1/gifs/' + choice.gifId
# qs:
# api_key: 'PI:KEY:<KEY>END_PI'
# json: true
# request props
# .catch (error) => errorLog error
# .then (result) =>
# choice.image =
# url: result.data.images.original.url
# source: result.data.source_post_url
# choice
incrementDeck: (deck) =>
parse.getBy {type: "Deck", field: "name", value: deck}
.then (parseDeck) =>
parse.increment {type: "Deck", id: parseDeck.id, field: "count", num: 1}
.then (result) =>
console.log "#{deck} deck incremented"
createCard: (post) =>
card = {}
cardId = null
parseCard = null
card.choices = undefined
card.deck = post.deck
card.question = post.question
card.ACL = "*": read: true
card.publishDate = new Date()
parse.create type: 'Card', object: card
.then (result) =>
parseCard = result
cardId = parseCard.id
Promise.when(
for choice in post.choices then do (choice, cardId) =>
choice.card = parse.pointer type: 'Card', id: cardId
choice.ACL = "*": read: true
parse.create type: 'Choice', object: choice
)
.then (parseChoices) =>
for choice, i in post.choices
choice.id = parseChoices[i].id
choice.cardId = cardId
choice.card = undefined
choice.ACL = undefined
card.choices = _.keyBy post.choices, 'id'
prunedChoices = _.cloneDeep card.choices
for own id, choice of prunedChoices
if _.isEmpty choice.text
delete prunedChoices[id]
parseCard.set 'choices', prunedChoices
parseCard.save null, { useMasterKey: true }
.then =>
debug pretty parseCard
result =
cardId: cardId
choices: _.map card.choices, (choice) => id: choice.id, num: choice.num
result
updatePost: (postId, content) =>
log "updating post: #{postId} #{content}"
wp.posts().id(postId).update(content: content)
.catch (err) => console.log err
.then (result) =>
console.log result
updateCard: (card) =>
cardId = card.id
console.log "updating card #{cardId}"
debug pretty card
choices = card.choices
Promise.when(
for choice, i in choices then do (choice, i, cardId) =>
choice.card = parse.pointer type: 'Card', id: cardId
choice.ACL = "*": read: true
# if _.isEmpty choice.id
# parse.create type: 'Choice', object: choice
# .then (result) =>
# choice.id = result.id
# choice.cardId = cardId
# choice.card = undefined
# choice.ACL = undefined
# else if _.isEmpty choice.text
# delete choices[i]
# parse.delete type: 'Choice', id: choice.id
# else
parse.update type: 'Choice', id: choice.id, object: choice
.then (result) =>
choice.cardId = cardId
choice.card = undefined
choice.ACL = undefined
).then =>
card.choices = _.keyBy choices, 'id'
card.ACL = "*": read: true
parse.update type: 'Card', id: cardId, object: card
.then =>
result =
cardId: cardId
choices: _.map card.choices, (choice) => id: choice.id, num: choice.num
result
module.exports = new PeggSquishle
|
[
{
"context": " @cocktail =\n id: 2\n name: 'Margarita'\n userId: 4\n ingredients:[ ]\n ",
"end": 765,
"score": 0.9991793632507324,
"start": 756,
"tag": "NAME",
"value": "Margarita"
}
] | spec/javascripts/controllers/CocktailShowCtrl_spec.coffee | baberthal/cocktails | 0 | #= require spec_helper
describe 'CocktailShowCtrl', ->
beforeEach ->
@setupController('CocktailShowCtrl')
@loadFixtures()
describe 'controller initialization', ->
describe 'when the current cocktail has ingredients', ->
beforeEach ->
@stateParams.id = 4
request = new RegExp("\/cocktails\/*")
@http.whenGET(request).respond(200, @cocktail)
@templateExpectations()
it 'knows the cocktail', ->
expect(@scope.cocktail).toEqualData(@cocktail)
it 'knows about cocktails ingredients', ->
expect(@scope.hasIngredients).toBeTruthy()
describe 'when the current cocktail does not have ingredients', ->
beforeEach ->
@cocktail =
id: 2
name: 'Margarita'
userId: 4
ingredients:[ ]
@stateParams.id = 4
request = new RegExp("\/cocktails\/*")
@http.whenGET(request).respond(200, @cocktail)
@templateExpectations()
it 'knows if a cocktail does not have ingredients', ->
expect(@scope.hasIngredients).toBeFalsy()
| 80860 | #= require spec_helper
describe 'CocktailShowCtrl', ->
beforeEach ->
@setupController('CocktailShowCtrl')
@loadFixtures()
describe 'controller initialization', ->
describe 'when the current cocktail has ingredients', ->
beforeEach ->
@stateParams.id = 4
request = new RegExp("\/cocktails\/*")
@http.whenGET(request).respond(200, @cocktail)
@templateExpectations()
it 'knows the cocktail', ->
expect(@scope.cocktail).toEqualData(@cocktail)
it 'knows about cocktails ingredients', ->
expect(@scope.hasIngredients).toBeTruthy()
describe 'when the current cocktail does not have ingredients', ->
beforeEach ->
@cocktail =
id: 2
name: '<NAME>'
userId: 4
ingredients:[ ]
@stateParams.id = 4
request = new RegExp("\/cocktails\/*")
@http.whenGET(request).respond(200, @cocktail)
@templateExpectations()
it 'knows if a cocktail does not have ingredients', ->
expect(@scope.hasIngredients).toBeFalsy()
| true | #= require spec_helper
describe 'CocktailShowCtrl', ->
beforeEach ->
@setupController('CocktailShowCtrl')
@loadFixtures()
describe 'controller initialization', ->
describe 'when the current cocktail has ingredients', ->
beforeEach ->
@stateParams.id = 4
request = new RegExp("\/cocktails\/*")
@http.whenGET(request).respond(200, @cocktail)
@templateExpectations()
it 'knows the cocktail', ->
expect(@scope.cocktail).toEqualData(@cocktail)
it 'knows about cocktails ingredients', ->
expect(@scope.hasIngredients).toBeTruthy()
describe 'when the current cocktail does not have ingredients', ->
beforeEach ->
@cocktail =
id: 2
name: 'PI:NAME:<NAME>END_PI'
userId: 4
ingredients:[ ]
@stateParams.id = 4
request = new RegExp("\/cocktails\/*")
@http.whenGET(request).respond(200, @cocktail)
@templateExpectations()
it 'knows if a cocktail does not have ingredients', ->
expect(@scope.hasIngredients).toBeFalsy()
|
[
{
"context": "\n\n entities = [\n { entity: 'funk', name: 'splosion' },\n { entity: 'funk', name: 'dealwithit' },",
"end": 1942,
"score": 0.9742152690887451,
"start": 1934,
"tag": "NAME",
"value": "splosion"
},
{
"context": "ame: 'splosion' },\n { entity: 'funk', na... | test/testEmojiProcessor.coffee | ianfixes/macramoji | 1 | fs = require 'fs'
test = require 'tape'
ctest = require 'tape-catch'
sinon = require 'sinon'
EmojiProcessor = require '../src/emojiProcessor'
ImageContainer = require '../src/imageContainer'
ImageResult = require '../src/imageResult'
ImageWorker = require '../src/imageWorker'
EmojiStore = require '../src/emojiStore'
input1 = '(dealwithit(:poop:, :kamina-glasses:))splosion'
emojiFetchFn = (cb) ->
cb null,
favico: 'http://tinylittlelife.org/favicon.ico'
fakeEmojiStore = new EmojiStore(emojiFetchFn, 0)
allMacros = require '../src/defaultMacros'
test 'EmojiProcessor', (troot) ->
test 'parser exists', (t) ->
ep = new EmojiProcessor({}, undefined)
t.ok(ep.parser(), 'parser exists')
t.end()
test 'parser parses positive input', (t) ->
ep = new EmojiProcessor({}, undefined)
t.equal(ep.parseable(input1), true)
t.end()
test 'does not parse negative input', (t) ->
onErr = sinon.spy()
ep = new EmojiProcessor({}, undefined)
t.equal(ep.parseable(input1 + " crap"), false)
t.end()
test 'can reduce (tree into array)', (t) ->
ep = new EmojiProcessor({}, undefined)
parseTree = ep.parse(input1)
entities = ep.reduce parseTree, [], (acc, tree) ->
acc.concat([
entity: tree.entity
name: tree.name
])
expected = [
{ entity: 'funk', name: 'splosion' },
{ entity: 'funk', name: 'dealwithit' },
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'kamina-glasses' }
]
t.deepEqual(entities, expected)
t.end()
test 'understands positional arguments and initializes proper vars', (t) ->
ep = new EmojiProcessor('foo', 'bar')
t.equal(ep.emojiStore, 'foo')
t.equal(ep.macros, 'bar')
t.end()
test 'can validate good function entities', (t) ->
funks =
dealwithit: "nevermind"
splosion: "nevermind"
entities = [
{ entity: 'funk', name: 'splosion' },
{ entity: 'funk', name: 'dealwithit' },
]
ep = new EmojiProcessor('foo', funks, 'baz')
t.equal(ep.invalidFunkNames(entities).length, 0)
t.end()
test 'can validate bad function entities', (t) ->
funks =
dealwithit: "nevermind"
splosion: "nevermind"
entities = [
{ entity: 'funk', name: 'splosion' },
{ entity: 'funk', name: 'bad' },
{ entity: 'funk', name: 'dealwithit' },
]
ep = new EmojiProcessor('foo', funks, 'baz')
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'bad')
t.end()
test 'can validate good emoji names', (t) ->
emoji =
poop: "nevermind"
glasses: "nevermind"
entities = [
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'glasses' },
]
ep = new EmojiProcessor('foo', 'bar', 'baz')
t.equal(ep.invalidEmojiNames(entities, emoji).length, 0)
t.end()
test 'can validate bad emoji names', (t) ->
emoji =
poop: "nevermind"
glasses: "nevermind"
entities = [
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'glasses' },
{ entity: 'emoji', name: 'bad' },
]
ep = new EmojiProcessor('foo', 'bar', 'baz')
invalidNames = ep.invalidEmojiNames(entities, emoji)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'bad')
t.end()
test 'can add good macros', (t) ->
entities = [{ entity: 'funk', name: 'splosion' }]
ep = new EmojiProcessor('foo', {}, 'baz')
# isn't there before
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'splosion')
# add it
t.ok(ep.addMacro('splosion', (_) -> ))
# is there now
t.equal(ep.invalidFunkNames(entities).length, 0)
t.end()
test "can't add bad macros -- macros lacking a function", (t) ->
entities = [{ entity: 'funk', name: 'splosion' }]
ep = new EmojiProcessor('foo', {}, 'baz')
# isn't there before
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'splosion')
# add it - fails
t.notOk(ep.addMacro('splosion', 0))
# isn't there now
t.equal(ep.invalidFunkNames(entities).length, 1)
t.end()
test 'can reduce (tree into array)', (t) ->
ep = new EmojiProcessor({}, undefined, undefined)
parseTree = ep.parse(input1)
entities = ep.reduce(parseTree, [], (acc, tree) ->
acc.concat([
entity: tree.entity
name: tree.name
])
)
expected = [
{ entity: 'funk', name: 'splosion' },
{ entity: 'funk', name: 'dealwithit' },
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'kamina-glasses' }
]
t.deepEqual(entities, expected)
t.end()
verifySize = (t, container) ->
t.equal(container.constructor.name, "ImageContainer", "Verify size of ImageContainers only")
t.true(fs.existsSync(container.path), "the temp image #{container.path} should exist")
t.equal(container.size(), 43, 'we downloaded what we expected')
verifyFavico = (t, result, onComplete) ->
t.deepEqual(result.errorMessages, [])
t.equal(result.constructor.name, "ImageResult", "Verify favicos of ImageResults only")
verifySize(t, result.resultImage)
result.dimensions (err, dims) ->
t.fail(err, 'getting dimensions succeeds') if err
t.deepEqual(dims, {height: 1, width: 1})
result.normalDimension (err, dim) ->
t.fail(err, 'getting normal dimension succeeds') if err
t.equal(dim, 1, 'dimension is 1')
onComplete() if onComplete
# do end-to-end test
doe2e = (title, input, checkResult) ->
ctest title, (t) ->
ImageContainer.clearContainerTracker()
ep = new EmojiProcessor fakeEmojiStore, allMacros
ep.process input, (slackResp) ->
checkResult t, slackResp, ep, () ->
slackResp.cleanup()
t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
t.end()
doe2e "Can do an end-to-end test with unparseable str", "zzzzz", (t, slackResp, ep, onComplete) ->
t.equal([
"I couldn't parse `zzzzz` as macromoji:",
"```Error: Parse error on line 1:",
"zzzzz",
"-----^",
"Expecting '(', got 'EOF'```"
].join("\n"), slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad funk", "nope(:favico:)", (t, slackResp, ep, onComplete) ->
t.equal("I didn't understand some of `nope(:favico:)`:\n • Unknown function names: nope",slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad emoji", "identity(:pooop:)", (t, slackResp, ep, onComplete) ->
t.equal("I didn't understand some of `identity(:pooop:)`:\n • Unknown emoji names: pooop",slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad funk/emoji", "nope(x(:pooop:, :y:))", (t, slackResp, ep, onComplete) ->
t.equal([
"I didn't understand some of `nope(x(:pooop:, :y:))`:",
" • Unknown function names: nope, x",
" • Unknown emoji names: pooop, y"].join("\n"), slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with builtin emoji", "identity(:copyright:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity-copyright", slackResp.fileDesc)
t.equal(ep.lastWorkTree.normalArgs.length, 1)
t.equal(ep.lastWorkTree.normalArgs[0].constructor.name, "ImageResult")
# t.deepEqual(slackResp.imgResult.provenance(), [])
t.equal(slackResp.imgResult.allTempImages().length, 5)
onComplete()
doe2e "Can do an end-to-end test with good entities", "identity(:favico:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity-favico", slackResp.fileDesc)
#emojiResult = ep.lastWorkTree.resolvedArgs[0]
t.equal(ep.lastWorkTree.parseDescription, "identity(:favico:)")
t.equal(ep.lastWorkTree.args.length, 1)
favicoProvenance = ep.lastWorkTree.args[0].result.provenance()[0]
t.notEqual(slackResp.imgResult.provenance().indexOf(favicoProvenance), -1,
"provenance of downloaded image should be part of identity function provenance")
t.equal(slackResp.imgResult.allTempImages().length, 5)
#t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
#verifyFavico(t, emojiResult)
#verifyFavico(t, ep.workTree.result)
verifyFavico(t, slackResp.imgResult, onComplete) # same as prev line
doe2e "Can do an end-to-end test with nesting", "identity_gm(identity_gm(:favico:), :favico:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity_gm-identity_gm-favico-favico", slackResp.fileDesc)
#emojiResult = ep.lastWorkTree.resolvedArgs[0]
#t.deepEqual(slackResp.imgResult.provenance(), [])
t.equal(slackResp.imgResult.allTempImages().length, 21)
#t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
#verifyFavico(t, emojiResult)
#verifyFavico(t, ep.workTree.result)
verifyFavico(t, slackResp.imgResult, onComplete) # same as prev line
troot.end()
| 212084 | fs = require 'fs'
test = require 'tape'
ctest = require 'tape-catch'
sinon = require 'sinon'
EmojiProcessor = require '../src/emojiProcessor'
ImageContainer = require '../src/imageContainer'
ImageResult = require '../src/imageResult'
ImageWorker = require '../src/imageWorker'
EmojiStore = require '../src/emojiStore'
input1 = '(dealwithit(:poop:, :kamina-glasses:))splosion'
emojiFetchFn = (cb) ->
cb null,
favico: 'http://tinylittlelife.org/favicon.ico'
fakeEmojiStore = new EmojiStore(emojiFetchFn, 0)
allMacros = require '../src/defaultMacros'
test 'EmojiProcessor', (troot) ->
test 'parser exists', (t) ->
ep = new EmojiProcessor({}, undefined)
t.ok(ep.parser(), 'parser exists')
t.end()
test 'parser parses positive input', (t) ->
ep = new EmojiProcessor({}, undefined)
t.equal(ep.parseable(input1), true)
t.end()
test 'does not parse negative input', (t) ->
onErr = sinon.spy()
ep = new EmojiProcessor({}, undefined)
t.equal(ep.parseable(input1 + " crap"), false)
t.end()
test 'can reduce (tree into array)', (t) ->
ep = new EmojiProcessor({}, undefined)
parseTree = ep.parse(input1)
entities = ep.reduce parseTree, [], (acc, tree) ->
acc.concat([
entity: tree.entity
name: tree.name
])
expected = [
{ entity: 'funk', name: 'splosion' },
{ entity: 'funk', name: 'dealwithit' },
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'kamina-glasses' }
]
t.deepEqual(entities, expected)
t.end()
test 'understands positional arguments and initializes proper vars', (t) ->
ep = new EmojiProcessor('foo', 'bar')
t.equal(ep.emojiStore, 'foo')
t.equal(ep.macros, 'bar')
t.end()
test 'can validate good function entities', (t) ->
funks =
dealwithit: "nevermind"
splosion: "nevermind"
entities = [
{ entity: 'funk', name: '<NAME>' },
{ entity: 'funk', name: '<NAME>' },
]
ep = new EmojiProcessor('foo', funks, 'baz')
t.equal(ep.invalidFunkNames(entities).length, 0)
t.end()
test 'can validate bad function entities', (t) ->
funks =
dealwithit: "nevermind"
splosion: "nevermind"
entities = [
{ entity: 'funk', name: '<NAME>' },
{ entity: 'funk', name: 'bad' },
{ entity: 'funk', name: '<NAME>' },
]
ep = new EmojiProcessor('foo', funks, 'baz')
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'bad')
t.end()
test 'can validate good emoji names', (t) ->
emoji =
poop: "nevermind"
glasses: "nevermind"
entities = [
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: '<NAME>' },
]
ep = new EmojiProcessor('foo', 'bar', 'baz')
t.equal(ep.invalidEmojiNames(entities, emoji).length, 0)
t.end()
test 'can validate bad emoji names', (t) ->
emoji =
poop: "nevermind"
glasses: "nevermind"
entities = [
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'glasses' },
{ entity: 'emoji', name: 'bad' },
]
ep = new EmojiProcessor('foo', 'bar', 'baz')
invalidNames = ep.invalidEmojiNames(entities, emoji)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'bad')
t.end()
test 'can add good macros', (t) ->
entities = [{ entity: 'funk', name: '<NAME>' }]
ep = new EmojiProcessor('foo', {}, 'baz')
# isn't there before
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], '<NAME>')
# add it
t.ok(ep.addMacro('splosion', (_) -> ))
# is there now
t.equal(ep.invalidFunkNames(entities).length, 0)
t.end()
test "can't add bad macros -- macros lacking a function", (t) ->
entities = [{ entity: 'funk', name: '<NAME>' }]
ep = new EmojiProcessor('foo', {}, 'baz')
# isn't there before
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], '<NAME>')
# add it - fails
t.notOk(ep.addMacro('splosion', 0))
# isn't there now
t.equal(ep.invalidFunkNames(entities).length, 1)
t.end()
test 'can reduce (tree into array)', (t) ->
ep = new EmojiProcessor({}, undefined, undefined)
parseTree = ep.parse(input1)
entities = ep.reduce(parseTree, [], (acc, tree) ->
acc.concat([
entity: tree.entity
name: tree.name
])
)
expected = [
{ entity: 'funk', name: '<NAME>' },
{ entity: 'funk', name: '<NAME>' },
{ entity: 'emoji', name: '<NAME>' },
{ entity: 'emoji', name: '<NAME>' }
]
t.deepEqual(entities, expected)
t.end()
verifySize = (t, container) ->
t.equal(container.constructor.name, "ImageContainer", "Verify size of ImageContainers only")
t.true(fs.existsSync(container.path), "the temp image #{container.path} should exist")
t.equal(container.size(), 43, 'we downloaded what we expected')
verifyFavico = (t, result, onComplete) ->
t.deepEqual(result.errorMessages, [])
t.equal(result.constructor.name, "ImageResult", "Verify favicos of ImageResults only")
verifySize(t, result.resultImage)
result.dimensions (err, dims) ->
t.fail(err, 'getting dimensions succeeds') if err
t.deepEqual(dims, {height: 1, width: 1})
result.normalDimension (err, dim) ->
t.fail(err, 'getting normal dimension succeeds') if err
t.equal(dim, 1, 'dimension is 1')
onComplete() if onComplete
# do end-to-end test
doe2e = (title, input, checkResult) ->
ctest title, (t) ->
ImageContainer.clearContainerTracker()
ep = new EmojiProcessor fakeEmojiStore, allMacros
ep.process input, (slackResp) ->
checkResult t, slackResp, ep, () ->
slackResp.cleanup()
t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
t.end()
doe2e "Can do an end-to-end test with unparseable str", "zzzzz", (t, slackResp, ep, onComplete) ->
t.equal([
"I couldn't parse `zzzzz` as macromoji:",
"```Error: Parse error on line 1:",
"zzzzz",
"-----^",
"Expecting '(', got 'EOF'```"
].join("\n"), slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad funk", "nope(:favico:)", (t, slackResp, ep, onComplete) ->
t.equal("I didn't understand some of `nope(:favico:)`:\n • Unknown function names: nope",slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad emoji", "identity(:pooop:)", (t, slackResp, ep, onComplete) ->
t.equal("I didn't understand some of `identity(:pooop:)`:\n • Unknown emoji names: pooop",slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad funk/emoji", "nope(x(:pooop:, :y:))", (t, slackResp, ep, onComplete) ->
t.equal([
"I didn't understand some of `nope(x(:pooop:, :y:))`:",
" • Unknown function names: nope, x",
" • Unknown emoji names: pooop, y"].join("\n"), slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with builtin emoji", "identity(:copyright:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity-copyright", slackResp.fileDesc)
t.equal(ep.lastWorkTree.normalArgs.length, 1)
t.equal(ep.lastWorkTree.normalArgs[0].constructor.name, "ImageResult")
# t.deepEqual(slackResp.imgResult.provenance(), [])
t.equal(slackResp.imgResult.allTempImages().length, 5)
onComplete()
doe2e "Can do an end-to-end test with good entities", "identity(:favico:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity-favico", slackResp.fileDesc)
#emojiResult = ep.lastWorkTree.resolvedArgs[0]
t.equal(ep.lastWorkTree.parseDescription, "identity(:favico:)")
t.equal(ep.lastWorkTree.args.length, 1)
favicoProvenance = ep.lastWorkTree.args[0].result.provenance()[0]
t.notEqual(slackResp.imgResult.provenance().indexOf(favicoProvenance), -1,
"provenance of downloaded image should be part of identity function provenance")
t.equal(slackResp.imgResult.allTempImages().length, 5)
#t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
#verifyFavico(t, emojiResult)
#verifyFavico(t, ep.workTree.result)
verifyFavico(t, slackResp.imgResult, onComplete) # same as prev line
doe2e "Can do an end-to-end test with nesting", "identity_gm(identity_gm(:favico:), :favico:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity_gm-identity_gm-favico-favico", slackResp.fileDesc)
#emojiResult = ep.lastWorkTree.resolvedArgs[0]
#t.deepEqual(slackResp.imgResult.provenance(), [])
t.equal(slackResp.imgResult.allTempImages().length, 21)
#t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
#verifyFavico(t, emojiResult)
#verifyFavico(t, ep.workTree.result)
verifyFavico(t, slackResp.imgResult, onComplete) # same as prev line
troot.end()
| true | fs = require 'fs'
test = require 'tape'
ctest = require 'tape-catch'
sinon = require 'sinon'
EmojiProcessor = require '../src/emojiProcessor'
ImageContainer = require '../src/imageContainer'
ImageResult = require '../src/imageResult'
ImageWorker = require '../src/imageWorker'
EmojiStore = require '../src/emojiStore'
input1 = '(dealwithit(:poop:, :kamina-glasses:))splosion'
emojiFetchFn = (cb) ->
cb null,
favico: 'http://tinylittlelife.org/favicon.ico'
fakeEmojiStore = new EmojiStore(emojiFetchFn, 0)
allMacros = require '../src/defaultMacros'
test 'EmojiProcessor', (troot) ->
test 'parser exists', (t) ->
ep = new EmojiProcessor({}, undefined)
t.ok(ep.parser(), 'parser exists')
t.end()
test 'parser parses positive input', (t) ->
ep = new EmojiProcessor({}, undefined)
t.equal(ep.parseable(input1), true)
t.end()
test 'does not parse negative input', (t) ->
onErr = sinon.spy()
ep = new EmojiProcessor({}, undefined)
t.equal(ep.parseable(input1 + " crap"), false)
t.end()
test 'can reduce (tree into array)', (t) ->
ep = new EmojiProcessor({}, undefined)
parseTree = ep.parse(input1)
entities = ep.reduce parseTree, [], (acc, tree) ->
acc.concat([
entity: tree.entity
name: tree.name
])
expected = [
{ entity: 'funk', name: 'splosion' },
{ entity: 'funk', name: 'dealwithit' },
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'kamina-glasses' }
]
t.deepEqual(entities, expected)
t.end()
test 'understands positional arguments and initializes proper vars', (t) ->
ep = new EmojiProcessor('foo', 'bar')
t.equal(ep.emojiStore, 'foo')
t.equal(ep.macros, 'bar')
t.end()
test 'can validate good function entities', (t) ->
funks =
dealwithit: "nevermind"
splosion: "nevermind"
entities = [
{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' },
{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' },
]
ep = new EmojiProcessor('foo', funks, 'baz')
t.equal(ep.invalidFunkNames(entities).length, 0)
t.end()
test 'can validate bad function entities', (t) ->
funks =
dealwithit: "nevermind"
splosion: "nevermind"
entities = [
{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' },
{ entity: 'funk', name: 'bad' },
{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' },
]
ep = new EmojiProcessor('foo', funks, 'baz')
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'bad')
t.end()
test 'can validate good emoji names', (t) ->
emoji =
poop: "nevermind"
glasses: "nevermind"
entities = [
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'PI:NAME:<NAME>END_PI' },
]
ep = new EmojiProcessor('foo', 'bar', 'baz')
t.equal(ep.invalidEmojiNames(entities, emoji).length, 0)
t.end()
test 'can validate bad emoji names', (t) ->
emoji =
poop: "nevermind"
glasses: "nevermind"
entities = [
{ entity: 'emoji', name: 'poop' },
{ entity: 'emoji', name: 'glasses' },
{ entity: 'emoji', name: 'bad' },
]
ep = new EmojiProcessor('foo', 'bar', 'baz')
invalidNames = ep.invalidEmojiNames(entities, emoji)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'bad')
t.end()
test 'can add good macros', (t) ->
entities = [{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' }]
ep = new EmojiProcessor('foo', {}, 'baz')
# isn't there before
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'PI:NAME:<NAME>END_PI')
# add it
t.ok(ep.addMacro('splosion', (_) -> ))
# is there now
t.equal(ep.invalidFunkNames(entities).length, 0)
t.end()
test "can't add bad macros -- macros lacking a function", (t) ->
entities = [{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' }]
ep = new EmojiProcessor('foo', {}, 'baz')
# isn't there before
invalidNames = ep.invalidFunkNames(entities)
t.equal(invalidNames.length, 1)
t.equal(invalidNames[0], 'PI:NAME:<NAME>END_PI')
# add it - fails
t.notOk(ep.addMacro('splosion', 0))
# isn't there now
t.equal(ep.invalidFunkNames(entities).length, 1)
t.end()
test 'can reduce (tree into array)', (t) ->
ep = new EmojiProcessor({}, undefined, undefined)
parseTree = ep.parse(input1)
entities = ep.reduce(parseTree, [], (acc, tree) ->
acc.concat([
entity: tree.entity
name: tree.name
])
)
expected = [
{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' },
{ entity: 'funk', name: 'PI:NAME:<NAME>END_PI' },
{ entity: 'emoji', name: 'PI:NAME:<NAME>END_PI' },
{ entity: 'emoji', name: 'PI:NAME:<NAME>END_PI' }
]
t.deepEqual(entities, expected)
t.end()
verifySize = (t, container) ->
t.equal(container.constructor.name, "ImageContainer", "Verify size of ImageContainers only")
t.true(fs.existsSync(container.path), "the temp image #{container.path} should exist")
t.equal(container.size(), 43, 'we downloaded what we expected')
verifyFavico = (t, result, onComplete) ->
t.deepEqual(result.errorMessages, [])
t.equal(result.constructor.name, "ImageResult", "Verify favicos of ImageResults only")
verifySize(t, result.resultImage)
result.dimensions (err, dims) ->
t.fail(err, 'getting dimensions succeeds') if err
t.deepEqual(dims, {height: 1, width: 1})
result.normalDimension (err, dim) ->
t.fail(err, 'getting normal dimension succeeds') if err
t.equal(dim, 1, 'dimension is 1')
onComplete() if onComplete
# do end-to-end test
doe2e = (title, input, checkResult) ->
ctest title, (t) ->
ImageContainer.clearContainerTracker()
ep = new EmojiProcessor fakeEmojiStore, allMacros
ep.process input, (slackResp) ->
checkResult t, slackResp, ep, () ->
slackResp.cleanup()
t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
t.end()
doe2e "Can do an end-to-end test with unparseable str", "zzzzz", (t, slackResp, ep, onComplete) ->
t.equal([
"I couldn't parse `zzzzz` as macromoji:",
"```Error: Parse error on line 1:",
"zzzzz",
"-----^",
"Expecting '(', got 'EOF'```"
].join("\n"), slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad funk", "nope(:favico:)", (t, slackResp, ep, onComplete) ->
t.equal("I didn't understand some of `nope(:favico:)`:\n • Unknown function names: nope",slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad emoji", "identity(:pooop:)", (t, slackResp, ep, onComplete) ->
t.equal("I didn't understand some of `identity(:pooop:)`:\n • Unknown emoji names: pooop",slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with bad funk/emoji", "nope(x(:pooop:, :y:))", (t, slackResp, ep, onComplete) ->
t.equal([
"I didn't understand some of `nope(x(:pooop:, :y:))`:",
" • Unknown function names: nope, x",
" • Unknown emoji names: pooop, y"].join("\n"), slackResp.message)
onComplete()
doe2e "Can do an end-to-end test with builtin emoji", "identity(:copyright:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity-copyright", slackResp.fileDesc)
t.equal(ep.lastWorkTree.normalArgs.length, 1)
t.equal(ep.lastWorkTree.normalArgs[0].constructor.name, "ImageResult")
# t.deepEqual(slackResp.imgResult.provenance(), [])
t.equal(slackResp.imgResult.allTempImages().length, 5)
onComplete()
doe2e "Can do an end-to-end test with good entities", "identity(:favico:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity-favico", slackResp.fileDesc)
#emojiResult = ep.lastWorkTree.resolvedArgs[0]
t.equal(ep.lastWorkTree.parseDescription, "identity(:favico:)")
t.equal(ep.lastWorkTree.args.length, 1)
favicoProvenance = ep.lastWorkTree.args[0].result.provenance()[0]
t.notEqual(slackResp.imgResult.provenance().indexOf(favicoProvenance), -1,
"provenance of downloaded image should be part of identity function provenance")
t.equal(slackResp.imgResult.allTempImages().length, 5)
#t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
#verifyFavico(t, emojiResult)
#verifyFavico(t, ep.workTree.result)
verifyFavico(t, slackResp.imgResult, onComplete) # same as prev line
doe2e "Can do an end-to-end test with nesting", "identity_gm(identity_gm(:favico:), :favico:)", (t, slackResp, ep, onComplete) ->
t.equal(slackResp.message, null)
t.true(slackResp.imgResult)
t.equal(slackResp.imgResult.constructor.name, "ImageResult")
t.equal("identity_gm-identity_gm-favico-favico", slackResp.fileDesc)
#emojiResult = ep.lastWorkTree.resolvedArgs[0]
#t.deepEqual(slackResp.imgResult.provenance(), [])
t.equal(slackResp.imgResult.allTempImages().length, 21)
#t.deepEqual(value for own _, value of ImageContainer.activeContainers(), [])
#verifyFavico(t, emojiResult)
#verifyFavico(t, ep.workTree.result)
verifyFavico(t, slackResp.imgResult, onComplete) # same as prev line
troot.end()
|
[
{
"context": "n 1.0.0\n@file DateField.js\n@author Welington Sampaio\n@contact http://jokerjs.zaez.net/contato\n\n@co",
"end": 142,
"score": 0.9998875856399536,
"start": 125,
"tag": "NAME",
"value": "Welington Sampaio"
}
] | vendor/assets/javascripts/joker/DateField.coffee | zaeznet/joker-rails | 0 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file DateField.js
@author Welington Sampaio
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2014 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
class Joker.DateField extends Joker.Core
constructor: (config={})->
super
@settings = @libSupport.extend true, new Object,
@accessor('defaultSettings'),
{
monthsFull: Joker.I18n.translate('date.month_names').slice(1,Joker.I18n.translate('date.month_names').length)
monthsShort: Joker.I18n.translate('date.abbr_month_names').slice(1,Joker.I18n.translate('date.abbr_month_names').length)
weekdaysFull: Joker.I18n.translate('date.day_names')
weekdaysShort: Joker.I18n.translate('date.abbr_day_names')
today: Joker.I18n.translate('date_field.today')
clear: Joker.I18n.translate('date_field.clear')
format: Joker.I18n.translate('date_field.format')
},
config
@debug "Inicializando o DateField", @objectId
@setEvents()
setDateField: (e)->
el = @libSupport e.currentTarget
settings = @libSupport.extend true, new Object, @settings, el.data('dateField')
el.pickadate settings
console.log el
el.attr 'name', ''
setEvents: ->
@libSupport( document ).on( 'focus', '.date-field', @libSupport.proxy( @setDateField, @ ))
@debugPrefix: "Joker_DateField"
@className : "Joker_DateField"
@defaultSettings:
# translations names
monthsFull: undefined
monthsShort: undefined
weekdaysFull: undefined
weekdaysShort: undefined
# Buttons
today: undefined
clear: undefined
# Formats
format: undefined
formatSubmit: 'yyyy-mm-dd'
# Editable input
editable: undefined
# Dropdown selectors
selectYears: undefined
selectMonths: undefined
# First day of the week
firstDay: undefined
# Date limits
min: undefined
max: undefined
# Disable dates
disable: undefined
# Root container
container: undefined
hiddenSuffix: ''
###
@type [Joker.DateField]
###
@instance : undefined
###
Retorna a variavel unica para a instacia do objeto
@returns [Joker.DateField]
###
@getInstance: ->
Joker.DateField.instance = new Joker.DateField() unless Joker.DateField.instance?
Joker.DateField.instance | 107072 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file DateField.js
@author <NAME>
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2014 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
class Joker.DateField extends Joker.Core
constructor: (config={})->
super
@settings = @libSupport.extend true, new Object,
@accessor('defaultSettings'),
{
monthsFull: Joker.I18n.translate('date.month_names').slice(1,Joker.I18n.translate('date.month_names').length)
monthsShort: Joker.I18n.translate('date.abbr_month_names').slice(1,Joker.I18n.translate('date.abbr_month_names').length)
weekdaysFull: Joker.I18n.translate('date.day_names')
weekdaysShort: Joker.I18n.translate('date.abbr_day_names')
today: Joker.I18n.translate('date_field.today')
clear: Joker.I18n.translate('date_field.clear')
format: Joker.I18n.translate('date_field.format')
},
config
@debug "Inicializando o DateField", @objectId
@setEvents()
setDateField: (e)->
el = @libSupport e.currentTarget
settings = @libSupport.extend true, new Object, @settings, el.data('dateField')
el.pickadate settings
console.log el
el.attr 'name', ''
setEvents: ->
@libSupport( document ).on( 'focus', '.date-field', @libSupport.proxy( @setDateField, @ ))
@debugPrefix: "Joker_DateField"
@className : "Joker_DateField"
@defaultSettings:
# translations names
monthsFull: undefined
monthsShort: undefined
weekdaysFull: undefined
weekdaysShort: undefined
# Buttons
today: undefined
clear: undefined
# Formats
format: undefined
formatSubmit: 'yyyy-mm-dd'
# Editable input
editable: undefined
# Dropdown selectors
selectYears: undefined
selectMonths: undefined
# First day of the week
firstDay: undefined
# Date limits
min: undefined
max: undefined
# Disable dates
disable: undefined
# Root container
container: undefined
hiddenSuffix: ''
###
@type [Joker.DateField]
###
@instance : undefined
###
Retorna a variavel unica para a instacia do objeto
@returns [Joker.DateField]
###
@getInstance: ->
Joker.DateField.instance = new Joker.DateField() unless Joker.DateField.instance?
Joker.DateField.instance | true | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file DateField.js
@author PI:NAME:<NAME>END_PI
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2014 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
class Joker.DateField extends Joker.Core
constructor: (config={})->
super
@settings = @libSupport.extend true, new Object,
@accessor('defaultSettings'),
{
monthsFull: Joker.I18n.translate('date.month_names').slice(1,Joker.I18n.translate('date.month_names').length)
monthsShort: Joker.I18n.translate('date.abbr_month_names').slice(1,Joker.I18n.translate('date.abbr_month_names').length)
weekdaysFull: Joker.I18n.translate('date.day_names')
weekdaysShort: Joker.I18n.translate('date.abbr_day_names')
today: Joker.I18n.translate('date_field.today')
clear: Joker.I18n.translate('date_field.clear')
format: Joker.I18n.translate('date_field.format')
},
config
@debug "Inicializando o DateField", @objectId
@setEvents()
setDateField: (e)->
el = @libSupport e.currentTarget
settings = @libSupport.extend true, new Object, @settings, el.data('dateField')
el.pickadate settings
console.log el
el.attr 'name', ''
setEvents: ->
@libSupport( document ).on( 'focus', '.date-field', @libSupport.proxy( @setDateField, @ ))
@debugPrefix: "Joker_DateField"
@className : "Joker_DateField"
@defaultSettings:
# translations names
monthsFull: undefined
monthsShort: undefined
weekdaysFull: undefined
weekdaysShort: undefined
# Buttons
today: undefined
clear: undefined
# Formats
format: undefined
formatSubmit: 'yyyy-mm-dd'
# Editable input
editable: undefined
# Dropdown selectors
selectYears: undefined
selectMonths: undefined
# First day of the week
firstDay: undefined
# Date limits
min: undefined
max: undefined
# Disable dates
disable: undefined
# Root container
container: undefined
hiddenSuffix: ''
###
@type [Joker.DateField]
###
@instance : undefined
###
Retorna a variavel unica para a instacia do objeto
@returns [Joker.DateField]
###
@getInstance: ->
Joker.DateField.instance = new Joker.DateField() unless Joker.DateField.instance?
Joker.DateField.instance |
[
{
"context": " do ( module, method_name ) =>\n rpc_key = \"^#{addon.aoid}/#{method_name}\"\n R.push rpc_key\n ### TAINT in upcom",
"end": 3093,
"score": 0.9324328899383545,
"start": 3062,
"tag": "KEY",
"value": "\"^#{addon.aoid}/#{method_name}\""
}
] | dev/intershop/src/cli.coffee | loveencounterflow/hengist | 0 |
'use strict'
t0 = process.hrtime.bigint()
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'HENGIST/DEV/INTERSHOP/INTERSHOP-CLI-NG'
debug = CND.get_logger 'debug', badge
debug '^76483-1^', Date.now() / 1000
alert = CND.get_logger 'alert', badge
whisper = CND.get_logger 'whisper', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
info = CND.get_logger 'info', badge
echo = CND.echo.bind CND
#...........................................................................................................
types = ( require 'intershop' ).types
{ isa
validate
cast
type_of } = types.export()
CP = require 'child_process'
defer = setImmediate
debug '^76483-2^', Date.now() / 1000
#-----------------------------------------------------------------------------------------------------------
@serve = ( project_path = null ) ->
PATH = require 'path'
INTERSHOP = require 'intershop/lib/intershop'
RPC = require '../../../apps/intershop-rpc'
project_path ?= PATH.resolve PATH.join __dirname, '../../../../hengist'
process.chdir project_path
shop = INTERSHOP.new_intershop project_path
### TAINT in the future `db`, `rpc` will be delivered with `new_intershop()` ###
# shop.db = require '../../../apps/intershop/intershop_modules/db'
shop.db = require 'intershop/lib/db'
shop.rpc = await RPC.create { show_counts: true, count_interval: 100, logging: true, }
#.........................................................................................................
rpc_keys = []
rpc_keys = [ rpc_keys..., ( await @_contract_registered_rpc_methods shop )..., ]
rpc_keys = [ rpc_keys..., ( await @_contract_demo_rpc_methods shop )..., ]
whisper '-'.repeat 108
urge "^4576^ registered RPC keys:"
info "^4576^ #{rpc_key}" for rpc_key in rpc_keys
whisper '-'.repeat 108
#.........................................................................................................
return shop
#-----------------------------------------------------------------------------------------------------------
@_contract_registered_rpc_methods = ( shop ) ->
R = []
sql = "select aoid, path from ADDONS.files where target = 'rpc' order by aoid, path;"
for addon from await shop.db.query [ sql, ]
module = require addon.path
method_names = ( Object.keys module ).sort()
for method_name in method_names
do ( module, method_name ) =>
rpc_key = "^#{addon.aoid}/#{method_name}"
R.push rpc_key
### TAINT in upcoming intershop-rpc version, all calls must pass a single list with arguments
to be applied to the contractor; this will then be done in `shop.rpc.contract(). For the
time being, we're applying arguments right here: ###
shop.rpc.contract rpc_key, ( d ) ->
unless ( type = type_of d.$value ) is 'list'
throw new Error "^intershop/cli@3376^ in RPC call to #{rpc_key}, expected a list for d.$value, got a #{type}"
module[ method_name ] d.$value...
return null
return R
#-----------------------------------------------------------------------------------------------------------
@_contract_demo_rpc_methods = ( shop ) ->
IX = require '../../../apps/intertext'
M3 = require '../../../apps/mojikura3-model/intershop_modules/rpc'
R = []
#.........................................................................................................
hyphenate = ( text ) ->
validate.text text
return IX.HYPH.hyphenate text
#.........................................................................................................
slabjoints_from_text = ( text ) ->
validate.text text
return IX.SLABS.slabjoints_from_text text
#.........................................................................................................
contract = ( key, method ) =>
shop.rpc.contract key, method
R.push key
return null
#.........................................................................................................
contract '^hyphenate', ( d ) -> hyphenate d.$value
contract '^slabjoints_from_text', ( d ) -> slabjoints_from_text d.$value
contract '^shyphenate', ( d ) -> slabjoints_from_text hyphenate d.$value
return R
#-----------------------------------------------------------------------------------------------------------
@new_intershop_runner = ( project_path ) ->
INTERSHOP = require 'intershop/lib/intershop'
return INTERSHOP.new_intershop project_path
#-----------------------------------------------------------------------------------------------------------
@_prepare_psql_commandline = ( me ) ->
cwd = me.get 'intershop/host/path'
db_name = me.get 'intershop/db/name'
db_user = me.get 'intershop/db/user'
return { cwd, db_user, db_name, }
#-----------------------------------------------------------------------------------------------------------
@psql_run = ( me, settings ) -> new Promise ( resolve, reject ) =>
cmd = @_prepare_psql_commandline me
parameters = [ '-U', cmd.db_user, '-d', cmd.db_name, settings.verdict.argv..., ]
whisper '^psql_run@@3367^', "psql #{CND.shellescape parameters}"
settings =
cwd: cmd.cwd
shell: false
stdio: [ 'inherit', 'inherit', 'inherit', ]
cp = CP.spawn 'psql', parameters, settings
cp.on 'close', ( code ) ->
return resolve 0 if code is 0
reject new Error "^psql_run_file@34479^ processs exited with code #{code}"
cp.on 'error', ( error ) -> reject error
return null
#-----------------------------------------------------------------------------------------------------------
@nodexh_run_file = ( project_path, file_path ) -> new Promise ( resolve, reject ) =>
parameters = [ file_path, ]
whisper '^psql_run@@3367^', "psql #{parameters.join ' '}"
settings =
cwd: project_path
shell: false
stdio: [ 'inherit', 'inherit', 'inherit', ]
cp = CP.spawn 'nodexh', parameters, settings
cp.on 'close', ( code ) ->
return resolve 0 if code is 0
reject new Error "^nodexh_run_file@34479^ processs exited with code #{code}"
cp.on 'error', ( error ) -> reject error
return null
#-----------------------------------------------------------------------------------------------------------
@cli = ->
# shop = await @serve()
await @_cli()
# await shop.rpc.stop()
return null
#-----------------------------------------------------------------------------------------------------------
@_cli_get_project_path = ( d ) -> d.verdict.cd ? process.cwd()
#-----------------------------------------------------------------------------------------------------------
@_cli = ->
debug '^76483-3^', Date.now() / 1000
MIXA = require '../../../apps/mixa'
debug '^76483-4^', Date.now() / 1000
#.........................................................................................................
# program.action ( { logger, } ) => logger.info "Hello, world!"
#.........................................................................................................
jobdef =
# .name 'intershop'
#.......................................................................................................
commands:
'start-rpc-server':
description: "start RPC server (to be accessed from psql scripts)"
allow_extra: true
runner: ( d ) => new Promise ( done ) =>
project_path = @_cli_get_project_path d
shop = await @serve project_path
#.....................................................................................................
'psql':
description: "run psql"
allow_extra: true
runner: ( d ) => new Promise ( done ) =>
project_path = @_cli_get_project_path d
shop = await @serve project_path
### TAINT ###
info "^5564^ d.verdict: #{rpr d.verdict}"
info "^5565^ project_path: #{rpr project_path}"
# debug '^2223^', rpr command
# debug '^2223^', rpr project_path
me = @new_intershop_runner project_path
# info "^5566^ running psql with #{rpr { file: d.file, command: d.command, }}"
await @psql_run me, d
await shop.rpc.stop()
done()
return null
#.....................................................................................................
'nodexh':
description: "run nodexh"
allow_extra: true
runner: MIXA.runners.execSync
#.....................................................................................................
'node':
description: "run node"
allow_extra: true
runner: MIXA.runners.execSync
#.........................................................................................................
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
debug '^33344^', MIXA.parse jobdef, process.argv
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
R = await MIXA.run jobdef, process.argv
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
return R
# #-----------------------------------------------------------------------------------------------------------
# @demo = ->
# rpc = await @serve()
# # T.eq ( await DB.query_single [ "select IPC.rpc( $1, $2 );", '^add-42', '{"x":1000}' ] ), 1042
# await @psql_run_file '/home/flow/jzr/interplot', 'db/080-intertext.sql'
# await @psql_run_file '/home/flow/jzr/interplot', 'db/100-harfbuzz.sql'
# await @psql_run_file '/home/flow/jzr/interplot', 'db/tests/080-intertext.tests.sql'
# debug '^3334^', process.argv
# info rpc.counts
# await rpc.stop()
# return null
#-----------------------------------------------------------------------------------------------------------
@demo_intershop_object = ->
PATH = require 'path'
project_path = PATH.resolve PATH.join __dirname, '../../../../hengist'
project_path = PATH.resolve PATH.join __dirname, '../../../../interplot'
INTERSHOP = require 'intershop/lib/intershop'
shop = INTERSHOP.new_intershop project_path
keys = ( k for k of shop.settings ).sort()
for key in keys
continue if key.startsWith 'os/'
setting = shop.settings[ key ]
echo ( CND.gold key.padEnd 42 ), ( CND.lime setting.value )
return null
#-----------------------------------------------------------------------------------------------------------
@demo_query_addons = ->
PATH = require 'path'
project_path = PATH.resolve PATH.join __dirname, '../../../../hengist'
INTERSHOP = require 'intershop/lib/intershop'
shop = INTERSHOP.new_intershop project_path
### TAINT in the future `db` will be delivered with `new_intershop()` ###
shop.db = require 'intershop/lib/db'
RPC = require '../../../apps/intershop-rpc'
rpc = await RPC.create { show_counts: true, count_interval: 100, logging: true, }
debug ( k for k of shop.db ).sort()
# for addon from await shop.db.query [ "select * from ADDONS.addons;", ]
# info addon.aoid
# for file from await shop.db.query [ "select * from ADDONS.files where aoid = $1;", addon.aoid, ]
# urge ' ', ( CND.blue file.target ), ( CND.yellow file.path )
sql = "select * from ADDONS.files where target = 'rpc' order by aoid;"
for addon from await shop.db.query [ sql, ]
module = require addon.path
for method_name of module
do ( module, method_name ) =>
rpc_name = "^#{addon.aoid}/#{method_name}"
debug '^3334^', rpc_name
rpc.contract rpc_name, ( d ) -> module[ method_name ] d.$value
return null
return null
############################################################################################################
if module is require.main then do =>
# await @demo()
await @cli()
# await @demo_query_addons()
# @demo_intershop_object()
| 169050 |
'use strict'
t0 = process.hrtime.bigint()
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'HENGIST/DEV/INTERSHOP/INTERSHOP-CLI-NG'
debug = CND.get_logger 'debug', badge
debug '^76483-1^', Date.now() / 1000
alert = CND.get_logger 'alert', badge
whisper = CND.get_logger 'whisper', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
info = CND.get_logger 'info', badge
echo = CND.echo.bind CND
#...........................................................................................................
types = ( require 'intershop' ).types
{ isa
validate
cast
type_of } = types.export()
CP = require 'child_process'
defer = setImmediate
debug '^76483-2^', Date.now() / 1000
#-----------------------------------------------------------------------------------------------------------
@serve = ( project_path = null ) ->
PATH = require 'path'
INTERSHOP = require 'intershop/lib/intershop'
RPC = require '../../../apps/intershop-rpc'
project_path ?= PATH.resolve PATH.join __dirname, '../../../../hengist'
process.chdir project_path
shop = INTERSHOP.new_intershop project_path
### TAINT in the future `db`, `rpc` will be delivered with `new_intershop()` ###
# shop.db = require '../../../apps/intershop/intershop_modules/db'
shop.db = require 'intershop/lib/db'
shop.rpc = await RPC.create { show_counts: true, count_interval: 100, logging: true, }
#.........................................................................................................
rpc_keys = []
rpc_keys = [ rpc_keys..., ( await @_contract_registered_rpc_methods shop )..., ]
rpc_keys = [ rpc_keys..., ( await @_contract_demo_rpc_methods shop )..., ]
whisper '-'.repeat 108
urge "^4576^ registered RPC keys:"
info "^4576^ #{rpc_key}" for rpc_key in rpc_keys
whisper '-'.repeat 108
#.........................................................................................................
return shop
#-----------------------------------------------------------------------------------------------------------
@_contract_registered_rpc_methods = ( shop ) ->
R = []
sql = "select aoid, path from ADDONS.files where target = 'rpc' order by aoid, path;"
for addon from await shop.db.query [ sql, ]
module = require addon.path
method_names = ( Object.keys module ).sort()
for method_name in method_names
do ( module, method_name ) =>
rpc_key = <KEY>
R.push rpc_key
### TAINT in upcoming intershop-rpc version, all calls must pass a single list with arguments
to be applied to the contractor; this will then be done in `shop.rpc.contract(). For the
time being, we're applying arguments right here: ###
shop.rpc.contract rpc_key, ( d ) ->
unless ( type = type_of d.$value ) is 'list'
throw new Error "^intershop/cli@3376^ in RPC call to #{rpc_key}, expected a list for d.$value, got a #{type}"
module[ method_name ] d.$value...
return null
return R
#-----------------------------------------------------------------------------------------------------------
@_contract_demo_rpc_methods = ( shop ) ->
IX = require '../../../apps/intertext'
M3 = require '../../../apps/mojikura3-model/intershop_modules/rpc'
R = []
#.........................................................................................................
hyphenate = ( text ) ->
validate.text text
return IX.HYPH.hyphenate text
#.........................................................................................................
slabjoints_from_text = ( text ) ->
validate.text text
return IX.SLABS.slabjoints_from_text text
#.........................................................................................................
contract = ( key, method ) =>
shop.rpc.contract key, method
R.push key
return null
#.........................................................................................................
contract '^hyphenate', ( d ) -> hyphenate d.$value
contract '^slabjoints_from_text', ( d ) -> slabjoints_from_text d.$value
contract '^shyphenate', ( d ) -> slabjoints_from_text hyphenate d.$value
return R
#-----------------------------------------------------------------------------------------------------------
@new_intershop_runner = ( project_path ) ->
INTERSHOP = require 'intershop/lib/intershop'
return INTERSHOP.new_intershop project_path
#-----------------------------------------------------------------------------------------------------------
@_prepare_psql_commandline = ( me ) ->
cwd = me.get 'intershop/host/path'
db_name = me.get 'intershop/db/name'
db_user = me.get 'intershop/db/user'
return { cwd, db_user, db_name, }
#-----------------------------------------------------------------------------------------------------------
@psql_run = ( me, settings ) -> new Promise ( resolve, reject ) =>
cmd = @_prepare_psql_commandline me
parameters = [ '-U', cmd.db_user, '-d', cmd.db_name, settings.verdict.argv..., ]
whisper '^psql_run@@3367^', "psql #{CND.shellescape parameters}"
settings =
cwd: cmd.cwd
shell: false
stdio: [ 'inherit', 'inherit', 'inherit', ]
cp = CP.spawn 'psql', parameters, settings
cp.on 'close', ( code ) ->
return resolve 0 if code is 0
reject new Error "^psql_run_file@34479^ processs exited with code #{code}"
cp.on 'error', ( error ) -> reject error
return null
#-----------------------------------------------------------------------------------------------------------
@nodexh_run_file = ( project_path, file_path ) -> new Promise ( resolve, reject ) =>
parameters = [ file_path, ]
whisper '^psql_run@@3367^', "psql #{parameters.join ' '}"
settings =
cwd: project_path
shell: false
stdio: [ 'inherit', 'inherit', 'inherit', ]
cp = CP.spawn 'nodexh', parameters, settings
cp.on 'close', ( code ) ->
return resolve 0 if code is 0
reject new Error "^nodexh_run_file@34479^ processs exited with code #{code}"
cp.on 'error', ( error ) -> reject error
return null
#-----------------------------------------------------------------------------------------------------------
@cli = ->
# shop = await @serve()
await @_cli()
# await shop.rpc.stop()
return null
#-----------------------------------------------------------------------------------------------------------
@_cli_get_project_path = ( d ) -> d.verdict.cd ? process.cwd()
#-----------------------------------------------------------------------------------------------------------
@_cli = ->
debug '^76483-3^', Date.now() / 1000
MIXA = require '../../../apps/mixa'
debug '^76483-4^', Date.now() / 1000
#.........................................................................................................
# program.action ( { logger, } ) => logger.info "Hello, world!"
#.........................................................................................................
jobdef =
# .name 'intershop'
#.......................................................................................................
commands:
'start-rpc-server':
description: "start RPC server (to be accessed from psql scripts)"
allow_extra: true
runner: ( d ) => new Promise ( done ) =>
project_path = @_cli_get_project_path d
shop = await @serve project_path
#.....................................................................................................
'psql':
description: "run psql"
allow_extra: true
runner: ( d ) => new Promise ( done ) =>
project_path = @_cli_get_project_path d
shop = await @serve project_path
### TAINT ###
info "^5564^ d.verdict: #{rpr d.verdict}"
info "^5565^ project_path: #{rpr project_path}"
# debug '^2223^', rpr command
# debug '^2223^', rpr project_path
me = @new_intershop_runner project_path
# info "^5566^ running psql with #{rpr { file: d.file, command: d.command, }}"
await @psql_run me, d
await shop.rpc.stop()
done()
return null
#.....................................................................................................
'nodexh':
description: "run nodexh"
allow_extra: true
runner: MIXA.runners.execSync
#.....................................................................................................
'node':
description: "run node"
allow_extra: true
runner: MIXA.runners.execSync
#.........................................................................................................
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
debug '^33344^', MIXA.parse jobdef, process.argv
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
R = await MIXA.run jobdef, process.argv
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
return R
# #-----------------------------------------------------------------------------------------------------------
# @demo = ->
# rpc = await @serve()
# # T.eq ( await DB.query_single [ "select IPC.rpc( $1, $2 );", '^add-42', '{"x":1000}' ] ), 1042
# await @psql_run_file '/home/flow/jzr/interplot', 'db/080-intertext.sql'
# await @psql_run_file '/home/flow/jzr/interplot', 'db/100-harfbuzz.sql'
# await @psql_run_file '/home/flow/jzr/interplot', 'db/tests/080-intertext.tests.sql'
# debug '^3334^', process.argv
# info rpc.counts
# await rpc.stop()
# return null
#-----------------------------------------------------------------------------------------------------------
@demo_intershop_object = ->
PATH = require 'path'
project_path = PATH.resolve PATH.join __dirname, '../../../../hengist'
project_path = PATH.resolve PATH.join __dirname, '../../../../interplot'
INTERSHOP = require 'intershop/lib/intershop'
shop = INTERSHOP.new_intershop project_path
keys = ( k for k of shop.settings ).sort()
for key in keys
continue if key.startsWith 'os/'
setting = shop.settings[ key ]
echo ( CND.gold key.padEnd 42 ), ( CND.lime setting.value )
return null
#-----------------------------------------------------------------------------------------------------------
@demo_query_addons = ->
PATH = require 'path'
project_path = PATH.resolve PATH.join __dirname, '../../../../hengist'
INTERSHOP = require 'intershop/lib/intershop'
shop = INTERSHOP.new_intershop project_path
### TAINT in the future `db` will be delivered with `new_intershop()` ###
shop.db = require 'intershop/lib/db'
RPC = require '../../../apps/intershop-rpc'
rpc = await RPC.create { show_counts: true, count_interval: 100, logging: true, }
debug ( k for k of shop.db ).sort()
# for addon from await shop.db.query [ "select * from ADDONS.addons;", ]
# info addon.aoid
# for file from await shop.db.query [ "select * from ADDONS.files where aoid = $1;", addon.aoid, ]
# urge ' ', ( CND.blue file.target ), ( CND.yellow file.path )
sql = "select * from ADDONS.files where target = 'rpc' order by aoid;"
for addon from await shop.db.query [ sql, ]
module = require addon.path
for method_name of module
do ( module, method_name ) =>
rpc_name = "^#{addon.aoid}/#{method_name}"
debug '^3334^', rpc_name
rpc.contract rpc_name, ( d ) -> module[ method_name ] d.$value
return null
return null
############################################################################################################
if module is require.main then do =>
# await @demo()
await @cli()
# await @demo_query_addons()
# @demo_intershop_object()
| true |
'use strict'
t0 = process.hrtime.bigint()
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'HENGIST/DEV/INTERSHOP/INTERSHOP-CLI-NG'
debug = CND.get_logger 'debug', badge
debug '^76483-1^', Date.now() / 1000
alert = CND.get_logger 'alert', badge
whisper = CND.get_logger 'whisper', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
info = CND.get_logger 'info', badge
echo = CND.echo.bind CND
#...........................................................................................................
types = ( require 'intershop' ).types
{ isa
validate
cast
type_of } = types.export()
CP = require 'child_process'
defer = setImmediate
debug '^76483-2^', Date.now() / 1000
#-----------------------------------------------------------------------------------------------------------
@serve = ( project_path = null ) ->
PATH = require 'path'
INTERSHOP = require 'intershop/lib/intershop'
RPC = require '../../../apps/intershop-rpc'
project_path ?= PATH.resolve PATH.join __dirname, '../../../../hengist'
process.chdir project_path
shop = INTERSHOP.new_intershop project_path
### TAINT in the future `db`, `rpc` will be delivered with `new_intershop()` ###
# shop.db = require '../../../apps/intershop/intershop_modules/db'
shop.db = require 'intershop/lib/db'
shop.rpc = await RPC.create { show_counts: true, count_interval: 100, logging: true, }
#.........................................................................................................
rpc_keys = []
rpc_keys = [ rpc_keys..., ( await @_contract_registered_rpc_methods shop )..., ]
rpc_keys = [ rpc_keys..., ( await @_contract_demo_rpc_methods shop )..., ]
whisper '-'.repeat 108
urge "^4576^ registered RPC keys:"
info "^4576^ #{rpc_key}" for rpc_key in rpc_keys
whisper '-'.repeat 108
#.........................................................................................................
return shop
#-----------------------------------------------------------------------------------------------------------
@_contract_registered_rpc_methods = ( shop ) ->
R = []
sql = "select aoid, path from ADDONS.files where target = 'rpc' order by aoid, path;"
for addon from await shop.db.query [ sql, ]
module = require addon.path
method_names = ( Object.keys module ).sort()
for method_name in method_names
do ( module, method_name ) =>
rpc_key = PI:KEY:<KEY>END_PI
R.push rpc_key
### TAINT in upcoming intershop-rpc version, all calls must pass a single list with arguments
to be applied to the contractor; this will then be done in `shop.rpc.contract(). For the
time being, we're applying arguments right here: ###
shop.rpc.contract rpc_key, ( d ) ->
unless ( type = type_of d.$value ) is 'list'
throw new Error "^intershop/cli@3376^ in RPC call to #{rpc_key}, expected a list for d.$value, got a #{type}"
module[ method_name ] d.$value...
return null
return R
#-----------------------------------------------------------------------------------------------------------
@_contract_demo_rpc_methods = ( shop ) ->
IX = require '../../../apps/intertext'
M3 = require '../../../apps/mojikura3-model/intershop_modules/rpc'
R = []
#.........................................................................................................
hyphenate = ( text ) ->
validate.text text
return IX.HYPH.hyphenate text
#.........................................................................................................
slabjoints_from_text = ( text ) ->
validate.text text
return IX.SLABS.slabjoints_from_text text
#.........................................................................................................
contract = ( key, method ) =>
shop.rpc.contract key, method
R.push key
return null
#.........................................................................................................
contract '^hyphenate', ( d ) -> hyphenate d.$value
contract '^slabjoints_from_text', ( d ) -> slabjoints_from_text d.$value
contract '^shyphenate', ( d ) -> slabjoints_from_text hyphenate d.$value
return R
#-----------------------------------------------------------------------------------------------------------
@new_intershop_runner = ( project_path ) ->
INTERSHOP = require 'intershop/lib/intershop'
return INTERSHOP.new_intershop project_path
#-----------------------------------------------------------------------------------------------------------
@_prepare_psql_commandline = ( me ) ->
cwd = me.get 'intershop/host/path'
db_name = me.get 'intershop/db/name'
db_user = me.get 'intershop/db/user'
return { cwd, db_user, db_name, }
#-----------------------------------------------------------------------------------------------------------
@psql_run = ( me, settings ) -> new Promise ( resolve, reject ) =>
cmd = @_prepare_psql_commandline me
parameters = [ '-U', cmd.db_user, '-d', cmd.db_name, settings.verdict.argv..., ]
whisper '^psql_run@@3367^', "psql #{CND.shellescape parameters}"
settings =
cwd: cmd.cwd
shell: false
stdio: [ 'inherit', 'inherit', 'inherit', ]
cp = CP.spawn 'psql', parameters, settings
cp.on 'close', ( code ) ->
return resolve 0 if code is 0
reject new Error "^psql_run_file@34479^ processs exited with code #{code}"
cp.on 'error', ( error ) -> reject error
return null
#-----------------------------------------------------------------------------------------------------------
@nodexh_run_file = ( project_path, file_path ) -> new Promise ( resolve, reject ) =>
parameters = [ file_path, ]
whisper '^psql_run@@3367^', "psql #{parameters.join ' '}"
settings =
cwd: project_path
shell: false
stdio: [ 'inherit', 'inherit', 'inherit', ]
cp = CP.spawn 'nodexh', parameters, settings
cp.on 'close', ( code ) ->
return resolve 0 if code is 0
reject new Error "^nodexh_run_file@34479^ processs exited with code #{code}"
cp.on 'error', ( error ) -> reject error
return null
#-----------------------------------------------------------------------------------------------------------
@cli = ->
# shop = await @serve()
await @_cli()
# await shop.rpc.stop()
return null
#-----------------------------------------------------------------------------------------------------------
@_cli_get_project_path = ( d ) -> d.verdict.cd ? process.cwd()
#-----------------------------------------------------------------------------------------------------------
@_cli = ->
debug '^76483-3^', Date.now() / 1000
MIXA = require '../../../apps/mixa'
debug '^76483-4^', Date.now() / 1000
#.........................................................................................................
# program.action ( { logger, } ) => logger.info "Hello, world!"
#.........................................................................................................
jobdef =
# .name 'intershop'
#.......................................................................................................
commands:
'start-rpc-server':
description: "start RPC server (to be accessed from psql scripts)"
allow_extra: true
runner: ( d ) => new Promise ( done ) =>
project_path = @_cli_get_project_path d
shop = await @serve project_path
#.....................................................................................................
'psql':
description: "run psql"
allow_extra: true
runner: ( d ) => new Promise ( done ) =>
project_path = @_cli_get_project_path d
shop = await @serve project_path
### TAINT ###
info "^5564^ d.verdict: #{rpr d.verdict}"
info "^5565^ project_path: #{rpr project_path}"
# debug '^2223^', rpr command
# debug '^2223^', rpr project_path
me = @new_intershop_runner project_path
# info "^5566^ running psql with #{rpr { file: d.file, command: d.command, }}"
await @psql_run me, d
await shop.rpc.stop()
done()
return null
#.....................................................................................................
'nodexh':
description: "run nodexh"
allow_extra: true
runner: MIXA.runners.execSync
#.....................................................................................................
'node':
description: "run node"
allow_extra: true
runner: MIXA.runners.execSync
#.........................................................................................................
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
debug '^33344^', MIXA.parse jobdef, process.argv
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
R = await MIXA.run jobdef, process.argv
whisper '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', CND.format_number ( process.hrtime.bigint() - t0 ) # / 1000000000n
return R
# #-----------------------------------------------------------------------------------------------------------
# @demo = ->
# rpc = await @serve()
# # T.eq ( await DB.query_single [ "select IPC.rpc( $1, $2 );", '^add-42', '{"x":1000}' ] ), 1042
# await @psql_run_file '/home/flow/jzr/interplot', 'db/080-intertext.sql'
# await @psql_run_file '/home/flow/jzr/interplot', 'db/100-harfbuzz.sql'
# await @psql_run_file '/home/flow/jzr/interplot', 'db/tests/080-intertext.tests.sql'
# debug '^3334^', process.argv
# info rpc.counts
# await rpc.stop()
# return null
#-----------------------------------------------------------------------------------------------------------
@demo_intershop_object = ->
PATH = require 'path'
project_path = PATH.resolve PATH.join __dirname, '../../../../hengist'
project_path = PATH.resolve PATH.join __dirname, '../../../../interplot'
INTERSHOP = require 'intershop/lib/intershop'
shop = INTERSHOP.new_intershop project_path
keys = ( k for k of shop.settings ).sort()
for key in keys
continue if key.startsWith 'os/'
setting = shop.settings[ key ]
echo ( CND.gold key.padEnd 42 ), ( CND.lime setting.value )
return null
#-----------------------------------------------------------------------------------------------------------
@demo_query_addons = ->
PATH = require 'path'
project_path = PATH.resolve PATH.join __dirname, '../../../../hengist'
INTERSHOP = require 'intershop/lib/intershop'
shop = INTERSHOP.new_intershop project_path
### TAINT in the future `db` will be delivered with `new_intershop()` ###
shop.db = require 'intershop/lib/db'
RPC = require '../../../apps/intershop-rpc'
rpc = await RPC.create { show_counts: true, count_interval: 100, logging: true, }
debug ( k for k of shop.db ).sort()
# for addon from await shop.db.query [ "select * from ADDONS.addons;", ]
# info addon.aoid
# for file from await shop.db.query [ "select * from ADDONS.files where aoid = $1;", addon.aoid, ]
# urge ' ', ( CND.blue file.target ), ( CND.yellow file.path )
sql = "select * from ADDONS.files where target = 'rpc' order by aoid;"
for addon from await shop.db.query [ sql, ]
module = require addon.path
for method_name of module
do ( module, method_name ) =>
rpc_name = "^#{addon.aoid}/#{method_name}"
debug '^3334^', rpc_name
rpc.contract rpc_name, ( d ) -> module[ method_name ] d.$value
return null
return null
############################################################################################################
if module is require.main then do =>
# await @demo()
await @cli()
# await @demo_query_addons()
# @demo_intershop_object()
|
[
{
"context": "# Maskew\n# Mocha test suite\n# Dan Motzenbecker\n\nstyleFetcher = (el) -> do (style = {}) ->\n styl",
"end": 46,
"score": 0.9998806118965149,
"start": 30,
"tag": "NAME",
"value": "Dan Motzenbecker"
}
] | test/main.coffee | dmotz/maskew | 19 | # Maskew
# Mocha test suite
# Dan Motzenbecker
styleFetcher = (el) -> do (style = {}) ->
style[k] = v for k, v of window.getComputedStyle el
(key) -> style[key]
getRotation = (el) ->
parseFloat el.style[transformKey].match(/(-?\d+)deg/i)?[0]
getY = (el) ->
parseFloat el.style[transformKey].match(/translate3d\(\d+px\,\s?(-?\d+)px/i)?[1]
testPresence = (el) ->
while el = el.parentNode
return true if el is document
false
testDiv = document.createElement 'div'
testDiv.className = 'maskew-test'
transformKey = do ->
return 'transform' if testDiv.style.transform?
for prefix in ['Webkit', 'Moz', 'ms']
return key if testDiv.style[(key = prefix + 'Transform')]?
testDiv.style.width = testDiv.style.height = '200px'
testDiv.style.margin = testDiv.style.padding = '20px'
testDiv.style.backgroundColor = '#fff'
testDiv2 = testDiv.cloneNode false
testDiv2.className = testClass = 'maskew-test2'
document.body.appendChild testDiv
document.body.appendChild testDiv2
originalParent = testDiv.parentNode
cleanStyle = styleFetcher testDiv
testMaskew = new Maskew testDiv
dirtyStyle = styleFetcher testMaskew._outerMask
describe 'Maskew', ->
describe '#constructor()', ->
it 'should return an instance of Maskew', ->
expect(testMaskew instanceof Maskew).to.equal true
it 'should correctly return an object when not called with `new`', ->
expect(Maskew(testDiv2) instanceof Maskew).to.equal true
it 'should accept selector strings and use their elements', ->
expect((new Maskew '.' + testClass)._el).to.equal testDiv2
it 'should insert an element into the document', ->
expect(testPresence testMaskew._outerMask).to.equal true
it 'should insert an element in the same place as the target', ->
expect(testMaskew._outerMask.parentNode).to.equal originalParent
it 'should create an element of the same dimensions', ->
expect(dirtyStyle 'width').to.equal testDiv.clientWidth + 'px'
expect(dirtyStyle 'height').to.equal testDiv.clientHeight + 'px'
it 'should create an element with the same margins and padding', ->
for side in ['Top', 'Right', 'Bottom', 'Left']
margin = 'margin' + side
padding = 'padding' + side
expect(dirtyStyle margin).to.equal cleanStyle margin
expect(testMaskew._el.style[padding]).to.equal cleanStyle padding
describe '#skew()', ->
it 'should skew an element to a given angle', ->
testMaskew.skew 20
expect(getRotation testMaskew._innerMask).to.equal 20
it 'should keep inner contents upright', ->
expect(getRotation testMaskew._holder).to.equal -20
it 'should shift contents within the view mask based on angle', ->
expect(getY testMaskew._innerMask).to.equal -72
testMaskew.skew 10
expect(getY testMaskew._innerMask).to.equal -39
it 'should narrow the mask width based on the given angle', ->
expect(parseInt testMaskew._innerMask.style.width, 10).to.equal 201
testMaskew.skew 30
expect(parseInt testMaskew._innerMask.style.width, 10).to.equal 139
it 'should shorten the mask height based on the given angle', ->
expect(parseInt testMaskew._outerMask.style.height, 10).to.equal 139
testMaskew.skew 5
expect(parseInt testMaskew._outerMask.style.height, 10).to.equal 220
it 'should revert to 0 degrees when given a negative angle', ->
testMaskew.skew -20
expect(getRotation testMaskew._innerMask).to.equal 0
describe '#destroy()', ->
el = testMaskew._outerMask
it 'should remove the Maskew element from the document', ->
testMaskew.destroy()
expect(testPresence el).to.equal false
it 'should set all the object attributes to null', ->
allNull = do ->
for k, v of testMaskew
return false if v isnt null
true
expect(allNull).to.equal true
describe '#$.fn.maskew()', ->
$testMaskew = $('.maskew-test2').maskew()
it 'should return a jQuery object', ->
expect($testMaskew instanceof jQuery).to.equal true
it 'should stash a reference to the Maskew instance in the data cache', ->
expect($testMaskew.maskew()).to.equal $testMaskew.maskew()
it 'should return its Maskew instance by calling it with no arguments', ->
expect($testMaskew.maskew() instanceof Maskew).to.equal true
it 'should proxy Maskew methods as string arguments', ->
$testMaskew.maskew 'skew', 5
expect(parseInt $testMaskew.maskew()._outerMask.style.height, 10).to.equal 220
$testMaskew.maskew 'setTouch', true
expect($testMaskew.maskew()._outerMask.style.cursor).to.equal 'ew-resize'
| 197994 | # Maskew
# Mocha test suite
# <NAME>
styleFetcher = (el) -> do (style = {}) ->
style[k] = v for k, v of window.getComputedStyle el
(key) -> style[key]
getRotation = (el) ->
parseFloat el.style[transformKey].match(/(-?\d+)deg/i)?[0]
getY = (el) ->
parseFloat el.style[transformKey].match(/translate3d\(\d+px\,\s?(-?\d+)px/i)?[1]
testPresence = (el) ->
while el = el.parentNode
return true if el is document
false
testDiv = document.createElement 'div'
testDiv.className = 'maskew-test'
transformKey = do ->
return 'transform' if testDiv.style.transform?
for prefix in ['Webkit', 'Moz', 'ms']
return key if testDiv.style[(key = prefix + 'Transform')]?
testDiv.style.width = testDiv.style.height = '200px'
testDiv.style.margin = testDiv.style.padding = '20px'
testDiv.style.backgroundColor = '#fff'
testDiv2 = testDiv.cloneNode false
testDiv2.className = testClass = 'maskew-test2'
document.body.appendChild testDiv
document.body.appendChild testDiv2
originalParent = testDiv.parentNode
cleanStyle = styleFetcher testDiv
testMaskew = new Maskew testDiv
dirtyStyle = styleFetcher testMaskew._outerMask
describe 'Maskew', ->
describe '#constructor()', ->
it 'should return an instance of Maskew', ->
expect(testMaskew instanceof Maskew).to.equal true
it 'should correctly return an object when not called with `new`', ->
expect(Maskew(testDiv2) instanceof Maskew).to.equal true
it 'should accept selector strings and use their elements', ->
expect((new Maskew '.' + testClass)._el).to.equal testDiv2
it 'should insert an element into the document', ->
expect(testPresence testMaskew._outerMask).to.equal true
it 'should insert an element in the same place as the target', ->
expect(testMaskew._outerMask.parentNode).to.equal originalParent
it 'should create an element of the same dimensions', ->
expect(dirtyStyle 'width').to.equal testDiv.clientWidth + 'px'
expect(dirtyStyle 'height').to.equal testDiv.clientHeight + 'px'
it 'should create an element with the same margins and padding', ->
for side in ['Top', 'Right', 'Bottom', 'Left']
margin = 'margin' + side
padding = 'padding' + side
expect(dirtyStyle margin).to.equal cleanStyle margin
expect(testMaskew._el.style[padding]).to.equal cleanStyle padding
describe '#skew()', ->
it 'should skew an element to a given angle', ->
testMaskew.skew 20
expect(getRotation testMaskew._innerMask).to.equal 20
it 'should keep inner contents upright', ->
expect(getRotation testMaskew._holder).to.equal -20
it 'should shift contents within the view mask based on angle', ->
expect(getY testMaskew._innerMask).to.equal -72
testMaskew.skew 10
expect(getY testMaskew._innerMask).to.equal -39
it 'should narrow the mask width based on the given angle', ->
expect(parseInt testMaskew._innerMask.style.width, 10).to.equal 201
testMaskew.skew 30
expect(parseInt testMaskew._innerMask.style.width, 10).to.equal 139
it 'should shorten the mask height based on the given angle', ->
expect(parseInt testMaskew._outerMask.style.height, 10).to.equal 139
testMaskew.skew 5
expect(parseInt testMaskew._outerMask.style.height, 10).to.equal 220
it 'should revert to 0 degrees when given a negative angle', ->
testMaskew.skew -20
expect(getRotation testMaskew._innerMask).to.equal 0
describe '#destroy()', ->
el = testMaskew._outerMask
it 'should remove the Maskew element from the document', ->
testMaskew.destroy()
expect(testPresence el).to.equal false
it 'should set all the object attributes to null', ->
allNull = do ->
for k, v of testMaskew
return false if v isnt null
true
expect(allNull).to.equal true
describe '#$.fn.maskew()', ->
$testMaskew = $('.maskew-test2').maskew()
it 'should return a jQuery object', ->
expect($testMaskew instanceof jQuery).to.equal true
it 'should stash a reference to the Maskew instance in the data cache', ->
expect($testMaskew.maskew()).to.equal $testMaskew.maskew()
it 'should return its Maskew instance by calling it with no arguments', ->
expect($testMaskew.maskew() instanceof Maskew).to.equal true
it 'should proxy Maskew methods as string arguments', ->
$testMaskew.maskew 'skew', 5
expect(parseInt $testMaskew.maskew()._outerMask.style.height, 10).to.equal 220
$testMaskew.maskew 'setTouch', true
expect($testMaskew.maskew()._outerMask.style.cursor).to.equal 'ew-resize'
| true | # Maskew
# Mocha test suite
# PI:NAME:<NAME>END_PI
styleFetcher = (el) -> do (style = {}) ->
style[k] = v for k, v of window.getComputedStyle el
(key) -> style[key]
getRotation = (el) ->
parseFloat el.style[transformKey].match(/(-?\d+)deg/i)?[0]
getY = (el) ->
parseFloat el.style[transformKey].match(/translate3d\(\d+px\,\s?(-?\d+)px/i)?[1]
testPresence = (el) ->
while el = el.parentNode
return true if el is document
false
testDiv = document.createElement 'div'
testDiv.className = 'maskew-test'
transformKey = do ->
return 'transform' if testDiv.style.transform?
for prefix in ['Webkit', 'Moz', 'ms']
return key if testDiv.style[(key = prefix + 'Transform')]?
testDiv.style.width = testDiv.style.height = '200px'
testDiv.style.margin = testDiv.style.padding = '20px'
testDiv.style.backgroundColor = '#fff'
testDiv2 = testDiv.cloneNode false
testDiv2.className = testClass = 'maskew-test2'
document.body.appendChild testDiv
document.body.appendChild testDiv2
originalParent = testDiv.parentNode
cleanStyle = styleFetcher testDiv
testMaskew = new Maskew testDiv
dirtyStyle = styleFetcher testMaskew._outerMask
describe 'Maskew', ->
describe '#constructor()', ->
it 'should return an instance of Maskew', ->
expect(testMaskew instanceof Maskew).to.equal true
it 'should correctly return an object when not called with `new`', ->
expect(Maskew(testDiv2) instanceof Maskew).to.equal true
it 'should accept selector strings and use their elements', ->
expect((new Maskew '.' + testClass)._el).to.equal testDiv2
it 'should insert an element into the document', ->
expect(testPresence testMaskew._outerMask).to.equal true
it 'should insert an element in the same place as the target', ->
expect(testMaskew._outerMask.parentNode).to.equal originalParent
it 'should create an element of the same dimensions', ->
expect(dirtyStyle 'width').to.equal testDiv.clientWidth + 'px'
expect(dirtyStyle 'height').to.equal testDiv.clientHeight + 'px'
it 'should create an element with the same margins and padding', ->
for side in ['Top', 'Right', 'Bottom', 'Left']
margin = 'margin' + side
padding = 'padding' + side
expect(dirtyStyle margin).to.equal cleanStyle margin
expect(testMaskew._el.style[padding]).to.equal cleanStyle padding
describe '#skew()', ->
it 'should skew an element to a given angle', ->
testMaskew.skew 20
expect(getRotation testMaskew._innerMask).to.equal 20
it 'should keep inner contents upright', ->
expect(getRotation testMaskew._holder).to.equal -20
it 'should shift contents within the view mask based on angle', ->
expect(getY testMaskew._innerMask).to.equal -72
testMaskew.skew 10
expect(getY testMaskew._innerMask).to.equal -39
it 'should narrow the mask width based on the given angle', ->
expect(parseInt testMaskew._innerMask.style.width, 10).to.equal 201
testMaskew.skew 30
expect(parseInt testMaskew._innerMask.style.width, 10).to.equal 139
it 'should shorten the mask height based on the given angle', ->
expect(parseInt testMaskew._outerMask.style.height, 10).to.equal 139
testMaskew.skew 5
expect(parseInt testMaskew._outerMask.style.height, 10).to.equal 220
it 'should revert to 0 degrees when given a negative angle', ->
testMaskew.skew -20
expect(getRotation testMaskew._innerMask).to.equal 0
describe '#destroy()', ->
el = testMaskew._outerMask
it 'should remove the Maskew element from the document', ->
testMaskew.destroy()
expect(testPresence el).to.equal false
it 'should set all the object attributes to null', ->
allNull = do ->
for k, v of testMaskew
return false if v isnt null
true
expect(allNull).to.equal true
describe '#$.fn.maskew()', ->
$testMaskew = $('.maskew-test2').maskew()
it 'should return a jQuery object', ->
expect($testMaskew instanceof jQuery).to.equal true
it 'should stash a reference to the Maskew instance in the data cache', ->
expect($testMaskew.maskew()).to.equal $testMaskew.maskew()
it 'should return its Maskew instance by calling it with no arguments', ->
expect($testMaskew.maskew() instanceof Maskew).to.equal true
it 'should proxy Maskew methods as string arguments', ->
$testMaskew.maskew 'skew', 5
expect(parseInt $testMaskew.maskew()._outerMask.style.height, 10).to.equal 220
$testMaskew.maskew 'setTouch', true
expect($testMaskew.maskew()._outerMask.style.cursor).to.equal 'ew-resize'
|
[
{
"context": "class Warrior\n key: 'warrior'\n name: 'warrior'\n\n genders: ['male', 'female']\n alignments: ['g",
"end": 47,
"score": 0.9981451034545898,
"start": 40,
"tag": "NAME",
"value": "warrior"
}
] | js/classes/warrior.coffee | ktchernov/7drl-lion.github.io | 27 | class Warrior
key: 'warrior'
name: 'warrior'
genders: ['male', 'female']
alignments: ['good', 'neutral', 'evil']
races: ['human', 'werewolf', 'dragon', 'giant', 'angel', 'demon', 'catfolk', 'elf', 'dwarf', 'hobbit', 'vampire']
base_hp: 10
base_mp: -10
base_speed: 0
base_attack: 5
base_sight_range: 0
skills: [
'whirlwind_strike'
'cleave'
'berserk'
'charge'
'bash'
'heavy_strike'
'skull_crack'
'savage_leap'
'adrenaline'
'cripple'
]
register_class Warrior
| 195736 | class Warrior
key: 'warrior'
name: '<NAME>'
genders: ['male', 'female']
alignments: ['good', 'neutral', 'evil']
races: ['human', 'werewolf', 'dragon', 'giant', 'angel', 'demon', 'catfolk', 'elf', 'dwarf', 'hobbit', 'vampire']
base_hp: 10
base_mp: -10
base_speed: 0
base_attack: 5
base_sight_range: 0
skills: [
'whirlwind_strike'
'cleave'
'berserk'
'charge'
'bash'
'heavy_strike'
'skull_crack'
'savage_leap'
'adrenaline'
'cripple'
]
register_class Warrior
| true | class Warrior
key: 'warrior'
name: 'PI:NAME:<NAME>END_PI'
genders: ['male', 'female']
alignments: ['good', 'neutral', 'evil']
races: ['human', 'werewolf', 'dragon', 'giant', 'angel', 'demon', 'catfolk', 'elf', 'dwarf', 'hobbit', 'vampire']
base_hp: 10
base_mp: -10
base_speed: 0
base_attack: 5
base_sight_range: 0
skills: [
'whirlwind_strike'
'cleave'
'berserk'
'charge'
'bash'
'heavy_strike'
'skull_crack'
'savage_leap'
'adrenaline'
'cripple'
]
register_class Warrior
|
[
{
"context": "###\n knockback-utils.js\n (c) 2011-2013 Kevin Malakoff.\n Knockback.js is freely distributable under the",
"end": 55,
"score": 0.9997914433479309,
"start": 41,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": " for full license details:\n https://github.c... | src/core/utils.coffee | npmcomponent/kmalakoff-knockback | 1 | ###
knockback-utils.js
(c) 2011-2013 Kevin Malakoff.
Knockback.js is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback/blob/master/LICENSE
Dependencies: Knockout.js, Backbone.js, and Underscore.js.
Optional dependency: Backbone.ModelRef.js.
###
####################################################
# Internal
####################################################
_wrappedKey = (obj, key, value) ->
# get
if arguments.length is 2
return if (obj and obj.__kb and obj.__kb.hasOwnProperty(key)) then obj.__kb[key] else undefined
# set
obj or _throwUnexpected(@, "no obj for wrapping #{key}")
obj.__kb or= {}
obj.__kb[key] = value
return value
_argumentsAddKey = (args, key) ->
_arraySplice.call(args, 1, 0, key)
return args
# used for attribute setting to ensure all model attributes have their underlying models
_unwrapModels = (obj) ->
return obj if not obj
if obj.__kb
return if ('object' of obj.__kb) then obj.__kb.object else obj
else if _.isArray(obj)
return _.map(obj, (test) -> return _unwrapModels(test))
else if _.isObject(obj) and (obj.constructor is {}.constructor) # a simple object
result = {}
for key, value of obj
result[key] = _unwrapModels(value)
return result
return obj
_mergeArray = (result, key, value) ->
result[key] or= []
value = [value] unless _.isArray(value)
result[key] = if result[key].length then _.union(result[key], value) else value
return result
_mergeObject = (result, key, value) ->
result[key] or= {}
return _.extend(result[key], value)
_keyArrayToObject = (value) ->
result = {}
result[item] = {key: item} for item in value
return result
_collapseOptions = (options) ->
result = {}
options = {options: options}
while options.options
for key, value of options.options
switch key
when 'internals', 'requires', 'excludes', 'statics' then _mergeArray(result, key, value)
when 'keys'
# an object
if (_.isObject(value) and not _.isArray(value)) or (_.isObject(result[key]) and not _.isArray(result[key]))
value = [value] unless _.isObject(value)
value = _keyArrayToObject(value) if _.isArray(value)
result[key] = _keyArrayToObject(result[key]) if _.isArray(result[key])
_mergeObject(result, key, value)
# an array
else
_mergeArray(result, key, value)
when 'factories'
if _.isFunction(value) # special case for ko.observable
result[key] = value
else
_mergeObject(result, key, value)
when 'static_defaults' then _mergeObject(result, key, value)
when 'options' then
else
result[key] = value
options = options.options
return result
####################################################
# Public API
####################################################
# Library of general-purpose utilities
class kb.utils
# Dual-purpose getter/setter for retrieving and storing the observable on an instance that returns a ko.observable instead of 'this'. Relevant for:
#
# * [kb.CollectionObservable]('classes/kb/CollectionObservable.html')
# * [kb.Observable]('classes/kb/Observable.html')
# * [kb.DefaultObservable]('classes/kb/DefaultObservable.html')
# * [kb.FormattedObservable]('classes/kb/FormattedObservable.html')
# * [kb.LocalizedObservable]('classes/kb/LocalizedObservable.html')
# * [kb.TriggeredObservable]('classes/kb/TriggeredObservable.html')
#
# @overload wrappedObservable(instance)
# Gets the observable from an object
# @param [Any] instance the owner
# @return [ko.observable|ko.observableArray] the observable
# @overload wrappedObservable(instance, observable)
# Sets the observable on an object
# @param [Any] instance the owner
# @param [ko.observable|ko.observableArray] observable the observable
#
# @example
# var ShortDateLocalizer = kb.LocalizedObservable.extend({
# constructor: function(value, options, view_model) {
# kb.LocalizedObservable.prototype.constructor.apply(this, arguments);
# return kb.utils.wrappedObservable(this);
# }
# });
@wrappedObservable = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'observable'))
# Dual-purpose getter/setter for retrieving and storing the Model or Collection on an owner.
# @note this is almost the same as {kb.utils.wrappedModel} except that if the Model doesn't exist, it returns null.
#
# @overload wrappedObject(obj)
# Gets the observable from an object
# @param [Object|kb.ViewModel|kb.CollectionObservable] obj owner the ViewModel/CollectionObservable owning the kb.Model or kb.Collection.
# @return [Model|Collection] the model/collection
# @overload wrappedObject(obj, value)
# Sets the observable on an object
# @param [Object|kb.ViewModel|kb.CollectionObservable] obj owner the ViewModel/CollectionObservable owning the kb.Model or kb.Collection.
# @param [Model|Collection] value the model/collection
#
# @example
# var model = kb.utils.wrappedObject(view_model);
# var collection = kb.utils.wrappedObject(collection_observable);
@wrappedObject = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'object'))
# Dual-purpose getter/setter for retrieving and storing the Model on a ViewModel.
# @note this is almost the same as {kb.utils.wrappedObject} except that if the Model doesn't exist, it returns the ViewModel itself (which is useful behaviour for sorting because it you can iterate over a kb.CollectionObservable's ko.ObservableArray whether it holds ViewModels or Models with the models_only option).
#
# @overload wrappedModel(view_model)
# Gets the model from a ViewModel
# @param [Object|kb.ViewModel] view_model the owning ViewModel for the Model.
# @return [Model|ViewModel] the Model or ViewModel itself if there is no Model
# @overload wrappedModel(view_model, model)
# Sets the observable on an object
# @param [Object|kb.ViewModel] view_model the owning ViewModel for the Model.
# @param [Model] model the Model
@wrappedModel = (obj, value) ->
# get
if (arguments.length is 1)
value = _wrappedKey(obj, 'object')
return if _.isUndefined(value) then obj else value
else
return _wrappedKey(obj, 'object', value)
# Dual-purpose getter/setter for retrieving and storing a kb.Store on an owner.
#
# @overload wrappedStore(obj)
# Gets the store from an object
# @param [Any] obj the owner
# @return [kb.Store] the store
# @overload wrappedStore(obj, store)
# Sets the store on an object
# @param [Any] obj the owner
# @param [kb.Store] store the store
#
# @example
# var co = kb.collectionObservable(new Backbone.Collection());
# var co_selected_options = kb.collectionObservable(new Backbone.Collection(), {
# store: kb.utils.wrappedStore(co)
# });
@wrappedStore = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'store'))
# @private
@wrappedStoreIsOwned = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'store_is_owned'))
# Dual-purpose getter/setter for retrieving and storing a kb.Factory on an owner.
#
# @overload wrappedFactory(obj)
# Gets the factory from an object
# @param [Any] obj the owner
# @return [kb.Factory] the factory
# @overload wrappedFactory(obj, factory)
# Sets the factory on an object
# @param [Any] obj the owner
# @param [kb.Factory] factory the factory
@wrappedFactory = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'factory'))
# Dual-purpose getter/setter for retrieving and storing a kb.EventWatcher on an owner.
#
# @overload wrappedEventWatcher(obj)
# Gets the event_watcher from an object
# @param [Any] obj the owner
# @return [kb.EventWatcher] the event_watcher
# @overload wrappedEventWatcher(obj, event_watcher)
# Sets the event_watcher on an object
# @param [Any] obj the owner
# @param [kb.EventWatcher] event_watcher the event_watcher
@wrappedEventWatcher = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'event_watcher'))
# @private
@wrappedEventWatcherIsOwned = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'event_watcher_is_owned'))
# Clean up function that releases all of the wrapped values on an owner.
@wrappedDestroy = (obj) ->
return unless obj.__kb
obj.__kb.event_watcher.releaseCallbacks(obj) if obj.__kb.event_watcher
__kb = obj.__kb; obj.__kb = null # clear now to break cycles
if __kb.observable
__kb.observable.destroy = __kb.observable.release = null
@wrappedDestroy(__kb.observable)
__kb.observable = null
__kb.factory = null
__kb.event_watcher.destroy() if __kb.event_watcher_is_owned # release the event_watcher
__kb.event_watcher = null
__kb.store.destroy() if __kb.store_is_owned # release the store
__kb.store = null
# kb.release(__kb, true) # release everything that remains
# Retrieves the value stored in a ko.observable.
#
# @see kb.Observable valueType
#
# @example
# var view_model = kb.viewModel(new Model({simple_attr: null, model_attr: null}), {factories: {model_attr: kb.ViewModel});
# kb.utils.valueType(view_model.simple_attr); // kb.TYPE_SIMPLE
# kb.utils.valueType(view_model.model_attr); // kb.TYPE_MODEL
@valueType = (observable) ->
return KB_TYPE_UNKNOWN unless observable
return observable.valueType() if observable.__kb_is_o
return KB_TYPE_COLLECTION if observable.__kb_is_co or (observable instanceof kb.Collection)
return KB_TYPE_MODEL if (observable instanceof kb.ViewModel) or (observable instanceof kb.Model)
return KB_TYPE_ARRAY if _.isArray(observable)
return KB_TYPE_SIMPLE
# Helper to join a dot-deliminated path.
#
# @param [String] path1 start path.
# @param [String] path2 append path.
# @return [String] combined dot-delimited path.
#
# @example
# kb.utils.pathJoin('models', 'name'); // 'models.name'
@pathJoin = (path1, path2) ->
return (if path1 then (if path1[path1.length-1] isnt '.' then "#{path1}." else path1) else '') + path2
# Helper to join a dot-deliminated path with the path on options and returns a new options object with the result.
#
# @param [Object] options with path property for the start path
# @param [String] path append path.
# @return [Object] new options with combined dot-delimited path `{path: combined_path}`.
#
# @example
# this.friends = kb.collectionObservable(model.get('friends'), kb.utils.optionsPathJoin(options, 'friends'));
@optionsPathJoin = (options, path) ->
return _.defaults({path: @pathJoin(options.path, path)}, options)
# Helper to find the creator constructor or function from a factory or ORM solution
@inferCreator = (value, factory, path, owner, key) ->
creator = factory.creatorForPath(value, path) if factory
return creator if creator
# try fallbacks
return null unless value
return kb.ViewModel if value instanceof kb.Model
return kb.CollectionObservable if value instanceof kb.Collection
return null
# Creates an observable based on a value's type.
@createFromDefaultCreator = (obj, options) ->
return kb.viewModel(obj, options) if obj instanceof kb.Model
return kb.collectionObservable(obj, options) if obj instanceof kb.Collection
return ko.observableArray(obj) if _.isArray(obj)
return ko.observable(obj)
# Helper to check an object for having a Model signature. For example, locale managers and ModelRef don't need to derive from Model
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.hasModelSignature(new Model());
@hasModelSignature = (obj) ->
return obj and (obj.attributes and not obj.models) and (typeof(obj.get) is 'function') and (typeof(obj.trigger) is 'function')
# Helper to check an object for having a Model signature. For example, locale managers and ModelRef don't need to derive from Model
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.hasModelSignature(new Model());
@hasCollectionSignature = (obj) ->
return obj and obj.models and (typeof(obj.get) is 'function') and (typeof(obj.trigger) is 'function')
# Helper to merge options including ViewmModel options like `keys` and `factories`
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.collapseOptions(options);
@collapseOptions = _collapseOptions
# Helper to ignore dependencies in a function
#
# @param [Object] obj the object to test
#
# @example
# kb.ignore(fn);
kb.ignore = ko.dependencyDetection?.ignore or (callback, callbackTarget, callbackArgs) -> value = null; ko.dependentObservable(-> value = callback.apply(callbackTarget, callbackArgs || [])).dispose(); return value
| 134289 | ###
knockback-utils.js
(c) 2011-2013 <NAME>.
Knockback.js is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback/blob/master/LICENSE
Dependencies: Knockout.js, Backbone.js, and Underscore.js.
Optional dependency: Backbone.ModelRef.js.
###
####################################################
# Internal
####################################################
_wrappedKey = (obj, key, value) ->
# get
if arguments.length is 2
return if (obj and obj.__kb and obj.__kb.hasOwnProperty(key)) then obj.__kb[key] else undefined
# set
obj or _throwUnexpected(@, "no obj for wrapping #{key}")
obj.__kb or= {}
obj.__kb[key] = value
return value
_argumentsAddKey = (args, key) ->
_arraySplice.call(args, 1, 0, key)
return args
# used for attribute setting to ensure all model attributes have their underlying models
_unwrapModels = (obj) ->
return obj if not obj
if obj.__kb
return if ('object' of obj.__kb) then obj.__kb.object else obj
else if _.isArray(obj)
return _.map(obj, (test) -> return _unwrapModels(test))
else if _.isObject(obj) and (obj.constructor is {}.constructor) # a simple object
result = {}
for key, value of obj
result[key] = _unwrapModels(value)
return result
return obj
_mergeArray = (result, key, value) ->
result[key] or= []
value = [value] unless _.isArray(value)
result[key] = if result[key].length then _.union(result[key], value) else value
return result
_mergeObject = (result, key, value) ->
result[key] or= {}
return _.extend(result[key], value)
_keyArrayToObject = (value) ->
result = {}
result[item] = {key: item} for item in value
return result
_collapseOptions = (options) ->
result = {}
options = {options: options}
while options.options
for key, value of options.options
switch key
when 'internals', 'requires', 'excludes', 'statics' then _mergeArray(result, key, value)
when 'keys'
# an object
if (_.isObject(value) and not _.isArray(value)) or (_.isObject(result[key]) and not _.isArray(result[key]))
value = [value] unless _.isObject(value)
value = _keyArrayToObject(value) if _.isArray(value)
result[key] = _keyArrayToObject(result[key]) if _.isArray(result[key])
_mergeObject(result, key, value)
# an array
else
_mergeArray(result, key, value)
when 'factories'
if _.isFunction(value) # special case for ko.observable
result[key] = value
else
_mergeObject(result, key, value)
when 'static_defaults' then _mergeObject(result, key, value)
when 'options' then
else
result[key] = value
options = options.options
return result
####################################################
# Public API
####################################################
# Library of general-purpose utilities
class kb.utils
# Dual-purpose getter/setter for retrieving and storing the observable on an instance that returns a ko.observable instead of 'this'. Relevant for:
#
# * [kb.CollectionObservable]('classes/kb/CollectionObservable.html')
# * [kb.Observable]('classes/kb/Observable.html')
# * [kb.DefaultObservable]('classes/kb/DefaultObservable.html')
# * [kb.FormattedObservable]('classes/kb/FormattedObservable.html')
# * [kb.LocalizedObservable]('classes/kb/LocalizedObservable.html')
# * [kb.TriggeredObservable]('classes/kb/TriggeredObservable.html')
#
# @overload wrappedObservable(instance)
# Gets the observable from an object
# @param [Any] instance the owner
# @return [ko.observable|ko.observableArray] the observable
# @overload wrappedObservable(instance, observable)
# Sets the observable on an object
# @param [Any] instance the owner
# @param [ko.observable|ko.observableArray] observable the observable
#
# @example
# var ShortDateLocalizer = kb.LocalizedObservable.extend({
# constructor: function(value, options, view_model) {
# kb.LocalizedObservable.prototype.constructor.apply(this, arguments);
# return kb.utils.wrappedObservable(this);
# }
# });
@wrappedObservable = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'observable'))
# Dual-purpose getter/setter for retrieving and storing the Model or Collection on an owner.
# @note this is almost the same as {kb.utils.wrappedModel} except that if the Model doesn't exist, it returns null.
#
# @overload wrappedObject(obj)
# Gets the observable from an object
# @param [Object|kb.ViewModel|kb.CollectionObservable] obj owner the ViewModel/CollectionObservable owning the kb.Model or kb.Collection.
# @return [Model|Collection] the model/collection
# @overload wrappedObject(obj, value)
# Sets the observable on an object
# @param [Object|kb.ViewModel|kb.CollectionObservable] obj owner the ViewModel/CollectionObservable owning the kb.Model or kb.Collection.
# @param [Model|Collection] value the model/collection
#
# @example
# var model = kb.utils.wrappedObject(view_model);
# var collection = kb.utils.wrappedObject(collection_observable);
@wrappedObject = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'object'))
# Dual-purpose getter/setter for retrieving and storing the Model on a ViewModel.
# @note this is almost the same as {kb.utils.wrappedObject} except that if the Model doesn't exist, it returns the ViewModel itself (which is useful behaviour for sorting because it you can iterate over a kb.CollectionObservable's ko.ObservableArray whether it holds ViewModels or Models with the models_only option).
#
# @overload wrappedModel(view_model)
# Gets the model from a ViewModel
# @param [Object|kb.ViewModel] view_model the owning ViewModel for the Model.
# @return [Model|ViewModel] the Model or ViewModel itself if there is no Model
# @overload wrappedModel(view_model, model)
# Sets the observable on an object
# @param [Object|kb.ViewModel] view_model the owning ViewModel for the Model.
# @param [Model] model the Model
@wrappedModel = (obj, value) ->
# get
if (arguments.length is 1)
value = _wrappedKey(obj, 'object')
return if _.isUndefined(value) then obj else value
else
return _wrappedKey(obj, 'object', value)
# Dual-purpose getter/setter for retrieving and storing a kb.Store on an owner.
#
# @overload wrappedStore(obj)
# Gets the store from an object
# @param [Any] obj the owner
# @return [kb.Store] the store
# @overload wrappedStore(obj, store)
# Sets the store on an object
# @param [Any] obj the owner
# @param [kb.Store] store the store
#
# @example
# var co = kb.collectionObservable(new Backbone.Collection());
# var co_selected_options = kb.collectionObservable(new Backbone.Collection(), {
# store: kb.utils.wrappedStore(co)
# });
@wrappedStore = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'store'))
# @private
@wrappedStoreIsOwned = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'store_is_owned'))
# Dual-purpose getter/setter for retrieving and storing a kb.Factory on an owner.
#
# @overload wrappedFactory(obj)
# Gets the factory from an object
# @param [Any] obj the owner
# @return [kb.Factory] the factory
# @overload wrappedFactory(obj, factory)
# Sets the factory on an object
# @param [Any] obj the owner
# @param [kb.Factory] factory the factory
@wrappedFactory = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'factory'))
# Dual-purpose getter/setter for retrieving and storing a kb.EventWatcher on an owner.
#
# @overload wrappedEventWatcher(obj)
# Gets the event_watcher from an object
# @param [Any] obj the owner
# @return [kb.EventWatcher] the event_watcher
# @overload wrappedEventWatcher(obj, event_watcher)
# Sets the event_watcher on an object
# @param [Any] obj the owner
# @param [kb.EventWatcher] event_watcher the event_watcher
@wrappedEventWatcher = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'event_watcher'))
# @private
@wrappedEventWatcherIsOwned = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'event_watcher_is_owned'))
# Clean up function that releases all of the wrapped values on an owner.
@wrappedDestroy = (obj) ->
return unless obj.__kb
obj.__kb.event_watcher.releaseCallbacks(obj) if obj.__kb.event_watcher
__kb = obj.__kb; obj.__kb = null # clear now to break cycles
if __kb.observable
__kb.observable.destroy = __kb.observable.release = null
@wrappedDestroy(__kb.observable)
__kb.observable = null
__kb.factory = null
__kb.event_watcher.destroy() if __kb.event_watcher_is_owned # release the event_watcher
__kb.event_watcher = null
__kb.store.destroy() if __kb.store_is_owned # release the store
__kb.store = null
# kb.release(__kb, true) # release everything that remains
# Retrieves the value stored in a ko.observable.
#
# @see kb.Observable valueType
#
# @example
# var view_model = kb.viewModel(new Model({simple_attr: null, model_attr: null}), {factories: {model_attr: kb.ViewModel});
# kb.utils.valueType(view_model.simple_attr); // kb.TYPE_SIMPLE
# kb.utils.valueType(view_model.model_attr); // kb.TYPE_MODEL
@valueType = (observable) ->
return KB_TYPE_UNKNOWN unless observable
return observable.valueType() if observable.__kb_is_o
return KB_TYPE_COLLECTION if observable.__kb_is_co or (observable instanceof kb.Collection)
return KB_TYPE_MODEL if (observable instanceof kb.ViewModel) or (observable instanceof kb.Model)
return KB_TYPE_ARRAY if _.isArray(observable)
return KB_TYPE_SIMPLE
# Helper to join a dot-deliminated path.
#
# @param [String] path1 start path.
# @param [String] path2 append path.
# @return [String] combined dot-delimited path.
#
# @example
# kb.utils.pathJoin('models', 'name'); // 'models.name'
@pathJoin = (path1, path2) ->
return (if path1 then (if path1[path1.length-1] isnt '.' then "#{path1}." else path1) else '') + path2
# Helper to join a dot-deliminated path with the path on options and returns a new options object with the result.
#
# @param [Object] options with path property for the start path
# @param [String] path append path.
# @return [Object] new options with combined dot-delimited path `{path: combined_path}`.
#
# @example
# this.friends = kb.collectionObservable(model.get('friends'), kb.utils.optionsPathJoin(options, 'friends'));
@optionsPathJoin = (options, path) ->
return _.defaults({path: @pathJoin(options.path, path)}, options)
# Helper to find the creator constructor or function from a factory or ORM solution
@inferCreator = (value, factory, path, owner, key) ->
creator = factory.creatorForPath(value, path) if factory
return creator if creator
# try fallbacks
return null unless value
return kb.ViewModel if value instanceof kb.Model
return kb.CollectionObservable if value instanceof kb.Collection
return null
# Creates an observable based on a value's type.
@createFromDefaultCreator = (obj, options) ->
return kb.viewModel(obj, options) if obj instanceof kb.Model
return kb.collectionObservable(obj, options) if obj instanceof kb.Collection
return ko.observableArray(obj) if _.isArray(obj)
return ko.observable(obj)
# Helper to check an object for having a Model signature. For example, locale managers and ModelRef don't need to derive from Model
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.hasModelSignature(new Model());
@hasModelSignature = (obj) ->
return obj and (obj.attributes and not obj.models) and (typeof(obj.get) is 'function') and (typeof(obj.trigger) is 'function')
# Helper to check an object for having a Model signature. For example, locale managers and ModelRef don't need to derive from Model
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.hasModelSignature(new Model());
@hasCollectionSignature = (obj) ->
return obj and obj.models and (typeof(obj.get) is 'function') and (typeof(obj.trigger) is 'function')
# Helper to merge options including ViewmModel options like `keys` and `factories`
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.collapseOptions(options);
@collapseOptions = _collapseOptions
# Helper to ignore dependencies in a function
#
# @param [Object] obj the object to test
#
# @example
# kb.ignore(fn);
kb.ignore = ko.dependencyDetection?.ignore or (callback, callbackTarget, callbackArgs) -> value = null; ko.dependentObservable(-> value = callback.apply(callbackTarget, callbackArgs || [])).dispose(); return value
| true | ###
knockback-utils.js
(c) 2011-2013 PI:NAME:<NAME>END_PI.
Knockback.js is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback/blob/master/LICENSE
Dependencies: Knockout.js, Backbone.js, and Underscore.js.
Optional dependency: Backbone.ModelRef.js.
###
####################################################
# Internal
####################################################
_wrappedKey = (obj, key, value) ->
# get
if arguments.length is 2
return if (obj and obj.__kb and obj.__kb.hasOwnProperty(key)) then obj.__kb[key] else undefined
# set
obj or _throwUnexpected(@, "no obj for wrapping #{key}")
obj.__kb or= {}
obj.__kb[key] = value
return value
_argumentsAddKey = (args, key) ->
_arraySplice.call(args, 1, 0, key)
return args
# used for attribute setting to ensure all model attributes have their underlying models
_unwrapModels = (obj) ->
return obj if not obj
if obj.__kb
return if ('object' of obj.__kb) then obj.__kb.object else obj
else if _.isArray(obj)
return _.map(obj, (test) -> return _unwrapModels(test))
else if _.isObject(obj) and (obj.constructor is {}.constructor) # a simple object
result = {}
for key, value of obj
result[key] = _unwrapModels(value)
return result
return obj
_mergeArray = (result, key, value) ->
result[key] or= []
value = [value] unless _.isArray(value)
result[key] = if result[key].length then _.union(result[key], value) else value
return result
_mergeObject = (result, key, value) ->
result[key] or= {}
return _.extend(result[key], value)
_keyArrayToObject = (value) ->
result = {}
result[item] = {key: item} for item in value
return result
_collapseOptions = (options) ->
result = {}
options = {options: options}
while options.options
for key, value of options.options
switch key
when 'internals', 'requires', 'excludes', 'statics' then _mergeArray(result, key, value)
when 'keys'
# an object
if (_.isObject(value) and not _.isArray(value)) or (_.isObject(result[key]) and not _.isArray(result[key]))
value = [value] unless _.isObject(value)
value = _keyArrayToObject(value) if _.isArray(value)
result[key] = _keyArrayToObject(result[key]) if _.isArray(result[key])
_mergeObject(result, key, value)
# an array
else
_mergeArray(result, key, value)
when 'factories'
if _.isFunction(value) # special case for ko.observable
result[key] = value
else
_mergeObject(result, key, value)
when 'static_defaults' then _mergeObject(result, key, value)
when 'options' then
else
result[key] = value
options = options.options
return result
####################################################
# Public API
####################################################
# Library of general-purpose utilities
class kb.utils
# Dual-purpose getter/setter for retrieving and storing the observable on an instance that returns a ko.observable instead of 'this'. Relevant for:
#
# * [kb.CollectionObservable]('classes/kb/CollectionObservable.html')
# * [kb.Observable]('classes/kb/Observable.html')
# * [kb.DefaultObservable]('classes/kb/DefaultObservable.html')
# * [kb.FormattedObservable]('classes/kb/FormattedObservable.html')
# * [kb.LocalizedObservable]('classes/kb/LocalizedObservable.html')
# * [kb.TriggeredObservable]('classes/kb/TriggeredObservable.html')
#
# @overload wrappedObservable(instance)
# Gets the observable from an object
# @param [Any] instance the owner
# @return [ko.observable|ko.observableArray] the observable
# @overload wrappedObservable(instance, observable)
# Sets the observable on an object
# @param [Any] instance the owner
# @param [ko.observable|ko.observableArray] observable the observable
#
# @example
# var ShortDateLocalizer = kb.LocalizedObservable.extend({
# constructor: function(value, options, view_model) {
# kb.LocalizedObservable.prototype.constructor.apply(this, arguments);
# return kb.utils.wrappedObservable(this);
# }
# });
@wrappedObservable = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'observable'))
# Dual-purpose getter/setter for retrieving and storing the Model or Collection on an owner.
# @note this is almost the same as {kb.utils.wrappedModel} except that if the Model doesn't exist, it returns null.
#
# @overload wrappedObject(obj)
# Gets the observable from an object
# @param [Object|kb.ViewModel|kb.CollectionObservable] obj owner the ViewModel/CollectionObservable owning the kb.Model or kb.Collection.
# @return [Model|Collection] the model/collection
# @overload wrappedObject(obj, value)
# Sets the observable on an object
# @param [Object|kb.ViewModel|kb.CollectionObservable] obj owner the ViewModel/CollectionObservable owning the kb.Model or kb.Collection.
# @param [Model|Collection] value the model/collection
#
# @example
# var model = kb.utils.wrappedObject(view_model);
# var collection = kb.utils.wrappedObject(collection_observable);
@wrappedObject = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'object'))
# Dual-purpose getter/setter for retrieving and storing the Model on a ViewModel.
# @note this is almost the same as {kb.utils.wrappedObject} except that if the Model doesn't exist, it returns the ViewModel itself (which is useful behaviour for sorting because it you can iterate over a kb.CollectionObservable's ko.ObservableArray whether it holds ViewModels or Models with the models_only option).
#
# @overload wrappedModel(view_model)
# Gets the model from a ViewModel
# @param [Object|kb.ViewModel] view_model the owning ViewModel for the Model.
# @return [Model|ViewModel] the Model or ViewModel itself if there is no Model
# @overload wrappedModel(view_model, model)
# Sets the observable on an object
# @param [Object|kb.ViewModel] view_model the owning ViewModel for the Model.
# @param [Model] model the Model
@wrappedModel = (obj, value) ->
# get
if (arguments.length is 1)
value = _wrappedKey(obj, 'object')
return if _.isUndefined(value) then obj else value
else
return _wrappedKey(obj, 'object', value)
# Dual-purpose getter/setter for retrieving and storing a kb.Store on an owner.
#
# @overload wrappedStore(obj)
# Gets the store from an object
# @param [Any] obj the owner
# @return [kb.Store] the store
# @overload wrappedStore(obj, store)
# Sets the store on an object
# @param [Any] obj the owner
# @param [kb.Store] store the store
#
# @example
# var co = kb.collectionObservable(new Backbone.Collection());
# var co_selected_options = kb.collectionObservable(new Backbone.Collection(), {
# store: kb.utils.wrappedStore(co)
# });
@wrappedStore = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'store'))
# @private
@wrappedStoreIsOwned = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'store_is_owned'))
# Dual-purpose getter/setter for retrieving and storing a kb.Factory on an owner.
#
# @overload wrappedFactory(obj)
# Gets the factory from an object
# @param [Any] obj the owner
# @return [kb.Factory] the factory
# @overload wrappedFactory(obj, factory)
# Sets the factory on an object
# @param [Any] obj the owner
# @param [kb.Factory] factory the factory
@wrappedFactory = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'factory'))
# Dual-purpose getter/setter for retrieving and storing a kb.EventWatcher on an owner.
#
# @overload wrappedEventWatcher(obj)
# Gets the event_watcher from an object
# @param [Any] obj the owner
# @return [kb.EventWatcher] the event_watcher
# @overload wrappedEventWatcher(obj, event_watcher)
# Sets the event_watcher on an object
# @param [Any] obj the owner
# @param [kb.EventWatcher] event_watcher the event_watcher
@wrappedEventWatcher = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'event_watcher'))
# @private
@wrappedEventWatcherIsOwned = (obj, value) -> return _wrappedKey.apply(@, _argumentsAddKey(arguments, 'event_watcher_is_owned'))
# Clean up function that releases all of the wrapped values on an owner.
@wrappedDestroy = (obj) ->
return unless obj.__kb
obj.__kb.event_watcher.releaseCallbacks(obj) if obj.__kb.event_watcher
__kb = obj.__kb; obj.__kb = null # clear now to break cycles
if __kb.observable
__kb.observable.destroy = __kb.observable.release = null
@wrappedDestroy(__kb.observable)
__kb.observable = null
__kb.factory = null
__kb.event_watcher.destroy() if __kb.event_watcher_is_owned # release the event_watcher
__kb.event_watcher = null
__kb.store.destroy() if __kb.store_is_owned # release the store
__kb.store = null
# kb.release(__kb, true) # release everything that remains
# Retrieves the value stored in a ko.observable.
#
# @see kb.Observable valueType
#
# @example
# var view_model = kb.viewModel(new Model({simple_attr: null, model_attr: null}), {factories: {model_attr: kb.ViewModel});
# kb.utils.valueType(view_model.simple_attr); // kb.TYPE_SIMPLE
# kb.utils.valueType(view_model.model_attr); // kb.TYPE_MODEL
@valueType = (observable) ->
return KB_TYPE_UNKNOWN unless observable
return observable.valueType() if observable.__kb_is_o
return KB_TYPE_COLLECTION if observable.__kb_is_co or (observable instanceof kb.Collection)
return KB_TYPE_MODEL if (observable instanceof kb.ViewModel) or (observable instanceof kb.Model)
return KB_TYPE_ARRAY if _.isArray(observable)
return KB_TYPE_SIMPLE
# Helper to join a dot-deliminated path.
#
# @param [String] path1 start path.
# @param [String] path2 append path.
# @return [String] combined dot-delimited path.
#
# @example
# kb.utils.pathJoin('models', 'name'); // 'models.name'
@pathJoin = (path1, path2) ->
return (if path1 then (if path1[path1.length-1] isnt '.' then "#{path1}." else path1) else '') + path2
# Helper to join a dot-deliminated path with the path on options and returns a new options object with the result.
#
# @param [Object] options with path property for the start path
# @param [String] path append path.
# @return [Object] new options with combined dot-delimited path `{path: combined_path}`.
#
# @example
# this.friends = kb.collectionObservable(model.get('friends'), kb.utils.optionsPathJoin(options, 'friends'));
@optionsPathJoin = (options, path) ->
return _.defaults({path: @pathJoin(options.path, path)}, options)
# Helper to find the creator constructor or function from a factory or ORM solution
@inferCreator = (value, factory, path, owner, key) ->
creator = factory.creatorForPath(value, path) if factory
return creator if creator
# try fallbacks
return null unless value
return kb.ViewModel if value instanceof kb.Model
return kb.CollectionObservable if value instanceof kb.Collection
return null
# Creates an observable based on a value's type.
@createFromDefaultCreator = (obj, options) ->
return kb.viewModel(obj, options) if obj instanceof kb.Model
return kb.collectionObservable(obj, options) if obj instanceof kb.Collection
return ko.observableArray(obj) if _.isArray(obj)
return ko.observable(obj)
# Helper to check an object for having a Model signature. For example, locale managers and ModelRef don't need to derive from Model
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.hasModelSignature(new Model());
@hasModelSignature = (obj) ->
return obj and (obj.attributes and not obj.models) and (typeof(obj.get) is 'function') and (typeof(obj.trigger) is 'function')
# Helper to check an object for having a Model signature. For example, locale managers and ModelRef don't need to derive from Model
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.hasModelSignature(new Model());
@hasCollectionSignature = (obj) ->
return obj and obj.models and (typeof(obj.get) is 'function') and (typeof(obj.trigger) is 'function')
# Helper to merge options including ViewmModel options like `keys` and `factories`
#
# @param [Object] obj the object to test
#
# @example
# kb.utils.collapseOptions(options);
@collapseOptions = _collapseOptions
# Helper to ignore dependencies in a function
#
# @param [Object] obj the object to test
#
# @example
# kb.ignore(fn);
kb.ignore = ko.dependencyDetection?.ignore or (callback, callbackTarget, callbackArgs) -> value = null; ko.dependentObservable(-> value = callback.apply(callbackTarget, callbackArgs || [])).dispose(); return value
|
[
{
"context": " are now empty.\n #\n # @access public\n # @author Chris Sauve\n # @since 0.0.1\n # @returns {String}\n # @defau",
"end": 331,
"score": 0.999886155128479,
"start": 320,
"tag": "NAME",
"value": "Chris Sauve"
},
{
"context": "opover appears.\n #\n # @access public... | spec/fixtures/parsers/coffeescript_parser_fixture_basic.coffee | docks-app/docks | 0 | defaults =
#*
# Determines what action will be taken on the original footnote markup: `"hide"` (using `display: none;`), `"delete"`, or `"ignore"` (leaves the original content in place). This action will also be taken on any elements containing the footnote if they are now empty.
#
# @access public
# @author Chris Sauve
# @since 0.0.1
# @returns {String}
# @default "hide"
actionOriginalFN : "hide"
#*
# Specifies a function to call on a footnote popover that is being instantiated (before it is added to the DOM). The function will be passed two arguments: `$popover`, which is a jQuery object containing the new popover element, and `$button`, the button that was cblicked to instantiate the popover. This option can be useful for adding additional classes or styling information before a popover appears.
#
# @access public
# @author Chris Sauve
# @since 0.0.1
# @type {Function}
# @default function() {}
activateCallback : () -> return
| 223123 | defaults =
#*
# Determines what action will be taken on the original footnote markup: `"hide"` (using `display: none;`), `"delete"`, or `"ignore"` (leaves the original content in place). This action will also be taken on any elements containing the footnote if they are now empty.
#
# @access public
# @author <NAME>
# @since 0.0.1
# @returns {String}
# @default "hide"
actionOriginalFN : "hide"
#*
# Specifies a function to call on a footnote popover that is being instantiated (before it is added to the DOM). The function will be passed two arguments: `$popover`, which is a jQuery object containing the new popover element, and `$button`, the button that was cblicked to instantiate the popover. This option can be useful for adding additional classes or styling information before a popover appears.
#
# @access public
# @author <NAME>
# @since 0.0.1
# @type {Function}
# @default function() {}
activateCallback : () -> return
| true | defaults =
#*
# Determines what action will be taken on the original footnote markup: `"hide"` (using `display: none;`), `"delete"`, or `"ignore"` (leaves the original content in place). This action will also be taken on any elements containing the footnote if they are now empty.
#
# @access public
# @author PI:NAME:<NAME>END_PI
# @since 0.0.1
# @returns {String}
# @default "hide"
actionOriginalFN : "hide"
#*
# Specifies a function to call on a footnote popover that is being instantiated (before it is added to the DOM). The function will be passed two arguments: `$popover`, which is a jQuery object containing the new popover element, and `$button`, the button that was cblicked to instantiate the popover. This option can be useful for adding additional classes or styling information before a popover appears.
#
# @access public
# @author PI:NAME:<NAME>END_PI
# @since 0.0.1
# @type {Function}
# @default function() {}
activateCallback : () -> return
|
[
{
"context": "r\n routes: [\n {\n path: '/',\n name: 'HelloWorld',\n component: HelloWorld\n }\n ]\n",
"end": 205,
"score": 0.899671733379364,
"start": 195,
"tag": "NAME",
"value": "HelloWorld"
}
] | template/src/router/index.coffee | thisredone/vue-phaser3-coffee | 0 | import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
| 214901 | import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router
routes: [
{
path: '/',
name: '<NAME>',
component: HelloWorld
}
]
| true | import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router
routes: [
{
path: '/',
name: 'PI:NAME:<NAME>END_PI',
component: HelloWorld
}
]
|
[
{
"context": " (see `tools/nogexecd/`) is running as user\n# `nogexecbot1` and continuously polls for work. When the daemo",
"end": 779,
"score": 0.9960254430770874,
"start": 768,
"tag": "USERNAME",
"value": "nogexecbot1"
},
{
"context": "b server.\n\nensureBotUser = ->\n sel = ... | apps/nog-app/meteor/server/nog-exec-server.coffee | nogproject/nog | 0 | # `nog-exec` implements a job execution service.
#
# Jobs are managed using the Meteor package `vsivsi:job-collection`. Each job
# has a job-collection doc `job` with an `_id`. It also has a nog `jobId`,
# which is created by `nog-flow` and stored in the `job.data.jobId`.
#
# Each job is run only once to completion, failure, or cancellation. Jobs are
# not restarted. If a job gets lost, a new job must be started.
#
# A job is processed as follows:
#
# - `nog-flow` calls `NogExec.submit()` to create a job. `submit()` creates a
# scoped access key for the job, so that the job can act as the user who
# started the job.
#
# - job-collection promotes the job to ready.
#
# - A worker daemon `nogexecd` (see `tools/nogexecd/`) is running as user
# `nogexecbot1` and continuously polls for work. When the daemon takes
# work, the job status is changed to `running`.
#
# - The worker daemon executes `exec-job` to run the job. `exec-job` runs
# with the scoped access key, so that it can act on behalf of the user who
# started the job. `exec-job` is started as a sub-process for testing and
# via slurm for production.
#
# - The program performs the work and reports progress via `POST
# /jobs/:jobId/status`.
#
# - `exec-job` reports the job as `completed` or `failed` via `POST
# /jobs/:jobId/status`, which deletes the scoped access key.
#
# The job status is published to the client, which implements a status UI.
#
# Nog bots use a custom login mechanism (see below) that is based on API keys.
# Admins can manage `nogexecbot*` API keys via the admin UI.
#
# Runtime parameters such as time limits are maintained in the meta field
# `meta.runtime`. The nog-flow method `addProgram()` initializes `runtime`
# from the base program. The user can modify `runtime` via the GUI (similar to
# `params`). `runtime` is copied to the job, so that it is directly available
# during job handling, specifically in `cleanupLostJobs()`
#
# Open questions:
#
# - Final removal of jobs is not yet implemented.
{
testAccess
checkAccess
} = NogAccess
{
ERR_UNKNOWN
ERR_PARAM_INVALID
nogthrow
} = NogError
AA_UPDATE_JOB = 'nog-exec/update-job'
AA_GET_JOB = 'nog-exec/get-job'
AA_SUBS_JOB_STATUS = 'nog-exec/subs-job-status'
AA_EXEC_WORK = 'nog-exec/worker'
config =
cleanupInterval_s: 5 * 60
optGlobalReadOnly = Meteor.settings.optGlobalReadOnly
# Enable job-collection processing:
#
# - Ensure that a bot user is present.
# - Add access statement that allows nogexebots to exec work.
# - Add access statement that allows admins to manage bot keys.
# - Start the job server.
ensureBotUser = ->
sel = {username: 'nogexecbot1'}
Meteor.users.upsert sel, {$set: sel}
bot = Meteor.users.findOne(sel)
Roles.addUsersToRoles bot, ['nogexecbots']
if optGlobalReadOnly
console.log('[exec] [GRO] Skipping ensure bot user in read-only mode.')
else
Meteor.startup ensureBotUser
NogAccess.addStatement
principal: 'role:nogexecbots'
action: AA_EXEC_WORK
effect: 'allow'
NogAccess.addStatement
principal: 'role:admins'
action: 'nog-auth/apiKey'
effect: (opts) ->
{keyOwnerId} = opts
unless keyOwnerId?
return 'deny' # Should not happen. Better be defensive.
owner = Meteor.users.findOne opts.keyOwnerId, {fields: {username: 1}}
unless owner?
return 'ignore' # Missing owner will be handled later.
if owner.username.match /^nog.*bot/
'allow'
else
'ignore'
NogExec.jobs.allow
worker: (userId, method, params) ->
aopts = {method, params}
testAccess userId, AA_EXEC_WORK, aopts
if optGlobalReadOnly
console.log('[exec] [GRO] Exec job server disabled in read-only mode.')
else
Meteor.startup ->
NogExec.jobs.startJobServer()
# Publish the jobs status to job owners.
NogAccess.addStatement
principal: 'role:users'
action: AA_SUBS_JOB_STATUS
effect: 'allow'
Meteor.publish 'jobStatus', (jobIds) ->
check jobIds, [String]
if not (user = Meteor.users.findOne @userId)?
return null
unless testAccess user, AA_SUBS_JOB_STATUS
@ready()
return null
NogExec.jobs.find {
'data.jobId': {$in: jobIds}
'data.ownerId': user._id
}, {
fields: {
'data.jobId': 1, 'data.ownerId': 1, 'data.workspaceRepo': 1,
'updated': 1, 'created': 1, 'status': 1, 'progress': 1,
'failures': 1, 'log': 1
}
}
# `NogExec.submit()` creates a new job with a scoped access key and submits it
# to the job-collection queue.
@NogExec.submit = (opts) ->
{jobId, ownerId, ownerName, repoName, commitId, runtime} = opts
jobdoc = {
jobId
ownerId
workspaceRepo: ownerName + '/' + repoName
commitId
runtime
}
jobdoc.key = NogAuth.createKeySudo {
keyOwnerId: ownerId
comment: """
Allow job #{jobId} to modify #{jobdoc.workspaceRepo}.
"""
scopes: [
{action: 'nog-content/get', opts: {ownerName, repoName}}
{action: 'nog-content/modify', opts: {ownerName, repoName}}
{action: 'nog-blob/download', opts: {ownerName, repoName}}
{action: 'nog-blob/upload', opts: {}}
{action: AA_UPDATE_JOB, opts: {jobId}}
{action: 'nog-auth/apiKey', opts: {keyOwnerId: ownerId}}
]
}
job = new Job NogExec.jobs, 'run', jobdoc
job.save()
# `job.log()` requires job-collection@1.2.1, so that it works when the job is
# not running.
cleanupLostJobs = ->
cutoff = new Date()
cutoff.setSeconds(cutoff.getSeconds() - config.cleanupInterval_s)
cursor = NogExec.jobs.find {
status: {$nin: ['completed', 'failed', 'cancelled']}
updated: {$lt: cutoff}
}
cursor.map (jobdoc) ->
job = new Job NogExec.jobs, jobdoc
now = new Date()
{maxTotalDuration_s, maxHeartbeatInterval_s} = jobdoc.data.runtime
if (now - jobdoc.created) > maxTotalDuration_s * 1000
job.log "
Canceled after total running time exceeded #{maxTotalDuration_s}
seconds (runtime.maxTotalDuration_s)
"
else if (now - jobdoc.updated) > maxHeartbeatInterval_s * 1000
job.log "
Canceled after lack of progress for more than #{maxHeartbeatInterval_s}
seconds (runtime.maxHeartbeatInterval_s)
"
else
return
job.cancel()
if (keyid = job.data.key?.keyid)?
NogAuth.deleteKeySudo {
keyid, keyOwnerId: job.data.ownerId
}
Meteor.setInterval cleanupLostJobs, config.cleanupInterval_s * 1000
# `nogjobd` uses this special login mechanism to authenticate: any valid signed
# request will be accepted. The convention is to use `GET /ddplogin`.
#
# Connection tokens cannot be disabled, since Meteor immediately closes
# connections without them.
Accounts.registerLoginHandler 'nogauthv1', (req) ->
unless (req = req.nogauthreq)?
return
NogAuth.checkRequestAuth req
unless (user = req.auth.user)?
return
userId = user._id
{userId}
# API to jobs and related access statements:
#
# - `nogexecbots` are allowed to update any job.
# - Users are allows to query and update their own jobs.
# - Job collection ids and nog job ids are both accepted.
# - Progress reporting and status changes are managed through a single POST
# route.
NogAccess.addStatement
principal: 'role:nogexecbots'
action: AA_UPDATE_JOB
effect: 'allow'
NogAccess.addStatement
principal: 'role:users'
action: AA_UPDATE_JOB
effect: (opts) ->
unless opts.job? and opts.user?
return 'ignore'
if opts.job.data.ownerId == opts.user._id
return 'allow'
else
return 'ignore'
NogAccess.addStatement
principal: 'role:users'
action: AA_GET_JOB
effect: (opts) ->
unless opts.job? and opts.user?
return 'ignore'
if opts.job.data.ownerId == opts.user._id
return 'allow'
else
return 'ignore'
# `matchProgress({completed, total})` requires non-negative values with
# `completed <= total`.
matchProgress = Match.Where (x) ->
check x, {completed: Number, total: Number}
unless x.completed >= 0
throw new Match.Error '`completed` must be non-negative'
unless x.total >= 0
throw new Match.Error '`total` must be non-negative'
unless x.total >= x.completed
throw new Match.Error '`total` must be greater equal `completed`'
true
matchLogLevel = Match.Where (x) ->
check x, String
levels = ['info', 'success', 'warning', 'danger']
unless x in levels
throw new Match.Error 'Invalid log level.'
true
# `findJob()` accepts either type of job id. It checks access and returns both
# types of ids together with the job doc.
findJob = (req) ->
{jobId} = req.params
if (job = NogExec.jobs.findOne(jobId))?
execJobId = jobId
jobId = job.data.jobId
else if (job = NogExec.jobs.findOne({'data.jobId': jobId}))?
execJobId = job._id
aopts = {job, jobId}
checkAccess req.auth?.user, AA_UPDATE_JOB, aopts
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
unless job.retried == req.body.retryId
nogthrow ERR_UNKNOWN, {reason: "`retryId` mismatch."}
return {jobId, execJobId, job}
post_job_status = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
status: String
reason: Match.Optional String
{job} = findJob req
unless job.status == 'running'
nogthrow ERR_PARAM_INVALID, {reason: 'Job is not running.'}
qjob = new Job(NogExec.jobs, job)
{status, progress, reason} = req.body
switch status
when 'completed'
qjob.done()
when 'failed'
reason ?= 'Unknown reason.'
qjob.fail({reason})
else
nogthrow ERR_PARAM_INVALID, {
reason: "Unknown status value `#{status}`."
}
if (keyid = qjob.data.key?.keyid)?
NogAuth.deleteKey req.auth?.user, {
keyid, keyOwnerId: qjob.data.ownerId
}
return {}
post_job_progress = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
progress: matchProgress
{job} = findJob req
unless job.status == 'running'
nogthrow ERR_PARAM_INVALID, {reason: 'Job is not running.'}
qjob = new Job(NogExec.jobs, job)
{progress} = req.body
qjob.progress(progress.completed, progress.total)
return {}
post_job_log = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
message: String
level: Match.Optional matchLogLevel
{job} = findJob req
qjob = new Job(NogExec.jobs, job)
{message, level} = req.body
level ?= 'info'
qjob.log message, {level}
return {}
# `get_job_status()` does not use `findJob()`, because `retryId` is not
# available. Instead, it returns status/progress of the job with the greatest
# `retryId`.
get_job_status = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
{jobId} = req.params
job = NogExec.jobs.findOne {'data.jobId': jobId}, {'sort': {'retried': -1}}
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
aopts = {job, jobId}
checkAccess req.auth?.user, AA_GET_JOB, aopts
status = job.status
return {status}
get_job_progress = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
{jobId} = req.params
job = NogExec.jobs.findOne {'data.jobId': jobId}, {'sort': {'retried': -1}}
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
aopts = {job, jobId}
checkAccess req.auth?.user, AA_GET_JOB, aopts
progress = job.progress
return {progress}
actions = [
{
method: 'POST'
path: '/:jobId/status'
action: post_job_status
}
{
method: 'POST'
path: '/:jobId/progress'
action: post_job_progress
}
{
method: 'POST'
path: '/:jobId/log'
action: post_job_log
}
{
method: 'GET'
path: '/:jobId/status'
action: get_job_status
}
{
method: 'GET'
path: '/:jobId/progress'
action: get_job_progress
}
]
NogRest.actions '/api/jobs', actions
NogRest.actions '/api/v0/jobs', actions
NogRest.actions '/api/v1/jobs', actions
| 217957 | # `nog-exec` implements a job execution service.
#
# Jobs are managed using the Meteor package `vsivsi:job-collection`. Each job
# has a job-collection doc `job` with an `_id`. It also has a nog `jobId`,
# which is created by `nog-flow` and stored in the `job.data.jobId`.
#
# Each job is run only once to completion, failure, or cancellation. Jobs are
# not restarted. If a job gets lost, a new job must be started.
#
# A job is processed as follows:
#
# - `nog-flow` calls `NogExec.submit()` to create a job. `submit()` creates a
# scoped access key for the job, so that the job can act as the user who
# started the job.
#
# - job-collection promotes the job to ready.
#
# - A worker daemon `nogexecd` (see `tools/nogexecd/`) is running as user
# `nogexecbot1` and continuously polls for work. When the daemon takes
# work, the job status is changed to `running`.
#
# - The worker daemon executes `exec-job` to run the job. `exec-job` runs
# with the scoped access key, so that it can act on behalf of the user who
# started the job. `exec-job` is started as a sub-process for testing and
# via slurm for production.
#
# - The program performs the work and reports progress via `POST
# /jobs/:jobId/status`.
#
# - `exec-job` reports the job as `completed` or `failed` via `POST
# /jobs/:jobId/status`, which deletes the scoped access key.
#
# The job status is published to the client, which implements a status UI.
#
# Nog bots use a custom login mechanism (see below) that is based on API keys.
# Admins can manage `nogexecbot*` API keys via the admin UI.
#
# Runtime parameters such as time limits are maintained in the meta field
# `meta.runtime`. The nog-flow method `addProgram()` initializes `runtime`
# from the base program. The user can modify `runtime` via the GUI (similar to
# `params`). `runtime` is copied to the job, so that it is directly available
# during job handling, specifically in `cleanupLostJobs()`
#
# Open questions:
#
# - Final removal of jobs is not yet implemented.
{
testAccess
checkAccess
} = NogAccess
{
ERR_UNKNOWN
ERR_PARAM_INVALID
nogthrow
} = NogError
AA_UPDATE_JOB = 'nog-exec/update-job'
AA_GET_JOB = 'nog-exec/get-job'
AA_SUBS_JOB_STATUS = 'nog-exec/subs-job-status'
AA_EXEC_WORK = 'nog-exec/worker'
config =
cleanupInterval_s: 5 * 60
optGlobalReadOnly = Meteor.settings.optGlobalReadOnly
# Enable job-collection processing:
#
# - Ensure that a bot user is present.
# - Add access statement that allows nogexebots to exec work.
# - Add access statement that allows admins to manage bot keys.
# - Start the job server.
ensureBotUser = ->
sel = {username: 'nogexecbot1'}
Meteor.users.upsert sel, {$set: sel}
bot = Meteor.users.findOne(sel)
Roles.addUsersToRoles bot, ['nogexecbots']
if optGlobalReadOnly
console.log('[exec] [GRO] Skipping ensure bot user in read-only mode.')
else
Meteor.startup ensureBotUser
NogAccess.addStatement
principal: 'role:nogexecbots'
action: AA_EXEC_WORK
effect: 'allow'
NogAccess.addStatement
principal: 'role:admins'
action: 'nog-auth/apiKey'
effect: (opts) ->
{keyOwnerId} = opts
unless keyOwnerId?
return 'deny' # Should not happen. Better be defensive.
owner = Meteor.users.findOne opts.keyOwnerId, {fields: {username: 1}}
unless owner?
return 'ignore' # Missing owner will be handled later.
if owner.username.match /^nog.*bot/
'allow'
else
'ignore'
NogExec.jobs.allow
worker: (userId, method, params) ->
aopts = {method, params}
testAccess userId, AA_EXEC_WORK, aopts
if optGlobalReadOnly
console.log('[exec] [GRO] Exec job server disabled in read-only mode.')
else
Meteor.startup ->
NogExec.jobs.startJobServer()
# Publish the jobs status to job owners.
NogAccess.addStatement
principal: 'role:users'
action: AA_SUBS_JOB_STATUS
effect: 'allow'
Meteor.publish 'jobStatus', (jobIds) ->
check jobIds, [String]
if not (user = Meteor.users.findOne @userId)?
return null
unless testAccess user, AA_SUBS_JOB_STATUS
@ready()
return null
NogExec.jobs.find {
'data.jobId': {$in: jobIds}
'data.ownerId': user._id
}, {
fields: {
'data.jobId': 1, 'data.ownerId': 1, 'data.workspaceRepo': 1,
'updated': 1, 'created': 1, 'status': 1, 'progress': 1,
'failures': 1, 'log': 1
}
}
# `NogExec.submit()` creates a new job with a scoped access key and submits it
# to the job-collection queue.
@NogExec.submit = (opts) ->
{jobId, ownerId, ownerName, repoName, commitId, runtime} = opts
jobdoc = {
jobId
ownerId
workspaceRepo: ownerName + '/' + repoName
commitId
runtime
}
jobdoc.key = <KEY>KeyS<KEY> {
keyOwnerId: ownerId
comment: """
Allow job #{jobId} to modify #{jobdoc.workspaceRepo}.
"""
scopes: [
{action: 'nog-content/get', opts: {ownerName, repoName}}
{action: 'nog-content/modify', opts: {ownerName, repoName}}
{action: 'nog-blob/download', opts: {ownerName, repoName}}
{action: 'nog-blob/upload', opts: {}}
{action: AA_UPDATE_JOB, opts: {jobId}}
{action: 'nog-auth/apiKey', opts: {keyOwnerId: ownerId}}
]
}
job = new Job NogExec.jobs, 'run', jobdoc
job.save()
# `job.log()` requires job-collection@1.2.1, so that it works when the job is
# not running.
cleanupLostJobs = ->
cutoff = new Date()
cutoff.setSeconds(cutoff.getSeconds() - config.cleanupInterval_s)
cursor = NogExec.jobs.find {
status: {$nin: ['completed', 'failed', 'cancelled']}
updated: {$lt: cutoff}
}
cursor.map (jobdoc) ->
job = new Job NogExec.jobs, jobdoc
now = new Date()
{maxTotalDuration_s, maxHeartbeatInterval_s} = jobdoc.data.runtime
if (now - jobdoc.created) > maxTotalDuration_s * 1000
job.log "
Canceled after total running time exceeded #{maxTotalDuration_s}
seconds (runtime.maxTotalDuration_s)
"
else if (now - jobdoc.updated) > maxHeartbeatInterval_s * 1000
job.log "
Canceled after lack of progress for more than #{maxHeartbeatInterval_s}
seconds (runtime.maxHeartbeatInterval_s)
"
else
return
job.cancel()
if (keyid = job.data.key?.keyid)?
NogAuth.deleteKeySudo {
keyid, keyOwnerId: job.data.ownerId
}
Meteor.setInterval cleanupLostJobs, config.cleanupInterval_s * 1000
# `nogjobd` uses this special login mechanism to authenticate: any valid signed
# request will be accepted. The convention is to use `GET /ddplogin`.
#
# Connection tokens cannot be disabled, since Meteor immediately closes
# connections without them.
Accounts.registerLoginHandler 'nogauthv1', (req) ->
unless (req = req.nogauthreq)?
return
NogAuth.checkRequestAuth req
unless (user = req.auth.user)?
return
userId = user._id
{userId}
# API to jobs and related access statements:
#
# - `nogexecbots` are allowed to update any job.
# - Users are allows to query and update their own jobs.
# - Job collection ids and nog job ids are both accepted.
# - Progress reporting and status changes are managed through a single POST
# route.
NogAccess.addStatement
principal: 'role:nogexecbots'
action: AA_UPDATE_JOB
effect: 'allow'
NogAccess.addStatement
principal: 'role:users'
action: AA_UPDATE_JOB
effect: (opts) ->
unless opts.job? and opts.user?
return 'ignore'
if opts.job.data.ownerId == opts.user._id
return 'allow'
else
return 'ignore'
NogAccess.addStatement
principal: 'role:users'
action: AA_GET_JOB
effect: (opts) ->
unless opts.job? and opts.user?
return 'ignore'
if opts.job.data.ownerId == opts.user._id
return 'allow'
else
return 'ignore'
# `matchProgress({completed, total})` requires non-negative values with
# `completed <= total`.
matchProgress = Match.Where (x) ->
check x, {completed: Number, total: Number}
unless x.completed >= 0
throw new Match.Error '`completed` must be non-negative'
unless x.total >= 0
throw new Match.Error '`total` must be non-negative'
unless x.total >= x.completed
throw new Match.Error '`total` must be greater equal `completed`'
true
matchLogLevel = Match.Where (x) ->
check x, String
levels = ['info', 'success', 'warning', 'danger']
unless x in levels
throw new Match.Error 'Invalid log level.'
true
# `findJob()` accepts either type of job id. It checks access and returns both
# types of ids together with the job doc.
findJob = (req) ->
{jobId} = req.params
if (job = NogExec.jobs.findOne(jobId))?
execJobId = jobId
jobId = job.data.jobId
else if (job = NogExec.jobs.findOne({'data.jobId': jobId}))?
execJobId = job._id
aopts = {job, jobId}
checkAccess req.auth?.user, AA_UPDATE_JOB, aopts
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
unless job.retried == req.body.retryId
nogthrow ERR_UNKNOWN, {reason: "`retryId` mismatch."}
return {jobId, execJobId, job}
post_job_status = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
status: String
reason: Match.Optional String
{job} = findJob req
unless job.status == 'running'
nogthrow ERR_PARAM_INVALID, {reason: 'Job is not running.'}
qjob = new Job(NogExec.jobs, job)
{status, progress, reason} = req.body
switch status
when 'completed'
qjob.done()
when 'failed'
reason ?= 'Unknown reason.'
qjob.fail({reason})
else
nogthrow ERR_PARAM_INVALID, {
reason: "Unknown status value `#{status}`."
}
if (keyid = qjob.data.key?.keyid)?
NogAuth.deleteKey req.auth?.user, {
keyid, keyOwnerId: qjob.data.ownerId
}
return {}
post_job_progress = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
progress: matchProgress
{job} = findJob req
unless job.status == 'running'
nogthrow ERR_PARAM_INVALID, {reason: 'Job is not running.'}
qjob = new Job(NogExec.jobs, job)
{progress} = req.body
qjob.progress(progress.completed, progress.total)
return {}
post_job_log = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
message: String
level: Match.Optional matchLogLevel
{job} = findJob req
qjob = new Job(NogExec.jobs, job)
{message, level} = req.body
level ?= 'info'
qjob.log message, {level}
return {}
# `get_job_status()` does not use `findJob()`, because `retryId` is not
# available. Instead, it returns status/progress of the job with the greatest
# `retryId`.
get_job_status = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
{jobId} = req.params
job = NogExec.jobs.findOne {'data.jobId': jobId}, {'sort': {'retried': -1}}
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
aopts = {job, jobId}
checkAccess req.auth?.user, AA_GET_JOB, aopts
status = job.status
return {status}
get_job_progress = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
{jobId} = req.params
job = NogExec.jobs.findOne {'data.jobId': jobId}, {'sort': {'retried': -1}}
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
aopts = {job, jobId}
checkAccess req.auth?.user, AA_GET_JOB, aopts
progress = job.progress
return {progress}
actions = [
{
method: 'POST'
path: '/:jobId/status'
action: post_job_status
}
{
method: 'POST'
path: '/:jobId/progress'
action: post_job_progress
}
{
method: 'POST'
path: '/:jobId/log'
action: post_job_log
}
{
method: 'GET'
path: '/:jobId/status'
action: get_job_status
}
{
method: 'GET'
path: '/:jobId/progress'
action: get_job_progress
}
]
NogRest.actions '/api/jobs', actions
NogRest.actions '/api/v0/jobs', actions
NogRest.actions '/api/v1/jobs', actions
| true | # `nog-exec` implements a job execution service.
#
# Jobs are managed using the Meteor package `vsivsi:job-collection`. Each job
# has a job-collection doc `job` with an `_id`. It also has a nog `jobId`,
# which is created by `nog-flow` and stored in the `job.data.jobId`.
#
# Each job is run only once to completion, failure, or cancellation. Jobs are
# not restarted. If a job gets lost, a new job must be started.
#
# A job is processed as follows:
#
# - `nog-flow` calls `NogExec.submit()` to create a job. `submit()` creates a
# scoped access key for the job, so that the job can act as the user who
# started the job.
#
# - job-collection promotes the job to ready.
#
# - A worker daemon `nogexecd` (see `tools/nogexecd/`) is running as user
# `nogexecbot1` and continuously polls for work. When the daemon takes
# work, the job status is changed to `running`.
#
# - The worker daemon executes `exec-job` to run the job. `exec-job` runs
# with the scoped access key, so that it can act on behalf of the user who
# started the job. `exec-job` is started as a sub-process for testing and
# via slurm for production.
#
# - The program performs the work and reports progress via `POST
# /jobs/:jobId/status`.
#
# - `exec-job` reports the job as `completed` or `failed` via `POST
# /jobs/:jobId/status`, which deletes the scoped access key.
#
# The job status is published to the client, which implements a status UI.
#
# Nog bots use a custom login mechanism (see below) that is based on API keys.
# Admins can manage `nogexecbot*` API keys via the admin UI.
#
# Runtime parameters such as time limits are maintained in the meta field
# `meta.runtime`. The nog-flow method `addProgram()` initializes `runtime`
# from the base program. The user can modify `runtime` via the GUI (similar to
# `params`). `runtime` is copied to the job, so that it is directly available
# during job handling, specifically in `cleanupLostJobs()`
#
# Open questions:
#
# - Final removal of jobs is not yet implemented.
{
testAccess
checkAccess
} = NogAccess
{
ERR_UNKNOWN
ERR_PARAM_INVALID
nogthrow
} = NogError
AA_UPDATE_JOB = 'nog-exec/update-job'
AA_GET_JOB = 'nog-exec/get-job'
AA_SUBS_JOB_STATUS = 'nog-exec/subs-job-status'
AA_EXEC_WORK = 'nog-exec/worker'
config =
cleanupInterval_s: 5 * 60
optGlobalReadOnly = Meteor.settings.optGlobalReadOnly
# Enable job-collection processing:
#
# - Ensure that a bot user is present.
# - Add access statement that allows nogexebots to exec work.
# - Add access statement that allows admins to manage bot keys.
# - Start the job server.
ensureBotUser = ->
sel = {username: 'nogexecbot1'}
Meteor.users.upsert sel, {$set: sel}
bot = Meteor.users.findOne(sel)
Roles.addUsersToRoles bot, ['nogexecbots']
if optGlobalReadOnly
console.log('[exec] [GRO] Skipping ensure bot user in read-only mode.')
else
Meteor.startup ensureBotUser
NogAccess.addStatement
principal: 'role:nogexecbots'
action: AA_EXEC_WORK
effect: 'allow'
NogAccess.addStatement
principal: 'role:admins'
action: 'nog-auth/apiKey'
effect: (opts) ->
{keyOwnerId} = opts
unless keyOwnerId?
return 'deny' # Should not happen. Better be defensive.
owner = Meteor.users.findOne opts.keyOwnerId, {fields: {username: 1}}
unless owner?
return 'ignore' # Missing owner will be handled later.
if owner.username.match /^nog.*bot/
'allow'
else
'ignore'
NogExec.jobs.allow
worker: (userId, method, params) ->
aopts = {method, params}
testAccess userId, AA_EXEC_WORK, aopts
if optGlobalReadOnly
console.log('[exec] [GRO] Exec job server disabled in read-only mode.')
else
Meteor.startup ->
NogExec.jobs.startJobServer()
# Publish the jobs status to job owners.
NogAccess.addStatement
principal: 'role:users'
action: AA_SUBS_JOB_STATUS
effect: 'allow'
Meteor.publish 'jobStatus', (jobIds) ->
check jobIds, [String]
if not (user = Meteor.users.findOne @userId)?
return null
unless testAccess user, AA_SUBS_JOB_STATUS
@ready()
return null
NogExec.jobs.find {
'data.jobId': {$in: jobIds}
'data.ownerId': user._id
}, {
fields: {
'data.jobId': 1, 'data.ownerId': 1, 'data.workspaceRepo': 1,
'updated': 1, 'created': 1, 'status': 1, 'progress': 1,
'failures': 1, 'log': 1
}
}
# `NogExec.submit()` creates a new job with a scoped access key and submits it
# to the job-collection queue.
@NogExec.submit = (opts) ->
{jobId, ownerId, ownerName, repoName, commitId, runtime} = opts
jobdoc = {
jobId
ownerId
workspaceRepo: ownerName + '/' + repoName
commitId
runtime
}
jobdoc.key = PI:KEY:<KEY>END_PIKeySPI:KEY:<KEY>END_PI {
keyOwnerId: ownerId
comment: """
Allow job #{jobId} to modify #{jobdoc.workspaceRepo}.
"""
scopes: [
{action: 'nog-content/get', opts: {ownerName, repoName}}
{action: 'nog-content/modify', opts: {ownerName, repoName}}
{action: 'nog-blob/download', opts: {ownerName, repoName}}
{action: 'nog-blob/upload', opts: {}}
{action: AA_UPDATE_JOB, opts: {jobId}}
{action: 'nog-auth/apiKey', opts: {keyOwnerId: ownerId}}
]
}
job = new Job NogExec.jobs, 'run', jobdoc
job.save()
# `job.log()` requires job-collection@1.2.1, so that it works when the job is
# not running.
cleanupLostJobs = ->
cutoff = new Date()
cutoff.setSeconds(cutoff.getSeconds() - config.cleanupInterval_s)
cursor = NogExec.jobs.find {
status: {$nin: ['completed', 'failed', 'cancelled']}
updated: {$lt: cutoff}
}
cursor.map (jobdoc) ->
job = new Job NogExec.jobs, jobdoc
now = new Date()
{maxTotalDuration_s, maxHeartbeatInterval_s} = jobdoc.data.runtime
if (now - jobdoc.created) > maxTotalDuration_s * 1000
job.log "
Canceled after total running time exceeded #{maxTotalDuration_s}
seconds (runtime.maxTotalDuration_s)
"
else if (now - jobdoc.updated) > maxHeartbeatInterval_s * 1000
job.log "
Canceled after lack of progress for more than #{maxHeartbeatInterval_s}
seconds (runtime.maxHeartbeatInterval_s)
"
else
return
job.cancel()
if (keyid = job.data.key?.keyid)?
NogAuth.deleteKeySudo {
keyid, keyOwnerId: job.data.ownerId
}
Meteor.setInterval cleanupLostJobs, config.cleanupInterval_s * 1000
# `nogjobd` uses this special login mechanism to authenticate: any valid signed
# request will be accepted. The convention is to use `GET /ddplogin`.
#
# Connection tokens cannot be disabled, since Meteor immediately closes
# connections without them.
Accounts.registerLoginHandler 'nogauthv1', (req) ->
unless (req = req.nogauthreq)?
return
NogAuth.checkRequestAuth req
unless (user = req.auth.user)?
return
userId = user._id
{userId}
# API to jobs and related access statements:
#
# - `nogexecbots` are allowed to update any job.
# - Users are allows to query and update their own jobs.
# - Job collection ids and nog job ids are both accepted.
# - Progress reporting and status changes are managed through a single POST
# route.
NogAccess.addStatement
principal: 'role:nogexecbots'
action: AA_UPDATE_JOB
effect: 'allow'
NogAccess.addStatement
principal: 'role:users'
action: AA_UPDATE_JOB
effect: (opts) ->
unless opts.job? and opts.user?
return 'ignore'
if opts.job.data.ownerId == opts.user._id
return 'allow'
else
return 'ignore'
NogAccess.addStatement
principal: 'role:users'
action: AA_GET_JOB
effect: (opts) ->
unless opts.job? and opts.user?
return 'ignore'
if opts.job.data.ownerId == opts.user._id
return 'allow'
else
return 'ignore'
# `matchProgress({completed, total})` requires non-negative values with
# `completed <= total`.
matchProgress = Match.Where (x) ->
check x, {completed: Number, total: Number}
unless x.completed >= 0
throw new Match.Error '`completed` must be non-negative'
unless x.total >= 0
throw new Match.Error '`total` must be non-negative'
unless x.total >= x.completed
throw new Match.Error '`total` must be greater equal `completed`'
true
matchLogLevel = Match.Where (x) ->
check x, String
levels = ['info', 'success', 'warning', 'danger']
unless x in levels
throw new Match.Error 'Invalid log level.'
true
# `findJob()` accepts either type of job id. It checks access and returns both
# types of ids together with the job doc.
findJob = (req) ->
{jobId} = req.params
if (job = NogExec.jobs.findOne(jobId))?
execJobId = jobId
jobId = job.data.jobId
else if (job = NogExec.jobs.findOne({'data.jobId': jobId}))?
execJobId = job._id
aopts = {job, jobId}
checkAccess req.auth?.user, AA_UPDATE_JOB, aopts
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
unless job.retried == req.body.retryId
nogthrow ERR_UNKNOWN, {reason: "`retryId` mismatch."}
return {jobId, execJobId, job}
post_job_status = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
status: String
reason: Match.Optional String
{job} = findJob req
unless job.status == 'running'
nogthrow ERR_PARAM_INVALID, {reason: 'Job is not running.'}
qjob = new Job(NogExec.jobs, job)
{status, progress, reason} = req.body
switch status
when 'completed'
qjob.done()
when 'failed'
reason ?= 'Unknown reason.'
qjob.fail({reason})
else
nogthrow ERR_PARAM_INVALID, {
reason: "Unknown status value `#{status}`."
}
if (keyid = qjob.data.key?.keyid)?
NogAuth.deleteKey req.auth?.user, {
keyid, keyOwnerId: qjob.data.ownerId
}
return {}
post_job_progress = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
progress: matchProgress
{job} = findJob req
unless job.status == 'running'
nogthrow ERR_PARAM_INVALID, {reason: 'Job is not running.'}
qjob = new Job(NogExec.jobs, job)
{progress} = req.body
qjob.progress(progress.completed, progress.total)
return {}
post_job_log = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
check req.body,
retryId: Number
message: String
level: Match.Optional matchLogLevel
{job} = findJob req
qjob = new Job(NogExec.jobs, job)
{message, level} = req.body
level ?= 'info'
qjob.log message, {level}
return {}
# `get_job_status()` does not use `findJob()`, because `retryId` is not
# available. Instead, it returns status/progress of the job with the greatest
# `retryId`.
get_job_status = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
{jobId} = req.params
job = NogExec.jobs.findOne {'data.jobId': jobId}, {'sort': {'retried': -1}}
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
aopts = {job, jobId}
checkAccess req.auth?.user, AA_GET_JOB, aopts
status = job.status
return {status}
get_job_progress = (req) ->
check req.params, Match.ObjectIncluding {jobId: String}
{jobId} = req.params
job = NogExec.jobs.findOne {'data.jobId': jobId}, {'sort': {'retried': -1}}
unless job?
nogthrow ERR_UNKNOWN, {reason: "Unknown job id #{jobId}."}
aopts = {job, jobId}
checkAccess req.auth?.user, AA_GET_JOB, aopts
progress = job.progress
return {progress}
actions = [
{
method: 'POST'
path: '/:jobId/status'
action: post_job_status
}
{
method: 'POST'
path: '/:jobId/progress'
action: post_job_progress
}
{
method: 'POST'
path: '/:jobId/log'
action: post_job_log
}
{
method: 'GET'
path: '/:jobId/status'
action: get_job_status
}
{
method: 'GET'
path: '/:jobId/progress'
action: get_job_progress
}
]
NogRest.actions '/api/jobs', actions
NogRest.actions '/api/v0/jobs', actions
NogRest.actions '/api/v1/jobs', actions
|
[
{
"context": "# Droplet C# mode\n#\n# Copyright (c) 2018 Kevin Jessup\n# MIT License\n\nhelper = require '../helper.coffee",
"end": 53,
"score": 0.9998173713684082,
"start": 41,
"tag": "NAME",
"value": "Kevin Jessup"
}
] | src/languages/csharp.coffee | sanyaade-teachings/spresensedroplet | 3 | # Droplet C# mode
#
# Copyright (c) 2018 Kevin Jessup
# MIT License
helper = require '../helper.coffee'
parser = require '../parser.coffee'
antlrHelper = require '../antlr.coffee'
model = require '../model.coffee'
{fixQuotedString, looseCUnescape, quoteAndCEscape} = helper
ADD_BUTTON = [
{
key: 'add-button'
glyph: '\u25B6'
border: false
}
]
SUBTRACT_BUTTON = [
{
key: 'subtract-button'
glyph: '\u25C0'
border: false
}
]
BOTH_BUTTON = [
{
key: 'subtract-button'
glyph: '\u25C0'
border: false
}
{
key: 'add-button'
glyph: '\u25B6'
border: false
}
]
ADD_BUTTON_VERT = [
{
key: 'add-button'
glyph: '\u25BC'
border: false
}
]
BOTH_BUTTON_VERT = [
{
key: 'subtract-button'
glyph: '\u25B2'
border: false
}
{
key: 'add-button'
glyph: '\u25BC'
border: false
}
]
RULES = {
# tell model to indent blocks within the main part of a n
# namespace body (indent everything past namespace_member_declarations)
'namespace_body': {
'type': 'indent',
'indexContext': 'namespace_member_declarations',
},
'class_body': {
'type': 'indent',
'indexContext': 'class_member_declarations',
},
'block': {
'type' : 'indent',
'indexContext': 'statement_list',
},
# Skips : no block for these elements
'compilationUnit' : 'skip',
'using_directives' : 'skip',
'namespace_or_type_name' : 'skip',
'namespace_member_declarations' : 'skip',
'namespace_member_declaration' : 'skip',
'class_definition' : 'skip',
'class_member_declarations' : 'skip',
'common_member_declaration' : 'skip',
'constructor_declaration' : 'skip',
'all_member_modifiers' : 'skip',
'all_member_modifier' : 'skip',
'qualified_identifier' : 'skip',
'method_declaration' : 'skip',
'method_body' : 'skip',
'method_member_name' : 'skip',
'variable_declarator' : 'skip',
'variable_declarators' : 'skip',
'var_type' : 'skip',
'base_type' : 'skip',
'class_type' : 'skip',
'simple_type' : 'skip',
'numeric_type' : 'skip',
'integral_type' : 'skip',
'floating_point_type' : 'skip',
'=' : 'skip',
'OPEN_PARENS' : 'skip',
'CLOSE_PARENS' : 'skip',
';' : 'skip',
'statement_list' : 'skip',
'PARAMS' : 'skip',
'array_type' : 'skip',
'rank_specifier' : 'skip',
'fixed_parameters' : 'skip',
'fixed_parameter' : 'skip',
'class_base' : 'skip',
'local_variable_declarator' : 'skip',
'embedded_statement' : 'skip',
'member_access' : 'skip',
'method_invocation' : 'skip',
'argument_list' : 'skip',
# Parens : defines nodes that can have parenthesis in them
# (used to wrap parenthesis in a block with the
# expression that is inside them, instead
# of having the parenthesis be a block with a
# socket that holds an expression)
'primary_expression_start' : 'parens',
# Sockets : can be used to enter inputs into a form or specify dropdowns
'IDENTIFIER' : 'socket',
'NEW' : 'socket',
'PUBLIC' : 'socket',
'PROTECTED' : 'socket',
'INTERNAL' : 'socket',
'PRIVATE' : 'socket',
'READONLY' : 'socket',
'VOLATILE' : 'socket',
'VIRTUAL' : 'socket',
'SEALED' : 'socket',
'OVERRIDE' : 'socket',
'ABSTRACT' : 'socket',
'STATIC' : 'socket',
'UNSAFE' : 'socket',
'EXTERN' : 'socket',
'PARTIAL' : 'socket',
'ASYNC' : 'socket',
'SBYTE' : 'socket',
'BYTE' : 'socket',
'SHORT' : 'socket',
'USHORT' : 'socket',
'INT' : 'socket',
'UINT' : 'socket',
'LONG' : 'socket',
'ULONG' : 'socket',
'CHAR' : 'socket',
'FLOAT' : 'socket',
'DOUBLE' : 'socket',
'DECIMAL' : 'socket',
'BOOL' : 'socket',
'VOID' : 'socket',
'VIRTUAL' : 'socket',
'INTEGER_LITERAL' : 'socket',
'HEX_INTEGER_LITERAL' : 'socket',
'REAL_LITERAL' : 'socket',
'CHARACTER_LITERAL' : 'socket',
'NULL' : 'socket',
'REGULAR_STRING' : 'socket',
'VERBATIUM_STRING' : 'socket',
'TRUE' : 'socket',
'FALSE' : 'socket',
# buttonContainer: defines a node that acts as
# a "button" that can be placed inside of another block (these nodes generally should not
# be able to be "by themselves", and wont be blocks if they are by themselves)
# NOTE: the handleButton function in this file determines the behavior for what
# happens when one of these buttons is pressed
'formal_parameter_list' : (node) ->
if (node.children[node.children?.length-1]?.type is 'parameter_array')
return {type : 'buttonContainer', buttons : SUBTRACT_BUTTON}
else
if (node.children[0]?.children?.length == 1)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
'field_declaration' : (node) ->
if (node.children[0]?.children?.length == 1)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
'local_variable_declaration' : (node) ->
if (node.children?.length == 2)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else if (node.children?.length > 2)
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
#### special: require functions to process blocks based on context/position in AST ####
# need to skip the block that defines a class if there are class modifiers for the class
# (will not detect a class with no modifiers otherwise)
'class_definition' : (node) ->
if (node.parent?)
if (node.parent.type is 'type_declaration') and (node.parent.children?.length > 1)
return 'skip'
else if (node.parent.type is 'type_declaration') and (node.parent.children?.length == 1)
return 'block'
else
return 'skip'
# need to process class variable/method declarations differently if they have or do not have
# member modifiers. I don't know why exactly it must be done this way, but this configuration is the only
# way that I was able to get method member modifiers working alongside variables/methods that don't
# have method modifiers
'class_member_declaration' : (node) ->
if (node.children?.length == 1)
return 'skip'
else
return 'block'
'typed_member_declaration' : (node) ->
if (node.parent?.parent?.children?.length > 1)
return 'skip'
else
return 'block'
'simple_embedded_statement' : (node) ->
if (node.parent?.type is 'if_body')
return 'skip'
else if (node.children[0]?.type is 'FOR') or
(node.children[0]?.type is 'WHILE')
return 'block'
else if (node.children[0]?.type is 'expression')
if (node.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.type is 'method_invocation')
params_list_node = node.children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[2]
if (params_list_node.children?.length == 2)
return {type : 'block', buttons : ADD_BUTTON}
else
return {type : 'block', buttons : BOTH_BUTTON}
else if (node.children[0]?.type is 'RETURN')
return 'block'
else
if (node.children[node.children?.length-2]?.type is 'ELSE')
return {type : 'block', buttons : BOTH_BUTTON_VERT}
else
return {type : 'block', buttons : ADD_BUTTON_VERT}
'primary_expression' : (node) ->
if (node.children[2]?.type is 'method_invocation')
return 'skip'
else
return 'block'
}
# Used to color nodes
# See view.coffee for a list of colors
COLOR_RULES = {
'using_directive' : 'using',
'namespace_declaration' : 'namespace',
'type_declaration' : 'type',
'class_definition' : 'type',
'parameter_array' : 'variable',
'arg_declaration' : 'variable',
'expression' : 'expression',
'assignment' : 'expression',
'non_assignment_expression' : 'expression',
'lambda_expression' : 'expression',
'query_expression' : 'expression',
'conditional_expression' : 'expression',
'null_coalescing_expression' : 'expression',
'conditional_or_expression' : 'expression',
'conditional_and_expression' : 'expression',
'inclusive_or_expression' : 'expression',
'exclusive_or_expression' : 'expression',
'and_expression' : 'expression',
'equality_expression' : 'expression',
'relational_expression' : 'expression',
'shift_expression' : 'expression',
'additive_expression' : 'expression',
'multiplicative_expression' : 'expression',
'unary_expression' : 'expression',
'primary_expression' : 'expression',
'primary_expression_start' : 'expression',
}
# defines categories for different colors, for better reusability
COLOR_DEFAULTS = {
'using' : 'purple'
'namespace' : 'green'
'type' : 'lightblue'
'variable' : 'yellow'
'expression' : 'deeporange'
'method' : 'indigo'
'functionCall' : 'pink'
'comment' : 'grey'
'conditional' : 'lightgreen'
'loop' : 'cyan'
}
# still not exactly sure what this section does, or what the helper does
SHAPE_RULES = {
'initializer' : helper.BLOCK_ONLY,
'expression' : helper.VALUE_ONLY,
'assignment' : helper.VALUE_ONLY,
'non_assignment_expression' : helper.VALUE_ONLY,
'lambda_expression' : helper.VALUE_ONLY,
'query_expression' : helper.VALUE_ONLY,
'conditional_expression' : helper.VALUE_ONLY,
'null_coalescing_expression' : helper.VALUE_ONLY,
'conditional_or_expression' : helper.VALUE_ONLY,
'conditional_and_expression' : helper.VALUE_ONLY,
'inclusive_or_expression' : helper.VALUE_ONLY,
'exclusive_or_expression' : helper.VALUE_ONLY,
'and_expression' : helper.VALUE_ONLY,
'equality_expression' : helper.VALUE_ONLY,
'relational_expression' : helper.VALUE_ONLY,
'shift_expression' : helper.VALUE_ONLY,
'additive_expression' : helper.VALUE_ONLY,
'multiplicative_expression' : helper.VALUE_ONLY,
'unary_expression' : helper.VALUE_ONLY,
'primary_expression' : helper.VALUE_ONLY,
'primary_expression_start' : helper.VALUE_ONLY,
}
# defines what string one should put in an empty socket when going
# from blocks to text (these can be any string, it seems)
# also allows any of the below nodes with these strings to be transformed
# into empty sockets when going from text to blocks (I think)
EMPTY_STRINGS = {
'IDENTIFIER' : '_',
'INTEGER_LITERAL' : '_',
'HEX_INTEGER_LITERAL' : '_',
'REAL_LITERAL' : '_',
'CHARACTER_LITERAL' : '_',
'NULL' : '_',
'REGULAR_STRING' : '_',
'VERBATIUM_STRING' : '_',
'TRUE' : '_',
'FALSE' : '_',
'arg_declaration' : '_',
}
# defines an empty character that is created when a block is dragged out of a socket
empty = '_'
emptyIndent = ''
ADD_PARENS = (leading, trailing, node, context) ->
leading '(' + leading()
trailing trailing() + ')'
ADD_SEMICOLON = (leading, trailing, node, context) ->
trailing trailing() + ';'
REMOVE_SEMICOLON = (leading, trailing, node, context) ->
trailing trailing().replace /\s*;\s*$/, ''
# helps control what can and cannot go into a socket?
PAREN_RULES = {
# 'primary_expression': {
# 'expression': ADD_PARENS
# },
# 'primary_expression': {
# 'literal': ADD_SEMICOLON
# }
# 'postfixExpression': {
# 'specialMethodCall': REMOVE_SEMICOLON
# }
}
SHAPE_CALLBACK = {
}
# defines any nodes that are to be turned into different kinds of dropdown menus;
# the choices for those dropdowns are defined by the items to the left of the semicolon
# these are used only if you aren't using the SHOULD_SOCKET function it seems?
DROPDOWNS = {
}
MODIFIERS = [
'public',
'private',
'protected',
'internal',
]
CLASS_MODIFIERS = MODIFIERS.concat([
'abstract',
'static',
'partial',
'sealed',
])
MEMBER_MODIFIERS = MODIFIERS.concat([
'virtual',
'abstract',
'sealed',
])
SIMPLE_TYPES = [
'sbyte',
'byte',
'short',
'ushort',
'int',
'uint',
'long',
'ulong',
'char',
'float',
'double',
'decimal',
'bool',
]
RETURN_TYPES = SIMPLE_TYPES.concat ([
'void',
])
# defines behavior for adding a locked socket + dropdown menu for class modifiers
# NOTE: any node/token that can/should be turned into a dropdown must be defined as a socket,
# like in the "rules" section
SHOULD_SOCKET = (opts, node) ->
if(node.type in ['PUBLIC', 'PRIVATE', 'PROTECTED', 'INTERNAL', 'ABSTRACT', 'STATIC', 'PARTIAL', 'SEALED', 'VIRTUAL'])
if (node.parent?.type is 'using_directive') # skip the static keyword for static using directives
return 'skip'
else if (node.parent?.type is 'class_definition')
return {
type : 'locked',
dropdown : CLASS_MODIFIERS
}
else if (node.parent?.type is 'all_member_modifier')
return {
type : 'locked',
dropdown : MEMBER_MODIFIERS
}
# adds a locked socket for variable type specifiers (for simple types)
else if(node.type in ['SBYTE', 'BYTE', 'SHORT', 'USHORT', 'INT', 'UINT', 'LONG', 'ULONG', 'CHAR', 'FLOAT', 'DOUBLE', 'DECIMAL', 'BOOL', 'VOID'])
if (node.parent?.parent?.parent?.parent?.parent?.parent?.children[1]?.type is 'method_declaration') or
(node.parent?.parent?.parent?.parent?.children[1]?.type is 'method_declaration') or
(node.parent?.children[1]?.type is 'method_declaration')
return {
type : 'locked',
dropdown : RETURN_TYPES
}
else
return {
type : 'locked',
dropdown : SIMPLE_TYPES
}
# return true by default (don't know why we do this)
return true
# defines behavior for what happens if we click a button in a block (like for
# clicking the arrow buttons in a variable assignment block)
handleButton = (str, type, block) ->
blockType = block.nodeContext?.type ? block.parseContext
if (type is 'add-button')
if (blockType is 'field_declaration')
newStr = str.slice(0, str.length-1) + ", _ = _;"
return newStr
else if (blockType is 'formal_parameter_list')
newStr = str + ", int param1"
return newStr
else if (blockType is 'local_variable_declaration')
newStr = str + ", _ = _"
return newStr
else if (blockType is 'simple_embedded_statement')
if (str.substring(0, 2) != 'if') # method invocation
if (str.substring(str.length-3, str.length-1) == "()")
newStr = str.substring(0, str.length-2) + "_);"
return newStr
else
newStr = str.substring(0, str.length-2) + ",_);"
return newStr
# TODO: add button for if-else-elseif statements (for nested statements)
lastElseIndex = str.lastIndexOf("else")
if (lastElseIndex == -1)
newStr = str + " else {\n\t\n}"
return newStr
else
lastElseIfIndex = str.lastIndexOf("else if")
if (lastElseIfIndex == -1)
trailingIfIndex = str.substring(lastElseIndex, str.length).lastIndexOf("if")
if (trailingIfIndex == -1)
newStr = str.substring(0, lastElseIndex) + "else if (a == b)" + str.substring(lastElseIndex + 4, str.length) + " else {\n\t\n}"
return newStr
else
newStr = str + " else {\n\t\n}"
return newStr
else
if ((str.match(/else/g) || []).length > 1)
newStr = str.substring(0, lastElseIndex) + "else if (a == b)" + str.substring(lastElseIndex + 4, str.length) + " else {\n\t\n}"
else
newStr = str + " else {\n\t\n}"
return newStr
else if (type is 'subtract-button')
if (blockType is 'field_declaration')
newStr = str.slice(0, str.lastIndexOf(",")) + ";"
return newStr
else if (blockType is 'formal_parameter_list')
lastCommaIndex = str.lastIndexOf(",")
newStr = str.substring(0, lastCommaIndex)
return newStr
else if (blockType is 'local_variable_declaration')
newStr = str.slice(0, str.lastIndexOf(","))
return newStr
# TODO: subtract button for if-else-elseif statements
else if (blockType is 'simple_embedded_statement')
if (str.substring(0, 2) != 'if') # method invocation
lastCommaIndex = str.lastIndexOf(",")
if (lastCommaIndex != -1)
newStr = str.substring(0, lastCommaIndex) + ");"
else
newStr = str.substring(0, str.length-3) + ");"
return newStr
elseCount = (str.match(/else/g) || []).length
if (elseCount == 1)
newStr = str.substring(0, str.lastIndexOf("else"))
return newStr
else
lastIfIndex = str.lastIndexOf("if")
return str;
return str
# allows us to color the same node in different ways given different
# contexts for it in the AST
COLOR_CALLBACK = (opts, node) ->
if (node.type is 'class_member_declaration')
if (node.children[node.children.length-1]?.children[0]?.children[1]?.type is 'field_declaration')
return 'variable'
else if (node.children[node.children?.length-1]?.children[0]?.children[1]?.type is 'method_declaration') or
(node.children[node.children?.length-1]?.children[1]?.type is 'method_declaration')
return 'method'
else return 'comment'
else if (node.type is 'typed_member_declaration')
if (node.children[1]?.type is 'field_declaration')
return 'variable'
else if (node.children[1]?.type is 'method_declaration')
return 'method'
else return 'comment'
else if (node.type is 'statement')
if (node.children[0]?.type is 'local_variable_declaration')
return 'variable'
else
return 'comment'
else if (node.type is 'simple_embedded_statement')
if (node.children[0]?.type is 'IF')
return 'conditional'
else if (node.children[0]?.type is 'expression')
# Forgive me, God
if (node.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.type is 'method_invocation')
return 'functionCall'
else
return 'expression'
else if (node.children[0]?.type is 'FOR') or
(node.children[0]?.type is 'WHILE')
return 'loop'
else if (node.children[0]?.type is 'RETURN')
return 'variable'
else
return 'comment'
return null
config = {
RULES,
COLOR_DEFAULTS,
COLOR_RULES,
SHAPE_RULES,
SHAPE_CALLBACK,
EMPTY_STRINGS,
COLOR_DEFAULTS,
DROPDOWNS,
EMPTY_STRINGS,
empty,
emptyIndent,
PAREN_RULES,
SHOULD_SOCKET,
handleButton,
COLOR_CALLBACK
}
module.exports = parser.wrapParser antlrHelper.createANTLRParser 'CSharp', config | 210230 | # Droplet C# mode
#
# Copyright (c) 2018 <NAME>
# MIT License
helper = require '../helper.coffee'
parser = require '../parser.coffee'
antlrHelper = require '../antlr.coffee'
model = require '../model.coffee'
{fixQuotedString, looseCUnescape, quoteAndCEscape} = helper
ADD_BUTTON = [
{
key: 'add-button'
glyph: '\u25B6'
border: false
}
]
SUBTRACT_BUTTON = [
{
key: 'subtract-button'
glyph: '\u25C0'
border: false
}
]
BOTH_BUTTON = [
{
key: 'subtract-button'
glyph: '\u25C0'
border: false
}
{
key: 'add-button'
glyph: '\u25B6'
border: false
}
]
ADD_BUTTON_VERT = [
{
key: 'add-button'
glyph: '\u25BC'
border: false
}
]
BOTH_BUTTON_VERT = [
{
key: 'subtract-button'
glyph: '\u25B2'
border: false
}
{
key: 'add-button'
glyph: '\u25BC'
border: false
}
]
RULES = {
# tell model to indent blocks within the main part of a n
# namespace body (indent everything past namespace_member_declarations)
'namespace_body': {
'type': 'indent',
'indexContext': 'namespace_member_declarations',
},
'class_body': {
'type': 'indent',
'indexContext': 'class_member_declarations',
},
'block': {
'type' : 'indent',
'indexContext': 'statement_list',
},
# Skips : no block for these elements
'compilationUnit' : 'skip',
'using_directives' : 'skip',
'namespace_or_type_name' : 'skip',
'namespace_member_declarations' : 'skip',
'namespace_member_declaration' : 'skip',
'class_definition' : 'skip',
'class_member_declarations' : 'skip',
'common_member_declaration' : 'skip',
'constructor_declaration' : 'skip',
'all_member_modifiers' : 'skip',
'all_member_modifier' : 'skip',
'qualified_identifier' : 'skip',
'method_declaration' : 'skip',
'method_body' : 'skip',
'method_member_name' : 'skip',
'variable_declarator' : 'skip',
'variable_declarators' : 'skip',
'var_type' : 'skip',
'base_type' : 'skip',
'class_type' : 'skip',
'simple_type' : 'skip',
'numeric_type' : 'skip',
'integral_type' : 'skip',
'floating_point_type' : 'skip',
'=' : 'skip',
'OPEN_PARENS' : 'skip',
'CLOSE_PARENS' : 'skip',
';' : 'skip',
'statement_list' : 'skip',
'PARAMS' : 'skip',
'array_type' : 'skip',
'rank_specifier' : 'skip',
'fixed_parameters' : 'skip',
'fixed_parameter' : 'skip',
'class_base' : 'skip',
'local_variable_declarator' : 'skip',
'embedded_statement' : 'skip',
'member_access' : 'skip',
'method_invocation' : 'skip',
'argument_list' : 'skip',
# Parens : defines nodes that can have parenthesis in them
# (used to wrap parenthesis in a block with the
# expression that is inside them, instead
# of having the parenthesis be a block with a
# socket that holds an expression)
'primary_expression_start' : 'parens',
# Sockets : can be used to enter inputs into a form or specify dropdowns
'IDENTIFIER' : 'socket',
'NEW' : 'socket',
'PUBLIC' : 'socket',
'PROTECTED' : 'socket',
'INTERNAL' : 'socket',
'PRIVATE' : 'socket',
'READONLY' : 'socket',
'VOLATILE' : 'socket',
'VIRTUAL' : 'socket',
'SEALED' : 'socket',
'OVERRIDE' : 'socket',
'ABSTRACT' : 'socket',
'STATIC' : 'socket',
'UNSAFE' : 'socket',
'EXTERN' : 'socket',
'PARTIAL' : 'socket',
'ASYNC' : 'socket',
'SBYTE' : 'socket',
'BYTE' : 'socket',
'SHORT' : 'socket',
'USHORT' : 'socket',
'INT' : 'socket',
'UINT' : 'socket',
'LONG' : 'socket',
'ULONG' : 'socket',
'CHAR' : 'socket',
'FLOAT' : 'socket',
'DOUBLE' : 'socket',
'DECIMAL' : 'socket',
'BOOL' : 'socket',
'VOID' : 'socket',
'VIRTUAL' : 'socket',
'INTEGER_LITERAL' : 'socket',
'HEX_INTEGER_LITERAL' : 'socket',
'REAL_LITERAL' : 'socket',
'CHARACTER_LITERAL' : 'socket',
'NULL' : 'socket',
'REGULAR_STRING' : 'socket',
'VERBATIUM_STRING' : 'socket',
'TRUE' : 'socket',
'FALSE' : 'socket',
# buttonContainer: defines a node that acts as
# a "button" that can be placed inside of another block (these nodes generally should not
# be able to be "by themselves", and wont be blocks if they are by themselves)
# NOTE: the handleButton function in this file determines the behavior for what
# happens when one of these buttons is pressed
'formal_parameter_list' : (node) ->
if (node.children[node.children?.length-1]?.type is 'parameter_array')
return {type : 'buttonContainer', buttons : SUBTRACT_BUTTON}
else
if (node.children[0]?.children?.length == 1)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
'field_declaration' : (node) ->
if (node.children[0]?.children?.length == 1)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
'local_variable_declaration' : (node) ->
if (node.children?.length == 2)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else if (node.children?.length > 2)
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
#### special: require functions to process blocks based on context/position in AST ####
# need to skip the block that defines a class if there are class modifiers for the class
# (will not detect a class with no modifiers otherwise)
'class_definition' : (node) ->
if (node.parent?)
if (node.parent.type is 'type_declaration') and (node.parent.children?.length > 1)
return 'skip'
else if (node.parent.type is 'type_declaration') and (node.parent.children?.length == 1)
return 'block'
else
return 'skip'
# need to process class variable/method declarations differently if they have or do not have
# member modifiers. I don't know why exactly it must be done this way, but this configuration is the only
# way that I was able to get method member modifiers working alongside variables/methods that don't
# have method modifiers
'class_member_declaration' : (node) ->
if (node.children?.length == 1)
return 'skip'
else
return 'block'
'typed_member_declaration' : (node) ->
if (node.parent?.parent?.children?.length > 1)
return 'skip'
else
return 'block'
'simple_embedded_statement' : (node) ->
if (node.parent?.type is 'if_body')
return 'skip'
else if (node.children[0]?.type is 'FOR') or
(node.children[0]?.type is 'WHILE')
return 'block'
else if (node.children[0]?.type is 'expression')
if (node.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.type is 'method_invocation')
params_list_node = node.children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[2]
if (params_list_node.children?.length == 2)
return {type : 'block', buttons : ADD_BUTTON}
else
return {type : 'block', buttons : BOTH_BUTTON}
else if (node.children[0]?.type is 'RETURN')
return 'block'
else
if (node.children[node.children?.length-2]?.type is 'ELSE')
return {type : 'block', buttons : BOTH_BUTTON_VERT}
else
return {type : 'block', buttons : ADD_BUTTON_VERT}
'primary_expression' : (node) ->
if (node.children[2]?.type is 'method_invocation')
return 'skip'
else
return 'block'
}
# Used to color nodes
# See view.coffee for a list of colors
COLOR_RULES = {
'using_directive' : 'using',
'namespace_declaration' : 'namespace',
'type_declaration' : 'type',
'class_definition' : 'type',
'parameter_array' : 'variable',
'arg_declaration' : 'variable',
'expression' : 'expression',
'assignment' : 'expression',
'non_assignment_expression' : 'expression',
'lambda_expression' : 'expression',
'query_expression' : 'expression',
'conditional_expression' : 'expression',
'null_coalescing_expression' : 'expression',
'conditional_or_expression' : 'expression',
'conditional_and_expression' : 'expression',
'inclusive_or_expression' : 'expression',
'exclusive_or_expression' : 'expression',
'and_expression' : 'expression',
'equality_expression' : 'expression',
'relational_expression' : 'expression',
'shift_expression' : 'expression',
'additive_expression' : 'expression',
'multiplicative_expression' : 'expression',
'unary_expression' : 'expression',
'primary_expression' : 'expression',
'primary_expression_start' : 'expression',
}
# defines categories for different colors, for better reusability
COLOR_DEFAULTS = {
'using' : 'purple'
'namespace' : 'green'
'type' : 'lightblue'
'variable' : 'yellow'
'expression' : 'deeporange'
'method' : 'indigo'
'functionCall' : 'pink'
'comment' : 'grey'
'conditional' : 'lightgreen'
'loop' : 'cyan'
}
# still not exactly sure what this section does, or what the helper does
SHAPE_RULES = {
'initializer' : helper.BLOCK_ONLY,
'expression' : helper.VALUE_ONLY,
'assignment' : helper.VALUE_ONLY,
'non_assignment_expression' : helper.VALUE_ONLY,
'lambda_expression' : helper.VALUE_ONLY,
'query_expression' : helper.VALUE_ONLY,
'conditional_expression' : helper.VALUE_ONLY,
'null_coalescing_expression' : helper.VALUE_ONLY,
'conditional_or_expression' : helper.VALUE_ONLY,
'conditional_and_expression' : helper.VALUE_ONLY,
'inclusive_or_expression' : helper.VALUE_ONLY,
'exclusive_or_expression' : helper.VALUE_ONLY,
'and_expression' : helper.VALUE_ONLY,
'equality_expression' : helper.VALUE_ONLY,
'relational_expression' : helper.VALUE_ONLY,
'shift_expression' : helper.VALUE_ONLY,
'additive_expression' : helper.VALUE_ONLY,
'multiplicative_expression' : helper.VALUE_ONLY,
'unary_expression' : helper.VALUE_ONLY,
'primary_expression' : helper.VALUE_ONLY,
'primary_expression_start' : helper.VALUE_ONLY,
}
# defines what string one should put in an empty socket when going
# from blocks to text (these can be any string, it seems)
# also allows any of the below nodes with these strings to be transformed
# into empty sockets when going from text to blocks (I think)
EMPTY_STRINGS = {
'IDENTIFIER' : '_',
'INTEGER_LITERAL' : '_',
'HEX_INTEGER_LITERAL' : '_',
'REAL_LITERAL' : '_',
'CHARACTER_LITERAL' : '_',
'NULL' : '_',
'REGULAR_STRING' : '_',
'VERBATIUM_STRING' : '_',
'TRUE' : '_',
'FALSE' : '_',
'arg_declaration' : '_',
}
# defines an empty character that is created when a block is dragged out of a socket
empty = '_'
emptyIndent = ''
ADD_PARENS = (leading, trailing, node, context) ->
leading '(' + leading()
trailing trailing() + ')'
ADD_SEMICOLON = (leading, trailing, node, context) ->
trailing trailing() + ';'
REMOVE_SEMICOLON = (leading, trailing, node, context) ->
trailing trailing().replace /\s*;\s*$/, ''
# helps control what can and cannot go into a socket?
PAREN_RULES = {
# 'primary_expression': {
# 'expression': ADD_PARENS
# },
# 'primary_expression': {
# 'literal': ADD_SEMICOLON
# }
# 'postfixExpression': {
# 'specialMethodCall': REMOVE_SEMICOLON
# }
}
SHAPE_CALLBACK = {
}
# defines any nodes that are to be turned into different kinds of dropdown menus;
# the choices for those dropdowns are defined by the items to the left of the semicolon
# these are used only if you aren't using the SHOULD_SOCKET function it seems?
DROPDOWNS = {
}
MODIFIERS = [
'public',
'private',
'protected',
'internal',
]
CLASS_MODIFIERS = MODIFIERS.concat([
'abstract',
'static',
'partial',
'sealed',
])
MEMBER_MODIFIERS = MODIFIERS.concat([
'virtual',
'abstract',
'sealed',
])
SIMPLE_TYPES = [
'sbyte',
'byte',
'short',
'ushort',
'int',
'uint',
'long',
'ulong',
'char',
'float',
'double',
'decimal',
'bool',
]
RETURN_TYPES = SIMPLE_TYPES.concat ([
'void',
])
# defines behavior for adding a locked socket + dropdown menu for class modifiers
# NOTE: any node/token that can/should be turned into a dropdown must be defined as a socket,
# like in the "rules" section
SHOULD_SOCKET = (opts, node) ->
if(node.type in ['PUBLIC', 'PRIVATE', 'PROTECTED', 'INTERNAL', 'ABSTRACT', 'STATIC', 'PARTIAL', 'SEALED', 'VIRTUAL'])
if (node.parent?.type is 'using_directive') # skip the static keyword for static using directives
return 'skip'
else if (node.parent?.type is 'class_definition')
return {
type : 'locked',
dropdown : CLASS_MODIFIERS
}
else if (node.parent?.type is 'all_member_modifier')
return {
type : 'locked',
dropdown : MEMBER_MODIFIERS
}
# adds a locked socket for variable type specifiers (for simple types)
else if(node.type in ['SBYTE', 'BYTE', 'SHORT', 'USHORT', 'INT', 'UINT', 'LONG', 'ULONG', 'CHAR', 'FLOAT', 'DOUBLE', 'DECIMAL', 'BOOL', 'VOID'])
if (node.parent?.parent?.parent?.parent?.parent?.parent?.children[1]?.type is 'method_declaration') or
(node.parent?.parent?.parent?.parent?.children[1]?.type is 'method_declaration') or
(node.parent?.children[1]?.type is 'method_declaration')
return {
type : 'locked',
dropdown : RETURN_TYPES
}
else
return {
type : 'locked',
dropdown : SIMPLE_TYPES
}
# return true by default (don't know why we do this)
return true
# defines behavior for what happens if we click a button in a block (like for
# clicking the arrow buttons in a variable assignment block)
handleButton = (str, type, block) ->
blockType = block.nodeContext?.type ? block.parseContext
if (type is 'add-button')
if (blockType is 'field_declaration')
newStr = str.slice(0, str.length-1) + ", _ = _;"
return newStr
else if (blockType is 'formal_parameter_list')
newStr = str + ", int param1"
return newStr
else if (blockType is 'local_variable_declaration')
newStr = str + ", _ = _"
return newStr
else if (blockType is 'simple_embedded_statement')
if (str.substring(0, 2) != 'if') # method invocation
if (str.substring(str.length-3, str.length-1) == "()")
newStr = str.substring(0, str.length-2) + "_);"
return newStr
else
newStr = str.substring(0, str.length-2) + ",_);"
return newStr
# TODO: add button for if-else-elseif statements (for nested statements)
lastElseIndex = str.lastIndexOf("else")
if (lastElseIndex == -1)
newStr = str + " else {\n\t\n}"
return newStr
else
lastElseIfIndex = str.lastIndexOf("else if")
if (lastElseIfIndex == -1)
trailingIfIndex = str.substring(lastElseIndex, str.length).lastIndexOf("if")
if (trailingIfIndex == -1)
newStr = str.substring(0, lastElseIndex) + "else if (a == b)" + str.substring(lastElseIndex + 4, str.length) + " else {\n\t\n}"
return newStr
else
newStr = str + " else {\n\t\n}"
return newStr
else
if ((str.match(/else/g) || []).length > 1)
newStr = str.substring(0, lastElseIndex) + "else if (a == b)" + str.substring(lastElseIndex + 4, str.length) + " else {\n\t\n}"
else
newStr = str + " else {\n\t\n}"
return newStr
else if (type is 'subtract-button')
if (blockType is 'field_declaration')
newStr = str.slice(0, str.lastIndexOf(",")) + ";"
return newStr
else if (blockType is 'formal_parameter_list')
lastCommaIndex = str.lastIndexOf(",")
newStr = str.substring(0, lastCommaIndex)
return newStr
else if (blockType is 'local_variable_declaration')
newStr = str.slice(0, str.lastIndexOf(","))
return newStr
# TODO: subtract button for if-else-elseif statements
else if (blockType is 'simple_embedded_statement')
if (str.substring(0, 2) != 'if') # method invocation
lastCommaIndex = str.lastIndexOf(",")
if (lastCommaIndex != -1)
newStr = str.substring(0, lastCommaIndex) + ");"
else
newStr = str.substring(0, str.length-3) + ");"
return newStr
elseCount = (str.match(/else/g) || []).length
if (elseCount == 1)
newStr = str.substring(0, str.lastIndexOf("else"))
return newStr
else
lastIfIndex = str.lastIndexOf("if")
return str;
return str
# allows us to color the same node in different ways given different
# contexts for it in the AST
COLOR_CALLBACK = (opts, node) ->
if (node.type is 'class_member_declaration')
if (node.children[node.children.length-1]?.children[0]?.children[1]?.type is 'field_declaration')
return 'variable'
else if (node.children[node.children?.length-1]?.children[0]?.children[1]?.type is 'method_declaration') or
(node.children[node.children?.length-1]?.children[1]?.type is 'method_declaration')
return 'method'
else return 'comment'
else if (node.type is 'typed_member_declaration')
if (node.children[1]?.type is 'field_declaration')
return 'variable'
else if (node.children[1]?.type is 'method_declaration')
return 'method'
else return 'comment'
else if (node.type is 'statement')
if (node.children[0]?.type is 'local_variable_declaration')
return 'variable'
else
return 'comment'
else if (node.type is 'simple_embedded_statement')
if (node.children[0]?.type is 'IF')
return 'conditional'
else if (node.children[0]?.type is 'expression')
# Forgive me, God
if (node.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.type is 'method_invocation')
return 'functionCall'
else
return 'expression'
else if (node.children[0]?.type is 'FOR') or
(node.children[0]?.type is 'WHILE')
return 'loop'
else if (node.children[0]?.type is 'RETURN')
return 'variable'
else
return 'comment'
return null
config = {
RULES,
COLOR_DEFAULTS,
COLOR_RULES,
SHAPE_RULES,
SHAPE_CALLBACK,
EMPTY_STRINGS,
COLOR_DEFAULTS,
DROPDOWNS,
EMPTY_STRINGS,
empty,
emptyIndent,
PAREN_RULES,
SHOULD_SOCKET,
handleButton,
COLOR_CALLBACK
}
module.exports = parser.wrapParser antlrHelper.createANTLRParser 'CSharp', config | true | # Droplet C# mode
#
# Copyright (c) 2018 PI:NAME:<NAME>END_PI
# MIT License
helper = require '../helper.coffee'
parser = require '../parser.coffee'
antlrHelper = require '../antlr.coffee'
model = require '../model.coffee'
{fixQuotedString, looseCUnescape, quoteAndCEscape} = helper
ADD_BUTTON = [
{
key: 'add-button'
glyph: '\u25B6'
border: false
}
]
SUBTRACT_BUTTON = [
{
key: 'subtract-button'
glyph: '\u25C0'
border: false
}
]
BOTH_BUTTON = [
{
key: 'subtract-button'
glyph: '\u25C0'
border: false
}
{
key: 'add-button'
glyph: '\u25B6'
border: false
}
]
ADD_BUTTON_VERT = [
{
key: 'add-button'
glyph: '\u25BC'
border: false
}
]
BOTH_BUTTON_VERT = [
{
key: 'subtract-button'
glyph: '\u25B2'
border: false
}
{
key: 'add-button'
glyph: '\u25BC'
border: false
}
]
RULES = {
# tell model to indent blocks within the main part of a n
# namespace body (indent everything past namespace_member_declarations)
'namespace_body': {
'type': 'indent',
'indexContext': 'namespace_member_declarations',
},
'class_body': {
'type': 'indent',
'indexContext': 'class_member_declarations',
},
'block': {
'type' : 'indent',
'indexContext': 'statement_list',
},
# Skips : no block for these elements
'compilationUnit' : 'skip',
'using_directives' : 'skip',
'namespace_or_type_name' : 'skip',
'namespace_member_declarations' : 'skip',
'namespace_member_declaration' : 'skip',
'class_definition' : 'skip',
'class_member_declarations' : 'skip',
'common_member_declaration' : 'skip',
'constructor_declaration' : 'skip',
'all_member_modifiers' : 'skip',
'all_member_modifier' : 'skip',
'qualified_identifier' : 'skip',
'method_declaration' : 'skip',
'method_body' : 'skip',
'method_member_name' : 'skip',
'variable_declarator' : 'skip',
'variable_declarators' : 'skip',
'var_type' : 'skip',
'base_type' : 'skip',
'class_type' : 'skip',
'simple_type' : 'skip',
'numeric_type' : 'skip',
'integral_type' : 'skip',
'floating_point_type' : 'skip',
'=' : 'skip',
'OPEN_PARENS' : 'skip',
'CLOSE_PARENS' : 'skip',
';' : 'skip',
'statement_list' : 'skip',
'PARAMS' : 'skip',
'array_type' : 'skip',
'rank_specifier' : 'skip',
'fixed_parameters' : 'skip',
'fixed_parameter' : 'skip',
'class_base' : 'skip',
'local_variable_declarator' : 'skip',
'embedded_statement' : 'skip',
'member_access' : 'skip',
'method_invocation' : 'skip',
'argument_list' : 'skip',
# Parens : defines nodes that can have parenthesis in them
# (used to wrap parenthesis in a block with the
# expression that is inside them, instead
# of having the parenthesis be a block with a
# socket that holds an expression)
'primary_expression_start' : 'parens',
# Sockets : can be used to enter inputs into a form or specify dropdowns
'IDENTIFIER' : 'socket',
'NEW' : 'socket',
'PUBLIC' : 'socket',
'PROTECTED' : 'socket',
'INTERNAL' : 'socket',
'PRIVATE' : 'socket',
'READONLY' : 'socket',
'VOLATILE' : 'socket',
'VIRTUAL' : 'socket',
'SEALED' : 'socket',
'OVERRIDE' : 'socket',
'ABSTRACT' : 'socket',
'STATIC' : 'socket',
'UNSAFE' : 'socket',
'EXTERN' : 'socket',
'PARTIAL' : 'socket',
'ASYNC' : 'socket',
'SBYTE' : 'socket',
'BYTE' : 'socket',
'SHORT' : 'socket',
'USHORT' : 'socket',
'INT' : 'socket',
'UINT' : 'socket',
'LONG' : 'socket',
'ULONG' : 'socket',
'CHAR' : 'socket',
'FLOAT' : 'socket',
'DOUBLE' : 'socket',
'DECIMAL' : 'socket',
'BOOL' : 'socket',
'VOID' : 'socket',
'VIRTUAL' : 'socket',
'INTEGER_LITERAL' : 'socket',
'HEX_INTEGER_LITERAL' : 'socket',
'REAL_LITERAL' : 'socket',
'CHARACTER_LITERAL' : 'socket',
'NULL' : 'socket',
'REGULAR_STRING' : 'socket',
'VERBATIUM_STRING' : 'socket',
'TRUE' : 'socket',
'FALSE' : 'socket',
# buttonContainer: defines a node that acts as
# a "button" that can be placed inside of another block (these nodes generally should not
# be able to be "by themselves", and wont be blocks if they are by themselves)
# NOTE: the handleButton function in this file determines the behavior for what
# happens when one of these buttons is pressed
'formal_parameter_list' : (node) ->
if (node.children[node.children?.length-1]?.type is 'parameter_array')
return {type : 'buttonContainer', buttons : SUBTRACT_BUTTON}
else
if (node.children[0]?.children?.length == 1)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
'field_declaration' : (node) ->
if (node.children[0]?.children?.length == 1)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
'local_variable_declaration' : (node) ->
if (node.children?.length == 2)
return {type : 'buttonContainer', buttons : ADD_BUTTON}
else if (node.children?.length > 2)
return {type : 'buttonContainer', buttons : BOTH_BUTTON}
#### special: require functions to process blocks based on context/position in AST ####
# need to skip the block that defines a class if there are class modifiers for the class
# (will not detect a class with no modifiers otherwise)
'class_definition' : (node) ->
if (node.parent?)
if (node.parent.type is 'type_declaration') and (node.parent.children?.length > 1)
return 'skip'
else if (node.parent.type is 'type_declaration') and (node.parent.children?.length == 1)
return 'block'
else
return 'skip'
# need to process class variable/method declarations differently if they have or do not have
# member modifiers. I don't know why exactly it must be done this way, but this configuration is the only
# way that I was able to get method member modifiers working alongside variables/methods that don't
# have method modifiers
'class_member_declaration' : (node) ->
if (node.children?.length == 1)
return 'skip'
else
return 'block'
'typed_member_declaration' : (node) ->
if (node.parent?.parent?.children?.length > 1)
return 'skip'
else
return 'block'
'simple_embedded_statement' : (node) ->
if (node.parent?.type is 'if_body')
return 'skip'
else if (node.children[0]?.type is 'FOR') or
(node.children[0]?.type is 'WHILE')
return 'block'
else if (node.children[0]?.type is 'expression')
if (node.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.type is 'method_invocation')
params_list_node = node.children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[0].children[2]
if (params_list_node.children?.length == 2)
return {type : 'block', buttons : ADD_BUTTON}
else
return {type : 'block', buttons : BOTH_BUTTON}
else if (node.children[0]?.type is 'RETURN')
return 'block'
else
if (node.children[node.children?.length-2]?.type is 'ELSE')
return {type : 'block', buttons : BOTH_BUTTON_VERT}
else
return {type : 'block', buttons : ADD_BUTTON_VERT}
'primary_expression' : (node) ->
if (node.children[2]?.type is 'method_invocation')
return 'skip'
else
return 'block'
}
# Used to color nodes
# See view.coffee for a list of colors
COLOR_RULES = {
'using_directive' : 'using',
'namespace_declaration' : 'namespace',
'type_declaration' : 'type',
'class_definition' : 'type',
'parameter_array' : 'variable',
'arg_declaration' : 'variable',
'expression' : 'expression',
'assignment' : 'expression',
'non_assignment_expression' : 'expression',
'lambda_expression' : 'expression',
'query_expression' : 'expression',
'conditional_expression' : 'expression',
'null_coalescing_expression' : 'expression',
'conditional_or_expression' : 'expression',
'conditional_and_expression' : 'expression',
'inclusive_or_expression' : 'expression',
'exclusive_or_expression' : 'expression',
'and_expression' : 'expression',
'equality_expression' : 'expression',
'relational_expression' : 'expression',
'shift_expression' : 'expression',
'additive_expression' : 'expression',
'multiplicative_expression' : 'expression',
'unary_expression' : 'expression',
'primary_expression' : 'expression',
'primary_expression_start' : 'expression',
}
# defines categories for different colors, for better reusability
COLOR_DEFAULTS = {
'using' : 'purple'
'namespace' : 'green'
'type' : 'lightblue'
'variable' : 'yellow'
'expression' : 'deeporange'
'method' : 'indigo'
'functionCall' : 'pink'
'comment' : 'grey'
'conditional' : 'lightgreen'
'loop' : 'cyan'
}
# still not exactly sure what this section does, or what the helper does
SHAPE_RULES = {
'initializer' : helper.BLOCK_ONLY,
'expression' : helper.VALUE_ONLY,
'assignment' : helper.VALUE_ONLY,
'non_assignment_expression' : helper.VALUE_ONLY,
'lambda_expression' : helper.VALUE_ONLY,
'query_expression' : helper.VALUE_ONLY,
'conditional_expression' : helper.VALUE_ONLY,
'null_coalescing_expression' : helper.VALUE_ONLY,
'conditional_or_expression' : helper.VALUE_ONLY,
'conditional_and_expression' : helper.VALUE_ONLY,
'inclusive_or_expression' : helper.VALUE_ONLY,
'exclusive_or_expression' : helper.VALUE_ONLY,
'and_expression' : helper.VALUE_ONLY,
'equality_expression' : helper.VALUE_ONLY,
'relational_expression' : helper.VALUE_ONLY,
'shift_expression' : helper.VALUE_ONLY,
'additive_expression' : helper.VALUE_ONLY,
'multiplicative_expression' : helper.VALUE_ONLY,
'unary_expression' : helper.VALUE_ONLY,
'primary_expression' : helper.VALUE_ONLY,
'primary_expression_start' : helper.VALUE_ONLY,
}
# defines what string one should put in an empty socket when going
# from blocks to text (these can be any string, it seems)
# also allows any of the below nodes with these strings to be transformed
# into empty sockets when going from text to blocks (I think)
EMPTY_STRINGS = {
'IDENTIFIER' : '_',
'INTEGER_LITERAL' : '_',
'HEX_INTEGER_LITERAL' : '_',
'REAL_LITERAL' : '_',
'CHARACTER_LITERAL' : '_',
'NULL' : '_',
'REGULAR_STRING' : '_',
'VERBATIUM_STRING' : '_',
'TRUE' : '_',
'FALSE' : '_',
'arg_declaration' : '_',
}
# defines an empty character that is created when a block is dragged out of a socket
empty = '_'
emptyIndent = ''
ADD_PARENS = (leading, trailing, node, context) ->
leading '(' + leading()
trailing trailing() + ')'
ADD_SEMICOLON = (leading, trailing, node, context) ->
trailing trailing() + ';'
REMOVE_SEMICOLON = (leading, trailing, node, context) ->
trailing trailing().replace /\s*;\s*$/, ''
# helps control what can and cannot go into a socket?
PAREN_RULES = {
# 'primary_expression': {
# 'expression': ADD_PARENS
# },
# 'primary_expression': {
# 'literal': ADD_SEMICOLON
# }
# 'postfixExpression': {
# 'specialMethodCall': REMOVE_SEMICOLON
# }
}
SHAPE_CALLBACK = {
}
# defines any nodes that are to be turned into different kinds of dropdown menus;
# the choices for those dropdowns are defined by the items to the left of the semicolon
# these are used only if you aren't using the SHOULD_SOCKET function it seems?
DROPDOWNS = {
}
MODIFIERS = [
'public',
'private',
'protected',
'internal',
]
CLASS_MODIFIERS = MODIFIERS.concat([
'abstract',
'static',
'partial',
'sealed',
])
MEMBER_MODIFIERS = MODIFIERS.concat([
'virtual',
'abstract',
'sealed',
])
SIMPLE_TYPES = [
'sbyte',
'byte',
'short',
'ushort',
'int',
'uint',
'long',
'ulong',
'char',
'float',
'double',
'decimal',
'bool',
]
RETURN_TYPES = SIMPLE_TYPES.concat ([
'void',
])
# defines behavior for adding a locked socket + dropdown menu for class modifiers
# NOTE: any node/token that can/should be turned into a dropdown must be defined as a socket,
# like in the "rules" section
SHOULD_SOCKET = (opts, node) ->
if(node.type in ['PUBLIC', 'PRIVATE', 'PROTECTED', 'INTERNAL', 'ABSTRACT', 'STATIC', 'PARTIAL', 'SEALED', 'VIRTUAL'])
if (node.parent?.type is 'using_directive') # skip the static keyword for static using directives
return 'skip'
else if (node.parent?.type is 'class_definition')
return {
type : 'locked',
dropdown : CLASS_MODIFIERS
}
else if (node.parent?.type is 'all_member_modifier')
return {
type : 'locked',
dropdown : MEMBER_MODIFIERS
}
# adds a locked socket for variable type specifiers (for simple types)
else if(node.type in ['SBYTE', 'BYTE', 'SHORT', 'USHORT', 'INT', 'UINT', 'LONG', 'ULONG', 'CHAR', 'FLOAT', 'DOUBLE', 'DECIMAL', 'BOOL', 'VOID'])
if (node.parent?.parent?.parent?.parent?.parent?.parent?.children[1]?.type is 'method_declaration') or
(node.parent?.parent?.parent?.parent?.children[1]?.type is 'method_declaration') or
(node.parent?.children[1]?.type is 'method_declaration')
return {
type : 'locked',
dropdown : RETURN_TYPES
}
else
return {
type : 'locked',
dropdown : SIMPLE_TYPES
}
# return true by default (don't know why we do this)
return true
# defines behavior for what happens if we click a button in a block (like for
# clicking the arrow buttons in a variable assignment block)
handleButton = (str, type, block) ->
blockType = block.nodeContext?.type ? block.parseContext
if (type is 'add-button')
if (blockType is 'field_declaration')
newStr = str.slice(0, str.length-1) + ", _ = _;"
return newStr
else if (blockType is 'formal_parameter_list')
newStr = str + ", int param1"
return newStr
else if (blockType is 'local_variable_declaration')
newStr = str + ", _ = _"
return newStr
else if (blockType is 'simple_embedded_statement')
if (str.substring(0, 2) != 'if') # method invocation
if (str.substring(str.length-3, str.length-1) == "()")
newStr = str.substring(0, str.length-2) + "_);"
return newStr
else
newStr = str.substring(0, str.length-2) + ",_);"
return newStr
# TODO: add button for if-else-elseif statements (for nested statements)
lastElseIndex = str.lastIndexOf("else")
if (lastElseIndex == -1)
newStr = str + " else {\n\t\n}"
return newStr
else
lastElseIfIndex = str.lastIndexOf("else if")
if (lastElseIfIndex == -1)
trailingIfIndex = str.substring(lastElseIndex, str.length).lastIndexOf("if")
if (trailingIfIndex == -1)
newStr = str.substring(0, lastElseIndex) + "else if (a == b)" + str.substring(lastElseIndex + 4, str.length) + " else {\n\t\n}"
return newStr
else
newStr = str + " else {\n\t\n}"
return newStr
else
if ((str.match(/else/g) || []).length > 1)
newStr = str.substring(0, lastElseIndex) + "else if (a == b)" + str.substring(lastElseIndex + 4, str.length) + " else {\n\t\n}"
else
newStr = str + " else {\n\t\n}"
return newStr
else if (type is 'subtract-button')
if (blockType is 'field_declaration')
newStr = str.slice(0, str.lastIndexOf(",")) + ";"
return newStr
else if (blockType is 'formal_parameter_list')
lastCommaIndex = str.lastIndexOf(",")
newStr = str.substring(0, lastCommaIndex)
return newStr
else if (blockType is 'local_variable_declaration')
newStr = str.slice(0, str.lastIndexOf(","))
return newStr
# TODO: subtract button for if-else-elseif statements
else if (blockType is 'simple_embedded_statement')
if (str.substring(0, 2) != 'if') # method invocation
lastCommaIndex = str.lastIndexOf(",")
if (lastCommaIndex != -1)
newStr = str.substring(0, lastCommaIndex) + ");"
else
newStr = str.substring(0, str.length-3) + ");"
return newStr
elseCount = (str.match(/else/g) || []).length
if (elseCount == 1)
newStr = str.substring(0, str.lastIndexOf("else"))
return newStr
else
lastIfIndex = str.lastIndexOf("if")
return str;
return str
# allows us to color the same node in different ways given different
# contexts for it in the AST
COLOR_CALLBACK = (opts, node) ->
if (node.type is 'class_member_declaration')
if (node.children[node.children.length-1]?.children[0]?.children[1]?.type is 'field_declaration')
return 'variable'
else if (node.children[node.children?.length-1]?.children[0]?.children[1]?.type is 'method_declaration') or
(node.children[node.children?.length-1]?.children[1]?.type is 'method_declaration')
return 'method'
else return 'comment'
else if (node.type is 'typed_member_declaration')
if (node.children[1]?.type is 'field_declaration')
return 'variable'
else if (node.children[1]?.type is 'method_declaration')
return 'method'
else return 'comment'
else if (node.type is 'statement')
if (node.children[0]?.type is 'local_variable_declaration')
return 'variable'
else
return 'comment'
else if (node.type is 'simple_embedded_statement')
if (node.children[0]?.type is 'IF')
return 'conditional'
else if (node.children[0]?.type is 'expression')
# Forgive me, God
if (node.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.type is 'method_invocation')
return 'functionCall'
else
return 'expression'
else if (node.children[0]?.type is 'FOR') or
(node.children[0]?.type is 'WHILE')
return 'loop'
else if (node.children[0]?.type is 'RETURN')
return 'variable'
else
return 'comment'
return null
config = {
RULES,
COLOR_DEFAULTS,
COLOR_RULES,
SHAPE_RULES,
SHAPE_CALLBACK,
EMPTY_STRINGS,
COLOR_DEFAULTS,
DROPDOWNS,
EMPTY_STRINGS,
empty,
emptyIndent,
PAREN_RULES,
SHOULD_SOCKET,
handleButton,
COLOR_CALLBACK
}
module.exports = parser.wrapParser antlrHelper.createANTLRParser 'CSharp', config |
[
{
"context": "e Music\n * @category Web Components\n * @author Nazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright Copyright (c",
"end": 96,
"score": 0.9998959302902222,
"start": 80,
"tag": "NAME",
"value": "Nazar Mokrynskyi"
},
{
"context": "y Web Components\n * @author N... | html/cs-music-menu/script.coffee | mariot/Klif-Mozika | 0 | ###*
* @package CleverStyle Music
* @category Web Components
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @copyright Copyright (c) 2014-2015, Nazar Mokrynskyi
* @license MIT License, see license.txt
###
music_settings = cs.music_settings
document.webL10n.ready ->
Polymer(
'cs-music-menu'
playlist_text : _('playlist')
equalizer_text : _('equalizer')
sound_environment_text : _('sound-environment')
library_text : _('library')
rescan_library_text : _('rescan-library')
low_performance_mode_text : _('low-performance-mode')
low_performance : music_settings.low_performance
playlist : ->
@go_to_screen('playlist')
equalizer : ->
@go_to_screen('equalizer')
sound_environment : ->
@go_to_screen('sound-environment')
library : ->
@go_to_screen('library')
rescan : ->
@go_to_screen('library-rescan')
performance : ->
if music_settings.low_performance != confirm _('low-performance-mode-details')
music_settings.low_performance = !music_settings.low_performance
location.reload()
back : ->
@go_to_screen('player')
)
| 42165 | ###*
* @package CleverStyle Music
* @category Web Components
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2014-2015, <NAME>
* @license MIT License, see license.txt
###
music_settings = cs.music_settings
document.webL10n.ready ->
Polymer(
'cs-music-menu'
playlist_text : _('playlist')
equalizer_text : _('equalizer')
sound_environment_text : _('sound-environment')
library_text : _('library')
rescan_library_text : _('rescan-library')
low_performance_mode_text : _('low-performance-mode')
low_performance : music_settings.low_performance
playlist : ->
@go_to_screen('playlist')
equalizer : ->
@go_to_screen('equalizer')
sound_environment : ->
@go_to_screen('sound-environment')
library : ->
@go_to_screen('library')
rescan : ->
@go_to_screen('library-rescan')
performance : ->
if music_settings.low_performance != confirm _('low-performance-mode-details')
music_settings.low_performance = !music_settings.low_performance
location.reload()
back : ->
@go_to_screen('player')
)
| true | ###*
* @package CleverStyle Music
* @category Web Components
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* @copyright Copyright (c) 2014-2015, PI:NAME:<NAME>END_PI
* @license MIT License, see license.txt
###
music_settings = cs.music_settings
document.webL10n.ready ->
Polymer(
'cs-music-menu'
playlist_text : _('playlist')
equalizer_text : _('equalizer')
sound_environment_text : _('sound-environment')
library_text : _('library')
rescan_library_text : _('rescan-library')
low_performance_mode_text : _('low-performance-mode')
low_performance : music_settings.low_performance
playlist : ->
@go_to_screen('playlist')
equalizer : ->
@go_to_screen('equalizer')
sound_environment : ->
@go_to_screen('sound-environment')
library : ->
@go_to_screen('library')
rescan : ->
@go_to_screen('library-rescan')
performance : ->
if music_settings.low_performance != confirm _('low-performance-mode-details')
music_settings.low_performance = !music_settings.low_performance
location.reload()
back : ->
@go_to_screen('player')
)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.99897700548172,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-stream-transform-objectmode-falsey-value.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
stream = require("stream")
PassThrough = stream.PassThrough
src = new PassThrough(objectMode: true)
tx = new PassThrough(objectMode: true)
dest = new PassThrough(objectMode: true)
expect = [
-1
0
1
2
3
4
5
6
7
8
9
10
]
results = []
process.on "exit", ->
assert.deepEqual results, expect
console.log "ok"
return
dest.on "data", (x) ->
results.push x
return
src.pipe(tx).pipe dest
i = -1
int = setInterval(->
if i > 10
src.end()
clearInterval int
else
src.write i++
return
)
| 35773 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
stream = require("stream")
PassThrough = stream.PassThrough
src = new PassThrough(objectMode: true)
tx = new PassThrough(objectMode: true)
dest = new PassThrough(objectMode: true)
expect = [
-1
0
1
2
3
4
5
6
7
8
9
10
]
results = []
process.on "exit", ->
assert.deepEqual results, expect
console.log "ok"
return
dest.on "data", (x) ->
results.push x
return
src.pipe(tx).pipe dest
i = -1
int = setInterval(->
if i > 10
src.end()
clearInterval int
else
src.write i++
return
)
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
stream = require("stream")
PassThrough = stream.PassThrough
src = new PassThrough(objectMode: true)
tx = new PassThrough(objectMode: true)
dest = new PassThrough(objectMode: true)
expect = [
-1
0
1
2
3
4
5
6
7
8
9
10
]
results = []
process.on "exit", ->
assert.deepEqual results, expect
console.log "ok"
return
dest.on "data", (x) ->
results.push x
return
src.pipe(tx).pipe dest
i = -1
int = setInterval(->
if i > 10
src.end()
clearInterval int
else
src.write i++
return
)
|
[
{
"context": " render: =>\n z '.z-tooltip-positioner', {key: \"tooltip-#{@key}\"}\n",
"end": 2706,
"score": 0.9155095815658569,
"start": 2698,
"tag": "KEY",
"value": "tooltip-"
},
{
"context": " z '.z-tooltip-positioner', {key: \"tooltip-#{@key}\"}\n",
"end": 2712,
"score... | src/components/tooltip_positioner/index.coffee | FreeRoamApp/free-roam | 14 | z = require 'zorium'
RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject
_find = require 'lodash/find'
_uniq = require 'lodash/uniq'
_every = require 'lodash/every'
Base = require '../base'
Tooltip = require '../tooltip'
colors = require '../../colors'
if window?
require './index.styl'
# this shows the main tooltip which is rendered in app.coffee
# if we render it here, it has issues with iscroll (having a position: fixed
# inside a transform)
module.exports = class TooltipPositioner extends Base
TOOLTIPS:
placeSearch:
prereqs: null
mapLayers:
prereqs: ['placeSearch']
mapTypes:
prereqs: ['mapLayers']
mapFilters:
prereqs: ['mapTypes']
placeTooltip:
prereqs: null
itemGuides:
prereqs: null
constructor: (options) ->
unless window? # could also return right away if cookie exists for perf
return
{@model, @isVisible, @offset, @key, @anchor, @$title, @$content,
@zIndex} = options
@isVisible ?= new RxBehaviorSubject false
@$title ?= @model.l.get "tooltips.#{@key}Title"
@$content ?= @model.l.get "tooltips.#{@key}Content"
@isShown = false
@shouldBeShown = @model.cookie.getStream().map (cookies) =>
completed = cookies.completedTooltips?.split(',') or []
isCompleted = completed.indexOf(@key) isnt -1
prereqs = @TOOLTIPS[@key]?.prereqs
not isCompleted and _every prereqs, (prereq) ->
completed.indexOf(prereq) isnt -1
.publishReplay(1).refCount()
afterMount: (@$$el) =>
super
@disposable = @shouldBeShown.subscribe (shouldBeShown) =>
# TODO: show main page tooltips when closing overlayPage?
# one option is to have model.tooltip store all visible tooltips
if shouldBeShown and not @isShown
@isShown = true
# despite having this, ios still calls this twice, hence the flag above
@disposable?.unsubscribe()
setTimeout =>
checkIsReady = =>
if @$$el and @$$el.clientWidth
@_show @$$el
else
setTimeout checkIsReady, 100
checkIsReady()
, 0 # give time for re-render...
beforeUnmount: =>
@disposable?.unsubscribe()
@isShown = false
@isVisible.next false
close: =>
@$tooltip?.close()
_show: ($$el) =>
rect = $$el.getBoundingClientRect()
initialPosition = {x: rect.left, y: rect.top}
@$tooltip = new Tooltip {
@model
@key
@anchor
@offset
@isVisible
@zIndex
initialPosition
$title: @$title
$content: @$content
}
@model.tooltip.set$ @$tooltip
render: =>
z '.z-tooltip-positioner', {key: "tooltip-#{@key}"}
| 105189 | z = require 'zorium'
RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject
_find = require 'lodash/find'
_uniq = require 'lodash/uniq'
_every = require 'lodash/every'
Base = require '../base'
Tooltip = require '../tooltip'
colors = require '../../colors'
if window?
require './index.styl'
# this shows the main tooltip which is rendered in app.coffee
# if we render it here, it has issues with iscroll (having a position: fixed
# inside a transform)
module.exports = class TooltipPositioner extends Base
TOOLTIPS:
placeSearch:
prereqs: null
mapLayers:
prereqs: ['placeSearch']
mapTypes:
prereqs: ['mapLayers']
mapFilters:
prereqs: ['mapTypes']
placeTooltip:
prereqs: null
itemGuides:
prereqs: null
constructor: (options) ->
unless window? # could also return right away if cookie exists for perf
return
{@model, @isVisible, @offset, @key, @anchor, @$title, @$content,
@zIndex} = options
@isVisible ?= new RxBehaviorSubject false
@$title ?= @model.l.get "tooltips.#{@key}Title"
@$content ?= @model.l.get "tooltips.#{@key}Content"
@isShown = false
@shouldBeShown = @model.cookie.getStream().map (cookies) =>
completed = cookies.completedTooltips?.split(',') or []
isCompleted = completed.indexOf(@key) isnt -1
prereqs = @TOOLTIPS[@key]?.prereqs
not isCompleted and _every prereqs, (prereq) ->
completed.indexOf(prereq) isnt -1
.publishReplay(1).refCount()
afterMount: (@$$el) =>
super
@disposable = @shouldBeShown.subscribe (shouldBeShown) =>
# TODO: show main page tooltips when closing overlayPage?
# one option is to have model.tooltip store all visible tooltips
if shouldBeShown and not @isShown
@isShown = true
# despite having this, ios still calls this twice, hence the flag above
@disposable?.unsubscribe()
setTimeout =>
checkIsReady = =>
if @$$el and @$$el.clientWidth
@_show @$$el
else
setTimeout checkIsReady, 100
checkIsReady()
, 0 # give time for re-render...
beforeUnmount: =>
@disposable?.unsubscribe()
@isShown = false
@isVisible.next false
close: =>
@$tooltip?.close()
_show: ($$el) =>
rect = $$el.getBoundingClientRect()
initialPosition = {x: rect.left, y: rect.top}
@$tooltip = new Tooltip {
@model
@key
@anchor
@offset
@isVisible
@zIndex
initialPosition
$title: @$title
$content: @$content
}
@model.tooltip.set$ @$tooltip
render: =>
z '.z-tooltip-positioner', {key: "<KEY>#{@key<KEY>}"}
| true | z = require 'zorium'
RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject
_find = require 'lodash/find'
_uniq = require 'lodash/uniq'
_every = require 'lodash/every'
Base = require '../base'
Tooltip = require '../tooltip'
colors = require '../../colors'
if window?
require './index.styl'
# this shows the main tooltip which is rendered in app.coffee
# if we render it here, it has issues with iscroll (having a position: fixed
# inside a transform)
module.exports = class TooltipPositioner extends Base
TOOLTIPS:
placeSearch:
prereqs: null
mapLayers:
prereqs: ['placeSearch']
mapTypes:
prereqs: ['mapLayers']
mapFilters:
prereqs: ['mapTypes']
placeTooltip:
prereqs: null
itemGuides:
prereqs: null
constructor: (options) ->
unless window? # could also return right away if cookie exists for perf
return
{@model, @isVisible, @offset, @key, @anchor, @$title, @$content,
@zIndex} = options
@isVisible ?= new RxBehaviorSubject false
@$title ?= @model.l.get "tooltips.#{@key}Title"
@$content ?= @model.l.get "tooltips.#{@key}Content"
@isShown = false
@shouldBeShown = @model.cookie.getStream().map (cookies) =>
completed = cookies.completedTooltips?.split(',') or []
isCompleted = completed.indexOf(@key) isnt -1
prereqs = @TOOLTIPS[@key]?.prereqs
not isCompleted and _every prereqs, (prereq) ->
completed.indexOf(prereq) isnt -1
.publishReplay(1).refCount()
afterMount: (@$$el) =>
super
@disposable = @shouldBeShown.subscribe (shouldBeShown) =>
# TODO: show main page tooltips when closing overlayPage?
# one option is to have model.tooltip store all visible tooltips
if shouldBeShown and not @isShown
@isShown = true
# despite having this, ios still calls this twice, hence the flag above
@disposable?.unsubscribe()
setTimeout =>
checkIsReady = =>
if @$$el and @$$el.clientWidth
@_show @$$el
else
setTimeout checkIsReady, 100
checkIsReady()
, 0 # give time for re-render...
beforeUnmount: =>
@disposable?.unsubscribe()
@isShown = false
@isVisible.next false
close: =>
@$tooltip?.close()
_show: ($$el) =>
rect = $$el.getBoundingClientRect()
initialPosition = {x: rect.left, y: rect.top}
@$tooltip = new Tooltip {
@model
@key
@anchor
@offset
@isVisible
@zIndex
initialPosition
$title: @$title
$content: @$content
}
@model.tooltip.set$ @$tooltip
render: =>
z '.z-tooltip-positioner', {key: "PI:KEY:<KEY>END_PI#{@keyPI:KEY:<KEY>END_PI}"}
|
[
{
"context": " # We're nosey.\n anal.track({\n 'userId': 'anonymous_user',\n 'event': 'Open App',\n 'properties': ",
"end": 1279,
"score": 0.9992847442626953,
"start": 1265,
"tag": "USERNAME",
"value": "anonymous_user"
},
{
"context": " the dev tools, because yolo\n... | app/index.coffee | sarthakganguly/notes | 191 | require './lib/setup.coffee'
Spine = require 'spine'
shell = window.require('shell') if window.require
Analytics = require 'analytics-node'
# Upgrader
Upgrader = require('./controllers/upgrader.coffee')
# Splitter. Not working in setup for whatever reason.
Splitter = require('./lib/splitter.js')
# Modals
Notebook = require './models/notebook.coffee'
Note = require './models/note.coffee'
# Controllers
Panel = require './controllers/panel.coffee'
Sidebar = require './controllers/sidebar.coffee'
Browser = require './controllers/browser.coffee'
Editor = require './controllers/editor.coffee'
Popover = require './controllers/popover.coffee'
Modal = require './controllers/modal.coffee'
Account = require './controllers/account.coffee'
Settings = require './controllers/settings.coffee'
class App extends Spine.Controller
elements:
'#panel': 'panel'
'#sidebar': 'sidebar'
'#browser': 'browser'
'#editor': 'editor'
'.popover-mask': 'popoverMask'
'.modal.preferences': 'settings'
events:
'mousedown': 'checkSel'
'mouseup': 'checkSel'
constructor: ->
super
Account.enableChecks()
Notebook.fetch()
Note.fetch()
anal = new Analytics('u9g1p9otaa')
# We're nosey.
anal.track({
'userId': 'anonymous_user',
'event': 'Open App',
'properties': {
'os': @getOS(),
'country': @getCountry(),
'language': navigator.language,
'version': localStorage.version
}
})
# Init the Splitter so we can see crap.
Splitter.init
parent: $('#parent')[0],
panels:
left:
el: $("#sidebar")[0]
min: 150
width: 200
max: 450
center:
el: $("#browser")[0]
min: 250
width: 300
max: 850
right:
el: $("#editor")[0]
min: 450
width: 550
max: Infinity
Modal.init()
Settings.init()
@settings = Settings.get()
# Init Stuff
new Upgrader()
@panel = new Panel( el: @panel )
@sidebar = new Sidebar( el: @sidebar )
@browser = new Browser( el: @browser )
@editor = new Editor( el: @editor )
@popover = new Popover( el: @popoverMask )
# We'll put the sync conenct here as well.
Spine.trigger 'sync:authorized' if Sync.oauth.service != "undefined"
Sync.anal()
# Stuff for node webkit.
$('a').on 'click', (e) ->
e.preventDefault()
if e.which is 1 or e.which is 2
shell.openExternal $(@).attr("href")
return false
# Going to use this to enable the dev tools, because yolo
# konami_keys = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]
# konami_index = 0
# $(document).keydown (e) ->
# location.reload() if e.keyCode is 116
# if e.keyCode is konami_keys[konami_index++]
# if konami_index is konami_keys.length
# $(document).unbind "keydown", arguments.callee
# <nw require>.Window.get().showDevTools()
# else
# konami_index = 0
# We're sending an event to the editor here because we need the checksel to be global
checkSel: ->
@editor.trigger("checkSel")
getOS: ->
ua = navigator.userAgent
return "Linux" if ua.indexOf("Linux") > -1
return "Mac OS X 10.9" if ua.indexOf("Mac OS X 10_9") > -1
return "Mac OS X 10.8" if ua.indexOf("Mac OS X 10_8") > -1
return "Mac OS X 10.7" if ua.indexOf("Mac OS X 10_7") > -1
return "Mac OS X 10.6" if ua.indexOf("Mac OS X 10_6") > -1
return "Windows XP" if ua.indexOf("Windows NT 6.2") > -1
return "Windows Vista" if ua.indexOf("Windows NT 6") > -1
return "Windows 7" if ua.indexOf("Windows NT 6.1") > -1
return "Windows 8" if ua.indexOf("Windows NT 6.2") > -1
return "Windows 8.1" if ua.indexOf("Windows NT 6.3") > -1
getCountry: ->
$.getJSON 'http://freegeoip.net/json/', (loc) ->
return loc.country_name
module.exports = App
| 216266 | require './lib/setup.coffee'
Spine = require 'spine'
shell = window.require('shell') if window.require
Analytics = require 'analytics-node'
# Upgrader
Upgrader = require('./controllers/upgrader.coffee')
# Splitter. Not working in setup for whatever reason.
Splitter = require('./lib/splitter.js')
# Modals
Notebook = require './models/notebook.coffee'
Note = require './models/note.coffee'
# Controllers
Panel = require './controllers/panel.coffee'
Sidebar = require './controllers/sidebar.coffee'
Browser = require './controllers/browser.coffee'
Editor = require './controllers/editor.coffee'
Popover = require './controllers/popover.coffee'
Modal = require './controllers/modal.coffee'
Account = require './controllers/account.coffee'
Settings = require './controllers/settings.coffee'
class App extends Spine.Controller
elements:
'#panel': 'panel'
'#sidebar': 'sidebar'
'#browser': 'browser'
'#editor': 'editor'
'.popover-mask': 'popoverMask'
'.modal.preferences': 'settings'
events:
'mousedown': 'checkSel'
'mouseup': 'checkSel'
constructor: ->
super
Account.enableChecks()
Notebook.fetch()
Note.fetch()
anal = new Analytics('u9g1p9otaa')
# We're nosey.
anal.track({
'userId': 'anonymous_user',
'event': 'Open App',
'properties': {
'os': @getOS(),
'country': @getCountry(),
'language': navigator.language,
'version': localStorage.version
}
})
# Init the Splitter so we can see crap.
Splitter.init
parent: $('#parent')[0],
panels:
left:
el: $("#sidebar")[0]
min: 150
width: 200
max: 450
center:
el: $("#browser")[0]
min: 250
width: 300
max: 850
right:
el: $("#editor")[0]
min: 450
width: 550
max: Infinity
Modal.init()
Settings.init()
@settings = Settings.get()
# Init Stuff
new Upgrader()
@panel = new Panel( el: @panel )
@sidebar = new Sidebar( el: @sidebar )
@browser = new Browser( el: @browser )
@editor = new Editor( el: @editor )
@popover = new Popover( el: @popoverMask )
# We'll put the sync conenct here as well.
Spine.trigger 'sync:authorized' if Sync.oauth.service != "undefined"
Sync.anal()
# Stuff for node webkit.
$('a').on 'click', (e) ->
e.preventDefault()
if e.which is 1 or e.which is 2
shell.openExternal $(@).attr("href")
return false
# Going to use this to enable the dev tools, because yolo
# konami_keys = [<KEY>]
# konami_index = 0
# $(document).keydown (e) ->
# location.reload() if e.keyCode is 116
# if e.keyCode is konami_keys[konami_index++]
# if konami_index is konami_keys.length
# $(document).unbind "keydown", arguments.callee
# <nw require>.Window.get().showDevTools()
# else
# konami_index = 0
# We're sending an event to the editor here because we need the checksel to be global
checkSel: ->
@editor.trigger("checkSel")
getOS: ->
ua = navigator.userAgent
return "Linux" if ua.indexOf("Linux") > -1
return "Mac OS X 10.9" if ua.indexOf("Mac OS X 10_9") > -1
return "Mac OS X 10.8" if ua.indexOf("Mac OS X 10_8") > -1
return "Mac OS X 10.7" if ua.indexOf("Mac OS X 10_7") > -1
return "Mac OS X 10.6" if ua.indexOf("Mac OS X 10_6") > -1
return "Windows XP" if ua.indexOf("Windows NT 6.2") > -1
return "Windows Vista" if ua.indexOf("Windows NT 6") > -1
return "Windows 7" if ua.indexOf("Windows NT 6.1") > -1
return "Windows 8" if ua.indexOf("Windows NT 6.2") > -1
return "Windows 8.1" if ua.indexOf("Windows NT 6.3") > -1
getCountry: ->
$.getJSON 'http://freegeoip.net/json/', (loc) ->
return loc.country_name
module.exports = App
| true | require './lib/setup.coffee'
Spine = require 'spine'
shell = window.require('shell') if window.require
Analytics = require 'analytics-node'
# Upgrader
Upgrader = require('./controllers/upgrader.coffee')
# Splitter. Not working in setup for whatever reason.
Splitter = require('./lib/splitter.js')
# Modals
Notebook = require './models/notebook.coffee'
Note = require './models/note.coffee'
# Controllers
Panel = require './controllers/panel.coffee'
Sidebar = require './controllers/sidebar.coffee'
Browser = require './controllers/browser.coffee'
Editor = require './controllers/editor.coffee'
Popover = require './controllers/popover.coffee'
Modal = require './controllers/modal.coffee'
Account = require './controllers/account.coffee'
Settings = require './controllers/settings.coffee'
class App extends Spine.Controller
elements:
'#panel': 'panel'
'#sidebar': 'sidebar'
'#browser': 'browser'
'#editor': 'editor'
'.popover-mask': 'popoverMask'
'.modal.preferences': 'settings'
events:
'mousedown': 'checkSel'
'mouseup': 'checkSel'
constructor: ->
super
Account.enableChecks()
Notebook.fetch()
Note.fetch()
anal = new Analytics('u9g1p9otaa')
# We're nosey.
anal.track({
'userId': 'anonymous_user',
'event': 'Open App',
'properties': {
'os': @getOS(),
'country': @getCountry(),
'language': navigator.language,
'version': localStorage.version
}
})
# Init the Splitter so we can see crap.
Splitter.init
parent: $('#parent')[0],
panels:
left:
el: $("#sidebar")[0]
min: 150
width: 200
max: 450
center:
el: $("#browser")[0]
min: 250
width: 300
max: 850
right:
el: $("#editor")[0]
min: 450
width: 550
max: Infinity
Modal.init()
Settings.init()
@settings = Settings.get()
# Init Stuff
new Upgrader()
@panel = new Panel( el: @panel )
@sidebar = new Sidebar( el: @sidebar )
@browser = new Browser( el: @browser )
@editor = new Editor( el: @editor )
@popover = new Popover( el: @popoverMask )
# We'll put the sync conenct here as well.
Spine.trigger 'sync:authorized' if Sync.oauth.service != "undefined"
Sync.anal()
# Stuff for node webkit.
$('a').on 'click', (e) ->
e.preventDefault()
if e.which is 1 or e.which is 2
shell.openExternal $(@).attr("href")
return false
# Going to use this to enable the dev tools, because yolo
# konami_keys = [PI:KEY:<KEY>END_PI]
# konami_index = 0
# $(document).keydown (e) ->
# location.reload() if e.keyCode is 116
# if e.keyCode is konami_keys[konami_index++]
# if konami_index is konami_keys.length
# $(document).unbind "keydown", arguments.callee
# <nw require>.Window.get().showDevTools()
# else
# konami_index = 0
# We're sending an event to the editor here because we need the checksel to be global
checkSel: ->
@editor.trigger("checkSel")
getOS: ->
ua = navigator.userAgent
return "Linux" if ua.indexOf("Linux") > -1
return "Mac OS X 10.9" if ua.indexOf("Mac OS X 10_9") > -1
return "Mac OS X 10.8" if ua.indexOf("Mac OS X 10_8") > -1
return "Mac OS X 10.7" if ua.indexOf("Mac OS X 10_7") > -1
return "Mac OS X 10.6" if ua.indexOf("Mac OS X 10_6") > -1
return "Windows XP" if ua.indexOf("Windows NT 6.2") > -1
return "Windows Vista" if ua.indexOf("Windows NT 6") > -1
return "Windows 7" if ua.indexOf("Windows NT 6.1") > -1
return "Windows 8" if ua.indexOf("Windows NT 6.2") > -1
return "Windows 8.1" if ua.indexOf("Windows NT 6.3") > -1
getCountry: ->
$.getJSON 'http://freegeoip.net/json/', (loc) ->
return loc.country_name
module.exports = App
|
[
{
"context": " keys = _.filter(keys, (key) -> key.match(/^__m2fa_/))\n ledger.storage.sync.get keys, (ite",
"end": 2015,
"score": 0.5207717418670654,
"start": 2014,
"tag": "KEY",
"value": "m"
},
{
"context": " keys = _.filter(keys, (key) -> key.match(/^__m2fa_/))\n ... | app/src/m2fa/m2fa.coffee | doged/ledger-wallet-doged-chrome | 1 | # M2FA, for Mobile 2 Factor Authentification, allow you to pair a mobile device,
# and then securely ask for user validation of the transaction.
@ledger.m2fa ?= {}
_.extend @ledger.m2fa,
clients: {}
# This method :
# - create a new pairingId ;
# - connect to the corresponding room on server ;
# - wait for mobile pubKey ;
# - send challenge to mobile ;
# - wait for challenge response ;
# - verify response ;
# - notify mobile of the pairing success/failure.
#
# The return promise :
# - notify when "pubKeyReceived" ;
# - notify when "challengeReceived" ;
# - resolve if dongle confirm pairing.
# - reject one any fail.
#
# @return [pairingId, aPromise]
pairDevice: () ->
d = Q.defer()
pairingId = @_nextPairingId()
client = @_clientFactory(pairingId)
@clients[pairingId] = client
client.on 'm2fa.identify', (e,pubKey) => @_onIdentify(client, pubKey, d)
client.on 'm2fa.challenge', (e,data) => @_onChallenge(client, data, d)
client.on 'm2fa.disconnect', (e, data) => @_onDisconnect(client, data, d)
[pairingId, d.promise, client]
# Creates a new pairing request and starts the m2fa pairing process.
# @see ledger.m2fa.PairingRequest
# @return [ledger.m2fa.PairingRequest] The request interface
requestPairing: () ->
[pairingId, promise, client] = @pairDevice()
new ledger.m2fa.PairingRequest(pairingId, promise, client)
# Allow you to assign a label to a pairingId (ex: "mobile Pierre").
# @params [String] pairingId
# @params [String] label
saveSecureScreen: (pairingId, screenData) ->
data =
name: screenData['name']
platform: screenData['platform']
uuid: screenData['uuid']
ledger.m2fa.PairedSecureScreen.create(pairingId, data).toSyncedStore()
# @return Promise an object where each key is pairingId and the value the associated label.
getPairingIds: () ->
d = Q.defer()
ledger.storage.sync.keys (keys) ->
try
keys = _.filter(keys, (key) -> key.match(/^__m2fa_/))
ledger.storage.sync.get keys, (items) ->
pairingCuple = {}
for key, value of items
pairingCuple[key.replace(/^__m2fa_/,'')] = value
d.resolve(pairingCuple)
catch err
d.reject(err)
d.promise
# Validate with M2FA that tx is correct.
# @param [Object] tx A ledger.wallet.Transaction
# @param [String] pairingId The paired mobile to send validation.
# @return A Q promise.
validateTx: (tx, pairingId) ->
ledger.api.M2faRestClient.instance.wakeUpSecureScreens([pairingId])
@_validateTx(tx, pairingId)
_validateTx: (tx, pairingId) ->
d = Q.defer()
client = @_getClientFor(pairingId)
client.off 'm2fa.accept'
client.off 'm2fa.response'
client.on 'm2fa.accept', ->
d.notify('accepted')
client.off 'm2fa.accept'
client.once 'm2fa.disconnect', ->
d.notify('disconnected')
client.on 'm2fa.response', (e,pin) ->
l "%c[M2FA][#{pairingId}] request's pin received :", "#888888", pin
client.stopIfNeccessary()
d.resolve(pin)
client.once 'm2fa.reject', ->
client.stopIfNeccessary()
d.reject('cancelled')
client.requestValidation(tx._out.authorizationPaired)
[client , d.promise]
# Validate with M2FA that tx is correct on every paired mobile.
# @param [Object] tx A ledger.wallet.Transaction
# @param [String] pairingId The paired mobile to send validation.
# @return A Q promise.
validateTxOnAll: (tx) ->
d = Q.defer()
clients = []
@getPairingIds().then (pairingIds) =>
ledger.api.M2faRestClient.instance.wakeUpSecureScreens(_.keys(pairingIds))
for pairingId, label of pairingIds
do (pairingId) =>
[client, promise] = @_validateTx(tx, pairingId)
clients.push client
promise.progress (msg) ->
if msg == 'accepted'
# Close all other client
@clients[pId].stopIfNeccessary() for pId, lbl of pairingIds when pId isnt pairingId
d.notify(msg)
.then (transaction) -> d.resolve(transaction)
.fail (er) -> d.reject er
.done()
.fail (er) ->
e er
throw er
[clients, d.promise]
validateTxOnMultipleIds: (tx, pairingIds) ->
d = Q.defer()
clients = []
ledger.api.M2faRestClient.instance.wakeUpSecureScreens(pairingIds)
for pairingId in pairingIds
do (pairingId) =>
[client, promise] = @_validateTx(tx, pairingId)
clients.push client
promise.progress (msg) =>
if msg == 'accepted'
# Close all other client
@clients[pId].stopIfNeccessary() for pId in pairingIds when pId isnt pairingId
d.notify(msg)
.then (transaction) -> d.resolve(transaction)
.fail (er) -> d.reject er
.done()
[clients, d.promise]
# Creates a transaction validation request and starts the validation process.
# @see ledger.m2fa.TransactionValidationRequest
# @return [ledger.m2fa.TransactionValidationRequest] The request interface
requestValidationOnAll: (tx) ->
[clients, promise] = @validateTxOnAll(tx)
new ledger.m2fa.TransactionValidationRequest(clients, promise)
requestValidation: (tx, screen) ->
unless _(screen).isArray()
[client, promise] = @validateTx(tx, screen.id)
new ledger.m2fa.TransactionValidationRequest([client], promise, tx, screen)
else
[clients, promise] = @validateTxOnMultipleIds(tx, _(screen).map (e) -> e.id)
new ledger.m2fa.TransactionValidationRequest(clients, promise)
requestValidationForLastPairing: (tx) ->
[client, promise] = @validateTx(tx)
_nextPairingId: () ->
# ledger.wallet.safe.randomBitIdAddress()
@_randomPairingId()
# @return a random 16 bytes pairingId + 1 checksum byte hex encoded.
_randomPairingId: () ->
words = sjcl.random.randomWords(4)
hexaWords = (Convert.toHexInt(w) for w in words).join('')
hash = sjcl.hash.sha256.hash(words)
pairingId = hexaWords + Convert.toHexByte(hash[0] >>> 24)
_getClientFor: (pairingId) ->
@clients[pairingId] ||= @_clientFactory(pairingId)
_onIdentify: (client, pubKey, d) ->
d.notify("pubKeyReceived", pubKey)
l("%c[_onIdentify] pubKeyReceived", "color: #4444cc", pubKey)
try
ledger.wallet.safe().initiateSecureScreen(pubKey).then((challenge) ->
l("%c[_onIdentify] challenge received:", "color: #4444cc", challenge)
d.notify("sendChallenge", challenge)
client.sendChallenge(challenge)
).fail( (err) =>
e(err)
d.reject('initiateFailure')
client.stopIfNeccessary()
).done()
catch err
e(err)
d.reject(err)
client.stopIfNeccessary()
_onChallenge: (client, data, d) ->
screenData = _.clone(client.lastIdentifyData)
d.notify("challengeReceived")
l("%c[_onChallenge] challengeReceived", "color: #4444cc", data)
try
ledger.wallet.safe().confirmSecureScreen(data).then( =>
l("%c[_onChallenge] SUCCESS !!!", "color: #00ff00", data )
client.confirmPairing()
d.notify("secureScreenConfirmed")
client.pairedDongleName.onComplete (name, err) =>
return d.reject('cancel') if err?
screenData['name'] = name
d.resolve @saveSecureScreen(client.pairingId, screenData)
).fail( (e) =>
l("%c[_onChallenge] >>> FAILURE <<<", "color: #ff0000", e)
client.rejectPairing()
d.reject('invalidChallenge')
).finally(=>
client.stopIfNeccessary()
).done()
catch err
e(err)
d.reject(err)
client.stopIfNeccessary()
_onDisconnect: (client, data, d) ->
d.notify "secureScreenDisconnect"
_clientFactory: (pairingId) ->
new ledger.m2fa.Client(pairingId)
#new ledger.m2fa.DebugClient(pairingId)
| 158438 | # M2FA, for Mobile 2 Factor Authentification, allow you to pair a mobile device,
# and then securely ask for user validation of the transaction.
@ledger.m2fa ?= {}
_.extend @ledger.m2fa,
clients: {}
# This method :
# - create a new pairingId ;
# - connect to the corresponding room on server ;
# - wait for mobile pubKey ;
# - send challenge to mobile ;
# - wait for challenge response ;
# - verify response ;
# - notify mobile of the pairing success/failure.
#
# The return promise :
# - notify when "pubKeyReceived" ;
# - notify when "challengeReceived" ;
# - resolve if dongle confirm pairing.
# - reject one any fail.
#
# @return [pairingId, aPromise]
pairDevice: () ->
d = Q.defer()
pairingId = @_nextPairingId()
client = @_clientFactory(pairingId)
@clients[pairingId] = client
client.on 'm2fa.identify', (e,pubKey) => @_onIdentify(client, pubKey, d)
client.on 'm2fa.challenge', (e,data) => @_onChallenge(client, data, d)
client.on 'm2fa.disconnect', (e, data) => @_onDisconnect(client, data, d)
[pairingId, d.promise, client]
# Creates a new pairing request and starts the m2fa pairing process.
# @see ledger.m2fa.PairingRequest
# @return [ledger.m2fa.PairingRequest] The request interface
requestPairing: () ->
[pairingId, promise, client] = @pairDevice()
new ledger.m2fa.PairingRequest(pairingId, promise, client)
# Allow you to assign a label to a pairingId (ex: "mobile Pierre").
# @params [String] pairingId
# @params [String] label
saveSecureScreen: (pairingId, screenData) ->
data =
name: screenData['name']
platform: screenData['platform']
uuid: screenData['uuid']
ledger.m2fa.PairedSecureScreen.create(pairingId, data).toSyncedStore()
# @return Promise an object where each key is pairingId and the value the associated label.
getPairingIds: () ->
d = Q.defer()
ledger.storage.sync.keys (keys) ->
try
keys = _.filter(keys, (key) -> key.match(/^__<KEY>2<KEY>_/))
ledger.storage.sync.get keys, (items) ->
pairingCuple = {}
for key, value of items
pairingCuple[key.replace(/^__m2fa_/,'')] = value
d.resolve(pairingCuple)
catch err
d.reject(err)
d.promise
# Validate with M2FA that tx is correct.
# @param [Object] tx A ledger.wallet.Transaction
# @param [String] pairingId The paired mobile to send validation.
# @return A Q promise.
validateTx: (tx, pairingId) ->
ledger.api.M2faRestClient.instance.wakeUpSecureScreens([pairingId])
@_validateTx(tx, pairingId)
_validateTx: (tx, pairingId) ->
d = Q.defer()
client = @_getClientFor(pairingId)
client.off 'm2fa.accept'
client.off 'm2fa.response'
client.on 'm2fa.accept', ->
d.notify('accepted')
client.off 'm2fa.accept'
client.once 'm2fa.disconnect', ->
d.notify('disconnected')
client.on 'm2fa.response', (e,pin) ->
l "%c[M2FA][#{pairingId}] request's pin received :", "#888888", pin
client.stopIfNeccessary()
d.resolve(pin)
client.once 'm2fa.reject', ->
client.stopIfNeccessary()
d.reject('cancelled')
client.requestValidation(tx._out.authorizationPaired)
[client , d.promise]
# Validate with M2FA that tx is correct on every paired mobile.
# @param [Object] tx A ledger.wallet.Transaction
# @param [String] pairingId The paired mobile to send validation.
# @return A Q promise.
validateTxOnAll: (tx) ->
d = Q.defer()
clients = []
@getPairingIds().then (pairingIds) =>
ledger.api.M2faRestClient.instance.wakeUpSecureScreens(_.keys(pairingIds))
for pairingId, label of pairingIds
do (pairingId) =>
[client, promise] = @_validateTx(tx, pairingId)
clients.push client
promise.progress (msg) ->
if msg == 'accepted'
# Close all other client
@clients[pId].stopIfNeccessary() for pId, lbl of pairingIds when pId isnt pairingId
d.notify(msg)
.then (transaction) -> d.resolve(transaction)
.fail (er) -> d.reject er
.done()
.fail (er) ->
e er
throw er
[clients, d.promise]
validateTxOnMultipleIds: (tx, pairingIds) ->
d = Q.defer()
clients = []
ledger.api.M2faRestClient.instance.wakeUpSecureScreens(pairingIds)
for pairingId in pairingIds
do (pairingId) =>
[client, promise] = @_validateTx(tx, pairingId)
clients.push client
promise.progress (msg) =>
if msg == 'accepted'
# Close all other client
@clients[pId].stopIfNeccessary() for pId in pairingIds when pId isnt pairingId
d.notify(msg)
.then (transaction) -> d.resolve(transaction)
.fail (er) -> d.reject er
.done()
[clients, d.promise]
# Creates a transaction validation request and starts the validation process.
# @see ledger.m2fa.TransactionValidationRequest
# @return [ledger.m2fa.TransactionValidationRequest] The request interface
requestValidationOnAll: (tx) ->
[clients, promise] = @validateTxOnAll(tx)
new ledger.m2fa.TransactionValidationRequest(clients, promise)
requestValidation: (tx, screen) ->
unless _(screen).isArray()
[client, promise] = @validateTx(tx, screen.id)
new ledger.m2fa.TransactionValidationRequest([client], promise, tx, screen)
else
[clients, promise] = @validateTxOnMultipleIds(tx, _(screen).map (e) -> e.id)
new ledger.m2fa.TransactionValidationRequest(clients, promise)
requestValidationForLastPairing: (tx) ->
[client, promise] = @validateTx(tx)
_nextPairingId: () ->
# ledger.wallet.safe.randomBitIdAddress()
@_randomPairingId()
# @return a random 16 bytes pairingId + 1 checksum byte hex encoded.
_randomPairingId: () ->
words = sjcl.random.randomWords(4)
hexaWords = (Convert.toHexInt(w) for w in words).join('')
hash = sjcl.hash.sha256.hash(words)
pairingId = hexaWords + Convert.toHexByte(hash[0] >>> 24)
_getClientFor: (pairingId) ->
@clients[pairingId] ||= @_clientFactory(pairingId)
_onIdentify: (client, pubKey, d) ->
d.notify("pubKeyReceived", pubKey)
l("%c[_onIdentify] pubKeyReceived", "color: #4444cc", pubKey)
try
ledger.wallet.safe().initiateSecureScreen(pubKey).then((challenge) ->
l("%c[_onIdentify] challenge received:", "color: #4444cc", challenge)
d.notify("sendChallenge", challenge)
client.sendChallenge(challenge)
).fail( (err) =>
e(err)
d.reject('initiateFailure')
client.stopIfNeccessary()
).done()
catch err
e(err)
d.reject(err)
client.stopIfNeccessary()
_onChallenge: (client, data, d) ->
screenData = _.clone(client.lastIdentifyData)
d.notify("challengeReceived")
l("%c[_onChallenge] challengeReceived", "color: #4444cc", data)
try
ledger.wallet.safe().confirmSecureScreen(data).then( =>
l("%c[_onChallenge] SUCCESS !!!", "color: #00ff00", data )
client.confirmPairing()
d.notify("secureScreenConfirmed")
client.pairedDongleName.onComplete (name, err) =>
return d.reject('cancel') if err?
screenData['name'] = name
d.resolve @saveSecureScreen(client.pairingId, screenData)
).fail( (e) =>
l("%c[_onChallenge] >>> FAILURE <<<", "color: #ff0000", e)
client.rejectPairing()
d.reject('invalidChallenge')
).finally(=>
client.stopIfNeccessary()
).done()
catch err
e(err)
d.reject(err)
client.stopIfNeccessary()
_onDisconnect: (client, data, d) ->
d.notify "secureScreenDisconnect"
_clientFactory: (pairingId) ->
new ledger.m2fa.Client(pairingId)
#new ledger.m2fa.DebugClient(pairingId)
| true | # M2FA, for Mobile 2 Factor Authentification, allow you to pair a mobile device,
# and then securely ask for user validation of the transaction.
@ledger.m2fa ?= {}
_.extend @ledger.m2fa,
clients: {}
# This method :
# - create a new pairingId ;
# - connect to the corresponding room on server ;
# - wait for mobile pubKey ;
# - send challenge to mobile ;
# - wait for challenge response ;
# - verify response ;
# - notify mobile of the pairing success/failure.
#
# The return promise :
# - notify when "pubKeyReceived" ;
# - notify when "challengeReceived" ;
# - resolve if dongle confirm pairing.
# - reject one any fail.
#
# @return [pairingId, aPromise]
pairDevice: () ->
d = Q.defer()
pairingId = @_nextPairingId()
client = @_clientFactory(pairingId)
@clients[pairingId] = client
client.on 'm2fa.identify', (e,pubKey) => @_onIdentify(client, pubKey, d)
client.on 'm2fa.challenge', (e,data) => @_onChallenge(client, data, d)
client.on 'm2fa.disconnect', (e, data) => @_onDisconnect(client, data, d)
[pairingId, d.promise, client]
# Creates a new pairing request and starts the m2fa pairing process.
# @see ledger.m2fa.PairingRequest
# @return [ledger.m2fa.PairingRequest] The request interface
requestPairing: () ->
[pairingId, promise, client] = @pairDevice()
new ledger.m2fa.PairingRequest(pairingId, promise, client)
# Allow you to assign a label to a pairingId (ex: "mobile Pierre").
# @params [String] pairingId
# @params [String] label
saveSecureScreen: (pairingId, screenData) ->
data =
name: screenData['name']
platform: screenData['platform']
uuid: screenData['uuid']
ledger.m2fa.PairedSecureScreen.create(pairingId, data).toSyncedStore()
# @return Promise an object where each key is pairingId and the value the associated label.
getPairingIds: () ->
d = Q.defer()
ledger.storage.sync.keys (keys) ->
try
keys = _.filter(keys, (key) -> key.match(/^__PI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PI_/))
ledger.storage.sync.get keys, (items) ->
pairingCuple = {}
for key, value of items
pairingCuple[key.replace(/^__m2fa_/,'')] = value
d.resolve(pairingCuple)
catch err
d.reject(err)
d.promise
# Validate with M2FA that tx is correct.
# @param [Object] tx A ledger.wallet.Transaction
# @param [String] pairingId The paired mobile to send validation.
# @return A Q promise.
validateTx: (tx, pairingId) ->
ledger.api.M2faRestClient.instance.wakeUpSecureScreens([pairingId])
@_validateTx(tx, pairingId)
_validateTx: (tx, pairingId) ->
d = Q.defer()
client = @_getClientFor(pairingId)
client.off 'm2fa.accept'
client.off 'm2fa.response'
client.on 'm2fa.accept', ->
d.notify('accepted')
client.off 'm2fa.accept'
client.once 'm2fa.disconnect', ->
d.notify('disconnected')
client.on 'm2fa.response', (e,pin) ->
l "%c[M2FA][#{pairingId}] request's pin received :", "#888888", pin
client.stopIfNeccessary()
d.resolve(pin)
client.once 'm2fa.reject', ->
client.stopIfNeccessary()
d.reject('cancelled')
client.requestValidation(tx._out.authorizationPaired)
[client , d.promise]
# Validate with M2FA that tx is correct on every paired mobile.
# @param [Object] tx A ledger.wallet.Transaction
# @param [String] pairingId The paired mobile to send validation.
# @return A Q promise.
validateTxOnAll: (tx) ->
d = Q.defer()
clients = []
@getPairingIds().then (pairingIds) =>
ledger.api.M2faRestClient.instance.wakeUpSecureScreens(_.keys(pairingIds))
for pairingId, label of pairingIds
do (pairingId) =>
[client, promise] = @_validateTx(tx, pairingId)
clients.push client
promise.progress (msg) ->
if msg == 'accepted'
# Close all other client
@clients[pId].stopIfNeccessary() for pId, lbl of pairingIds when pId isnt pairingId
d.notify(msg)
.then (transaction) -> d.resolve(transaction)
.fail (er) -> d.reject er
.done()
.fail (er) ->
e er
throw er
[clients, d.promise]
validateTxOnMultipleIds: (tx, pairingIds) ->
d = Q.defer()
clients = []
ledger.api.M2faRestClient.instance.wakeUpSecureScreens(pairingIds)
for pairingId in pairingIds
do (pairingId) =>
[client, promise] = @_validateTx(tx, pairingId)
clients.push client
promise.progress (msg) =>
if msg == 'accepted'
# Close all other client
@clients[pId].stopIfNeccessary() for pId in pairingIds when pId isnt pairingId
d.notify(msg)
.then (transaction) -> d.resolve(transaction)
.fail (er) -> d.reject er
.done()
[clients, d.promise]
# Creates a transaction validation request and starts the validation process.
# @see ledger.m2fa.TransactionValidationRequest
# @return [ledger.m2fa.TransactionValidationRequest] The request interface
requestValidationOnAll: (tx) ->
[clients, promise] = @validateTxOnAll(tx)
new ledger.m2fa.TransactionValidationRequest(clients, promise)
requestValidation: (tx, screen) ->
unless _(screen).isArray()
[client, promise] = @validateTx(tx, screen.id)
new ledger.m2fa.TransactionValidationRequest([client], promise, tx, screen)
else
[clients, promise] = @validateTxOnMultipleIds(tx, _(screen).map (e) -> e.id)
new ledger.m2fa.TransactionValidationRequest(clients, promise)
requestValidationForLastPairing: (tx) ->
[client, promise] = @validateTx(tx)
_nextPairingId: () ->
# ledger.wallet.safe.randomBitIdAddress()
@_randomPairingId()
# @return a random 16 bytes pairingId + 1 checksum byte hex encoded.
_randomPairingId: () ->
words = sjcl.random.randomWords(4)
hexaWords = (Convert.toHexInt(w) for w in words).join('')
hash = sjcl.hash.sha256.hash(words)
pairingId = hexaWords + Convert.toHexByte(hash[0] >>> 24)
_getClientFor: (pairingId) ->
@clients[pairingId] ||= @_clientFactory(pairingId)
_onIdentify: (client, pubKey, d) ->
d.notify("pubKeyReceived", pubKey)
l("%c[_onIdentify] pubKeyReceived", "color: #4444cc", pubKey)
try
ledger.wallet.safe().initiateSecureScreen(pubKey).then((challenge) ->
l("%c[_onIdentify] challenge received:", "color: #4444cc", challenge)
d.notify("sendChallenge", challenge)
client.sendChallenge(challenge)
).fail( (err) =>
e(err)
d.reject('initiateFailure')
client.stopIfNeccessary()
).done()
catch err
e(err)
d.reject(err)
client.stopIfNeccessary()
_onChallenge: (client, data, d) ->
screenData = _.clone(client.lastIdentifyData)
d.notify("challengeReceived")
l("%c[_onChallenge] challengeReceived", "color: #4444cc", data)
try
ledger.wallet.safe().confirmSecureScreen(data).then( =>
l("%c[_onChallenge] SUCCESS !!!", "color: #00ff00", data )
client.confirmPairing()
d.notify("secureScreenConfirmed")
client.pairedDongleName.onComplete (name, err) =>
return d.reject('cancel') if err?
screenData['name'] = name
d.resolve @saveSecureScreen(client.pairingId, screenData)
).fail( (e) =>
l("%c[_onChallenge] >>> FAILURE <<<", "color: #ff0000", e)
client.rejectPairing()
d.reject('invalidChallenge')
).finally(=>
client.stopIfNeccessary()
).done()
catch err
e(err)
d.reject(err)
client.stopIfNeccessary()
_onDisconnect: (client, data, d) ->
d.notify "secureScreenDisconnect"
_clientFactory: (pairingId) ->
new ledger.m2fa.Client(pairingId)
#new ledger.m2fa.DebugClient(pairingId)
|
[
{
"context": "se.Schema(\n name:\n type: String\n default: 'Anonymous'\n \n date:\n type: Date\n default: Date.now\n",
"end": 113,
"score": 0.6184452772140503,
"start": 104,
"tag": "NAME",
"value": "Anonymous"
}
] | server/models/schemas/postSchema.coffee | Nuke928/nchan | 0 | mongoose = require 'mongoose'
module.exports = mongoose.Schema(
name:
type: String
default: 'Anonymous'
date:
type: Date
default: Date.now
image: String
id:
type: Number
isOp:
type: Boolean
default: false
text:
type: String
maxLength: 500
file: String
) | 97362 | mongoose = require 'mongoose'
module.exports = mongoose.Schema(
name:
type: String
default: '<NAME>'
date:
type: Date
default: Date.now
image: String
id:
type: Number
isOp:
type: Boolean
default: false
text:
type: String
maxLength: 500
file: String
) | true | mongoose = require 'mongoose'
module.exports = mongoose.Schema(
name:
type: String
default: 'PI:NAME:<NAME>END_PI'
date:
type: Date
default: Date.now
image: String
id:
type: Number
isOp:
type: Boolean
default: false
text:
type: String
maxLength: 500
file: String
) |
[
{
"context": "lowing to http://YourHueHub/api\n#\n# {\"username\": \"YourHash\", \"devicetype\": \"YourAppName\"}\n# If you have not ",
"end": 490,
"score": 0.9996780157089233,
"start": 482,
"tag": "USERNAME",
"value": "YourHash"
},
{
"context": "d you should receive;\n#\n# {\"succes... | src/philips-hue.coffee | kingbin/hubot-philipshue | 6 | # Description:
# Control your Philips Hue Lights from HUBOT! BAM, easy candy for the kids
#
# Configuration:
# PHILIPS_HUE_HASH : export PHILIPS_HUE_HASH="secrets"
# PHILIPS_HUE_IP : export PHILIPS_HUE_IP="xxx.xxx.xxx.xxx"
#
# Setting your Hue Hash
#
# This needs to be done once, it seems older versions of the Hue bridge used an md5 hash as a 'username' but now you can use anything.
#
# Make an HTTP POST request of the following to http://YourHueHub/api
#
# {"username": "YourHash", "devicetype": "YourAppName"}
# If you have not pressed the button on the Hue Hub you will receive an error like this;
#
# {"error":{"type":101,"address":"/","description":"link button not pressed"}}
# Press the link button on the hub and try again and you should receive;
#
# {"success":{"username":"YourHash"}}
# The key above will be the username you sent, remember this, you'll need it in all future requests
#
# ie: curl -v -H "Content-Type: application/json" -X POST 'http://YourHueHub/api' -d '{"username": "YourHash", "devicetype": "YourAppName"}'
#
# Dependencies:
# "node-hue-api": "^2.4"
#
# Commands:
# hubot hue lights - list all lights
# hubot hue light <light number> - shows light status
# hubot hue turn light <light number> <on|off> - flips the switch
# hubot hue groups - lists the groups of lights
# hubot hue config - reads bridge config
# hubot hue (alert|alerts) light <light number> - blink once or blink for 10 seconds specific light
# hubot hue (colors|colorloop|colorloop) (on|off) light <light number> - enable or disable the colorloop effect
# hubot hue hsb light <light number> <hue 0-65535> <saturation 0-254> <brightness 0-254>
# hubot hue xy light <light number> <x 0.0-1.0> <y 0.0-1.0>
# hubot hue ct light <light number> <color temp 153-500>
# hubot hue group <group name>=[<comma separated list of light indexes>]
# hubot hue rm group <group number> - remove grouping of lights with ID <group number>
# hubot hue @<group name> <on|off> - turn all lights in <group name> on or off
# hubot hue @<group name> hsb=(<hue>,<sat>,<bri>) - set hsb value for all lights in group
# hubot hue @<group name> xy=(<x>,<y>) - set x, y value for all lights in group
# hubot hue @<group name> ct=<color temp> - set color temp for all lights in group
#
# Author:
# kingbin - chris.blazek@gmail.com
hue = require('node-hue-api').v3
LightState = hue.lightStates.LightState
GroupLightState = hue.lightStates.GroupLightState
module.exports = (robot) ->
baseUrl = process.env.PHILIPS_HUE_IP
hash = process.env.PHILIPS_HUE_HASH
# Connect based on provided string
if /^https\:/i.test(baseUrl)
hueApi = hue.api.createLocal(baseUrl).connect(hash)
else
hueApi = hue.api.createInsecureLocal(baseUrl).connect(hash)
state = new LightState()
# GROUP COMMANDS
robot.respond /hue (?:ls )?groups/i, (msg) ->
hueApi.then (api) ->
api.groups.getAll()
.then (groups) ->
robot.logger.debug groups
msg.send "Light groups:"
for group in groups
if group.id == 0
msg.send "- #{group.id}: '#{group.name}' (All)"
else
msg.send "- #{group.id}: '#{group.name}' (#{group.lights.join(', ')})"
.catch (err) ->
handleError msg, err
robot.respond /hue group (\w+)=(\[((\d)+,)*((\d)+)\])/i, (msg) ->
groupName = msg.match[1]
groupLights = JSON.parse(msg.match[2])
msg.send "Setting #{groupName} to #{groupLights.join(', ')} ..."
hueApi.then (api) ->
lightGroup = hue.model.createLightGroup()
lightGroup.name = groupName
lightGroup.lights = groupLights
api.groups.createGroup(lightGroup)
.then (group) ->
robot.logger.debug group
msg.send "Group created!"
.catch (err) ->
handleError msg, err
robot.respond /hue rm group (\d)/i, (msg) ->
groupId = msg.match[1]
msg.send "Deleting Group #{groupId} ..."
hueApi.then (api) ->
api.groups.deleteGroup(groupId)
.then (response) ->
robot.logger.debug response
msg.send "Group deleted!"
.catch (err) ->
handleError msg, err
# LIGHT COMMANDS
robot.respond /hue lights/i, (msg) ->
hueApi.then (api) ->
api.lights.getAll()
.then (lights) ->
robot.logger.debug lights
msg.send "Connected hue lights:"
for light in lights
msg.send "- #{light.id}: '#{light.name}'"
.catch (err) ->
handleError msg, err
robot.respond /hue light (\d+)/i, (msg) ->
lightId = parseInt(msg.match[1], 10)
hueApi.then (api) ->
api.lights.getLight(lightId)
.then (light) ->
robot.logger.debug light
msg.send "Light Status:"
msg.send "- On: #{light.state.on}"
msg.send "- Reachable: #{light.state.reachable}"
msg.send "- Name: '#{light.name}'"
msg.send "- Model: #{light.modelid} - #{light.type}"
msg.send "- Unique ID: #{light.uniqueid}"
msg.send "- Software Version: #{light.swversion}"
.catch (err) ->
handleError msg, err
robot.respond /hue @(.*) hsb=\((\d+),(\d+),(\d+)\)$/i, (msg) ->
[groupName, vHue, vSat, vBri] = msg.match[1..4]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: Hue=#{vHue}, Saturation=#{vSat}, Brightness=#{vBri}"
lightState = new GroupLightState().on(true).bri(vBri).hue(vHue).sat(vSat)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue hsb light (\d+) (\d+) (\d+) (\d+)/i, (msg) ->
[light, vHue, vSat, vBri] = msg.match[1..4]
msg.send "Setting light #{light} to: Hue=#{vHue}, Saturation=#{vSat}, Brightness=#{vBri}"
lightState = new LightState().on(true).bri(vBri).hue(vHue).sat(vSat)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) xy=\(([0-9]*[.][0-9]+),([0-9]*[.][0-9]+)\)/i, (msg) ->
[groupName,x,y] = msg.match[1..3]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: X=#{x}, Y=#{y}"
lightState = new GroupLightState().on(true).xy(x, y)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue xy light (.*) ([0-9]*[.][0-9]+) ([0-9]*[.][0-9]+)/i, (msg) ->
[light,x,y] = msg.match[1..3]
msg.send "Setting light #{light} to: X=#{x}, Y=#{y}"
lightState = new LightState().on(true).xy(x, y)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) ct=(\d{3})/i, (msg) ->
[groupName,ct] = msg.match[1..2]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: CT=#{ct}"
lightState = new GroupLightState().on(true).ct(ct)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue ct light (.*) (\d{3})/i, (msg) ->
[light,ct] = msg.match[1..2]
msg.send "Setting light #{light} to: CT=#{ct}"
lightState = new LightState().on(true).ct(ct)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) (on|off)/i, (msg) ->
[groupName, state] = msg.match[1..2]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to #{state}"
lightState = new GroupLightState().on(state=='on')
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue turn light (\d+) (on|off)/i, (msg) ->
lightId = msg.match[1]
state = msg.match[2]
msg.send "Turning light #{lightId} #{state} ..."
hueApi.then (api) ->
lightState = new LightState().on(state=='on')
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} turned #{state}"
.catch (err) ->
handleError msg, err
robot.respond /hue (alert|alerts) light (.+)/i, (msg) ->
alertLength = msg.match[1]
lightId = parseInt(msg.match[2], 10)
if alertLength == 'alert'
alertText = 'short alert'
lightState = new LightState().alertShort()
else
alertText = 'long alert'
lightState = new LightState().alertLong()
msg.send "Setting light #{lightId} to #{alertText} ..."
hueApi.then (api) ->
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} set to #{alertText}"
.catch (err) ->
handleError msg, err
robot.respond /hue (?:colors|colorloop|loop) (on|off) light (.+)/i, (msg) ->
loopState = msg.match[1]
lightId = parseInt(msg.match[2], 10)
if loopState == 'on'
lightState = new LightState().on().effect('colorloop')
else
lightState = new LightState().on().effect('none')
msg.send "Setting light #{lightId} colorloop to #{loopState} ..."
hueApi.then (api) ->
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} colorloop set to #{loopState}"
.catch (err) ->
handleError msg, err
# BRIDGE COMMANDS
robot.respond /hue config/i, (msg) ->
hueApi.then (api) ->
api.configuration.getConfiguration()
.then (config) ->
robot.logger.debug config
msg.send "Base Station: '#{config.name}'"
msg.send "IP: #{config.ipaddress} / MAC: #{config.mac} / ZigBee Channel: #{config.zigbeechannel}"
msg.send "Software: #{config.swversion} / API: #{config.apiversion}"
.catch (err) ->
handleError msg, err
# HELPERS
groupMap = (groupName, callback) ->
hueApi.then (api) ->
api.groups.getAll()
.then (groups) ->
result = {all: 0}
for group in groups
robot.logger.debug group
result[group.name.toLowerCase()] = group.id
match = result[groupName.toLowerCase()]
callback match
.catch (err) ->
console.error err
handleError = (res, err) ->
robot.logger.debug err
switch err.code
when 'ETIMEDOUT'
res.send 'Connection timed out to Hue bridge.'
else
res.send "An error ocurred: #{err}"
| 68233 | # Description:
# Control your Philips Hue Lights from HUBOT! BAM, easy candy for the kids
#
# Configuration:
# PHILIPS_HUE_HASH : export PHILIPS_HUE_HASH="secrets"
# PHILIPS_HUE_IP : export PHILIPS_HUE_IP="xxx.xxx.xxx.xxx"
#
# Setting your Hue Hash
#
# This needs to be done once, it seems older versions of the Hue bridge used an md5 hash as a 'username' but now you can use anything.
#
# Make an HTTP POST request of the following to http://YourHueHub/api
#
# {"username": "YourHash", "devicetype": "YourAppName"}
# If you have not pressed the button on the Hue Hub you will receive an error like this;
#
# {"error":{"type":101,"address":"/","description":"link button not pressed"}}
# Press the link button on the hub and try again and you should receive;
#
# {"success":{"username":"YourHash"}}
# The key above will be the username you sent, remember this, you'll need it in all future requests
#
# ie: curl -v -H "Content-Type: application/json" -X POST 'http://YourHueHub/api' -d '{"username": "YourHash", "devicetype": "YourAppName"}'
#
# Dependencies:
# "node-hue-api": "^2.4"
#
# Commands:
# hubot hue lights - list all lights
# hubot hue light <light number> - shows light status
# hubot hue turn light <light number> <on|off> - flips the switch
# hubot hue groups - lists the groups of lights
# hubot hue config - reads bridge config
# hubot hue (alert|alerts) light <light number> - blink once or blink for 10 seconds specific light
# hubot hue (colors|colorloop|colorloop) (on|off) light <light number> - enable or disable the colorloop effect
# hubot hue hsb light <light number> <hue 0-65535> <saturation 0-254> <brightness 0-254>
# hubot hue xy light <light number> <x 0.0-1.0> <y 0.0-1.0>
# hubot hue ct light <light number> <color temp 153-500>
# hubot hue group <group name>=[<comma separated list of light indexes>]
# hubot hue rm group <group number> - remove grouping of lights with ID <group number>
# hubot hue @<group name> <on|off> - turn all lights in <group name> on or off
# hubot hue @<group name> hsb=(<hue>,<sat>,<bri>) - set hsb value for all lights in group
# hubot hue @<group name> xy=(<x>,<y>) - set x, y value for all lights in group
# hubot hue @<group name> ct=<color temp> - set color temp for all lights in group
#
# Author:
# kingbin - <EMAIL>
hue = require('node-hue-api').v3
LightState = hue.lightStates.LightState
GroupLightState = hue.lightStates.GroupLightState
module.exports = (robot) ->
baseUrl = process.env.PHILIPS_HUE_IP
hash = process.env.PHILIPS_HUE_HASH
# Connect based on provided string
if /^https\:/i.test(baseUrl)
hueApi = hue.api.createLocal(baseUrl).connect(hash)
else
hueApi = hue.api.createInsecureLocal(baseUrl).connect(hash)
state = new LightState()
# GROUP COMMANDS
robot.respond /hue (?:ls )?groups/i, (msg) ->
hueApi.then (api) ->
api.groups.getAll()
.then (groups) ->
robot.logger.debug groups
msg.send "Light groups:"
for group in groups
if group.id == 0
msg.send "- #{group.id}: '#{group.name}' (All)"
else
msg.send "- #{group.id}: '#{group.name}' (#{group.lights.join(', ')})"
.catch (err) ->
handleError msg, err
robot.respond /hue group (\w+)=(\[((\d)+,)*((\d)+)\])/i, (msg) ->
groupName = msg.match[1]
groupLights = JSON.parse(msg.match[2])
msg.send "Setting #{groupName} to #{groupLights.join(', ')} ..."
hueApi.then (api) ->
lightGroup = hue.model.createLightGroup()
lightGroup.name = groupName
lightGroup.lights = groupLights
api.groups.createGroup(lightGroup)
.then (group) ->
robot.logger.debug group
msg.send "Group created!"
.catch (err) ->
handleError msg, err
robot.respond /hue rm group (\d)/i, (msg) ->
groupId = msg.match[1]
msg.send "Deleting Group #{groupId} ..."
hueApi.then (api) ->
api.groups.deleteGroup(groupId)
.then (response) ->
robot.logger.debug response
msg.send "Group deleted!"
.catch (err) ->
handleError msg, err
# LIGHT COMMANDS
robot.respond /hue lights/i, (msg) ->
hueApi.then (api) ->
api.lights.getAll()
.then (lights) ->
robot.logger.debug lights
msg.send "Connected hue lights:"
for light in lights
msg.send "- #{light.id}: '#{light.name}'"
.catch (err) ->
handleError msg, err
robot.respond /hue light (\d+)/i, (msg) ->
lightId = parseInt(msg.match[1], 10)
hueApi.then (api) ->
api.lights.getLight(lightId)
.then (light) ->
robot.logger.debug light
msg.send "Light Status:"
msg.send "- On: #{light.state.on}"
msg.send "- Reachable: #{light.state.reachable}"
msg.send "- Name: '#{light.name}'"
msg.send "- Model: #{light.modelid} - #{light.type}"
msg.send "- Unique ID: #{light.uniqueid}"
msg.send "- Software Version: #{light.swversion}"
.catch (err) ->
handleError msg, err
robot.respond /hue @(.*) hsb=\((\d+),(\d+),(\d+)\)$/i, (msg) ->
[groupName, vHue, vSat, vBri] = msg.match[1..4]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: Hue=#{vHue}, Saturation=#{vSat}, Brightness=#{vBri}"
lightState = new GroupLightState().on(true).bri(vBri).hue(vHue).sat(vSat)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue hsb light (\d+) (\d+) (\d+) (\d+)/i, (msg) ->
[light, vHue, vSat, vBri] = msg.match[1..4]
msg.send "Setting light #{light} to: Hue=#{vHue}, Saturation=#{vSat}, Brightness=#{vBri}"
lightState = new LightState().on(true).bri(vBri).hue(vHue).sat(vSat)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) xy=\(([0-9]*[.][0-9]+),([0-9]*[.][0-9]+)\)/i, (msg) ->
[groupName,x,y] = msg.match[1..3]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: X=#{x}, Y=#{y}"
lightState = new GroupLightState().on(true).xy(x, y)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue xy light (.*) ([0-9]*[.][0-9]+) ([0-9]*[.][0-9]+)/i, (msg) ->
[light,x,y] = msg.match[1..3]
msg.send "Setting light #{light} to: X=#{x}, Y=#{y}"
lightState = new LightState().on(true).xy(x, y)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) ct=(\d{3})/i, (msg) ->
[groupName,ct] = msg.match[1..2]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: CT=#{ct}"
lightState = new GroupLightState().on(true).ct(ct)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue ct light (.*) (\d{3})/i, (msg) ->
[light,ct] = msg.match[1..2]
msg.send "Setting light #{light} to: CT=#{ct}"
lightState = new LightState().on(true).ct(ct)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) (on|off)/i, (msg) ->
[groupName, state] = msg.match[1..2]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to #{state}"
lightState = new GroupLightState().on(state=='on')
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue turn light (\d+) (on|off)/i, (msg) ->
lightId = msg.match[1]
state = msg.match[2]
msg.send "Turning light #{lightId} #{state} ..."
hueApi.then (api) ->
lightState = new LightState().on(state=='on')
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} turned #{state}"
.catch (err) ->
handleError msg, err
robot.respond /hue (alert|alerts) light (.+)/i, (msg) ->
alertLength = msg.match[1]
lightId = parseInt(msg.match[2], 10)
if alertLength == 'alert'
alertText = 'short alert'
lightState = new LightState().alertShort()
else
alertText = 'long alert'
lightState = new LightState().alertLong()
msg.send "Setting light #{lightId} to #{alertText} ..."
hueApi.then (api) ->
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} set to #{alertText}"
.catch (err) ->
handleError msg, err
robot.respond /hue (?:colors|colorloop|loop) (on|off) light (.+)/i, (msg) ->
loopState = msg.match[1]
lightId = parseInt(msg.match[2], 10)
if loopState == 'on'
lightState = new LightState().on().effect('colorloop')
else
lightState = new LightState().on().effect('none')
msg.send "Setting light #{lightId} colorloop to #{loopState} ..."
hueApi.then (api) ->
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} colorloop set to #{loopState}"
.catch (err) ->
handleError msg, err
# BRIDGE COMMANDS
robot.respond /hue config/i, (msg) ->
hueApi.then (api) ->
api.configuration.getConfiguration()
.then (config) ->
robot.logger.debug config
msg.send "Base Station: '#{config.name}'"
msg.send "IP: #{config.ipaddress} / MAC: #{config.mac} / ZigBee Channel: #{config.zigbeechannel}"
msg.send "Software: #{config.swversion} / API: #{config.apiversion}"
.catch (err) ->
handleError msg, err
# HELPERS
groupMap = (groupName, callback) ->
hueApi.then (api) ->
api.groups.getAll()
.then (groups) ->
result = {all: 0}
for group in groups
robot.logger.debug group
result[group.name.toLowerCase()] = group.id
match = result[groupName.toLowerCase()]
callback match
.catch (err) ->
console.error err
handleError = (res, err) ->
robot.logger.debug err
switch err.code
when 'ETIMEDOUT'
res.send 'Connection timed out to Hue bridge.'
else
res.send "An error ocurred: #{err}"
| true | # Description:
# Control your Philips Hue Lights from HUBOT! BAM, easy candy for the kids
#
# Configuration:
# PHILIPS_HUE_HASH : export PHILIPS_HUE_HASH="secrets"
# PHILIPS_HUE_IP : export PHILIPS_HUE_IP="xxx.xxx.xxx.xxx"
#
# Setting your Hue Hash
#
# This needs to be done once, it seems older versions of the Hue bridge used an md5 hash as a 'username' but now you can use anything.
#
# Make an HTTP POST request of the following to http://YourHueHub/api
#
# {"username": "YourHash", "devicetype": "YourAppName"}
# If you have not pressed the button on the Hue Hub you will receive an error like this;
#
# {"error":{"type":101,"address":"/","description":"link button not pressed"}}
# Press the link button on the hub and try again and you should receive;
#
# {"success":{"username":"YourHash"}}
# The key above will be the username you sent, remember this, you'll need it in all future requests
#
# ie: curl -v -H "Content-Type: application/json" -X POST 'http://YourHueHub/api' -d '{"username": "YourHash", "devicetype": "YourAppName"}'
#
# Dependencies:
# "node-hue-api": "^2.4"
#
# Commands:
# hubot hue lights - list all lights
# hubot hue light <light number> - shows light status
# hubot hue turn light <light number> <on|off> - flips the switch
# hubot hue groups - lists the groups of lights
# hubot hue config - reads bridge config
# hubot hue (alert|alerts) light <light number> - blink once or blink for 10 seconds specific light
# hubot hue (colors|colorloop|colorloop) (on|off) light <light number> - enable or disable the colorloop effect
# hubot hue hsb light <light number> <hue 0-65535> <saturation 0-254> <brightness 0-254>
# hubot hue xy light <light number> <x 0.0-1.0> <y 0.0-1.0>
# hubot hue ct light <light number> <color temp 153-500>
# hubot hue group <group name>=[<comma separated list of light indexes>]
# hubot hue rm group <group number> - remove grouping of lights with ID <group number>
# hubot hue @<group name> <on|off> - turn all lights in <group name> on or off
# hubot hue @<group name> hsb=(<hue>,<sat>,<bri>) - set hsb value for all lights in group
# hubot hue @<group name> xy=(<x>,<y>) - set x, y value for all lights in group
# hubot hue @<group name> ct=<color temp> - set color temp for all lights in group
#
# Author:
# kingbin - PI:EMAIL:<EMAIL>END_PI
hue = require('node-hue-api').v3
LightState = hue.lightStates.LightState
GroupLightState = hue.lightStates.GroupLightState
module.exports = (robot) ->
baseUrl = process.env.PHILIPS_HUE_IP
hash = process.env.PHILIPS_HUE_HASH
# Connect based on provided string
if /^https\:/i.test(baseUrl)
hueApi = hue.api.createLocal(baseUrl).connect(hash)
else
hueApi = hue.api.createInsecureLocal(baseUrl).connect(hash)
state = new LightState()
# GROUP COMMANDS
robot.respond /hue (?:ls )?groups/i, (msg) ->
hueApi.then (api) ->
api.groups.getAll()
.then (groups) ->
robot.logger.debug groups
msg.send "Light groups:"
for group in groups
if group.id == 0
msg.send "- #{group.id}: '#{group.name}' (All)"
else
msg.send "- #{group.id}: '#{group.name}' (#{group.lights.join(', ')})"
.catch (err) ->
handleError msg, err
robot.respond /hue group (\w+)=(\[((\d)+,)*((\d)+)\])/i, (msg) ->
groupName = msg.match[1]
groupLights = JSON.parse(msg.match[2])
msg.send "Setting #{groupName} to #{groupLights.join(', ')} ..."
hueApi.then (api) ->
lightGroup = hue.model.createLightGroup()
lightGroup.name = groupName
lightGroup.lights = groupLights
api.groups.createGroup(lightGroup)
.then (group) ->
robot.logger.debug group
msg.send "Group created!"
.catch (err) ->
handleError msg, err
robot.respond /hue rm group (\d)/i, (msg) ->
groupId = msg.match[1]
msg.send "Deleting Group #{groupId} ..."
hueApi.then (api) ->
api.groups.deleteGroup(groupId)
.then (response) ->
robot.logger.debug response
msg.send "Group deleted!"
.catch (err) ->
handleError msg, err
# LIGHT COMMANDS
robot.respond /hue lights/i, (msg) ->
hueApi.then (api) ->
api.lights.getAll()
.then (lights) ->
robot.logger.debug lights
msg.send "Connected hue lights:"
for light in lights
msg.send "- #{light.id}: '#{light.name}'"
.catch (err) ->
handleError msg, err
robot.respond /hue light (\d+)/i, (msg) ->
lightId = parseInt(msg.match[1], 10)
hueApi.then (api) ->
api.lights.getLight(lightId)
.then (light) ->
robot.logger.debug light
msg.send "Light Status:"
msg.send "- On: #{light.state.on}"
msg.send "- Reachable: #{light.state.reachable}"
msg.send "- Name: '#{light.name}'"
msg.send "- Model: #{light.modelid} - #{light.type}"
msg.send "- Unique ID: #{light.uniqueid}"
msg.send "- Software Version: #{light.swversion}"
.catch (err) ->
handleError msg, err
robot.respond /hue @(.*) hsb=\((\d+),(\d+),(\d+)\)$/i, (msg) ->
[groupName, vHue, vSat, vBri] = msg.match[1..4]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: Hue=#{vHue}, Saturation=#{vSat}, Brightness=#{vBri}"
lightState = new GroupLightState().on(true).bri(vBri).hue(vHue).sat(vSat)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue hsb light (\d+) (\d+) (\d+) (\d+)/i, (msg) ->
[light, vHue, vSat, vBri] = msg.match[1..4]
msg.send "Setting light #{light} to: Hue=#{vHue}, Saturation=#{vSat}, Brightness=#{vBri}"
lightState = new LightState().on(true).bri(vBri).hue(vHue).sat(vSat)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) xy=\(([0-9]*[.][0-9]+),([0-9]*[.][0-9]+)\)/i, (msg) ->
[groupName,x,y] = msg.match[1..3]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: X=#{x}, Y=#{y}"
lightState = new GroupLightState().on(true).xy(x, y)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue xy light (.*) ([0-9]*[.][0-9]+) ([0-9]*[.][0-9]+)/i, (msg) ->
[light,x,y] = msg.match[1..3]
msg.send "Setting light #{light} to: X=#{x}, Y=#{y}"
lightState = new LightState().on(true).xy(x, y)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) ct=(\d{3})/i, (msg) ->
[groupName,ct] = msg.match[1..2]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to: CT=#{ct}"
lightState = new GroupLightState().on(true).ct(ct)
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue ct light (.*) (\d{3})/i, (msg) ->
[light,ct] = msg.match[1..2]
msg.send "Setting light #{light} to: CT=#{ct}"
lightState = new LightState().on(true).ct(ct)
hueApi.then (api) ->
api.lights.setLightState(light, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Light #{light} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue @(\w+) (on|off)/i, (msg) ->
[groupName, state] = msg.match[1..2]
groupMap groupName, (group) ->
return msg.send "Could not find '#{groupName}' in list of groups" if typeof group == undefined
msg.send "Setting light group #{group} to #{state}"
lightState = new GroupLightState().on(state=='on')
hueApi.then (api) ->
api.groups.setGroupState(group, lightState)
.then (response) ->
robot.logger.debug response
msg.send "Group #{groupName} updated"
.catch (err) ->
handleError msg, err
robot.respond /hue turn light (\d+) (on|off)/i, (msg) ->
lightId = msg.match[1]
state = msg.match[2]
msg.send "Turning light #{lightId} #{state} ..."
hueApi.then (api) ->
lightState = new LightState().on(state=='on')
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} turned #{state}"
.catch (err) ->
handleError msg, err
robot.respond /hue (alert|alerts) light (.+)/i, (msg) ->
alertLength = msg.match[1]
lightId = parseInt(msg.match[2], 10)
if alertLength == 'alert'
alertText = 'short alert'
lightState = new LightState().alertShort()
else
alertText = 'long alert'
lightState = new LightState().alertLong()
msg.send "Setting light #{lightId} to #{alertText} ..."
hueApi.then (api) ->
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} set to #{alertText}"
.catch (err) ->
handleError msg, err
robot.respond /hue (?:colors|colorloop|loop) (on|off) light (.+)/i, (msg) ->
loopState = msg.match[1]
lightId = parseInt(msg.match[2], 10)
if loopState == 'on'
lightState = new LightState().on().effect('colorloop')
else
lightState = new LightState().on().effect('none')
msg.send "Setting light #{lightId} colorloop to #{loopState} ..."
hueApi.then (api) ->
api.lights.setLightState(lightId, lightState)
.then (status) ->
msg.send "Light #{lightId} colorloop set to #{loopState}"
.catch (err) ->
handleError msg, err
# BRIDGE COMMANDS
robot.respond /hue config/i, (msg) ->
hueApi.then (api) ->
api.configuration.getConfiguration()
.then (config) ->
robot.logger.debug config
msg.send "Base Station: '#{config.name}'"
msg.send "IP: #{config.ipaddress} / MAC: #{config.mac} / ZigBee Channel: #{config.zigbeechannel}"
msg.send "Software: #{config.swversion} / API: #{config.apiversion}"
.catch (err) ->
handleError msg, err
# HELPERS
groupMap = (groupName, callback) ->
hueApi.then (api) ->
api.groups.getAll()
.then (groups) ->
result = {all: 0}
for group in groups
robot.logger.debug group
result[group.name.toLowerCase()] = group.id
match = result[groupName.toLowerCase()]
callback match
.catch (err) ->
console.error err
handleError = (res, err) ->
robot.logger.debug err
switch err.code
when 'ETIMEDOUT'
res.send 'Connection timed out to Hue bridge.'
else
res.send "An error ocurred: #{err}"
|
[
{
"context": "u.compile_template(source)\n context = { name: \"World\", the_flag: true }\n du.render_template templat",
"end": 2030,
"score": 0.8202518820762634,
"start": 2025,
"tag": "NAME",
"value": "World"
},
{
"context": "rt.equal output, \"TRUE!\"\n context = { name: ... | test/test-dust-util.coffee | intellinote/inote-util | 1 | require 'coffee-errors'
#------------------------------------------------------------------------------#
fs = require 'fs'
path = require 'path'
HOME_DIR = path.join(__dirname, '..')
LIB_COV = path.join(HOME_DIR, 'lib-cov')
LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else path.join(HOME_DIR, 'lib')
#------------------------------------------------------------------------------#
assert = require 'assert'
#------------------------------------------------------------------------------#
DustUtil = require(path.join(LIB_DIR, 'dust-util')).DustUtil.DustUtil
StringUtil = require(path.join(LIB_DIR, 'string-util')).StringUtil
#------------------------------------------------------------------------------#
describe 'DustUtil', ()->
it "renders templates from strings", (done)->
du = new DustUtil()
template = "Hello {name}!"
context = { name: "World" }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "Hello World!"
done()
it "compiles templates and later renders them", (done)->
du = new DustUtil()
template_source = "Hello {name}!"
template = du.compile_template template_source
context = { name: "World" }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "Hello World!"
done()
it "supports creation of helper tags", (done)->
du = new DustUtil()
my_helper = (chunk, context, bodies, params)->
assert.equal du.ctx_get(context, ["not_name", "name"]), "World"
assert.equal du.ctx_get(context, "name"), "World"
flag = StringUtil.truthy_string(du.eval_dust_string(params.flag, chunk, context))
return du.render_if_else flag, chunk, context, bodies, params
du.ensure_dust().helpers ?= {}
du.ensure_dust().helpers.myhelper = my_helper
source = '{@myhelper flag="{the_flag}"}TRUE{:else}FALSE{/myhelper}!'
template = du.compile_template(source)
context = { name: "World", the_flag: true }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "TRUE!"
context = { name: "World", the_flag: false }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "FALSE!"
done()
| 46310 | require 'coffee-errors'
#------------------------------------------------------------------------------#
fs = require 'fs'
path = require 'path'
HOME_DIR = path.join(__dirname, '..')
LIB_COV = path.join(HOME_DIR, 'lib-cov')
LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else path.join(HOME_DIR, 'lib')
#------------------------------------------------------------------------------#
assert = require 'assert'
#------------------------------------------------------------------------------#
DustUtil = require(path.join(LIB_DIR, 'dust-util')).DustUtil.DustUtil
StringUtil = require(path.join(LIB_DIR, 'string-util')).StringUtil
#------------------------------------------------------------------------------#
describe 'DustUtil', ()->
it "renders templates from strings", (done)->
du = new DustUtil()
template = "Hello {name}!"
context = { name: "World" }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "Hello World!"
done()
it "compiles templates and later renders them", (done)->
du = new DustUtil()
template_source = "Hello {name}!"
template = du.compile_template template_source
context = { name: "World" }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "Hello World!"
done()
it "supports creation of helper tags", (done)->
du = new DustUtil()
my_helper = (chunk, context, bodies, params)->
assert.equal du.ctx_get(context, ["not_name", "name"]), "World"
assert.equal du.ctx_get(context, "name"), "World"
flag = StringUtil.truthy_string(du.eval_dust_string(params.flag, chunk, context))
return du.render_if_else flag, chunk, context, bodies, params
du.ensure_dust().helpers ?= {}
du.ensure_dust().helpers.myhelper = my_helper
source = '{@myhelper flag="{the_flag}"}TRUE{:else}FALSE{/myhelper}!'
template = du.compile_template(source)
context = { name: "<NAME>", the_flag: true }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "TRUE!"
context = { name: "<NAME>", the_flag: false }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "FALSE!"
done()
| true | require 'coffee-errors'
#------------------------------------------------------------------------------#
fs = require 'fs'
path = require 'path'
HOME_DIR = path.join(__dirname, '..')
LIB_COV = path.join(HOME_DIR, 'lib-cov')
LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else path.join(HOME_DIR, 'lib')
#------------------------------------------------------------------------------#
assert = require 'assert'
#------------------------------------------------------------------------------#
DustUtil = require(path.join(LIB_DIR, 'dust-util')).DustUtil.DustUtil
StringUtil = require(path.join(LIB_DIR, 'string-util')).StringUtil
#------------------------------------------------------------------------------#
describe 'DustUtil', ()->
it "renders templates from strings", (done)->
du = new DustUtil()
template = "Hello {name}!"
context = { name: "World" }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "Hello World!"
done()
it "compiles templates and later renders them", (done)->
du = new DustUtil()
template_source = "Hello {name}!"
template = du.compile_template template_source
context = { name: "World" }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "Hello World!"
done()
it "supports creation of helper tags", (done)->
du = new DustUtil()
my_helper = (chunk, context, bodies, params)->
assert.equal du.ctx_get(context, ["not_name", "name"]), "World"
assert.equal du.ctx_get(context, "name"), "World"
flag = StringUtil.truthy_string(du.eval_dust_string(params.flag, chunk, context))
return du.render_if_else flag, chunk, context, bodies, params
du.ensure_dust().helpers ?= {}
du.ensure_dust().helpers.myhelper = my_helper
source = '{@myhelper flag="{the_flag}"}TRUE{:else}FALSE{/myhelper}!'
template = du.compile_template(source)
context = { name: "PI:NAME:<NAME>END_PI", the_flag: true }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "TRUE!"
context = { name: "PI:NAME:<NAME>END_PI", the_flag: false }
du.render_template template, context, (err, output)->
assert.ok not err?, err
assert.equal output, "FALSE!"
done()
|
[
{
"context": " pwd, callback)\n # - Name = user name\n # - Pwd = password\n # - Callback = function to call when done\n sav",
"end": 114,
"score": 0.9953699707984924,
"start": 106,
"tag": "PASSWORD",
"value": "password"
}
] | src/user.coffee | vincentbas/asynchronus_tehnologies_server_BAS | 0 | module.exports =
# Save a user
# Usage : save(name, pwd, callback)
# - Name = user name
# - Pwd = password
# - Callback = function to call when done
save: (name, pwd, callback) ->
if callback == undefined
callback = pwd
callback new Error "missing parameters"
else
#console.log("saving " + name + " with pwd " + pwd)
callback()
get: (name, callback) ->
#console.log("saving " + name)
callback()
| 193434 | module.exports =
# Save a user
# Usage : save(name, pwd, callback)
# - Name = user name
# - Pwd = <PASSWORD>
# - Callback = function to call when done
save: (name, pwd, callback) ->
if callback == undefined
callback = pwd
callback new Error "missing parameters"
else
#console.log("saving " + name + " with pwd " + pwd)
callback()
get: (name, callback) ->
#console.log("saving " + name)
callback()
| true | module.exports =
# Save a user
# Usage : save(name, pwd, callback)
# - Name = user name
# - Pwd = PI:PASSWORD:<PASSWORD>END_PI
# - Callback = function to call when done
save: (name, pwd, callback) ->
if callback == undefined
callback = pwd
callback new Error "missing parameters"
else
#console.log("saving " + name + " with pwd " + pwd)
callback()
get: (name, callback) ->
#console.log("saving " + name)
callback()
|
[
{
"context": "'#rebel-builder', [\n {\n ship: 'X-Wing'\n pilot: 'Luke Skywalker'\n ",
"end": 210,
"score": 0.6371340751647949,
"start": 206,
"tag": "NAME",
"value": "Wing"
},
{
"context": " {\n ship: 'X-Wing'\n pilot: 'Luk... | tests/test_clone.coffee | michigun/xwing | 0 | common = require './common'
common.setup()
casper.test.begin "Copy pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Luke Skywalker'
upgrades: [
]
}
{
ship: 'X-Wing'
pilot: 'Rookie Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
# Unique pilots can't be cloned
.then ->
@log("#rebel-builder #{common.selectorForCloneShip(1)}")
test.assertNotVisible("#rebel-builder #{common.selectorForCloneShip(1)}", "Unique pilots cannot be cloned")
# Non-uniques
common.cloneShip('#rebel-builder', 2)
common.assertTotalPoints(test, '#rebel-builder', 88)
# Don't clone uniques
common.addUpgrade('#rebel-builder', 2, 2, 'R2-D2')
common.cloneShip('#rebel-builder', 2)
common.assertTotalPoints(test, '#rebel-builder', 120)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy A-Wing with Test Pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'A-Wing'
pilot: 'Green Squadron Pilot'
upgrades: [
'Deadeye'
null
'A-Wing Test Pilot'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 44)
common.removeShip('#rebel-builder', 2)
common.addUpgrade('#rebel-builder', 1, 5, 'Squad Leader')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 42)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy B-Wing with B-Wing/E2", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'B-Wing'
pilot: 'Blue Squadron Pilot'
upgrades: [
'Fire-Control System'
null
'Proton Torpedoes'
null
'B-Wing/E2'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 6, 'Gunner')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 34 * 2)
common.removeShip('#rebel-builder', 1)
common.addUpgrade('#rebel-builder', 1, 6, 'Nien Nunb')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 59)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy Royal Guard Pilot with Royal Guard TIE", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'TIE Interceptor'
pilot: 'Royal Guard Pilot'
upgrades: [
'Determination'
'Royal Guard TIE'
'Stealth Device'
]
}
])
common.addUpgrade('#empire-builder', 1, 4, 'Hull Upgrade')
common.cloneShip('#empire-builder', 1)
common.assertTotalPoints(test, '#empire-builder', 58)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
| 188665 | common = require './common'
common.setup()
casper.test.begin "Copy pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-<NAME>'
pilot: '<NAME>'
upgrades: [
]
}
{
ship: 'X-<NAME>ing'
pilot: 'Rookie Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
# Unique pilots can't be cloned
.then ->
@log("#rebel-builder #{common.selectorForCloneShip(1)}")
test.assertNotVisible("#rebel-builder #{common.selectorForCloneShip(1)}", "Unique pilots cannot be cloned")
# Non-uniques
common.cloneShip('#rebel-builder', 2)
common.assertTotalPoints(test, '#rebel-builder', 88)
# Don't clone uniques
common.addUpgrade('#rebel-builder', 2, 2, 'R2-D2')
common.cloneShip('#rebel-builder', 2)
common.assertTotalPoints(test, '#rebel-builder', 120)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy A-Wing with Test Pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'A-Wing'
pilot: 'Green Squadron Pilot'
upgrades: [
'Deadeye'
null
'A-Wing Test Pilot'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 44)
common.removeShip('#rebel-builder', 2)
common.addUpgrade('#rebel-builder', 1, 5, 'Squad Leader')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 42)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy B-Wing with B-Wing/E2", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'B-Wing'
pilot: 'Blue Squadron Pilot'
upgrades: [
'Fire-Control System'
null
'Proton Torpedoes'
null
'B-Wing/E2'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 6, 'Gunner')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 34 * 2)
common.removeShip('#rebel-builder', 1)
common.addUpgrade('#rebel-builder', 1, 6, '<NAME>')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 59)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy Royal Guard Pilot with Royal Guard TIE", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'TIE Interceptor'
pilot: 'Royal Guard Pilot'
upgrades: [
'Determination'
'Royal Guard TIE'
'Stealth Device'
]
}
])
common.addUpgrade('#empire-builder', 1, 4, 'Hull Upgrade')
common.cloneShip('#empire-builder', 1)
common.assertTotalPoints(test, '#empire-builder', 58)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
| true | common = require './common'
common.setup()
casper.test.begin "Copy pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-PI:NAME:<NAME>END_PI'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
]
}
{
ship: 'X-PI:NAME:<NAME>END_PIing'
pilot: 'Rookie Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
# Unique pilots can't be cloned
.then ->
@log("#rebel-builder #{common.selectorForCloneShip(1)}")
test.assertNotVisible("#rebel-builder #{common.selectorForCloneShip(1)}", "Unique pilots cannot be cloned")
# Non-uniques
common.cloneShip('#rebel-builder', 2)
common.assertTotalPoints(test, '#rebel-builder', 88)
# Don't clone uniques
common.addUpgrade('#rebel-builder', 2, 2, 'R2-D2')
common.cloneShip('#rebel-builder', 2)
common.assertTotalPoints(test, '#rebel-builder', 120)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy A-Wing with Test Pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'A-Wing'
pilot: 'Green Squadron Pilot'
upgrades: [
'Deadeye'
null
'A-Wing Test Pilot'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 44)
common.removeShip('#rebel-builder', 2)
common.addUpgrade('#rebel-builder', 1, 5, 'Squad Leader')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 42)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy B-Wing with B-Wing/E2", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'B-Wing'
pilot: 'Blue Squadron Pilot'
upgrades: [
'Fire-Control System'
null
'Proton Torpedoes'
null
'B-Wing/E2'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 6, 'Gunner')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 34 * 2)
common.removeShip('#rebel-builder', 1)
common.addUpgrade('#rebel-builder', 1, 6, 'PI:NAME:<NAME>END_PI')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 59)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy Royal Guard Pilot with Royal Guard TIE", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'TIE Interceptor'
pilot: 'Royal Guard Pilot'
upgrades: [
'Determination'
'Royal Guard TIE'
'Stealth Device'
]
}
])
common.addUpgrade('#empire-builder', 1, 4, 'Hull Upgrade')
common.cloneShip('#empire-builder', 1)
common.assertTotalPoints(test, '#empire-builder', 58)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
|
[
{
"context": " email: $scope.user.email\n password: $scope.user.password\n firstName: $scope.user.firstName\n ",
"end": 1788,
"score": 0.9987399578094482,
"start": 1768,
"tag": "PASSWORD",
"value": "$scope.user.password"
}
] | frontend/app/login/login.coffee | Contactis/translation-manager | 0 | angular.module('translation.pages.login', [
'ui.router'
'pascalprecht.translate'
'ngCookies'
'toastr'
'translation.services.account'
'translation.services.authorization'
'translation.providers.userPermissionsSettings'
])
.config ($stateProvider, UserPermissionsSettingsProvider) ->
access = UserPermissionsSettingsProvider.accessLevels
$stateProvider.state 'login',
url: '/login'
controller: 'LoginController'
templateUrl: 'login/login.tpl.html'
data:
access: access.anon
.controller 'LoginController', ($scope, $state, $http, $filter, $log,
AuthorizationService, toastr) ->
$scope.rememberMe = true
$scope.user =
email: ''
password: ''
repeatPassword: ''
firstName: ''
lastName: ''
username: ''
$scope.showRegistration = false
$scope.toggleRegister = ->
$scope.showRegistration = !$scope.showRegistration
$scope.login = ->
AuthorizationService.login($scope.rememberMe, $scope.user.email, $scope.user.password).then (account) ->
$state.go 'app.manager.dashboard'
msg = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.WELCOME')
toastr.success msg
, (error) ->
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.LOGGING_ERROR')
msg = error.data.error.message
toastr.error msg, title
$scope.register = ->
if $scope.user.password != $scope.user.repeatPassword
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR')
msg = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.PASSWORDS_DONT_MATCH')
toastr.warning msg, title
else
AuthorizationService.register
email: $scope.user.email
password: $scope.user.password
firstName: $scope.user.firstName
lastName: $scope.user.lastName
username: $scope.user.username
.then $scope.login
, (error) ->
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR')
msg = error.data.error.message
toastr.error msg, title
return
$scope.sizes = [
"small (12-inch)"
"medium (14-inch)"
"large (16-inch)"
"insane (42-inch)"
]
return
| 119986 | angular.module('translation.pages.login', [
'ui.router'
'pascalprecht.translate'
'ngCookies'
'toastr'
'translation.services.account'
'translation.services.authorization'
'translation.providers.userPermissionsSettings'
])
.config ($stateProvider, UserPermissionsSettingsProvider) ->
access = UserPermissionsSettingsProvider.accessLevels
$stateProvider.state 'login',
url: '/login'
controller: 'LoginController'
templateUrl: 'login/login.tpl.html'
data:
access: access.anon
.controller 'LoginController', ($scope, $state, $http, $filter, $log,
AuthorizationService, toastr) ->
$scope.rememberMe = true
$scope.user =
email: ''
password: ''
repeatPassword: ''
firstName: ''
lastName: ''
username: ''
$scope.showRegistration = false
$scope.toggleRegister = ->
$scope.showRegistration = !$scope.showRegistration
$scope.login = ->
AuthorizationService.login($scope.rememberMe, $scope.user.email, $scope.user.password).then (account) ->
$state.go 'app.manager.dashboard'
msg = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.WELCOME')
toastr.success msg
, (error) ->
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.LOGGING_ERROR')
msg = error.data.error.message
toastr.error msg, title
$scope.register = ->
if $scope.user.password != $scope.user.repeatPassword
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR')
msg = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.PASSWORDS_DONT_MATCH')
toastr.warning msg, title
else
AuthorizationService.register
email: $scope.user.email
password: <PASSWORD>
firstName: $scope.user.firstName
lastName: $scope.user.lastName
username: $scope.user.username
.then $scope.login
, (error) ->
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR')
msg = error.data.error.message
toastr.error msg, title
return
$scope.sizes = [
"small (12-inch)"
"medium (14-inch)"
"large (16-inch)"
"insane (42-inch)"
]
return
| true | angular.module('translation.pages.login', [
'ui.router'
'pascalprecht.translate'
'ngCookies'
'toastr'
'translation.services.account'
'translation.services.authorization'
'translation.providers.userPermissionsSettings'
])
.config ($stateProvider, UserPermissionsSettingsProvider) ->
access = UserPermissionsSettingsProvider.accessLevels
$stateProvider.state 'login',
url: '/login'
controller: 'LoginController'
templateUrl: 'login/login.tpl.html'
data:
access: access.anon
.controller 'LoginController', ($scope, $state, $http, $filter, $log,
AuthorizationService, toastr) ->
$scope.rememberMe = true
$scope.user =
email: ''
password: ''
repeatPassword: ''
firstName: ''
lastName: ''
username: ''
$scope.showRegistration = false
$scope.toggleRegister = ->
$scope.showRegistration = !$scope.showRegistration
$scope.login = ->
AuthorizationService.login($scope.rememberMe, $scope.user.email, $scope.user.password).then (account) ->
$state.go 'app.manager.dashboard'
msg = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.WELCOME')
toastr.success msg
, (error) ->
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.LOGGING_ERROR')
msg = error.data.error.message
toastr.error msg, title
$scope.register = ->
if $scope.user.password != $scope.user.repeatPassword
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR')
msg = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.PASSWORDS_DONT_MATCH')
toastr.warning msg, title
else
AuthorizationService.register
email: $scope.user.email
password: PI:PASSWORD:<PASSWORD>END_PI
firstName: $scope.user.firstName
lastName: $scope.user.lastName
username: $scope.user.username
.then $scope.login
, (error) ->
title = $filter('translate')('APP.FRONTEND_MESSAGES.LOGIN.REGISTRATION_ERROR')
msg = error.data.error.message
toastr.error msg, title
return
$scope.sizes = [
"small (12-inch)"
"medium (14-inch)"
"large (16-inch)"
"insane (42-inch)"
]
return
|
[
{
"context": "###\n# Earl\n# The MIT License (MIT)\n# Copyright (c) Travis Kriplean, Consider.it LLC\n# \n# Hire Earl to handle the bro",
"end": 72,
"score": 0.999871015548706,
"start": 57,
"tag": "NAME",
"value": "Travis Kriplean"
},
{
"context": "browsers try installing the \n# htt... | earl.coffee | invisible-college/Earl | 1 | #########
# Earl
# The MIT License (MIT)
# Copyright (c) Travis Kriplean, Consider.it LLC
#
# Hire Earl to handle the browser history & location bar.
#
# When your web application is loaded, Earl will update your application's
# fetch('location') state with the url, params, and anchor. Your application
# can simply react to location state changes as it would any other state change.
#
# If your application changes the location state, Earl will dutifully update
# the browser history/location to reflect this change.
#
# Earl also likes to brag about the souped-up, history-aware dom.A link he
# offers. It is a drop in replacement for dom.A that will cause internal links
# on your site to update state and browser location without loading a new page.
# Make sure to tell him you want it by setting a history-aware-link attribute
# on the script tag you use to request Earl to attend to your page:
#
# <script src="/path/to/earl.js" history-aware-links></script>
#
# If the root of your app is served off of a directory, let Earl know by adding
# a script attribute, like:
#
# <script src="/path/to/earl.js" root="path/served/at"></script>
#
# DISCLAIMER: Earl assumes his clients are html5 pushstate history compatible.
# If you want to serve older non-pushstate compatible browsers try installing the
# https://github.com/devote/HTML5-History-API polyfill first.
#
#
# Aside from the public API, you can communicate with Earl through this state:
# fetch('location')
# url: the current browser location
# query_params: browser search values (e.g. blah?foo=fab&bar=nice)
# hash: the anchor tag (if any) in the link. e.g. blah.html#hash
# title: the window title
###################################
# Earl's API (Admissible Professional Inquiries):
#
# Earl.load_page
# Convenience method for changing the page's url
window.get_script_attr ||= (script, attr) ->
sc = document.querySelector("script[src*='#{script}'][src$='.coffee'], script[src*='#{script}'][src$='.js']")
val = sc.getAttribute(attr)
if val == ''
val = true
val
hist_aware = !!get_script_attr('earl', 'history-aware-links')
onload = ->
Earl.root = get_script_attr('earl', 'root') or '/'
if Earl.root == true # earl attribute just set with no value
Earl.root = '/'
if window.location.pathname.match('.html')
Earl.root += location.pathname.match(/\/([\w-_]+\.html)/)[1] + '/'
if Earl.root[0] != '/'
Earl.root = '/' + Earl.root
# Earl, don't forget to update us if the browser back or forward button pressed
window.addEventListener 'popstate', (ev) ->
Earl.load_page url_from_browser_location()
# By all means Earl, please do initialize location state
Earl.load_page url_from_browser_location()
# Earl, don't fall asleep on the job!
react_to_location()
window.addEventListener?('load', onload, false) or window.attachEvent?('onload', onload)
window.Earl =
seek_to_hash: false
# Updating the browser window location.
load_page: (url, query_params) ->
loc = fetch('location')
loc.host = window.location.host
loc.query_params = query_params or {}
parser = document.createElement('a');
parser.href = url
# if the url has query parameters, parse and merge them into params
if parser.search
query_params = parser.search.replace('?', '')
for query_param in query_params.split('&')
query_param = query_param.split('=')
if query_param.length == 2
loc.query_params[query_param[0]] = query_param[1]
# ...and parse anchors
hash = parser.hash.replace('#', '')
# When loading a page with a hash, we need to scroll the page
# to proper element represented by that id. This is hard to
# represent in Statebus, as it is more of an event than state.
# We'll set seek_to_hash here, then it will get set to null
# after it is processed.
Earl.seek_to_hash = hash?.length > 0
url = parser.pathname
url = '/' if !url || url == ''
path = url
if path.substring(0, Earl.root.length) != Earl.root
path = Earl.root + '/' + path
loc.path = path.replace('//', '/')
loc.url = path.substring(Earl.root.length).replace('//', '/')
loc.hash = hash
save loc
##################################
# Internal
# Enables history aware link. Wraps basic dom.A.
if hist_aware
window.dom = window.dom || {}
dom.A = ->
props = @props
loc = fetch 'location'
if @props.href
href = @props.href
# Earl will call a click handler that the programmer passes in
onClick = @props.onClick or (-> null)
# Earl rewrites the address when necessary
internal_link = !href.match('//') || !!href.match(location.origin)
is_mailto = !!href.toLowerCase().match('mailto')
if internal_link && !is_mailto
if href.substring(0, Earl.root.length) != Earl.root
rel = href[0] != '/'
if rel
href = loc.path + '/' + href
else
href = Earl.root + href
href = @props.href = href.replace('//', '/')
handle_click = (event) =>
opened_in_new_tab = event.altKey || \
event.ctrlKey || \
event.metaKey || \
event.shiftKey
# In his wisdom, Earl sometimes just lets the default behavior occur
if !internal_link || opened_in_new_tab || is_mailto || @props.target == '_blank'
onClick event
# ... but other times Earl is history aware
else
event.preventDefault()
event.stopPropagation()
Earl.load_page href
onClick event
# Upon navigation to a new page, it is conventional to be scrolled
# to the top of that page. Earl obliges. Pass noScroll:true to
# the history aware dom.A if you don't want Earl to do this.
window.scrollTo(0, 0) if !@props.noScroll
return false
if is_mobile
@props.onTouchEnd = (e) ->
# Earl won't make you follow the link if you're in the middle of swipping
if !Earl._user_swipping
handle_click e
if is_android_browser # Earl's least favorite browser to support...
@props.onClick = (e) -> e.preventDefault(); e.stopPropagation()
else
@props.onClick = handle_click
React.DOM.a props, props.children
# Earl's Reactive nerves keep him vigilant in making sure that changes in location
# state are reflected in the browser history. Earl also updates the window title
# for you, free of charge, if you set fetch('location').title.
react_to_location = ->
monitor = bus.reactive ->
loc = fetch 'location'
# Update the window title if it has changed
title = location.title or document.title
if title && title != location.title
document.title = title
# Respond to a location change
new_location = url_from_statebus()
if @last_location != new_location
# update browser history if it hasn't already been updated
if url_from_browser_location() != new_location
l = new_location.replace(/(\/){2,}/, '/').replace(/(\/)$/, '')
l = '/' if l == ''
history.pushState loc.query_params, title, l
@last_location = new_location
# If someone clicked a link with an anchor, Earl strives to scroll
# the page to that element. Unfortunately, Earl isn't powerful
# enough to deal with the mightly Webkit browser's imposition of
# a remembered scroll position for a return visitor upon initial
# page load!
if Earl.seek_to_hash && !@int
@int = setInterval ->
Earl.seek_to_hash = false
el = document.getElementById("#{loc.hash}") or document.querySelector("[name='#{loc.hash}']")
if el
window.scrollTo 0, getCoords(el).top - 50
if loc.query_params.c
delete loc.query_params.c
delete loc.hash
save loc
clearInterval @int
@int = null
, 50
monitor()
url_from_browser_location = ->
# location.search returns the query parameters
# fix url encoding
search = location.search?.replace(/\%2[fF]/g, '/')
loc = location.pathname?.replace(/\%20/g, ' ')
"#{loc}#{search}#{location.hash}"
url_from_statebus = ->
loc = fetch 'location'
url = loc.path or '/'
if loc.query_params && Object.keys(loc.query_params).length > 0
query_params = ("#{k}=#{v}" for own k,v of loc.query_params)
url += "?#{query_params.join('&')}"
if loc.hash?.length > 0
url += "##{loc.hash}"
url
# For handling device-specific annoyances
document.ontouchmove = (e) -> Earl._user_swipping = true
document.ontouchend = (e) -> Earl._user_swipping = false
rxaosp = window.navigator.userAgent.match /Android.*AppleWebKit\/([\d.]+)/
is_android_browser = !!(rxaosp && rxaosp[1]<537)
ua = navigator.userAgent
is_mobile = is_android_browser || \
ua.match(/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i)
| 56710 | #########
# Earl
# The MIT License (MIT)
# Copyright (c) <NAME>, Consider.it LLC
#
# Hire Earl to handle the browser history & location bar.
#
# When your web application is loaded, Earl will update your application's
# fetch('location') state with the url, params, and anchor. Your application
# can simply react to location state changes as it would any other state change.
#
# If your application changes the location state, Earl will dutifully update
# the browser history/location to reflect this change.
#
# Earl also likes to brag about the souped-up, history-aware dom.A link he
# offers. It is a drop in replacement for dom.A that will cause internal links
# on your site to update state and browser location without loading a new page.
# Make sure to tell him you want it by setting a history-aware-link attribute
# on the script tag you use to request Earl to attend to your page:
#
# <script src="/path/to/earl.js" history-aware-links></script>
#
# If the root of your app is served off of a directory, let Earl know by adding
# a script attribute, like:
#
# <script src="/path/to/earl.js" root="path/served/at"></script>
#
# DISCLAIMER: Earl assumes his clients are html5 pushstate history compatible.
# If you want to serve older non-pushstate compatible browsers try installing the
# https://github.com/devote/HTML5-History-API polyfill first.
#
#
# Aside from the public API, you can communicate with Earl through this state:
# fetch('location')
# url: the current browser location
# query_params: browser search values (e.g. blah?foo=fab&bar=nice)
# hash: the anchor tag (if any) in the link. e.g. blah.html#hash
# title: the window title
###################################
# Earl's API (Admissible Professional Inquiries):
#
# Earl.load_page
# Convenience method for changing the page's url
window.get_script_attr ||= (script, attr) ->
sc = document.querySelector("script[src*='#{script}'][src$='.coffee'], script[src*='#{script}'][src$='.js']")
val = sc.getAttribute(attr)
if val == ''
val = true
val
hist_aware = !!get_script_attr('earl', 'history-aware-links')
onload = ->
Earl.root = get_script_attr('earl', 'root') or '/'
if Earl.root == true # earl attribute just set with no value
Earl.root = '/'
if window.location.pathname.match('.html')
Earl.root += location.pathname.match(/\/([\w-_]+\.html)/)[1] + '/'
if Earl.root[0] != '/'
Earl.root = '/' + Earl.root
# Earl, don't forget to update us if the browser back or forward button pressed
window.addEventListener 'popstate', (ev) ->
Earl.load_page url_from_browser_location()
# By all means Earl, please do initialize location state
Earl.load_page url_from_browser_location()
# Earl, don't fall asleep on the job!
react_to_location()
window.addEventListener?('load', onload, false) or window.attachEvent?('onload', onload)
window.Earl =
seek_to_hash: false
# Updating the browser window location.
load_page: (url, query_params) ->
loc = fetch('location')
loc.host = window.location.host
loc.query_params = query_params or {}
parser = document.createElement('a');
parser.href = url
# if the url has query parameters, parse and merge them into params
if parser.search
query_params = parser.search.replace('?', '')
for query_param in query_params.split('&')
query_param = query_param.split('=')
if query_param.length == 2
loc.query_params[query_param[0]] = query_param[1]
# ...and parse anchors
hash = parser.hash.replace('#', '')
# When loading a page with a hash, we need to scroll the page
# to proper element represented by that id. This is hard to
# represent in Statebus, as it is more of an event than state.
# We'll set seek_to_hash here, then it will get set to null
# after it is processed.
Earl.seek_to_hash = hash?.length > 0
url = parser.pathname
url = '/' if !url || url == ''
path = url
if path.substring(0, Earl.root.length) != Earl.root
path = Earl.root + '/' + path
loc.path = path.replace('//', '/')
loc.url = path.substring(Earl.root.length).replace('//', '/')
loc.hash = hash
save loc
##################################
# Internal
# Enables history aware link. Wraps basic dom.A.
if hist_aware
window.dom = window.dom || {}
dom.A = ->
props = @props
loc = fetch 'location'
if @props.href
href = @props.href
# Earl will call a click handler that the programmer passes in
onClick = @props.onClick or (-> null)
# Earl rewrites the address when necessary
internal_link = !href.match('//') || !!href.match(location.origin)
is_mailto = !!href.toLowerCase().match('mailto')
if internal_link && !is_mailto
if href.substring(0, Earl.root.length) != Earl.root
rel = href[0] != '/'
if rel
href = loc.path + '/' + href
else
href = Earl.root + href
href = @props.href = href.replace('//', '/')
handle_click = (event) =>
opened_in_new_tab = event.altKey || \
event.ctrlKey || \
event.metaKey || \
event.shiftKey
# In his wisdom, Earl sometimes just lets the default behavior occur
if !internal_link || opened_in_new_tab || is_mailto || @props.target == '_blank'
onClick event
# ... but other times Earl is history aware
else
event.preventDefault()
event.stopPropagation()
Earl.load_page href
onClick event
# Upon navigation to a new page, it is conventional to be scrolled
# to the top of that page. Earl obliges. Pass noScroll:true to
# the history aware dom.A if you don't want Earl to do this.
window.scrollTo(0, 0) if !@props.noScroll
return false
if is_mobile
@props.onTouchEnd = (e) ->
# Earl won't make you follow the link if you're in the middle of swipping
if !Earl._user_swipping
handle_click e
if is_android_browser # Earl's least favorite browser to support...
@props.onClick = (e) -> e.preventDefault(); e.stopPropagation()
else
@props.onClick = handle_click
React.DOM.a props, props.children
# Earl's Reactive nerves keep him vigilant in making sure that changes in location
# state are reflected in the browser history. Earl also updates the window title
# for you, free of charge, if you set fetch('location').title.
react_to_location = ->
monitor = bus.reactive ->
loc = fetch 'location'
# Update the window title if it has changed
title = location.title or document.title
if title && title != location.title
document.title = title
# Respond to a location change
new_location = url_from_statebus()
if @last_location != new_location
# update browser history if it hasn't already been updated
if url_from_browser_location() != new_location
l = new_location.replace(/(\/){2,}/, '/').replace(/(\/)$/, '')
l = '/' if l == ''
history.pushState loc.query_params, title, l
@last_location = new_location
# If someone clicked a link with an anchor, Earl strives to scroll
# the page to that element. Unfortunately, Earl isn't powerful
# enough to deal with the mightly Webkit browser's imposition of
# a remembered scroll position for a return visitor upon initial
# page load!
if Earl.seek_to_hash && !@int
@int = setInterval ->
Earl.seek_to_hash = false
el = document.getElementById("#{loc.hash}") or document.querySelector("[name='#{loc.hash}']")
if el
window.scrollTo 0, getCoords(el).top - 50
if loc.query_params.c
delete loc.query_params.c
delete loc.hash
save loc
clearInterval @int
@int = null
, 50
monitor()
url_from_browser_location = ->
# location.search returns the query parameters
# fix url encoding
search = location.search?.replace(/\%2[fF]/g, '/')
loc = location.pathname?.replace(/\%20/g, ' ')
"#{loc}#{search}#{location.hash}"
url_from_statebus = ->
loc = fetch 'location'
url = loc.path or '/'
if loc.query_params && Object.keys(loc.query_params).length > 0
query_params = ("#{k}=#{v}" for own k,v of loc.query_params)
url += "?#{query_params.join('&')}"
if loc.hash?.length > 0
url += "##{loc.hash}"
url
# For handling device-specific annoyances
document.ontouchmove = (e) -> Earl._user_swipping = true
document.ontouchend = (e) -> Earl._user_swipping = false
rxaosp = window.navigator.userAgent.match /Android.*AppleWebKit\/([\d.]+)/
is_android_browser = !!(rxaosp && rxaosp[1]<537)
ua = navigator.userAgent
is_mobile = is_android_browser || \
ua.match(/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i)
| true | #########
# Earl
# The MIT License (MIT)
# Copyright (c) PI:NAME:<NAME>END_PI, Consider.it LLC
#
# Hire Earl to handle the browser history & location bar.
#
# When your web application is loaded, Earl will update your application's
# fetch('location') state with the url, params, and anchor. Your application
# can simply react to location state changes as it would any other state change.
#
# If your application changes the location state, Earl will dutifully update
# the browser history/location to reflect this change.
#
# Earl also likes to brag about the souped-up, history-aware dom.A link he
# offers. It is a drop in replacement for dom.A that will cause internal links
# on your site to update state and browser location without loading a new page.
# Make sure to tell him you want it by setting a history-aware-link attribute
# on the script tag you use to request Earl to attend to your page:
#
# <script src="/path/to/earl.js" history-aware-links></script>
#
# If the root of your app is served off of a directory, let Earl know by adding
# a script attribute, like:
#
# <script src="/path/to/earl.js" root="path/served/at"></script>
#
# DISCLAIMER: Earl assumes his clients are html5 pushstate history compatible.
# If you want to serve older non-pushstate compatible browsers try installing the
# https://github.com/devote/HTML5-History-API polyfill first.
#
#
# Aside from the public API, you can communicate with Earl through this state:
# fetch('location')
# url: the current browser location
# query_params: browser search values (e.g. blah?foo=fab&bar=nice)
# hash: the anchor tag (if any) in the link. e.g. blah.html#hash
# title: the window title
###################################
# Earl's API (Admissible Professional Inquiries):
#
# Earl.load_page
# Convenience method for changing the page's url
window.get_script_attr ||= (script, attr) ->
sc = document.querySelector("script[src*='#{script}'][src$='.coffee'], script[src*='#{script}'][src$='.js']")
val = sc.getAttribute(attr)
if val == ''
val = true
val
hist_aware = !!get_script_attr('earl', 'history-aware-links')
onload = ->
Earl.root = get_script_attr('earl', 'root') or '/'
if Earl.root == true # earl attribute just set with no value
Earl.root = '/'
if window.location.pathname.match('.html')
Earl.root += location.pathname.match(/\/([\w-_]+\.html)/)[1] + '/'
if Earl.root[0] != '/'
Earl.root = '/' + Earl.root
# Earl, don't forget to update us if the browser back or forward button pressed
window.addEventListener 'popstate', (ev) ->
Earl.load_page url_from_browser_location()
# By all means Earl, please do initialize location state
Earl.load_page url_from_browser_location()
# Earl, don't fall asleep on the job!
react_to_location()
window.addEventListener?('load', onload, false) or window.attachEvent?('onload', onload)
window.Earl =
seek_to_hash: false
# Updating the browser window location.
load_page: (url, query_params) ->
loc = fetch('location')
loc.host = window.location.host
loc.query_params = query_params or {}
parser = document.createElement('a');
parser.href = url
# if the url has query parameters, parse and merge them into params
if parser.search
query_params = parser.search.replace('?', '')
for query_param in query_params.split('&')
query_param = query_param.split('=')
if query_param.length == 2
loc.query_params[query_param[0]] = query_param[1]
# ...and parse anchors
hash = parser.hash.replace('#', '')
# When loading a page with a hash, we need to scroll the page
# to proper element represented by that id. This is hard to
# represent in Statebus, as it is more of an event than state.
# We'll set seek_to_hash here, then it will get set to null
# after it is processed.
Earl.seek_to_hash = hash?.length > 0
url = parser.pathname
url = '/' if !url || url == ''
path = url
if path.substring(0, Earl.root.length) != Earl.root
path = Earl.root + '/' + path
loc.path = path.replace('//', '/')
loc.url = path.substring(Earl.root.length).replace('//', '/')
loc.hash = hash
save loc
##################################
# Internal
# Enables history aware link. Wraps basic dom.A.
if hist_aware
window.dom = window.dom || {}
dom.A = ->
props = @props
loc = fetch 'location'
if @props.href
href = @props.href
# Earl will call a click handler that the programmer passes in
onClick = @props.onClick or (-> null)
# Earl rewrites the address when necessary
internal_link = !href.match('//') || !!href.match(location.origin)
is_mailto = !!href.toLowerCase().match('mailto')
if internal_link && !is_mailto
if href.substring(0, Earl.root.length) != Earl.root
rel = href[0] != '/'
if rel
href = loc.path + '/' + href
else
href = Earl.root + href
href = @props.href = href.replace('//', '/')
handle_click = (event) =>
opened_in_new_tab = event.altKey || \
event.ctrlKey || \
event.metaKey || \
event.shiftKey
# In his wisdom, Earl sometimes just lets the default behavior occur
if !internal_link || opened_in_new_tab || is_mailto || @props.target == '_blank'
onClick event
# ... but other times Earl is history aware
else
event.preventDefault()
event.stopPropagation()
Earl.load_page href
onClick event
# Upon navigation to a new page, it is conventional to be scrolled
# to the top of that page. Earl obliges. Pass noScroll:true to
# the history aware dom.A if you don't want Earl to do this.
window.scrollTo(0, 0) if !@props.noScroll
return false
if is_mobile
@props.onTouchEnd = (e) ->
# Earl won't make you follow the link if you're in the middle of swipping
if !Earl._user_swipping
handle_click e
if is_android_browser # Earl's least favorite browser to support...
@props.onClick = (e) -> e.preventDefault(); e.stopPropagation()
else
@props.onClick = handle_click
React.DOM.a props, props.children
# Earl's Reactive nerves keep him vigilant in making sure that changes in location
# state are reflected in the browser history. Earl also updates the window title
# for you, free of charge, if you set fetch('location').title.
react_to_location = ->
monitor = bus.reactive ->
loc = fetch 'location'
# Update the window title if it has changed
title = location.title or document.title
if title && title != location.title
document.title = title
# Respond to a location change
new_location = url_from_statebus()
if @last_location != new_location
# update browser history if it hasn't already been updated
if url_from_browser_location() != new_location
l = new_location.replace(/(\/){2,}/, '/').replace(/(\/)$/, '')
l = '/' if l == ''
history.pushState loc.query_params, title, l
@last_location = new_location
# If someone clicked a link with an anchor, Earl strives to scroll
# the page to that element. Unfortunately, Earl isn't powerful
# enough to deal with the mightly Webkit browser's imposition of
# a remembered scroll position for a return visitor upon initial
# page load!
if Earl.seek_to_hash && !@int
@int = setInterval ->
Earl.seek_to_hash = false
el = document.getElementById("#{loc.hash}") or document.querySelector("[name='#{loc.hash}']")
if el
window.scrollTo 0, getCoords(el).top - 50
if loc.query_params.c
delete loc.query_params.c
delete loc.hash
save loc
clearInterval @int
@int = null
, 50
monitor()
url_from_browser_location = ->
# location.search returns the query parameters
# fix url encoding
search = location.search?.replace(/\%2[fF]/g, '/')
loc = location.pathname?.replace(/\%20/g, ' ')
"#{loc}#{search}#{location.hash}"
url_from_statebus = ->
loc = fetch 'location'
url = loc.path or '/'
if loc.query_params && Object.keys(loc.query_params).length > 0
query_params = ("#{k}=#{v}" for own k,v of loc.query_params)
url += "?#{query_params.join('&')}"
if loc.hash?.length > 0
url += "##{loc.hash}"
url
# For handling device-specific annoyances
document.ontouchmove = (e) -> Earl._user_swipping = true
document.ontouchend = (e) -> Earl._user_swipping = false
rxaosp = window.navigator.userAgent.match /Android.*AppleWebKit\/([\d.]+)/
is_android_browser = !!(rxaosp && rxaosp[1]<537)
ua = navigator.userAgent
is_mobile = is_android_browser || \
ua.match(/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i)
|
[
{
"context": " controller : 'ListStepController'\n 'wizard@step.list' :\n templateUrl : 'views/components/o",
"end": 1090,
"score": 0.995876133441925,
"start": 1074,
"tag": "EMAIL",
"value": "wizard@step.list"
}
] | client/web/src/features/step/scripts/step-routes.coffee | TimeoutZero/ProjectTrail | 0 | 'use strict'
# =============================================
# Module
# =============================================
angular.module 'ProjectTrailApp'
# =============================================
# App Config
# =============================================
.config( ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) ->
# States
# =============================================
$stateProvider
# step
# ==============================
.state('step'
url : '/:teamId/:toolId/:actionId/'
templateUrl : 'views/features/step/views/step-view.html'
controller : 'StepController'
abstract : yes
data :
restrict : no
)
# List
# ==============================
.state('step.list'
url : 'list'
data :
restrict : no
views :
'' :
templateUrl : 'views/features/step/views/list-step-view.html'
controller : 'ListStepController'
'wizard@step.list' :
templateUrl : 'views/components/other/iwizard/views/i-list-wizard.html'
controller : 'IListWizardController'
)
# step
# ==============================
.state('step.create'
url : 'create'
templateUrl : 'views/features/step/views/form-step.html'
controller : 'FormStepController'
data :
restrict : no
)
# step
# ==============================
.state('step.edit'
url : ':id/edit/'
templateUrl : 'views/features/step/views/form-step.html'
controller : 'FormStepController'
data :
restrict : no
)
])
| 196363 | 'use strict'
# =============================================
# Module
# =============================================
angular.module 'ProjectTrailApp'
# =============================================
# App Config
# =============================================
.config( ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) ->
# States
# =============================================
$stateProvider
# step
# ==============================
.state('step'
url : '/:teamId/:toolId/:actionId/'
templateUrl : 'views/features/step/views/step-view.html'
controller : 'StepController'
abstract : yes
data :
restrict : no
)
# List
# ==============================
.state('step.list'
url : 'list'
data :
restrict : no
views :
'' :
templateUrl : 'views/features/step/views/list-step-view.html'
controller : 'ListStepController'
'<EMAIL>' :
templateUrl : 'views/components/other/iwizard/views/i-list-wizard.html'
controller : 'IListWizardController'
)
# step
# ==============================
.state('step.create'
url : 'create'
templateUrl : 'views/features/step/views/form-step.html'
controller : 'FormStepController'
data :
restrict : no
)
# step
# ==============================
.state('step.edit'
url : ':id/edit/'
templateUrl : 'views/features/step/views/form-step.html'
controller : 'FormStepController'
data :
restrict : no
)
])
| true | 'use strict'
# =============================================
# Module
# =============================================
angular.module 'ProjectTrailApp'
# =============================================
# App Config
# =============================================
.config( ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) ->
# States
# =============================================
$stateProvider
# step
# ==============================
.state('step'
url : '/:teamId/:toolId/:actionId/'
templateUrl : 'views/features/step/views/step-view.html'
controller : 'StepController'
abstract : yes
data :
restrict : no
)
# List
# ==============================
.state('step.list'
url : 'list'
data :
restrict : no
views :
'' :
templateUrl : 'views/features/step/views/list-step-view.html'
controller : 'ListStepController'
'PI:EMAIL:<EMAIL>END_PI' :
templateUrl : 'views/components/other/iwizard/views/i-list-wizard.html'
controller : 'IListWizardController'
)
# step
# ==============================
.state('step.create'
url : 'create'
templateUrl : 'views/features/step/views/form-step.html'
controller : 'FormStepController'
data :
restrict : no
)
# step
# ==============================
.state('step.edit'
url : ':id/edit/'
templateUrl : 'views/features/step/views/form-step.html'
controller : 'FormStepController'
data :
restrict : no
)
])
|
[
{
"context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nAPI_URL = 'http://putainmedia.ngrok.com'\nMEDIA_U",
"end": 66,
"score": 0.9999159574508667,
"start": 49,
"tag": "EMAIL",
"value": "nhim175@gmail.com"
}
] | src/lib/config.coffee | nhim175/scorpionsmasher | 0 | # Copyright © 2013 All rights reserved
# Author: nhim175@gmail.com
API_URL = 'http://putainmedia.ngrok.com'
MEDIA_URL = 'https://putainstatic.ngrok.com'
module.exports =
upload_url: API_URL + '/file/public_upload',
media_url: MEDIA_URL
width: 640
height: 1136
stage:
backgroundColor: 0x000000
boot:
images:
loading:
src: 'assets/img/loading.png'
images:
background:
src: 'assets/img/bg.png'
ground:
src: 'assets/img/ground.png'
logo:
src: 'assets/img/logo2.png'
start_btn:
src: 'assets/img/start_btn.png'
exit_btn:
src: 'assets/img/share_btn.png'
score_board:
src: 'assets/img/score_board.png'
game_over:
src: 'assets/img/game_over2.png'
axe:
src: 'assets/img/axe.png'
pause_btn:
src: 'assets/img/pause_button.png'
sprites:
red_duck:
src: 'assets/img/enemy1.png'
width: 79
height: 96
frames: 5
green_duck:
src: 'assets/img/enemy2.png'
width: 79
height: 96
frames: 5
cloud:
src: 'assets/img/cloud2.png'
width: 64
height: 96
frames: 2
atlasXML:
scorpion:
src: 'assets/atlasXML/scorpion.png'
xml: 'assets/atlasXML/scorpion.xml'
bitmap_fonts:
'8bit_wonder':
src: 'assets/font/8bit_wonder/font.png'
map: 'assets/font/8bit_wonder/font.xml'
sounds:
intro:
src: 'assets/sound/intro.ogg'
src_mp3: 'assets/sound/intro.mp3'
click:
src: 'assets/sound/click.ogg'
src_mp3: 'assets/sound/click.mp3'
pickup:
src: 'assets/sound/pickup.ogg'
src_mp3: 'assets/sound/pickup.mp3'
die:
src: 'assets/sound/die.mp3'
src_mp3: 'assets/sound/die.mp3'
double_kill:
src: 'assets/sound/double_kill.ogg'
src_mp3: 'assets/sound/double_kill.mp3'
triple_kill:
src: 'assets/sound/triple_kill.ogg'
src_mp3: 'assets/sound/triple_kill.mp3'
cockroach:
src: 'assets/sound/cockroach.mp3'
src_mp3: 'assets/sound/cockroach.mp3'
| 6350 | # Copyright © 2013 All rights reserved
# Author: <EMAIL>
API_URL = 'http://putainmedia.ngrok.com'
MEDIA_URL = 'https://putainstatic.ngrok.com'
module.exports =
upload_url: API_URL + '/file/public_upload',
media_url: MEDIA_URL
width: 640
height: 1136
stage:
backgroundColor: 0x000000
boot:
images:
loading:
src: 'assets/img/loading.png'
images:
background:
src: 'assets/img/bg.png'
ground:
src: 'assets/img/ground.png'
logo:
src: 'assets/img/logo2.png'
start_btn:
src: 'assets/img/start_btn.png'
exit_btn:
src: 'assets/img/share_btn.png'
score_board:
src: 'assets/img/score_board.png'
game_over:
src: 'assets/img/game_over2.png'
axe:
src: 'assets/img/axe.png'
pause_btn:
src: 'assets/img/pause_button.png'
sprites:
red_duck:
src: 'assets/img/enemy1.png'
width: 79
height: 96
frames: 5
green_duck:
src: 'assets/img/enemy2.png'
width: 79
height: 96
frames: 5
cloud:
src: 'assets/img/cloud2.png'
width: 64
height: 96
frames: 2
atlasXML:
scorpion:
src: 'assets/atlasXML/scorpion.png'
xml: 'assets/atlasXML/scorpion.xml'
bitmap_fonts:
'8bit_wonder':
src: 'assets/font/8bit_wonder/font.png'
map: 'assets/font/8bit_wonder/font.xml'
sounds:
intro:
src: 'assets/sound/intro.ogg'
src_mp3: 'assets/sound/intro.mp3'
click:
src: 'assets/sound/click.ogg'
src_mp3: 'assets/sound/click.mp3'
pickup:
src: 'assets/sound/pickup.ogg'
src_mp3: 'assets/sound/pickup.mp3'
die:
src: 'assets/sound/die.mp3'
src_mp3: 'assets/sound/die.mp3'
double_kill:
src: 'assets/sound/double_kill.ogg'
src_mp3: 'assets/sound/double_kill.mp3'
triple_kill:
src: 'assets/sound/triple_kill.ogg'
src_mp3: 'assets/sound/triple_kill.mp3'
cockroach:
src: 'assets/sound/cockroach.mp3'
src_mp3: 'assets/sound/cockroach.mp3'
| true | # Copyright © 2013 All rights reserved
# Author: PI:EMAIL:<EMAIL>END_PI
API_URL = 'http://putainmedia.ngrok.com'
MEDIA_URL = 'https://putainstatic.ngrok.com'
module.exports =
upload_url: API_URL + '/file/public_upload',
media_url: MEDIA_URL
width: 640
height: 1136
stage:
backgroundColor: 0x000000
boot:
images:
loading:
src: 'assets/img/loading.png'
images:
background:
src: 'assets/img/bg.png'
ground:
src: 'assets/img/ground.png'
logo:
src: 'assets/img/logo2.png'
start_btn:
src: 'assets/img/start_btn.png'
exit_btn:
src: 'assets/img/share_btn.png'
score_board:
src: 'assets/img/score_board.png'
game_over:
src: 'assets/img/game_over2.png'
axe:
src: 'assets/img/axe.png'
pause_btn:
src: 'assets/img/pause_button.png'
sprites:
red_duck:
src: 'assets/img/enemy1.png'
width: 79
height: 96
frames: 5
green_duck:
src: 'assets/img/enemy2.png'
width: 79
height: 96
frames: 5
cloud:
src: 'assets/img/cloud2.png'
width: 64
height: 96
frames: 2
atlasXML:
scorpion:
src: 'assets/atlasXML/scorpion.png'
xml: 'assets/atlasXML/scorpion.xml'
bitmap_fonts:
'8bit_wonder':
src: 'assets/font/8bit_wonder/font.png'
map: 'assets/font/8bit_wonder/font.xml'
sounds:
intro:
src: 'assets/sound/intro.ogg'
src_mp3: 'assets/sound/intro.mp3'
click:
src: 'assets/sound/click.ogg'
src_mp3: 'assets/sound/click.mp3'
pickup:
src: 'assets/sound/pickup.ogg'
src_mp3: 'assets/sound/pickup.mp3'
die:
src: 'assets/sound/die.mp3'
src_mp3: 'assets/sound/die.mp3'
double_kill:
src: 'assets/sound/double_kill.ogg'
src_mp3: 'assets/sound/double_kill.mp3'
triple_kill:
src: 'assets/sound/triple_kill.ogg'
src_mp3: 'assets/sound/triple_kill.mp3'
cockroach:
src: 'assets/sound/cockroach.mp3'
src_mp3: 'assets/sound/cockroach.mp3'
|
[
{
"context": "# // REGEXES\n replacePattern0 = /(http:\\/\\/127.0.0.1:43110\\/)/gi\n replacePattern1 = /(\\b(https?",
"end": 3054,
"score": 0.9996731877326965,
"start": 3045,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "/\\/0mail/gim;\n \n # ... | js/ZeroChat.coffee | angristan/zerochat-irc-fr | 1 | class ZeroChat extends ZeroFrame
init: ->
@addLine "inited!"
selectUser: =>
Page.cmd "certSelect", [["zeroid.bit"]]
return false
route: (cmd, message) ->
if cmd == "setSiteInfo"
if message.params.cert_user_id
document.getElementById("select_user").innerHTML = message.params.cert_user_id
else
document.getElementById("select_user").innerHTML = "Select user"
@site_info = message.params # Save site info data to allow access it later
# Reload messages if new file arrives
if message.params.event[0] == "file_done"
@loadMessages()
resetDebug: ->
document.getElementById("list").innerHTML = ""
debugMsg: (msg) ->
newElement = document.createElement('li')
newElement.innerHTML = msg
document.getElementById("list").appendChild(newElement)
resetInputField: =>
document.getElementById("message").disabled = false
document.getElementById("message").value = "" # Reset the message input
document.getElementById("message").focus()
sendMessage: =>
if not Page.site_info.cert_user_id # No account selected, display error
Page.cmd "wrapperNotification", ["info", "Please, select your account."]
return false
document.getElementById("message").disabled = true
inner_path = "data/users/#{@site_info.auth_address}/data.json" # This is our data file
# Load our current messages
@cmd "fileGet", {"inner_path": inner_path, "required": false}, (data) =>
if data # Parse if already exits
data = JSON.parse(data)
else # Not exits yet, use default data
data = { "message": [] }
# // EMPTY MESSAGES
msg = document.getElementById("message").value
if msg == "" or msg == "/me" or msg == "/me "
@debugMsg('empty message')
@resetInputField()
return false
# Add the message to data
data.message.push({
"body": document.getElementById("message").value,
"date_added": (+new Date)
})
# Encode data array to utf8 json text
json_raw = unescape(encodeURIComponent(JSON.stringify(data, undefined, '\t')))
# Write file to disk
@cmd "fileWrite", [inner_path, btoa(json_raw)], (res) =>
if res == "ok"
# Publish the file to other users
@cmd "sitePublish", {"inner_path": inner_path}, (res) =>
@resetInputField()
@loadMessages()
else
@cmd "wrapperNotification", ["error", "File write error: #{res}"]
document.getElementById("message").disabled = false
return false
replaceURLs: (body) ->
# // REGEXES
replacePattern0 = /(http:\/\/127.0.0.1:43110\/)/gi
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim
replacePattern4 = /0net:\/\/([-a-zA-Z0-9+&.,:+_\/=?]*)/g
replacePattern5 = /(([a-zA-Z0-9\-\_\.])+)\/\/0mail/gim;
# // url rewriting 127.0.0.1:43110 to 0net:// so other replacements don't break
replacedText = body.replace(replacePattern0, '0net://')
replacedText = replacedText.replace('@zeroid.bit', '//0mail')
# // URLs starting with http://, https://, or ftp://
replacedText = replacedText.replace(replacePattern1, '<a href="$1" target="_blank" style="color: red; font-weight: bold;">$1</a>');
# // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank" style="color: red; font-weight: bold;">$2</a>')
# // Change email addresses to mailto:: links.
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1" style="color: red; font-weight: bold;">$1</a>')
# // replace 0net:// URL href back to http://127.0.0.1:43110
replacedText = replacedText.replace(replacePattern4, '<a href="http://127.0.0.1:43110/$1" target="_blank" style="color: green; font-weight: bold;">0net://$1</a>')
# // rewrite link href and replace //0mail with @zeroid.bit
replacedText = replacedText.replace(replacePattern5, '<a href="http://127.0.0.1:43110/Mail.ZeroNetwork.bit/?to=$1" target="_blank" style="color: green; font-weight: bold;">$1@zeroid.bit</a>')
return replacedText
loadMessages: ->
query = """
SELECT message.*, keyvalue.value AS cert_user_id FROM message
LEFT JOIN json AS data_json USING (json_id)
LEFT JOIN json AS content_json ON (
data_json.directory = content_json.directory AND content_json.file_name = 'content.json'
)
LEFT JOIN keyvalue ON (keyvalue.key = 'cert_user_id' AND keyvalue.json_id = content_json.json_id)
ORDER BY date_added
"""
@cmd "dbQuery", [query], (messages) =>
document.getElementById("messages").innerHTML = "" # Always start with empty messages
message_lines = []
# // remove later
@resetDebug()
for message in messages
body = message.body.replace(/</g, "<").replace(/>/g, ">") # Escape html tags in body
added = new Date(message.date_added)
# // OUR ADDITIONS
time = Time.since(message.date_added / 1000)
userid = message.cert_user_id
useridcolor = Text.toColor(userid)
username = message.cert_user_id.replace('@zeroid.bit', '')
msgseparator = ":"
# // REPLACE URLS
body = @replaceURLs(body)
# // REPLACE IRC
if body.substr(0,3) == "/me"
action = body.replace("/me","")
username = username+' '+action
body = ''
msgseparator = ''
# // STYLE OUR MESSAGES AND MENTIONS
prestyle=""
poststyle=""
# our messages
if userid == Page.site_info.cert_user_id
prestyle = '<span style="color:black; font-weight:bold;">'
poststyle = '</span>'
# our mentions
if Page.site_info.cert_user_id and body.indexOf(Page.site_info.cert_user_id.replace('@zeroid.bit', '')) > -1
prestyle = '<span style="color:blue; font-weight:bold;">'
poststyle = '</span>'
body = prestyle + body + poststyle
message_lines.push "<li><small title='#{added}'>#{time}</small> <b style='color: #{useridcolor}'>#{username}</b>#{msgseparator} #{body}</li>"
message_lines.reverse()
document.getElementById("messages").innerHTML = message_lines.join("\n")
addLine: (line) ->
messages = document.getElementById("messages")
messages.innerHTML = "<li>#{line}</li>"+messages.innerHTML
# Wrapper websocket connection ready
onOpenWebsocket: (e) =>
@cmd "siteInfo", {}, (site_info) =>
document.getElementById("bigTitle").innerHTML = site_info.content.title + ' - ' + site_info.content.description
document.getElementById("peerCount").innerHTML = site_info.peers + ' Peers'
# Update currently selected username
if site_info.cert_user_id
document.getElementById("select_user").innerHTML = site_info.cert_user_id
@site_info = site_info # Save site info data to allow access it later
@loadMessages()
window.Page = new ZeroChat()
| 2438 | class ZeroChat extends ZeroFrame
init: ->
@addLine "inited!"
selectUser: =>
Page.cmd "certSelect", [["zeroid.bit"]]
return false
route: (cmd, message) ->
if cmd == "setSiteInfo"
if message.params.cert_user_id
document.getElementById("select_user").innerHTML = message.params.cert_user_id
else
document.getElementById("select_user").innerHTML = "Select user"
@site_info = message.params # Save site info data to allow access it later
# Reload messages if new file arrives
if message.params.event[0] == "file_done"
@loadMessages()
resetDebug: ->
document.getElementById("list").innerHTML = ""
debugMsg: (msg) ->
newElement = document.createElement('li')
newElement.innerHTML = msg
document.getElementById("list").appendChild(newElement)
resetInputField: =>
document.getElementById("message").disabled = false
document.getElementById("message").value = "" # Reset the message input
document.getElementById("message").focus()
sendMessage: =>
if not Page.site_info.cert_user_id # No account selected, display error
Page.cmd "wrapperNotification", ["info", "Please, select your account."]
return false
document.getElementById("message").disabled = true
inner_path = "data/users/#{@site_info.auth_address}/data.json" # This is our data file
# Load our current messages
@cmd "fileGet", {"inner_path": inner_path, "required": false}, (data) =>
if data # Parse if already exits
data = JSON.parse(data)
else # Not exits yet, use default data
data = { "message": [] }
# // EMPTY MESSAGES
msg = document.getElementById("message").value
if msg == "" or msg == "/me" or msg == "/me "
@debugMsg('empty message')
@resetInputField()
return false
# Add the message to data
data.message.push({
"body": document.getElementById("message").value,
"date_added": (+new Date)
})
# Encode data array to utf8 json text
json_raw = unescape(encodeURIComponent(JSON.stringify(data, undefined, '\t')))
# Write file to disk
@cmd "fileWrite", [inner_path, btoa(json_raw)], (res) =>
if res == "ok"
# Publish the file to other users
@cmd "sitePublish", {"inner_path": inner_path}, (res) =>
@resetInputField()
@loadMessages()
else
@cmd "wrapperNotification", ["error", "File write error: #{res}"]
document.getElementById("message").disabled = false
return false
replaceURLs: (body) ->
# // REGEXES
replacePattern0 = /(http:\/\/127.0.0.1:43110\/)/gi
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim
replacePattern4 = /0net:\/\/([-a-zA-Z0-9+&.,:+_\/=?]*)/g
replacePattern5 = /(([a-zA-Z0-9\-\_\.])+)\/\/0mail/gim;
# // url rewriting 127.0.0.1:43110 to 0net:// so other replacements don't break
replacedText = body.replace(replacePattern0, '0net://')
replacedText = replacedText.replace('@zeroid.bit', '//0mail')
# // URLs starting with http://, https://, or ftp://
replacedText = replacedText.replace(replacePattern1, '<a href="$1" target="_blank" style="color: red; font-weight: bold;">$1</a>');
# // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank" style="color: red; font-weight: bold;">$2</a>')
# // Change email addresses to mailto:: links.
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1" style="color: red; font-weight: bold;">$1</a>')
# // replace 0net:// URL href back to http://127.0.0.1:43110
replacedText = replacedText.replace(replacePattern4, '<a href="http://127.0.0.1:43110/$1" target="_blank" style="color: green; font-weight: bold;">0net://$1</a>')
# // rewrite link href and replace //0mail with @zeroid.bit
replacedText = replacedText.replace(replacePattern5, '<a href="http://127.0.0.1:43110/Mail.ZeroNetwork.bit/?to=$1" target="_blank" style="color: green; font-weight: bold;"><EMAIL></a>')
return replacedText
loadMessages: ->
query = """
SELECT message.*, keyvalue.value AS cert_user_id FROM message
LEFT JOIN json AS data_json USING (json_id)
LEFT JOIN json AS content_json ON (
data_json.directory = content_json.directory AND content_json.file_name = 'content.json'
)
LEFT JOIN keyvalue ON (keyvalue.key = '<KEY>' AND keyvalue.json_id = content_json.json_id)
ORDER BY date_added
"""
@cmd "dbQuery", [query], (messages) =>
document.getElementById("messages").innerHTML = "" # Always start with empty messages
message_lines = []
# // remove later
@resetDebug()
for message in messages
body = message.body.replace(/</g, "<").replace(/>/g, ">") # Escape html tags in body
added = new Date(message.date_added)
# // OUR ADDITIONS
time = Time.since(message.date_added / 1000)
userid = message.cert_user_id
useridcolor = Text.toColor(userid)
username = message.cert_user_id.replace('@zeroid.bit', '')
msgseparator = ":"
# // REPLACE URLS
body = @replaceURLs(body)
# // REPLACE IRC
if body.substr(0,3) == "/me"
action = body.replace("/me","")
username = username+' '+action
body = ''
msgseparator = ''
# // STYLE OUR MESSAGES AND MENTIONS
prestyle=""
poststyle=""
# our messages
if userid == Page.site_info.cert_user_id
prestyle = '<span style="color:black; font-weight:bold;">'
poststyle = '</span>'
# our mentions
if Page.site_info.cert_user_id and body.indexOf(Page.site_info.cert_user_id.replace('@zeroid.bit', '')) > -1
prestyle = '<span style="color:blue; font-weight:bold;">'
poststyle = '</span>'
body = prestyle + body + poststyle
message_lines.push "<li><small title='#{added}'>#{time}</small> <b style='color: #{useridcolor}'>#{username}</b>#{msgseparator} #{body}</li>"
message_lines.reverse()
document.getElementById("messages").innerHTML = message_lines.join("\n")
addLine: (line) ->
messages = document.getElementById("messages")
messages.innerHTML = "<li>#{line}</li>"+messages.innerHTML
# Wrapper websocket connection ready
onOpenWebsocket: (e) =>
@cmd "siteInfo", {}, (site_info) =>
document.getElementById("bigTitle").innerHTML = site_info.content.title + ' - ' + site_info.content.description
document.getElementById("peerCount").innerHTML = site_info.peers + ' Peers'
# Update currently selected username
if site_info.cert_user_id
document.getElementById("select_user").innerHTML = site_info.cert_user_id
@site_info = site_info # Save site info data to allow access it later
@loadMessages()
window.Page = new ZeroChat()
| true | class ZeroChat extends ZeroFrame
init: ->
@addLine "inited!"
selectUser: =>
Page.cmd "certSelect", [["zeroid.bit"]]
return false
route: (cmd, message) ->
if cmd == "setSiteInfo"
if message.params.cert_user_id
document.getElementById("select_user").innerHTML = message.params.cert_user_id
else
document.getElementById("select_user").innerHTML = "Select user"
@site_info = message.params # Save site info data to allow access it later
# Reload messages if new file arrives
if message.params.event[0] == "file_done"
@loadMessages()
resetDebug: ->
document.getElementById("list").innerHTML = ""
debugMsg: (msg) ->
newElement = document.createElement('li')
newElement.innerHTML = msg
document.getElementById("list").appendChild(newElement)
resetInputField: =>
document.getElementById("message").disabled = false
document.getElementById("message").value = "" # Reset the message input
document.getElementById("message").focus()
sendMessage: =>
if not Page.site_info.cert_user_id # No account selected, display error
Page.cmd "wrapperNotification", ["info", "Please, select your account."]
return false
document.getElementById("message").disabled = true
inner_path = "data/users/#{@site_info.auth_address}/data.json" # This is our data file
# Load our current messages
@cmd "fileGet", {"inner_path": inner_path, "required": false}, (data) =>
if data # Parse if already exits
data = JSON.parse(data)
else # Not exits yet, use default data
data = { "message": [] }
# // EMPTY MESSAGES
msg = document.getElementById("message").value
if msg == "" or msg == "/me" or msg == "/me "
@debugMsg('empty message')
@resetInputField()
return false
# Add the message to data
data.message.push({
"body": document.getElementById("message").value,
"date_added": (+new Date)
})
# Encode data array to utf8 json text
json_raw = unescape(encodeURIComponent(JSON.stringify(data, undefined, '\t')))
# Write file to disk
@cmd "fileWrite", [inner_path, btoa(json_raw)], (res) =>
if res == "ok"
# Publish the file to other users
@cmd "sitePublish", {"inner_path": inner_path}, (res) =>
@resetInputField()
@loadMessages()
else
@cmd "wrapperNotification", ["error", "File write error: #{res}"]
document.getElementById("message").disabled = false
return false
replaceURLs: (body) ->
# // REGEXES
replacePattern0 = /(http:\/\/127.0.0.1:43110\/)/gi
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim
replacePattern4 = /0net:\/\/([-a-zA-Z0-9+&.,:+_\/=?]*)/g
replacePattern5 = /(([a-zA-Z0-9\-\_\.])+)\/\/0mail/gim;
# // url rewriting 127.0.0.1:43110 to 0net:// so other replacements don't break
replacedText = body.replace(replacePattern0, '0net://')
replacedText = replacedText.replace('@zeroid.bit', '//0mail')
# // URLs starting with http://, https://, or ftp://
replacedText = replacedText.replace(replacePattern1, '<a href="$1" target="_blank" style="color: red; font-weight: bold;">$1</a>');
# // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank" style="color: red; font-weight: bold;">$2</a>')
# // Change email addresses to mailto:: links.
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1" style="color: red; font-weight: bold;">$1</a>')
# // replace 0net:// URL href back to http://127.0.0.1:43110
replacedText = replacedText.replace(replacePattern4, '<a href="http://127.0.0.1:43110/$1" target="_blank" style="color: green; font-weight: bold;">0net://$1</a>')
# // rewrite link href and replace //0mail with @zeroid.bit
replacedText = replacedText.replace(replacePattern5, '<a href="http://127.0.0.1:43110/Mail.ZeroNetwork.bit/?to=$1" target="_blank" style="color: green; font-weight: bold;">PI:EMAIL:<EMAIL>END_PI</a>')
return replacedText
loadMessages: ->
query = """
SELECT message.*, keyvalue.value AS cert_user_id FROM message
LEFT JOIN json AS data_json USING (json_id)
LEFT JOIN json AS content_json ON (
data_json.directory = content_json.directory AND content_json.file_name = 'content.json'
)
LEFT JOIN keyvalue ON (keyvalue.key = 'PI:KEY:<KEY>END_PI' AND keyvalue.json_id = content_json.json_id)
ORDER BY date_added
"""
@cmd "dbQuery", [query], (messages) =>
document.getElementById("messages").innerHTML = "" # Always start with empty messages
message_lines = []
# // remove later
@resetDebug()
for message in messages
body = message.body.replace(/</g, "<").replace(/>/g, ">") # Escape html tags in body
added = new Date(message.date_added)
# // OUR ADDITIONS
time = Time.since(message.date_added / 1000)
userid = message.cert_user_id
useridcolor = Text.toColor(userid)
username = message.cert_user_id.replace('@zeroid.bit', '')
msgseparator = ":"
# // REPLACE URLS
body = @replaceURLs(body)
# // REPLACE IRC
if body.substr(0,3) == "/me"
action = body.replace("/me","")
username = username+' '+action
body = ''
msgseparator = ''
# // STYLE OUR MESSAGES AND MENTIONS
prestyle=""
poststyle=""
# our messages
if userid == Page.site_info.cert_user_id
prestyle = '<span style="color:black; font-weight:bold;">'
poststyle = '</span>'
# our mentions
if Page.site_info.cert_user_id and body.indexOf(Page.site_info.cert_user_id.replace('@zeroid.bit', '')) > -1
prestyle = '<span style="color:blue; font-weight:bold;">'
poststyle = '</span>'
body = prestyle + body + poststyle
message_lines.push "<li><small title='#{added}'>#{time}</small> <b style='color: #{useridcolor}'>#{username}</b>#{msgseparator} #{body}</li>"
message_lines.reverse()
document.getElementById("messages").innerHTML = message_lines.join("\n")
addLine: (line) ->
messages = document.getElementById("messages")
messages.innerHTML = "<li>#{line}</li>"+messages.innerHTML
# Wrapper websocket connection ready
onOpenWebsocket: (e) =>
@cmd "siteInfo", {}, (site_info) =>
document.getElementById("bigTitle").innerHTML = site_info.content.title + ' - ' + site_info.content.description
document.getElementById("peerCount").innerHTML = site_info.peers + ' Peers'
# Update currently selected username
if site_info.cert_user_id
document.getElementById("select_user").innerHTML = site_info.cert_user_id
@site_info = site_info # Save site info data to allow access it later
@loadMessages()
window.Page = new ZeroChat()
|
[
{
"context": "orts = (mockup)->\n client = mockup.data.clients['awesome-app']\n PROVIDER_BASEURL = mockup.config.PROVIDER_BAS",
"end": 100,
"score": 0.8668273091316223,
"start": 89,
"tag": "USERNAME",
"value": "awesome-app"
},
{
"context": "icationLogin {clientId: client.id, client... | test/exchanges/client_credentials.coffee | tungv/oauth2-provider | 2 | request = require 'request'
module.exports = (mockup)->
client = mockup.data.clients['awesome-app']
PROVIDER_BASEURL = mockup.config.PROVIDER_BASEURL
describe 'Client Credentials', ->
applicationLogin = (client, cb)->
query = {
grant_type: 'client_credentials'
client_id: client.clientId
client_secret: client.clientSecret
scope: '*'
}
request.post {
uri: "#{PROVIDER_BASEURL}/oauth/token"
json: query
}, cb
apiRequest = mockup.methods.apiRequest
describe 'Successful scenario', ->
resp = {}
it 'should return 200 code', (done)->
applicationLogin client, (err, _resp, body)->
resp = _resp
resp.statusCode.should.equal 200
done()
it 'should contain an access_token', ->
resp.body.access_token.should.be.a 'string'
it 'should contain an token_type', ->
resp.body.token_type.should.equal 'Bearer'
it 'should allow returned access_token to access protected resources', (done)->
apiRequest resp.body, (err, resp, body)->
body.name.should.equal 'correct'
done()
describe 'Failure scenario', ->
it 'should not return access_token on invalid credentials', (done)->
applicationLogin {clientId: client.id, clientSecret: 'hacker'}, (err, resp, body)->
resp.statusCode.should.equal 401
body.should.equal 'Unauthorized'
done()
it 'should not allow invalid access_token to access protected resources', (done)->
apiRequest {
token_type: 'Bearer'
access_token: '1nv@l1D-@cc355'
}, (err, resp, body)->
resp.statusCode.should.equal 401
body.should.equal 'Unauthorized'
done()
| 522 | request = require 'request'
module.exports = (mockup)->
client = mockup.data.clients['awesome-app']
PROVIDER_BASEURL = mockup.config.PROVIDER_BASEURL
describe 'Client Credentials', ->
applicationLogin = (client, cb)->
query = {
grant_type: 'client_credentials'
client_id: client.clientId
client_secret: client.clientSecret
scope: '*'
}
request.post {
uri: "#{PROVIDER_BASEURL}/oauth/token"
json: query
}, cb
apiRequest = mockup.methods.apiRequest
describe 'Successful scenario', ->
resp = {}
it 'should return 200 code', (done)->
applicationLogin client, (err, _resp, body)->
resp = _resp
resp.statusCode.should.equal 200
done()
it 'should contain an access_token', ->
resp.body.access_token.should.be.a 'string'
it 'should contain an token_type', ->
resp.body.token_type.should.equal 'Bearer'
it 'should allow returned access_token to access protected resources', (done)->
apiRequest resp.body, (err, resp, body)->
body.name.should.equal 'correct'
done()
describe 'Failure scenario', ->
it 'should not return access_token on invalid credentials', (done)->
applicationLogin {clientId: client.id, clientSecret: '<KEY>'}, (err, resp, body)->
resp.statusCode.should.equal 401
body.should.equal 'Unauthorized'
done()
it 'should not allow invalid access_token to access protected resources', (done)->
apiRequest {
token_type: 'Bearer'
access_token: '<PASSWORD>'
}, (err, resp, body)->
resp.statusCode.should.equal 401
body.should.equal 'Unauthorized'
done()
| true | request = require 'request'
module.exports = (mockup)->
client = mockup.data.clients['awesome-app']
PROVIDER_BASEURL = mockup.config.PROVIDER_BASEURL
describe 'Client Credentials', ->
applicationLogin = (client, cb)->
query = {
grant_type: 'client_credentials'
client_id: client.clientId
client_secret: client.clientSecret
scope: '*'
}
request.post {
uri: "#{PROVIDER_BASEURL}/oauth/token"
json: query
}, cb
apiRequest = mockup.methods.apiRequest
describe 'Successful scenario', ->
resp = {}
it 'should return 200 code', (done)->
applicationLogin client, (err, _resp, body)->
resp = _resp
resp.statusCode.should.equal 200
done()
it 'should contain an access_token', ->
resp.body.access_token.should.be.a 'string'
it 'should contain an token_type', ->
resp.body.token_type.should.equal 'Bearer'
it 'should allow returned access_token to access protected resources', (done)->
apiRequest resp.body, (err, resp, body)->
body.name.should.equal 'correct'
done()
describe 'Failure scenario', ->
it 'should not return access_token on invalid credentials', (done)->
applicationLogin {clientId: client.id, clientSecret: 'PI:KEY:<KEY>END_PI'}, (err, resp, body)->
resp.statusCode.should.equal 401
body.should.equal 'Unauthorized'
done()
it 'should not allow invalid access_token to access protected resources', (done)->
apiRequest {
token_type: 'Bearer'
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}, (err, resp, body)->
resp.statusCode.should.equal 401
body.should.equal 'Unauthorized'
done()
|
[
{
"context": "ect, next)->\n assert object.doc.name == 'carol'\n next()\n done()\n m = Mode",
"end": 845,
"score": 0.999513566493988,
"start": 840,
"tag": "NAME",
"value": "carol"
},
{
"context": " done()\n m = Model.create 'pre-put', name:'caro... | ExampleZukaiRestApi/node_modules/zukai/test/hooks.coffee | radjivC/interaction-node-riak | 0 | assert = require 'assert'
{createClient} = require 'riakpbc'
{createModel} = require '../src'
Model = null
connection = null
badgePlugin = (model, options)->
model.schema.properties.badge =
type: 'string'
describe 'Hooks', ->
beforeEach (done)->
Model = createModel
name: 'plugins-test'
connection: createClient()
schema:
properties:
name:
type: 'string'
age:
type: 'number'
done()
describe 'basic plugin', ->
it 'should add schema items', (done)->
Model.plugin badgePlugin, {k:1, v:2}
assert Model.schema.properties.badge
done()
describe 'plugin put events', ->
it 'pre-put should work', (done)->
Model.plugin (model, options)->
model.pre 'put', (object, next)->
assert object.doc.name == 'carol'
next()
done()
m = Model.create 'pre-put', name:'carol', age:77
m.put().then ->
m.del().then()
it 'pre-put should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'put', (object, next)->
next 'fail'
m = Model.create 'pre-put-error', name:'dave', age:88
m.put().catch (err)->
assert err.message == 'fail'
done()
it 'post-put should work', (done)->
Model.plugin (model, options)->
model.post 'put', (object, next)->
assert object.doc.name == 'ed'
next()
done()
m = Model.create 'post-put', name:'ed', age:99
m.put().then ->
m.del().then()
it 'post-put should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'put', (object, next)->
next 'fail'
m = Model.create 'post-put-error', name:'frank', age:101
m.put().catch (err)->
assert err.message == 'fail'
m.del().then done
describe 'plugin delete events', ->
it 'pre-delete should work', (done)->
Model.plugin (model, options)->
model.pre 'del', (object, next)->
assert object.doc.name == 'gene'
next()
done()
m = Model.create 'pre-del', name:'gene', age:22
m.put().then ->
m.del().then()
it 'pre-delete should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'del', (object, next)->
next 'fail'
m = Model.create 'pre-del-error', name:'harry', age:33
m.put().then ->
ok = ->
assert 0
er = (err)->
assert err.message == 'fail'
Model.hooks.pre.del = []
m.del().then done
m.del().then ok, er
it 'post-delete should work', (done)->
Model.plugin (model, options)->
model.post 'del', (object, next)->
assert object.doc.name == 'iris'
next()
done()
m = Model.create 'post-del', name:'iris', age:44
m.put().then ->
m.del().then()
it 'post-delete should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'del', (object, next)->
next 'fail'
m = Model.create 'post-del-error', name:'james', age:55
m.put().then ->
ok = ->
assert 0
er = (err)->
assert err.message == 'fail'
Model.hooks.post.del = []
m.del().then done
m.del().then ok, er
describe 'plugin create events', ->
it 'pre-create should work', (done)->
Model.plugin (model, options)->
model.pre 'create', (object, next)->
assert object.doc.name == 'kate'
#next()
done()
m = Model.create 'pre-create', name:'kate', age:66
assert m.doc.name == 'kate'
it 'pre-create should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'create', (object)->
throw new Error
try
m = Model.create 'pre-create-error', name:'larry', age:77
catch err
done()
it 'post-create should work', (done)->
Model.plugin (model, options)->
model.post 'create', (object)->
assert object.doc.name == 'moe'
object.doc.name = 'mose'
m = Model.create 'post-create', name:'moe', age:88
assert m.doc.name == 'mose'
done()
it 'post-create should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'create', (object)->
throw new Error
try
m = Model.create 'post-create-error', name:'ned', age:99
catch err
done()
| 94052 | assert = require 'assert'
{createClient} = require 'riakpbc'
{createModel} = require '../src'
Model = null
connection = null
badgePlugin = (model, options)->
model.schema.properties.badge =
type: 'string'
describe 'Hooks', ->
beforeEach (done)->
Model = createModel
name: 'plugins-test'
connection: createClient()
schema:
properties:
name:
type: 'string'
age:
type: 'number'
done()
describe 'basic plugin', ->
it 'should add schema items', (done)->
Model.plugin badgePlugin, {k:1, v:2}
assert Model.schema.properties.badge
done()
describe 'plugin put events', ->
it 'pre-put should work', (done)->
Model.plugin (model, options)->
model.pre 'put', (object, next)->
assert object.doc.name == '<NAME>'
next()
done()
m = Model.create 'pre-put', name:'<NAME>', age:77
m.put().then ->
m.del().then()
it 'pre-put should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'put', (object, next)->
next 'fail'
m = Model.create 'pre-put-error', name:'<NAME>', age:88
m.put().catch (err)->
assert err.message == 'fail'
done()
it 'post-put should work', (done)->
Model.plugin (model, options)->
model.post 'put', (object, next)->
assert object.doc.name == 'ed'
next()
done()
m = Model.create 'post-put', name:'<NAME>', age:99
m.put().then ->
m.del().then()
it 'post-put should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'put', (object, next)->
next 'fail'
m = Model.create 'post-put-error', name:'<NAME>', age:101
m.put().catch (err)->
assert err.message == 'fail'
m.del().then done
describe 'plugin delete events', ->
it 'pre-delete should work', (done)->
Model.plugin (model, options)->
model.pre 'del', (object, next)->
assert object.doc.name == 'gene'
next()
done()
m = Model.create 'pre-del', name:'<NAME>', age:22
m.put().then ->
m.del().then()
it 'pre-delete should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'del', (object, next)->
next 'fail'
m = Model.create 'pre-del-error', name:'<NAME>', age:33
m.put().then ->
ok = ->
assert 0
er = (err)->
assert err.message == 'fail'
Model.hooks.pre.del = []
m.del().then done
m.del().then ok, er
it 'post-delete should work', (done)->
Model.plugin (model, options)->
model.post 'del', (object, next)->
assert object.doc.name == '<NAME>'
next()
done()
m = Model.create 'post-del', name:'<NAME>', age:44
m.put().then ->
m.del().then()
it 'post-delete should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'del', (object, next)->
next 'fail'
m = Model.create 'post-del-error', name:'<NAME>', age:55
m.put().then ->
ok = ->
assert 0
er = (err)->
assert err.message == 'fail'
Model.hooks.post.del = []
m.del().then done
m.del().then ok, er
describe 'plugin create events', ->
it 'pre-create should work', (done)->
Model.plugin (model, options)->
model.pre 'create', (object, next)->
assert object.doc.name == '<NAME>'
#next()
done()
m = Model.create 'pre-create', name:'<NAME>', age:66
assert m.doc.name == '<NAME>'
it 'pre-create should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'create', (object)->
throw new Error
try
m = Model.create 'pre-create-error', name:'<NAME>', age:77
catch err
done()
it 'post-create should work', (done)->
Model.plugin (model, options)->
model.post 'create', (object)->
assert object.doc.name == '<NAME>'
object.doc.name = '<NAME>'
m = Model.create 'post-create', name:'<NAME>', age:88
assert m.doc.name == '<NAME>'
done()
it 'post-create should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'create', (object)->
throw new Error
try
m = Model.create 'post-create-error', name:'<NAME>', age:99
catch err
done()
| true | assert = require 'assert'
{createClient} = require 'riakpbc'
{createModel} = require '../src'
Model = null
connection = null
badgePlugin = (model, options)->
model.schema.properties.badge =
type: 'string'
describe 'Hooks', ->
beforeEach (done)->
Model = createModel
name: 'plugins-test'
connection: createClient()
schema:
properties:
name:
type: 'string'
age:
type: 'number'
done()
describe 'basic plugin', ->
it 'should add schema items', (done)->
Model.plugin badgePlugin, {k:1, v:2}
assert Model.schema.properties.badge
done()
describe 'plugin put events', ->
it 'pre-put should work', (done)->
Model.plugin (model, options)->
model.pre 'put', (object, next)->
assert object.doc.name == 'PI:NAME:<NAME>END_PI'
next()
done()
m = Model.create 'pre-put', name:'PI:NAME:<NAME>END_PI', age:77
m.put().then ->
m.del().then()
it 'pre-put should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'put', (object, next)->
next 'fail'
m = Model.create 'pre-put-error', name:'PI:NAME:<NAME>END_PI', age:88
m.put().catch (err)->
assert err.message == 'fail'
done()
it 'post-put should work', (done)->
Model.plugin (model, options)->
model.post 'put', (object, next)->
assert object.doc.name == 'ed'
next()
done()
m = Model.create 'post-put', name:'PI:NAME:<NAME>END_PI', age:99
m.put().then ->
m.del().then()
it 'post-put should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'put', (object, next)->
next 'fail'
m = Model.create 'post-put-error', name:'PI:NAME:<NAME>END_PI', age:101
m.put().catch (err)->
assert err.message == 'fail'
m.del().then done
describe 'plugin delete events', ->
it 'pre-delete should work', (done)->
Model.plugin (model, options)->
model.pre 'del', (object, next)->
assert object.doc.name == 'gene'
next()
done()
m = Model.create 'pre-del', name:'PI:NAME:<NAME>END_PI', age:22
m.put().then ->
m.del().then()
it 'pre-delete should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'del', (object, next)->
next 'fail'
m = Model.create 'pre-del-error', name:'PI:NAME:<NAME>END_PI', age:33
m.put().then ->
ok = ->
assert 0
er = (err)->
assert err.message == 'fail'
Model.hooks.pre.del = []
m.del().then done
m.del().then ok, er
it 'post-delete should work', (done)->
Model.plugin (model, options)->
model.post 'del', (object, next)->
assert object.doc.name == 'PI:NAME:<NAME>END_PI'
next()
done()
m = Model.create 'post-del', name:'PI:NAME:<NAME>END_PI', age:44
m.put().then ->
m.del().then()
it 'post-delete should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'del', (object, next)->
next 'fail'
m = Model.create 'post-del-error', name:'PI:NAME:<NAME>END_PI', age:55
m.put().then ->
ok = ->
assert 0
er = (err)->
assert err.message == 'fail'
Model.hooks.post.del = []
m.del().then done
m.del().then ok, er
describe 'plugin create events', ->
it 'pre-create should work', (done)->
Model.plugin (model, options)->
model.pre 'create', (object, next)->
assert object.doc.name == 'PI:NAME:<NAME>END_PI'
#next()
done()
m = Model.create 'pre-create', name:'PI:NAME:<NAME>END_PI', age:66
assert m.doc.name == 'PI:NAME:<NAME>END_PI'
it 'pre-create should propagate errors', (done)->
Model.plugin (model, options)->
model.pre 'create', (object)->
throw new Error
try
m = Model.create 'pre-create-error', name:'PI:NAME:<NAME>END_PI', age:77
catch err
done()
it 'post-create should work', (done)->
Model.plugin (model, options)->
model.post 'create', (object)->
assert object.doc.name == 'PI:NAME:<NAME>END_PI'
object.doc.name = 'PI:NAME:<NAME>END_PI'
m = Model.create 'post-create', name:'PI:NAME:<NAME>END_PI', age:88
assert m.doc.name == 'PI:NAME:<NAME>END_PI'
done()
it 'post-create should propagate errors', (done)->
Model.plugin (model, options)->
model.post 'create', (object)->
throw new Error
try
m = Model.create 'post-create-error', name:'PI:NAME:<NAME>END_PI', age:99
catch err
done()
|
[
{
"context": "', ->\n @view.preInitialize userData: email: 'foo@bar.com'\n @view.templateData.email.should.containEql",
"end": 3241,
"score": 0.9999120831489563,
"start": 3230,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": " @view.templateData.email.should.con... | src/desktop/components/auth_modal/test/view.coffee | streamich/force | 1 | _ = require 'underscore'
sd = require('sharify').data
benv = require 'benv'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
mediator = require '../../../lib/mediator'
LoggedOutUser = rewire '../../../models/logged_out_user'
jade = require 'jade'
path = require 'path'
fs = require 'fs'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'AuthModalView', ->
before (done) ->
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
@AuthModalView = rewire '../view'
@AuthModalView.__set__ 'Cookies',
set: sinon.stub()
get: sinon.stub()
LoggedOutUser.__set__ 'sd', AP: {}
sinon.stub @AuthModalView::, 'initialize'
done()
after ->
benv.teardown()
beforeEach ->
@view = new @AuthModalView
sinon.stub(Backbone, 'sync').yieldsTo 'success', user: accessToken: 'secrets'
afterEach ->
Backbone.sync.restore()
describe '#preInitialize', ->
it 'can render custom copy a single individual mode', ->
@view.preInitialize copy: 'Log in to foobar', mode: 'login'
@view.templateData.copy.get('login').should.equal 'Log in to foobar'
@view.templateData.copy.has('register').should.be.false()
it 'can render custom copy for the default individual mode', ->
# 'register' is the default mode for the view's State
@view.preInitialize copy: 'Sign up to foobar'
@view.templateData.copy.get('register').should.equal 'Sign up to foobar'
@view.templateData.copy.has('login').should.be.false()
it 'can render custom copy for multiple individual modes', ->
@view.preInitialize copy:
register: 'Sign up to foobar'
signup: 'Create an account to foobar'
login: 'Log in to foobar'
@view.templateData.copy.attributes.should.eql
register: 'Sign up to foobar'
signup: 'Create an account to foobar'
login: 'Log in to foobar'
it 'always returns an object for copy templateData', ->
@view.preInitialize()
@view.templateData.copy.attributes.should.containEql {}
it 'returns custom copy for the redirecTo route if present', ->
@view.redirectTo = '/following/profiles'
@view.preInitialize()
@view.templateData.copy.attributes.should.eql
signup: null
register: 'Sign up to follow galleries and museums'
login: 'Login to follow galleries and museums'
it 'can render custom redirect', ->
@view.redirectTo = '/awesome-fair'
@view.preInitialize copy: 'Sign up to foobar.'
@view.templateData.redirectTo.should.containEql '/awesome-fair'
it 'passes the pathname to the template', ->
_location = @AuthModalView.__get__ 'location'
@AuthModalView.__set__ 'location', pathname: 'foobarbaz'
@view.preInitialize mode: 'login'
@view.templateData.redirectTo.should.equal 'foobarbaz'
@AuthModalView.__set__ 'location', _location
it 'accepts optional userData that gets passed to the template', ->
@view.preInitialize userData: email: 'foo@bar.com'
@view.templateData.email.should.containEql 'foo@bar.com'
describe '#submit', ->
beforeEach ->
sinon.stub location, 'assign'
sinon.stub location, 'reload'
@view.validateForm = -> true
@view.state = new Backbone.Model
@view.user = new LoggedOutUser
afterEach ->
location.assign.restore()
location.reload.restore()
it 'sets a cookie named destination with whatever the passed in destination is', ->
@view.destination = '/artist/some-guy/follow'
@view.state.set mode: 'register'
@view.submit $.Event('click')
_.last(@AuthModalView.__get__('Cookies').set.args)[1].should.equal @view.destination
it 'creates a signed_in cookie', ->
@view.state.set mode: 'login'
@view.submit $.Event('click')
_.last(@AuthModalView.__get__('Cookies').set.args)[1].should.be.true()
it 'sends a CSRF token', ->
@view.$el.html $ "<form>" + render('register')(
copy: new Backbone.Model
sd: CSRF_TOKEN: 'csrfoo', AP: loginPagePath: 'foo'
) + "</form>"
@view.state.set mode: 'register'
@view.submit $.Event('click')
Backbone.sync.args[1][1].toJSON()._csrf.should.equal 'csrfoo'
describe '#onSubmitSuccess', ->
beforeEach ->
@view.state = new Backbone.Model mode: 'reset'
@view.user = new LoggedOutUser
sinon.stub @view, 'reenableForm'
@submitSpy = sinon.spy $.fn, 'submit'
afterEach ->
@view.reenableForm.restore()
@submitSpy.restore()
it 'does not submit form if the the mode is password reset', ->
@view.onSubmitSuccess @view.user, { success: 200 }
@submitSpy.should.be.calledOnce
| 180053 | _ = require 'underscore'
sd = require('sharify').data
benv = require 'benv'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
mediator = require '../../../lib/mediator'
LoggedOutUser = rewire '../../../models/logged_out_user'
jade = require 'jade'
path = require 'path'
fs = require 'fs'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'AuthModalView', ->
before (done) ->
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
@AuthModalView = rewire '../view'
@AuthModalView.__set__ 'Cookies',
set: sinon.stub()
get: sinon.stub()
LoggedOutUser.__set__ 'sd', AP: {}
sinon.stub @AuthModalView::, 'initialize'
done()
after ->
benv.teardown()
beforeEach ->
@view = new @AuthModalView
sinon.stub(Backbone, 'sync').yieldsTo 'success', user: accessToken: 'secrets'
afterEach ->
Backbone.sync.restore()
describe '#preInitialize', ->
it 'can render custom copy a single individual mode', ->
@view.preInitialize copy: 'Log in to foobar', mode: 'login'
@view.templateData.copy.get('login').should.equal 'Log in to foobar'
@view.templateData.copy.has('register').should.be.false()
it 'can render custom copy for the default individual mode', ->
# 'register' is the default mode for the view's State
@view.preInitialize copy: 'Sign up to foobar'
@view.templateData.copy.get('register').should.equal 'Sign up to foobar'
@view.templateData.copy.has('login').should.be.false()
it 'can render custom copy for multiple individual modes', ->
@view.preInitialize copy:
register: 'Sign up to foobar'
signup: 'Create an account to foobar'
login: 'Log in to foobar'
@view.templateData.copy.attributes.should.eql
register: 'Sign up to foobar'
signup: 'Create an account to foobar'
login: 'Log in to foobar'
it 'always returns an object for copy templateData', ->
@view.preInitialize()
@view.templateData.copy.attributes.should.containEql {}
it 'returns custom copy for the redirecTo route if present', ->
@view.redirectTo = '/following/profiles'
@view.preInitialize()
@view.templateData.copy.attributes.should.eql
signup: null
register: 'Sign up to follow galleries and museums'
login: 'Login to follow galleries and museums'
it 'can render custom redirect', ->
@view.redirectTo = '/awesome-fair'
@view.preInitialize copy: 'Sign up to foobar.'
@view.templateData.redirectTo.should.containEql '/awesome-fair'
it 'passes the pathname to the template', ->
_location = @AuthModalView.__get__ 'location'
@AuthModalView.__set__ 'location', pathname: 'foobarbaz'
@view.preInitialize mode: 'login'
@view.templateData.redirectTo.should.equal 'foobarbaz'
@AuthModalView.__set__ 'location', _location
it 'accepts optional userData that gets passed to the template', ->
@view.preInitialize userData: email: '<EMAIL>'
@view.templateData.email.should.containEql '<EMAIL>'
describe '#submit', ->
beforeEach ->
sinon.stub location, 'assign'
sinon.stub location, 'reload'
@view.validateForm = -> true
@view.state = new Backbone.Model
@view.user = new LoggedOutUser
afterEach ->
location.assign.restore()
location.reload.restore()
it 'sets a cookie named destination with whatever the passed in destination is', ->
@view.destination = '/artist/some-guy/follow'
@view.state.set mode: 'register'
@view.submit $.Event('click')
_.last(@AuthModalView.__get__('Cookies').set.args)[1].should.equal @view.destination
it 'creates a signed_in cookie', ->
@view.state.set mode: 'login'
@view.submit $.Event('click')
_.last(@AuthModalView.__get__('Cookies').set.args)[1].should.be.true()
it 'sends a CSRF token', ->
@view.$el.html $ "<form>" + render('register')(
copy: new Backbone.Model
sd: CSRF_TOKEN: '<PASSWORD>', AP: loginPagePath: 'foo'
) + "</form>"
@view.state.set mode: 'register'
@view.submit $.Event('click')
Backbone.sync.args[1][1].toJSON()._csrf.should.equal 'csrfoo'
describe '#onSubmitSuccess', ->
beforeEach ->
@view.state = new Backbone.Model mode: 'reset'
@view.user = new LoggedOutUser
sinon.stub @view, 'reenableForm'
@submitSpy = sinon.spy $.fn, 'submit'
afterEach ->
@view.reenableForm.restore()
@submitSpy.restore()
it 'does not submit form if the the mode is password reset', ->
@view.onSubmitSuccess @view.user, { success: 200 }
@submitSpy.should.be.calledOnce
| true | _ = require 'underscore'
sd = require('sharify').data
benv = require 'benv'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
mediator = require '../../../lib/mediator'
LoggedOutUser = rewire '../../../models/logged_out_user'
jade = require 'jade'
path = require 'path'
fs = require 'fs'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'AuthModalView', ->
before (done) ->
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
@AuthModalView = rewire '../view'
@AuthModalView.__set__ 'Cookies',
set: sinon.stub()
get: sinon.stub()
LoggedOutUser.__set__ 'sd', AP: {}
sinon.stub @AuthModalView::, 'initialize'
done()
after ->
benv.teardown()
beforeEach ->
@view = new @AuthModalView
sinon.stub(Backbone, 'sync').yieldsTo 'success', user: accessToken: 'secrets'
afterEach ->
Backbone.sync.restore()
describe '#preInitialize', ->
it 'can render custom copy a single individual mode', ->
@view.preInitialize copy: 'Log in to foobar', mode: 'login'
@view.templateData.copy.get('login').should.equal 'Log in to foobar'
@view.templateData.copy.has('register').should.be.false()
it 'can render custom copy for the default individual mode', ->
# 'register' is the default mode for the view's State
@view.preInitialize copy: 'Sign up to foobar'
@view.templateData.copy.get('register').should.equal 'Sign up to foobar'
@view.templateData.copy.has('login').should.be.false()
it 'can render custom copy for multiple individual modes', ->
@view.preInitialize copy:
register: 'Sign up to foobar'
signup: 'Create an account to foobar'
login: 'Log in to foobar'
@view.templateData.copy.attributes.should.eql
register: 'Sign up to foobar'
signup: 'Create an account to foobar'
login: 'Log in to foobar'
it 'always returns an object for copy templateData', ->
@view.preInitialize()
@view.templateData.copy.attributes.should.containEql {}
it 'returns custom copy for the redirecTo route if present', ->
@view.redirectTo = '/following/profiles'
@view.preInitialize()
@view.templateData.copy.attributes.should.eql
signup: null
register: 'Sign up to follow galleries and museums'
login: 'Login to follow galleries and museums'
it 'can render custom redirect', ->
@view.redirectTo = '/awesome-fair'
@view.preInitialize copy: 'Sign up to foobar.'
@view.templateData.redirectTo.should.containEql '/awesome-fair'
it 'passes the pathname to the template', ->
_location = @AuthModalView.__get__ 'location'
@AuthModalView.__set__ 'location', pathname: 'foobarbaz'
@view.preInitialize mode: 'login'
@view.templateData.redirectTo.should.equal 'foobarbaz'
@AuthModalView.__set__ 'location', _location
it 'accepts optional userData that gets passed to the template', ->
@view.preInitialize userData: email: 'PI:EMAIL:<EMAIL>END_PI'
@view.templateData.email.should.containEql 'PI:EMAIL:<EMAIL>END_PI'
describe '#submit', ->
beforeEach ->
sinon.stub location, 'assign'
sinon.stub location, 'reload'
@view.validateForm = -> true
@view.state = new Backbone.Model
@view.user = new LoggedOutUser
afterEach ->
location.assign.restore()
location.reload.restore()
it 'sets a cookie named destination with whatever the passed in destination is', ->
@view.destination = '/artist/some-guy/follow'
@view.state.set mode: 'register'
@view.submit $.Event('click')
_.last(@AuthModalView.__get__('Cookies').set.args)[1].should.equal @view.destination
it 'creates a signed_in cookie', ->
@view.state.set mode: 'login'
@view.submit $.Event('click')
_.last(@AuthModalView.__get__('Cookies').set.args)[1].should.be.true()
it 'sends a CSRF token', ->
@view.$el.html $ "<form>" + render('register')(
copy: new Backbone.Model
sd: CSRF_TOKEN: 'PI:PASSWORD:<PASSWORD>END_PI', AP: loginPagePath: 'foo'
) + "</form>"
@view.state.set mode: 'register'
@view.submit $.Event('click')
Backbone.sync.args[1][1].toJSON()._csrf.should.equal 'csrfoo'
describe '#onSubmitSuccess', ->
beforeEach ->
@view.state = new Backbone.Model mode: 'reset'
@view.user = new LoggedOutUser
sinon.stub @view, 'reenableForm'
@submitSpy = sinon.spy $.fn, 'submit'
afterEach ->
@view.reenableForm.restore()
@submitSpy.restore()
it 'does not submit form if the the mode is password reset', ->
@view.onSubmitSuccess @view.user, { success: 200 }
@submitSpy.should.be.calledOnce
|
[
{
"context": "###\n\tCopyright 2013 David Pearson.\n\tBSD License.\n###\n\n# Adds two matrices\n#\n# a - T",
"end": 33,
"score": 0.9998437762260437,
"start": 20,
"tag": "NAME",
"value": "David Pearson"
}
] | src/matrix.coffee | dpearson/linalgebra | 1 | ###
Copyright 2013 David Pearson.
BSD License.
###
# Adds two matrices
#
# a - The left matrix in the addition
# b - The right matrix in the addition
#
# Example:
# add [[1, 3], [1, 0], [1, 2]], [[0, 0], [7, 5], [2, 1]]
# => [[1, 3], [8, 5], [3, 3]]
#
# Returns the resulting matrix or null if the dimensions differ
add=(a, b) ->
if a.length==b.length and a[0].length==b[0].length
c=[]
for i of a
c[i]=[]
for j of a[i]
c[i][j]=a[i][j]+b[i][j]
c
else
null
# Multiplies a matrix by a scalar value
#
# a - The matrix to scale
# mult - The scalar value to multiply by
#
# Example:
# multiplyScalar [[1, 3], [1, 0], [1, 2]], 5
# => [[5, 15], [5, 0], [5, 10]]
#
# Returns the resulting matrix
multiplyScalar=(a, mult) ->
for i of a
for j of a[i]
a[i][j]*=mult
a
# Multiplies two matrices
#
# a - The left matrix in the operation
# b - The right matrix in the operation
#
# Example:
# multiply [[1, 3], [1, 0]], [[7, 5], [2, 1]]
# => [[13, 8], [7, 5]]
#
# Returns the resulting matrix or null if the operation
# is undefined
multiply=(a, b) ->
if a[0].length==b.length
c=[]
for i of a
c[i]=[]
for j of b[i]
c[i][j]=0
for k of b
c[i][j]+=a[i][k]*b[k][j]
c
else
null
# Calculates the trace of a matrix
#
# matrix - The matrix to calculate the trace of
#
# Example:
# trace [[7, 5], [2, 1]]
# => 8
#
# Returns the trace or NaN if the trace is undefined
trace=(matrix) ->
if matrix.length==matrix[0].length
tr=0
for i of matrix
tr+=matrix[i][i]
tr
else
NaN
# Transposes a matrix
#
# matrix - The matrix to transpose
#
# Example:
# transpose [[1, 2]]
# => [[1], [2]]
#
# Returns a transposed copy of the matrix
transpose=(matrix) ->
res=[]
for row of matrix[0]
res[row]=[]
for row of matrix
for col of matrix[row]
res[col][row]=matrix[row][col]
res
# Tests two matrices for strict equality
#
# a - The first matrix
# b - The second matrix
#
# Example:
# equals [[7, 5]], [[7, 5]]
# => true
#
# Returns true if each element in a is equal
# to its counterpart in b
equals=(a, b) ->
if a.length==b.length and a[0].length==b[0].length
for i of a
for j of a[i]
if a[i][j]!=b[i][j]
return false
true
else
false
exports.add=add
exports.multiplyScalar=multiplyScalar
exports.multiply=multiply
exports.trace=trace
exports.transpose=transpose
exports.equals=equals | 25475 | ###
Copyright 2013 <NAME>.
BSD License.
###
# Adds two matrices
#
# a - The left matrix in the addition
# b - The right matrix in the addition
#
# Example:
# add [[1, 3], [1, 0], [1, 2]], [[0, 0], [7, 5], [2, 1]]
# => [[1, 3], [8, 5], [3, 3]]
#
# Returns the resulting matrix or null if the dimensions differ
add=(a, b) ->
if a.length==b.length and a[0].length==b[0].length
c=[]
for i of a
c[i]=[]
for j of a[i]
c[i][j]=a[i][j]+b[i][j]
c
else
null
# Multiplies a matrix by a scalar value
#
# a - The matrix to scale
# mult - The scalar value to multiply by
#
# Example:
# multiplyScalar [[1, 3], [1, 0], [1, 2]], 5
# => [[5, 15], [5, 0], [5, 10]]
#
# Returns the resulting matrix
multiplyScalar=(a, mult) ->
for i of a
for j of a[i]
a[i][j]*=mult
a
# Multiplies two matrices
#
# a - The left matrix in the operation
# b - The right matrix in the operation
#
# Example:
# multiply [[1, 3], [1, 0]], [[7, 5], [2, 1]]
# => [[13, 8], [7, 5]]
#
# Returns the resulting matrix or null if the operation
# is undefined
multiply=(a, b) ->
if a[0].length==b.length
c=[]
for i of a
c[i]=[]
for j of b[i]
c[i][j]=0
for k of b
c[i][j]+=a[i][k]*b[k][j]
c
else
null
# Calculates the trace of a matrix
#
# matrix - The matrix to calculate the trace of
#
# Example:
# trace [[7, 5], [2, 1]]
# => 8
#
# Returns the trace or NaN if the trace is undefined
trace=(matrix) ->
if matrix.length==matrix[0].length
tr=0
for i of matrix
tr+=matrix[i][i]
tr
else
NaN
# Transposes a matrix
#
# matrix - The matrix to transpose
#
# Example:
# transpose [[1, 2]]
# => [[1], [2]]
#
# Returns a transposed copy of the matrix
transpose=(matrix) ->
res=[]
for row of matrix[0]
res[row]=[]
for row of matrix
for col of matrix[row]
res[col][row]=matrix[row][col]
res
# Tests two matrices for strict equality
#
# a - The first matrix
# b - The second matrix
#
# Example:
# equals [[7, 5]], [[7, 5]]
# => true
#
# Returns true if each element in a is equal
# to its counterpart in b
equals=(a, b) ->
if a.length==b.length and a[0].length==b[0].length
for i of a
for j of a[i]
if a[i][j]!=b[i][j]
return false
true
else
false
exports.add=add
exports.multiplyScalar=multiplyScalar
exports.multiply=multiply
exports.trace=trace
exports.transpose=transpose
exports.equals=equals | true | ###
Copyright 2013 PI:NAME:<NAME>END_PI.
BSD License.
###
# Adds two matrices
#
# a - The left matrix in the addition
# b - The right matrix in the addition
#
# Example:
# add [[1, 3], [1, 0], [1, 2]], [[0, 0], [7, 5], [2, 1]]
# => [[1, 3], [8, 5], [3, 3]]
#
# Returns the resulting matrix or null if the dimensions differ
add=(a, b) ->
if a.length==b.length and a[0].length==b[0].length
c=[]
for i of a
c[i]=[]
for j of a[i]
c[i][j]=a[i][j]+b[i][j]
c
else
null
# Multiplies a matrix by a scalar value
#
# a - The matrix to scale
# mult - The scalar value to multiply by
#
# Example:
# multiplyScalar [[1, 3], [1, 0], [1, 2]], 5
# => [[5, 15], [5, 0], [5, 10]]
#
# Returns the resulting matrix
multiplyScalar=(a, mult) ->
for i of a
for j of a[i]
a[i][j]*=mult
a
# Multiplies two matrices
#
# a - The left matrix in the operation
# b - The right matrix in the operation
#
# Example:
# multiply [[1, 3], [1, 0]], [[7, 5], [2, 1]]
# => [[13, 8], [7, 5]]
#
# Returns the resulting matrix or null if the operation
# is undefined
multiply=(a, b) ->
if a[0].length==b.length
c=[]
for i of a
c[i]=[]
for j of b[i]
c[i][j]=0
for k of b
c[i][j]+=a[i][k]*b[k][j]
c
else
null
# Calculates the trace of a matrix
#
# matrix - The matrix to calculate the trace of
#
# Example:
# trace [[7, 5], [2, 1]]
# => 8
#
# Returns the trace or NaN if the trace is undefined
trace=(matrix) ->
if matrix.length==matrix[0].length
tr=0
for i of matrix
tr+=matrix[i][i]
tr
else
NaN
# Transposes a matrix
#
# matrix - The matrix to transpose
#
# Example:
# transpose [[1, 2]]
# => [[1], [2]]
#
# Returns a transposed copy of the matrix
transpose=(matrix) ->
res=[]
for row of matrix[0]
res[row]=[]
for row of matrix
for col of matrix[row]
res[col][row]=matrix[row][col]
res
# Tests two matrices for strict equality
#
# a - The first matrix
# b - The second matrix
#
# Example:
# equals [[7, 5]], [[7, 5]]
# => true
#
# Returns true if each element in a is equal
# to its counterpart in b
equals=(a, b) ->
if a.length==b.length and a[0].length==b[0].length
for i of a
for j of a[i]
if a[i][j]!=b[i][j]
return false
true
else
false
exports.add=add
exports.multiplyScalar=multiplyScalar
exports.multiply=multiply
exports.trace=trace
exports.transpose=transpose
exports.equals=equals |
[
{
"context": "nName_default = orgx\n \n commonName = ioc\n commonName_default = ioc\n \n emailAddre",
"end": 1663,
"score": 0.7469310760498047,
"start": 1662,
"tag": "NAME",
"value": "i"
},
{
"context": "monName = ioc\n commonName_default = ioc\n ... | notes/797d28e7-94d4-4d39-af00-f45f6f6080e1.cson | cwocwo/boostnote | 0 | createdAt: "2018-04-27T11:04:10.707Z"
updatedAt: "2018-09-22T03:28:04.528Z"
type: "MARKDOWN_NOTE"
folder: "66dff0cfbfde06f3d2e8"
title: "kubectl 常用操作"
content: '''
# kubectl 常用操作
kubectl logs jenkins-9f8c8ddf9-96hww -n jenkins -c copy-default-config -f
helm install jenkins/ --name jenkins --tls --namespace jenkins
helm del --purge jenkins --tls
kubectl exec -it jenkins-5cdf68f4fd-nv524 -n jenkins -- /bin/bash
## 强制删除pod
kubectl delete pod devops-app-web-test-deploy-rswfd-6bd49cf8b8-n8svf -n ioc-test --grace-period=0 --force
kubectl get pods --namespace foo -l status=pending
kubectl get pod -o jsonpath='{range .items[*]}{.metadata.name} {" "}{end}' -n ioc
kubectl get pod -o jsonpath='kubectl delete pod {range .items[*]}{.metadata.name} {" "}{end}' -l app=app-web
jenkins=slave
## ingress 重定向
annotations:
ingress.kubernetes.io/rewrite-target: /
## 生成tls证书:
mkdir app-cert
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout app-cert/tls.key -out app-cert/tls.crt -subj "/CN=app.ioc.com"
### 生成多DNS证书
创建文件 openssl.conf
```
[ req ]
default_bits = 2048
default_keyfile = server-key.pem
distinguished_name = subject
req_extensions = extensions
x509_extensions = extensions
string_mask = utf8only
[ subject ]
countryName = CN
countryName_default = CN
stateOrProvinceName = Shandong
stateOrProvinceName_default = SD
localityName = Beijing
localityName_default = Beijing
organizationName = orgx
organizationName_default = orgx
commonName = ioc
commonName_default = ioc
emailAddress = ioc@orgx.com
emailAddress_default = ioc@orgx.com
[ extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alternate_names
nsComment = "OpenSSL Generated Certificate"
[ alternate_names ]
DNS.1 = ioc.site
DNS.2 = www.ioc.site
```
执行命令:
```
openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem
```
### 创建k8s tls secret
```
kubectl create secret tls app-web-tls-cert --key app-cert/tls.key --cert app-cert/tls.crt -n ioc
```
## 使用externalIPs访问外部服务
service的targetPort对应Endpoints的port
### Endpoints
```
kind: Endpoints
apiVersion: v1
metadata:
name: keycloak-external
subsets:
- addresses:
- ip: 10.17.1.160
ports:
- port: 8888
```
### Service
```
apiVersion: v1
kind: Service
metadata:
name: keycloak-external
spec:
ports:
- port: 30888
targetPort: 8888
externalIPs:
- 10.17.1.160
```
### docker操作
docker save -o app-web.tar app-web:0.1
docker load < app-web.tar
docker tag app-web:0.1 registry.iot.com:5000/ioc/app-web:0.1
docker push registry.iot.com:5000/ioc/app-web:0.1
#### 镜像仓库配置
vi /usr/lib/systemd/system/docker.service.d/docker-options.conf
vi /etc/systemd/system/docker.service.d/docker-options.conf
添加
--insecure-registry=registry.domain.com:5000
--insecure-registry=registry.domain.cn
执行
systemctl daemon-reload
systemctl restart docker
echo '10.110.25.73 registry.icp.com' >> /etc/hosts
docker login registry.icp.com:5000 -u admin -p 123456a?
#### docker 代理配置
给Centos7加上网络代理后发现Docker依然无法联网查找原因才知道Docker需要额外配置代理,步骤如下:
1 创建目录
mkdir /etc/systemd/system/docker.service.d
2 创建配置文件
touch /etc/systemd/system/docker.service.d/http-proxy.conf
3 编辑文件并加入以下内容
vim/vi http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://ip:port"
4 更新重加载配置&重启Docker服务
systemctl daemon-reload
systemctl restart docker
## openssl查看证书信息
```
openssl x509 -in cert.pem -noout -text
```
## 查看kubelet日志
sudo journalctl _UID=1000 --since today
journalctl -e kubelet --since "1 min ago"
'''
tags: []
isStarred: false
isTrashed: false
| 92185 | createdAt: "2018-04-27T11:04:10.707Z"
updatedAt: "2018-09-22T03:28:04.528Z"
type: "MARKDOWN_NOTE"
folder: "66dff0cfbfde06f3d2e8"
title: "kubectl 常用操作"
content: '''
# kubectl 常用操作
kubectl logs jenkins-9f8c8ddf9-96hww -n jenkins -c copy-default-config -f
helm install jenkins/ --name jenkins --tls --namespace jenkins
helm del --purge jenkins --tls
kubectl exec -it jenkins-5cdf68f4fd-nv524 -n jenkins -- /bin/bash
## 强制删除pod
kubectl delete pod devops-app-web-test-deploy-rswfd-6bd49cf8b8-n8svf -n ioc-test --grace-period=0 --force
kubectl get pods --namespace foo -l status=pending
kubectl get pod -o jsonpath='{range .items[*]}{.metadata.name} {" "}{end}' -n ioc
kubectl get pod -o jsonpath='kubectl delete pod {range .items[*]}{.metadata.name} {" "}{end}' -l app=app-web
jenkins=slave
## ingress 重定向
annotations:
ingress.kubernetes.io/rewrite-target: /
## 生成tls证书:
mkdir app-cert
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout app-cert/tls.key -out app-cert/tls.crt -subj "/CN=app.ioc.com"
### 生成多DNS证书
创建文件 openssl.conf
```
[ req ]
default_bits = 2048
default_keyfile = server-key.pem
distinguished_name = subject
req_extensions = extensions
x509_extensions = extensions
string_mask = utf8only
[ subject ]
countryName = CN
countryName_default = CN
stateOrProvinceName = Shandong
stateOrProvinceName_default = SD
localityName = Beijing
localityName_default = Beijing
organizationName = orgx
organizationName_default = orgx
commonName = <NAME>oc
commonName_default = <NAME>oc
emailAddress = <EMAIL>
emailAddress_default = <EMAIL>
[ extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alternate_names
nsComment = "OpenSSL Generated Certificate"
[ alternate_names ]
DNS.1 = ioc.site
DNS.2 = www.ioc.site
```
执行命令:
```
openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem
```
### 创建k8s tls secret
```
kubectl create secret tls app-web-tls-cert --key app-cert/tls.key --cert app-cert/tls.crt -n ioc
```
## 使用externalIPs访问外部服务
service的targetPort对应Endpoints的port
### Endpoints
```
kind: Endpoints
apiVersion: v1
metadata:
name: keycloak-external
subsets:
- addresses:
- ip: 10.17.1.160
ports:
- port: 8888
```
### Service
```
apiVersion: v1
kind: Service
metadata:
name: keycloak-external
spec:
ports:
- port: 30888
targetPort: 8888
externalIPs:
- 10.17.1.160
```
### docker操作
docker save -o app-web.tar app-web:0.1
docker load < app-web.tar
docker tag app-web:0.1 registry.iot.com:5000/ioc/app-web:0.1
docker push registry.iot.com:5000/ioc/app-web:0.1
#### 镜像仓库配置
vi /usr/lib/systemd/system/docker.service.d/docker-options.conf
vi /etc/systemd/system/docker.service.d/docker-options.conf
添加
--insecure-registry=registry.domain.com:5000
--insecure-registry=registry.domain.cn
执行
systemctl daemon-reload
systemctl restart docker
echo '10.110.25.73 registry.icp.com' >> /etc/hosts
docker login registry.icp.com:5000 -u admin -p 123456a?
#### docker 代理配置
给Centos7加上网络代理后发现Docker依然无法联网查找原因才知道Docker需要额外配置代理,步骤如下:
1 创建目录
mkdir /etc/systemd/system/docker.service.d
2 创建配置文件
touch /etc/systemd/system/docker.service.d/http-proxy.conf
3 编辑文件并加入以下内容
vim/vi http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://ip:port"
4 更新重加载配置&重启Docker服务
systemctl daemon-reload
systemctl restart docker
## openssl查看证书信息
```
openssl x509 -in cert.pem -noout -text
```
## 查看kubelet日志
sudo journalctl _UID=1000 --since today
journalctl -e kubelet --since "1 min ago"
'''
tags: []
isStarred: false
isTrashed: false
| true | createdAt: "2018-04-27T11:04:10.707Z"
updatedAt: "2018-09-22T03:28:04.528Z"
type: "MARKDOWN_NOTE"
folder: "66dff0cfbfde06f3d2e8"
title: "kubectl 常用操作"
content: '''
# kubectl 常用操作
kubectl logs jenkins-9f8c8ddf9-96hww -n jenkins -c copy-default-config -f
helm install jenkins/ --name jenkins --tls --namespace jenkins
helm del --purge jenkins --tls
kubectl exec -it jenkins-5cdf68f4fd-nv524 -n jenkins -- /bin/bash
## 强制删除pod
kubectl delete pod devops-app-web-test-deploy-rswfd-6bd49cf8b8-n8svf -n ioc-test --grace-period=0 --force
kubectl get pods --namespace foo -l status=pending
kubectl get pod -o jsonpath='{range .items[*]}{.metadata.name} {" "}{end}' -n ioc
kubectl get pod -o jsonpath='kubectl delete pod {range .items[*]}{.metadata.name} {" "}{end}' -l app=app-web
jenkins=slave
## ingress 重定向
annotations:
ingress.kubernetes.io/rewrite-target: /
## 生成tls证书:
mkdir app-cert
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout app-cert/tls.key -out app-cert/tls.crt -subj "/CN=app.ioc.com"
### 生成多DNS证书
创建文件 openssl.conf
```
[ req ]
default_bits = 2048
default_keyfile = server-key.pem
distinguished_name = subject
req_extensions = extensions
x509_extensions = extensions
string_mask = utf8only
[ subject ]
countryName = CN
countryName_default = CN
stateOrProvinceName = Shandong
stateOrProvinceName_default = SD
localityName = Beijing
localityName_default = Beijing
organizationName = orgx
organizationName_default = orgx
commonName = PI:NAME:<NAME>END_PIoc
commonName_default = PI:NAME:<NAME>END_PIoc
emailAddress = PI:EMAIL:<EMAIL>END_PI
emailAddress_default = PI:EMAIL:<EMAIL>END_PI
[ extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alternate_names
nsComment = "OpenSSL Generated Certificate"
[ alternate_names ]
DNS.1 = ioc.site
DNS.2 = www.ioc.site
```
执行命令:
```
openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem
```
### 创建k8s tls secret
```
kubectl create secret tls app-web-tls-cert --key app-cert/tls.key --cert app-cert/tls.crt -n ioc
```
## 使用externalIPs访问外部服务
service的targetPort对应Endpoints的port
### Endpoints
```
kind: Endpoints
apiVersion: v1
metadata:
name: keycloak-external
subsets:
- addresses:
- ip: 10.17.1.160
ports:
- port: 8888
```
### Service
```
apiVersion: v1
kind: Service
metadata:
name: keycloak-external
spec:
ports:
- port: 30888
targetPort: 8888
externalIPs:
- 10.17.1.160
```
### docker操作
docker save -o app-web.tar app-web:0.1
docker load < app-web.tar
docker tag app-web:0.1 registry.iot.com:5000/ioc/app-web:0.1
docker push registry.iot.com:5000/ioc/app-web:0.1
#### 镜像仓库配置
vi /usr/lib/systemd/system/docker.service.d/docker-options.conf
vi /etc/systemd/system/docker.service.d/docker-options.conf
添加
--insecure-registry=registry.domain.com:5000
--insecure-registry=registry.domain.cn
执行
systemctl daemon-reload
systemctl restart docker
echo '10.110.25.73 registry.icp.com' >> /etc/hosts
docker login registry.icp.com:5000 -u admin -p 123456a?
#### docker 代理配置
给Centos7加上网络代理后发现Docker依然无法联网查找原因才知道Docker需要额外配置代理,步骤如下:
1 创建目录
mkdir /etc/systemd/system/docker.service.d
2 创建配置文件
touch /etc/systemd/system/docker.service.d/http-proxy.conf
3 编辑文件并加入以下内容
vim/vi http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://ip:port"
4 更新重加载配置&重启Docker服务
systemctl daemon-reload
systemctl restart docker
## openssl查看证书信息
```
openssl x509 -in cert.pem -noout -text
```
## 查看kubelet日志
sudo journalctl _UID=1000 --since today
journalctl -e kubelet --since "1 min ago"
'''
tags: []
isStarred: false
isTrashed: false
|
[
{
"context": " '1'\n 'gpgkey': 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7'\n , (err, {status}) ->\n statu",
"end": 6110,
"score": 0.5710289478302002,
"start": 6102,
"tag": "KEY",
"value": "RPM-GPG-"
},
{
"context": " 'gpgkey': 'file:///etc/pki/rpm-gpg/RPM-GPG-K... | packages/core/test/file.ini/index.coffee | chibanemourad/node-nikita | 0 |
nikita = require '../../src'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'file.ini', ->
they 'stringify an object', ({ssh}) ->
nikita
ssh: ssh
.file.ini
content: user: preference: color: 'rouge'
target: "#{scratch}/user.ini"
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
content: user: preference: color: 'rouge'
target: "#{scratch}/user.ini"
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\ncolor = rouge\n'
.promise()
they 'merge an object', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: 'violet'
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = violet\n'
.promise()
they 'discard undefined and null', ({ssh}) ->
nikita
ssh: ssh
.file.ini
content: user: preference: color: 'violet', age: undefined, gender: null
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\ncolor = violet\n'
.promise()
they 'remove null within merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: null
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'disregard undefined within merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: undefined
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.false() unless err
.promise()
they 'use default source file', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: false
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'options source file + content', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: remember: 'me'
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\nremember = me\n'
.promise()
they 'options missing source file + content', ({ssh}) ->
nikita
ssh: ssh
.file.ini
source: "#{scratch}/does_not_exist.ini"
target: "#{scratch}/test.ini"
content: user: preference: remember: 'me'
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nremember = me\n'
.promise()
they 'options source file + merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = c++\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: true
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'use default source file with merge and content', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = java\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: language: 'c++'
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = c++\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: language: 'c++'
merge: true
, (err, status) ->
{status}.sh
.promise()
they 'generate from content object with escape', ({ssh}) ->
nikita
ssh: ssh
.file.ini
target: "#{scratch}/test.ini"
escape: false
content:
"test-repo-0.0.1":
'name': 'CentOS-$releasever - Base'
'mirrorlist': 'http://test/?infra=$infra'
'baseurl': 'http://mirror.centos.org/centos/$releasever/os/$basearch/'
'gpgcheck': '1'
'gpgkey': 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7'
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
target: "#{scratch}/test.ini"
escape: false
content:
"test-repo-0.0.1":
'name': 'CentOS-$releasever - Base'
'mirrorlist': 'http://test/?infra=$infra'
'baseurl': 'http://mirror.centos.org/centos/$releasever/os/$basearch/'
'gpgcheck': '1'
'gpgkey': 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7'
, (err, {status}) ->
status.should.be.false() unless err
.promise()
| 177816 |
nikita = require '../../src'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'file.ini', ->
they 'stringify an object', ({ssh}) ->
nikita
ssh: ssh
.file.ini
content: user: preference: color: 'rouge'
target: "#{scratch}/user.ini"
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
content: user: preference: color: 'rouge'
target: "#{scratch}/user.ini"
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\ncolor = rouge\n'
.promise()
they 'merge an object', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: 'violet'
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = violet\n'
.promise()
they 'discard undefined and null', ({ssh}) ->
nikita
ssh: ssh
.file.ini
content: user: preference: color: 'violet', age: undefined, gender: null
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\ncolor = violet\n'
.promise()
they 'remove null within merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: null
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'disregard undefined within merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: undefined
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.false() unless err
.promise()
they 'use default source file', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: false
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'options source file + content', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: remember: 'me'
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\nremember = me\n'
.promise()
they 'options missing source file + content', ({ssh}) ->
nikita
ssh: ssh
.file.ini
source: "#{scratch}/does_not_exist.ini"
target: "#{scratch}/test.ini"
content: user: preference: remember: 'me'
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nremember = me\n'
.promise()
they 'options source file + merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = c++\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: true
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'use default source file with merge and content', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = java\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: language: 'c++'
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = c++\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: language: 'c++'
merge: true
, (err, status) ->
{status}.sh
.promise()
they 'generate from content object with escape', ({ssh}) ->
nikita
ssh: ssh
.file.ini
target: "#{scratch}/test.ini"
escape: false
content:
"test-repo-0.0.1":
'name': 'CentOS-$releasever - Base'
'mirrorlist': 'http://test/?infra=$infra'
'baseurl': 'http://mirror.centos.org/centos/$releasever/os/$basearch/'
'gpgcheck': '1'
'gpgkey': 'file:///etc/pki/rpm-gpg/<KEY>KEY-<KEY>'
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
target: "#{scratch}/test.ini"
escape: false
content:
"test-repo-0.0.1":
'name': 'CentOS-$releasever - Base'
'mirrorlist': 'http://test/?infra=$infra'
'baseurl': 'http://mirror.centos.org/centos/$releasever/os/$basearch/'
'gpgcheck': '1'
'gpgkey': 'file:///etc/pki/rpm-gpg/<KEY>KEY-<KEY>'
, (err, {status}) ->
status.should.be.false() unless err
.promise()
| true |
nikita = require '../../src'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'file.ini', ->
they 'stringify an object', ({ssh}) ->
nikita
ssh: ssh
.file.ini
content: user: preference: color: 'rouge'
target: "#{scratch}/user.ini"
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
content: user: preference: color: 'rouge'
target: "#{scratch}/user.ini"
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\ncolor = rouge\n'
.promise()
they 'merge an object', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: 'violet'
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = violet\n'
.promise()
they 'discard undefined and null', ({ssh}) ->
nikita
ssh: ssh
.file.ini
content: user: preference: color: 'violet', age: undefined, gender: null
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\ncolor = violet\n'
.promise()
they 'remove null within merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: null
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'disregard undefined within merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\ncolor = rouge\n'
.file.ini
content: user: preference: color: undefined
target: "#{scratch}/user.ini"
merge: true
, (err, {status}) ->
status.should.be.false() unless err
.promise()
they 'use default source file', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: false
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'options source file + content', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: remember: 'me'
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\nremember = me\n'
.promise()
they 'options missing source file + content', ({ssh}) ->
nikita
ssh: ssh
.file.ini
source: "#{scratch}/does_not_exist.ini"
target: "#{scratch}/test.ini"
content: user: preference: remember: 'me'
merge: false
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nremember = me\n'
.promise()
they 'options source file + merge', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = c++\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
merge: true
, (err, {status}) ->
status.should.be.false() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = node\n'
.promise()
they 'use default source file with merge and content', ({ssh}) ->
nikita
ssh: ssh
.file
target: "#{scratch}/user.ini"
content: '[user.preference]\nlanguage = node\n'
.file
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = java\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: language: 'c++'
merge: true
, (err, {status}) ->
status.should.be.true() unless err
.file.assert
target: "#{scratch}/test.ini"
content: '[user.preference]\nlanguage = c++\n'
.file.ini
source: "#{scratch}/user.ini"
target: "#{scratch}/test.ini"
content: user: preference: language: 'c++'
merge: true
, (err, status) ->
{status}.sh
.promise()
they 'generate from content object with escape', ({ssh}) ->
nikita
ssh: ssh
.file.ini
target: "#{scratch}/test.ini"
escape: false
content:
"test-repo-0.0.1":
'name': 'CentOS-$releasever - Base'
'mirrorlist': 'http://test/?infra=$infra'
'baseurl': 'http://mirror.centos.org/centos/$releasever/os/$basearch/'
'gpgcheck': '1'
'gpgkey': 'file:///etc/pki/rpm-gpg/PI:KEY:<KEY>END_PIKEY-PI:KEY:<KEY>END_PI'
, (err, {status}) ->
status.should.be.true() unless err
.file.ini
target: "#{scratch}/test.ini"
escape: false
content:
"test-repo-0.0.1":
'name': 'CentOS-$releasever - Base'
'mirrorlist': 'http://test/?infra=$infra'
'baseurl': 'http://mirror.centos.org/centos/$releasever/os/$basearch/'
'gpgcheck': '1'
'gpgkey': 'file:///etc/pki/rpm-gpg/PI:KEY:<KEY>END_PIKEY-PI:KEY:<KEY>END_PI'
, (err, {status}) ->
status.should.be.false() unless err
.promise()
|
[
{
"context": "ed = ->\n log \"acceptKeyButtonClicked\"\n key = utl.strip0x(importKeyInput.value)\n return unless utl.isVal",
"end": 4894,
"score": 0.9672266840934753,
"start": 4883,
"tag": "KEY",
"value": "utl.strip0x"
},
{
"context": "dregion\n\nmodule.exports = accountsett... | accountsettingsmodule.coffee | JhonnyJason/pwa-sources-accountsettingsmodule | 0 | accountsettingsmodule = {name: "accountsettingsmodule"}
############################################################
#region printLogFunctions
log = (arg) ->
if allModules.debugmodule.modulesToDebug["accountsettingsmodule"]? then console.log "[accountsettingsmodule]: " + arg
return
ostr = (obj) -> JSON.stringify(obj, null, 4)
olog = (obj) -> log "\n" + ostr(obj)
print = (arg) -> console.log(arg)
#endregion
############################################################
#region modulesFromEnvironment
secretManagerClientFactory = require("secret-manager-client")
############################################################
utl = null
state = null
qrDisplay = null
qrReader = null
#endregion
############################################################
idContent = null
currentClient = null
############################################################
accountsettingsmodule.initialize = ->
log "accountsettingsmodule.initialize"
utl = allModules.utilmodule
state = allModules.statemodule
qrDisplay = allModules.qrdisplaymodule
qrReader = allModules.qrreadermodule
idContent = idDisplay.getElementsByClassName("display-frame-content")[0]
idDisplay.addEventListener("click", idDisplayClicked)
idQrButton.addEventListener("click", idQrButtonClicked)
addKeyButton.addEventListener("click", addKeyButtonClicked)
deleteKeyButton.addEventListener("click", deleteKeyButtonClicked)
importKeyInput.addEventListener("change", importKeyInputChanged)
acceptKeyButton.addEventListener("click", acceptKeyButtonClicked)
qrScanImport.addEventListener("click", qrScanImportClicked)
floatingImport.addEventListener("click", floatingImportClicked)
signatureImport.addEventListener("click", signatureImportClicked)
copyExport.addEventListener("click", copyExportClicked)
qrExport.addEventListener("click", qrExportClicked)
floatingExport.addEventListener("click", floatingExportClicked)
signatureExport.addEventListener("click", signatureExportClicked)
syncIdFromState()
state.addOnChangeListener("publicKeyHex", syncIdFromState)
state.addOnChangeListener("secretManagerURL", onServerURLChanged)
await createCurrentClient()
return
############################################################
#region internalFunctions
createCurrentClient = ->
log "createCurrentClient"
try
key = utl.strip0x(state.load("secretKeyHex"))
id = utl.strip0x(state.load("publicKeyHex"))
serverURL = state.get("secretManagerURL")
if utl.isValidKey(key) and utl.isValidKey(id) then currentClient = await secretManagerClientFactory.createClient(key, id, serverURL)
catch err then log err
return
############################################################
onServerURLChanged = ->
log "onServerURLChanged"
serverURL = state.get("secretManagerURL")
secretManagerClient.updateServerURL(serverURL)
return
############################################################
syncIdFromState = ->
log "syncIdFromState"
idHex = state.load("publicKeyHex")
log "idHex is "+idHex
if utl.isValidKey(idHex)
displayId(idHex)
accountsettings.classList.remove("no-key")
else
displayId("")
accountsettings.classList.add("no-key")
return
############################################################
displayId = (idHex) ->
log "displayId"
idContent.textContent = utl.add0x(idHex)
return
############################################################
#region eventListeners
idDisplayClicked = ->
log "idDisplayClicked"
utl.copyToClipboard(idContent.textContent)
return
idQrButtonClicked = ->
log "idDisplayClicked"
qrDisplay.displayCode(idContent.textContent)
return
############################################################
addKeyButtonClicked = ->
log "addKeyButtonClicked"
try
serverURL = state.load("secretManagerURL")
currentClient = await secretManagerClientFactory.createClient(null, null, serverURL)
state.save("secretKeyHex", currentClient.secretKeyHex)
state.save("publicKeyHex", currentClient.publicKeyHex)
state.save("accountId", currentClient.publicKeyHex)
catch err
log err
return
deleteKeyButtonClicked = ->
log "deleteKeyButtonClicked"
currentClient = null
state.save("publicKeyHex", "")
state.save("secretKeyHex", "")
state.save("accountId", "")
return
############################################################
importKeyInputChanged = ->
log "importKeyInputChanged"
validKey = utl.isValidKey(importKeyInput.value)
log "input is valid key: "+validKey
if validKey then accountsettings.classList.add("importing")
else accountsettings.classList.remove("importing")
return
acceptKeyButtonClicked = ->
log "acceptKeyButtonClicked"
key = utl.strip0x(importKeyInput.value)
return unless utl.isValidKey(key)
serverURL = state.load("secretManagerURL")
currentClient = await secretManagerClientFactory.createClient(key, null, serverURL)
state.save("secretKeyHex", currentClient.secretKeyHex)
state.save("publicKeyHex", currentClient.publicKeyHex)
state.save("accountId", currentClient.publicKeyHex)
importKeyInput.value = ""
importKeyInputChanged()
return
############################################################
qrScanImportClicked = ->
log "qrScanImportClicked"
try
key = await qrReader.read()
importKeyInput.value = key
importKeyInputChanged()
catch err then log err
return
floatingImportClicked = ->
log "floatingImportClicked"
##TODO implement
return
signatureImportClicked = ->
log "signatureImportClicked"
##TODO implement
return
############################################################
copyExportClicked = ->
log "copyExportClicked"
key = state.get("secretKeyHex")
utl.copyToClipboard(key)
return
qrExportClicked = ->
log "qrExportClicked"
key = state.get("secretKeyHex")
qrDisplay.displayCode(key)
return
floatingExportClicked = ->
log "floatingExportClicked"
return
signatureExportClicked = ->
log "signatureExportClicked"
return
#endregion
#endregion
############################################################
#region exposedFunctions
accountsettingsmodule.getClient = -> currentClient
#endregion
module.exports = accountsettingsmodule
#92e102b2b2ef0d5b498fae3d7a9bbc94fc6ddc9544159b3803a6f4d239d76d62 | 15905 | accountsettingsmodule = {name: "accountsettingsmodule"}
############################################################
#region printLogFunctions
log = (arg) ->
if allModules.debugmodule.modulesToDebug["accountsettingsmodule"]? then console.log "[accountsettingsmodule]: " + arg
return
ostr = (obj) -> JSON.stringify(obj, null, 4)
olog = (obj) -> log "\n" + ostr(obj)
print = (arg) -> console.log(arg)
#endregion
############################################################
#region modulesFromEnvironment
secretManagerClientFactory = require("secret-manager-client")
############################################################
utl = null
state = null
qrDisplay = null
qrReader = null
#endregion
############################################################
idContent = null
currentClient = null
############################################################
accountsettingsmodule.initialize = ->
log "accountsettingsmodule.initialize"
utl = allModules.utilmodule
state = allModules.statemodule
qrDisplay = allModules.qrdisplaymodule
qrReader = allModules.qrreadermodule
idContent = idDisplay.getElementsByClassName("display-frame-content")[0]
idDisplay.addEventListener("click", idDisplayClicked)
idQrButton.addEventListener("click", idQrButtonClicked)
addKeyButton.addEventListener("click", addKeyButtonClicked)
deleteKeyButton.addEventListener("click", deleteKeyButtonClicked)
importKeyInput.addEventListener("change", importKeyInputChanged)
acceptKeyButton.addEventListener("click", acceptKeyButtonClicked)
qrScanImport.addEventListener("click", qrScanImportClicked)
floatingImport.addEventListener("click", floatingImportClicked)
signatureImport.addEventListener("click", signatureImportClicked)
copyExport.addEventListener("click", copyExportClicked)
qrExport.addEventListener("click", qrExportClicked)
floatingExport.addEventListener("click", floatingExportClicked)
signatureExport.addEventListener("click", signatureExportClicked)
syncIdFromState()
state.addOnChangeListener("publicKeyHex", syncIdFromState)
state.addOnChangeListener("secretManagerURL", onServerURLChanged)
await createCurrentClient()
return
############################################################
#region internalFunctions
createCurrentClient = ->
log "createCurrentClient"
try
key = utl.strip0x(state.load("secretKeyHex"))
id = utl.strip0x(state.load("publicKeyHex"))
serverURL = state.get("secretManagerURL")
if utl.isValidKey(key) and utl.isValidKey(id) then currentClient = await secretManagerClientFactory.createClient(key, id, serverURL)
catch err then log err
return
############################################################
onServerURLChanged = ->
log "onServerURLChanged"
serverURL = state.get("secretManagerURL")
secretManagerClient.updateServerURL(serverURL)
return
############################################################
syncIdFromState = ->
log "syncIdFromState"
idHex = state.load("publicKeyHex")
log "idHex is "+idHex
if utl.isValidKey(idHex)
displayId(idHex)
accountsettings.classList.remove("no-key")
else
displayId("")
accountsettings.classList.add("no-key")
return
############################################################
displayId = (idHex) ->
log "displayId"
idContent.textContent = utl.add0x(idHex)
return
############################################################
#region eventListeners
idDisplayClicked = ->
log "idDisplayClicked"
utl.copyToClipboard(idContent.textContent)
return
idQrButtonClicked = ->
log "idDisplayClicked"
qrDisplay.displayCode(idContent.textContent)
return
############################################################
addKeyButtonClicked = ->
log "addKeyButtonClicked"
try
serverURL = state.load("secretManagerURL")
currentClient = await secretManagerClientFactory.createClient(null, null, serverURL)
state.save("secretKeyHex", currentClient.secretKeyHex)
state.save("publicKeyHex", currentClient.publicKeyHex)
state.save("accountId", currentClient.publicKeyHex)
catch err
log err
return
deleteKeyButtonClicked = ->
log "deleteKeyButtonClicked"
currentClient = null
state.save("publicKeyHex", "")
state.save("secretKeyHex", "")
state.save("accountId", "")
return
############################################################
importKeyInputChanged = ->
log "importKeyInputChanged"
validKey = utl.isValidKey(importKeyInput.value)
log "input is valid key: "+validKey
if validKey then accountsettings.classList.add("importing")
else accountsettings.classList.remove("importing")
return
acceptKeyButtonClicked = ->
log "acceptKeyButtonClicked"
key = <KEY>(importKeyInput.value)
return unless utl.isValidKey(key)
serverURL = state.load("secretManagerURL")
currentClient = await secretManagerClientFactory.createClient(key, null, serverURL)
state.save("secretKeyHex", currentClient.secretKeyHex)
state.save("publicKeyHex", currentClient.publicKeyHex)
state.save("accountId", currentClient.publicKeyHex)
importKeyInput.value = ""
importKeyInputChanged()
return
############################################################
qrScanImportClicked = ->
log "qrScanImportClicked"
try
key = await qrReader.read()
importKeyInput.value = key
importKeyInputChanged()
catch err then log err
return
floatingImportClicked = ->
log "floatingImportClicked"
##TODO implement
return
signatureImportClicked = ->
log "signatureImportClicked"
##TODO implement
return
############################################################
copyExportClicked = ->
log "copyExportClicked"
key = state.get("secretKeyHex")
utl.copyToClipboard(key)
return
qrExportClicked = ->
log "qrExportClicked"
key = state.get("secretKeyHex")
qrDisplay.displayCode(key)
return
floatingExportClicked = ->
log "floatingExportClicked"
return
signatureExportClicked = ->
log "signatureExportClicked"
return
#endregion
#endregion
############################################################
#region exposedFunctions
accountsettingsmodule.getClient = -> currentClient
#endregion
module.exports = accountsettingsmodule
#<KEY> | true | accountsettingsmodule = {name: "accountsettingsmodule"}
############################################################
#region printLogFunctions
log = (arg) ->
if allModules.debugmodule.modulesToDebug["accountsettingsmodule"]? then console.log "[accountsettingsmodule]: " + arg
return
ostr = (obj) -> JSON.stringify(obj, null, 4)
olog = (obj) -> log "\n" + ostr(obj)
print = (arg) -> console.log(arg)
#endregion
############################################################
#region modulesFromEnvironment
secretManagerClientFactory = require("secret-manager-client")
############################################################
utl = null
state = null
qrDisplay = null
qrReader = null
#endregion
############################################################
idContent = null
currentClient = null
############################################################
accountsettingsmodule.initialize = ->
log "accountsettingsmodule.initialize"
utl = allModules.utilmodule
state = allModules.statemodule
qrDisplay = allModules.qrdisplaymodule
qrReader = allModules.qrreadermodule
idContent = idDisplay.getElementsByClassName("display-frame-content")[0]
idDisplay.addEventListener("click", idDisplayClicked)
idQrButton.addEventListener("click", idQrButtonClicked)
addKeyButton.addEventListener("click", addKeyButtonClicked)
deleteKeyButton.addEventListener("click", deleteKeyButtonClicked)
importKeyInput.addEventListener("change", importKeyInputChanged)
acceptKeyButton.addEventListener("click", acceptKeyButtonClicked)
qrScanImport.addEventListener("click", qrScanImportClicked)
floatingImport.addEventListener("click", floatingImportClicked)
signatureImport.addEventListener("click", signatureImportClicked)
copyExport.addEventListener("click", copyExportClicked)
qrExport.addEventListener("click", qrExportClicked)
floatingExport.addEventListener("click", floatingExportClicked)
signatureExport.addEventListener("click", signatureExportClicked)
syncIdFromState()
state.addOnChangeListener("publicKeyHex", syncIdFromState)
state.addOnChangeListener("secretManagerURL", onServerURLChanged)
await createCurrentClient()
return
############################################################
#region internalFunctions
createCurrentClient = ->
log "createCurrentClient"
try
key = utl.strip0x(state.load("secretKeyHex"))
id = utl.strip0x(state.load("publicKeyHex"))
serverURL = state.get("secretManagerURL")
if utl.isValidKey(key) and utl.isValidKey(id) then currentClient = await secretManagerClientFactory.createClient(key, id, serverURL)
catch err then log err
return
############################################################
onServerURLChanged = ->
log "onServerURLChanged"
serverURL = state.get("secretManagerURL")
secretManagerClient.updateServerURL(serverURL)
return
############################################################
syncIdFromState = ->
log "syncIdFromState"
idHex = state.load("publicKeyHex")
log "idHex is "+idHex
if utl.isValidKey(idHex)
displayId(idHex)
accountsettings.classList.remove("no-key")
else
displayId("")
accountsettings.classList.add("no-key")
return
############################################################
displayId = (idHex) ->
log "displayId"
idContent.textContent = utl.add0x(idHex)
return
############################################################
#region eventListeners
idDisplayClicked = ->
log "idDisplayClicked"
utl.copyToClipboard(idContent.textContent)
return
idQrButtonClicked = ->
log "idDisplayClicked"
qrDisplay.displayCode(idContent.textContent)
return
############################################################
addKeyButtonClicked = ->
log "addKeyButtonClicked"
try
serverURL = state.load("secretManagerURL")
currentClient = await secretManagerClientFactory.createClient(null, null, serverURL)
state.save("secretKeyHex", currentClient.secretKeyHex)
state.save("publicKeyHex", currentClient.publicKeyHex)
state.save("accountId", currentClient.publicKeyHex)
catch err
log err
return
deleteKeyButtonClicked = ->
log "deleteKeyButtonClicked"
currentClient = null
state.save("publicKeyHex", "")
state.save("secretKeyHex", "")
state.save("accountId", "")
return
############################################################
importKeyInputChanged = ->
log "importKeyInputChanged"
validKey = utl.isValidKey(importKeyInput.value)
log "input is valid key: "+validKey
if validKey then accountsettings.classList.add("importing")
else accountsettings.classList.remove("importing")
return
acceptKeyButtonClicked = ->
log "acceptKeyButtonClicked"
key = PI:KEY:<KEY>END_PI(importKeyInput.value)
return unless utl.isValidKey(key)
serverURL = state.load("secretManagerURL")
currentClient = await secretManagerClientFactory.createClient(key, null, serverURL)
state.save("secretKeyHex", currentClient.secretKeyHex)
state.save("publicKeyHex", currentClient.publicKeyHex)
state.save("accountId", currentClient.publicKeyHex)
importKeyInput.value = ""
importKeyInputChanged()
return
############################################################
qrScanImportClicked = ->
log "qrScanImportClicked"
try
key = await qrReader.read()
importKeyInput.value = key
importKeyInputChanged()
catch err then log err
return
floatingImportClicked = ->
log "floatingImportClicked"
##TODO implement
return
signatureImportClicked = ->
log "signatureImportClicked"
##TODO implement
return
############################################################
copyExportClicked = ->
log "copyExportClicked"
key = state.get("secretKeyHex")
utl.copyToClipboard(key)
return
qrExportClicked = ->
log "qrExportClicked"
key = state.get("secretKeyHex")
qrDisplay.displayCode(key)
return
floatingExportClicked = ->
log "floatingExportClicked"
return
signatureExportClicked = ->
log "signatureExportClicked"
return
#endregion
#endregion
############################################################
#region exposedFunctions
accountsettingsmodule.getClient = -> currentClient
#endregion
module.exports = accountsettingsmodule
#PI:KEY:<KEY>END_PI |
[
{
"context": "\tmeta: {\n\t\t# \t\t\tusers: [\"user_id\", { first_name: \"James\", ... }, ...]\n\t\t# \t\t\t...\n\t\t# \t\t}\n\t\t# \t}, ...]\n\t\t#",
"end": 1497,
"score": 0.9997971057891846,
"start": 1492,
"tag": "NAME",
"value": "James"
},
{
"context": "\tmeta: {\n\t\t# \t\t\tuser... | app/coffee/Features/History/HistoryManager.coffee | shyoshyo/web-sharelatex | 1 | request = require "request"
settings = require "settings-sharelatex"
async = require 'async'
UserGetter = require "../User/UserGetter"
module.exports = HistoryManager =
initializeProject: (callback = (error, history_id) ->) ->
return callback() if !settings.apis.project_history?.initializeHistoryForNewProjects
request.post {
url: "#{settings.apis.project_history.url}/project"
}, (error, res, body)->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
try
project = JSON.parse(body)
catch error
return callback(error)
overleaf_id = project?.project?.id
if !overleaf_id
error = new Error("project-history did not provide an id", project)
return callback(error)
callback null, { overleaf_id }
else
error = new Error("project-history returned a non-success status code: #{res.statusCode}")
callback error
flushProject: (project_id, callback = (error) ->) ->
request.post {
url: "#{settings.apis.project_history.url}/project/#{project_id}/flush"
}, (error, res, body)->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
callback()
else
error = new Error("project-history returned a non-success status code: #{res.statusCode}")
callback error
injectUserDetails: (data, callback = (error, data_with_users) ->) ->
# data can be either:
# {
# diff: [{
# i: "foo",
# meta: {
# users: ["user_id", { first_name: "James", ... }, ...]
# ...
# }
# }, ...]
# }
# or
# {
# updates: [{
# pathnames: ["main.tex"]
# meta: {
# users: ["user_id", { first_name: "James", ... }, ...]
# ...
# },
# ...
# }, ...]
# }
# Either way, the top level key points to an array of objects with a meta.users property
# that we need to replace user_ids with populated user objects.
# Note that some entries in the users arrays may already have user objects from the v1 history
# service
user_ids = new Set()
for entry in data.diff or data.updates or []
for user in entry.meta?.users or []
if typeof user == "string"
user_ids.add user
user_ids = Array.from(user_ids)
UserGetter.getUsers user_ids, { first_name: 1, last_name: 1, email: 1 }, (error, users_array) ->
return callback(error) if error?
users = {}
for user in users_array or []
users[user._id.toString()] = HistoryManager._userView(user)
for entry in data.diff or data.updates or []
entry.meta?.users = (entry.meta?.users or []).map (user) ->
if typeof user == "string"
return users[user]
else
return user
callback null, data
_userView: (user) ->
{ _id, first_name, last_name, email } = user
return { first_name, last_name, email, id: _id } | 51908 | request = require "request"
settings = require "settings-sharelatex"
async = require 'async'
UserGetter = require "../User/UserGetter"
module.exports = HistoryManager =
initializeProject: (callback = (error, history_id) ->) ->
return callback() if !settings.apis.project_history?.initializeHistoryForNewProjects
request.post {
url: "#{settings.apis.project_history.url}/project"
}, (error, res, body)->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
try
project = JSON.parse(body)
catch error
return callback(error)
overleaf_id = project?.project?.id
if !overleaf_id
error = new Error("project-history did not provide an id", project)
return callback(error)
callback null, { overleaf_id }
else
error = new Error("project-history returned a non-success status code: #{res.statusCode}")
callback error
flushProject: (project_id, callback = (error) ->) ->
request.post {
url: "#{settings.apis.project_history.url}/project/#{project_id}/flush"
}, (error, res, body)->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
callback()
else
error = new Error("project-history returned a non-success status code: #{res.statusCode}")
callback error
injectUserDetails: (data, callback = (error, data_with_users) ->) ->
# data can be either:
# {
# diff: [{
# i: "foo",
# meta: {
# users: ["user_id", { first_name: "<NAME>", ... }, ...]
# ...
# }
# }, ...]
# }
# or
# {
# updates: [{
# pathnames: ["main.tex"]
# meta: {
# users: ["user_id", { first_name: "<NAME>", ... }, ...]
# ...
# },
# ...
# }, ...]
# }
# Either way, the top level key points to an array of objects with a meta.users property
# that we need to replace user_ids with populated user objects.
# Note that some entries in the users arrays may already have user objects from the v1 history
# service
user_ids = new Set()
for entry in data.diff or data.updates or []
for user in entry.meta?.users or []
if typeof user == "string"
user_ids.add user
user_ids = Array.from(user_ids)
UserGetter.getUsers user_ids, { first_name: 1, last_name: 1, email: 1 }, (error, users_array) ->
return callback(error) if error?
users = {}
for user in users_array or []
users[user._id.toString()] = HistoryManager._userView(user)
for entry in data.diff or data.updates or []
entry.meta?.users = (entry.meta?.users or []).map (user) ->
if typeof user == "string"
return users[user]
else
return user
callback null, data
_userView: (user) ->
{ _id, first_name, last_name, email } = user
return { first_name, last_name, email, id: _id } | true | request = require "request"
settings = require "settings-sharelatex"
async = require 'async'
UserGetter = require "../User/UserGetter"
module.exports = HistoryManager =
initializeProject: (callback = (error, history_id) ->) ->
return callback() if !settings.apis.project_history?.initializeHistoryForNewProjects
request.post {
url: "#{settings.apis.project_history.url}/project"
}, (error, res, body)->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
try
project = JSON.parse(body)
catch error
return callback(error)
overleaf_id = project?.project?.id
if !overleaf_id
error = new Error("project-history did not provide an id", project)
return callback(error)
callback null, { overleaf_id }
else
error = new Error("project-history returned a non-success status code: #{res.statusCode}")
callback error
flushProject: (project_id, callback = (error) ->) ->
request.post {
url: "#{settings.apis.project_history.url}/project/#{project_id}/flush"
}, (error, res, body)->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
callback()
else
error = new Error("project-history returned a non-success status code: #{res.statusCode}")
callback error
injectUserDetails: (data, callback = (error, data_with_users) ->) ->
# data can be either:
# {
# diff: [{
# i: "foo",
# meta: {
# users: ["user_id", { first_name: "PI:NAME:<NAME>END_PI", ... }, ...]
# ...
# }
# }, ...]
# }
# or
# {
# updates: [{
# pathnames: ["main.tex"]
# meta: {
# users: ["user_id", { first_name: "PI:NAME:<NAME>END_PI", ... }, ...]
# ...
# },
# ...
# }, ...]
# }
# Either way, the top level key points to an array of objects with a meta.users property
# that we need to replace user_ids with populated user objects.
# Note that some entries in the users arrays may already have user objects from the v1 history
# service
user_ids = new Set()
for entry in data.diff or data.updates or []
for user in entry.meta?.users or []
if typeof user == "string"
user_ids.add user
user_ids = Array.from(user_ids)
UserGetter.getUsers user_ids, { first_name: 1, last_name: 1, email: 1 }, (error, users_array) ->
return callback(error) if error?
users = {}
for user in users_array or []
users[user._id.toString()] = HistoryManager._userView(user)
for entry in data.diff or data.updates or []
entry.meta?.users = (entry.meta?.users or []).map (user) ->
if typeof user == "string"
return users[user]
else
return user
callback null, data
_userView: (user) ->
{ _id, first_name, last_name, email } = user
return { first_name, last_name, email, id: _id } |
[
{
"context": "fierDyingWishDamageNearbyAllies\"\n\n\t@modifierName:\"Curse of Agony\"\n\t@keyworded: false\n\t@description: \"When this min",
"end": 375,
"score": 0.9727956652641296,
"start": 361,
"tag": "NAME",
"value": "Curse of Agony"
}
] | app/sdk/modifiers/modifierDyingWishDamageNearbyAllies.coffee | willroberts/duelyst | 5 | CONFIG = require 'app/common/config'
ModifierDyingWish = require './modifierDyingWish'
DamageAction = require 'app/sdk/actions/damageAction'
CardType = require 'app/sdk/cards/cardType'
class ModifierDyingWishDamageNearbyAllies extends ModifierDyingWish
type:"ModifierDyingWishDamageNearbyAllies"
@type:"ModifierDyingWishDamageNearbyAllies"
@modifierName:"Curse of Agony"
@keyworded: false
@description: "When this minion dies, deal %X damage to all nearby friendly minions and General"
damageAmount: 0
fxResource: ["FX.Modifiers.ModifierDyingWishDamageNearbyAllies", "FX.Modifiers.ModifierGenericDamageNearbyShadow"]
@createContextObject: (damageAmount, options) ->
contextObject = super(options)
contextObject.damageAmount = damageAmount
return contextObject
@getDescription: (modifierContextObject) ->
if modifierContextObject
return @description.replace /%X/, modifierContextObject.damageAmount
else
return @description
onDyingWish: () ->
validEntities = @getGameSession().getBoard().getFriendlyEntitiesAroundEntity(@getCard(), CardType.Unit, 1)
for entity in validEntities
damageAction = new DamageAction(@getGameSession())
damageAction.setOwnerId(@getCard().getOwnerId())
damageAction.setSource(@getCard())
damageAction.setTarget(entity)
damageAction.setDamageAmount(@damageAmount)
@getGameSession().executeAction(damageAction)
module.exports = ModifierDyingWishDamageNearbyAllies
| 50065 | CONFIG = require 'app/common/config'
ModifierDyingWish = require './modifierDyingWish'
DamageAction = require 'app/sdk/actions/damageAction'
CardType = require 'app/sdk/cards/cardType'
class ModifierDyingWishDamageNearbyAllies extends ModifierDyingWish
type:"ModifierDyingWishDamageNearbyAllies"
@type:"ModifierDyingWishDamageNearbyAllies"
@modifierName:"<NAME>"
@keyworded: false
@description: "When this minion dies, deal %X damage to all nearby friendly minions and General"
damageAmount: 0
fxResource: ["FX.Modifiers.ModifierDyingWishDamageNearbyAllies", "FX.Modifiers.ModifierGenericDamageNearbyShadow"]
@createContextObject: (damageAmount, options) ->
contextObject = super(options)
contextObject.damageAmount = damageAmount
return contextObject
@getDescription: (modifierContextObject) ->
if modifierContextObject
return @description.replace /%X/, modifierContextObject.damageAmount
else
return @description
onDyingWish: () ->
validEntities = @getGameSession().getBoard().getFriendlyEntitiesAroundEntity(@getCard(), CardType.Unit, 1)
for entity in validEntities
damageAction = new DamageAction(@getGameSession())
damageAction.setOwnerId(@getCard().getOwnerId())
damageAction.setSource(@getCard())
damageAction.setTarget(entity)
damageAction.setDamageAmount(@damageAmount)
@getGameSession().executeAction(damageAction)
module.exports = ModifierDyingWishDamageNearbyAllies
| true | CONFIG = require 'app/common/config'
ModifierDyingWish = require './modifierDyingWish'
DamageAction = require 'app/sdk/actions/damageAction'
CardType = require 'app/sdk/cards/cardType'
class ModifierDyingWishDamageNearbyAllies extends ModifierDyingWish
type:"ModifierDyingWishDamageNearbyAllies"
@type:"ModifierDyingWishDamageNearbyAllies"
@modifierName:"PI:NAME:<NAME>END_PI"
@keyworded: false
@description: "When this minion dies, deal %X damage to all nearby friendly minions and General"
damageAmount: 0
fxResource: ["FX.Modifiers.ModifierDyingWishDamageNearbyAllies", "FX.Modifiers.ModifierGenericDamageNearbyShadow"]
@createContextObject: (damageAmount, options) ->
contextObject = super(options)
contextObject.damageAmount = damageAmount
return contextObject
@getDescription: (modifierContextObject) ->
if modifierContextObject
return @description.replace /%X/, modifierContextObject.damageAmount
else
return @description
onDyingWish: () ->
validEntities = @getGameSession().getBoard().getFriendlyEntitiesAroundEntity(@getCard(), CardType.Unit, 1)
for entity in validEntities
damageAction = new DamageAction(@getGameSession())
damageAction.setOwnerId(@getCard().getOwnerId())
damageAction.setSource(@getCard())
damageAction.setTarget(entity)
damageAction.setDamageAmount(@damageAmount)
@getGameSession().executeAction(damageAction)
module.exports = ModifierDyingWishDamageNearbyAllies
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.