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": "ethod, url, data)\n user = \"name\": \"huawei\"\n\n return [200, user, {}]; \n ",
"end": 722,
"score": 0.999102771282196,
"start": 716,
"tag": "USERNAME",
"value": "huawei"
},
{
"context": "ditable\": true,\n \"create_by\": \"user@someemail.com\",\n \"create_at\": \"2014-3-25 12:",
"end": 1277,
"score": 0.9999186396598816,
"start": 1259,
"tag": "EMAIL",
"value": "user@someemail.com"
},
{
"context": "ditable\": true,\n \"create_by\": \"user@someemail.com\",\n \"create_at\": \"2014-3-25 12:",
"end": 2000,
"score": 0.9999197125434875,
"start": 1982,
"tag": "EMAIL",
"value": "user@someemail.com"
},
{
"context": "ditable\": true,\n \"create_by\": \"user@someemail.com\",\n \"create_at\": \"2014-3-25 12:",
"end": 2723,
"score": 0.9999210238456726,
"start": 2705,
"tag": "EMAIL",
"value": "user@someemail.com"
},
{
"context": "ditable\": true,\n \"create_by\": \"user@someemail.com\",\n \"create_at\": \"2014-3-25 12:",
"end": 3446,
"score": 0.9999201893806458,
"start": 3428,
"tag": "EMAIL",
"value": "user@someemail.com"
},
{
"context": "ditable\": true,\n \"create_by\": \"user@someemail.com\",\n \"create_at\": \"2014-4-25 12:",
"end": 4169,
"score": 0.9999218583106995,
"start": 4151,
"tag": "EMAIL",
"value": "user@someemail.com"
}
] | v2.5/src/app/server/testServer.coffee | sharonlucong/compass-intel-rsa-dist | 0 | define(['angular','angularMocks'
], (ng)->
'use strict';
# class Server
# constructor: (@httpBackend, @settings, @$http) ->
ng.module('compass.testServer', ['ngMockE2E'])
.constant('settings',{
apiUrlBase: '/api'
metadataUrlBase: 'data'
monitoringUrlBase: '/monit/api/v1'
})
.run(($httpBackend, settings, $http) ->
$httpBackend.whenGET(new RegExp('src\/.*')).passThrough()
$httpBackend.whenGET(new RegExp('data\/.*')).passThrough()
$httpBackend.whenPOST(settings.apiUrlBase + '/users/login').respond( (method, url, data) ->
console.log(method, url, data)
user = "name": "huawei"
return [200, user, {}];
)
$httpBackend.whenGET(/\.*\/clusters$/).respond((method, url, data) ->
console.log(method, url)
clusters = [{
"id": 1,
"name": "cluster_01 long string",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "user@someemail.com",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-26 13:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 2,
"name": "cluster_02",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "user@someemail.com",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-28 14:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 3,
"name": "cluster_03",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "user@someemail.com",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-5-26 09:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 4,
"name": "cluster_04",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "user@someemail.com",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-19 08:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 5,
"name": "cluster_05",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "user@someemail.com",
"create_at": "2014-4-25 12:00:00",
"updated_at": "2014-2-27 20:00:00",
"links": [{
"href": "/clusters/2",
"rel": "self"
}, {
"href": "/clusters/2/hosts",
"rel": "hosts"
}]
}];
return [200, clusters, {}];
)
$httpBackend.whenGET(/\.*\/clusters\/[1-9][0-9]*\/state/).respond((method, url, data) ->
console.log(method, url, data);
states = ["UNINITIALIZED", "INITIALIZED", "INSTALLING", "SUCCESSFUL", "ERROR"];
progressData = {
"id": 1,
"state": states[Math.floor((Math.random() * 5))],
"config_step": "deploy",
"status": {
"total_hosts": 4,
"installing_hosts": 2,
"completed_hosts": 1,
"failed_hosts": 1,
"message": ""
}
};
return [200, progressData, {}];
)
)
) | 139191 | define(['angular','angularMocks'
], (ng)->
'use strict';
# class Server
# constructor: (@httpBackend, @settings, @$http) ->
ng.module('compass.testServer', ['ngMockE2E'])
.constant('settings',{
apiUrlBase: '/api'
metadataUrlBase: 'data'
monitoringUrlBase: '/monit/api/v1'
})
.run(($httpBackend, settings, $http) ->
$httpBackend.whenGET(new RegExp('src\/.*')).passThrough()
$httpBackend.whenGET(new RegExp('data\/.*')).passThrough()
$httpBackend.whenPOST(settings.apiUrlBase + '/users/login').respond( (method, url, data) ->
console.log(method, url, data)
user = "name": "huawei"
return [200, user, {}];
)
$httpBackend.whenGET(/\.*\/clusters$/).respond((method, url, data) ->
console.log(method, url)
clusters = [{
"id": 1,
"name": "cluster_01 long string",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "<EMAIL>",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-26 13:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 2,
"name": "cluster_02",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "<EMAIL>",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-28 14:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 3,
"name": "cluster_03",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "<EMAIL>",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-5-26 09:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 4,
"name": "cluster_04",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "<EMAIL>",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-19 08:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 5,
"name": "cluster_05",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "<EMAIL>",
"create_at": "2014-4-25 12:00:00",
"updated_at": "2014-2-27 20:00:00",
"links": [{
"href": "/clusters/2",
"rel": "self"
}, {
"href": "/clusters/2/hosts",
"rel": "hosts"
}]
}];
return [200, clusters, {}];
)
$httpBackend.whenGET(/\.*\/clusters\/[1-9][0-9]*\/state/).respond((method, url, data) ->
console.log(method, url, data);
states = ["UNINITIALIZED", "INITIALIZED", "INSTALLING", "SUCCESSFUL", "ERROR"];
progressData = {
"id": 1,
"state": states[Math.floor((Math.random() * 5))],
"config_step": "deploy",
"status": {
"total_hosts": 4,
"installing_hosts": 2,
"completed_hosts": 1,
"failed_hosts": 1,
"message": ""
}
};
return [200, progressData, {}];
)
)
) | true | define(['angular','angularMocks'
], (ng)->
'use strict';
# class Server
# constructor: (@httpBackend, @settings, @$http) ->
ng.module('compass.testServer', ['ngMockE2E'])
.constant('settings',{
apiUrlBase: '/api'
metadataUrlBase: 'data'
monitoringUrlBase: '/monit/api/v1'
})
.run(($httpBackend, settings, $http) ->
$httpBackend.whenGET(new RegExp('src\/.*')).passThrough()
$httpBackend.whenGET(new RegExp('data\/.*')).passThrough()
$httpBackend.whenPOST(settings.apiUrlBase + '/users/login').respond( (method, url, data) ->
console.log(method, url, data)
user = "name": "huawei"
return [200, user, {}];
)
$httpBackend.whenGET(/\.*\/clusters$/).respond((method, url, data) ->
console.log(method, url)
clusters = [{
"id": 1,
"name": "cluster_01 long string",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "PI:EMAIL:<EMAIL>END_PI",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-26 13:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 2,
"name": "cluster_02",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "PI:EMAIL:<EMAIL>END_PI",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-28 14:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 3,
"name": "cluster_03",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "PI:EMAIL:<EMAIL>END_PI",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-5-26 09:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 4,
"name": "cluster_04",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "PI:EMAIL:<EMAIL>END_PI",
"create_at": "2014-3-25 12:00:00",
"updated_at": "2014-3-19 08:00:00",
"links": [{
"href": "/clusters/1",
"rel": "self"
}, {
"href": "/clusters/1/hosts",
"rel": "hosts"
}]
}, {
"id": 5,
"name": "cluster_05",
"adapter_id": 1,
"os_id": 1,
"os_name": "CentOS",
"distributed_system_name": "OpenStack",
"editable": true,
"create_by": "PI:EMAIL:<EMAIL>END_PI",
"create_at": "2014-4-25 12:00:00",
"updated_at": "2014-2-27 20:00:00",
"links": [{
"href": "/clusters/2",
"rel": "self"
}, {
"href": "/clusters/2/hosts",
"rel": "hosts"
}]
}];
return [200, clusters, {}];
)
$httpBackend.whenGET(/\.*\/clusters\/[1-9][0-9]*\/state/).respond((method, url, data) ->
console.log(method, url, data);
states = ["UNINITIALIZED", "INITIALIZED", "INSTALLING", "SUCCESSFUL", "ERROR"];
progressData = {
"id": 1,
"state": states[Math.floor((Math.random() * 5))],
"config_step": "deploy",
"status": {
"total_hosts": 4,
"installing_hosts": 2,
"completed_hosts": 1,
"failed_hosts": 1,
"message": ""
}
};
return [200, progressData, {}];
)
)
) |
[
{
"context": "rview Tests for no-unsafe-negation rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------",
"end": 80,
"score": 0.999859631061554,
"start": 66,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/tests/rules/no-unsafe-negation.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-unsafe-negation rule.
# @author Toru Nagashima
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-unsafe-negation'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unsafe-negation', rule,
valid: [
'a in b'
'a not in b'
'a of b'
'a not of b'
'a in b is false'
'!(a in b)'
'not (a in b)'
'!(a not in b)'
'!(a of b)'
'!(a not of b)'
'(!a) in b'
'(not a) in b'
'(!a) not in b'
'(!a) of b'
'(!a) not of b'
'a instanceof b'
'a not instanceof b'
'a instanceof b is false'
'!(a instanceof b)'
'not (a instanceof b)'
'!(a not instanceof b)'
'(!a) instanceof b'
'(!a) not instanceof b'
]
invalid: [
code: '!a in b'
# output: '!(a in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: 'not a in b'
# output: 'not (a in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '!a not in b'
# output: '!(a not in b)'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '!a of b'
# output: '!(a of b)'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '!a not of b'
# output: '!(a not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: 'not a not of b'
# output: 'not (a not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '(!a in b)'
# output: '(!(a in b))'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '(not a in b)'
# output: '(not (a in b))'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '(!a not in b)'
# output: '(!(a not in b))'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '(!a of b)'
# output: '(!(a of b))'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '(!a not of b)'
# output: '(!(a not of b))'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '!(a) in b'
# output: '!((a) in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '!(a) not in b'
# output: '!((a) not in b)'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '!(a) of b'
# output: '!((a) of b)'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '!(a) not of b'
# output: '!((a) not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '!a instanceof b'
# output: '!(a instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '!a not instanceof b'
# output: '!(a not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: 'not a not instanceof b'
# output: 'not (a not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: '(!a instanceof b)'
# output: '(!(a instanceof b))'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '(!a not instanceof b)'
# output: '(!(a not instanceof b))'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: '!(a) instanceof b'
# output: '!((a) instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: 'not (a) instanceof b'
# output: 'not ((a) instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '!(a) not instanceof b'
# output: '!((a) not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
]
| 45774 | ###*
# @fileoverview Tests for no-unsafe-negation rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-unsafe-negation'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unsafe-negation', rule,
valid: [
'a in b'
'a not in b'
'a of b'
'a not of b'
'a in b is false'
'!(a in b)'
'not (a in b)'
'!(a not in b)'
'!(a of b)'
'!(a not of b)'
'(!a) in b'
'(not a) in b'
'(!a) not in b'
'(!a) of b'
'(!a) not of b'
'a instanceof b'
'a not instanceof b'
'a instanceof b is false'
'!(a instanceof b)'
'not (a instanceof b)'
'!(a not instanceof b)'
'(!a) instanceof b'
'(!a) not instanceof b'
]
invalid: [
code: '!a in b'
# output: '!(a in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: 'not a in b'
# output: 'not (a in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '!a not in b'
# output: '!(a not in b)'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '!a of b'
# output: '!(a of b)'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '!a not of b'
# output: '!(a not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: 'not a not of b'
# output: 'not (a not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '(!a in b)'
# output: '(!(a in b))'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '(not a in b)'
# output: '(not (a in b))'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '(!a not in b)'
# output: '(!(a not in b))'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '(!a of b)'
# output: '(!(a of b))'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '(!a not of b)'
# output: '(!(a not of b))'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '!(a) in b'
# output: '!((a) in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '!(a) not in b'
# output: '!((a) not in b)'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '!(a) of b'
# output: '!((a) of b)'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '!(a) not of b'
# output: '!((a) not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '!a instanceof b'
# output: '!(a instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '!a not instanceof b'
# output: '!(a not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: 'not a not instanceof b'
# output: 'not (a not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: '(!a instanceof b)'
# output: '(!(a instanceof b))'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '(!a not instanceof b)'
# output: '(!(a not instanceof b))'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: '!(a) instanceof b'
# output: '!((a) instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: 'not (a) instanceof b'
# output: 'not ((a) instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '!(a) not instanceof b'
# output: '!((a) not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
]
| true | ###*
# @fileoverview Tests for no-unsafe-negation rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-unsafe-negation'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unsafe-negation', rule,
valid: [
'a in b'
'a not in b'
'a of b'
'a not of b'
'a in b is false'
'!(a in b)'
'not (a in b)'
'!(a not in b)'
'!(a of b)'
'!(a not of b)'
'(!a) in b'
'(not a) in b'
'(!a) not in b'
'(!a) of b'
'(!a) not of b'
'a instanceof b'
'a not instanceof b'
'a instanceof b is false'
'!(a instanceof b)'
'not (a instanceof b)'
'!(a not instanceof b)'
'(!a) instanceof b'
'(!a) not instanceof b'
]
invalid: [
code: '!a in b'
# output: '!(a in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: 'not a in b'
# output: 'not (a in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '!a not in b'
# output: '!(a not in b)'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '!a of b'
# output: '!(a of b)'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '!a not of b'
# output: '!(a not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: 'not a not of b'
# output: 'not (a not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '(!a in b)'
# output: '(!(a in b))'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '(not a in b)'
# output: '(not (a in b))'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '(!a not in b)'
# output: '(!(a not in b))'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '(!a of b)'
# output: '(!(a of b))'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '(!a not of b)'
# output: '(!(a not of b))'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '!(a) in b'
# output: '!((a) in b)'
errors: ["Unexpected negating the left operand of 'in' operator."]
,
code: '!(a) not in b'
# output: '!((a) not in b)'
errors: ["Unexpected negating the left operand of 'not in' operator."]
,
code: '!(a) of b'
# output: '!((a) of b)'
errors: ["Unexpected negating the left operand of 'of' operator."]
,
code: '!(a) not of b'
# output: '!((a) not of b)'
errors: ["Unexpected negating the left operand of 'not of' operator."]
,
code: '!a instanceof b'
# output: '!(a instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '!a not instanceof b'
# output: '!(a not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: 'not a not instanceof b'
# output: 'not (a not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: '(!a instanceof b)'
# output: '(!(a instanceof b))'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '(!a not instanceof b)'
# output: '(!(a not instanceof b))'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
,
code: '!(a) instanceof b'
# output: '!((a) instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: 'not (a) instanceof b'
# output: 'not ((a) instanceof b)'
errors: ["Unexpected negating the left operand of 'instanceof' operator."]
,
code: '!(a) not instanceof b'
# output: '!((a) not instanceof b)'
errors: [
"Unexpected negating the left operand of 'not instanceof' operator."
]
]
|
[
{
"context": "lt native-key-bindings', =>\n @div \"iksh edgsiughis\", outlet: 'resultsView'\n\n initialize: ->\n ato",
"end": 197,
"score": 0.4799724221229553,
"start": 192,
"tag": "NAME",
"value": "ughis"
}
] | lib/cache-list-view.coffee | UGroup/AtomDialogTest | 0 | {$, $$$, ScrollView} = require 'atom'
module.exports =
class CacheListView extends ScrollView
@content: ->
@div class: 'ask-stack-result native-key-bindings', =>
@div "iksh edgsiughis", outlet: 'resultsView'
initialize: ->
atom.workspaceView.command "cache-modal-dialog:toggle2", => @toggle()
#@render()
super
destroy: ->
@unsubscribe()
getTitle: ->
'Cache Package List'
getUri: ->
'cache://list-view'
getIconName: ->
'three-bars'
render : (ClassList) ->
console.log (ClassList)
list="<ul>"
for item in ClassList
list=list+"<li>"+item.Name+"</li>"
list=list+"</ul>"
@resultsView.html(list)
toggle: ->
if @hasParent()
@detach()
else
atom.workspaceView.append(this)
| 186924 | {$, $$$, ScrollView} = require 'atom'
module.exports =
class CacheListView extends ScrollView
@content: ->
@div class: 'ask-stack-result native-key-bindings', =>
@div "iksh edgsi<NAME>", outlet: 'resultsView'
initialize: ->
atom.workspaceView.command "cache-modal-dialog:toggle2", => @toggle()
#@render()
super
destroy: ->
@unsubscribe()
getTitle: ->
'Cache Package List'
getUri: ->
'cache://list-view'
getIconName: ->
'three-bars'
render : (ClassList) ->
console.log (ClassList)
list="<ul>"
for item in ClassList
list=list+"<li>"+item.Name+"</li>"
list=list+"</ul>"
@resultsView.html(list)
toggle: ->
if @hasParent()
@detach()
else
atom.workspaceView.append(this)
| true | {$, $$$, ScrollView} = require 'atom'
module.exports =
class CacheListView extends ScrollView
@content: ->
@div class: 'ask-stack-result native-key-bindings', =>
@div "iksh edgsiPI:NAME:<NAME>END_PI", outlet: 'resultsView'
initialize: ->
atom.workspaceView.command "cache-modal-dialog:toggle2", => @toggle()
#@render()
super
destroy: ->
@unsubscribe()
getTitle: ->
'Cache Package List'
getUri: ->
'cache://list-view'
getIconName: ->
'three-bars'
render : (ClassList) ->
console.log (ClassList)
list="<ul>"
for item in ClassList
list=list+"<li>"+item.Name+"</li>"
list=list+"</ul>"
@resultsView.html(list)
toggle: ->
if @hasParent()
@detach()
else
atom.workspaceView.append(this)
|
[
{
"context": "t.Name += \" 1\"\n\t\tapp.Universe.Games.push \n\t\t\tName: name\n\t\t\tStartingNumberOfLives: 9\n\t\t\tPlanets : [planet]",
"end": 1561,
"score": 0.5680721402168274,
"start": 1557,
"tag": "NAME",
"value": "name"
}
] | game/scripts/Game/Constructor/old/GameOptions.coffee | belczyk/robbo | 5 | window.app = window.app ? {}
app = window.app
class app.GameDesigner
constructor: () ->
@gameName = ko.observable()
@planetName = ko.observable()
@lives = ko.observable()
@bolts = ko.observable()
@width = ko.observable()
@height = ko.observable()
@optionsPanel = $('.options-panel')
@games = ko.observableArray()
@planets = ko.observableArray()
@selectedGame = ko.observable()
@selectedPlanet = ko.observable()
@selectedGameId = ko.observable(0)
@selectedPlanetId = ko.observable(0)
@selectedGameId.subscribe =>
@selectedGame = @games()[@selectedGameId()]
@selectedPlanetId(0)
return
@selectedPlanetId.subscribe =>
@selectedPlanet = @planets[@selectedPlanetId()]
@load()
return
@loadGames()
@loadPlanets()
ko.applyBindings this,$('.game-designer')[0]
$('.has-tooltip').tooltip()
loadGames: ()->
for game,i in app.Universe.Games
game.index = i
@games.push game
@selectedGameId 0
@selectedGame @games[0]
return
loadPlanets: () ->
for planet,i in app.Universe.Games[@selectedGameId()].Planets
planet.index = i
@planets.push planet
@selectedPlanetId 0
@selectedPlanet @planets[0]
return
saveGame: () ->
$('.save-game').text('Saving...')
$.ajax
url: app.ConstructorConfig.serverAddress+"/api/robbo"
data: app.Universe
type: "POST"
success: ()-> setTimeout((()->$('.save-game').text('Save game')),200)
return
newGame: () ->
name = "Game "+@games.length+1
planet = @createPlanet()
planet.Name += " 1"
app.Universe.Games.push
Name: name
StartingNumberOfLives: 9
Planets : [planet]
@loadGames()
@load()
return
removePlanet: () ->
if (!@currentPlanetId()?) then return
if !confirm("Are you sure you want remove current planet?") then return
@currentGame().Planets.splice(@currentPlanetId(),1)
toggleRawMap: () ->
if($('.map').is(":visible"))
$('.map').hide("blind")
else
$('.map').show("blind")
removeGame: () ->
if (@currentGameId()=="0")
alert("You can't remove original game")
return
if !confirm("Are you sure you want remove current game?") then return
app.Universe.Games.splice(@currentGameId(),1)
toggleOptions: (x,e) ->
if(@optionsPanel.is(':visible'))
@optionsPanel.hide('blind')
else
@optionsPanel.show('blind')
createPlanet: () ->
planet =
BoltsToBeCollected: 5
Name: "Planet"
Map : ""
lines = []
for x in [0..31]
line = ""
for y in [0..16]
line+="_.."
lines.push line
planet.Map = lines.join("\n")
planet
newPlanet: ()->
planet = @createPlanet()
planet.Name += " "+(@currentGame().Planets.length+1)
game.Planets.push planet
app.Universe.Games[@currentGameId()].Planets push planet
@selectedPlanetId(game.Planets.length-1)
@load()
testPlanet: () ->
window.open("robbo.html?game=#{@currentGameId()}&planet=#{@currentPlanetId()}","_blank")
load: () ->
@width(app.MapLoader.getWidth(@currentPlanet().Map))
@height(app.MapLoader.getHeight(@currentPlanet().Map))
@planetName(@currentPlanet().Name)
@gameName(@currentGame().Name)
@bolts(@currentPlanet().BoltsToBeCollected)
@lives(@currentGame().StartingNumberOfLives)
$ ->
new app.GameDesigner() | 31090 | window.app = window.app ? {}
app = window.app
class app.GameDesigner
constructor: () ->
@gameName = ko.observable()
@planetName = ko.observable()
@lives = ko.observable()
@bolts = ko.observable()
@width = ko.observable()
@height = ko.observable()
@optionsPanel = $('.options-panel')
@games = ko.observableArray()
@planets = ko.observableArray()
@selectedGame = ko.observable()
@selectedPlanet = ko.observable()
@selectedGameId = ko.observable(0)
@selectedPlanetId = ko.observable(0)
@selectedGameId.subscribe =>
@selectedGame = @games()[@selectedGameId()]
@selectedPlanetId(0)
return
@selectedPlanetId.subscribe =>
@selectedPlanet = @planets[@selectedPlanetId()]
@load()
return
@loadGames()
@loadPlanets()
ko.applyBindings this,$('.game-designer')[0]
$('.has-tooltip').tooltip()
loadGames: ()->
for game,i in app.Universe.Games
game.index = i
@games.push game
@selectedGameId 0
@selectedGame @games[0]
return
loadPlanets: () ->
for planet,i in app.Universe.Games[@selectedGameId()].Planets
planet.index = i
@planets.push planet
@selectedPlanetId 0
@selectedPlanet @planets[0]
return
saveGame: () ->
$('.save-game').text('Saving...')
$.ajax
url: app.ConstructorConfig.serverAddress+"/api/robbo"
data: app.Universe
type: "POST"
success: ()-> setTimeout((()->$('.save-game').text('Save game')),200)
return
newGame: () ->
name = "Game "+@games.length+1
planet = @createPlanet()
planet.Name += " 1"
app.Universe.Games.push
Name: <NAME>
StartingNumberOfLives: 9
Planets : [planet]
@loadGames()
@load()
return
removePlanet: () ->
if (!@currentPlanetId()?) then return
if !confirm("Are you sure you want remove current planet?") then return
@currentGame().Planets.splice(@currentPlanetId(),1)
toggleRawMap: () ->
if($('.map').is(":visible"))
$('.map').hide("blind")
else
$('.map').show("blind")
removeGame: () ->
if (@currentGameId()=="0")
alert("You can't remove original game")
return
if !confirm("Are you sure you want remove current game?") then return
app.Universe.Games.splice(@currentGameId(),1)
toggleOptions: (x,e) ->
if(@optionsPanel.is(':visible'))
@optionsPanel.hide('blind')
else
@optionsPanel.show('blind')
createPlanet: () ->
planet =
BoltsToBeCollected: 5
Name: "Planet"
Map : ""
lines = []
for x in [0..31]
line = ""
for y in [0..16]
line+="_.."
lines.push line
planet.Map = lines.join("\n")
planet
newPlanet: ()->
planet = @createPlanet()
planet.Name += " "+(@currentGame().Planets.length+1)
game.Planets.push planet
app.Universe.Games[@currentGameId()].Planets push planet
@selectedPlanetId(game.Planets.length-1)
@load()
testPlanet: () ->
window.open("robbo.html?game=#{@currentGameId()}&planet=#{@currentPlanetId()}","_blank")
load: () ->
@width(app.MapLoader.getWidth(@currentPlanet().Map))
@height(app.MapLoader.getHeight(@currentPlanet().Map))
@planetName(@currentPlanet().Name)
@gameName(@currentGame().Name)
@bolts(@currentPlanet().BoltsToBeCollected)
@lives(@currentGame().StartingNumberOfLives)
$ ->
new app.GameDesigner() | true | window.app = window.app ? {}
app = window.app
class app.GameDesigner
constructor: () ->
@gameName = ko.observable()
@planetName = ko.observable()
@lives = ko.observable()
@bolts = ko.observable()
@width = ko.observable()
@height = ko.observable()
@optionsPanel = $('.options-panel')
@games = ko.observableArray()
@planets = ko.observableArray()
@selectedGame = ko.observable()
@selectedPlanet = ko.observable()
@selectedGameId = ko.observable(0)
@selectedPlanetId = ko.observable(0)
@selectedGameId.subscribe =>
@selectedGame = @games()[@selectedGameId()]
@selectedPlanetId(0)
return
@selectedPlanetId.subscribe =>
@selectedPlanet = @planets[@selectedPlanetId()]
@load()
return
@loadGames()
@loadPlanets()
ko.applyBindings this,$('.game-designer')[0]
$('.has-tooltip').tooltip()
loadGames: ()->
for game,i in app.Universe.Games
game.index = i
@games.push game
@selectedGameId 0
@selectedGame @games[0]
return
loadPlanets: () ->
for planet,i in app.Universe.Games[@selectedGameId()].Planets
planet.index = i
@planets.push planet
@selectedPlanetId 0
@selectedPlanet @planets[0]
return
saveGame: () ->
$('.save-game').text('Saving...')
$.ajax
url: app.ConstructorConfig.serverAddress+"/api/robbo"
data: app.Universe
type: "POST"
success: ()-> setTimeout((()->$('.save-game').text('Save game')),200)
return
newGame: () ->
name = "Game "+@games.length+1
planet = @createPlanet()
planet.Name += " 1"
app.Universe.Games.push
Name: PI:NAME:<NAME>END_PI
StartingNumberOfLives: 9
Planets : [planet]
@loadGames()
@load()
return
removePlanet: () ->
if (!@currentPlanetId()?) then return
if !confirm("Are you sure you want remove current planet?") then return
@currentGame().Planets.splice(@currentPlanetId(),1)
toggleRawMap: () ->
if($('.map').is(":visible"))
$('.map').hide("blind")
else
$('.map').show("blind")
removeGame: () ->
if (@currentGameId()=="0")
alert("You can't remove original game")
return
if !confirm("Are you sure you want remove current game?") then return
app.Universe.Games.splice(@currentGameId(),1)
toggleOptions: (x,e) ->
if(@optionsPanel.is(':visible'))
@optionsPanel.hide('blind')
else
@optionsPanel.show('blind')
createPlanet: () ->
planet =
BoltsToBeCollected: 5
Name: "Planet"
Map : ""
lines = []
for x in [0..31]
line = ""
for y in [0..16]
line+="_.."
lines.push line
planet.Map = lines.join("\n")
planet
newPlanet: ()->
planet = @createPlanet()
planet.Name += " "+(@currentGame().Planets.length+1)
game.Planets.push planet
app.Universe.Games[@currentGameId()].Planets push planet
@selectedPlanetId(game.Planets.length-1)
@load()
testPlanet: () ->
window.open("robbo.html?game=#{@currentGameId()}&planet=#{@currentPlanetId()}","_blank")
load: () ->
@width(app.MapLoader.getWidth(@currentPlanet().Map))
@height(app.MapLoader.getHeight(@currentPlanet().Map))
@planetName(@currentPlanet().Name)
@gameName(@currentGame().Name)
@bolts(@currentPlanet().BoltsToBeCollected)
@lives(@currentGame().StartingNumberOfLives)
$ ->
new app.GameDesigner() |
[
{
"context": "wnProperty(\"tense\")\n key += \".#{options.tense}\"\n if options.hasOwnProperty(\"count\")\n swit",
"end": 468,
"score": 0.5611642003059387,
"start": 468,
"tag": "KEY",
"value": ""
},
{
"context": "re: ->\n @_store ||= {}\n\n # https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb\n i",
"end": 1103,
"score": 0.9997218251228333,
"start": 1094,
"tag": "USERNAME",
"value": "svenfuchs"
}
] | src/tower/support/i18n.coffee | vjsingh/tower | 1 | # @module
Tower.Support.I18n =
PATTERN: /(?:%%|%\{(\w+)\}|%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps]))/g
defaultLanguage: "en"
load: (pathOrObject, language = @defaultLanguage) ->
store = @store()
language = store[language] ||= {}
_.deepMerge(language, if typeof(pathOrObject) == "string" then require(pathOrObject) else pathOrObject)
@
translate: (key, options = {}) ->
if options.hasOwnProperty("tense")
key += ".#{options.tense}"
if options.hasOwnProperty("count")
switch options.count
when 0 then key += ".none"
when 1 then key += ".one"
else key += ".other"
@interpolate(@lookup(key, options.language), options)
localize: ->
@translate arguments...
lookup: (key, language = @defaultLanguage) ->
parts = key.split(".")
result = @store()[language]
try
for part in parts
result = result[part]
catch error
result = null
throw new Error("Translation doesn't exist for '#{key}'") unless result?
result
store: ->
@_store ||= {}
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb
interpolate: (string, locals = {}) ->
string.replace @PATTERN, (match, $1, $2, $3) ->
if match == '%%'
'%'
else
key = $1 || $2
if locals.hasOwnProperty(key)
value = locals[key]
else
throw new Error("Missing interpolation argument #{key}")
value = value.call(locals) if typeof value == 'function'
if $3 then sprintf("%#{$3}", value) else value
Tower.Support.I18n.t = Tower.Support.I18n.translate
module.exports = Tower.Support.I18n
| 127473 | # @module
Tower.Support.I18n =
PATTERN: /(?:%%|%\{(\w+)\}|%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps]))/g
defaultLanguage: "en"
load: (pathOrObject, language = @defaultLanguage) ->
store = @store()
language = store[language] ||= {}
_.deepMerge(language, if typeof(pathOrObject) == "string" then require(pathOrObject) else pathOrObject)
@
translate: (key, options = {}) ->
if options.hasOwnProperty("tense")
key += ".#{options.tense<KEY>}"
if options.hasOwnProperty("count")
switch options.count
when 0 then key += ".none"
when 1 then key += ".one"
else key += ".other"
@interpolate(@lookup(key, options.language), options)
localize: ->
@translate arguments...
lookup: (key, language = @defaultLanguage) ->
parts = key.split(".")
result = @store()[language]
try
for part in parts
result = result[part]
catch error
result = null
throw new Error("Translation doesn't exist for '#{key}'") unless result?
result
store: ->
@_store ||= {}
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb
interpolate: (string, locals = {}) ->
string.replace @PATTERN, (match, $1, $2, $3) ->
if match == '%%'
'%'
else
key = $1 || $2
if locals.hasOwnProperty(key)
value = locals[key]
else
throw new Error("Missing interpolation argument #{key}")
value = value.call(locals) if typeof value == 'function'
if $3 then sprintf("%#{$3}", value) else value
Tower.Support.I18n.t = Tower.Support.I18n.translate
module.exports = Tower.Support.I18n
| true | # @module
Tower.Support.I18n =
PATTERN: /(?:%%|%\{(\w+)\}|%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps]))/g
defaultLanguage: "en"
load: (pathOrObject, language = @defaultLanguage) ->
store = @store()
language = store[language] ||= {}
_.deepMerge(language, if typeof(pathOrObject) == "string" then require(pathOrObject) else pathOrObject)
@
translate: (key, options = {}) ->
if options.hasOwnProperty("tense")
key += ".#{options.tensePI:KEY:<KEY>END_PI}"
if options.hasOwnProperty("count")
switch options.count
when 0 then key += ".none"
when 1 then key += ".one"
else key += ".other"
@interpolate(@lookup(key, options.language), options)
localize: ->
@translate arguments...
lookup: (key, language = @defaultLanguage) ->
parts = key.split(".")
result = @store()[language]
try
for part in parts
result = result[part]
catch error
result = null
throw new Error("Translation doesn't exist for '#{key}'") unless result?
result
store: ->
@_store ||= {}
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb
interpolate: (string, locals = {}) ->
string.replace @PATTERN, (match, $1, $2, $3) ->
if match == '%%'
'%'
else
key = $1 || $2
if locals.hasOwnProperty(key)
value = locals[key]
else
throw new Error("Missing interpolation argument #{key}")
value = value.call(locals) if typeof value == 'function'
if $3 then sprintf("%#{$3}", value) else value
Tower.Support.I18n.t = Tower.Support.I18n.translate
module.exports = Tower.Support.I18n
|
[
{
"context": ".getTranslator(\"en\")\n @user = null\n @token = null\n\n @checkCookie()\n @last_active = Date.now()",
"end": 492,
"score": 0.5138739943504333,
"start": 488,
"tag": "PASSWORD",
"value": "null"
},
{
"context": "ccessfully!\")]\n token: @content.createToken(@user).value\n request_id: data.request_id\n\n @se",
"end": 10454,
"score": 0.7941738963127136,
"start": 10450,
"tag": "USERNAME",
"value": "user"
},
{
"context": "logged_in\"\n token: @content.createToken(@user).value\n nick: @user.nick\n email",
"end": 11244,
"score": 0.8751474618911743,
"start": 11240,
"tag": "USERNAME",
"value": "user"
},
{
"context": " @content.createToken(@user).value\n nick: @user.nick\n email: @user.email\n flags: if ",
"end": 11278,
"score": 0.8578079342842102,
"start": 11268,
"tag": "USERNAME",
"value": "@user.nick"
},
{
"context": " @send\n name: \"token_valid\"\n nick: @user.nick\n email: @user.email\n flags: if",
"end": 12508,
"score": 0.5047841668128967,
"start": 12504,
"tag": "USERNAME",
"value": "user"
},
{
"context": " @send\n name: \"token_valid\"\n nick: @user.nick\n email: @user.email\n flags: if",
"end": 13012,
"score": 0.7514989972114563,
"start": 13007,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "d\n name: \"token_valid\"\n nick: @user.nick\n email: @user.email\n flags: if not ",
"end": 13017,
"score": 0.6414960026741028,
"start": 13013,
"tag": "USERNAME",
"value": "nick"
},
{
"context": "getProjectManager project\n if manager.canRead(@user)\n @content.createProject @user,{\n ",
"end": 17731,
"score": 0.9947364330291748,
"start": 17726,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "_image\n likes: p.likes\n liked: @user? and @user.isLiked(p.id)\n tags: p.tags\n ",
"end": 29229,
"score": 0.8449456691741943,
"start": 29225,
"tag": "USERNAME",
"value": "user"
},
{
"context": " if @server.rate_limiter.accept(\"send_mail_user\",@user.id)\n @server.content.sendValidationMail(",
"end": 32915,
"score": 0.6275320649147034,
"start": 32915,
"tag": "USERNAME",
"value": ""
},
{
"context": "@user.id)\n @server.content.sendValidationMail(@user)\n if data?\n @send\n name:\"sen",
"end": 32971,
"score": 0.7818477749824524,
"start": 32966,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "mment_user\",@user.id)\n project.comments.add(@user,data.text)\n @send\n name: \"add_pro",
"end": 37264,
"score": 0.9797028303146362,
"start": 37259,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "comments.get(data.id)\n if c? and (c.user == @user or @user.flags.admin)\n c.remove()\n ",
"end": 37649,
"score": 0.9890010952949524,
"start": 37644,
"tag": "USERNAME",
"value": "@user"
},
{
"context": ".comments.get(data.id)\n if c? and c.user == @user\n c.edit(data.text)\n @send\n ",
"end": 38101,
"score": 0.831684410572052,
"start": 38096,
"tag": "USERNAME",
"value": "@user"
}
] | server/session/session.coffee | karlmolina/microstudio | 0 | SHA256 = require("crypto-js/sha256")
ProjectManager = require __dirname+"/projectmanager.js"
RegexLib = require __dirname+"/../../static/js/util/regexlib.js"
ForumSession = require __dirname+"/../forum/forumsession.js"
JSZip = require "jszip"
class @Session
constructor:(@server,@socket)->
#console.info "new session"
@content = @server.content
return @socket.close() if not @content?
@translator = @content.translator.getTranslator("en")
@user = null
@token = null
@checkCookie()
@last_active = Date.now()
@socket.on "message",(msg)=>
#console.info "received msg: #{msg}"
@messageReceived msg
@last_active = Date.now()
@socket.on "close",()=>
@server.sessionClosed @
@disconnected()
@socket.on "error",(err)=>
if @user
console.error "WS ERROR for user #{@user.id} - #{@user.nick}"
else
console.error "WS ERROR"
console.error err
@commands = {}
@register "ping",(msg)=>
@send({name:"pong"})
@checkUpdates()
@register "create_account",(msg)=>@createAccount(msg)
@register "create_guest",(msg)=>@createGuestAccount(msg)
@register "login",(msg)=>@login(msg)
@register "send_password_recovery",(msg)=>@sendPasswordRecovery(msg)
@register "token",(msg)=>@checkToken(msg)
@register "delete_guest",(msg)=>@deleteGuest(msg)
@register "send_validation_mail",(msg)=>@sendValidationMail(msg)
@register "change_email",(msg)=>@changeEmail(msg)
@register "change_nick",(msg)=>@changeNick(msg)
@register "change_password",(msg)=>@changePassword(msg)
@register "change_newsletter",(msg)=>@changeNewsletter(msg)
@register "change_experimental",(msg)=>@changeExperimental(msg)
@register "set_user_setting",(msg)=>@setUserSetting(msg)
@register "set_user_profile",(msg)=>@setUserProfile(msg)
@register "create_project",(msg)=>@createProject(msg)
@register "import_project",(msg)=>@importProject(msg)
@register "set_project_option",(msg)=>@setProjectOption(msg)
@register "set_project_public",(msg)=>@setProjectPublic(msg)
@register "set_project_tags",(msg)=>@setProjectTags(msg)
@register "delete_project",(msg)=>@deleteProject(msg)
@register "get_project_list",(msg)=>@getProjectList(msg)
@register "update_code",(msg)=>@updateCode(msg)
@register "lock_project_file",(msg)=>@lockProjectFile(msg)
@register "write_project_file",(msg)=>@writeProjectFile(msg)
@register "read_project_file",(msg)=>@readProjectFile(msg)
@register "rename_project_file",(msg)=>@renameProjectFile(msg)
@register "delete_project_file",(msg)=>@deleteProjectFile(msg)
@register "list_project_files",(msg)=>@listProjectFiles(msg)
@register "list_public_project_files",(msg)=>@listPublicProjectFiles(msg)
@register "read_public_project_file",(msg)=>@readPublicProjectFile(msg)
@register "listen_to_project",(msg)=>@listenToProject(msg)
@register "get_file_versions",(msg)=>@getFileVersions(msg)
@register "invite_to_project",(msg)=>@inviteToProject(msg)
@register "accept_invite",(msg)=>@acceptInvite(msg)
@register "remove_project_user",(msg)=>@removeProjectUser(msg)
@register "get_public_projects",(msg)=>@getPublicProjects(msg)
@register "get_public_project",(msg)=>@getPublicProject(msg)
@register "clone_project",(msg)=>@cloneProject(msg)
@register "clone_public_project",(msg)=>@clonePublicProject(msg)
@register "toggle_like",(msg)=>@toggleLike(msg)
@register "get_language",(msg)=>@getLanguage(msg)
@register "get_translation_list",(msg)=>@getTranslationList(msg)
@register "set_translation",(msg)=>@setTranslation(msg)
@register "add_translation",(msg)=>@addTranslation(msg)
@register "get_project_comments",(msg)=>@getProjectComments(msg)
@register "add_project_comment",(msg)=>@addProjectComment(msg)
@register "delete_project_comment",(msg)=>@deleteProjectComment(msg)
@register "edit_project_comment",(msg)=>@editProjectComment(msg)
@register "build_project",(msg)=>@buildProject(msg)
@register "get_build_status",(msg)=>@getBuildStatus(msg)
@register "start_builder",(msg)=>@startBuilder(msg)
@register "backup_complete",(msg)=>@backupComplete(msg)
@register "upload_request",(msg)=>@uploadRequest(msg)
@register "tutorial_completed",(msg)=>@tutorialCompleted(msg)
for plugin in @server.plugins
if plugin.registerSessionMessages?
plugin.registerSessionMessages @
@forum_session = new ForumSession @
@reserved_nicks =
"admin":true
"api":true
"static":true
"blog":true
"news":true
"about":true
"discord":true
"article":true
"forum": true
"community":true
checkCookie:()->
try
cookie = @socket.request.headers.cookie
if cookie? and cookie.indexOf("token")>=0
cookie = cookie.split("token")[1]
cookie = cookie.split("=")[1]
if cookie?
cookie = cookie.split(";")[0]
@token = cookie.trim()
@token = @content.findToken @token
if @token?
@user = @token.user
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
flags: if not @user.flags.censored then @user.flags else []
info: @getUserInfo()
settings: @user.settings
@user.set "last_active",Date.now()
@logActiveUser()
catch error
console.error error
logActiveUser:()->
return if not @user?
if @user.flags.guest
@server.stats.unique("active_guests",@user.id)
else
@server.stats.unique("active_users",@user.id)
register:(name,callback)->
@commands[name] = callback
disconnected:()->
try
if @project? and @project.manager?
@project.manager.removeSession @
@project.manager.removeListener @
if @user?
@user.removeListener @
catch err
console.error err
setCurrentProject:(project)->
if project != @project or not @project.manager?
if @project? and @project.manager?
@project.manager.removeSession @
@project = project
if not @project.manager?
new ProjectManager @project
@project.manager.addUser @
messageReceived:(msg)->
if typeof msg != "string"
return @bufferReceived msg
#console.info msg
try
msg = JSON.parse msg
if msg.name?
c = @commands[msg.name]
c(msg) if c?
catch err
console.info err
@server.stats.inc("websocket_requests")
@logActiveUser() if @user?
sendCodeUpdated:(file,code)->
@send
name: "code_updated"
file: file
code: code
return
sendProjectFileUpdated:(type,file,version,data,properties)->
@send
name: "project_file_updated"
type: type
file: file
version: version
data: data
properties: properties
sendProjectFileDeleted:(type,file)->
@send
name: "project_file_deleted"
type: type
file: file
createGuestAccount:(data)->
return if not @server.rate_limiter.accept("create_account_ip",@socket.remoteAddress)
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
loop
nick = ""
for i in [0..9] by 1
nick += chars.charAt(Math.floor(Math.random()*chars.length))
break if not @content.findUserByNick(nick)
@user = @content.createUser
nick: nick
flags: { guest: true }
language: data.language
date_created: Date.now()
last_active: Date.now()
creation_ip: @socket.remoteAddress
@user.addListener @
@send
name:"guest_created"
nick: nick
flags: @user.flags
info: @getUserInfo()
settings: @user.settings
token: @content.createToken(@user).value
request_id: data.request_id
@logActiveUser()
deleteGuest:(data)->
if @user? and @user.flags.guest
@user.delete()
@send
name:"guest_deleted"
request_id: data.request_id
createAccount:(data)->
return @sendError(@translator.get("email not specified"),data.request_id) if not data.email?
return @sendError(@translator.get("nickname not specified"),data.request_id) if not data.nick?
return @sendError(@translator.get("password not specified"),data.request_id) if not data.password?
return @sendError(@translator.get("email already exists"),data.request_id) if @content.findUserByEmail(data.email)
return @sendError(@translator.get("nickname already exists"),data.request_id) if @content.findUserByNick(data.nick)
return @sendError(@translator.get("nickname already exists"),data.request_id) if @reserved_nicks[data.nick]
return @sendError(@translator.get("Incorrect nickname. Use 5 characters minimum, only letters, numbers or _"),data.request_id) if not RegexLib.nick.test(data.nick)
return @sendError(@translator.get("Incorrect e-mail address"),data.request_id) if not RegexLib.email.test(data.email)
return @sendError(@translator.get("Password too weak"),data.request_id) if data.password.trim().length<6
return if not @server.rate_limiter.accept("create_account_ip",@socket.remoteAddress)
salt = ""
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for i in [0..15] by 1
salt += chars.charAt(Math.floor(Math.random()*chars.length))
hash = salt+"|"+SHA256(salt+data.password)
if @user? and @user.flags.guest
@server.content.changeUserNick @user,data.nick
@server.content.changeUserEmail @user,data.email
@user.setFlag("guest",false)
@user.setFlag("newsletter",data.newsletter)
@user.set("hash",hash)
@user.resetValidationToken()
else
@user = @content.createUser
nick: data.nick
email: data.email
flags: { newsletter: data.newsletter }
language: data.language
hash: hash
date_created: Date.now()
last_active: Date.now()
creation_ip: @socket.remoteAddress
@user.addListener @
@send
name:"account_created"
nick: data.nick
email: data.email
flags: @user.flags
info: @getUserInfo()
settings: @user.settings
notifications: [@server.content.translator.getTranslator(data.language).get("Account created successfully!")]
token: @content.createToken(@user).value
request_id: data.request_id
@sendValidationMail()
@logActiveUser()
login:(data)->
return if not data.nick?
return if not @server.rate_limiter.accept("login_ip",@socket.remoteAddress)
return if not @server.rate_limiter.accept("login_user",data.nick)
user = @content.findUserByNick data.nick
if not user?
user = @content.findUserByEmail data.nick
if user? and user.hash?
hash = user.hash
s = hash.split("|")
h = SHA256(s[0]+data.password)
#console.info "salt: #{s[0]}"
#console.info "hash: #{h}"
#console.info "recorded hash: #{s[1]}"
if h.toString() == s[1]
@user = user
@user.addListener @
@send
name:"logged_in"
token: @content.createToken(@user).value
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@logActiveUser()
else
@sendError "wrong password",data.request_id
else
@sendError "unknown user",data.request_id
getUserInfo:()->
return
size: @user.getTotalSize()
early_access: @user.early_access
max_storage: @user.max_storage
description: @user.description
stats: @user.progress.exportStats()
achievements: @user.progress.exportAchievements()
sendPasswordRecovery:(data)->
if data.email?
user = @content.findUserByEmail data.email
if user?
if @server.rate_limiter.accept("send_mail_user",user.id)
@server.content.sendPasswordRecoveryMail(user)
@send
name: "send_password_recovery"
request_id: data.request_id
checkToken:(data)->
if @server.config.standalone and @content.user_count == 1
@user = @server.content.users[0]
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@user.set "last_active",Date.now()
@logActiveUser()
token = @content.findToken data.token
if token?
@user = token.user
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@user.set "last_active",Date.now()
@logActiveUser()
else
@sendError "invalid token",data.request_id
send:(data)->
@socket.send JSON.stringify data
sendError:(error,request_id)->
@send
name: "error"
error: error
request_id: request_id
importProject:(data)->
return @sendError("Bad request") if not data.request_id?
return @sendError("not connected",data.request_id) if not @user?
return @sendError("Email validation is required",data.request_id) if @server.PROD and not @user.flags.validated
return @sendError("Rate limited",data.request_id) if not @server.rate_limiter.accept("import_project_user",@user.id)
#return @sendError("wrong data") if not data.zip_data? or typeof data.zip_data != "string"
#split = data.zip_data.split(",")
#return @sendError("unrecognized data") if not split[1]?
buffer = data.data #Buffer.from(split[1],'base64')
return @sendError("storage space exceeded",data.request_id) if buffer.byteLength>@user.max_storage-@user.getTotalSize()
zip = new JSZip
projectFileName = "project.json"
zip.loadAsync(buffer).then ((contents) =>
if not zip.file(projectFileName)?
@sendError("[ZIP] Missing #{projectFileName}; import aborted",data.request_id)
console.log "[ZIP] Missing #{projectFileName}; import aborted"
return
zip.file(projectFileName).async("string").then ((text) =>
try
projectInfo = JSON.parse(text)
catch err
@sendError("Incorrect JSON data",data.request_id)
console.error err
return
@content.createProject @user,projectInfo,((project)=>
@setCurrentProject project
project.manager.importFiles contents,()=>
project.set "files",projectInfo.files or {}
@send
name:"project_imported"
id: project.id
request_id: data.request_id
),true
),()=>
@sendError("Malformed ZIP file",data.request_id)
),()=>
@sendError("Malformed ZIP file",data.request_id)
createProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
@content.createProject @user,data,(project)=>
@send
name:"project_created"
id: project.id
request_id: data.request_id
clonePublicProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
return @sendError("") if not data.project?
project = @server.content.projects[data.project]
if project? and project.public
@content.createProject @user,{
title: project.title
slug: project.slug
public: false
},((clone)=>
clone.setType project.type
clone.setOrientation project.orientation
clone.setAspect project.aspect
clone.set "language",project.language
clone.setGraphics project.graphics
clone.set "libs",project.libs
clone.set "tabs",project.tabs
clone.set "files",JSON.parse JSON.stringify project.files
man = @getProjectManager(project)
folders = ["ms","sprites","maps","sounds","sounds_th","music","music_th","assets","assets_th","doc"]
files = []
funk = ()=>
if folders.length>0
folder = folders.splice(0,1)[0]
man.listFiles folder,(list)=>
for f in list
files.push
file: f.file
folder: folder
funk()
else if files.length>0
f = files.splice(0,1)[0]
src = "#{project.owner.id}/#{project.id}/#{f.folder}/#{f.file}"
dest = "#{clone.owner.id}/#{clone.id}/#{f.folder}/#{f.file}"
@server.content.files.copy src,dest,()=>
funk()
else
@send
name:"project_created"
id: clone.id
request_id: data.request_id
funk()),true
cloneProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
return @sendError("") if not data.project?
project = @server.content.projects[data.project]
if project?
manager = @getProjectManager project
if manager.canRead(@user)
@content.createProject @user,{
title: data.title or project.title
slug: project.slug
public: false
},((clone)=>
clone.setType project.type
clone.setOrientation project.orientation
clone.setAspect project.aspect
clone.set "language",project.language
clone.setGraphics project.graphics
clone.set "libs",project.libs
clone.set "tabs",project.tabs
clone.set "files",JSON.parse JSON.stringify project.files
man = @getProjectManager(project)
folders = ["ms","sprites","maps","sounds","sounds_th","music","music_th","assets","assets_th","doc"]
files = []
funk = ()=>
if folders.length>0
folder = folders.splice(0,1)[0]
man.listFiles folder,(list)=>
for f in list
files.push
file: f.file
folder: folder
funk()
else if files.length>0
f = files.splice(0,1)[0]
src = "#{project.owner.id}/#{project.id}/#{f.folder}/#{f.file}"
dest = "#{clone.owner.id}/#{clone.id}/#{f.folder}/#{f.file}"
@server.content.files.copy src,dest,()=>
funk()
else
@send
name:"project_created"
id: clone.id
request_id: data.request_id
funk()),true
getProjectManager:(project)->
if not project.manager?
new ProjectManager project
project.manager
setProjectPublic:(data)->
return @sendError("not connected") if not @user?
return if data.public and not @user.flags["validated"]
if not data.project?
if @user.flags.admin and data.id
project = @content.projects[data.id]
if project?
@content.setProjectPublic(project,data.public)
@send
name:"set_project_public"
id: project.id
public: project.public
request_id: data.request_id
else
project = @user.findProject(data.project)
if project?
@content.setProjectPublic(project,data.public)
@send
name:"set_project_public"
id: project.id
public: project.public
request_id: data.request_id
setProjectTags:(data)->
return @sendError("not connected") if not @user?
return if data.public and not @user.flags["validated"]
return if not data.project?
project = @user.findProject(data.project)
if not project? and @user.flags.admin
project = @content.projects[data.project]
if project? and data.tags?
@content.setProjectTags(project,data.tags)
@send
name:"set_project_tags"
id: project.id
tags: project.tags
request_id: data.request_id
setProjectOption:(data)->
return @sendError("not connected") if not @user?
return @sendError("no value") if not data.value?
project = @user.findProject(data.project)
if project?
switch data.option
when "title"
if not project.setTitle data.value
@send
name:"error"
value: project.title
request_id: data.request_id
when "slug"
if not project.setSlug data.value
@send
name:"error"
value: project.slug
request_id: data.request_id
when "description"
project.set "description",data.value
when "code"
if not project.setCode data.value
@send
name:"error"
value: project.code
request_id: data.request_id
when "platforms"
project.setPlatforms data.value if Array.isArray data.value
when "libs"
if Array.isArray data.value
for v in data.value
return if typeof v != "string" or v.length>100 or data.value.length>20
project.set "libs",data.value
when "tabs"
if typeof data.value == "object"
project.set "tabs",data.value
when "type"
project.setType data.value if typeof data.value == "string"
when "orientation"
project.setOrientation data.value if typeof data.value == "string"
when "aspect"
project.setAspect data.value if typeof data.value == "string"
when "graphics"
project.setGraphics data.value if typeof data.value == "string"
when "unlisted"
project.set "unlisted",if data.value then true else false
when "language"
project.set "language",data.value
if project.manager?
project.manager.propagateOptions @
project.touch()
deleteProject:(data)->
return @sendError("not connected") if not @user?
project = @user.findProject(data.project)
if project?
@user.deleteProject project
@send
name:"project_deleted"
id: project.id
request_id: data.request_id
getProjectList:(data)->
return @sendError("not connected") if not @user?
source = @user.listProjects()
list = []
for p in source
if not p.deleted
list.push
id: p.id
owner:
id: p.owner.id
nick: p.owner.nick
title: p.title
slug: p.slug
code: p.code
description: p.description
tags: p.tags
poster: p.files? and p.files["sprites/poster.png"]?
platforms: p.platforms
controls: p.controls
type: p.type
orientation: p.orientation
aspect: p.aspect
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
date_created: p.date_created
last_modified: p.last_modified
public: p.public
unlisted: p.unlisted
size: p.getSize()
users: p.listUsers()
source = @user.listProjectLinks()
for link in source
if not link.project.deleted
p = link.project
list.push
id: p.id
owner:
id: p.owner.id
nick: p.owner.nick
accepted: link.accepted
title: p.title
slug: p.slug
code: p.code
description: p.description
tags: p.tags
poster: p.files? and p.files["sprites/poster.png"]?
platforms: p.platforms
controls: p.controls
type: p.type
orientation: p.orientation
aspect: p.aspect
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
date_created: p.date_created
last_modified: p.last_modified
public: p.public
unlisted: p.unlisted
users: p.listUsers()
@send
name: "project_list"
list: list
request_id: if data? then data.request_id else undefined
lockProjectFile:(data)->
return @sendError("not connected") if not @user?
#console.info JSON.stringify data
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.lockFile(@,data.file)
writeProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.writeProjectFile(@,data)
if typeof data.file == "string"
if data.file.startsWith "ms/"
@user.progress.recordTime "time_coding"
if data.characters?
@user.progress.incrementLimitedStat "characters_typed",data.characters
if data.lines?
@user.progress.incrementLimitedStat "lines_of_code",data.lines
@checkUpdates()
else if data.file.startsWith "sprites/"
@user.progress.recordTime "time_drawing"
if data.pixels?
@user.progress.incrementLimitedStat "pixels_drawn",data.pixels
@checkUpdates()
else if data.file.startsWith "maps/"
@user.progress.recordTime "time_mapping"
if data.cells?
@user.progress.incrementLimitedStat "map_cells_drawn",data.cells
@checkUpdates()
renameProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.renameProjectFile(@,data)
deleteProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.deleteProjectFile(@,data)
readProjectFile:(data)->
#console.info "session.readProjectFile "+JSON.stringify data
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.readProjectFile(@,data)
listProjectFiles:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.listProjectFiles @,data
listPublicProjectFiles:(data)->
project = @content.projects[data.project] if data.project?
if project?
manager = @getProjectManager project
manager.listProjectFiles @,data
readPublicProjectFile:(data)->
project = @content.projects[data.project] if data.project?
if project? and project.public
manager = @getProjectManager project
project.manager.readProjectFile(@,data)
listenToProject:(data)->
user = data.user
project = data.project
if user? and project?
user = @content.findUserByNick(user)
if user?
project = user.findProjectBySlug(project)
if project?
if @project? and @project.manager?
@project.manager.removeListener @
@project = project
new ProjectManager @project if not @project.manager?
@project.manager.addListener @
getFileVersions:(data)->
user = data.user
project = data.project
if user? and project?
user = @content.findUserByNick(user)
if user?
project = user.findProjectBySlug(project)
if project?
new ProjectManager project if not project.manager?
project.manager.getFileVersions (res)=>
@send
name: "project_file_versions"
data: res
request_id: data.request_id
getPublicProjects:(data)->
switch data.ranking
when "new"
source = @content.new_projects
when "top"
source = @content.top_projects
else
source = @content.hot_projects
list = []
for p,i in source
break if list.length>=300
if p.public and not p.deleted and not p.owner.flags.censored
list.push
id: p.id
title: p.title
description: p.description
poster: p.files? and p.files["sprites/poster.png"]?
type: p.type
tags: p.tags
slug: p.slug
owner: p.owner.nick
owner_info:
tier: p.owner.flags.tier
profile_image: p.owner.flags.profile_image
likes: p.likes
liked: @user? and @user.isLiked(p.id)
tags: p.tags
date_published: p.first_published
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
@send
name: "public_projects"
list: list
request_id: data.request_id
getPublicProject:(msg)->
owner = msg.owner
project = msg.project
if owner? and project?
owner = @content.findUserByNick(owner)
if owner?
p = owner.findProjectBySlug(project)
if p? and p.public
res =
id: p.id
title: p.title
description: p.description
poster: p.files? and p.files["sprites/poster.png"]?
type: p.type
tags: p.tags
slug: p.slug
owner: p.owner.nick
owner_info:
tier: p.owner.flags.tier
profile_image: p.owner.flags.profile_image
likes: p.likes
liked: @user? and @user.isLiked(p.id)
tags: p.tags
date_published: p.first_published
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
@send
name: "get_public_project"
project: res
request_id: msg.request_id
toggleLike:(data)->
return @sendError("not connected") if not @user?
return @sendError("not validated") if not @user.flags.validated
project = @content.projects[data.project]
if project?
if @user.isLiked(project.id)
@user.removeLike(project.id)
project.likes--
else
@user.addLike(project.id)
project.likes++
if project.likes>=5
project.owner.progress.unlockAchievement("community/5_likes")
@send
name:"project_likes"
likes: project.likes
liked: @user.isLiked(project.id)
request_id: data.request_id
inviteToProject:(data)->
return @sendError("not connected",data.request_id) if not @user?
user = @content.findUserByNick(data.user)
return @sendError("user not found",data.request_id) if not user?
project = @user.findProject(data.project)
return @sendError("project not found",data.request_id) if not project?
@setCurrentProject project
project.manager.inviteUser @,user
acceptInvite:(data)->
return @sendError("not connected") if not @user?
for link in @user.project_links
if link.project.id == data.project
link.accept()
@setCurrentProject link.project
if link.project.manager?
link.project.manager.propagateUserListChange()
for li in @user.listeners
li.getProjectList()
return
removeProjectUser:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
return @sendError("project not found",data.request_id) if not project?
nick = data.user
return if not nick?
user = @content.findUserByNick(nick)
return if @user != project.owner and @user != user
for link in project.users
if link? and link.user? and link.user.nick == nick
link.remove()
if @user == project.owner
@setCurrentProject project
else
@send
name:"project_link_deleted"
request_id: data.request_id
if project.manager?
project.manager.propagateUserListChange()
if user?
for li in user.listeners
li.getProjectList()
return
sendValidationMail:(data)->
return @sendError("not connected") if not @user?
if @server.rate_limiter.accept("send_mail_user",@user.id)
@server.content.sendValidationMail(@user)
if data?
@send
name:"send_validation_mail"
request_id: data.request_id
return
changeNick:(data)->
return if not @user?
return if not data.nick?
if not RegexLib.nick.test(data.nick)
@send
name: "error"
value: "Incorrect nickname"
request_id: data.request_id
else
if @server.content.findUserByNick(data.nick)? or @reserved_nicks[data.nick]
@send
name: "error"
value: "Nickname not available"
request_id: data.request_id
else
@server.content.changeUserNick @user,data.nick
@send
name: "change_nick"
nick: data.nick
request_id: data.request_id
changeEmail:(data)->
return if not @user?
return if not data.email?
if not RegexLib.email.test(data.email)
@send
name: "error"
value: "Incorrect email"
request_id: data.request_id
else
if @server.content.findUserByEmail(data.email)?
@send
name: "error"
value: "E-mail is already used for another account"
request_id: data.request_id
else
@user.setFlag "validated",false
@user.resetValidationToken()
@server.content.changeUserEmail @user,data.email
@sendValidationMail()
@send
name: "change_email"
email: data.email
request_id: data.request_id
changeNewsletter:(data)->
return if not @user?
@user.setFlag "newsletter",data.newsletter
@send
name: "change_newsletter"
newsletter: data.newsletter
request_id: data.request_id
changeExperimental:(data)->
return if not @user? or not @user.flags.validated
@user.setFlag "experimental",data.experimental
@send
name: "change_experimental"
experimental: data.experimental
request_id: data.request_id
setUserSetting:(data)->
return if not @user?
return if not data.setting? or not data.value?
@user.setSetting data.setting,data.value
setUserProfile:(data)->
return if not @user?
if data.image?
if data.image == 0
@user.setFlag "profile_image",false
else
file = "#{@user.id}/profile_image.png"
content = new Buffer(data.image,"base64")
@server.content.files.write file,content,()=>
@user.setFlag "profile_image",true
@send
name: "set_user_profile"
request_id: data.request_id
return
if data.description?
@user.set "description",data.description
@send
name: "set_user_profile"
request_id: data.request_id
getLanguage:(msg)->
return if not msg.language?
lang = @server.content.translator.languages[msg.language]
lang = if lang? then lang.export() else "{}"
@send
name: "get_language"
language: lang
request_id: msg.request_id
getTranslationList:(msg)->
@send
name: "get_translation_list"
list: @server.content.translator.list
request_id: msg.request_id
setTranslation:(msg)->
return if not @user?
lang = msg.language
return if not @user.flags["translator_"+lang]
source = msg.source
translation = msg.translation
if not @server.content.translator.languages[lang]
@server.content.translator.createLanguage(lang)
@server.content.translator.languages[lang].set(@user.id,source,translation)
addTranslation:(msg)->
return if not @user?
#return if not @user.flags.admin
source = msg.source
@server.content.translator.reference source
getProjectComments:(data)->
return if not data.project?
project = @content.projects[data.project] if data.project?
if project? and project.public
@send
name: "project_comments"
request_id: data.request_id
comments: project.comments.getAll()
addProjectComment:(data)->
return if not data.project?
return if not data.text?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user? and @user.flags.validated and not @user.flags.banned and not @user.flags.censored
return if not @server.rate_limiter.accept("post_comment_user",@user.id)
project.comments.add(@user,data.text)
@send
name: "add_project_comment"
request_id: data.request_id
deleteProjectComment:(data)->
return if not data.project?
return if not data.id?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user?
c = project.comments.get(data.id)
if c? and (c.user == @user or @user.flags.admin)
c.remove()
@send
name: "delete_project_comment"
request_id: data.request_id
editProjectComment:(data)->
return if not data.project?
return if not data.id?
return if not data.text?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user?
c = project.comments.get(data.id)
if c? and c.user == @user
c.edit(data.text)
@send
name: "edit_project_comment"
request_id: data.request_id
tutorialCompleted:(msg)->
return if not @user?
return if not msg.id? or typeof msg.id != "string"
return if not msg.id.startsWith("tutorials/")
@user.progress.unlockAchievement(msg.id)
@checkUpdates()
checkUpdates:()->
if @user?
if @user.progress.achievements_update != @achievements_update
@achievements_update = @user.progress.achievements_update
@sendAchievements()
if @user.progress.stats_update != @stats_update
@stats_update = @user.progress.stats_update
@sendUserStats()
sendAchievements:()->
return if not @user?
@send
name: "achievements"
achievements: @user.progress.exportAchievements()
sendUserStats:()->
return if not @user?
@send
name: "user_stats"
stats: @user.progress.exportStats()
buildProject:(msg)->
return @sendError("not connected") if not @user?
project = @content.projects[msg.project] if msg.project?
if project?
@setCurrentProject project
return if not project.manager.canWrite @user
return if not msg.target?
build = @server.build_manager.startBuild(project,msg.target)
@send
name: "build_project"
request_id: msg.request_id
build: if build? then build.export() else null
getBuildStatus:(msg)->
return @sendError("not connected") if not @user?
project = @content.projects[msg.project] if msg.project?
if project?
@setCurrentProject project
return if not project.manager.canWrite @user
return if not msg.target?
build = @server.build_manager.getBuildInfo(project,msg.target)
@send
name: "build_project"
request_id: msg.request_id
build: if build? then build.export() else null
active_target: @server.build_manager.hasBuilder msg.target
timeCheck:()->
if Date.now()>@last_active+5*60000 # 5 minutes prevents breaking large assets uploads
@socket.close()
@server.sessionClosed @
@socket.terminate()
if @upload_request_activity? and Date.now()>@upload_request_activity+60000
@upload_request_id = -1
@upload_request_buffers = []
startBuilder:(msg)->
if msg.target?
if msg.key == @server.config["builder-key"]
@server.sessionClosed @
@server.build_manager.registerBuilder @,msg.target
backupComplete:(msg)->
if msg.key == @server.config["backup-key"]
@server.sessionClosed @
@server.last_backup_time = Date.now()
uploadRequest:(msg)=>
return if not @user?
return @sendError "Bad request" if not msg.size?
return @sendError "Bad request" if not msg.request_id?
return @sendError "Bad request" if not msg.request?
return @sendError("Rate limited",msg.request_id) if not @server.rate_limiter.accept("file_upload_user",@user.id)
return @sendError "File size limit exceeded" if msg.size>100000000 # 100 Mb max
@upload_request_id = msg.request_id
@upload_request_size = msg.size
@upload_uploaded = 0
@upload_request_buffers = []
@upload_request_request = msg.request
@upload_request_activity = Date.now()
@send
name:"upload_request"
request_id: msg.request_id
bufferReceived:(buffer)=>
if buffer.byteLength>=4
id = buffer.readInt32LE(0)
if id == @upload_request_id
len = buffer.byteLength-4
if len>0 and @upload_uploaded<@upload_request_size
buf = Buffer.alloc(len)
buffer.copy buf,0,4,buffer.byteLength
@upload_request_buffers.push buf
@upload_uploaded += len
@upload_request_activity = Date.now()
if @upload_uploaded >= @upload_request_size
msg = @upload_request_request
buf = Buffer.alloc @upload_request_size
count = 0
for b in @upload_request_buffers
b.copy buf,count,0,b.byteLength
count += b.byteLength
msg.data = buf
msg.request_id = id
try
if msg.name?
c = @commands[msg.name]
c(msg) if c?
catch error
console.error error
else
@send
name:"next_chunk"
request_id: id
module.exports = @Session
| 195746 | SHA256 = require("crypto-js/sha256")
ProjectManager = require __dirname+"/projectmanager.js"
RegexLib = require __dirname+"/../../static/js/util/regexlib.js"
ForumSession = require __dirname+"/../forum/forumsession.js"
JSZip = require "jszip"
class @Session
constructor:(@server,@socket)->
#console.info "new session"
@content = @server.content
return @socket.close() if not @content?
@translator = @content.translator.getTranslator("en")
@user = null
@token = <PASSWORD>
@checkCookie()
@last_active = Date.now()
@socket.on "message",(msg)=>
#console.info "received msg: #{msg}"
@messageReceived msg
@last_active = Date.now()
@socket.on "close",()=>
@server.sessionClosed @
@disconnected()
@socket.on "error",(err)=>
if @user
console.error "WS ERROR for user #{@user.id} - #{@user.nick}"
else
console.error "WS ERROR"
console.error err
@commands = {}
@register "ping",(msg)=>
@send({name:"pong"})
@checkUpdates()
@register "create_account",(msg)=>@createAccount(msg)
@register "create_guest",(msg)=>@createGuestAccount(msg)
@register "login",(msg)=>@login(msg)
@register "send_password_recovery",(msg)=>@sendPasswordRecovery(msg)
@register "token",(msg)=>@checkToken(msg)
@register "delete_guest",(msg)=>@deleteGuest(msg)
@register "send_validation_mail",(msg)=>@sendValidationMail(msg)
@register "change_email",(msg)=>@changeEmail(msg)
@register "change_nick",(msg)=>@changeNick(msg)
@register "change_password",(msg)=>@changePassword(msg)
@register "change_newsletter",(msg)=>@changeNewsletter(msg)
@register "change_experimental",(msg)=>@changeExperimental(msg)
@register "set_user_setting",(msg)=>@setUserSetting(msg)
@register "set_user_profile",(msg)=>@setUserProfile(msg)
@register "create_project",(msg)=>@createProject(msg)
@register "import_project",(msg)=>@importProject(msg)
@register "set_project_option",(msg)=>@setProjectOption(msg)
@register "set_project_public",(msg)=>@setProjectPublic(msg)
@register "set_project_tags",(msg)=>@setProjectTags(msg)
@register "delete_project",(msg)=>@deleteProject(msg)
@register "get_project_list",(msg)=>@getProjectList(msg)
@register "update_code",(msg)=>@updateCode(msg)
@register "lock_project_file",(msg)=>@lockProjectFile(msg)
@register "write_project_file",(msg)=>@writeProjectFile(msg)
@register "read_project_file",(msg)=>@readProjectFile(msg)
@register "rename_project_file",(msg)=>@renameProjectFile(msg)
@register "delete_project_file",(msg)=>@deleteProjectFile(msg)
@register "list_project_files",(msg)=>@listProjectFiles(msg)
@register "list_public_project_files",(msg)=>@listPublicProjectFiles(msg)
@register "read_public_project_file",(msg)=>@readPublicProjectFile(msg)
@register "listen_to_project",(msg)=>@listenToProject(msg)
@register "get_file_versions",(msg)=>@getFileVersions(msg)
@register "invite_to_project",(msg)=>@inviteToProject(msg)
@register "accept_invite",(msg)=>@acceptInvite(msg)
@register "remove_project_user",(msg)=>@removeProjectUser(msg)
@register "get_public_projects",(msg)=>@getPublicProjects(msg)
@register "get_public_project",(msg)=>@getPublicProject(msg)
@register "clone_project",(msg)=>@cloneProject(msg)
@register "clone_public_project",(msg)=>@clonePublicProject(msg)
@register "toggle_like",(msg)=>@toggleLike(msg)
@register "get_language",(msg)=>@getLanguage(msg)
@register "get_translation_list",(msg)=>@getTranslationList(msg)
@register "set_translation",(msg)=>@setTranslation(msg)
@register "add_translation",(msg)=>@addTranslation(msg)
@register "get_project_comments",(msg)=>@getProjectComments(msg)
@register "add_project_comment",(msg)=>@addProjectComment(msg)
@register "delete_project_comment",(msg)=>@deleteProjectComment(msg)
@register "edit_project_comment",(msg)=>@editProjectComment(msg)
@register "build_project",(msg)=>@buildProject(msg)
@register "get_build_status",(msg)=>@getBuildStatus(msg)
@register "start_builder",(msg)=>@startBuilder(msg)
@register "backup_complete",(msg)=>@backupComplete(msg)
@register "upload_request",(msg)=>@uploadRequest(msg)
@register "tutorial_completed",(msg)=>@tutorialCompleted(msg)
for plugin in @server.plugins
if plugin.registerSessionMessages?
plugin.registerSessionMessages @
@forum_session = new ForumSession @
@reserved_nicks =
"admin":true
"api":true
"static":true
"blog":true
"news":true
"about":true
"discord":true
"article":true
"forum": true
"community":true
checkCookie:()->
try
cookie = @socket.request.headers.cookie
if cookie? and cookie.indexOf("token")>=0
cookie = cookie.split("token")[1]
cookie = cookie.split("=")[1]
if cookie?
cookie = cookie.split(";")[0]
@token = cookie.trim()
@token = @content.findToken @token
if @token?
@user = @token.user
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
flags: if not @user.flags.censored then @user.flags else []
info: @getUserInfo()
settings: @user.settings
@user.set "last_active",Date.now()
@logActiveUser()
catch error
console.error error
logActiveUser:()->
return if not @user?
if @user.flags.guest
@server.stats.unique("active_guests",@user.id)
else
@server.stats.unique("active_users",@user.id)
register:(name,callback)->
@commands[name] = callback
disconnected:()->
try
if @project? and @project.manager?
@project.manager.removeSession @
@project.manager.removeListener @
if @user?
@user.removeListener @
catch err
console.error err
setCurrentProject:(project)->
if project != @project or not @project.manager?
if @project? and @project.manager?
@project.manager.removeSession @
@project = project
if not @project.manager?
new ProjectManager @project
@project.manager.addUser @
messageReceived:(msg)->
if typeof msg != "string"
return @bufferReceived msg
#console.info msg
try
msg = JSON.parse msg
if msg.name?
c = @commands[msg.name]
c(msg) if c?
catch err
console.info err
@server.stats.inc("websocket_requests")
@logActiveUser() if @user?
sendCodeUpdated:(file,code)->
@send
name: "code_updated"
file: file
code: code
return
sendProjectFileUpdated:(type,file,version,data,properties)->
@send
name: "project_file_updated"
type: type
file: file
version: version
data: data
properties: properties
sendProjectFileDeleted:(type,file)->
@send
name: "project_file_deleted"
type: type
file: file
createGuestAccount:(data)->
return if not @server.rate_limiter.accept("create_account_ip",@socket.remoteAddress)
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
loop
nick = ""
for i in [0..9] by 1
nick += chars.charAt(Math.floor(Math.random()*chars.length))
break if not @content.findUserByNick(nick)
@user = @content.createUser
nick: nick
flags: { guest: true }
language: data.language
date_created: Date.now()
last_active: Date.now()
creation_ip: @socket.remoteAddress
@user.addListener @
@send
name:"guest_created"
nick: nick
flags: @user.flags
info: @getUserInfo()
settings: @user.settings
token: @content.createToken(@user).value
request_id: data.request_id
@logActiveUser()
deleteGuest:(data)->
if @user? and @user.flags.guest
@user.delete()
@send
name:"guest_deleted"
request_id: data.request_id
createAccount:(data)->
return @sendError(@translator.get("email not specified"),data.request_id) if not data.email?
return @sendError(@translator.get("nickname not specified"),data.request_id) if not data.nick?
return @sendError(@translator.get("password not specified"),data.request_id) if not data.password?
return @sendError(@translator.get("email already exists"),data.request_id) if @content.findUserByEmail(data.email)
return @sendError(@translator.get("nickname already exists"),data.request_id) if @content.findUserByNick(data.nick)
return @sendError(@translator.get("nickname already exists"),data.request_id) if @reserved_nicks[data.nick]
return @sendError(@translator.get("Incorrect nickname. Use 5 characters minimum, only letters, numbers or _"),data.request_id) if not RegexLib.nick.test(data.nick)
return @sendError(@translator.get("Incorrect e-mail address"),data.request_id) if not RegexLib.email.test(data.email)
return @sendError(@translator.get("Password too weak"),data.request_id) if data.password.trim().length<6
return if not @server.rate_limiter.accept("create_account_ip",@socket.remoteAddress)
salt = ""
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for i in [0..15] by 1
salt += chars.charAt(Math.floor(Math.random()*chars.length))
hash = salt+"|"+SHA256(salt+data.password)
if @user? and @user.flags.guest
@server.content.changeUserNick @user,data.nick
@server.content.changeUserEmail @user,data.email
@user.setFlag("guest",false)
@user.setFlag("newsletter",data.newsletter)
@user.set("hash",hash)
@user.resetValidationToken()
else
@user = @content.createUser
nick: data.nick
email: data.email
flags: { newsletter: data.newsletter }
language: data.language
hash: hash
date_created: Date.now()
last_active: Date.now()
creation_ip: @socket.remoteAddress
@user.addListener @
@send
name:"account_created"
nick: data.nick
email: data.email
flags: @user.flags
info: @getUserInfo()
settings: @user.settings
notifications: [@server.content.translator.getTranslator(data.language).get("Account created successfully!")]
token: @content.createToken(@user).value
request_id: data.request_id
@sendValidationMail()
@logActiveUser()
login:(data)->
return if not data.nick?
return if not @server.rate_limiter.accept("login_ip",@socket.remoteAddress)
return if not @server.rate_limiter.accept("login_user",data.nick)
user = @content.findUserByNick data.nick
if not user?
user = @content.findUserByEmail data.nick
if user? and user.hash?
hash = user.hash
s = hash.split("|")
h = SHA256(s[0]+data.password)
#console.info "salt: #{s[0]}"
#console.info "hash: #{h}"
#console.info "recorded hash: #{s[1]}"
if h.toString() == s[1]
@user = user
@user.addListener @
@send
name:"logged_in"
token: @content.createToken(@user).value
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@logActiveUser()
else
@sendError "wrong password",data.request_id
else
@sendError "unknown user",data.request_id
getUserInfo:()->
return
size: @user.getTotalSize()
early_access: @user.early_access
max_storage: @user.max_storage
description: @user.description
stats: @user.progress.exportStats()
achievements: @user.progress.exportAchievements()
sendPasswordRecovery:(data)->
if data.email?
user = @content.findUserByEmail data.email
if user?
if @server.rate_limiter.accept("send_mail_user",user.id)
@server.content.sendPasswordRecoveryMail(user)
@send
name: "send_password_recovery"
request_id: data.request_id
checkToken:(data)->
if @server.config.standalone and @content.user_count == 1
@user = @server.content.users[0]
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@user.set "last_active",Date.now()
@logActiveUser()
token = @content.findToken data.token
if token?
@user = token.user
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@user.set "last_active",Date.now()
@logActiveUser()
else
@sendError "invalid token",data.request_id
send:(data)->
@socket.send JSON.stringify data
sendError:(error,request_id)->
@send
name: "error"
error: error
request_id: request_id
importProject:(data)->
return @sendError("Bad request") if not data.request_id?
return @sendError("not connected",data.request_id) if not @user?
return @sendError("Email validation is required",data.request_id) if @server.PROD and not @user.flags.validated
return @sendError("Rate limited",data.request_id) if not @server.rate_limiter.accept("import_project_user",@user.id)
#return @sendError("wrong data") if not data.zip_data? or typeof data.zip_data != "string"
#split = data.zip_data.split(",")
#return @sendError("unrecognized data") if not split[1]?
buffer = data.data #Buffer.from(split[1],'base64')
return @sendError("storage space exceeded",data.request_id) if buffer.byteLength>@user.max_storage-@user.getTotalSize()
zip = new JSZip
projectFileName = "project.json"
zip.loadAsync(buffer).then ((contents) =>
if not zip.file(projectFileName)?
@sendError("[ZIP] Missing #{projectFileName}; import aborted",data.request_id)
console.log "[ZIP] Missing #{projectFileName}; import aborted"
return
zip.file(projectFileName).async("string").then ((text) =>
try
projectInfo = JSON.parse(text)
catch err
@sendError("Incorrect JSON data",data.request_id)
console.error err
return
@content.createProject @user,projectInfo,((project)=>
@setCurrentProject project
project.manager.importFiles contents,()=>
project.set "files",projectInfo.files or {}
@send
name:"project_imported"
id: project.id
request_id: data.request_id
),true
),()=>
@sendError("Malformed ZIP file",data.request_id)
),()=>
@sendError("Malformed ZIP file",data.request_id)
createProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
@content.createProject @user,data,(project)=>
@send
name:"project_created"
id: project.id
request_id: data.request_id
clonePublicProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
return @sendError("") if not data.project?
project = @server.content.projects[data.project]
if project? and project.public
@content.createProject @user,{
title: project.title
slug: project.slug
public: false
},((clone)=>
clone.setType project.type
clone.setOrientation project.orientation
clone.setAspect project.aspect
clone.set "language",project.language
clone.setGraphics project.graphics
clone.set "libs",project.libs
clone.set "tabs",project.tabs
clone.set "files",JSON.parse JSON.stringify project.files
man = @getProjectManager(project)
folders = ["ms","sprites","maps","sounds","sounds_th","music","music_th","assets","assets_th","doc"]
files = []
funk = ()=>
if folders.length>0
folder = folders.splice(0,1)[0]
man.listFiles folder,(list)=>
for f in list
files.push
file: f.file
folder: folder
funk()
else if files.length>0
f = files.splice(0,1)[0]
src = "#{project.owner.id}/#{project.id}/#{f.folder}/#{f.file}"
dest = "#{clone.owner.id}/#{clone.id}/#{f.folder}/#{f.file}"
@server.content.files.copy src,dest,()=>
funk()
else
@send
name:"project_created"
id: clone.id
request_id: data.request_id
funk()),true
cloneProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
return @sendError("") if not data.project?
project = @server.content.projects[data.project]
if project?
manager = @getProjectManager project
if manager.canRead(@user)
@content.createProject @user,{
title: data.title or project.title
slug: project.slug
public: false
},((clone)=>
clone.setType project.type
clone.setOrientation project.orientation
clone.setAspect project.aspect
clone.set "language",project.language
clone.setGraphics project.graphics
clone.set "libs",project.libs
clone.set "tabs",project.tabs
clone.set "files",JSON.parse JSON.stringify project.files
man = @getProjectManager(project)
folders = ["ms","sprites","maps","sounds","sounds_th","music","music_th","assets","assets_th","doc"]
files = []
funk = ()=>
if folders.length>0
folder = folders.splice(0,1)[0]
man.listFiles folder,(list)=>
for f in list
files.push
file: f.file
folder: folder
funk()
else if files.length>0
f = files.splice(0,1)[0]
src = "#{project.owner.id}/#{project.id}/#{f.folder}/#{f.file}"
dest = "#{clone.owner.id}/#{clone.id}/#{f.folder}/#{f.file}"
@server.content.files.copy src,dest,()=>
funk()
else
@send
name:"project_created"
id: clone.id
request_id: data.request_id
funk()),true
getProjectManager:(project)->
if not project.manager?
new ProjectManager project
project.manager
setProjectPublic:(data)->
return @sendError("not connected") if not @user?
return if data.public and not @user.flags["validated"]
if not data.project?
if @user.flags.admin and data.id
project = @content.projects[data.id]
if project?
@content.setProjectPublic(project,data.public)
@send
name:"set_project_public"
id: project.id
public: project.public
request_id: data.request_id
else
project = @user.findProject(data.project)
if project?
@content.setProjectPublic(project,data.public)
@send
name:"set_project_public"
id: project.id
public: project.public
request_id: data.request_id
setProjectTags:(data)->
return @sendError("not connected") if not @user?
return if data.public and not @user.flags["validated"]
return if not data.project?
project = @user.findProject(data.project)
if not project? and @user.flags.admin
project = @content.projects[data.project]
if project? and data.tags?
@content.setProjectTags(project,data.tags)
@send
name:"set_project_tags"
id: project.id
tags: project.tags
request_id: data.request_id
setProjectOption:(data)->
return @sendError("not connected") if not @user?
return @sendError("no value") if not data.value?
project = @user.findProject(data.project)
if project?
switch data.option
when "title"
if not project.setTitle data.value
@send
name:"error"
value: project.title
request_id: data.request_id
when "slug"
if not project.setSlug data.value
@send
name:"error"
value: project.slug
request_id: data.request_id
when "description"
project.set "description",data.value
when "code"
if not project.setCode data.value
@send
name:"error"
value: project.code
request_id: data.request_id
when "platforms"
project.setPlatforms data.value if Array.isArray data.value
when "libs"
if Array.isArray data.value
for v in data.value
return if typeof v != "string" or v.length>100 or data.value.length>20
project.set "libs",data.value
when "tabs"
if typeof data.value == "object"
project.set "tabs",data.value
when "type"
project.setType data.value if typeof data.value == "string"
when "orientation"
project.setOrientation data.value if typeof data.value == "string"
when "aspect"
project.setAspect data.value if typeof data.value == "string"
when "graphics"
project.setGraphics data.value if typeof data.value == "string"
when "unlisted"
project.set "unlisted",if data.value then true else false
when "language"
project.set "language",data.value
if project.manager?
project.manager.propagateOptions @
project.touch()
deleteProject:(data)->
return @sendError("not connected") if not @user?
project = @user.findProject(data.project)
if project?
@user.deleteProject project
@send
name:"project_deleted"
id: project.id
request_id: data.request_id
getProjectList:(data)->
return @sendError("not connected") if not @user?
source = @user.listProjects()
list = []
for p in source
if not p.deleted
list.push
id: p.id
owner:
id: p.owner.id
nick: p.owner.nick
title: p.title
slug: p.slug
code: p.code
description: p.description
tags: p.tags
poster: p.files? and p.files["sprites/poster.png"]?
platforms: p.platforms
controls: p.controls
type: p.type
orientation: p.orientation
aspect: p.aspect
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
date_created: p.date_created
last_modified: p.last_modified
public: p.public
unlisted: p.unlisted
size: p.getSize()
users: p.listUsers()
source = @user.listProjectLinks()
for link in source
if not link.project.deleted
p = link.project
list.push
id: p.id
owner:
id: p.owner.id
nick: p.owner.nick
accepted: link.accepted
title: p.title
slug: p.slug
code: p.code
description: p.description
tags: p.tags
poster: p.files? and p.files["sprites/poster.png"]?
platforms: p.platforms
controls: p.controls
type: p.type
orientation: p.orientation
aspect: p.aspect
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
date_created: p.date_created
last_modified: p.last_modified
public: p.public
unlisted: p.unlisted
users: p.listUsers()
@send
name: "project_list"
list: list
request_id: if data? then data.request_id else undefined
lockProjectFile:(data)->
return @sendError("not connected") if not @user?
#console.info JSON.stringify data
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.lockFile(@,data.file)
writeProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.writeProjectFile(@,data)
if typeof data.file == "string"
if data.file.startsWith "ms/"
@user.progress.recordTime "time_coding"
if data.characters?
@user.progress.incrementLimitedStat "characters_typed",data.characters
if data.lines?
@user.progress.incrementLimitedStat "lines_of_code",data.lines
@checkUpdates()
else if data.file.startsWith "sprites/"
@user.progress.recordTime "time_drawing"
if data.pixels?
@user.progress.incrementLimitedStat "pixels_drawn",data.pixels
@checkUpdates()
else if data.file.startsWith "maps/"
@user.progress.recordTime "time_mapping"
if data.cells?
@user.progress.incrementLimitedStat "map_cells_drawn",data.cells
@checkUpdates()
renameProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.renameProjectFile(@,data)
deleteProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.deleteProjectFile(@,data)
readProjectFile:(data)->
#console.info "session.readProjectFile "+JSON.stringify data
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.readProjectFile(@,data)
listProjectFiles:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.listProjectFiles @,data
listPublicProjectFiles:(data)->
project = @content.projects[data.project] if data.project?
if project?
manager = @getProjectManager project
manager.listProjectFiles @,data
readPublicProjectFile:(data)->
project = @content.projects[data.project] if data.project?
if project? and project.public
manager = @getProjectManager project
project.manager.readProjectFile(@,data)
listenToProject:(data)->
user = data.user
project = data.project
if user? and project?
user = @content.findUserByNick(user)
if user?
project = user.findProjectBySlug(project)
if project?
if @project? and @project.manager?
@project.manager.removeListener @
@project = project
new ProjectManager @project if not @project.manager?
@project.manager.addListener @
getFileVersions:(data)->
user = data.user
project = data.project
if user? and project?
user = @content.findUserByNick(user)
if user?
project = user.findProjectBySlug(project)
if project?
new ProjectManager project if not project.manager?
project.manager.getFileVersions (res)=>
@send
name: "project_file_versions"
data: res
request_id: data.request_id
getPublicProjects:(data)->
switch data.ranking
when "new"
source = @content.new_projects
when "top"
source = @content.top_projects
else
source = @content.hot_projects
list = []
for p,i in source
break if list.length>=300
if p.public and not p.deleted and not p.owner.flags.censored
list.push
id: p.id
title: p.title
description: p.description
poster: p.files? and p.files["sprites/poster.png"]?
type: p.type
tags: p.tags
slug: p.slug
owner: p.owner.nick
owner_info:
tier: p.owner.flags.tier
profile_image: p.owner.flags.profile_image
likes: p.likes
liked: @user? and @user.isLiked(p.id)
tags: p.tags
date_published: p.first_published
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
@send
name: "public_projects"
list: list
request_id: data.request_id
getPublicProject:(msg)->
owner = msg.owner
project = msg.project
if owner? and project?
owner = @content.findUserByNick(owner)
if owner?
p = owner.findProjectBySlug(project)
if p? and p.public
res =
id: p.id
title: p.title
description: p.description
poster: p.files? and p.files["sprites/poster.png"]?
type: p.type
tags: p.tags
slug: p.slug
owner: p.owner.nick
owner_info:
tier: p.owner.flags.tier
profile_image: p.owner.flags.profile_image
likes: p.likes
liked: @user? and @user.isLiked(p.id)
tags: p.tags
date_published: p.first_published
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
@send
name: "get_public_project"
project: res
request_id: msg.request_id
toggleLike:(data)->
return @sendError("not connected") if not @user?
return @sendError("not validated") if not @user.flags.validated
project = @content.projects[data.project]
if project?
if @user.isLiked(project.id)
@user.removeLike(project.id)
project.likes--
else
@user.addLike(project.id)
project.likes++
if project.likes>=5
project.owner.progress.unlockAchievement("community/5_likes")
@send
name:"project_likes"
likes: project.likes
liked: @user.isLiked(project.id)
request_id: data.request_id
inviteToProject:(data)->
return @sendError("not connected",data.request_id) if not @user?
user = @content.findUserByNick(data.user)
return @sendError("user not found",data.request_id) if not user?
project = @user.findProject(data.project)
return @sendError("project not found",data.request_id) if not project?
@setCurrentProject project
project.manager.inviteUser @,user
acceptInvite:(data)->
return @sendError("not connected") if not @user?
for link in @user.project_links
if link.project.id == data.project
link.accept()
@setCurrentProject link.project
if link.project.manager?
link.project.manager.propagateUserListChange()
for li in @user.listeners
li.getProjectList()
return
removeProjectUser:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
return @sendError("project not found",data.request_id) if not project?
nick = data.user
return if not nick?
user = @content.findUserByNick(nick)
return if @user != project.owner and @user != user
for link in project.users
if link? and link.user? and link.user.nick == nick
link.remove()
if @user == project.owner
@setCurrentProject project
else
@send
name:"project_link_deleted"
request_id: data.request_id
if project.manager?
project.manager.propagateUserListChange()
if user?
for li in user.listeners
li.getProjectList()
return
sendValidationMail:(data)->
return @sendError("not connected") if not @user?
if @server.rate_limiter.accept("send_mail_user",@user.id)
@server.content.sendValidationMail(@user)
if data?
@send
name:"send_validation_mail"
request_id: data.request_id
return
changeNick:(data)->
return if not @user?
return if not data.nick?
if not RegexLib.nick.test(data.nick)
@send
name: "error"
value: "Incorrect nickname"
request_id: data.request_id
else
if @server.content.findUserByNick(data.nick)? or @reserved_nicks[data.nick]
@send
name: "error"
value: "Nickname not available"
request_id: data.request_id
else
@server.content.changeUserNick @user,data.nick
@send
name: "change_nick"
nick: data.nick
request_id: data.request_id
changeEmail:(data)->
return if not @user?
return if not data.email?
if not RegexLib.email.test(data.email)
@send
name: "error"
value: "Incorrect email"
request_id: data.request_id
else
if @server.content.findUserByEmail(data.email)?
@send
name: "error"
value: "E-mail is already used for another account"
request_id: data.request_id
else
@user.setFlag "validated",false
@user.resetValidationToken()
@server.content.changeUserEmail @user,data.email
@sendValidationMail()
@send
name: "change_email"
email: data.email
request_id: data.request_id
changeNewsletter:(data)->
return if not @user?
@user.setFlag "newsletter",data.newsletter
@send
name: "change_newsletter"
newsletter: data.newsletter
request_id: data.request_id
changeExperimental:(data)->
return if not @user? or not @user.flags.validated
@user.setFlag "experimental",data.experimental
@send
name: "change_experimental"
experimental: data.experimental
request_id: data.request_id
setUserSetting:(data)->
return if not @user?
return if not data.setting? or not data.value?
@user.setSetting data.setting,data.value
setUserProfile:(data)->
return if not @user?
if data.image?
if data.image == 0
@user.setFlag "profile_image",false
else
file = "#{@user.id}/profile_image.png"
content = new Buffer(data.image,"base64")
@server.content.files.write file,content,()=>
@user.setFlag "profile_image",true
@send
name: "set_user_profile"
request_id: data.request_id
return
if data.description?
@user.set "description",data.description
@send
name: "set_user_profile"
request_id: data.request_id
getLanguage:(msg)->
return if not msg.language?
lang = @server.content.translator.languages[msg.language]
lang = if lang? then lang.export() else "{}"
@send
name: "get_language"
language: lang
request_id: msg.request_id
getTranslationList:(msg)->
@send
name: "get_translation_list"
list: @server.content.translator.list
request_id: msg.request_id
setTranslation:(msg)->
return if not @user?
lang = msg.language
return if not @user.flags["translator_"+lang]
source = msg.source
translation = msg.translation
if not @server.content.translator.languages[lang]
@server.content.translator.createLanguage(lang)
@server.content.translator.languages[lang].set(@user.id,source,translation)
addTranslation:(msg)->
return if not @user?
#return if not @user.flags.admin
source = msg.source
@server.content.translator.reference source
getProjectComments:(data)->
return if not data.project?
project = @content.projects[data.project] if data.project?
if project? and project.public
@send
name: "project_comments"
request_id: data.request_id
comments: project.comments.getAll()
addProjectComment:(data)->
return if not data.project?
return if not data.text?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user? and @user.flags.validated and not @user.flags.banned and not @user.flags.censored
return if not @server.rate_limiter.accept("post_comment_user",@user.id)
project.comments.add(@user,data.text)
@send
name: "add_project_comment"
request_id: data.request_id
deleteProjectComment:(data)->
return if not data.project?
return if not data.id?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user?
c = project.comments.get(data.id)
if c? and (c.user == @user or @user.flags.admin)
c.remove()
@send
name: "delete_project_comment"
request_id: data.request_id
editProjectComment:(data)->
return if not data.project?
return if not data.id?
return if not data.text?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user?
c = project.comments.get(data.id)
if c? and c.user == @user
c.edit(data.text)
@send
name: "edit_project_comment"
request_id: data.request_id
tutorialCompleted:(msg)->
return if not @user?
return if not msg.id? or typeof msg.id != "string"
return if not msg.id.startsWith("tutorials/")
@user.progress.unlockAchievement(msg.id)
@checkUpdates()
checkUpdates:()->
if @user?
if @user.progress.achievements_update != @achievements_update
@achievements_update = @user.progress.achievements_update
@sendAchievements()
if @user.progress.stats_update != @stats_update
@stats_update = @user.progress.stats_update
@sendUserStats()
sendAchievements:()->
return if not @user?
@send
name: "achievements"
achievements: @user.progress.exportAchievements()
sendUserStats:()->
return if not @user?
@send
name: "user_stats"
stats: @user.progress.exportStats()
buildProject:(msg)->
return @sendError("not connected") if not @user?
project = @content.projects[msg.project] if msg.project?
if project?
@setCurrentProject project
return if not project.manager.canWrite @user
return if not msg.target?
build = @server.build_manager.startBuild(project,msg.target)
@send
name: "build_project"
request_id: msg.request_id
build: if build? then build.export() else null
getBuildStatus:(msg)->
return @sendError("not connected") if not @user?
project = @content.projects[msg.project] if msg.project?
if project?
@setCurrentProject project
return if not project.manager.canWrite @user
return if not msg.target?
build = @server.build_manager.getBuildInfo(project,msg.target)
@send
name: "build_project"
request_id: msg.request_id
build: if build? then build.export() else null
active_target: @server.build_manager.hasBuilder msg.target
timeCheck:()->
if Date.now()>@last_active+5*60000 # 5 minutes prevents breaking large assets uploads
@socket.close()
@server.sessionClosed @
@socket.terminate()
if @upload_request_activity? and Date.now()>@upload_request_activity+60000
@upload_request_id = -1
@upload_request_buffers = []
startBuilder:(msg)->
if msg.target?
if msg.key == @server.config["builder-key"]
@server.sessionClosed @
@server.build_manager.registerBuilder @,msg.target
backupComplete:(msg)->
if msg.key == @server.config["backup-key"]
@server.sessionClosed @
@server.last_backup_time = Date.now()
uploadRequest:(msg)=>
return if not @user?
return @sendError "Bad request" if not msg.size?
return @sendError "Bad request" if not msg.request_id?
return @sendError "Bad request" if not msg.request?
return @sendError("Rate limited",msg.request_id) if not @server.rate_limiter.accept("file_upload_user",@user.id)
return @sendError "File size limit exceeded" if msg.size>100000000 # 100 Mb max
@upload_request_id = msg.request_id
@upload_request_size = msg.size
@upload_uploaded = 0
@upload_request_buffers = []
@upload_request_request = msg.request
@upload_request_activity = Date.now()
@send
name:"upload_request"
request_id: msg.request_id
bufferReceived:(buffer)=>
if buffer.byteLength>=4
id = buffer.readInt32LE(0)
if id == @upload_request_id
len = buffer.byteLength-4
if len>0 and @upload_uploaded<@upload_request_size
buf = Buffer.alloc(len)
buffer.copy buf,0,4,buffer.byteLength
@upload_request_buffers.push buf
@upload_uploaded += len
@upload_request_activity = Date.now()
if @upload_uploaded >= @upload_request_size
msg = @upload_request_request
buf = Buffer.alloc @upload_request_size
count = 0
for b in @upload_request_buffers
b.copy buf,count,0,b.byteLength
count += b.byteLength
msg.data = buf
msg.request_id = id
try
if msg.name?
c = @commands[msg.name]
c(msg) if c?
catch error
console.error error
else
@send
name:"next_chunk"
request_id: id
module.exports = @Session
| true | SHA256 = require("crypto-js/sha256")
ProjectManager = require __dirname+"/projectmanager.js"
RegexLib = require __dirname+"/../../static/js/util/regexlib.js"
ForumSession = require __dirname+"/../forum/forumsession.js"
JSZip = require "jszip"
class @Session
constructor:(@server,@socket)->
#console.info "new session"
@content = @server.content
return @socket.close() if not @content?
@translator = @content.translator.getTranslator("en")
@user = null
@token = PI:PASSWORD:<PASSWORD>END_PI
@checkCookie()
@last_active = Date.now()
@socket.on "message",(msg)=>
#console.info "received msg: #{msg}"
@messageReceived msg
@last_active = Date.now()
@socket.on "close",()=>
@server.sessionClosed @
@disconnected()
@socket.on "error",(err)=>
if @user
console.error "WS ERROR for user #{@user.id} - #{@user.nick}"
else
console.error "WS ERROR"
console.error err
@commands = {}
@register "ping",(msg)=>
@send({name:"pong"})
@checkUpdates()
@register "create_account",(msg)=>@createAccount(msg)
@register "create_guest",(msg)=>@createGuestAccount(msg)
@register "login",(msg)=>@login(msg)
@register "send_password_recovery",(msg)=>@sendPasswordRecovery(msg)
@register "token",(msg)=>@checkToken(msg)
@register "delete_guest",(msg)=>@deleteGuest(msg)
@register "send_validation_mail",(msg)=>@sendValidationMail(msg)
@register "change_email",(msg)=>@changeEmail(msg)
@register "change_nick",(msg)=>@changeNick(msg)
@register "change_password",(msg)=>@changePassword(msg)
@register "change_newsletter",(msg)=>@changeNewsletter(msg)
@register "change_experimental",(msg)=>@changeExperimental(msg)
@register "set_user_setting",(msg)=>@setUserSetting(msg)
@register "set_user_profile",(msg)=>@setUserProfile(msg)
@register "create_project",(msg)=>@createProject(msg)
@register "import_project",(msg)=>@importProject(msg)
@register "set_project_option",(msg)=>@setProjectOption(msg)
@register "set_project_public",(msg)=>@setProjectPublic(msg)
@register "set_project_tags",(msg)=>@setProjectTags(msg)
@register "delete_project",(msg)=>@deleteProject(msg)
@register "get_project_list",(msg)=>@getProjectList(msg)
@register "update_code",(msg)=>@updateCode(msg)
@register "lock_project_file",(msg)=>@lockProjectFile(msg)
@register "write_project_file",(msg)=>@writeProjectFile(msg)
@register "read_project_file",(msg)=>@readProjectFile(msg)
@register "rename_project_file",(msg)=>@renameProjectFile(msg)
@register "delete_project_file",(msg)=>@deleteProjectFile(msg)
@register "list_project_files",(msg)=>@listProjectFiles(msg)
@register "list_public_project_files",(msg)=>@listPublicProjectFiles(msg)
@register "read_public_project_file",(msg)=>@readPublicProjectFile(msg)
@register "listen_to_project",(msg)=>@listenToProject(msg)
@register "get_file_versions",(msg)=>@getFileVersions(msg)
@register "invite_to_project",(msg)=>@inviteToProject(msg)
@register "accept_invite",(msg)=>@acceptInvite(msg)
@register "remove_project_user",(msg)=>@removeProjectUser(msg)
@register "get_public_projects",(msg)=>@getPublicProjects(msg)
@register "get_public_project",(msg)=>@getPublicProject(msg)
@register "clone_project",(msg)=>@cloneProject(msg)
@register "clone_public_project",(msg)=>@clonePublicProject(msg)
@register "toggle_like",(msg)=>@toggleLike(msg)
@register "get_language",(msg)=>@getLanguage(msg)
@register "get_translation_list",(msg)=>@getTranslationList(msg)
@register "set_translation",(msg)=>@setTranslation(msg)
@register "add_translation",(msg)=>@addTranslation(msg)
@register "get_project_comments",(msg)=>@getProjectComments(msg)
@register "add_project_comment",(msg)=>@addProjectComment(msg)
@register "delete_project_comment",(msg)=>@deleteProjectComment(msg)
@register "edit_project_comment",(msg)=>@editProjectComment(msg)
@register "build_project",(msg)=>@buildProject(msg)
@register "get_build_status",(msg)=>@getBuildStatus(msg)
@register "start_builder",(msg)=>@startBuilder(msg)
@register "backup_complete",(msg)=>@backupComplete(msg)
@register "upload_request",(msg)=>@uploadRequest(msg)
@register "tutorial_completed",(msg)=>@tutorialCompleted(msg)
for plugin in @server.plugins
if plugin.registerSessionMessages?
plugin.registerSessionMessages @
@forum_session = new ForumSession @
@reserved_nicks =
"admin":true
"api":true
"static":true
"blog":true
"news":true
"about":true
"discord":true
"article":true
"forum": true
"community":true
checkCookie:()->
try
cookie = @socket.request.headers.cookie
if cookie? and cookie.indexOf("token")>=0
cookie = cookie.split("token")[1]
cookie = cookie.split("=")[1]
if cookie?
cookie = cookie.split(";")[0]
@token = cookie.trim()
@token = @content.findToken @token
if @token?
@user = @token.user
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
flags: if not @user.flags.censored then @user.flags else []
info: @getUserInfo()
settings: @user.settings
@user.set "last_active",Date.now()
@logActiveUser()
catch error
console.error error
logActiveUser:()->
return if not @user?
if @user.flags.guest
@server.stats.unique("active_guests",@user.id)
else
@server.stats.unique("active_users",@user.id)
register:(name,callback)->
@commands[name] = callback
disconnected:()->
try
if @project? and @project.manager?
@project.manager.removeSession @
@project.manager.removeListener @
if @user?
@user.removeListener @
catch err
console.error err
setCurrentProject:(project)->
if project != @project or not @project.manager?
if @project? and @project.manager?
@project.manager.removeSession @
@project = project
if not @project.manager?
new ProjectManager @project
@project.manager.addUser @
messageReceived:(msg)->
if typeof msg != "string"
return @bufferReceived msg
#console.info msg
try
msg = JSON.parse msg
if msg.name?
c = @commands[msg.name]
c(msg) if c?
catch err
console.info err
@server.stats.inc("websocket_requests")
@logActiveUser() if @user?
sendCodeUpdated:(file,code)->
@send
name: "code_updated"
file: file
code: code
return
sendProjectFileUpdated:(type,file,version,data,properties)->
@send
name: "project_file_updated"
type: type
file: file
version: version
data: data
properties: properties
sendProjectFileDeleted:(type,file)->
@send
name: "project_file_deleted"
type: type
file: file
createGuestAccount:(data)->
return if not @server.rate_limiter.accept("create_account_ip",@socket.remoteAddress)
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
loop
nick = ""
for i in [0..9] by 1
nick += chars.charAt(Math.floor(Math.random()*chars.length))
break if not @content.findUserByNick(nick)
@user = @content.createUser
nick: nick
flags: { guest: true }
language: data.language
date_created: Date.now()
last_active: Date.now()
creation_ip: @socket.remoteAddress
@user.addListener @
@send
name:"guest_created"
nick: nick
flags: @user.flags
info: @getUserInfo()
settings: @user.settings
token: @content.createToken(@user).value
request_id: data.request_id
@logActiveUser()
deleteGuest:(data)->
if @user? and @user.flags.guest
@user.delete()
@send
name:"guest_deleted"
request_id: data.request_id
createAccount:(data)->
return @sendError(@translator.get("email not specified"),data.request_id) if not data.email?
return @sendError(@translator.get("nickname not specified"),data.request_id) if not data.nick?
return @sendError(@translator.get("password not specified"),data.request_id) if not data.password?
return @sendError(@translator.get("email already exists"),data.request_id) if @content.findUserByEmail(data.email)
return @sendError(@translator.get("nickname already exists"),data.request_id) if @content.findUserByNick(data.nick)
return @sendError(@translator.get("nickname already exists"),data.request_id) if @reserved_nicks[data.nick]
return @sendError(@translator.get("Incorrect nickname. Use 5 characters minimum, only letters, numbers or _"),data.request_id) if not RegexLib.nick.test(data.nick)
return @sendError(@translator.get("Incorrect e-mail address"),data.request_id) if not RegexLib.email.test(data.email)
return @sendError(@translator.get("Password too weak"),data.request_id) if data.password.trim().length<6
return if not @server.rate_limiter.accept("create_account_ip",@socket.remoteAddress)
salt = ""
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for i in [0..15] by 1
salt += chars.charAt(Math.floor(Math.random()*chars.length))
hash = salt+"|"+SHA256(salt+data.password)
if @user? and @user.flags.guest
@server.content.changeUserNick @user,data.nick
@server.content.changeUserEmail @user,data.email
@user.setFlag("guest",false)
@user.setFlag("newsletter",data.newsletter)
@user.set("hash",hash)
@user.resetValidationToken()
else
@user = @content.createUser
nick: data.nick
email: data.email
flags: { newsletter: data.newsletter }
language: data.language
hash: hash
date_created: Date.now()
last_active: Date.now()
creation_ip: @socket.remoteAddress
@user.addListener @
@send
name:"account_created"
nick: data.nick
email: data.email
flags: @user.flags
info: @getUserInfo()
settings: @user.settings
notifications: [@server.content.translator.getTranslator(data.language).get("Account created successfully!")]
token: @content.createToken(@user).value
request_id: data.request_id
@sendValidationMail()
@logActiveUser()
login:(data)->
return if not data.nick?
return if not @server.rate_limiter.accept("login_ip",@socket.remoteAddress)
return if not @server.rate_limiter.accept("login_user",data.nick)
user = @content.findUserByNick data.nick
if not user?
user = @content.findUserByEmail data.nick
if user? and user.hash?
hash = user.hash
s = hash.split("|")
h = SHA256(s[0]+data.password)
#console.info "salt: #{s[0]}"
#console.info "hash: #{h}"
#console.info "recorded hash: #{s[1]}"
if h.toString() == s[1]
@user = user
@user.addListener @
@send
name:"logged_in"
token: @content.createToken(@user).value
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@logActiveUser()
else
@sendError "wrong password",data.request_id
else
@sendError "unknown user",data.request_id
getUserInfo:()->
return
size: @user.getTotalSize()
early_access: @user.early_access
max_storage: @user.max_storage
description: @user.description
stats: @user.progress.exportStats()
achievements: @user.progress.exportAchievements()
sendPasswordRecovery:(data)->
if data.email?
user = @content.findUserByEmail data.email
if user?
if @server.rate_limiter.accept("send_mail_user",user.id)
@server.content.sendPasswordRecoveryMail(user)
@send
name: "send_password_recovery"
request_id: data.request_id
checkToken:(data)->
if @server.config.standalone and @content.user_count == 1
@user = @server.content.users[0]
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@user.set "last_active",Date.now()
@logActiveUser()
token = @content.findToken data.token
if token?
@user = token.user
@user.addListener @
@send
name: "token_valid"
nick: @user.nick
email: @user.email
flags: if not @user.flags.censored then @user.flags else {}
info: @getUserInfo()
settings: @user.settings
notifications: @user.notifications
request_id: data.request_id
@user.notifications = []
@user.set "last_active",Date.now()
@logActiveUser()
else
@sendError "invalid token",data.request_id
send:(data)->
@socket.send JSON.stringify data
sendError:(error,request_id)->
@send
name: "error"
error: error
request_id: request_id
importProject:(data)->
return @sendError("Bad request") if not data.request_id?
return @sendError("not connected",data.request_id) if not @user?
return @sendError("Email validation is required",data.request_id) if @server.PROD and not @user.flags.validated
return @sendError("Rate limited",data.request_id) if not @server.rate_limiter.accept("import_project_user",@user.id)
#return @sendError("wrong data") if not data.zip_data? or typeof data.zip_data != "string"
#split = data.zip_data.split(",")
#return @sendError("unrecognized data") if not split[1]?
buffer = data.data #Buffer.from(split[1],'base64')
return @sendError("storage space exceeded",data.request_id) if buffer.byteLength>@user.max_storage-@user.getTotalSize()
zip = new JSZip
projectFileName = "project.json"
zip.loadAsync(buffer).then ((contents) =>
if not zip.file(projectFileName)?
@sendError("[ZIP] Missing #{projectFileName}; import aborted",data.request_id)
console.log "[ZIP] Missing #{projectFileName}; import aborted"
return
zip.file(projectFileName).async("string").then ((text) =>
try
projectInfo = JSON.parse(text)
catch err
@sendError("Incorrect JSON data",data.request_id)
console.error err
return
@content.createProject @user,projectInfo,((project)=>
@setCurrentProject project
project.manager.importFiles contents,()=>
project.set "files",projectInfo.files or {}
@send
name:"project_imported"
id: project.id
request_id: data.request_id
),true
),()=>
@sendError("Malformed ZIP file",data.request_id)
),()=>
@sendError("Malformed ZIP file",data.request_id)
createProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
@content.createProject @user,data,(project)=>
@send
name:"project_created"
id: project.id
request_id: data.request_id
clonePublicProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
return @sendError("") if not data.project?
project = @server.content.projects[data.project]
if project? and project.public
@content.createProject @user,{
title: project.title
slug: project.slug
public: false
},((clone)=>
clone.setType project.type
clone.setOrientation project.orientation
clone.setAspect project.aspect
clone.set "language",project.language
clone.setGraphics project.graphics
clone.set "libs",project.libs
clone.set "tabs",project.tabs
clone.set "files",JSON.parse JSON.stringify project.files
man = @getProjectManager(project)
folders = ["ms","sprites","maps","sounds","sounds_th","music","music_th","assets","assets_th","doc"]
files = []
funk = ()=>
if folders.length>0
folder = folders.splice(0,1)[0]
man.listFiles folder,(list)=>
for f in list
files.push
file: f.file
folder: folder
funk()
else if files.length>0
f = files.splice(0,1)[0]
src = "#{project.owner.id}/#{project.id}/#{f.folder}/#{f.file}"
dest = "#{clone.owner.id}/#{clone.id}/#{f.folder}/#{f.file}"
@server.content.files.copy src,dest,()=>
funk()
else
@send
name:"project_created"
id: clone.id
request_id: data.request_id
funk()),true
cloneProject:(data)->
return @sendError("not connected") if not @user?
return if not @server.rate_limiter.accept("create_project_user",@user.id)
return @sendError("") if not data.project?
project = @server.content.projects[data.project]
if project?
manager = @getProjectManager project
if manager.canRead(@user)
@content.createProject @user,{
title: data.title or project.title
slug: project.slug
public: false
},((clone)=>
clone.setType project.type
clone.setOrientation project.orientation
clone.setAspect project.aspect
clone.set "language",project.language
clone.setGraphics project.graphics
clone.set "libs",project.libs
clone.set "tabs",project.tabs
clone.set "files",JSON.parse JSON.stringify project.files
man = @getProjectManager(project)
folders = ["ms","sprites","maps","sounds","sounds_th","music","music_th","assets","assets_th","doc"]
files = []
funk = ()=>
if folders.length>0
folder = folders.splice(0,1)[0]
man.listFiles folder,(list)=>
for f in list
files.push
file: f.file
folder: folder
funk()
else if files.length>0
f = files.splice(0,1)[0]
src = "#{project.owner.id}/#{project.id}/#{f.folder}/#{f.file}"
dest = "#{clone.owner.id}/#{clone.id}/#{f.folder}/#{f.file}"
@server.content.files.copy src,dest,()=>
funk()
else
@send
name:"project_created"
id: clone.id
request_id: data.request_id
funk()),true
getProjectManager:(project)->
if not project.manager?
new ProjectManager project
project.manager
setProjectPublic:(data)->
return @sendError("not connected") if not @user?
return if data.public and not @user.flags["validated"]
if not data.project?
if @user.flags.admin and data.id
project = @content.projects[data.id]
if project?
@content.setProjectPublic(project,data.public)
@send
name:"set_project_public"
id: project.id
public: project.public
request_id: data.request_id
else
project = @user.findProject(data.project)
if project?
@content.setProjectPublic(project,data.public)
@send
name:"set_project_public"
id: project.id
public: project.public
request_id: data.request_id
setProjectTags:(data)->
return @sendError("not connected") if not @user?
return if data.public and not @user.flags["validated"]
return if not data.project?
project = @user.findProject(data.project)
if not project? and @user.flags.admin
project = @content.projects[data.project]
if project? and data.tags?
@content.setProjectTags(project,data.tags)
@send
name:"set_project_tags"
id: project.id
tags: project.tags
request_id: data.request_id
setProjectOption:(data)->
return @sendError("not connected") if not @user?
return @sendError("no value") if not data.value?
project = @user.findProject(data.project)
if project?
switch data.option
when "title"
if not project.setTitle data.value
@send
name:"error"
value: project.title
request_id: data.request_id
when "slug"
if not project.setSlug data.value
@send
name:"error"
value: project.slug
request_id: data.request_id
when "description"
project.set "description",data.value
when "code"
if not project.setCode data.value
@send
name:"error"
value: project.code
request_id: data.request_id
when "platforms"
project.setPlatforms data.value if Array.isArray data.value
when "libs"
if Array.isArray data.value
for v in data.value
return if typeof v != "string" or v.length>100 or data.value.length>20
project.set "libs",data.value
when "tabs"
if typeof data.value == "object"
project.set "tabs",data.value
when "type"
project.setType data.value if typeof data.value == "string"
when "orientation"
project.setOrientation data.value if typeof data.value == "string"
when "aspect"
project.setAspect data.value if typeof data.value == "string"
when "graphics"
project.setGraphics data.value if typeof data.value == "string"
when "unlisted"
project.set "unlisted",if data.value then true else false
when "language"
project.set "language",data.value
if project.manager?
project.manager.propagateOptions @
project.touch()
deleteProject:(data)->
return @sendError("not connected") if not @user?
project = @user.findProject(data.project)
if project?
@user.deleteProject project
@send
name:"project_deleted"
id: project.id
request_id: data.request_id
getProjectList:(data)->
return @sendError("not connected") if not @user?
source = @user.listProjects()
list = []
for p in source
if not p.deleted
list.push
id: p.id
owner:
id: p.owner.id
nick: p.owner.nick
title: p.title
slug: p.slug
code: p.code
description: p.description
tags: p.tags
poster: p.files? and p.files["sprites/poster.png"]?
platforms: p.platforms
controls: p.controls
type: p.type
orientation: p.orientation
aspect: p.aspect
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
date_created: p.date_created
last_modified: p.last_modified
public: p.public
unlisted: p.unlisted
size: p.getSize()
users: p.listUsers()
source = @user.listProjectLinks()
for link in source
if not link.project.deleted
p = link.project
list.push
id: p.id
owner:
id: p.owner.id
nick: p.owner.nick
accepted: link.accepted
title: p.title
slug: p.slug
code: p.code
description: p.description
tags: p.tags
poster: p.files? and p.files["sprites/poster.png"]?
platforms: p.platforms
controls: p.controls
type: p.type
orientation: p.orientation
aspect: p.aspect
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
date_created: p.date_created
last_modified: p.last_modified
public: p.public
unlisted: p.unlisted
users: p.listUsers()
@send
name: "project_list"
list: list
request_id: if data? then data.request_id else undefined
lockProjectFile:(data)->
return @sendError("not connected") if not @user?
#console.info JSON.stringify data
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.lockFile(@,data.file)
writeProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.writeProjectFile(@,data)
if typeof data.file == "string"
if data.file.startsWith "ms/"
@user.progress.recordTime "time_coding"
if data.characters?
@user.progress.incrementLimitedStat "characters_typed",data.characters
if data.lines?
@user.progress.incrementLimitedStat "lines_of_code",data.lines
@checkUpdates()
else if data.file.startsWith "sprites/"
@user.progress.recordTime "time_drawing"
if data.pixels?
@user.progress.incrementLimitedStat "pixels_drawn",data.pixels
@checkUpdates()
else if data.file.startsWith "maps/"
@user.progress.recordTime "time_mapping"
if data.cells?
@user.progress.incrementLimitedStat "map_cells_drawn",data.cells
@checkUpdates()
renameProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.renameProjectFile(@,data)
deleteProjectFile:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.deleteProjectFile(@,data)
readProjectFile:(data)->
#console.info "session.readProjectFile "+JSON.stringify data
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.readProjectFile(@,data)
listProjectFiles:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
if project?
@setCurrentProject project
project.manager.listProjectFiles @,data
listPublicProjectFiles:(data)->
project = @content.projects[data.project] if data.project?
if project?
manager = @getProjectManager project
manager.listProjectFiles @,data
readPublicProjectFile:(data)->
project = @content.projects[data.project] if data.project?
if project? and project.public
manager = @getProjectManager project
project.manager.readProjectFile(@,data)
listenToProject:(data)->
user = data.user
project = data.project
if user? and project?
user = @content.findUserByNick(user)
if user?
project = user.findProjectBySlug(project)
if project?
if @project? and @project.manager?
@project.manager.removeListener @
@project = project
new ProjectManager @project if not @project.manager?
@project.manager.addListener @
getFileVersions:(data)->
user = data.user
project = data.project
if user? and project?
user = @content.findUserByNick(user)
if user?
project = user.findProjectBySlug(project)
if project?
new ProjectManager project if not project.manager?
project.manager.getFileVersions (res)=>
@send
name: "project_file_versions"
data: res
request_id: data.request_id
getPublicProjects:(data)->
switch data.ranking
when "new"
source = @content.new_projects
when "top"
source = @content.top_projects
else
source = @content.hot_projects
list = []
for p,i in source
break if list.length>=300
if p.public and not p.deleted and not p.owner.flags.censored
list.push
id: p.id
title: p.title
description: p.description
poster: p.files? and p.files["sprites/poster.png"]?
type: p.type
tags: p.tags
slug: p.slug
owner: p.owner.nick
owner_info:
tier: p.owner.flags.tier
profile_image: p.owner.flags.profile_image
likes: p.likes
liked: @user? and @user.isLiked(p.id)
tags: p.tags
date_published: p.first_published
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
@send
name: "public_projects"
list: list
request_id: data.request_id
getPublicProject:(msg)->
owner = msg.owner
project = msg.project
if owner? and project?
owner = @content.findUserByNick(owner)
if owner?
p = owner.findProjectBySlug(project)
if p? and p.public
res =
id: p.id
title: p.title
description: p.description
poster: p.files? and p.files["sprites/poster.png"]?
type: p.type
tags: p.tags
slug: p.slug
owner: p.owner.nick
owner_info:
tier: p.owner.flags.tier
profile_image: p.owner.flags.profile_image
likes: p.likes
liked: @user? and @user.isLiked(p.id)
tags: p.tags
date_published: p.first_published
graphics: p.graphics
language: p.language
libs: p.libs
tabs: p.tabs
@send
name: "get_public_project"
project: res
request_id: msg.request_id
toggleLike:(data)->
return @sendError("not connected") if not @user?
return @sendError("not validated") if not @user.flags.validated
project = @content.projects[data.project]
if project?
if @user.isLiked(project.id)
@user.removeLike(project.id)
project.likes--
else
@user.addLike(project.id)
project.likes++
if project.likes>=5
project.owner.progress.unlockAchievement("community/5_likes")
@send
name:"project_likes"
likes: project.likes
liked: @user.isLiked(project.id)
request_id: data.request_id
inviteToProject:(data)->
return @sendError("not connected",data.request_id) if not @user?
user = @content.findUserByNick(data.user)
return @sendError("user not found",data.request_id) if not user?
project = @user.findProject(data.project)
return @sendError("project not found",data.request_id) if not project?
@setCurrentProject project
project.manager.inviteUser @,user
acceptInvite:(data)->
return @sendError("not connected") if not @user?
for link in @user.project_links
if link.project.id == data.project
link.accept()
@setCurrentProject link.project
if link.project.manager?
link.project.manager.propagateUserListChange()
for li in @user.listeners
li.getProjectList()
return
removeProjectUser:(data)->
return @sendError("not connected") if not @user?
project = @content.projects[data.project] if data.project?
return @sendError("project not found",data.request_id) if not project?
nick = data.user
return if not nick?
user = @content.findUserByNick(nick)
return if @user != project.owner and @user != user
for link in project.users
if link? and link.user? and link.user.nick == nick
link.remove()
if @user == project.owner
@setCurrentProject project
else
@send
name:"project_link_deleted"
request_id: data.request_id
if project.manager?
project.manager.propagateUserListChange()
if user?
for li in user.listeners
li.getProjectList()
return
sendValidationMail:(data)->
return @sendError("not connected") if not @user?
if @server.rate_limiter.accept("send_mail_user",@user.id)
@server.content.sendValidationMail(@user)
if data?
@send
name:"send_validation_mail"
request_id: data.request_id
return
changeNick:(data)->
return if not @user?
return if not data.nick?
if not RegexLib.nick.test(data.nick)
@send
name: "error"
value: "Incorrect nickname"
request_id: data.request_id
else
if @server.content.findUserByNick(data.nick)? or @reserved_nicks[data.nick]
@send
name: "error"
value: "Nickname not available"
request_id: data.request_id
else
@server.content.changeUserNick @user,data.nick
@send
name: "change_nick"
nick: data.nick
request_id: data.request_id
changeEmail:(data)->
return if not @user?
return if not data.email?
if not RegexLib.email.test(data.email)
@send
name: "error"
value: "Incorrect email"
request_id: data.request_id
else
if @server.content.findUserByEmail(data.email)?
@send
name: "error"
value: "E-mail is already used for another account"
request_id: data.request_id
else
@user.setFlag "validated",false
@user.resetValidationToken()
@server.content.changeUserEmail @user,data.email
@sendValidationMail()
@send
name: "change_email"
email: data.email
request_id: data.request_id
changeNewsletter:(data)->
return if not @user?
@user.setFlag "newsletter",data.newsletter
@send
name: "change_newsletter"
newsletter: data.newsletter
request_id: data.request_id
changeExperimental:(data)->
return if not @user? or not @user.flags.validated
@user.setFlag "experimental",data.experimental
@send
name: "change_experimental"
experimental: data.experimental
request_id: data.request_id
setUserSetting:(data)->
return if not @user?
return if not data.setting? or not data.value?
@user.setSetting data.setting,data.value
setUserProfile:(data)->
return if not @user?
if data.image?
if data.image == 0
@user.setFlag "profile_image",false
else
file = "#{@user.id}/profile_image.png"
content = new Buffer(data.image,"base64")
@server.content.files.write file,content,()=>
@user.setFlag "profile_image",true
@send
name: "set_user_profile"
request_id: data.request_id
return
if data.description?
@user.set "description",data.description
@send
name: "set_user_profile"
request_id: data.request_id
getLanguage:(msg)->
return if not msg.language?
lang = @server.content.translator.languages[msg.language]
lang = if lang? then lang.export() else "{}"
@send
name: "get_language"
language: lang
request_id: msg.request_id
getTranslationList:(msg)->
@send
name: "get_translation_list"
list: @server.content.translator.list
request_id: msg.request_id
setTranslation:(msg)->
return if not @user?
lang = msg.language
return if not @user.flags["translator_"+lang]
source = msg.source
translation = msg.translation
if not @server.content.translator.languages[lang]
@server.content.translator.createLanguage(lang)
@server.content.translator.languages[lang].set(@user.id,source,translation)
addTranslation:(msg)->
return if not @user?
#return if not @user.flags.admin
source = msg.source
@server.content.translator.reference source
getProjectComments:(data)->
return if not data.project?
project = @content.projects[data.project] if data.project?
if project? and project.public
@send
name: "project_comments"
request_id: data.request_id
comments: project.comments.getAll()
addProjectComment:(data)->
return if not data.project?
return if not data.text?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user? and @user.flags.validated and not @user.flags.banned and not @user.flags.censored
return if not @server.rate_limiter.accept("post_comment_user",@user.id)
project.comments.add(@user,data.text)
@send
name: "add_project_comment"
request_id: data.request_id
deleteProjectComment:(data)->
return if not data.project?
return if not data.id?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user?
c = project.comments.get(data.id)
if c? and (c.user == @user or @user.flags.admin)
c.remove()
@send
name: "delete_project_comment"
request_id: data.request_id
editProjectComment:(data)->
return if not data.project?
return if not data.id?
return if not data.text?
project = @content.projects[data.project] if data.project?
if project? and project.public
if @user?
c = project.comments.get(data.id)
if c? and c.user == @user
c.edit(data.text)
@send
name: "edit_project_comment"
request_id: data.request_id
tutorialCompleted:(msg)->
return if not @user?
return if not msg.id? or typeof msg.id != "string"
return if not msg.id.startsWith("tutorials/")
@user.progress.unlockAchievement(msg.id)
@checkUpdates()
checkUpdates:()->
if @user?
if @user.progress.achievements_update != @achievements_update
@achievements_update = @user.progress.achievements_update
@sendAchievements()
if @user.progress.stats_update != @stats_update
@stats_update = @user.progress.stats_update
@sendUserStats()
sendAchievements:()->
return if not @user?
@send
name: "achievements"
achievements: @user.progress.exportAchievements()
sendUserStats:()->
return if not @user?
@send
name: "user_stats"
stats: @user.progress.exportStats()
buildProject:(msg)->
return @sendError("not connected") if not @user?
project = @content.projects[msg.project] if msg.project?
if project?
@setCurrentProject project
return if not project.manager.canWrite @user
return if not msg.target?
build = @server.build_manager.startBuild(project,msg.target)
@send
name: "build_project"
request_id: msg.request_id
build: if build? then build.export() else null
getBuildStatus:(msg)->
return @sendError("not connected") if not @user?
project = @content.projects[msg.project] if msg.project?
if project?
@setCurrentProject project
return if not project.manager.canWrite @user
return if not msg.target?
build = @server.build_manager.getBuildInfo(project,msg.target)
@send
name: "build_project"
request_id: msg.request_id
build: if build? then build.export() else null
active_target: @server.build_manager.hasBuilder msg.target
timeCheck:()->
if Date.now()>@last_active+5*60000 # 5 minutes prevents breaking large assets uploads
@socket.close()
@server.sessionClosed @
@socket.terminate()
if @upload_request_activity? and Date.now()>@upload_request_activity+60000
@upload_request_id = -1
@upload_request_buffers = []
startBuilder:(msg)->
if msg.target?
if msg.key == @server.config["builder-key"]
@server.sessionClosed @
@server.build_manager.registerBuilder @,msg.target
backupComplete:(msg)->
if msg.key == @server.config["backup-key"]
@server.sessionClosed @
@server.last_backup_time = Date.now()
uploadRequest:(msg)=>
return if not @user?
return @sendError "Bad request" if not msg.size?
return @sendError "Bad request" if not msg.request_id?
return @sendError "Bad request" if not msg.request?
return @sendError("Rate limited",msg.request_id) if not @server.rate_limiter.accept("file_upload_user",@user.id)
return @sendError "File size limit exceeded" if msg.size>100000000 # 100 Mb max
@upload_request_id = msg.request_id
@upload_request_size = msg.size
@upload_uploaded = 0
@upload_request_buffers = []
@upload_request_request = msg.request
@upload_request_activity = Date.now()
@send
name:"upload_request"
request_id: msg.request_id
bufferReceived:(buffer)=>
if buffer.byteLength>=4
id = buffer.readInt32LE(0)
if id == @upload_request_id
len = buffer.byteLength-4
if len>0 and @upload_uploaded<@upload_request_size
buf = Buffer.alloc(len)
buffer.copy buf,0,4,buffer.byteLength
@upload_request_buffers.push buf
@upload_uploaded += len
@upload_request_activity = Date.now()
if @upload_uploaded >= @upload_request_size
msg = @upload_request_request
buf = Buffer.alloc @upload_request_size
count = 0
for b in @upload_request_buffers
b.copy buf,count,0,b.byteLength
count += b.byteLength
msg.data = buf
msg.request_id = id
try
if msg.name?
c = @commands[msg.name]
c(msg) if c?
catch error
console.error error
else
@send
name:"next_chunk"
request_id: id
module.exports = @Session
|
[
{
"context": "nd displayed page numbers.\n * @function\n * @author İsmail Demirbilek\n###\nangular.module 'esef.frontend.pagination'\n .",
"end": 270,
"score": 0.9998948574066162,
"start": 253,
"tag": "NAME",
"value": "İsmail Demirbilek"
}
] | src/pagination/coffee/services/pagination.coffee | egemsoft/esef-frontend | 0 | 'use strict'
###*
* @ngdoc service
* @name esef.frontend.pagination.services:pagination
* @description
* Pagination helper service. Makes calculations for current page, offset fix, number of pages and displayed page numbers.
* @function
* @author İsmail Demirbilek
###
angular.module 'esef.frontend.pagination'
.factory 'pagination', ->
# public api
###*
* @ngdoc object
* @name getFixedOffset
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Fixes data offset if it is beyond the count + active page size.
* @param {number} offset - Data offset.
* @param {number} size - Number of entries displayed on each page.
* @param {number} count - Total data count.
* @return {number} - Fixed offset.
* @function
###
getFixedOffset: (offset, size, count) ->
if (count < (offset + size))
count - size
else
offset
###*
* @ngdoc object
* @name getNumberOfPages
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Returns total number of pages.
* @param {number} size - Number of entries displayed on each page.
* @param {number} count - Total data count.
* @return {number} - Number of pages.
* @function
###
getNumberOfPages: (size, count) ->
pages = Math.ceil count / size
if pages is 0
pages++
pages
###*
* @ngdoc object
* @name getCurrentPage
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Calculates and returns current page number.
* @param {number} offset - Data offset.
* @param {number} size - Number of entries displayed on each page.
* @param {number} totalPages - Total number of pages.
* @return {number} - Active page number.
* @function
###
getCurrentPage: (offset, size, totalPages) ->
currentPage = (offset / size) + 1
if currentPage > totalPages
totalPages
else currentPage
###*
* @ngdoc object
* @name getPages
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Calculates displayed page numbers and constructs them in an array.
* @param {number} currentPage - Active page number being displayed.
* @param {number} totalPages - Total number of pages.
* @param {number} paginationOffset - Number of pages to be displayed beginning from current page on left and right.
* @return {array} - Page numbers array.
* @function
###
getPages: (currentPage, totalPages, paginationOffset) ->
start = 1
end = totalPages
if currentPage < paginationOffset + 1
paginationOffset = paginationOffset + (paginationOffset - currentPage) + 1
else if totalPages - currentPage < paginationOffset + 1
paginationOffset = paginationOffset + (paginationOffset - (totalPages - currentPage))
if currentPage - paginationOffset > 0
start = currentPage - paginationOffset
if currentPage + paginationOffset < totalPages
end = currentPage + paginationOffset
(i for i in [start .. end]) | 216968 | 'use strict'
###*
* @ngdoc service
* @name esef.frontend.pagination.services:pagination
* @description
* Pagination helper service. Makes calculations for current page, offset fix, number of pages and displayed page numbers.
* @function
* @author <NAME>
###
angular.module 'esef.frontend.pagination'
.factory 'pagination', ->
# public api
###*
* @ngdoc object
* @name getFixedOffset
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Fixes data offset if it is beyond the count + active page size.
* @param {number} offset - Data offset.
* @param {number} size - Number of entries displayed on each page.
* @param {number} count - Total data count.
* @return {number} - Fixed offset.
* @function
###
getFixedOffset: (offset, size, count) ->
if (count < (offset + size))
count - size
else
offset
###*
* @ngdoc object
* @name getNumberOfPages
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Returns total number of pages.
* @param {number} size - Number of entries displayed on each page.
* @param {number} count - Total data count.
* @return {number} - Number of pages.
* @function
###
getNumberOfPages: (size, count) ->
pages = Math.ceil count / size
if pages is 0
pages++
pages
###*
* @ngdoc object
* @name getCurrentPage
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Calculates and returns current page number.
* @param {number} offset - Data offset.
* @param {number} size - Number of entries displayed on each page.
* @param {number} totalPages - Total number of pages.
* @return {number} - Active page number.
* @function
###
getCurrentPage: (offset, size, totalPages) ->
currentPage = (offset / size) + 1
if currentPage > totalPages
totalPages
else currentPage
###*
* @ngdoc object
* @name getPages
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Calculates displayed page numbers and constructs them in an array.
* @param {number} currentPage - Active page number being displayed.
* @param {number} totalPages - Total number of pages.
* @param {number} paginationOffset - Number of pages to be displayed beginning from current page on left and right.
* @return {array} - Page numbers array.
* @function
###
getPages: (currentPage, totalPages, paginationOffset) ->
start = 1
end = totalPages
if currentPage < paginationOffset + 1
paginationOffset = paginationOffset + (paginationOffset - currentPage) + 1
else if totalPages - currentPage < paginationOffset + 1
paginationOffset = paginationOffset + (paginationOffset - (totalPages - currentPage))
if currentPage - paginationOffset > 0
start = currentPage - paginationOffset
if currentPage + paginationOffset < totalPages
end = currentPage + paginationOffset
(i for i in [start .. end]) | true | 'use strict'
###*
* @ngdoc service
* @name esef.frontend.pagination.services:pagination
* @description
* Pagination helper service. Makes calculations for current page, offset fix, number of pages and displayed page numbers.
* @function
* @author PI:NAME:<NAME>END_PI
###
angular.module 'esef.frontend.pagination'
.factory 'pagination', ->
# public api
###*
* @ngdoc object
* @name getFixedOffset
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Fixes data offset if it is beyond the count + active page size.
* @param {number} offset - Data offset.
* @param {number} size - Number of entries displayed on each page.
* @param {number} count - Total data count.
* @return {number} - Fixed offset.
* @function
###
getFixedOffset: (offset, size, count) ->
if (count < (offset + size))
count - size
else
offset
###*
* @ngdoc object
* @name getNumberOfPages
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Returns total number of pages.
* @param {number} size - Number of entries displayed on each page.
* @param {number} count - Total data count.
* @return {number} - Number of pages.
* @function
###
getNumberOfPages: (size, count) ->
pages = Math.ceil count / size
if pages is 0
pages++
pages
###*
* @ngdoc object
* @name getCurrentPage
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Calculates and returns current page number.
* @param {number} offset - Data offset.
* @param {number} size - Number of entries displayed on each page.
* @param {number} totalPages - Total number of pages.
* @return {number} - Active page number.
* @function
###
getCurrentPage: (offset, size, totalPages) ->
currentPage = (offset / size) + 1
if currentPage > totalPages
totalPages
else currentPage
###*
* @ngdoc object
* @name getPages
* @methodOf esef.frontend.pagination.services:pagination
* @description
* Calculates displayed page numbers and constructs them in an array.
* @param {number} currentPage - Active page number being displayed.
* @param {number} totalPages - Total number of pages.
* @param {number} paginationOffset - Number of pages to be displayed beginning from current page on left and right.
* @return {array} - Page numbers array.
* @function
###
getPages: (currentPage, totalPages, paginationOffset) ->
start = 1
end = totalPages
if currentPage < paginationOffset + 1
paginationOffset = paginationOffset + (paginationOffset - currentPage) + 1
else if totalPages - currentPage < paginationOffset + 1
paginationOffset = paginationOffset + (paginationOffset - (totalPages - currentPage))
if currentPage - paginationOffset > 0
start = currentPage - paginationOffset
if currentPage + paginationOffset < totalPages
end = currentPage + paginationOffset
(i for i in [start .. end]) |
[
{
"context": " await @krb5.delprinc\n principal: \"nikita@#{krb5.realm}\"\n await @krb5.addprinc\n ",
"end": 1048,
"score": 0.9425027966499329,
"start": 1042,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": "it @krb5.delprinc\n principal: \"nikita@#{krb5.realm}\"\n await @krb5.addprinc\n principa",
"end": 1061,
"score": 0.8322897553443909,
"start": 1052,
"tag": "EMAIL",
"value": "rb5.realm"
},
{
"context": " await @krb5.addprinc\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n ",
"end": 1121,
"score": 0.9564145803451538,
"start": 1115,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": "it @krb5.addprinc\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n await ",
"end": 1134,
"score": 0.909572958946228,
"start": 1125,
"tag": "EMAIL",
"value": "rb5.realm"
},
{
"context": "ipal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n await @execute 'kdestroy'\n {$stat",
"end": 1168,
"score": 0.9992551207542419,
"start": 1158,
"tag": "PASSWORD",
"value": "myprecious"
},
{
"context": "tatus} = await @krb5.ticket\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n ",
"end": 1271,
"score": 0.9328317046165466,
"start": 1265,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": "wait @krb5.ticket\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n $statu",
"end": 1284,
"score": 0.8539628386497498,
"start": 1275,
"tag": "EMAIL",
"value": "rb5.realm"
},
{
"context": "ipal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n $status.should.be.true()\n {$statu",
"end": 1318,
"score": 0.9993083477020264,
"start": 1308,
"tag": "PASSWORD",
"value": "myprecious"
},
{
"context": "tatus} = await @krb5.ticket\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n $statu",
"end": 1433,
"score": 0.972548246383667,
"start": 1414,
"tag": "EMAIL",
"value": "nikita@#{krb5.realm"
},
{
"context": "ipal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n $status.should.be.false()\n await ",
"end": 1467,
"score": 0.9993165135383606,
"start": 1457,
"tag": "PASSWORD",
"value": "myprecious"
},
{
"context": " await @krb5.delprinc\n principal: \"nikita@#{krb5.realm}\"\n await @krb5.addprinc\n ",
"end": 1784,
"score": 0.9183027148246765,
"start": 1778,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": "it @krb5.delprinc\n principal: \"nikita@#{krb5.realm}\"\n await @krb5.addprinc\n principa",
"end": 1797,
"score": 0.7987133860588074,
"start": 1788,
"tag": "EMAIL",
"value": "rb5.realm"
},
{
"context": " await @krb5.addprinc\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n ",
"end": 1857,
"score": 0.924443781375885,
"start": 1851,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": "it @krb5.addprinc\n principal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n keyt",
"end": 1870,
"score": 0.8362250924110413,
"start": 1861,
"tag": "EMAIL",
"value": "rb5.realm"
},
{
"context": "ipal: \"nikita@#{krb5.realm}\"\n password: 'myprecious'\n keytab: \"#{tmpdir}/nikita.keytab\"\n ",
"end": 1904,
"score": 0.9992807507514954,
"start": 1894,
"tag": "PASSWORD",
"value": "myprecious"
},
{
"context": "tatus} = await @krb5.ticket\n principal: \"nikita@#{krb5.realm}\"\n keytab: \"#{tmpdir}/nikita.keytab\"\n ",
"end": 2064,
"score": 0.907189667224884,
"start": 2045,
"tag": "EMAIL",
"value": "nikita@#{krb5.realm"
},
{
"context": "tatus} = await @krb5.ticket\n principal: \"nikita@#{krb5.realm}\"\n keytab: \"#{tmpdir}/nikita.k",
"end": 2211,
"score": 0.8901950120925903,
"start": 2205,
"tag": "EMAIL",
"value": "nikita"
},
{
"context": "wait @krb5.ticket\n principal: \"nikita@#{krb5.realm}\"\n keytab: \"#{tmpdir}/nikita.keytab\"\n ",
"end": 2224,
"score": 0.8498600721359253,
"start": 2215,
"tag": "EMAIL",
"value": "rb5.realm"
}
] | packages/krb5/test/ticket.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config, krb5} = require './test'
they = require('mocha-they')(config)
return unless tags.krb5_addprinc
describe 'krb5.ticket', ->
describe 'schema', ->
it 'password or keytab must be provided', ->
nikita
krb5: admin: krb5
, ->
@krb5.ticket {}
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.ticket`:'
'#/oneOf config must match exactly one schema in oneOf, passingSchemas is null;'
'#/oneOf/0/required config must have required property \'keytab\';'
'#/oneOf/1/required config must have required property \'password\'.'
].join ' '
describe 'action', ->
they 'create a new ticket with password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "nikita@#{krb5.realm}"
await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'myprecious'
await @execute 'kdestroy'
{$status} = await @krb5.ticket
principal: "nikita@#{krb5.realm}"
password: 'myprecious'
$status.should.be.true()
{$status} = await @krb5.ticket
principal: "nikita@#{krb5.realm}"
password: 'myprecious'
$status.should.be.false()
await @execute
command: 'klist -s'
they 'create a new ticket with a keytab', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @krb5.delprinc
principal: "nikita@#{krb5.realm}"
await @krb5.addprinc
principal: "nikita@#{krb5.realm}"
password: 'myprecious'
keytab: "#{tmpdir}/nikita.keytab"
await @execute 'kdestroy'
{$status} = await @krb5.ticket
principal: "nikita@#{krb5.realm}"
keytab: "#{tmpdir}/nikita.keytab"
$status.should.be.true()
{$status} = await @krb5.ticket
principal: "nikita@#{krb5.realm}"
keytab: "#{tmpdir}/nikita.keytab"
$status.should.be.false()
await @execute
command: 'klist -s'
| 145430 |
nikita = require '@nikitajs/core/lib'
{tags, config, krb5} = require './test'
they = require('mocha-they')(config)
return unless tags.krb5_addprinc
describe 'krb5.ticket', ->
describe 'schema', ->
it 'password or keytab must be provided', ->
nikita
krb5: admin: krb5
, ->
@krb5.ticket {}
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.ticket`:'
'#/oneOf config must match exactly one schema in oneOf, passingSchemas is null;'
'#/oneOf/0/required config must have required property \'keytab\';'
'#/oneOf/1/required config must have required property \'password\'.'
].join ' '
describe 'action', ->
they 'create a new ticket with password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "<EMAIL>@#{k<EMAIL>}"
await @krb5.addprinc
principal: "<EMAIL>@#{k<EMAIL>}"
password: '<PASSWORD>'
await @execute 'kdestroy'
{$status} = await @krb5.ticket
principal: "<EMAIL>@#{k<EMAIL>}"
password: '<PASSWORD>'
$status.should.be.true()
{$status} = await @krb5.ticket
principal: "<EMAIL>}"
password: '<PASSWORD>'
$status.should.be.false()
await @execute
command: 'klist -s'
they 'create a new ticket with a keytab', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @krb5.delprinc
principal: "<EMAIL>@#{k<EMAIL>}"
await @krb5.addprinc
principal: "<EMAIL>@#{k<EMAIL>}"
password: '<PASSWORD>'
keytab: "#{tmpdir}/nikita.keytab"
await @execute 'kdestroy'
{$status} = await @krb5.ticket
principal: "<EMAIL>}"
keytab: "#{tmpdir}/nikita.keytab"
$status.should.be.true()
{$status} = await @krb5.ticket
principal: "<EMAIL>@#{k<EMAIL>}"
keytab: "#{tmpdir}/nikita.keytab"
$status.should.be.false()
await @execute
command: 'klist -s'
| true |
nikita = require '@nikitajs/core/lib'
{tags, config, krb5} = require './test'
they = require('mocha-they')(config)
return unless tags.krb5_addprinc
describe 'krb5.ticket', ->
describe 'schema', ->
it 'password or keytab must be provided', ->
nikita
krb5: admin: krb5
, ->
@krb5.ticket {}
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `krb5.ticket`:'
'#/oneOf config must match exactly one schema in oneOf, passingSchemas is null;'
'#/oneOf/0/required config must have required property \'keytab\';'
'#/oneOf/1/required config must have required property \'password\'.'
].join ' '
describe 'action', ->
they 'create a new ticket with password', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
, ->
await @krb5.delprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}"
await @krb5.addprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
await @execute 'kdestroy'
{$status} = await @krb5.ticket
principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
$status.should.be.true()
{$status} = await @krb5.ticket
principal: "PI:EMAIL:<EMAIL>END_PI}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
$status.should.be.false()
await @execute
command: 'klist -s'
they 'create a new ticket with a keytab', ({ssh}) ->
nikita
$ssh: ssh
krb5: admin: krb5
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @krb5.delprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}"
await @krb5.addprinc
principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}"
password: 'PI:PASSWORD:<PASSWORD>END_PI'
keytab: "#{tmpdir}/nikita.keytab"
await @execute 'kdestroy'
{$status} = await @krb5.ticket
principal: "PI:EMAIL:<EMAIL>END_PI}"
keytab: "#{tmpdir}/nikita.keytab"
$status.should.be.true()
{$status} = await @krb5.ticket
principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}"
keytab: "#{tmpdir}/nikita.keytab"
$status.should.be.false()
await @execute
command: 'klist -s'
|
[
{
"context": "n/env coffee\n#\n# cli.coffee\n#\n# Copyright (c) 2016 Junpei Kawamoto\n#\n# This software is released under the MIT Licen",
"end": 76,
"score": 0.9998316168785095,
"start": 61,
"tag": "NAME",
"value": "Junpei Kawamoto"
}
] | src/cli.coffee | jkawamoto/community-centre-search-fukuoka | 1 | #! /usr/bin/env coffee
#
# cli.coffee
#
# Copyright (c) 2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
yargs = require "yargs"
{area, building, institution, status} = require "../lib/scraper"
argv = yargs
.usage "Usage: $0 <command> [options]"
.command "area", "List up areas.", {}, (args) ->
area().then (res) ->
res.forEach (v)->
console.log v
.command "building", "List up buildings in an area.",
(yargs) ->
yargs.option "area",
rewuired: true
describe: "Name of area."
,
(args) ->
building(args.area).then (res) ->
res.forEach (v)->
console.log v
.command "institution", "List up institutions in a building",
(yargs) ->
yargs.option "area",
required: true
describe: "Name of area."
.option "building",
required: true
describe: "Name of building."
,
(args) ->
institution(args.area, args.building).then (res) ->
res.forEach (v)->
console.log v
.command "state", "Search reservation status.",
(yargs) ->
today = new Date()
yargs.option "area",
required: true
describe: "Name of area."
.option "building",
required: true
describe: "Name of building."
.option "institution",
required: true
describe: "Name of institution."
.option "year",
default: today.getFullYear()
describe: "Year."
.option "month",
default: today.getMonth() + 1
describe: "Month."
.option "day",
default: today.getDay() + 1
describe: "Day."
,
(args) ->
status args.area, args.building,
args.institution, args.year, args.month, args.day
.then (res) ->
console.log JSON.stringify res, null, " "
.help()
.argv
if argv._.length is 0
yargs.showHelp()
| 92469 | #! /usr/bin/env coffee
#
# cli.coffee
#
# Copyright (c) 2016 <NAME>
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
yargs = require "yargs"
{area, building, institution, status} = require "../lib/scraper"
argv = yargs
.usage "Usage: $0 <command> [options]"
.command "area", "List up areas.", {}, (args) ->
area().then (res) ->
res.forEach (v)->
console.log v
.command "building", "List up buildings in an area.",
(yargs) ->
yargs.option "area",
rewuired: true
describe: "Name of area."
,
(args) ->
building(args.area).then (res) ->
res.forEach (v)->
console.log v
.command "institution", "List up institutions in a building",
(yargs) ->
yargs.option "area",
required: true
describe: "Name of area."
.option "building",
required: true
describe: "Name of building."
,
(args) ->
institution(args.area, args.building).then (res) ->
res.forEach (v)->
console.log v
.command "state", "Search reservation status.",
(yargs) ->
today = new Date()
yargs.option "area",
required: true
describe: "Name of area."
.option "building",
required: true
describe: "Name of building."
.option "institution",
required: true
describe: "Name of institution."
.option "year",
default: today.getFullYear()
describe: "Year."
.option "month",
default: today.getMonth() + 1
describe: "Month."
.option "day",
default: today.getDay() + 1
describe: "Day."
,
(args) ->
status args.area, args.building,
args.institution, args.year, args.month, args.day
.then (res) ->
console.log JSON.stringify res, null, " "
.help()
.argv
if argv._.length is 0
yargs.showHelp()
| true | #! /usr/bin/env coffee
#
# cli.coffee
#
# Copyright (c) 2016 PI:NAME:<NAME>END_PI
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
yargs = require "yargs"
{area, building, institution, status} = require "../lib/scraper"
argv = yargs
.usage "Usage: $0 <command> [options]"
.command "area", "List up areas.", {}, (args) ->
area().then (res) ->
res.forEach (v)->
console.log v
.command "building", "List up buildings in an area.",
(yargs) ->
yargs.option "area",
rewuired: true
describe: "Name of area."
,
(args) ->
building(args.area).then (res) ->
res.forEach (v)->
console.log v
.command "institution", "List up institutions in a building",
(yargs) ->
yargs.option "area",
required: true
describe: "Name of area."
.option "building",
required: true
describe: "Name of building."
,
(args) ->
institution(args.area, args.building).then (res) ->
res.forEach (v)->
console.log v
.command "state", "Search reservation status.",
(yargs) ->
today = new Date()
yargs.option "area",
required: true
describe: "Name of area."
.option "building",
required: true
describe: "Name of building."
.option "institution",
required: true
describe: "Name of institution."
.option "year",
default: today.getFullYear()
describe: "Year."
.option "month",
default: today.getMonth() + 1
describe: "Month."
.option "day",
default: today.getDay() + 1
describe: "Day."
,
(args) ->
status args.area, args.building,
args.institution, args.year, args.month, args.day
.then (res) ->
console.log JSON.stringify res, null, " "
.help()
.argv
if argv._.length is 0
yargs.showHelp()
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.9998898506164551,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 96,
"score": 0.9999343752861023,
"start": 76,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
},
{
"context": "o/Component/Static/Tools')\n\n# Translator\n# @author Jessym Reziga <jessym@konsserto.com>\nclass Translator\n\n # Clas",
"end": 405,
"score": 0.9998936057090759,
"start": 392,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "ic/Tools')\n\n# Translator\n# @author Jessym Reziga <jessym@konsserto.com>\nclass Translator\n\n # Class constructor\n # @par",
"end": 427,
"score": 0.9999345541000366,
"start": 407,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Component/Translator/Translator.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
CONFIG = use('/app/config/config')
Finder = use('@Konsserto/Component/Finder/Finder')
Tools = use('@Konsserto/Component/Static/Tools')
# Translator
# @author Jessym Reziga <jessym@konsserto.com>
class Translator
# Class constructor
# @param {String} locale The locale language
# @param {Application} application The unique instance of application
constructor: (locale, @application) ->
@catalogues = {}
if locale?
@locale = locale
@loadCatalogues()
# @return {String} The locale of the application
getLocale: () ->
if CONFIG['locale']?
return CONFIG['locale']
return 'en'
# /!\ Have to do the documentation
trans: (id, parameters = {}, domain, locale = null) ->
if !locale?
locale = @getLocale()
if !domain?
domain = 'translations'
if !@catalogueHasDomainLocale(domain, locale)
return id
if @catalogues[domain][locale][id]?
id = @catalogues[domain][locale][id]
for key,value of parameters
eval('id = id.replace(/' + key + '/g,\'' + value + '\')')
return id
# Check if the catalogue has domain locale
# @param {String} domain The domain
# @param {String} locale The locale
# @return {Boolean} True if contains, false in the other cases
catalogueHasDomainLocale: (domain, locale)->
if @catalogues[domain]?
if @catalogues[domain][locale]?
return true
return false
#Load the languages catalogues
loadCatalogues: ()->
for bundleName,bundle of @application.getBundles()
domainsFiles = new Finder().files().notRecursive().in(bundle.getTranslationsPath()).ext('.js').end()
path = bundle.getTranslationsNamespace() + '/'
for file in domainsFiles
name = file.getName()
domainSpecs = name.split('.')
if domainSpecs.length == 3
currentDomain = domainSpecs[0]
currentLocale = domainSpecs[1]
@catalogues[currentDomain] = {} if !@catalogues[currentDomain]
@catalogues[currentDomain][currentLocale] = {} if !@catalogues[currentDomain][currentLocale]?
module = use(path + name)
@catalogues[currentDomain][currentLocale] = Tools.mergeObjects(@catalogues[currentDomain][currentLocale],
module, true)
@catalogues[currentDomain]['_fromBundle'] = bundleName
module.exports = Translator
| 98691 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
CONFIG = use('/app/config/config')
Finder = use('@Konsserto/Component/Finder/Finder')
Tools = use('@Konsserto/Component/Static/Tools')
# Translator
# @author <NAME> <<EMAIL>>
class Translator
# Class constructor
# @param {String} locale The locale language
# @param {Application} application The unique instance of application
constructor: (locale, @application) ->
@catalogues = {}
if locale?
@locale = locale
@loadCatalogues()
# @return {String} The locale of the application
getLocale: () ->
if CONFIG['locale']?
return CONFIG['locale']
return 'en'
# /!\ Have to do the documentation
trans: (id, parameters = {}, domain, locale = null) ->
if !locale?
locale = @getLocale()
if !domain?
domain = 'translations'
if !@catalogueHasDomainLocale(domain, locale)
return id
if @catalogues[domain][locale][id]?
id = @catalogues[domain][locale][id]
for key,value of parameters
eval('id = id.replace(/' + key + '/g,\'' + value + '\')')
return id
# Check if the catalogue has domain locale
# @param {String} domain The domain
# @param {String} locale The locale
# @return {Boolean} True if contains, false in the other cases
catalogueHasDomainLocale: (domain, locale)->
if @catalogues[domain]?
if @catalogues[domain][locale]?
return true
return false
#Load the languages catalogues
loadCatalogues: ()->
for bundleName,bundle of @application.getBundles()
domainsFiles = new Finder().files().notRecursive().in(bundle.getTranslationsPath()).ext('.js').end()
path = bundle.getTranslationsNamespace() + '/'
for file in domainsFiles
name = file.getName()
domainSpecs = name.split('.')
if domainSpecs.length == 3
currentDomain = domainSpecs[0]
currentLocale = domainSpecs[1]
@catalogues[currentDomain] = {} if !@catalogues[currentDomain]
@catalogues[currentDomain][currentLocale] = {} if !@catalogues[currentDomain][currentLocale]?
module = use(path + name)
@catalogues[currentDomain][currentLocale] = Tools.mergeObjects(@catalogues[currentDomain][currentLocale],
module, true)
@catalogues[currentDomain]['_fromBundle'] = bundleName
module.exports = Translator
| true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
CONFIG = use('/app/config/config')
Finder = use('@Konsserto/Component/Finder/Finder')
Tools = use('@Konsserto/Component/Static/Tools')
# Translator
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
class Translator
# Class constructor
# @param {String} locale The locale language
# @param {Application} application The unique instance of application
constructor: (locale, @application) ->
@catalogues = {}
if locale?
@locale = locale
@loadCatalogues()
# @return {String} The locale of the application
getLocale: () ->
if CONFIG['locale']?
return CONFIG['locale']
return 'en'
# /!\ Have to do the documentation
trans: (id, parameters = {}, domain, locale = null) ->
if !locale?
locale = @getLocale()
if !domain?
domain = 'translations'
if !@catalogueHasDomainLocale(domain, locale)
return id
if @catalogues[domain][locale][id]?
id = @catalogues[domain][locale][id]
for key,value of parameters
eval('id = id.replace(/' + key + '/g,\'' + value + '\')')
return id
# Check if the catalogue has domain locale
# @param {String} domain The domain
# @param {String} locale The locale
# @return {Boolean} True if contains, false in the other cases
catalogueHasDomainLocale: (domain, locale)->
if @catalogues[domain]?
if @catalogues[domain][locale]?
return true
return false
#Load the languages catalogues
loadCatalogues: ()->
for bundleName,bundle of @application.getBundles()
domainsFiles = new Finder().files().notRecursive().in(bundle.getTranslationsPath()).ext('.js').end()
path = bundle.getTranslationsNamespace() + '/'
for file in domainsFiles
name = file.getName()
domainSpecs = name.split('.')
if domainSpecs.length == 3
currentDomain = domainSpecs[0]
currentLocale = domainSpecs[1]
@catalogues[currentDomain] = {} if !@catalogues[currentDomain]
@catalogues[currentDomain][currentLocale] = {} if !@catalogues[currentDomain][currentLocale]?
module = use(path + name)
@catalogues[currentDomain][currentLocale] = Tools.mergeObjects(@catalogues[currentDomain][currentLocale],
module, true)
@catalogues[currentDomain]['_fromBundle'] = bundleName
module.exports = Translator
|
[
{
"context": " just turned our user into a subscribing customer. Chapeau!\n # Show some links so that we can fetch som",
"end": 3197,
"score": 0.9800167679786682,
"start": 3190,
"tag": "NAME",
"value": "Chapeau"
}
] | examples/express.coffee | jaybryant/paypal-recurring | 25 | # Demo application of the paypal-recurring package.
#
# If coffeescript confuses you, go wild with http://js2coffee.org/
#
# Do only use this for personal testing and make sure to
# use HTTPS on your own server when using the package in production.
#
# Enter your own credentials below, or you won't be able
# to run this demo.
#
# Obtain your very own API credentials at: https://developer.paypal.com
#
express = require 'express'
app = express()
Paypal = require '../'
#####
# ENTER YOUR CREDENTIALS HERE
#####
paypal = new Paypal
username: ""
password: ""
signature: ""
#####
# No need to edit anything below. The demo should run itself.
#####
app.get "/", (req, res) ->
res.send '<a href="/purchase/buy">Click here to do a demo subscription</a> <br/><br/>
Make sure to have your test account credentials at hands - click
<a href="https://developer.paypal.com/">here</a> to obtain such
if you haven\'t already done so.'
app.get "/purchase/buy", (req, res) ->
# We want to create a demo subscription to learn how this
# works, so as we run this script at port 3000 on localhost,
# we can pass below URL's as RETURNURL and CANCELURL to PayPal accordingly.
#
# L_BILLINGAGREEMENTDESCRIPTION0 could be just anything but must stay the same
# in both calls of authenticate() and createSubscription()
#
# PAYMENTREQUEST_0_AMT sets the cost of the subscription to 10 USD, which
# is the default PayPal currency.
#
# See all params that you can use on following website:
# https://www.x.com/developers/paypal/documentation-tools/api/setexpresscheckout-api-operation-nvp
#
params =
"RETURNURL": "http://localhost:3000/purchase/success"
"CANCELURL": "http://localhost:3000/purchase/fail"
"L_BILLINGAGREEMENTDESCRIPTION0": "Demo subscription"
"PAYMENTREQUEST_0_AMT": 10
# Do the authenticate() call (SetExpressCheckout on the PayPal API)
paypal.authenticate params, (error, data, url) ->
# Show a friendly error message to the user if PayPal's API isn't available
return res.send "Temporary error, please come back later", 500 if error or !url
# Make a HTTP 302 redirect of our user to PayPal.
res.redirect 302, url
app.get "/purchase/success", (req, res) ->
# Extract the Token and PayerID which PayPal has appended to the URL as
# query strings:
token = req.query.token ? false
payerid = req.query['PayerID'] ? false
# Show an error if we don't have both token & payerid
return res.send "Invalid request.", 500 if !token or !payerid
# We want to create a demo subscription with one month of free trial period
# with no initial charging of the user.
# Therefore we set the PROFILESTARTDATE to one month ahead from now
startdate = new Date()
startdate.setMonth(startdate.getMonth()+1)
params =
AMT: 10
DESC: "Demo subscription"
BILLINGPERIOD: "Month"
BILLINGFREQUENCY: 1
PROFILESTARTDATE: startdate
paypal.createSubscription token, payerid, params, (error, data) ->
if !error
# We've just turned our user into a subscribing customer. Chapeau!
# Show some links so that we can fetch some data about the subscription
# or to cancel the subscription.
res.send '<strong>Thanks for subscribing to our service!</strong><br/><br/>
Click <a href="/subscription/'+data["PROFILEID"]+'/info" target="_blank">here</a>
to fetch details about your subscription or
<a href="/subscription/'+data["PROFILEID"]+'/cancel" target="_blank">here</a> if
you want to cancel your subscription.'
else
# PayPal's API can be down or more probably, you provided an invalid token.
return res.send "Temporary error or invalid token, please come back later"
app.get "/purchase/fail", (req,res) ->
# The user gets returned here when he/she didn't go through with the PayPal
# login/account creation.
res.send "Aww. We're so sorry that you didn't go through with our subscription. Next time maybe?"
app.get "/subscription/:pid/info", (req, res) ->
# Show an error if we didn't get a PROFILEID
pid = req.params.pid ? false
return res.send "Invalid request.", 500 if !pid
# Fetch subscription data based upon given PROFILEID
paypal.getSubscription pid, (error, data) ->
return res.json data if !error
res.send "Your subscription doesn't exist or we couldn't reach PayPal's API right now"
app.get "/subscription/:pid/cancel", (req, res) ->
# Show an error if we didn't get a PROFILEID
pid = req.params.pid ? false
return res.send "Invalid request.", 500 if !pid
paypal.modifySubscription pid, "Cancel", (error, data) ->
if !error and data["ACK"] isnt "Failure"
res.send "<pre>" + JSON.stringify(data, null, 4) + "</pre>
<br/><br/>
<a href=\"/subscription/"+pid+"/info\">
Check status now for the subscription and it should have changed to \"Cancelled\"</a>"
else
# PayPal's API can be down or more probably, you provided an invalid PROFILEID.
res.send "Your subscription either doesn't exist, is already cancelled or
something just went plain wrong..."
app.listen(3000)
console.log "Open http://localhost:3000 in your browser to launch the demo" | 18123 | # Demo application of the paypal-recurring package.
#
# If coffeescript confuses you, go wild with http://js2coffee.org/
#
# Do only use this for personal testing and make sure to
# use HTTPS on your own server when using the package in production.
#
# Enter your own credentials below, or you won't be able
# to run this demo.
#
# Obtain your very own API credentials at: https://developer.paypal.com
#
express = require 'express'
app = express()
Paypal = require '../'
#####
# ENTER YOUR CREDENTIALS HERE
#####
paypal = new Paypal
username: ""
password: ""
signature: ""
#####
# No need to edit anything below. The demo should run itself.
#####
app.get "/", (req, res) ->
res.send '<a href="/purchase/buy">Click here to do a demo subscription</a> <br/><br/>
Make sure to have your test account credentials at hands - click
<a href="https://developer.paypal.com/">here</a> to obtain such
if you haven\'t already done so.'
app.get "/purchase/buy", (req, res) ->
# We want to create a demo subscription to learn how this
# works, so as we run this script at port 3000 on localhost,
# we can pass below URL's as RETURNURL and CANCELURL to PayPal accordingly.
#
# L_BILLINGAGREEMENTDESCRIPTION0 could be just anything but must stay the same
# in both calls of authenticate() and createSubscription()
#
# PAYMENTREQUEST_0_AMT sets the cost of the subscription to 10 USD, which
# is the default PayPal currency.
#
# See all params that you can use on following website:
# https://www.x.com/developers/paypal/documentation-tools/api/setexpresscheckout-api-operation-nvp
#
params =
"RETURNURL": "http://localhost:3000/purchase/success"
"CANCELURL": "http://localhost:3000/purchase/fail"
"L_BILLINGAGREEMENTDESCRIPTION0": "Demo subscription"
"PAYMENTREQUEST_0_AMT": 10
# Do the authenticate() call (SetExpressCheckout on the PayPal API)
paypal.authenticate params, (error, data, url) ->
# Show a friendly error message to the user if PayPal's API isn't available
return res.send "Temporary error, please come back later", 500 if error or !url
# Make a HTTP 302 redirect of our user to PayPal.
res.redirect 302, url
app.get "/purchase/success", (req, res) ->
# Extract the Token and PayerID which PayPal has appended to the URL as
# query strings:
token = req.query.token ? false
payerid = req.query['PayerID'] ? false
# Show an error if we don't have both token & payerid
return res.send "Invalid request.", 500 if !token or !payerid
# We want to create a demo subscription with one month of free trial period
# with no initial charging of the user.
# Therefore we set the PROFILESTARTDATE to one month ahead from now
startdate = new Date()
startdate.setMonth(startdate.getMonth()+1)
params =
AMT: 10
DESC: "Demo subscription"
BILLINGPERIOD: "Month"
BILLINGFREQUENCY: 1
PROFILESTARTDATE: startdate
paypal.createSubscription token, payerid, params, (error, data) ->
if !error
# We've just turned our user into a subscribing customer. <NAME>!
# Show some links so that we can fetch some data about the subscription
# or to cancel the subscription.
res.send '<strong>Thanks for subscribing to our service!</strong><br/><br/>
Click <a href="/subscription/'+data["PROFILEID"]+'/info" target="_blank">here</a>
to fetch details about your subscription or
<a href="/subscription/'+data["PROFILEID"]+'/cancel" target="_blank">here</a> if
you want to cancel your subscription.'
else
# PayPal's API can be down or more probably, you provided an invalid token.
return res.send "Temporary error or invalid token, please come back later"
app.get "/purchase/fail", (req,res) ->
# The user gets returned here when he/she didn't go through with the PayPal
# login/account creation.
res.send "Aww. We're so sorry that you didn't go through with our subscription. Next time maybe?"
app.get "/subscription/:pid/info", (req, res) ->
# Show an error if we didn't get a PROFILEID
pid = req.params.pid ? false
return res.send "Invalid request.", 500 if !pid
# Fetch subscription data based upon given PROFILEID
paypal.getSubscription pid, (error, data) ->
return res.json data if !error
res.send "Your subscription doesn't exist or we couldn't reach PayPal's API right now"
app.get "/subscription/:pid/cancel", (req, res) ->
# Show an error if we didn't get a PROFILEID
pid = req.params.pid ? false
return res.send "Invalid request.", 500 if !pid
paypal.modifySubscription pid, "Cancel", (error, data) ->
if !error and data["ACK"] isnt "Failure"
res.send "<pre>" + JSON.stringify(data, null, 4) + "</pre>
<br/><br/>
<a href=\"/subscription/"+pid+"/info\">
Check status now for the subscription and it should have changed to \"Cancelled\"</a>"
else
# PayPal's API can be down or more probably, you provided an invalid PROFILEID.
res.send "Your subscription either doesn't exist, is already cancelled or
something just went plain wrong..."
app.listen(3000)
console.log "Open http://localhost:3000 in your browser to launch the demo" | true | # Demo application of the paypal-recurring package.
#
# If coffeescript confuses you, go wild with http://js2coffee.org/
#
# Do only use this for personal testing and make sure to
# use HTTPS on your own server when using the package in production.
#
# Enter your own credentials below, or you won't be able
# to run this demo.
#
# Obtain your very own API credentials at: https://developer.paypal.com
#
express = require 'express'
app = express()
Paypal = require '../'
#####
# ENTER YOUR CREDENTIALS HERE
#####
paypal = new Paypal
username: ""
password: ""
signature: ""
#####
# No need to edit anything below. The demo should run itself.
#####
app.get "/", (req, res) ->
res.send '<a href="/purchase/buy">Click here to do a demo subscription</a> <br/><br/>
Make sure to have your test account credentials at hands - click
<a href="https://developer.paypal.com/">here</a> to obtain such
if you haven\'t already done so.'
app.get "/purchase/buy", (req, res) ->
# We want to create a demo subscription to learn how this
# works, so as we run this script at port 3000 on localhost,
# we can pass below URL's as RETURNURL and CANCELURL to PayPal accordingly.
#
# L_BILLINGAGREEMENTDESCRIPTION0 could be just anything but must stay the same
# in both calls of authenticate() and createSubscription()
#
# PAYMENTREQUEST_0_AMT sets the cost of the subscription to 10 USD, which
# is the default PayPal currency.
#
# See all params that you can use on following website:
# https://www.x.com/developers/paypal/documentation-tools/api/setexpresscheckout-api-operation-nvp
#
params =
"RETURNURL": "http://localhost:3000/purchase/success"
"CANCELURL": "http://localhost:3000/purchase/fail"
"L_BILLINGAGREEMENTDESCRIPTION0": "Demo subscription"
"PAYMENTREQUEST_0_AMT": 10
# Do the authenticate() call (SetExpressCheckout on the PayPal API)
paypal.authenticate params, (error, data, url) ->
# Show a friendly error message to the user if PayPal's API isn't available
return res.send "Temporary error, please come back later", 500 if error or !url
# Make a HTTP 302 redirect of our user to PayPal.
res.redirect 302, url
app.get "/purchase/success", (req, res) ->
# Extract the Token and PayerID which PayPal has appended to the URL as
# query strings:
token = req.query.token ? false
payerid = req.query['PayerID'] ? false
# Show an error if we don't have both token & payerid
return res.send "Invalid request.", 500 if !token or !payerid
# We want to create a demo subscription with one month of free trial period
# with no initial charging of the user.
# Therefore we set the PROFILESTARTDATE to one month ahead from now
startdate = new Date()
startdate.setMonth(startdate.getMonth()+1)
params =
AMT: 10
DESC: "Demo subscription"
BILLINGPERIOD: "Month"
BILLINGFREQUENCY: 1
PROFILESTARTDATE: startdate
paypal.createSubscription token, payerid, params, (error, data) ->
if !error
# We've just turned our user into a subscribing customer. PI:NAME:<NAME>END_PI!
# Show some links so that we can fetch some data about the subscription
# or to cancel the subscription.
res.send '<strong>Thanks for subscribing to our service!</strong><br/><br/>
Click <a href="/subscription/'+data["PROFILEID"]+'/info" target="_blank">here</a>
to fetch details about your subscription or
<a href="/subscription/'+data["PROFILEID"]+'/cancel" target="_blank">here</a> if
you want to cancel your subscription.'
else
# PayPal's API can be down or more probably, you provided an invalid token.
return res.send "Temporary error or invalid token, please come back later"
app.get "/purchase/fail", (req,res) ->
# The user gets returned here when he/she didn't go through with the PayPal
# login/account creation.
res.send "Aww. We're so sorry that you didn't go through with our subscription. Next time maybe?"
app.get "/subscription/:pid/info", (req, res) ->
# Show an error if we didn't get a PROFILEID
pid = req.params.pid ? false
return res.send "Invalid request.", 500 if !pid
# Fetch subscription data based upon given PROFILEID
paypal.getSubscription pid, (error, data) ->
return res.json data if !error
res.send "Your subscription doesn't exist or we couldn't reach PayPal's API right now"
app.get "/subscription/:pid/cancel", (req, res) ->
# Show an error if we didn't get a PROFILEID
pid = req.params.pid ? false
return res.send "Invalid request.", 500 if !pid
paypal.modifySubscription pid, "Cancel", (error, data) ->
if !error and data["ACK"] isnt "Failure"
res.send "<pre>" + JSON.stringify(data, null, 4) + "</pre>
<br/><br/>
<a href=\"/subscription/"+pid+"/info\">
Check status now for the subscription and it should have changed to \"Cancelled\"</a>"
else
# PayPal's API can be down or more probably, you provided an invalid PROFILEID.
res.send "Your subscription either doesn't exist, is already cancelled or
something just went plain wrong..."
app.listen(3000)
console.log "Open http://localhost:3000 in your browser to launch the demo" |
[
{
"context": "odels.RoleMapping\n\n User.create [\n username: \"admin\"\n email: \"admin@admin.com\"\n password: \"admi",
"end": 153,
"score": 0.9992639422416687,
"start": 148,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " User.create [\n username: \"admin\"\n email: \"admin@admin.com\"\n password: \"admin\"\n ], (err, users) ->\n r",
"end": 182,
"score": 0.9999198913574219,
"start": 167,
"tag": "EMAIL",
"value": "admin@admin.com"
},
{
"context": "dmin\"\n email: \"admin@admin.com\"\n password: \"admin\"\n ], (err, users) ->\n return console.error(er",
"end": 204,
"score": 0.9994685053825378,
"start": 199,
"tag": "PASSWORD",
"value": "admin"
}
] | application/user/server/boot/users.coffee | darkoverlordofdata/games | 0 | module.exports = (app) ->
User = app.models.User
Role = app.models.Role
RoleMapping = app.models.RoleMapping
User.create [
username: "admin"
email: "admin@admin.com"
password: "admin"
], (err, users) ->
return console.error(err) if err
# Create the admin role
Role.create
name: "admin"
, (err, role) ->
return console.error(err) if err
# Give Admin user the admin role
role.principals.create
principalType: RoleMapping.USER
principalId: users[0].id
, (err, principal) ->
console.error err if err
return
return
return
# done!
| 150430 | module.exports = (app) ->
User = app.models.User
Role = app.models.Role
RoleMapping = app.models.RoleMapping
User.create [
username: "admin"
email: "<EMAIL>"
password: "<PASSWORD>"
], (err, users) ->
return console.error(err) if err
# Create the admin role
Role.create
name: "admin"
, (err, role) ->
return console.error(err) if err
# Give Admin user the admin role
role.principals.create
principalType: RoleMapping.USER
principalId: users[0].id
, (err, principal) ->
console.error err if err
return
return
return
# done!
| true | module.exports = (app) ->
User = app.models.User
Role = app.models.Role
RoleMapping = app.models.RoleMapping
User.create [
username: "admin"
email: "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
], (err, users) ->
return console.error(err) if err
# Create the admin role
Role.create
name: "admin"
, (err, role) ->
return console.error(err) if err
# Give Admin user the admin role
role.principals.create
principalType: RoleMapping.USER
principalId: users[0].id
, (err, principal) ->
console.error err if err
return
return
return
# done!
|
[
{
"context": " queryBuilder\n .start({ name: 'Kieve' })\n .toString().should.equal ",
"end": 5506,
"score": 0.9996065497398376,
"start": 5501,
"tag": "NAME",
"value": "Kieve"
},
{
"context": " .getParams().name.should.equal 'Kieve'\n\n describe 'queryBuilder.start(query, tru",
"end": 5770,
"score": 0.9996098279953003,
"start": 5765,
"tag": "NAME",
"value": "Kieve"
},
{
"context": "eryBuilder\n .set(\"n.surname = 'Kieve'\")\n .toString().should.equal \"",
"end": 8175,
"score": 0.991910457611084,
"start": 8170,
"tag": "NAME",
"value": "Kieve"
},
{
"context": " .toString().should.equal \"SET n.surname = 'Kieve'\"\n\n describe 'queryBuilder.merge(query)', ",
"end": 8247,
"score": 0.9977017641067505,
"start": 8242,
"tag": "NAME",
"value": "Kieve"
},
{
"context": "ueryBuilder\n .return({'name': 'Name', 'age': 'Age'})\n .toString().",
"end": 10829,
"score": 0.5455318689346313,
"start": 10825,
"tag": "NAME",
"value": "Name"
}
] | test/test.cypher.coffee | kievechua/js-neo4j | 2 | Q = require 'q'
chai = require 'chai'
chaiAsPromised = require 'chai-as-promised'
chai.should()
chai.use(chaiAsPromised)
require("mocha-as-promised")()
{Neo4js} = require '../src/main'
describe 'Cypher', ->
neo = new Neo4js()
testNode = null
before (done) ->
Q.all([
neo.createNode({ name: 'Test cypher 1' })
neo.createNode({ name: 'Test cypher 2' })
])
.then (result) ->
testNode = result
done()
describe 'neo.executeCypher(query, parameters)', ->
describe 'when valid', ->
it 'should run cypher query', ->
neo
.executeCypher(
'START n = node({nodeId}) RETURN n'
{
"nodeId" : parseInt(testNode[0]._id)
}
)
.then((result) ->
result.should.include.keys('columns')
)
describe 'neo.queryBuilder()', ->
queryBuilder = null
beforeEach ->
queryBuilder = neo.queryBuilder()
describe 'queryBuilder.cypher(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.cypher('START n = node(*)')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.direction(query)', ->
describe 'n', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('n')
.toString().should.equal '()'
describe 'tn', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('tn=n')
.toString().should.equal '-->(n)'
describe 'fn', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('fn=n')
.toString().should.equal '<--(n)'
describe 'r', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('r=r')
.toString().should.equal '-[r]->'
describe 'tr', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('tr=r')
.toString().should.equal '-[r]->'
describe 'fr', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('fr=r')
.toString().should.equal '<-[r]-'
describe 'or', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('or=r')
.toString().should.equal '<-[r]->'
describe 'ir', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('ir=r')
.toString().should.equal '-[r]-'
describe '--', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('--')
.toString().should.equal '--'
describe 'chaining', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('n=n/r=friend/n=m')
.toString().should.equal '(n)-[friend]->(m)'
describe 'queryBuilder.start(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('*')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.start(nodeId)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start(1)
.toString().should.equal 'START n = node({id})'
queryBuilder
.getParams().should.include.keys('id')
queryBuilder
.getParams().id.should.equal 1
describe 'queryBuilder.start(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('n = node(*)')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.start({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start({ name: 'Kieve' })
.toString().should.equal 'START name = node({name})'
queryBuilder
.getParams().should.include.keys('name')
queryBuilder
.getParams().name.should.equal 'Kieve'
describe 'queryBuilder.start(query, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('*', true)
.toString().should.equal 'START r = relationship(*)'
describe 'queryBuilder.start(nodeId, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start(1, true)
.toString().should.equal 'START r = relationship({id})'
queryBuilder
.getParams().should.include.keys('id')
queryBuilder
.getParams().id.should.equal 1
describe 'queryBuilder.create(query)', ->
describe 'when valid', ->
it 'should create normal query', ->
queryBuilder
.create('n')
.toString().should.equal 'CREATE n'
describe 'queryBuilder.create(query, true)', ->
describe 'when valid', ->
it 'should create unique query', ->
queryBuilder
.create('n', true)
.toString().should.equal 'CREATE UNIQUE n'
describe 'queryBuilder.match(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.match('(movie:Movie)')
.toString().should.equal 'MATCH (movie:Movie)'
describe 'queryBuilder.where(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.where('n:Swedish')
.toString().should.equal 'WHERE n:Swedish'
describe 'queryBuilder.with(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.with('m')
.toString().should.equal 'WITH m'
describe 'queryBuilder.set(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.set("n.surname = 'Kieve'")
.toString().should.equal "SET n.surname = 'Kieve'"
describe 'queryBuilder.merge(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.merge('kieve:Critic')
.toString().should.equal 'MERGE (kieve:Critic)'
describe 'queryBuilder.drop(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.drop('(movie:Movie)')
.toString().should.equal 'DROP (movie:Movie)'
describe 'queryBuilder.remove(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.remove('kieve.age')
.toString().should.equal 'REMOVE kieve.age'
describe 'queryBuilder.del(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.del('n')
.toString().should.equal 'DELETE n'
describe 'queryBuilder.del([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.del(['n', 'm'])
.toString().should.equal 'DELETE n, m'
describe 'queryBuilder.foreach([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.foreach('(n IN nodes(p)| SET n.marked = TRUE )')
.toString().should.equal 'FOREACH (n IN nodes(p)| SET n.marked = TRUE )'
describe 'queryBuilder.return(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return('n')
.toString().should.equal 'RETURN n'
describe 'queryBuilder.return([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return(['name', 'age'])
.toString().should.equal 'RETURN n.name, n.age'
describe 'queryBuilder.return({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return({'name': 'Name', 'age': 'Age'})
.toString().should.equal 'RETURN n.name AS Name, n.age AS Age'
describe 'queryBuilder.return([query], true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return(['name', 'age'], true)
.toString().should.equal 'RETURN r.name, r.age'
describe 'queryBuilder.return({query}, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return({'name': 'Name', 'age': 'Age'}, true)
.toString().should.equal 'RETURN r.name AS Name, r.age AS Age'
describe 'queryBuilder.union([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.union('all')
.toString().should.equal 'UNION ALL'
describe 'queryBuilder.using(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.using('n:Swedish(surname)')
.toString().should.equal 'USING n:Swedish(surname)'
describe 'queryBuilder.using(query, parameter)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.using('n:Swedish(surname)', 'INDEX')
.toString().should.equal 'USING INDEX n:Swedish(surname)'
describe 'queryBuilder.orderBy(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy('n.name')
.toString().should.equal 'ORDER BY n.name'
describe 'queryBuilder.orderBy([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy(['name', 'age'])
.toString().should.equal 'ORDER BY n.name, n.age'
describe 'queryBuilder.orderBy({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy({ 'name': 'asc', 'age': 1, 'gender': true })
.toString().should.equal 'ORDER BY n.name ASC, n.age ASC, n.gender ASC'
describe 'queryBuilder.orderBy([query], true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy(['name', 'age'], true)
.toString().should.equal 'ORDER BY r.name, r.age'
describe 'queryBuilder.orderBy({query}, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy({ 'name': 'asc', 'age': 1, 'gender': true }, true)
.toString().should.equal 'ORDER BY r.name ASC, r.age ASC, r.gender ASC'
describe 'queryBuilder.skip(skip)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.skip(1)
.toString().should.equal 'SKIP 1'
describe 'queryBuilder.limit(limit)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.limit(1)
.toString().should.equal 'LIMIT 1'
describe 'queryBuilder.limit(limit, step)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.limit(1, 2)
.toString().should.equal 'LIMIT 1 SKIP 2'
describe 'queryBuilder.getList(type)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.getList('function')
.should.deep.equal [
'ALL', 'ANY', 'NONE', 'SINGLE',
'LENGTH', 'TYPE', 'ID', 'COALESCE', 'HEAD', 'LAST', 'TIMESTAMP', 'STARTNODE', 'ENDNODE',
'NODES', 'RELATIONSHIPS', 'LABELS', 'EXTRACT', 'FILTER', 'TAIL', 'RANGE', 'REDUCE',
'ABS', 'ACOS', 'ASIN', 'ATAN', 'COS', 'COT', 'DEGREES', 'E', 'EXP', 'FLOOR', 'HAVERSIN', 'LOG', 'LOG10', 'PI', 'RADIANS', 'RAND', 'ROUND', 'SIGN', 'SIN', 'SQRT', 'TAN',
'STR', 'REPLACE', 'SUBSTRING', 'LEFT', 'RIGHT', 'LTRIM', 'RTRIM', 'TRIM', 'LOWER', 'UPPER'
]
describe 'queryBuilder.execute()', ->
describe 'when valid', ->
it 'should run cypher query', ->
result = queryBuilder
.start('*')
.return('*')
.execute()
result.should.eventually.include.keys('data')
after ->
Q.all([
neo.deleteNode(testNode[0]._id)
neo.deleteNode(testNode[1]._id)
])
| 17350 | Q = require 'q'
chai = require 'chai'
chaiAsPromised = require 'chai-as-promised'
chai.should()
chai.use(chaiAsPromised)
require("mocha-as-promised")()
{Neo4js} = require '../src/main'
describe 'Cypher', ->
neo = new Neo4js()
testNode = null
before (done) ->
Q.all([
neo.createNode({ name: 'Test cypher 1' })
neo.createNode({ name: 'Test cypher 2' })
])
.then (result) ->
testNode = result
done()
describe 'neo.executeCypher(query, parameters)', ->
describe 'when valid', ->
it 'should run cypher query', ->
neo
.executeCypher(
'START n = node({nodeId}) RETURN n'
{
"nodeId" : parseInt(testNode[0]._id)
}
)
.then((result) ->
result.should.include.keys('columns')
)
describe 'neo.queryBuilder()', ->
queryBuilder = null
beforeEach ->
queryBuilder = neo.queryBuilder()
describe 'queryBuilder.cypher(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.cypher('START n = node(*)')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.direction(query)', ->
describe 'n', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('n')
.toString().should.equal '()'
describe 'tn', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('tn=n')
.toString().should.equal '-->(n)'
describe 'fn', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('fn=n')
.toString().should.equal '<--(n)'
describe 'r', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('r=r')
.toString().should.equal '-[r]->'
describe 'tr', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('tr=r')
.toString().should.equal '-[r]->'
describe 'fr', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('fr=r')
.toString().should.equal '<-[r]-'
describe 'or', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('or=r')
.toString().should.equal '<-[r]->'
describe 'ir', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('ir=r')
.toString().should.equal '-[r]-'
describe '--', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('--')
.toString().should.equal '--'
describe 'chaining', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('n=n/r=friend/n=m')
.toString().should.equal '(n)-[friend]->(m)'
describe 'queryBuilder.start(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('*')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.start(nodeId)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start(1)
.toString().should.equal 'START n = node({id})'
queryBuilder
.getParams().should.include.keys('id')
queryBuilder
.getParams().id.should.equal 1
describe 'queryBuilder.start(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('n = node(*)')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.start({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start({ name: '<NAME>' })
.toString().should.equal 'START name = node({name})'
queryBuilder
.getParams().should.include.keys('name')
queryBuilder
.getParams().name.should.equal '<NAME>'
describe 'queryBuilder.start(query, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('*', true)
.toString().should.equal 'START r = relationship(*)'
describe 'queryBuilder.start(nodeId, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start(1, true)
.toString().should.equal 'START r = relationship({id})'
queryBuilder
.getParams().should.include.keys('id')
queryBuilder
.getParams().id.should.equal 1
describe 'queryBuilder.create(query)', ->
describe 'when valid', ->
it 'should create normal query', ->
queryBuilder
.create('n')
.toString().should.equal 'CREATE n'
describe 'queryBuilder.create(query, true)', ->
describe 'when valid', ->
it 'should create unique query', ->
queryBuilder
.create('n', true)
.toString().should.equal 'CREATE UNIQUE n'
describe 'queryBuilder.match(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.match('(movie:Movie)')
.toString().should.equal 'MATCH (movie:Movie)'
describe 'queryBuilder.where(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.where('n:Swedish')
.toString().should.equal 'WHERE n:Swedish'
describe 'queryBuilder.with(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.with('m')
.toString().should.equal 'WITH m'
describe 'queryBuilder.set(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.set("n.surname = '<NAME>'")
.toString().should.equal "SET n.surname = '<NAME>'"
describe 'queryBuilder.merge(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.merge('kieve:Critic')
.toString().should.equal 'MERGE (kieve:Critic)'
describe 'queryBuilder.drop(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.drop('(movie:Movie)')
.toString().should.equal 'DROP (movie:Movie)'
describe 'queryBuilder.remove(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.remove('kieve.age')
.toString().should.equal 'REMOVE kieve.age'
describe 'queryBuilder.del(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.del('n')
.toString().should.equal 'DELETE n'
describe 'queryBuilder.del([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.del(['n', 'm'])
.toString().should.equal 'DELETE n, m'
describe 'queryBuilder.foreach([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.foreach('(n IN nodes(p)| SET n.marked = TRUE )')
.toString().should.equal 'FOREACH (n IN nodes(p)| SET n.marked = TRUE )'
describe 'queryBuilder.return(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return('n')
.toString().should.equal 'RETURN n'
describe 'queryBuilder.return([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return(['name', 'age'])
.toString().should.equal 'RETURN n.name, n.age'
describe 'queryBuilder.return({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return({'name': '<NAME>', 'age': 'Age'})
.toString().should.equal 'RETURN n.name AS Name, n.age AS Age'
describe 'queryBuilder.return([query], true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return(['name', 'age'], true)
.toString().should.equal 'RETURN r.name, r.age'
describe 'queryBuilder.return({query}, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return({'name': 'Name', 'age': 'Age'}, true)
.toString().should.equal 'RETURN r.name AS Name, r.age AS Age'
describe 'queryBuilder.union([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.union('all')
.toString().should.equal 'UNION ALL'
describe 'queryBuilder.using(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.using('n:Swedish(surname)')
.toString().should.equal 'USING n:Swedish(surname)'
describe 'queryBuilder.using(query, parameter)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.using('n:Swedish(surname)', 'INDEX')
.toString().should.equal 'USING INDEX n:Swedish(surname)'
describe 'queryBuilder.orderBy(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy('n.name')
.toString().should.equal 'ORDER BY n.name'
describe 'queryBuilder.orderBy([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy(['name', 'age'])
.toString().should.equal 'ORDER BY n.name, n.age'
describe 'queryBuilder.orderBy({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy({ 'name': 'asc', 'age': 1, 'gender': true })
.toString().should.equal 'ORDER BY n.name ASC, n.age ASC, n.gender ASC'
describe 'queryBuilder.orderBy([query], true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy(['name', 'age'], true)
.toString().should.equal 'ORDER BY r.name, r.age'
describe 'queryBuilder.orderBy({query}, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy({ 'name': 'asc', 'age': 1, 'gender': true }, true)
.toString().should.equal 'ORDER BY r.name ASC, r.age ASC, r.gender ASC'
describe 'queryBuilder.skip(skip)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.skip(1)
.toString().should.equal 'SKIP 1'
describe 'queryBuilder.limit(limit)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.limit(1)
.toString().should.equal 'LIMIT 1'
describe 'queryBuilder.limit(limit, step)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.limit(1, 2)
.toString().should.equal 'LIMIT 1 SKIP 2'
describe 'queryBuilder.getList(type)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.getList('function')
.should.deep.equal [
'ALL', 'ANY', 'NONE', 'SINGLE',
'LENGTH', 'TYPE', 'ID', 'COALESCE', 'HEAD', 'LAST', 'TIMESTAMP', 'STARTNODE', 'ENDNODE',
'NODES', 'RELATIONSHIPS', 'LABELS', 'EXTRACT', 'FILTER', 'TAIL', 'RANGE', 'REDUCE',
'ABS', 'ACOS', 'ASIN', 'ATAN', 'COS', 'COT', 'DEGREES', 'E', 'EXP', 'FLOOR', 'HAVERSIN', 'LOG', 'LOG10', 'PI', 'RADIANS', 'RAND', 'ROUND', 'SIGN', 'SIN', 'SQRT', 'TAN',
'STR', 'REPLACE', 'SUBSTRING', 'LEFT', 'RIGHT', 'LTRIM', 'RTRIM', 'TRIM', 'LOWER', 'UPPER'
]
describe 'queryBuilder.execute()', ->
describe 'when valid', ->
it 'should run cypher query', ->
result = queryBuilder
.start('*')
.return('*')
.execute()
result.should.eventually.include.keys('data')
after ->
Q.all([
neo.deleteNode(testNode[0]._id)
neo.deleteNode(testNode[1]._id)
])
| true | Q = require 'q'
chai = require 'chai'
chaiAsPromised = require 'chai-as-promised'
chai.should()
chai.use(chaiAsPromised)
require("mocha-as-promised")()
{Neo4js} = require '../src/main'
describe 'Cypher', ->
neo = new Neo4js()
testNode = null
before (done) ->
Q.all([
neo.createNode({ name: 'Test cypher 1' })
neo.createNode({ name: 'Test cypher 2' })
])
.then (result) ->
testNode = result
done()
describe 'neo.executeCypher(query, parameters)', ->
describe 'when valid', ->
it 'should run cypher query', ->
neo
.executeCypher(
'START n = node({nodeId}) RETURN n'
{
"nodeId" : parseInt(testNode[0]._id)
}
)
.then((result) ->
result.should.include.keys('columns')
)
describe 'neo.queryBuilder()', ->
queryBuilder = null
beforeEach ->
queryBuilder = neo.queryBuilder()
describe 'queryBuilder.cypher(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.cypher('START n = node(*)')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.direction(query)', ->
describe 'n', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('n')
.toString().should.equal '()'
describe 'tn', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('tn=n')
.toString().should.equal '-->(n)'
describe 'fn', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('fn=n')
.toString().should.equal '<--(n)'
describe 'r', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('r=r')
.toString().should.equal '-[r]->'
describe 'tr', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('tr=r')
.toString().should.equal '-[r]->'
describe 'fr', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('fr=r')
.toString().should.equal '<-[r]-'
describe 'or', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('or=r')
.toString().should.equal '<-[r]->'
describe 'ir', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('ir=r')
.toString().should.equal '-[r]-'
describe '--', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('--')
.toString().should.equal '--'
describe 'chaining', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.direction('n=n/r=friend/n=m')
.toString().should.equal '(n)-[friend]->(m)'
describe 'queryBuilder.start(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('*')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.start(nodeId)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start(1)
.toString().should.equal 'START n = node({id})'
queryBuilder
.getParams().should.include.keys('id')
queryBuilder
.getParams().id.should.equal 1
describe 'queryBuilder.start(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('n = node(*)')
.toString().should.equal 'START n = node(*)'
describe 'queryBuilder.start({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start({ name: 'PI:NAME:<NAME>END_PI' })
.toString().should.equal 'START name = node({name})'
queryBuilder
.getParams().should.include.keys('name')
queryBuilder
.getParams().name.should.equal 'PI:NAME:<NAME>END_PI'
describe 'queryBuilder.start(query, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start('*', true)
.toString().should.equal 'START r = relationship(*)'
describe 'queryBuilder.start(nodeId, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.start(1, true)
.toString().should.equal 'START r = relationship({id})'
queryBuilder
.getParams().should.include.keys('id')
queryBuilder
.getParams().id.should.equal 1
describe 'queryBuilder.create(query)', ->
describe 'when valid', ->
it 'should create normal query', ->
queryBuilder
.create('n')
.toString().should.equal 'CREATE n'
describe 'queryBuilder.create(query, true)', ->
describe 'when valid', ->
it 'should create unique query', ->
queryBuilder
.create('n', true)
.toString().should.equal 'CREATE UNIQUE n'
describe 'queryBuilder.match(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.match('(movie:Movie)')
.toString().should.equal 'MATCH (movie:Movie)'
describe 'queryBuilder.where(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.where('n:Swedish')
.toString().should.equal 'WHERE n:Swedish'
describe 'queryBuilder.with(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.with('m')
.toString().should.equal 'WITH m'
describe 'queryBuilder.set(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.set("n.surname = 'PI:NAME:<NAME>END_PI'")
.toString().should.equal "SET n.surname = 'PI:NAME:<NAME>END_PI'"
describe 'queryBuilder.merge(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.merge('kieve:Critic')
.toString().should.equal 'MERGE (kieve:Critic)'
describe 'queryBuilder.drop(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.drop('(movie:Movie)')
.toString().should.equal 'DROP (movie:Movie)'
describe 'queryBuilder.remove(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.remove('kieve.age')
.toString().should.equal 'REMOVE kieve.age'
describe 'queryBuilder.del(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.del('n')
.toString().should.equal 'DELETE n'
describe 'queryBuilder.del([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.del(['n', 'm'])
.toString().should.equal 'DELETE n, m'
describe 'queryBuilder.foreach([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.foreach('(n IN nodes(p)| SET n.marked = TRUE )')
.toString().should.equal 'FOREACH (n IN nodes(p)| SET n.marked = TRUE )'
describe 'queryBuilder.return(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return('n')
.toString().should.equal 'RETURN n'
describe 'queryBuilder.return([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return(['name', 'age'])
.toString().should.equal 'RETURN n.name, n.age'
describe 'queryBuilder.return({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return({'name': 'PI:NAME:<NAME>END_PI', 'age': 'Age'})
.toString().should.equal 'RETURN n.name AS Name, n.age AS Age'
describe 'queryBuilder.return([query], true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return(['name', 'age'], true)
.toString().should.equal 'RETURN r.name, r.age'
describe 'queryBuilder.return({query}, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.return({'name': 'Name', 'age': 'Age'}, true)
.toString().should.equal 'RETURN r.name AS Name, r.age AS Age'
describe 'queryBuilder.union([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.union('all')
.toString().should.equal 'UNION ALL'
describe 'queryBuilder.using(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.using('n:Swedish(surname)')
.toString().should.equal 'USING n:Swedish(surname)'
describe 'queryBuilder.using(query, parameter)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.using('n:Swedish(surname)', 'INDEX')
.toString().should.equal 'USING INDEX n:Swedish(surname)'
describe 'queryBuilder.orderBy(query)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy('n.name')
.toString().should.equal 'ORDER BY n.name'
describe 'queryBuilder.orderBy([query])', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy(['name', 'age'])
.toString().should.equal 'ORDER BY n.name, n.age'
describe 'queryBuilder.orderBy({query})', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy({ 'name': 'asc', 'age': 1, 'gender': true })
.toString().should.equal 'ORDER BY n.name ASC, n.age ASC, n.gender ASC'
describe 'queryBuilder.orderBy([query], true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy(['name', 'age'], true)
.toString().should.equal 'ORDER BY r.name, r.age'
describe 'queryBuilder.orderBy({query}, true)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.orderBy({ 'name': 'asc', 'age': 1, 'gender': true }, true)
.toString().should.equal 'ORDER BY r.name ASC, r.age ASC, r.gender ASC'
describe 'queryBuilder.skip(skip)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.skip(1)
.toString().should.equal 'SKIP 1'
describe 'queryBuilder.limit(limit)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.limit(1)
.toString().should.equal 'LIMIT 1'
describe 'queryBuilder.limit(limit, step)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.limit(1, 2)
.toString().should.equal 'LIMIT 1 SKIP 2'
describe 'queryBuilder.getList(type)', ->
describe 'when valid', ->
it 'should construct correct cypher query', ->
queryBuilder
.getList('function')
.should.deep.equal [
'ALL', 'ANY', 'NONE', 'SINGLE',
'LENGTH', 'TYPE', 'ID', 'COALESCE', 'HEAD', 'LAST', 'TIMESTAMP', 'STARTNODE', 'ENDNODE',
'NODES', 'RELATIONSHIPS', 'LABELS', 'EXTRACT', 'FILTER', 'TAIL', 'RANGE', 'REDUCE',
'ABS', 'ACOS', 'ASIN', 'ATAN', 'COS', 'COT', 'DEGREES', 'E', 'EXP', 'FLOOR', 'HAVERSIN', 'LOG', 'LOG10', 'PI', 'RADIANS', 'RAND', 'ROUND', 'SIGN', 'SIN', 'SQRT', 'TAN',
'STR', 'REPLACE', 'SUBSTRING', 'LEFT', 'RIGHT', 'LTRIM', 'RTRIM', 'TRIM', 'LOWER', 'UPPER'
]
describe 'queryBuilder.execute()', ->
describe 'when valid', ->
it 'should run cypher query', ->
result = queryBuilder
.start('*')
.return('*')
.execute()
result.should.eventually.include.keys('data')
after ->
Q.all([
neo.deleteNode(testNode[0]._id)
neo.deleteNode(testNode[1]._id)
])
|
[
{
"context": " : buf(u16)\n bin32_key : buf(u32)\n double_key : 3.1415927e3\n uint8_key : u8\n uint16_key : u16\n uint32_key ",
"end": 623,
"score": 0.9955138564109802,
"start": 612,
"tag": "KEY",
"value": "3.1415927e3"
}
] | testdata/megatest.iced | marceloneil/msgpackzip | 5 | #
# run:
# iced megatest.iced > megatest.b64
#
{pack} = require 'purepack'
buf = (x) -> new Buffer ((i&0xff) for i in [0...x])
str = (x) -> (new Buffer ((i % 26) + 'a'.charCodeAt(0) for i in [0...x])).toString('utf8')
arr = (x) -> ((i & 0x3f) for i in [0...x])
map = (x) ->
r = {}
for i in [0...x]
k = (new Buffer [(i % 26) + 'a'.charCodeAt(0)]).toString('utf8') + i
v = i & 0x3f
r[k] = v
r
u8 = 0xa3
u16 = 0x103
u32 = 0x10003
u64 = 0x10000003
v =
null_key : null
false_key : false
true_key : true
bin8_key : buf(u8)
bin16_key : buf(u16)
bin32_key : buf(u32)
double_key : 3.1415927e3
uint8_key : u8
uint16_key : u16
uint32_key : u32
uint64_key : u64
int8_key : (0 - u8)
int16_key : (0 - u16)
int32_key : (0 - u32)
int64_key : (0 - u64)
str8 : str(u8)
str16 : str(u16)
str32 : str(u32)
array16 : arr(u16)
array32 : arr(u32)
map16 : map(u16)
map32 : map(u32)
for i in [0..0x1f]
v['str'+i] = str(i)
for i in [0..0xf]
v['arr'+i] = arr(i)
for i in [0..0xf]
v['map'+i] = map(i)
for i in [0..0x7f]
v['u'+i] = i
for i in [0..0x1f]
v['i'+i] = (0 - i)
# console.log v
console.log (pack v).toString('base64') | 198855 | #
# run:
# iced megatest.iced > megatest.b64
#
{pack} = require 'purepack'
buf = (x) -> new Buffer ((i&0xff) for i in [0...x])
str = (x) -> (new Buffer ((i % 26) + 'a'.charCodeAt(0) for i in [0...x])).toString('utf8')
arr = (x) -> ((i & 0x3f) for i in [0...x])
map = (x) ->
r = {}
for i in [0...x]
k = (new Buffer [(i % 26) + 'a'.charCodeAt(0)]).toString('utf8') + i
v = i & 0x3f
r[k] = v
r
u8 = 0xa3
u16 = 0x103
u32 = 0x10003
u64 = 0x10000003
v =
null_key : null
false_key : false
true_key : true
bin8_key : buf(u8)
bin16_key : buf(u16)
bin32_key : buf(u32)
double_key : <KEY>
uint8_key : u8
uint16_key : u16
uint32_key : u32
uint64_key : u64
int8_key : (0 - u8)
int16_key : (0 - u16)
int32_key : (0 - u32)
int64_key : (0 - u64)
str8 : str(u8)
str16 : str(u16)
str32 : str(u32)
array16 : arr(u16)
array32 : arr(u32)
map16 : map(u16)
map32 : map(u32)
for i in [0..0x1f]
v['str'+i] = str(i)
for i in [0..0xf]
v['arr'+i] = arr(i)
for i in [0..0xf]
v['map'+i] = map(i)
for i in [0..0x7f]
v['u'+i] = i
for i in [0..0x1f]
v['i'+i] = (0 - i)
# console.log v
console.log (pack v).toString('base64') | true | #
# run:
# iced megatest.iced > megatest.b64
#
{pack} = require 'purepack'
buf = (x) -> new Buffer ((i&0xff) for i in [0...x])
str = (x) -> (new Buffer ((i % 26) + 'a'.charCodeAt(0) for i in [0...x])).toString('utf8')
arr = (x) -> ((i & 0x3f) for i in [0...x])
map = (x) ->
r = {}
for i in [0...x]
k = (new Buffer [(i % 26) + 'a'.charCodeAt(0)]).toString('utf8') + i
v = i & 0x3f
r[k] = v
r
u8 = 0xa3
u16 = 0x103
u32 = 0x10003
u64 = 0x10000003
v =
null_key : null
false_key : false
true_key : true
bin8_key : buf(u8)
bin16_key : buf(u16)
bin32_key : buf(u32)
double_key : PI:KEY:<KEY>END_PI
uint8_key : u8
uint16_key : u16
uint32_key : u32
uint64_key : u64
int8_key : (0 - u8)
int16_key : (0 - u16)
int32_key : (0 - u32)
int64_key : (0 - u64)
str8 : str(u8)
str16 : str(u16)
str32 : str(u32)
array16 : arr(u16)
array32 : arr(u32)
map16 : map(u16)
map32 : map(u32)
for i in [0..0x1f]
v['str'+i] = str(i)
for i in [0..0xf]
v['arr'+i] = arr(i)
for i in [0..0xf]
v['map'+i] = map(i)
for i in [0..0x7f]
v['u'+i] = i
for i in [0..0x1f]
v['i'+i] = (0 - i)
# console.log v
console.log (pack v).toString('base64') |
[
{
"context": "\n options =\n name: \"Lol\"\n username: \"lollerblades\"\n email: \"lollerblades@lollerblades.com\"\n ",
"end": 617,
"score": 0.9995690584182739,
"start": 605,
"tag": "USERNAME",
"value": "lollerblades"
},
{
"context": "Lol\"\n username: \"lollerblades\"\n email: \"lollerblades@lollerblades.com\"\n passphrase: \"keep it secret keep it safe\"\n",
"end": 662,
"score": 0.9999192953109741,
"start": 633,
"tag": "EMAIL",
"value": "lollerblades@lollerblades.com"
},
{
"context": "lollerblades@lollerblades.com\"\n passphrase: \"keep it secret keep it safe\"\n invitation_id: \"342128cecb14dbe6af0fab0d\"\n",
"end": 710,
"score": 0.9991224408149719,
"start": 683,
"tag": "PASSWORD",
"value": "keep it secret keep it safe"
},
{
"context": " await keybase.user_lookup {\n usernames: ['testing'],\n fields: ['basics']\n }, defer err, res",
"end": 2348,
"score": 0.9951956272125244,
"start": 2341,
"tag": "USERNAME",
"value": "testing"
},
{
"context": "e) ->\n await keybase.key_fetch {pgp_key_ids: ['6052b2ad31a6631c', '980A3F0D01FE04DF'], ops: 1}, defer err, result",
"end": 3386,
"score": 0.9909011721611023,
"start": 3370,
"tag": "KEY",
"value": "6052b2ad31a6631c"
},
{
"context": "hould be able to generate a key\"\n # username = 'lol'\n # passphrase = 'lolagain'\n\n # await util.ge",
"end": 5252,
"score": 0.9984517693519592,
"start": 5249,
"tag": "USERNAME",
"value": "lol"
},
{
"context": "e a key\"\n # username = 'lol'\n # passphrase = 'lolagain'\n\n # await util.gen_key {username, passphrase},",
"end": 5281,
"score": 0.9979603290557861,
"start": 5273,
"tag": "USERNAME",
"value": "lolagain"
}
] | test/index.iced | taterbase/node-keybase | 10 | USERNAME_OR_EMAIL = process.env['KEYBASE_USERNAME_OR_EMAIL']
PASSPHRASE = process.env['KEYBASE_PASSPHRASE']
PUBLIC_KEY = process.env['KEYBASE_PUBLIC_KEY'] or require './publickey'
PRIVATE_KEY = process.env['KEYBASE_PRIVATE_KEY'] or require './privatekey'
Keybase = require '../'
keybase = new Keybase USERNAME_OR_EMAIL, PASSPHRASE
util = require '../util'
add_public_key = (cb) ->
keybase.key_add {
public_key: PUBLIC_KEY
is_primary: true
}, cb
describe 'node-keybase', ->
@timeout 9000
it 'should allow a user to sign up', (done) ->
options =
name: "Lol"
username: "lollerblades"
email: "lollerblades@lollerblades.com"
passphrase: "keep it secret keep it safe"
invitation_id: "342128cecb14dbe6af0fab0d"
await keybase.signup options, defer err, result
result.status.code.should.equal 707
result.status.name.should.equal "BAD_INVITATION_CODE"
result.guest_id.should.be.ok
result.csrf_token.should.be.ok
done err
it 'should get salt with passed in creds', (done) ->
await keybase.getsalt USERNAME_OR_EMAIL, defer err, result
return done err if err
result.guest_id.should.be.ok
result.salt.should.be.ok
result.login_session.should.be.ok
result.pwh_version.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should get salt with initialized creds', (done) ->
await keybase.getsalt defer err, result
return done err if err
result.guest_id.should.be.ok
result.salt.should.be.ok
result.login_session.should.be.ok
result.pwh_version.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should login with passed in creds', (done) ->
await keybase.login USERNAME_OR_EMAIL, PASSPHRASE, defer err, result
return done err if err
result.guest_id.should.be.ok
result.session.should.be.ok
result.uid.should.be.ok
result.me.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should login with initialized in creds', (done) ->
await keybase.login defer err, result
return done err if err
result.guest_id.should.be.ok
result.session.should.be.ok
result.uid.should.be.ok
result.me.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should find users', (done) ->
await keybase.user_lookup {
usernames: ['testing'],
fields: ['basics']
}, defer err, result
return done err if err
result.them.should.be.ok
result.them.length.should.equal 1
result.them[0].basics.should.be.ok
done()
it 'should use autocomplete', (done) ->
await keybase.user_autocomplete 'testing', defer err, result
return done err if err
result.completions.should.be.ok
done()
it 'should grab the public key for a user', (done) ->
await keybase.public_key_for_username 'testing', defer err, result
return done err if err
result.should.be.ok
(typeof result).should.equal 'string'
done()
it 'should allow you to add a public key', (done) ->
await add_public_key defer err, result
return done err if err
result.status.name.should.equal "OK"
done()
# TODO: We need a clean way to generate a p3skb to test this functionality
it 'should allow you to add a private key'
it 'should allow you to fetch public keys', (done) ->
await keybase.key_fetch {pgp_key_ids: ['6052b2ad31a6631c', '980A3F0D01FE04DF'], ops: 1}, defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.keys.should.be.ok
result.keys.length.should.equal 2
done()
# TODO: need to be able upload private keys first
it 'should allow you to fetch private keys'
it 'should allow you to revoke the primary key', (done) ->
await add_public_key defer err, result
return done err if err
await keybase.key_revoke defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.revocation_id.should.be.ok
done()
it 'should allow you to revoke a key by kid', (done) ->
await add_public_key defer err, result
return done err if err
kid = result.kid
await keybase.key_revoke {kid}, defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.revocation_id.should.be.ok
done()
it 'should kill all sessions', (done) ->
await keybase.session_killall defer err, result
return done err if err
result.status.name.should.equal 'OK'
done()
after (done) ->
# We have to make sure this test runs by itself to function correctly
# it "should get the next sequence number in the user's signature chain", (done) ->
await keybase.key_revoke defer err, result
return done err if err
await add_public_key defer err, result
return done err if err
await keybase.sig_next_seqno defer err, result
return done err if err
result.status.name.should.equal 'OK'
done()
it 'should allow signature posting'
it 'should allow authentication via signing a message'
it 'return the current site-wide Merkle root hash'
it 'should, given a hash, lookup the block that hashes to it'
describe 'keybase-utils', ->
it "should be able to generate a key"
# username = 'lol'
# passphrase = 'lolagain'
# await util.gen_key {username, passphrase}, defer err
# done err
| 45043 | USERNAME_OR_EMAIL = process.env['KEYBASE_USERNAME_OR_EMAIL']
PASSPHRASE = process.env['KEYBASE_PASSPHRASE']
PUBLIC_KEY = process.env['KEYBASE_PUBLIC_KEY'] or require './publickey'
PRIVATE_KEY = process.env['KEYBASE_PRIVATE_KEY'] or require './privatekey'
Keybase = require '../'
keybase = new Keybase USERNAME_OR_EMAIL, PASSPHRASE
util = require '../util'
add_public_key = (cb) ->
keybase.key_add {
public_key: PUBLIC_KEY
is_primary: true
}, cb
describe 'node-keybase', ->
@timeout 9000
it 'should allow a user to sign up', (done) ->
options =
name: "Lol"
username: "lollerblades"
email: "<EMAIL>"
passphrase: "<PASSWORD>"
invitation_id: "342128cecb14dbe6af0fab0d"
await keybase.signup options, defer err, result
result.status.code.should.equal 707
result.status.name.should.equal "BAD_INVITATION_CODE"
result.guest_id.should.be.ok
result.csrf_token.should.be.ok
done err
it 'should get salt with passed in creds', (done) ->
await keybase.getsalt USERNAME_OR_EMAIL, defer err, result
return done err if err
result.guest_id.should.be.ok
result.salt.should.be.ok
result.login_session.should.be.ok
result.pwh_version.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should get salt with initialized creds', (done) ->
await keybase.getsalt defer err, result
return done err if err
result.guest_id.should.be.ok
result.salt.should.be.ok
result.login_session.should.be.ok
result.pwh_version.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should login with passed in creds', (done) ->
await keybase.login USERNAME_OR_EMAIL, PASSPHRASE, defer err, result
return done err if err
result.guest_id.should.be.ok
result.session.should.be.ok
result.uid.should.be.ok
result.me.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should login with initialized in creds', (done) ->
await keybase.login defer err, result
return done err if err
result.guest_id.should.be.ok
result.session.should.be.ok
result.uid.should.be.ok
result.me.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should find users', (done) ->
await keybase.user_lookup {
usernames: ['testing'],
fields: ['basics']
}, defer err, result
return done err if err
result.them.should.be.ok
result.them.length.should.equal 1
result.them[0].basics.should.be.ok
done()
it 'should use autocomplete', (done) ->
await keybase.user_autocomplete 'testing', defer err, result
return done err if err
result.completions.should.be.ok
done()
it 'should grab the public key for a user', (done) ->
await keybase.public_key_for_username 'testing', defer err, result
return done err if err
result.should.be.ok
(typeof result).should.equal 'string'
done()
it 'should allow you to add a public key', (done) ->
await add_public_key defer err, result
return done err if err
result.status.name.should.equal "OK"
done()
# TODO: We need a clean way to generate a p3skb to test this functionality
it 'should allow you to add a private key'
it 'should allow you to fetch public keys', (done) ->
await keybase.key_fetch {pgp_key_ids: ['<KEY>', '980A3F0D01FE04DF'], ops: 1}, defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.keys.should.be.ok
result.keys.length.should.equal 2
done()
# TODO: need to be able upload private keys first
it 'should allow you to fetch private keys'
it 'should allow you to revoke the primary key', (done) ->
await add_public_key defer err, result
return done err if err
await keybase.key_revoke defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.revocation_id.should.be.ok
done()
it 'should allow you to revoke a key by kid', (done) ->
await add_public_key defer err, result
return done err if err
kid = result.kid
await keybase.key_revoke {kid}, defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.revocation_id.should.be.ok
done()
it 'should kill all sessions', (done) ->
await keybase.session_killall defer err, result
return done err if err
result.status.name.should.equal 'OK'
done()
after (done) ->
# We have to make sure this test runs by itself to function correctly
# it "should get the next sequence number in the user's signature chain", (done) ->
await keybase.key_revoke defer err, result
return done err if err
await add_public_key defer err, result
return done err if err
await keybase.sig_next_seqno defer err, result
return done err if err
result.status.name.should.equal 'OK'
done()
it 'should allow signature posting'
it 'should allow authentication via signing a message'
it 'return the current site-wide Merkle root hash'
it 'should, given a hash, lookup the block that hashes to it'
describe 'keybase-utils', ->
it "should be able to generate a key"
# username = 'lol'
# passphrase = 'lolagain'
# await util.gen_key {username, passphrase}, defer err
# done err
| true | USERNAME_OR_EMAIL = process.env['KEYBASE_USERNAME_OR_EMAIL']
PASSPHRASE = process.env['KEYBASE_PASSPHRASE']
PUBLIC_KEY = process.env['KEYBASE_PUBLIC_KEY'] or require './publickey'
PRIVATE_KEY = process.env['KEYBASE_PRIVATE_KEY'] or require './privatekey'
Keybase = require '../'
keybase = new Keybase USERNAME_OR_EMAIL, PASSPHRASE
util = require '../util'
add_public_key = (cb) ->
keybase.key_add {
public_key: PUBLIC_KEY
is_primary: true
}, cb
describe 'node-keybase', ->
@timeout 9000
it 'should allow a user to sign up', (done) ->
options =
name: "Lol"
username: "lollerblades"
email: "PI:EMAIL:<EMAIL>END_PI"
passphrase: "PI:PASSWORD:<PASSWORD>END_PI"
invitation_id: "342128cecb14dbe6af0fab0d"
await keybase.signup options, defer err, result
result.status.code.should.equal 707
result.status.name.should.equal "BAD_INVITATION_CODE"
result.guest_id.should.be.ok
result.csrf_token.should.be.ok
done err
it 'should get salt with passed in creds', (done) ->
await keybase.getsalt USERNAME_OR_EMAIL, defer err, result
return done err if err
result.guest_id.should.be.ok
result.salt.should.be.ok
result.login_session.should.be.ok
result.pwh_version.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should get salt with initialized creds', (done) ->
await keybase.getsalt defer err, result
return done err if err
result.guest_id.should.be.ok
result.salt.should.be.ok
result.login_session.should.be.ok
result.pwh_version.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should login with passed in creds', (done) ->
await keybase.login USERNAME_OR_EMAIL, PASSPHRASE, defer err, result
return done err if err
result.guest_id.should.be.ok
result.session.should.be.ok
result.uid.should.be.ok
result.me.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should login with initialized in creds', (done) ->
await keybase.login defer err, result
return done err if err
result.guest_id.should.be.ok
result.session.should.be.ok
result.uid.should.be.ok
result.me.should.be.ok
result.csrf_token.should.be.ok
done()
it 'should find users', (done) ->
await keybase.user_lookup {
usernames: ['testing'],
fields: ['basics']
}, defer err, result
return done err if err
result.them.should.be.ok
result.them.length.should.equal 1
result.them[0].basics.should.be.ok
done()
it 'should use autocomplete', (done) ->
await keybase.user_autocomplete 'testing', defer err, result
return done err if err
result.completions.should.be.ok
done()
it 'should grab the public key for a user', (done) ->
await keybase.public_key_for_username 'testing', defer err, result
return done err if err
result.should.be.ok
(typeof result).should.equal 'string'
done()
it 'should allow you to add a public key', (done) ->
await add_public_key defer err, result
return done err if err
result.status.name.should.equal "OK"
done()
# TODO: We need a clean way to generate a p3skb to test this functionality
it 'should allow you to add a private key'
it 'should allow you to fetch public keys', (done) ->
await keybase.key_fetch {pgp_key_ids: ['PI:KEY:<KEY>END_PI', '980A3F0D01FE04DF'], ops: 1}, defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.keys.should.be.ok
result.keys.length.should.equal 2
done()
# TODO: need to be able upload private keys first
it 'should allow you to fetch private keys'
it 'should allow you to revoke the primary key', (done) ->
await add_public_key defer err, result
return done err if err
await keybase.key_revoke defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.revocation_id.should.be.ok
done()
it 'should allow you to revoke a key by kid', (done) ->
await add_public_key defer err, result
return done err if err
kid = result.kid
await keybase.key_revoke {kid}, defer err, result
return done err if err
result.status.name.should.equal 'OK'
result.revocation_id.should.be.ok
done()
it 'should kill all sessions', (done) ->
await keybase.session_killall defer err, result
return done err if err
result.status.name.should.equal 'OK'
done()
after (done) ->
# We have to make sure this test runs by itself to function correctly
# it "should get the next sequence number in the user's signature chain", (done) ->
await keybase.key_revoke defer err, result
return done err if err
await add_public_key defer err, result
return done err if err
await keybase.sig_next_seqno defer err, result
return done err if err
result.status.name.should.equal 'OK'
done()
it 'should allow signature posting'
it 'should allow authentication via signing a message'
it 'return the current site-wide Merkle root hash'
it 'should, given a hash, lookup the block that hashes to it'
describe 'keybase-utils', ->
it "should be able to generate a key"
# username = 'lol'
# passphrase = 'lolagain'
# await util.gen_key {username, passphrase}, defer err
# done err
|
[
{
"context": " })\n .when('/users/edit/:firstName/:lastName', {\n templateUrl: '/assets/partial",
"end": 632,
"score": 0.6030091047286987,
"start": 624,
"tag": "NAME",
"value": "lastName"
}
] | app/assets/javascripts/app.coffee | jock71/nigstore | 0 |
dependencies = [
'ngRoute',
'ui.bootstrap',
'myApp.filters',
'myApp.services',
'myApp.controllers',
'myApp.directives',
'myApp.common',
'myApp.routeConfig'
]
app = angular.module('myApp', dependencies)
angular.module('myApp.routeConfig', ['ngRoute'])
.config(['$routeProvider', ($routeProvider) ->
$routeProvider
.when('/', {
templateUrl: '/assets/partials/storageView.html'
})
.when('/users/create', {
templateUrl: '/assets/partials/userCreate.html'
})
.when('/users/edit/:firstName/:lastName', {
templateUrl: '/assets/partials/userUpdate.html'
})
.when('/product', {
templateUrl: '/assets/partials/productView.html'
})
.when('/product/create', {
templateUrl: '/assets/partials/productCreate.html'
})
.when('/product/edit/:_id', {
templateUtl: '/assets/partials/wip.html'
})
.when('/storage', {
templateUrl: '/assets/partials/storageView.html'
})
.when('/storage/create', {
templateUrl: '/assets/partials/storageCreate.html'
})
.when('/storage/details/:opId', {
templateUrl: '/assets/partials/storageDetailsView.html'
})
.when('/storage/edit/:opId', {
templateUrl: '/assets/partials/wip.html'
})
.when('/storage/edit/:_id/:pickId', {
templateUrl: '/assets/partials/wip.html'
})
.when('/storage/picking/:_id', {
templateUrl: '/assets/partials/storagePicking.html'
})
.when('/stock', {
templateUrl: '/assets/partials/stockView.html'
})
.when('/stock/:_id', {
templateUrl: '/assets/partials/wip.html'
})
.when('/stock/details/:prodId', {
templateUrl: '/assets/partials/stockView.html'
})
.otherwise({redirectTo: '/'})])
.config(['$locationProvider', ($locationProvider) ->
$locationProvider.html5Mode({
enabled: true,
requireBase: false
})])
@commonModule = angular.module('myApp.common', [])
@controllersModule = angular.module('myApp.controllers', [])
@servicesModule = angular.module('myApp.services', [])
@modelsModule = angular.module('myApp.models', [])
@directivesModule = angular.module('myApp.directives', [])
@filtersModule = angular.module('myApp.filters', [])
| 64063 |
dependencies = [
'ngRoute',
'ui.bootstrap',
'myApp.filters',
'myApp.services',
'myApp.controllers',
'myApp.directives',
'myApp.common',
'myApp.routeConfig'
]
app = angular.module('myApp', dependencies)
angular.module('myApp.routeConfig', ['ngRoute'])
.config(['$routeProvider', ($routeProvider) ->
$routeProvider
.when('/', {
templateUrl: '/assets/partials/storageView.html'
})
.when('/users/create', {
templateUrl: '/assets/partials/userCreate.html'
})
.when('/users/edit/:firstName/:<NAME>', {
templateUrl: '/assets/partials/userUpdate.html'
})
.when('/product', {
templateUrl: '/assets/partials/productView.html'
})
.when('/product/create', {
templateUrl: '/assets/partials/productCreate.html'
})
.when('/product/edit/:_id', {
templateUtl: '/assets/partials/wip.html'
})
.when('/storage', {
templateUrl: '/assets/partials/storageView.html'
})
.when('/storage/create', {
templateUrl: '/assets/partials/storageCreate.html'
})
.when('/storage/details/:opId', {
templateUrl: '/assets/partials/storageDetailsView.html'
})
.when('/storage/edit/:opId', {
templateUrl: '/assets/partials/wip.html'
})
.when('/storage/edit/:_id/:pickId', {
templateUrl: '/assets/partials/wip.html'
})
.when('/storage/picking/:_id', {
templateUrl: '/assets/partials/storagePicking.html'
})
.when('/stock', {
templateUrl: '/assets/partials/stockView.html'
})
.when('/stock/:_id', {
templateUrl: '/assets/partials/wip.html'
})
.when('/stock/details/:prodId', {
templateUrl: '/assets/partials/stockView.html'
})
.otherwise({redirectTo: '/'})])
.config(['$locationProvider', ($locationProvider) ->
$locationProvider.html5Mode({
enabled: true,
requireBase: false
})])
@commonModule = angular.module('myApp.common', [])
@controllersModule = angular.module('myApp.controllers', [])
@servicesModule = angular.module('myApp.services', [])
@modelsModule = angular.module('myApp.models', [])
@directivesModule = angular.module('myApp.directives', [])
@filtersModule = angular.module('myApp.filters', [])
| true |
dependencies = [
'ngRoute',
'ui.bootstrap',
'myApp.filters',
'myApp.services',
'myApp.controllers',
'myApp.directives',
'myApp.common',
'myApp.routeConfig'
]
app = angular.module('myApp', dependencies)
angular.module('myApp.routeConfig', ['ngRoute'])
.config(['$routeProvider', ($routeProvider) ->
$routeProvider
.when('/', {
templateUrl: '/assets/partials/storageView.html'
})
.when('/users/create', {
templateUrl: '/assets/partials/userCreate.html'
})
.when('/users/edit/:firstName/:PI:NAME:<NAME>END_PI', {
templateUrl: '/assets/partials/userUpdate.html'
})
.when('/product', {
templateUrl: '/assets/partials/productView.html'
})
.when('/product/create', {
templateUrl: '/assets/partials/productCreate.html'
})
.when('/product/edit/:_id', {
templateUtl: '/assets/partials/wip.html'
})
.when('/storage', {
templateUrl: '/assets/partials/storageView.html'
})
.when('/storage/create', {
templateUrl: '/assets/partials/storageCreate.html'
})
.when('/storage/details/:opId', {
templateUrl: '/assets/partials/storageDetailsView.html'
})
.when('/storage/edit/:opId', {
templateUrl: '/assets/partials/wip.html'
})
.when('/storage/edit/:_id/:pickId', {
templateUrl: '/assets/partials/wip.html'
})
.when('/storage/picking/:_id', {
templateUrl: '/assets/partials/storagePicking.html'
})
.when('/stock', {
templateUrl: '/assets/partials/stockView.html'
})
.when('/stock/:_id', {
templateUrl: '/assets/partials/wip.html'
})
.when('/stock/details/:prodId', {
templateUrl: '/assets/partials/stockView.html'
})
.otherwise({redirectTo: '/'})])
.config(['$locationProvider', ($locationProvider) ->
$locationProvider.html5Mode({
enabled: true,
requireBase: false
})])
@commonModule = angular.module('myApp.common', [])
@controllersModule = angular.module('myApp.controllers', [])
@servicesModule = angular.module('myApp.services', [])
@modelsModule = angular.module('myApp.models', [])
@directivesModule = angular.module('myApp.directives', [])
@filtersModule = angular.module('myApp.filters', [])
|
[
{
"context": "data'\n process.env.FOURSQUARE_CLIENT_SECRET = 'somedata'\n process.env.FOURSQUARE_ACCESS_TOKEN = 'somed",
"end": 322,
"score": 0.7423150539398193,
"start": 314,
"tag": "KEY",
"value": "somedata"
},
{
"context": "edata'\n process.env.FOURSQUARE_ACCESS_TOKEN = 'somedata'\n\n @robot =\n respond: sinon.spy()\n h",
"end": 375,
"score": 0.7176141738891602,
"start": 367,
"tag": "PASSWORD",
"value": "somedata"
}
] | test/foursquare-locator_test.coffee | watson/hubot-foursquare-locator | 1 | chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
expect = chai.expect
describe 'foursquare-locator', ->
beforeEach ->
# Must be defined so as to avoid throwing errors in lower scripts
process.env.FOURSQUARE_CLIENT_ID = 'somedata'
process.env.FOURSQUARE_CLIENT_SECRET = 'somedata'
process.env.FOURSQUARE_ACCESS_TOKEN = 'somedata'
@robot =
respond: sinon.spy()
hear: sinon.spy()
require('../src/foursquare-locator')(@robot)
it 'registers a respond listener for friends', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) friends/i)
it 'registers a respond listener for approve', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) approve/i)
it 'registers a respond listener for register', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) register/i)
it 'registers a respond listener for mapping user as ID', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) ([a-zA-Z0-9]+) as ([0-9]+)/i)
it 'registers a respond listener for forgetting a user', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) forget ([a-zA-Z0-9]+)/i)
it 'registers a hear listener', ->
expect(@robot.respond).to.have.been.calledWith(/where[ ']i?s ([a-zA-Z0-9 ]+)(\?)?$/i)
| 205160 | chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
expect = chai.expect
describe 'foursquare-locator', ->
beforeEach ->
# Must be defined so as to avoid throwing errors in lower scripts
process.env.FOURSQUARE_CLIENT_ID = 'somedata'
process.env.FOURSQUARE_CLIENT_SECRET = '<KEY>'
process.env.FOURSQUARE_ACCESS_TOKEN = '<KEY>'
@robot =
respond: sinon.spy()
hear: sinon.spy()
require('../src/foursquare-locator')(@robot)
it 'registers a respond listener for friends', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) friends/i)
it 'registers a respond listener for approve', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) approve/i)
it 'registers a respond listener for register', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) register/i)
it 'registers a respond listener for mapping user as ID', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) ([a-zA-Z0-9]+) as ([0-9]+)/i)
it 'registers a respond listener for forgetting a user', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) forget ([a-zA-Z0-9]+)/i)
it 'registers a hear listener', ->
expect(@robot.respond).to.have.been.calledWith(/where[ ']i?s ([a-zA-Z0-9 ]+)(\?)?$/i)
| true | chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
expect = chai.expect
describe 'foursquare-locator', ->
beforeEach ->
# Must be defined so as to avoid throwing errors in lower scripts
process.env.FOURSQUARE_CLIENT_ID = 'somedata'
process.env.FOURSQUARE_CLIENT_SECRET = 'PI:KEY:<KEY>END_PI'
process.env.FOURSQUARE_ACCESS_TOKEN = 'PI:PASSWORD:<KEY>END_PI'
@robot =
respond: sinon.spy()
hear: sinon.spy()
require('../src/foursquare-locator')(@robot)
it 'registers a respond listener for friends', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) friends/i)
it 'registers a respond listener for approve', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) approve/i)
it 'registers a respond listener for register', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) register/i)
it 'registers a respond listener for mapping user as ID', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) ([a-zA-Z0-9]+) as ([0-9]+)/i)
it 'registers a respond listener for forgetting a user', ->
expect(@robot.respond).to.have.been.calledWith(/(foursquare|4sq|swarm) forget ([a-zA-Z0-9]+)/i)
it 'registers a hear listener', ->
expect(@robot.respond).to.have.been.calledWith(/where[ ']i?s ([a-zA-Z0-9 ]+)(\?)?$/i)
|
[
{
"context": "r a Go proverb\n#\n# Notes:\n# None\n#\n# Author:\n# Michael Ivey <michael.ivey@riotgames.com>\n\nproverbs = [\n\t\"Don'",
"end": 239,
"score": 0.9998641014099121,
"start": 227,
"tag": "NAME",
"value": "Michael Ivey"
},
{
"context": "#\n# Notes:\n# None\n#\n# Author:\n# Michael Ivey <michael.ivey@riotgames.com>\n\nproverbs = [\n\t\"Don't communicate by sharing mem",
"end": 267,
"score": 0.9999298453330994,
"start": 241,
"tag": "EMAIL",
"value": "michael.ivey@riotgames.com"
}
] | scripts/go-proverbs.coffee | RiotGamesMinions/lefay | 7 | # Description:
# Hear one of Rob Pike's Go Proverbs
# http://go-proverbs.github.io
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# go proverb - hear a Go proverb
#
# Notes:
# None
#
# Author:
# Michael Ivey <michael.ivey@riotgames.com>
proverbs = [
"Don't communicate by sharing memory, share memory by communicating.",
"Concurrency is not parallelism.",
"Channels orchestrate; mutexes serialize.",
"The bigger the interface, the weaker the abstraction.",
"Make the zero value useful.",
"interface{} says nothing.",
"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.",
"A little copying is better than a little dependency.",
"Syscall must always be guarded with build tags.",
"Cgo must always be guarded with build tags.",
"Cgo is not Go.",
"With the unsafe package there are no guarantees.",
"Clear is better than clever.",
"Reflection is never clear.",
"Errors are values.",
"Don't just check errors, handle them gracefully.",
"Design the architecture, name the components, document the details.",
"Documentation is for users.",
"Don't panic."
]
module.exports = (robot) ->
robot.hear /.*go proverb.*/i, (msg) ->
msg.send msg.random proverbs
| 93065 | # Description:
# Hear one of Rob Pike's Go Proverbs
# http://go-proverbs.github.io
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# go proverb - hear a Go proverb
#
# Notes:
# None
#
# Author:
# <NAME> <<EMAIL>>
proverbs = [
"Don't communicate by sharing memory, share memory by communicating.",
"Concurrency is not parallelism.",
"Channels orchestrate; mutexes serialize.",
"The bigger the interface, the weaker the abstraction.",
"Make the zero value useful.",
"interface{} says nothing.",
"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.",
"A little copying is better than a little dependency.",
"Syscall must always be guarded with build tags.",
"Cgo must always be guarded with build tags.",
"Cgo is not Go.",
"With the unsafe package there are no guarantees.",
"Clear is better than clever.",
"Reflection is never clear.",
"Errors are values.",
"Don't just check errors, handle them gracefully.",
"Design the architecture, name the components, document the details.",
"Documentation is for users.",
"Don't panic."
]
module.exports = (robot) ->
robot.hear /.*go proverb.*/i, (msg) ->
msg.send msg.random proverbs
| true | # Description:
# Hear one of Rob Pike's Go Proverbs
# http://go-proverbs.github.io
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# go proverb - hear a Go proverb
#
# Notes:
# None
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
proverbs = [
"Don't communicate by sharing memory, share memory by communicating.",
"Concurrency is not parallelism.",
"Channels orchestrate; mutexes serialize.",
"The bigger the interface, the weaker the abstraction.",
"Make the zero value useful.",
"interface{} says nothing.",
"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.",
"A little copying is better than a little dependency.",
"Syscall must always be guarded with build tags.",
"Cgo must always be guarded with build tags.",
"Cgo is not Go.",
"With the unsafe package there are no guarantees.",
"Clear is better than clever.",
"Reflection is never clear.",
"Errors are values.",
"Don't just check errors, handle them gracefully.",
"Design the architecture, name the components, document the details.",
"Documentation is for users.",
"Don't panic."
]
module.exports = (robot) ->
robot.hear /.*go proverb.*/i, (msg) ->
msg.send msg.random proverbs
|
[
{
"context": " father(abe, homer). \n father(homer, bart). \n father(homer, lisa).\"\n quer",
"end": 977,
"score": 0.6586806774139404,
"start": 973,
"tag": "NAME",
"value": "bart"
}
] | test/prolog.coffee | mattsouth/dprolog | 7 | should = require('chai').should()
Prolog = require '../src/prolog'
# NB Prolog parser is identical to Simple parser, hence no tests
describe 'Prolog', ->
it 'should match terms', ->
kb = Prolog.parseKb "english(jack).
english(jill)."
query = Prolog.parseQuery "english(X)"
iter = Prolog.solve(kb, query)
results = []
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal false
# check a second time to make sure emptied state is properly recorded
iter.hasNext().should.equal false
results.should.include 'english(jack)'
results.should.include 'english(jill)'
it 'should use rules', ->
kb = Prolog.parseKb "grandfather(X,Y) :- father(X,Z), father(Z,Y).
father(abe, homer).
father(homer, bart).
father(homer, lisa)."
query = Prolog.parseQuery "grandfather(abe, X)"
iter = Prolog.solve(kb, query)
results = []
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal false
# check a second time to make sure emptied state is properly recorded
iter.hasNext().should.equal false
results.should.include 'grandfather(abe, lisa)'
results.should.include 'grandfather(abe, bart)'
it 'should recurse (infinitely if you let it)', ->
kb = Prolog.parseKb "nat(z). nat(s(X)) :- nat(X)."
query = Prolog.parseQuery "nat(Y)"
iter = Prolog.solve(kb, query)
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(z)"
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(s(z))"
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(s(s(z)))"
# ad infinitum ...
# todo: compound query with unification between terms | 214205 | should = require('chai').should()
Prolog = require '../src/prolog'
# NB Prolog parser is identical to Simple parser, hence no tests
describe 'Prolog', ->
it 'should match terms', ->
kb = Prolog.parseKb "english(jack).
english(jill)."
query = Prolog.parseQuery "english(X)"
iter = Prolog.solve(kb, query)
results = []
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal false
# check a second time to make sure emptied state is properly recorded
iter.hasNext().should.equal false
results.should.include 'english(jack)'
results.should.include 'english(jill)'
it 'should use rules', ->
kb = Prolog.parseKb "grandfather(X,Y) :- father(X,Z), father(Z,Y).
father(abe, homer).
father(homer, <NAME>).
father(homer, lisa)."
query = Prolog.parseQuery "grandfather(abe, X)"
iter = Prolog.solve(kb, query)
results = []
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal false
# check a second time to make sure emptied state is properly recorded
iter.hasNext().should.equal false
results.should.include 'grandfather(abe, lisa)'
results.should.include 'grandfather(abe, bart)'
it 'should recurse (infinitely if you let it)', ->
kb = Prolog.parseKb "nat(z). nat(s(X)) :- nat(X)."
query = Prolog.parseQuery "nat(Y)"
iter = Prolog.solve(kb, query)
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(z)"
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(s(z))"
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(s(s(z)))"
# ad infinitum ...
# todo: compound query with unification between terms | true | should = require('chai').should()
Prolog = require '../src/prolog'
# NB Prolog parser is identical to Simple parser, hence no tests
describe 'Prolog', ->
it 'should match terms', ->
kb = Prolog.parseKb "english(jack).
english(jill)."
query = Prolog.parseQuery "english(X)"
iter = Prolog.solve(kb, query)
results = []
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal false
# check a second time to make sure emptied state is properly recorded
iter.hasNext().should.equal false
results.should.include 'english(jack)'
results.should.include 'english(jill)'
it 'should use rules', ->
kb = Prolog.parseKb "grandfather(X,Y) :- father(X,Z), father(Z,Y).
father(abe, homer).
father(homer, PI:NAME:<NAME>END_PI).
father(homer, lisa)."
query = Prolog.parseQuery "grandfather(abe, X)"
iter = Prolog.solve(kb, query)
results = []
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal true
results.push iter.next().toAnswerString()
iter.hasNext().should.equal false
# check a second time to make sure emptied state is properly recorded
iter.hasNext().should.equal false
results.should.include 'grandfather(abe, lisa)'
results.should.include 'grandfather(abe, bart)'
it 'should recurse (infinitely if you let it)', ->
kb = Prolog.parseKb "nat(z). nat(s(X)) :- nat(X)."
query = Prolog.parseQuery "nat(Y)"
iter = Prolog.solve(kb, query)
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(z)"
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(s(z))"
iter.hasNext().should.equal true
iter.next().toAnswerString().should.equal "nat(s(s(z)))"
# ad infinitum ...
# todo: compound query with unification between terms |
[
{
"context": " beforeEach ->\n @view.$('#password').val('test password')\n spyOn @view.model, 'sync'\n clickSubm",
"end": 1224,
"score": 0.9992348551750183,
"start": 1211,
"tag": "PASSWORD",
"value": "test password"
},
{
"context": "->\n beforeEach ->\n @view.$('#email').val('test@test.ru')\n spyOn @view.model, 'sync'\n clickSubm",
"end": 1688,
"score": 0.9999017715454102,
"start": 1676,
"tag": "EMAIL",
"value": "test@test.ru"
},
{
"context": "->\n beforeEach ->\n @view.$('#email').val('test@test.ru')\n @view.$('#password').val('test password')",
"end": 2149,
"score": 0.999921977519989,
"start": 2137,
"tag": "EMAIL",
"value": "test@test.ru"
},
{
"context": "l('test@test.ru')\n @view.$('#password').val('test password')\n spyOn @view.model, 'sync'\n clickSubm",
"end": 2197,
"score": 0.999158501625061,
"start": 2184,
"tag": "PASSWORD",
"value": "test password"
}
] | spec/javascripts/langtrainer_app/views/dialogs/sign_in_spec.js.coffee | beorc/langtrainer_frontend_backbone | 0 | describe "Langtrainer.LangtrainerApp.Views.Dialogs.SignIn", ->
clickSubmitButton = (view) ->
view.$('.js-submit').click()
beforeEach ->
Langtrainer.LangtrainerApp.clearCookies()
worldData = getJSONFixture('world.json')
@world = new Langtrainer.LangtrainerApp.Models.World
Langtrainer.LangtrainerApp.currentUser = new Langtrainer.LangtrainerApp.Models.User
@world.set(worldData)
@view = new Langtrainer.LangtrainerApp.Views.Dialogs.SignIn
@view.render()
it "should be a Backbone.View", ->
expect(@view).toEqual(jasmine.any(Backbone.View))
it "should render markup", ->
expect(@view.$('input#email')).toExist()
expect(@view.$('input#password')).toExist()
describe 'given an empty form', ->
beforeEach ->
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).toExist()
describe 'given an empty email', ->
beforeEach ->
@view.$('#password').val('test password')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).not.toExist()
describe 'given an empty password', ->
beforeEach ->
@view.$('#email').val('test@test.ru')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).not.toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).toExist()
describe 'given an filled form', ->
beforeEach ->
@view.$('#email').val('test@test.ru')
@view.$('#password').val('test password')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).not.toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).not.toExist()
| 71527 | describe "Langtrainer.LangtrainerApp.Views.Dialogs.SignIn", ->
clickSubmitButton = (view) ->
view.$('.js-submit').click()
beforeEach ->
Langtrainer.LangtrainerApp.clearCookies()
worldData = getJSONFixture('world.json')
@world = new Langtrainer.LangtrainerApp.Models.World
Langtrainer.LangtrainerApp.currentUser = new Langtrainer.LangtrainerApp.Models.User
@world.set(worldData)
@view = new Langtrainer.LangtrainerApp.Views.Dialogs.SignIn
@view.render()
it "should be a Backbone.View", ->
expect(@view).toEqual(jasmine.any(Backbone.View))
it "should render markup", ->
expect(@view.$('input#email')).toExist()
expect(@view.$('input#password')).toExist()
describe 'given an empty form', ->
beforeEach ->
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).toExist()
describe 'given an empty email', ->
beforeEach ->
@view.$('#password').val('<PASSWORD>')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).not.toExist()
describe 'given an empty password', ->
beforeEach ->
@view.$('#email').val('<EMAIL>')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).not.toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).toExist()
describe 'given an filled form', ->
beforeEach ->
@view.$('#email').val('<EMAIL>')
@view.$('#password').val('<PASSWORD>')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).not.toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).not.toExist()
| true | describe "Langtrainer.LangtrainerApp.Views.Dialogs.SignIn", ->
clickSubmitButton = (view) ->
view.$('.js-submit').click()
beforeEach ->
Langtrainer.LangtrainerApp.clearCookies()
worldData = getJSONFixture('world.json')
@world = new Langtrainer.LangtrainerApp.Models.World
Langtrainer.LangtrainerApp.currentUser = new Langtrainer.LangtrainerApp.Models.User
@world.set(worldData)
@view = new Langtrainer.LangtrainerApp.Views.Dialogs.SignIn
@view.render()
it "should be a Backbone.View", ->
expect(@view).toEqual(jasmine.any(Backbone.View))
it "should render markup", ->
expect(@view.$('input#email')).toExist()
expect(@view.$('input#password')).toExist()
describe 'given an empty form', ->
beforeEach ->
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).toExist()
describe 'given an empty email', ->
beforeEach ->
@view.$('#password').val('PI:PASSWORD:<PASSWORD>END_PI')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).not.toExist()
describe 'given an empty password', ->
beforeEach ->
@view.$('#email').val('PI:EMAIL:<EMAIL>END_PI')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).not.toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).not.toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).toExist()
describe 'given an filled form', ->
beforeEach ->
@view.$('#email').val('PI:EMAIL:<EMAIL>END_PI')
@view.$('#password').val('PI:PASSWORD:<PASSWORD>END_PI')
spyOn @view.model, 'sync'
clickSubmitButton(@view)
it 'should not send request', ->
expect(@view.model.sync).toHaveBeenCalled()
it 'should render validation errors', ->
expect(@view.$('.form-group.email.has-error p.help-block')).not.toExist()
expect(@view.$('.form-group.password.has-error p.help-block')).not.toExist()
|
[
{
"context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n\nLicensed under the A",
"end": 39,
"score": 0.9998894929885864,
"start": 26,
"tag": "NAME",
"value": "Stephan Jorek"
},
{
"context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n\nLicensed under the Apache License, Version 2.",
"end": 64,
"score": 0.9999324679374695,
"start": 41,
"tag": "EMAIL",
"value": "stephan.jorek@gmail.com"
}
] | src/Dom/Traversal/ElementTraversal.coffee | sjorek/goatee.js | 0 | ###
© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com>
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.
###
#~ require
{Level1NodeTypeMatcher} = require '../Traversal'
#~ export
exports = module?.exports ? this
# ElementTraversal
# ================================
# --------------------------------
# A class to hold state for a DOM traversal.
#
# This implementation depends on the `ElementTraversal`-interface providing
# `node.firstElementChild` and `node.nextElementSibling`.
#
# @public
# @class ElementTraversal
# @extends goatee.Dom.Traversal
# @namespace goatee.Dom.Traversal
# @see [`firstElementChild` Interface-Specification](http://dom.spec.whatwg.org/#dom-parentnode-firstelementchild)
# @see [`firstElementChild` Attribute-Specification](http://www.w3.org/TR/ElementTraversal/#attribute-firstElementChild)
# @see [`nextElementSibling` Interface-Specification](http://dom.spec.whatwg.org/#dom-childnode-nextelementsibling)
# @see [`nextElementSibling` Attribute-Specification](http://www.w3.org/TR/ElementTraversal/#attribute-nextElementSibling)
exports.ElementTraversal = \
class ElementTraversal extends Traversal
# --------------------------------
# Collect a single node's immediate child-nodes.
#
# @public
# @method collect
# @param {Node} node The current node of the traversal
# @return {Array.<Node>}
# @see [`firstElementChild` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ElementTraversal.firstElementChild)
# @see [`nextElementSibling` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ElementTraversal.nextElementSibling)
collect: (node) ->
result = []
# Internet Explorer 6-8 supported it, but erroneously include Comment nodes.
`for (var child = node.firstElementChild; child; child = child.nextElementSibling) {
result.push(child);
}`
return result
# --------------------------------
# Creates the `Traversal`-instance.
#
# @static
# @public
# @method create
# @param {Function} callback A function, called for each traversed node
# @return {goatee.Dom.Traversal}
@create: (callback) ->
new GeckoElementTraversal callback
| 33431 | ###
© Copyright 2013-2014 <NAME> <<EMAIL>>
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.
###
#~ require
{Level1NodeTypeMatcher} = require '../Traversal'
#~ export
exports = module?.exports ? this
# ElementTraversal
# ================================
# --------------------------------
# A class to hold state for a DOM traversal.
#
# This implementation depends on the `ElementTraversal`-interface providing
# `node.firstElementChild` and `node.nextElementSibling`.
#
# @public
# @class ElementTraversal
# @extends goatee.Dom.Traversal
# @namespace goatee.Dom.Traversal
# @see [`firstElementChild` Interface-Specification](http://dom.spec.whatwg.org/#dom-parentnode-firstelementchild)
# @see [`firstElementChild` Attribute-Specification](http://www.w3.org/TR/ElementTraversal/#attribute-firstElementChild)
# @see [`nextElementSibling` Interface-Specification](http://dom.spec.whatwg.org/#dom-childnode-nextelementsibling)
# @see [`nextElementSibling` Attribute-Specification](http://www.w3.org/TR/ElementTraversal/#attribute-nextElementSibling)
exports.ElementTraversal = \
class ElementTraversal extends Traversal
# --------------------------------
# Collect a single node's immediate child-nodes.
#
# @public
# @method collect
# @param {Node} node The current node of the traversal
# @return {Array.<Node>}
# @see [`firstElementChild` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ElementTraversal.firstElementChild)
# @see [`nextElementSibling` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ElementTraversal.nextElementSibling)
collect: (node) ->
result = []
# Internet Explorer 6-8 supported it, but erroneously include Comment nodes.
`for (var child = node.firstElementChild; child; child = child.nextElementSibling) {
result.push(child);
}`
return result
# --------------------------------
# Creates the `Traversal`-instance.
#
# @static
# @public
# @method create
# @param {Function} callback A function, called for each traversed node
# @return {goatee.Dom.Traversal}
@create: (callback) ->
new GeckoElementTraversal callback
| true | ###
© Copyright 2013-2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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.
###
#~ require
{Level1NodeTypeMatcher} = require '../Traversal'
#~ export
exports = module?.exports ? this
# ElementTraversal
# ================================
# --------------------------------
# A class to hold state for a DOM traversal.
#
# This implementation depends on the `ElementTraversal`-interface providing
# `node.firstElementChild` and `node.nextElementSibling`.
#
# @public
# @class ElementTraversal
# @extends goatee.Dom.Traversal
# @namespace goatee.Dom.Traversal
# @see [`firstElementChild` Interface-Specification](http://dom.spec.whatwg.org/#dom-parentnode-firstelementchild)
# @see [`firstElementChild` Attribute-Specification](http://www.w3.org/TR/ElementTraversal/#attribute-firstElementChild)
# @see [`nextElementSibling` Interface-Specification](http://dom.spec.whatwg.org/#dom-childnode-nextelementsibling)
# @see [`nextElementSibling` Attribute-Specification](http://www.w3.org/TR/ElementTraversal/#attribute-nextElementSibling)
exports.ElementTraversal = \
class ElementTraversal extends Traversal
# --------------------------------
# Collect a single node's immediate child-nodes.
#
# @public
# @method collect
# @param {Node} node The current node of the traversal
# @return {Array.<Node>}
# @see [`firstElementChild` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ElementTraversal.firstElementChild)
# @see [`nextElementSibling` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ElementTraversal.nextElementSibling)
collect: (node) ->
result = []
# Internet Explorer 6-8 supported it, but erroneously include Comment nodes.
`for (var child = node.firstElementChild; child; child = child.nextElementSibling) {
result.push(child);
}`
return result
# --------------------------------
# Creates the `Traversal`-instance.
#
# @static
# @public
# @method create
# @param {Function} callback A function, called for each traversed node
# @return {goatee.Dom.Traversal}
@create: (callback) ->
new GeckoElementTraversal callback
|
[
{
"context": "id: 2\nname: \"Find pension contact details\"\ndescription: \"Lets users",
"end": 17,
"score": 0.5761334300041199,
"start": 13,
"tag": "NAME",
"value": "Find"
},
{
"context": "vision\"\nlocation: \"Newcastle\"\nphase: \"live\"\nsro: \"Graeme Wallace\"\nservice_man: \"Daniel McLauglin\"\nphase_history:\n ",
"end": 260,
"score": 0.9998878240585327,
"start": 246,
"tag": "NAME",
"value": "Graeme Wallace"
},
{
"context": "phase: \"live\"\nsro: \"Graeme Wallace\"\nservice_man: \"Daniel McLauglin\"\nphase_history:\n discovery: [\n {\n label:",
"end": 292,
"score": 0.9998857378959656,
"start": 276,
"tag": "NAME",
"value": "Daniel McLauglin"
}
] | app/data/projects/find-lost-pension.cson | tsmorgan/dwp-ux-work | 0 | id: 2
name: "Find pension contact details"
description: "Lets users find contact details for pension schemes they may have paid into so they can get money they may be owed."
theme: "Retirement Provision"
location: "Newcastle"
phase: "live"
sro: "Graeme Wallace"
service_man: "Daniel McLauglin"
phase_history:
discovery: [
{
label: "Completed"
date: "February 2015"
}
]
alpha: [
{
label: "Completed"
date: "June 2015"
}
]
beta: [
{
label: "Started"
date: "July 2015"
}
{
label: "Private beta started"
date: "October 2015"
}
{
label: "Public beta Completed"
date: "April 2016"
}
]
live: [
{
label: "Live service assessment"
date: "April 2016"
}
]
priority: "High" | 190301 | id: 2
name: "<NAME> pension contact details"
description: "Lets users find contact details for pension schemes they may have paid into so they can get money they may be owed."
theme: "Retirement Provision"
location: "Newcastle"
phase: "live"
sro: "<NAME>"
service_man: "<NAME>"
phase_history:
discovery: [
{
label: "Completed"
date: "February 2015"
}
]
alpha: [
{
label: "Completed"
date: "June 2015"
}
]
beta: [
{
label: "Started"
date: "July 2015"
}
{
label: "Private beta started"
date: "October 2015"
}
{
label: "Public beta Completed"
date: "April 2016"
}
]
live: [
{
label: "Live service assessment"
date: "April 2016"
}
]
priority: "High" | true | id: 2
name: "PI:NAME:<NAME>END_PI pension contact details"
description: "Lets users find contact details for pension schemes they may have paid into so they can get money they may be owed."
theme: "Retirement Provision"
location: "Newcastle"
phase: "live"
sro: "PI:NAME:<NAME>END_PI"
service_man: "PI:NAME:<NAME>END_PI"
phase_history:
discovery: [
{
label: "Completed"
date: "February 2015"
}
]
alpha: [
{
label: "Completed"
date: "June 2015"
}
]
beta: [
{
label: "Started"
date: "July 2015"
}
{
label: "Private beta started"
date: "October 2015"
}
{
label: "Public beta Completed"
date: "April 2016"
}
]
live: [
{
label: "Live service assessment"
date: "April 2016"
}
]
priority: "High" |
[
{
"context": ") ->\n\t\n\tconsole.log \"// Framer #{version} (c) 2014 Koen Bok\"\n\tconsole.log \"// https://github.com/koenbok/Fram",
"end": 147,
"score": 0.9982656240463257,
"start": 139,
"tag": "NAME",
"value": "Koen Bok"
},
{
"context": "014 Koen Bok\"\n\tconsole.log \"// https://github.com/koenbok/Framer\\n\"\n\t\n\tconsole.log \"window.FramerVersion = ",
"end": 192,
"score": 0.9970210194587708,
"start": 185,
"tag": "USERNAME",
"value": "koenbok"
}
] | scripts/banner.coffee | BreezeLife/Framer | 1 | {exec} = require "child_process"
{getVersion} = require "./version"
getVersion (version) ->
console.log "// Framer #{version} (c) 2014 Koen Bok"
console.log "// https://github.com/koenbok/Framer\n"
console.log "window.FramerVersion = \"#{version}\";\n\n"
| 146536 | {exec} = require "child_process"
{getVersion} = require "./version"
getVersion (version) ->
console.log "// Framer #{version} (c) 2014 <NAME>"
console.log "// https://github.com/koenbok/Framer\n"
console.log "window.FramerVersion = \"#{version}\";\n\n"
| true | {exec} = require "child_process"
{getVersion} = require "./version"
getVersion (version) ->
console.log "// Framer #{version} (c) 2014 PI:NAME:<NAME>END_PI"
console.log "// https://github.com/koenbok/Framer\n"
console.log "window.FramerVersion = \"#{version}\";\n\n"
|
[
{
"context": " Node.js scripts,\n# see https://github.com/dannycoates/node-inspector\n#\n# Copyright 2012 Mindspace, ",
"end": 167,
"score": 0.9997045993804932,
"start": 156,
"tag": "USERNAME",
"value": "dannycoates"
},
{
"context": "\t\t\t\t\t'local_port' : 8000\n\t\t\t\t\t'local_host' : '127.0.0.1'\n\n\t\t\t\t\t'remote_port' : 8080\n\t\t\t\t\t'remote_host' ",
"end": 713,
"score": 0.9997944235801697,
"start": 704,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "\t\t\t\t\t'remote_port' : 8080\n\t\t\t\t\t'remote_host' : '166.78.24.115'\n\n\t\t\t\t\t# Only used to explicity define the local,",
"end": 779,
"score": 0.9997864961624146,
"start": 766,
"tag": "IP_ADDRESS",
"value": "166.78.24.115"
}
] | tools/webserver/run.coffee | tiarebalbi/angularjs-Quizzler | 226 | # ************************************************
# Build HTTP and HTTP_PROXY servers
#
# Note: to debug Node.js scripts,
# see https://github.com/dannycoates/node-inspector
#
# Copyright 2012 Mindspace, LLC.
# ************************************************
# Include the HTTP and HTTP Proxy classes
# @see http://nodejs.org/docs/v0.4.2/api/modules.html
# Routes all `matching` calls from local_port to remote_port. Only urls matching the
#
ext = require('httpServers' )
fs = require( 'fs' )
# Main application
#
main = (options) ->
options ||= {
'proxy_enabled': false
'proxy_regexp' : /^\/app\/api/
'local_port' : 8000
'local_host' : '127.0.0.1'
'remote_port' : 8080
'remote_host' : '166.78.24.115'
# Only used to explicity define the local, hidden web server port
#'silent_port' : 8000
}
# Primary server, proxies specific GETs to remote web
# server or to local web server
new ext.HttpProxyServer() .start( options )
return
# Auto-start
#
main() | 206761 | # ************************************************
# Build HTTP and HTTP_PROXY servers
#
# Note: to debug Node.js scripts,
# see https://github.com/dannycoates/node-inspector
#
# Copyright 2012 Mindspace, LLC.
# ************************************************
# Include the HTTP and HTTP Proxy classes
# @see http://nodejs.org/docs/v0.4.2/api/modules.html
# Routes all `matching` calls from local_port to remote_port. Only urls matching the
#
ext = require('httpServers' )
fs = require( 'fs' )
# Main application
#
main = (options) ->
options ||= {
'proxy_enabled': false
'proxy_regexp' : /^\/app\/api/
'local_port' : 8000
'local_host' : '127.0.0.1'
'remote_port' : 8080
'remote_host' : '192.168.3.11'
# Only used to explicity define the local, hidden web server port
#'silent_port' : 8000
}
# Primary server, proxies specific GETs to remote web
# server or to local web server
new ext.HttpProxyServer() .start( options )
return
# Auto-start
#
main() | true | # ************************************************
# Build HTTP and HTTP_PROXY servers
#
# Note: to debug Node.js scripts,
# see https://github.com/dannycoates/node-inspector
#
# Copyright 2012 Mindspace, LLC.
# ************************************************
# Include the HTTP and HTTP Proxy classes
# @see http://nodejs.org/docs/v0.4.2/api/modules.html
# Routes all `matching` calls from local_port to remote_port. Only urls matching the
#
ext = require('httpServers' )
fs = require( 'fs' )
# Main application
#
main = (options) ->
options ||= {
'proxy_enabled': false
'proxy_regexp' : /^\/app\/api/
'local_port' : 8000
'local_host' : '127.0.0.1'
'remote_port' : 8080
'remote_host' : 'PI:IP_ADDRESS:192.168.3.11END_PI'
# Only used to explicity define the local, hidden web server port
#'silent_port' : 8000
}
# Primary server, proxies specific GETs to remote web
# server or to local web server
new ext.HttpProxyServer() .start( options )
return
# Auto-start
#
main() |
[
{
"context": ">\n router.get '/', (next) ->\n @body = \"Hi, I'm Obi.\"\n @status = 200\n yield next\n\n router.post",
"end": 103,
"score": 0.9286065101623535,
"start": 100,
"tag": "NAME",
"value": "Obi"
}
] | src/routes.coffee | burtonjc/obi | 0 | _ = require 'lodash'
module.exports = (router) ->
router.get '/', (next) ->
@body = "Hi, I'm Obi."
@status = 200
yield next
router.post '/messages', (next) ->
message = @request.body.message
plugins = [require './plugins/github']
responses = {}
_.each plugins, (plugin) ->
if plugin.caresAbout message
responses[plugin.name] = plugin.respondTo message
@status = 200
@body = responses
yield next
| 49364 | _ = require 'lodash'
module.exports = (router) ->
router.get '/', (next) ->
@body = "Hi, I'm <NAME>."
@status = 200
yield next
router.post '/messages', (next) ->
message = @request.body.message
plugins = [require './plugins/github']
responses = {}
_.each plugins, (plugin) ->
if plugin.caresAbout message
responses[plugin.name] = plugin.respondTo message
@status = 200
@body = responses
yield next
| true | _ = require 'lodash'
module.exports = (router) ->
router.get '/', (next) ->
@body = "Hi, I'm PI:NAME:<NAME>END_PI."
@status = 200
yield next
router.post '/messages', (next) ->
message = @request.body.message
plugins = [require './plugins/github']
responses = {}
_.each plugins, (plugin) ->
if plugin.caresAbout message
responses[plugin.name] = plugin.respondTo message
@status = 200
@body = responses
yield next
|
[
{
"context": "or for word representations (spaces)\n#\n# Author: Pontus Stenetorp <pontus stenetorp se>\n# Version: 2012-09-22\n\n",
"end": 167,
"score": 0.9998955726623535,
"start": 151,
"tag": "NAME",
"value": "Pontus Stenetorp"
}
] | src/coffee/picard.coffee | DrDub/picard | 1 | # vim:set ft=coffee ts=4 sw=4 sts=4 autoindent: encoding=utf-8:
# Picard - a visualiser and navigator for word representations (spaces)
#
# Author: Pontus Stenetorp <pontus stenetorp se>
# Version: 2012-09-22
$ = jQuery
# TODO: These should not be hard-coded
BORDER = 50
WIDTH = 1024
HEIGHT = 768
class Picard
constructor: (anchor_xpath, file_xpath) ->
@anchor_elem = $ anchor_xpath
@file_elem = $ file_xpath
# Attach our file change logic
@file_elem.change (evt) => @on_file_change evt
run: ->
@anchor_elem.svg onLoad: => do @on_load
on_load: ->
@svg = @anchor_elem.svg 'get'
on_file_change: (evt) ->
oevt = evt.originalEvent
file = oevt.target.files[0]
reader = new FileReader
reader.onload = (evt) => @on_file_read evt
reader.readAsText file
on_file_read: (evt) ->
# TODO: Extend to support more formats
lbl_space = {}
for line in evt.target.result.split '\n' when line
soup = line.split '\t'
lbl = soup[0]
lbl_pos = (parseFloat val for val, i in soup when i > 0)
lbl_space[lbl] = lbl_pos
@visualise lbl_space
visualise: (lbl_space) ->
for lbl, lbl_pos of lbl_space
x_pos = BORDER + lbl_pos[0] * (WIDTH - BORDER)
y_pos = BORDER + lbl_pos[1] * (HEIGHT - BORDER)
@svg.text x_pos, y_pos, lbl, 'text-anchor': 'middle'
# Export to the global namespace
root = exports ? this
root.Picard = Picard
| 28055 | # vim:set ft=coffee ts=4 sw=4 sts=4 autoindent: encoding=utf-8:
# Picard - a visualiser and navigator for word representations (spaces)
#
# Author: <NAME> <pontus stenetorp se>
# Version: 2012-09-22
$ = jQuery
# TODO: These should not be hard-coded
BORDER = 50
WIDTH = 1024
HEIGHT = 768
class Picard
constructor: (anchor_xpath, file_xpath) ->
@anchor_elem = $ anchor_xpath
@file_elem = $ file_xpath
# Attach our file change logic
@file_elem.change (evt) => @on_file_change evt
run: ->
@anchor_elem.svg onLoad: => do @on_load
on_load: ->
@svg = @anchor_elem.svg 'get'
on_file_change: (evt) ->
oevt = evt.originalEvent
file = oevt.target.files[0]
reader = new FileReader
reader.onload = (evt) => @on_file_read evt
reader.readAsText file
on_file_read: (evt) ->
# TODO: Extend to support more formats
lbl_space = {}
for line in evt.target.result.split '\n' when line
soup = line.split '\t'
lbl = soup[0]
lbl_pos = (parseFloat val for val, i in soup when i > 0)
lbl_space[lbl] = lbl_pos
@visualise lbl_space
visualise: (lbl_space) ->
for lbl, lbl_pos of lbl_space
x_pos = BORDER + lbl_pos[0] * (WIDTH - BORDER)
y_pos = BORDER + lbl_pos[1] * (HEIGHT - BORDER)
@svg.text x_pos, y_pos, lbl, 'text-anchor': 'middle'
# Export to the global namespace
root = exports ? this
root.Picard = Picard
| true | # vim:set ft=coffee ts=4 sw=4 sts=4 autoindent: encoding=utf-8:
# Picard - a visualiser and navigator for word representations (spaces)
#
# Author: PI:NAME:<NAME>END_PI <pontus stenetorp se>
# Version: 2012-09-22
$ = jQuery
# TODO: These should not be hard-coded
BORDER = 50
WIDTH = 1024
HEIGHT = 768
class Picard
constructor: (anchor_xpath, file_xpath) ->
@anchor_elem = $ anchor_xpath
@file_elem = $ file_xpath
# Attach our file change logic
@file_elem.change (evt) => @on_file_change evt
run: ->
@anchor_elem.svg onLoad: => do @on_load
on_load: ->
@svg = @anchor_elem.svg 'get'
on_file_change: (evt) ->
oevt = evt.originalEvent
file = oevt.target.files[0]
reader = new FileReader
reader.onload = (evt) => @on_file_read evt
reader.readAsText file
on_file_read: (evt) ->
# TODO: Extend to support more formats
lbl_space = {}
for line in evt.target.result.split '\n' when line
soup = line.split '\t'
lbl = soup[0]
lbl_pos = (parseFloat val for val, i in soup when i > 0)
lbl_space[lbl] = lbl_pos
@visualise lbl_space
visualise: (lbl_space) ->
for lbl, lbl_pos of lbl_space
x_pos = BORDER + lbl_pos[0] * (WIDTH - BORDER)
y_pos = BORDER + lbl_pos[1] * (HEIGHT - BORDER)
@svg.text x_pos, y_pos, lbl, 'text-anchor': 'middle'
# Export to the global namespace
root = exports ? this
root.Picard = Picard
|
[
{
"context": "corporates code from [markmon](https://github.com/yyjhao/markmon)\n# covered by the following terms:\n#\n# Co",
"end": 70,
"score": 0.9992453455924988,
"start": 64,
"tag": "USERNAME",
"value": "yyjhao"
},
{
"context": "ed by the following terms:\n#\n# Copyright (c) 2014, Yao Yujian, http://yjyao.com\n#\n# Permission is hereby grante",
"end": 148,
"score": 0.9998263120651245,
"start": 138,
"tag": "NAME",
"value": "Yao Yujian"
}
] | packages/markdown-preview-plus/lib/two-dim-array.coffee | jarednipper/atom-config | 0 | # This file incorporates code from [markmon](https://github.com/yyjhao/markmon)
# covered by the following terms:
#
# Copyright (c) 2014, Yao Yujian, http://yjyao.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.
module.exports = class TwoDimArray
constructor: (rows, cols) ->
@_arr = new Array(rows*cols)
@row = rows
@col = cols
return
getInd: (row, col) ->
row*@col + col
get2DInd: (ind) ->
r: ind/@col | 0,
c: ind % @col
get: (row, col) ->
@_arr[@getInd(row, col)]
set: (row, col, val) ->
@_arr[row*@col + col] = val
return
rawGet: (ind) ->
@_arr[ind]
| 208055 | # This file incorporates code from [markmon](https://github.com/yyjhao/markmon)
# covered by the following terms:
#
# Copyright (c) 2014, <NAME>, http://yjyao.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.
module.exports = class TwoDimArray
constructor: (rows, cols) ->
@_arr = new Array(rows*cols)
@row = rows
@col = cols
return
getInd: (row, col) ->
row*@col + col
get2DInd: (ind) ->
r: ind/@col | 0,
c: ind % @col
get: (row, col) ->
@_arr[@getInd(row, col)]
set: (row, col, val) ->
@_arr[row*@col + col] = val
return
rawGet: (ind) ->
@_arr[ind]
| true | # This file incorporates code from [markmon](https://github.com/yyjhao/markmon)
# covered by the following terms:
#
# Copyright (c) 2014, PI:NAME:<NAME>END_PI, http://yjyao.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.
module.exports = class TwoDimArray
constructor: (rows, cols) ->
@_arr = new Array(rows*cols)
@row = rows
@col = cols
return
getInd: (row, col) ->
row*@col + col
get2DInd: (ind) ->
r: ind/@col | 0,
c: ind % @col
get: (row, col) ->
@_arr[@getInd(row, col)]
set: (row, col, val) ->
@_arr[row*@col + col] = val
return
rawGet: (ind) ->
@_arr[ind]
|
[
{
"context": "36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36\"\n \"X-Redmine-API-Key\": @token\n\n options =",
"end": 9693,
"score": 0.8585287928581238,
"start": 9687,
"tag": "KEY",
"value": "537.36"
}
] | scripts/redmine.coffee | suvene/hubot-irc-scripts | 0 | # Description:
# Redmine
#
# Commands:
# #99999 - チケットのタイトルとか URL を取ってくるよ.
# hubot redmine (みんな|<nickname[,nickname]>) の実績[詳細] - 前営業日の実績を教えてもらおう!
# hubot redmine 実績チェック - 前営業日の実績をチェックするよ!
# hubot redmine <nickname> 実績チェック(する|しない) - 実績チェックの対象、または対象外にするよ!
# hubot redmine [yyyy-mm-dd] <#9999> 99[.25](h|時間) <活動> [コメント]- 実績を登録しよう!(日付省略時は前営業日になるよ) 例) hubot redmine #41 1.25h 製造 働いたよ!
#
# URLS:
# None.
#
# Notes:
# None.
URL = require('url')
QUERY = require('querystring')
request = require('request')
async = require('async')
rssparser = require('rssparser')
cronJob = require('cron').CronJob
_ = require('underscore')
DateUtil = require('date-utils')
PATH_ACTIVITY = process.env.HUBOT_REDMINE_ACTIVITY_URL
# {{{ SenpaiStorage
setSenpaiStorage = (robot, key, val) ->
storage = robot.brain.data.senpaiStorage ||= {}
storage[key] = val
# msg.send "storage #{key}, #{val}"
robot.brain.data.senpaiStorage = storage
getSenpaiStorage = (robot, key) ->
storage = robot.brain.data.senpaiStorage ||= {}
storage[key]
# }}}
# {{{ existsUser
existsUser = (robot, name) ->
name = name.toLowerCase()
return true if name is robot.name
users = robot.brain.data.usersInfo ||= {}
for u, v of users
if u is name
return true
return false
# }}}
whoIsThis = (robot, name) -> # {{{
name = name.toLowerCase()
return name if existsUser robot, name
gNicknames = getSenpaiStorage robot, 'NICKNAMES'
gNicknames ||= {}
return gNicknames[name] if gNicknames[name]
return null
# }}}
# {{{ UserInfo
setUserInfo = (robot, name, key, val) ->
name = name.toLowerCase()
return null unless existsUser robot, name
usersInfo = robot.brain.data.usersInfo ||= {}
usersInfo[name] ||= {}
usersInfo[name][key] = val
robot.brain.data.usersInfo = usersInfo
getUserInfo = (robot, name, key) ->
name = name.toLowerCase()
return null unless existsUser robot, name
usersInfo = robot.brain.data.usersInfo ||= {}
usersInfo[name] ||= {}
usersInfo[name][key]
# }}}
getPrevKadobi = (robot, date) -> # {{{
# console.log 'getPrevKadobi: ' + date.toYMD()
loop
week = date.getDay()
gHolidays = getSenpaiStorage robot, 'HOLIDAYS'
# console.log "week: #{week}"
if week is 0 or week is 6 or gHolidays[date.toYMD()]
date = date.addDays(-1)
continue
break
return date
# }}}
# from enumrations
getActivityId = (activity) -> # {{{
return 8 if activity.match /要件定義/
return 9 if activity.match /製造/
return 10 if activity.match /管理/
return 11 if activity.match /結テ仕/
return 12 if activity.match /調査/
return 13 if activity.match /見積/
return 14 if activity.match /リリース/
return 15 if activity.match /ヒアリング/
return 16 if activity.match /開発環境/
return 17 if activity.match /オペマニ/
return 18 if activity.match /営業/
return 24 if activity.match /社内手続き/
return 25 if activity.match /現状分析/
return 26 if activity.match /教育/
return 27 if activity.match /社内環境/
return 28 if activity.match /業務外作業/
return 29 if activity.match /引継/
return 30 if activity.match /土曜出勤/
return 31 if activity.match /提案活動/
return 32 if activity.match /単テ仕/
return 33 if activity.match /単テ実/
return 34 if activity.match /基本設計/
return 35 if activity.match /詳細設計/
return 37 if activity.match /結テ実/
return 38 if activity.match /PMO/
return 39 if activity.match /ユーザー環境/
return 40 if activity.match /サポート/
return null
# }}}
# tries to resolve ambiguous users by matching login or firstname# {{{
# redmine's user search is pretty broad (using login/name/email/etc.) so
# we're trying to just pull it in a bit and get a single user
#
# name - this should be the name you're trying to match
# data - this is the array of users from redmine
#
# returns an array with a single user, or the original array if nothing matched
resolveUsers = (name, data) ->
name = name.toLowerCase();
# try matching login
found = data.filter (user) -> user.login.toLowerCase() == name
return found if found.length == 1
# try first name
found = data.filter (user) -> user.firstname.toLowerCase() == name
return found if found.length == 1
# give up
data
# }}}
class Redmine # {{{
constructor: (@robot, @room, @url, @token) -> # {{{
endpoint = URL.parse(@url)
@protocol = endpoint.protocol
@hostname = endpoint.hostname
@pathname = endpoint.pathname.replace /^\/$/, ''
@url = "#{@protocol}//#{@hostname}#{@pathname}"
# }}}
Users: (params, callback, opt) -> # {{{
@get "/users.json", params, opt, callback
# }}}
Issues: (params, callback, opt) -> # {{{
@get "/issues.json", params, opt, callback
Issue: (id) ->
# console.log 'issue: ' + id
show: (params, callback, opt) =>
# console.log 'show: ' + id
paramsDef = {include: "children"}
params = _.extend(paramsDef, params);
@get "/issues/#{id}.json", params, opt, (err, data, response) =>
issue = data.issue
childrenCnt = issue.children?.length || 0
if childrenCnt is 0
callback null, issue
else
f = _.object(issue.children.map (child) =>
f2 = (cb) =>
# console.log 'child' + child.id + ': ' + child.subject
@Issue(child.id).show null, cb
[child.id, f2])
async.parallel f, (err, result) ->
return callback err, null if err or result is null
# console.log result
issue.children = (v for k, v of result)
callback null, issue
# }}}
TimeEntry: () -> # {{{
get: (params, callback, opt) =>
console.log 'TimeEntry#get'
paramsDefault =
from: Date.yesterday().toFormat('YYYY-MM-DD')
to: Date.yesterday().toFormat('YYYY-MM-DD')
params = _.extend(paramsDefault, params);
@get "/time_entries.json", params, opt, (err, data, response) =>
return callback err, null if err or data is null
timeEntries = data.time_entries
callback null, timeEntries
create: (attributes, callback, opt) =>
@post "/time_entries.json", {time_entry: attributes, su_userid: attributes.su_userid}, opt, callback
# }}}
getActivity: () -> # {{{
@get PATH_ACTIVITY, null, {type: "atom"}, (error, feed, response) =>
cacheActivities = getSenpaiStorage @robot, 'REDMINE_ACTIVITIES'
cacheActivities ||= []
dispcnt = 0
items = feed.items
for i, item of items
break if dispcnt >= 5
text = item.author + ': '
text += item.title
text += '(' + item.link + ')'
if item.summary
summary = item.summary.replace /<("[^"]*"|'[^']*'|[^'">])*>/g, ''
# console.log summary
matches = summary.match /([\r\n]*)([^\r\n]*)([\r\n]*)?(.*)/
text += ' ' + matches[2].substring(0, 60) if matches[2]
text += '...つづく...' if matches[4]
# console.log 'matches[1]:' + matches[1]
# console.log 'matches[2]:' + matches[2]
# console.log 'matches[4]:' + matches[4]
text = text.replace /<("[^"]*"|'[^']*'|[^'">])*>/g, ''
# console.log text
continue if text in cacheActivities
cacheActivities.push text
@send "[Redmineタイムライン] #{text}"
dispcnt++
while cacheActivities.length > 100
cacheActivities.shift()
setSenpaiStorage @robot, 'REDMINE_ACTIVITIES', cacheActivities
# }}}
checkJisseki: (date) -> # {{{
console.log 'checkJisseki'
usersInfo = @robot.brain.data.usersInfo ||= {}
users = {}
userCnt = 0
for u, v of usersInfo
continue if v['IS_NOT_CHECK_JISSEKI'] or u is @robot.name
userCnt++
console.log "check user: #{u}"
users[u] =
errNoInput: true
warnNoActivity: false
return unless userCnt
params =
from: date.toYMD()
to: date.toYMD()
@TimeEntry().get params, (err, timeEntries) =>
@send 'Error!: ' + err if err or timeEntries is null
for k, v of timeEntries
name = whoIsThis @robot, v.user.name
unless name
name = v.user.name
users[name] = {}
users[name].warnWho = true
users[name]?.errNoInput = false if users[name]?.errNoInput
users[name]?.warnNoActivity = true if v.activity.name is '【設定してください】'
reply = "#{params.from} の実績チェック\n"
for k, v of users
if v.errNoInput or v.warnNoActivity or v.warnWho
reply += "#{k}: "
reply += "<だれかわからない>" if v.warnWho
reply += "<実績入力なし>" if v.errNoInput
reply += "<活動が設定されてない実績あり>" if v.warnNoActivity
reply += "\n"
@send reply
# }}}
# private send, get, post, put # {{{
# Private: do a SEND
send: (msg) ->
response = new @robot.Response(@robot, {user : {id : -1, name : @room}, text : "none", done : false}, [])
# console.log @room + ':' + msg
response.send msg
# Private: do a GET request against the API
get: (path, params, opt, callback) ->
path = "#{path}?#{QUERY.stringify params}" if params?
# console.log 'get: ' + path
@request "GET", path, null, opt, callback
# Private: do a POST request against the API
post: (path, body, opt, callback) ->
@request "POST", path, body, opt, callback
# Private: do a PUT request against the API
put: (path, body, opt, callback) ->
@request "PUT", path, body, opt, callback
# }}}
# private request # {{{
request: (method, path, body, opt, callback) ->
optDefault =
"type": "json"
opt = _.extend(optDefault, opt)
headers =
"Content-Type": "application/json"
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36"
"X-Redmine-API-Key": @token
options =
"url" : "#{@url}#{path}"
"method" : method
"headers": headers
"timeout": 10000
"strictSSL": false
if method in ["POST", "PUT"]
if typeof(body) isnt "string"
body = JSON.stringify body
options.body = body
# options.headers["Content-Length"] = body.length
# console.log options.url
request options, (err, response, data) ->
if !err and response?.statusCode is 200
parsedData = data
try
parsedData = JSON.parse(data)
if opt.type is 'json'
callback null, (parsedData or { }), response
else if opt.type is 'atom'
rssparser.parseString data, {}, (error, feed) ->
# console.log feed
callback error, feed, response
else
console.log 'code: ' + response?.statusCode + ', url =>' + options.url
console.log err ||= response?.statusCode
callback err, data, response
# /private request }}}
# /Redmine }}}
module.exports = (robot) ->
redmine = new Redmine robot, process.env.HUBOT_REDMINE_SEND_ROOM, process.env.HUBOT_REDMINE_BASE_URL, process.env.HUBOT_REDMINE_TOKEN
# {{{ for cron
checkUpdate = () ->
getActivity()
getActivity = () ->
# console.log 'start Redmine getActivity!!!'
redmine.getActivity()
robot.respond /redmine activity/i, (msg) ->
getActivity()
checkJisseki = (date) ->
redmine.checkJisseki(date)
# *(sec) *(min) *(hour) *(day) *(month) *(day of the week)
new cronJob('*/10 * * * * *', () ->
checkUpdate()
).start()
new cronJob('0 15 9,12,15,18 * * *', () ->
date = getPrevKadobi(robot, Date.yesterday())
checkJisseki(date)
).start()
# }}}
robot.respond /redmine [\s]*([\S]*)[\s]*(?:は|を|の)?(?:実績)?(?:check|チェック)(?:実績)?(する|して|しない)?/i, (msg) -> # {{{
name = msg.match[1].replace /(実績|チェック)/, ''
flg = msg.match[2]
if name and flg
user = whoIsThis robot, name
return msg.send "#{name} は\"面通し\"されてない" unless user
isNotCheck = false
isNotCheck = true if flg.match /(しない)/
setUserInfo robot, user, 'IS_NOT_CHECK_JISSEKI', isNotCheck
msg.send "次から #{user} の実績チェック#{flg}!"
else
date = getPrevKadobi(@robot, Date.yesterday())
checkJisseki date
# }}}
robot.hear /.*(#(\d+)).*/, (msg) -> # {{{
id = msg.match[1].replace /#/, ""
return if isNaN id
redmine.Issue(id).show null, (err, issue) ->
return msg.send 'Error!: ' + err if err or issue is null
# console.log issue.children
url = "#{redmine.url}/issues/#{id}"
estimated_hours = issue.estimated_hours || 0
spent_hours = issue.spent_hours || 0
for i, v of issue.children
spent_hours += v.spent_hours || 0
msg.send "#{url} : #{issue.subject}(予: #{estimated_hours}h / 消: #{spent_hours}h) - #{issue.project.name}"
# }}}
robot.respond /redmine[\s]+([\S]*)[\s]*実績(詳細)?/, (msg) -> # {{{
command = msg.match[1]
return if msg.message.match /(check|チェック)/
d = getPrevKadobi(robot, Date.yesterday())
params =
from: d.toYMD()
to: d.toYMD()
isDetail = true if msg.match[2]
redmine.TimeEntry().get params, (err, timeEntries) ->
return msg.send 'Error!: ' + err if err or timeEntries is null
return msg.send "#{params.from} 〜 #{params.to} に誰も実績入れてません!" unless timeEntries.length
messages = {}
for k, v of timeEntries
id = v.user.id
messages[id] ||=
name: v.user.name
hours: 0
messages[id].hours += v.hours
if isDetail
messages[id].issues ||= {}
messages[id].issues[v.issue.id] ||=
hours: 0
comments: ''
messages[id].issues[v.issue.id].hours += v.hours
if v.comments
messages[id].issues[v.issue.id].comments += ',' if messages[id].issues[v.issue.id].comments
messages[id].issues[v.issue.id].comments += v.comments
reply = "#{params.from} 〜 #{params.to} の実績\n"
for id, m of messages
reply += "#{m.name}: #{m.hours}h\n"
if isDetail
for issueId, issue of m.issues
reply += " ##{issueId}: #{issue.hours}h #{issue.comments}\n"
msg.send reply
# }}}
robot.respond /redmine[\s]+(\d{2,4}(?:-|\/)\d{1,2}(?:-|\/)\d{1,2}[\s]+)?#(\d+)[\s]+(\d{1,2}(\.00?|\.25|\.50?|.75)?)[\s]*(?:h|時間)[\s]+([\S]+)(?:[\s]+"?([^"]+)"?)?/i, (msg) -> # {{{
userName = msg.message.user.name
user = whoIsThis robot, userName
return msg.send "誰?" unless user
[date, id, hours, hoursshosu, activity, userComments] = msg.match[1..6]
if date
date = new Date date
return msg.send "#{date} は日付じゃない" unless Date.validateDay(date.getDate(), date.getFullYear(), date.getMonth())
else
date = getPrevKadobi robot, Date.yesterday()
dateYMD = date.toYMD()
console.log dateYMD
if userComments?
comments = "#{userComments}"
else
comments = "Time logged by: #{msg.message.user.name}"
activityId = getActivityId activity
unless activityId
msg.reply "こんな\"活動\"はない > #{activity}\n"
msg.send " Usage: #{robot.name} redmine ##{id} #{hours}h 製造 #{activity}"
return
redmine.Users name:user, (err, data) =>
# console.log 'count:' + userName + ' ' + data.total_count
unless data.total_count > 0
msg.send "\"#{user}\" が redmine で見つけられない"
return false
redmineUser = resolveUsers(user, data.users)[0]
attributes =
issue_id: id
spent_on: dateYMD
hours: hours
comments: comments
su_userid: redmineUser.id
activity_id: activityId
redmine.TimeEntry().create attributes, (error, data, response) ->
if response?.statusCode == 201
msg.reply "よく頑張りました!(#{dateYMD} で登録)"
else
msg.reply "なんか失敗"
# }}}
| 51688 | # Description:
# Redmine
#
# Commands:
# #99999 - チケットのタイトルとか URL を取ってくるよ.
# hubot redmine (みんな|<nickname[,nickname]>) の実績[詳細] - 前営業日の実績を教えてもらおう!
# hubot redmine 実績チェック - 前営業日の実績をチェックするよ!
# hubot redmine <nickname> 実績チェック(する|しない) - 実績チェックの対象、または対象外にするよ!
# hubot redmine [yyyy-mm-dd] <#9999> 99[.25](h|時間) <活動> [コメント]- 実績を登録しよう!(日付省略時は前営業日になるよ) 例) hubot redmine #41 1.25h 製造 働いたよ!
#
# URLS:
# None.
#
# Notes:
# None.
URL = require('url')
QUERY = require('querystring')
request = require('request')
async = require('async')
rssparser = require('rssparser')
cronJob = require('cron').CronJob
_ = require('underscore')
DateUtil = require('date-utils')
PATH_ACTIVITY = process.env.HUBOT_REDMINE_ACTIVITY_URL
# {{{ SenpaiStorage
setSenpaiStorage = (robot, key, val) ->
storage = robot.brain.data.senpaiStorage ||= {}
storage[key] = val
# msg.send "storage #{key}, #{val}"
robot.brain.data.senpaiStorage = storage
getSenpaiStorage = (robot, key) ->
storage = robot.brain.data.senpaiStorage ||= {}
storage[key]
# }}}
# {{{ existsUser
existsUser = (robot, name) ->
name = name.toLowerCase()
return true if name is robot.name
users = robot.brain.data.usersInfo ||= {}
for u, v of users
if u is name
return true
return false
# }}}
whoIsThis = (robot, name) -> # {{{
name = name.toLowerCase()
return name if existsUser robot, name
gNicknames = getSenpaiStorage robot, 'NICKNAMES'
gNicknames ||= {}
return gNicknames[name] if gNicknames[name]
return null
# }}}
# {{{ UserInfo
setUserInfo = (robot, name, key, val) ->
name = name.toLowerCase()
return null unless existsUser robot, name
usersInfo = robot.brain.data.usersInfo ||= {}
usersInfo[name] ||= {}
usersInfo[name][key] = val
robot.brain.data.usersInfo = usersInfo
getUserInfo = (robot, name, key) ->
name = name.toLowerCase()
return null unless existsUser robot, name
usersInfo = robot.brain.data.usersInfo ||= {}
usersInfo[name] ||= {}
usersInfo[name][key]
# }}}
getPrevKadobi = (robot, date) -> # {{{
# console.log 'getPrevKadobi: ' + date.toYMD()
loop
week = date.getDay()
gHolidays = getSenpaiStorage robot, 'HOLIDAYS'
# console.log "week: #{week}"
if week is 0 or week is 6 or gHolidays[date.toYMD()]
date = date.addDays(-1)
continue
break
return date
# }}}
# from enumrations
getActivityId = (activity) -> # {{{
return 8 if activity.match /要件定義/
return 9 if activity.match /製造/
return 10 if activity.match /管理/
return 11 if activity.match /結テ仕/
return 12 if activity.match /調査/
return 13 if activity.match /見積/
return 14 if activity.match /リリース/
return 15 if activity.match /ヒアリング/
return 16 if activity.match /開発環境/
return 17 if activity.match /オペマニ/
return 18 if activity.match /営業/
return 24 if activity.match /社内手続き/
return 25 if activity.match /現状分析/
return 26 if activity.match /教育/
return 27 if activity.match /社内環境/
return 28 if activity.match /業務外作業/
return 29 if activity.match /引継/
return 30 if activity.match /土曜出勤/
return 31 if activity.match /提案活動/
return 32 if activity.match /単テ仕/
return 33 if activity.match /単テ実/
return 34 if activity.match /基本設計/
return 35 if activity.match /詳細設計/
return 37 if activity.match /結テ実/
return 38 if activity.match /PMO/
return 39 if activity.match /ユーザー環境/
return 40 if activity.match /サポート/
return null
# }}}
# tries to resolve ambiguous users by matching login or firstname# {{{
# redmine's user search is pretty broad (using login/name/email/etc.) so
# we're trying to just pull it in a bit and get a single user
#
# name - this should be the name you're trying to match
# data - this is the array of users from redmine
#
# returns an array with a single user, or the original array if nothing matched
resolveUsers = (name, data) ->
name = name.toLowerCase();
# try matching login
found = data.filter (user) -> user.login.toLowerCase() == name
return found if found.length == 1
# try first name
found = data.filter (user) -> user.firstname.toLowerCase() == name
return found if found.length == 1
# give up
data
# }}}
class Redmine # {{{
constructor: (@robot, @room, @url, @token) -> # {{{
endpoint = URL.parse(@url)
@protocol = endpoint.protocol
@hostname = endpoint.hostname
@pathname = endpoint.pathname.replace /^\/$/, ''
@url = "#{@protocol}//#{@hostname}#{@pathname}"
# }}}
Users: (params, callback, opt) -> # {{{
@get "/users.json", params, opt, callback
# }}}
Issues: (params, callback, opt) -> # {{{
@get "/issues.json", params, opt, callback
Issue: (id) ->
# console.log 'issue: ' + id
show: (params, callback, opt) =>
# console.log 'show: ' + id
paramsDef = {include: "children"}
params = _.extend(paramsDef, params);
@get "/issues/#{id}.json", params, opt, (err, data, response) =>
issue = data.issue
childrenCnt = issue.children?.length || 0
if childrenCnt is 0
callback null, issue
else
f = _.object(issue.children.map (child) =>
f2 = (cb) =>
# console.log 'child' + child.id + ': ' + child.subject
@Issue(child.id).show null, cb
[child.id, f2])
async.parallel f, (err, result) ->
return callback err, null if err or result is null
# console.log result
issue.children = (v for k, v of result)
callback null, issue
# }}}
TimeEntry: () -> # {{{
get: (params, callback, opt) =>
console.log 'TimeEntry#get'
paramsDefault =
from: Date.yesterday().toFormat('YYYY-MM-DD')
to: Date.yesterday().toFormat('YYYY-MM-DD')
params = _.extend(paramsDefault, params);
@get "/time_entries.json", params, opt, (err, data, response) =>
return callback err, null if err or data is null
timeEntries = data.time_entries
callback null, timeEntries
create: (attributes, callback, opt) =>
@post "/time_entries.json", {time_entry: attributes, su_userid: attributes.su_userid}, opt, callback
# }}}
getActivity: () -> # {{{
@get PATH_ACTIVITY, null, {type: "atom"}, (error, feed, response) =>
cacheActivities = getSenpaiStorage @robot, 'REDMINE_ACTIVITIES'
cacheActivities ||= []
dispcnt = 0
items = feed.items
for i, item of items
break if dispcnt >= 5
text = item.author + ': '
text += item.title
text += '(' + item.link + ')'
if item.summary
summary = item.summary.replace /<("[^"]*"|'[^']*'|[^'">])*>/g, ''
# console.log summary
matches = summary.match /([\r\n]*)([^\r\n]*)([\r\n]*)?(.*)/
text += ' ' + matches[2].substring(0, 60) if matches[2]
text += '...つづく...' if matches[4]
# console.log 'matches[1]:' + matches[1]
# console.log 'matches[2]:' + matches[2]
# console.log 'matches[4]:' + matches[4]
text = text.replace /<("[^"]*"|'[^']*'|[^'">])*>/g, ''
# console.log text
continue if text in cacheActivities
cacheActivities.push text
@send "[Redmineタイムライン] #{text}"
dispcnt++
while cacheActivities.length > 100
cacheActivities.shift()
setSenpaiStorage @robot, 'REDMINE_ACTIVITIES', cacheActivities
# }}}
checkJisseki: (date) -> # {{{
console.log 'checkJisseki'
usersInfo = @robot.brain.data.usersInfo ||= {}
users = {}
userCnt = 0
for u, v of usersInfo
continue if v['IS_NOT_CHECK_JISSEKI'] or u is @robot.name
userCnt++
console.log "check user: #{u}"
users[u] =
errNoInput: true
warnNoActivity: false
return unless userCnt
params =
from: date.toYMD()
to: date.toYMD()
@TimeEntry().get params, (err, timeEntries) =>
@send 'Error!: ' + err if err or timeEntries is null
for k, v of timeEntries
name = whoIsThis @robot, v.user.name
unless name
name = v.user.name
users[name] = {}
users[name].warnWho = true
users[name]?.errNoInput = false if users[name]?.errNoInput
users[name]?.warnNoActivity = true if v.activity.name is '【設定してください】'
reply = "#{params.from} の実績チェック\n"
for k, v of users
if v.errNoInput or v.warnNoActivity or v.warnWho
reply += "#{k}: "
reply += "<だれかわからない>" if v.warnWho
reply += "<実績入力なし>" if v.errNoInput
reply += "<活動が設定されてない実績あり>" if v.warnNoActivity
reply += "\n"
@send reply
# }}}
# private send, get, post, put # {{{
# Private: do a SEND
send: (msg) ->
response = new @robot.Response(@robot, {user : {id : -1, name : @room}, text : "none", done : false}, [])
# console.log @room + ':' + msg
response.send msg
# Private: do a GET request against the API
get: (path, params, opt, callback) ->
path = "#{path}?#{QUERY.stringify params}" if params?
# console.log 'get: ' + path
@request "GET", path, null, opt, callback
# Private: do a POST request against the API
post: (path, body, opt, callback) ->
@request "POST", path, body, opt, callback
# Private: do a PUT request against the API
put: (path, body, opt, callback) ->
@request "PUT", path, body, opt, callback
# }}}
# private request # {{{
request: (method, path, body, opt, callback) ->
optDefault =
"type": "json"
opt = _.extend(optDefault, opt)
headers =
"Content-Type": "application/json"
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/<KEY>"
"X-Redmine-API-Key": @token
options =
"url" : "#{@url}#{path}"
"method" : method
"headers": headers
"timeout": 10000
"strictSSL": false
if method in ["POST", "PUT"]
if typeof(body) isnt "string"
body = JSON.stringify body
options.body = body
# options.headers["Content-Length"] = body.length
# console.log options.url
request options, (err, response, data) ->
if !err and response?.statusCode is 200
parsedData = data
try
parsedData = JSON.parse(data)
if opt.type is 'json'
callback null, (parsedData or { }), response
else if opt.type is 'atom'
rssparser.parseString data, {}, (error, feed) ->
# console.log feed
callback error, feed, response
else
console.log 'code: ' + response?.statusCode + ', url =>' + options.url
console.log err ||= response?.statusCode
callback err, data, response
# /private request }}}
# /Redmine }}}
module.exports = (robot) ->
redmine = new Redmine robot, process.env.HUBOT_REDMINE_SEND_ROOM, process.env.HUBOT_REDMINE_BASE_URL, process.env.HUBOT_REDMINE_TOKEN
# {{{ for cron
checkUpdate = () ->
getActivity()
getActivity = () ->
# console.log 'start Redmine getActivity!!!'
redmine.getActivity()
robot.respond /redmine activity/i, (msg) ->
getActivity()
checkJisseki = (date) ->
redmine.checkJisseki(date)
# *(sec) *(min) *(hour) *(day) *(month) *(day of the week)
new cronJob('*/10 * * * * *', () ->
checkUpdate()
).start()
new cronJob('0 15 9,12,15,18 * * *', () ->
date = getPrevKadobi(robot, Date.yesterday())
checkJisseki(date)
).start()
# }}}
robot.respond /redmine [\s]*([\S]*)[\s]*(?:は|を|の)?(?:実績)?(?:check|チェック)(?:実績)?(する|して|しない)?/i, (msg) -> # {{{
name = msg.match[1].replace /(実績|チェック)/, ''
flg = msg.match[2]
if name and flg
user = whoIsThis robot, name
return msg.send "#{name} は\"面通し\"されてない" unless user
isNotCheck = false
isNotCheck = true if flg.match /(しない)/
setUserInfo robot, user, 'IS_NOT_CHECK_JISSEKI', isNotCheck
msg.send "次から #{user} の実績チェック#{flg}!"
else
date = getPrevKadobi(@robot, Date.yesterday())
checkJisseki date
# }}}
robot.hear /.*(#(\d+)).*/, (msg) -> # {{{
id = msg.match[1].replace /#/, ""
return if isNaN id
redmine.Issue(id).show null, (err, issue) ->
return msg.send 'Error!: ' + err if err or issue is null
# console.log issue.children
url = "#{redmine.url}/issues/#{id}"
estimated_hours = issue.estimated_hours || 0
spent_hours = issue.spent_hours || 0
for i, v of issue.children
spent_hours += v.spent_hours || 0
msg.send "#{url} : #{issue.subject}(予: #{estimated_hours}h / 消: #{spent_hours}h) - #{issue.project.name}"
# }}}
robot.respond /redmine[\s]+([\S]*)[\s]*実績(詳細)?/, (msg) -> # {{{
command = msg.match[1]
return if msg.message.match /(check|チェック)/
d = getPrevKadobi(robot, Date.yesterday())
params =
from: d.toYMD()
to: d.toYMD()
isDetail = true if msg.match[2]
redmine.TimeEntry().get params, (err, timeEntries) ->
return msg.send 'Error!: ' + err if err or timeEntries is null
return msg.send "#{params.from} 〜 #{params.to} に誰も実績入れてません!" unless timeEntries.length
messages = {}
for k, v of timeEntries
id = v.user.id
messages[id] ||=
name: v.user.name
hours: 0
messages[id].hours += v.hours
if isDetail
messages[id].issues ||= {}
messages[id].issues[v.issue.id] ||=
hours: 0
comments: ''
messages[id].issues[v.issue.id].hours += v.hours
if v.comments
messages[id].issues[v.issue.id].comments += ',' if messages[id].issues[v.issue.id].comments
messages[id].issues[v.issue.id].comments += v.comments
reply = "#{params.from} 〜 #{params.to} の実績\n"
for id, m of messages
reply += "#{m.name}: #{m.hours}h\n"
if isDetail
for issueId, issue of m.issues
reply += " ##{issueId}: #{issue.hours}h #{issue.comments}\n"
msg.send reply
# }}}
robot.respond /redmine[\s]+(\d{2,4}(?:-|\/)\d{1,2}(?:-|\/)\d{1,2}[\s]+)?#(\d+)[\s]+(\d{1,2}(\.00?|\.25|\.50?|.75)?)[\s]*(?:h|時間)[\s]+([\S]+)(?:[\s]+"?([^"]+)"?)?/i, (msg) -> # {{{
userName = msg.message.user.name
user = whoIsThis robot, userName
return msg.send "誰?" unless user
[date, id, hours, hoursshosu, activity, userComments] = msg.match[1..6]
if date
date = new Date date
return msg.send "#{date} は日付じゃない" unless Date.validateDay(date.getDate(), date.getFullYear(), date.getMonth())
else
date = getPrevKadobi robot, Date.yesterday()
dateYMD = date.toYMD()
console.log dateYMD
if userComments?
comments = "#{userComments}"
else
comments = "Time logged by: #{msg.message.user.name}"
activityId = getActivityId activity
unless activityId
msg.reply "こんな\"活動\"はない > #{activity}\n"
msg.send " Usage: #{robot.name} redmine ##{id} #{hours}h 製造 #{activity}"
return
redmine.Users name:user, (err, data) =>
# console.log 'count:' + userName + ' ' + data.total_count
unless data.total_count > 0
msg.send "\"#{user}\" が redmine で見つけられない"
return false
redmineUser = resolveUsers(user, data.users)[0]
attributes =
issue_id: id
spent_on: dateYMD
hours: hours
comments: comments
su_userid: redmineUser.id
activity_id: activityId
redmine.TimeEntry().create attributes, (error, data, response) ->
if response?.statusCode == 201
msg.reply "よく頑張りました!(#{dateYMD} で登録)"
else
msg.reply "なんか失敗"
# }}}
| true | # Description:
# Redmine
#
# Commands:
# #99999 - チケットのタイトルとか URL を取ってくるよ.
# hubot redmine (みんな|<nickname[,nickname]>) の実績[詳細] - 前営業日の実績を教えてもらおう!
# hubot redmine 実績チェック - 前営業日の実績をチェックするよ!
# hubot redmine <nickname> 実績チェック(する|しない) - 実績チェックの対象、または対象外にするよ!
# hubot redmine [yyyy-mm-dd] <#9999> 99[.25](h|時間) <活動> [コメント]- 実績を登録しよう!(日付省略時は前営業日になるよ) 例) hubot redmine #41 1.25h 製造 働いたよ!
#
# URLS:
# None.
#
# Notes:
# None.
URL = require('url')
QUERY = require('querystring')
request = require('request')
async = require('async')
rssparser = require('rssparser')
cronJob = require('cron').CronJob
_ = require('underscore')
DateUtil = require('date-utils')
PATH_ACTIVITY = process.env.HUBOT_REDMINE_ACTIVITY_URL
# {{{ SenpaiStorage
setSenpaiStorage = (robot, key, val) ->
storage = robot.brain.data.senpaiStorage ||= {}
storage[key] = val
# msg.send "storage #{key}, #{val}"
robot.brain.data.senpaiStorage = storage
getSenpaiStorage = (robot, key) ->
storage = robot.brain.data.senpaiStorage ||= {}
storage[key]
# }}}
# {{{ existsUser
existsUser = (robot, name) ->
name = name.toLowerCase()
return true if name is robot.name
users = robot.brain.data.usersInfo ||= {}
for u, v of users
if u is name
return true
return false
# }}}
whoIsThis = (robot, name) -> # {{{
name = name.toLowerCase()
return name if existsUser robot, name
gNicknames = getSenpaiStorage robot, 'NICKNAMES'
gNicknames ||= {}
return gNicknames[name] if gNicknames[name]
return null
# }}}
# {{{ UserInfo
setUserInfo = (robot, name, key, val) ->
name = name.toLowerCase()
return null unless existsUser robot, name
usersInfo = robot.brain.data.usersInfo ||= {}
usersInfo[name] ||= {}
usersInfo[name][key] = val
robot.brain.data.usersInfo = usersInfo
getUserInfo = (robot, name, key) ->
name = name.toLowerCase()
return null unless existsUser robot, name
usersInfo = robot.brain.data.usersInfo ||= {}
usersInfo[name] ||= {}
usersInfo[name][key]
# }}}
getPrevKadobi = (robot, date) -> # {{{
# console.log 'getPrevKadobi: ' + date.toYMD()
loop
week = date.getDay()
gHolidays = getSenpaiStorage robot, 'HOLIDAYS'
# console.log "week: #{week}"
if week is 0 or week is 6 or gHolidays[date.toYMD()]
date = date.addDays(-1)
continue
break
return date
# }}}
# from enumrations
getActivityId = (activity) -> # {{{
return 8 if activity.match /要件定義/
return 9 if activity.match /製造/
return 10 if activity.match /管理/
return 11 if activity.match /結テ仕/
return 12 if activity.match /調査/
return 13 if activity.match /見積/
return 14 if activity.match /リリース/
return 15 if activity.match /ヒアリング/
return 16 if activity.match /開発環境/
return 17 if activity.match /オペマニ/
return 18 if activity.match /営業/
return 24 if activity.match /社内手続き/
return 25 if activity.match /現状分析/
return 26 if activity.match /教育/
return 27 if activity.match /社内環境/
return 28 if activity.match /業務外作業/
return 29 if activity.match /引継/
return 30 if activity.match /土曜出勤/
return 31 if activity.match /提案活動/
return 32 if activity.match /単テ仕/
return 33 if activity.match /単テ実/
return 34 if activity.match /基本設計/
return 35 if activity.match /詳細設計/
return 37 if activity.match /結テ実/
return 38 if activity.match /PMO/
return 39 if activity.match /ユーザー環境/
return 40 if activity.match /サポート/
return null
# }}}
# tries to resolve ambiguous users by matching login or firstname# {{{
# redmine's user search is pretty broad (using login/name/email/etc.) so
# we're trying to just pull it in a bit and get a single user
#
# name - this should be the name you're trying to match
# data - this is the array of users from redmine
#
# returns an array with a single user, or the original array if nothing matched
resolveUsers = (name, data) ->
name = name.toLowerCase();
# try matching login
found = data.filter (user) -> user.login.toLowerCase() == name
return found if found.length == 1
# try first name
found = data.filter (user) -> user.firstname.toLowerCase() == name
return found if found.length == 1
# give up
data
# }}}
class Redmine # {{{
constructor: (@robot, @room, @url, @token) -> # {{{
endpoint = URL.parse(@url)
@protocol = endpoint.protocol
@hostname = endpoint.hostname
@pathname = endpoint.pathname.replace /^\/$/, ''
@url = "#{@protocol}//#{@hostname}#{@pathname}"
# }}}
Users: (params, callback, opt) -> # {{{
@get "/users.json", params, opt, callback
# }}}
Issues: (params, callback, opt) -> # {{{
@get "/issues.json", params, opt, callback
Issue: (id) ->
# console.log 'issue: ' + id
show: (params, callback, opt) =>
# console.log 'show: ' + id
paramsDef = {include: "children"}
params = _.extend(paramsDef, params);
@get "/issues/#{id}.json", params, opt, (err, data, response) =>
issue = data.issue
childrenCnt = issue.children?.length || 0
if childrenCnt is 0
callback null, issue
else
f = _.object(issue.children.map (child) =>
f2 = (cb) =>
# console.log 'child' + child.id + ': ' + child.subject
@Issue(child.id).show null, cb
[child.id, f2])
async.parallel f, (err, result) ->
return callback err, null if err or result is null
# console.log result
issue.children = (v for k, v of result)
callback null, issue
# }}}
TimeEntry: () -> # {{{
get: (params, callback, opt) =>
console.log 'TimeEntry#get'
paramsDefault =
from: Date.yesterday().toFormat('YYYY-MM-DD')
to: Date.yesterday().toFormat('YYYY-MM-DD')
params = _.extend(paramsDefault, params);
@get "/time_entries.json", params, opt, (err, data, response) =>
return callback err, null if err or data is null
timeEntries = data.time_entries
callback null, timeEntries
create: (attributes, callback, opt) =>
@post "/time_entries.json", {time_entry: attributes, su_userid: attributes.su_userid}, opt, callback
# }}}
getActivity: () -> # {{{
@get PATH_ACTIVITY, null, {type: "atom"}, (error, feed, response) =>
cacheActivities = getSenpaiStorage @robot, 'REDMINE_ACTIVITIES'
cacheActivities ||= []
dispcnt = 0
items = feed.items
for i, item of items
break if dispcnt >= 5
text = item.author + ': '
text += item.title
text += '(' + item.link + ')'
if item.summary
summary = item.summary.replace /<("[^"]*"|'[^']*'|[^'">])*>/g, ''
# console.log summary
matches = summary.match /([\r\n]*)([^\r\n]*)([\r\n]*)?(.*)/
text += ' ' + matches[2].substring(0, 60) if matches[2]
text += '...つづく...' if matches[4]
# console.log 'matches[1]:' + matches[1]
# console.log 'matches[2]:' + matches[2]
# console.log 'matches[4]:' + matches[4]
text = text.replace /<("[^"]*"|'[^']*'|[^'">])*>/g, ''
# console.log text
continue if text in cacheActivities
cacheActivities.push text
@send "[Redmineタイムライン] #{text}"
dispcnt++
while cacheActivities.length > 100
cacheActivities.shift()
setSenpaiStorage @robot, 'REDMINE_ACTIVITIES', cacheActivities
# }}}
checkJisseki: (date) -> # {{{
console.log 'checkJisseki'
usersInfo = @robot.brain.data.usersInfo ||= {}
users = {}
userCnt = 0
for u, v of usersInfo
continue if v['IS_NOT_CHECK_JISSEKI'] or u is @robot.name
userCnt++
console.log "check user: #{u}"
users[u] =
errNoInput: true
warnNoActivity: false
return unless userCnt
params =
from: date.toYMD()
to: date.toYMD()
@TimeEntry().get params, (err, timeEntries) =>
@send 'Error!: ' + err if err or timeEntries is null
for k, v of timeEntries
name = whoIsThis @robot, v.user.name
unless name
name = v.user.name
users[name] = {}
users[name].warnWho = true
users[name]?.errNoInput = false if users[name]?.errNoInput
users[name]?.warnNoActivity = true if v.activity.name is '【設定してください】'
reply = "#{params.from} の実績チェック\n"
for k, v of users
if v.errNoInput or v.warnNoActivity or v.warnWho
reply += "#{k}: "
reply += "<だれかわからない>" if v.warnWho
reply += "<実績入力なし>" if v.errNoInput
reply += "<活動が設定されてない実績あり>" if v.warnNoActivity
reply += "\n"
@send reply
# }}}
# private send, get, post, put # {{{
# Private: do a SEND
send: (msg) ->
response = new @robot.Response(@robot, {user : {id : -1, name : @room}, text : "none", done : false}, [])
# console.log @room + ':' + msg
response.send msg
# Private: do a GET request against the API
get: (path, params, opt, callback) ->
path = "#{path}?#{QUERY.stringify params}" if params?
# console.log 'get: ' + path
@request "GET", path, null, opt, callback
# Private: do a POST request against the API
post: (path, body, opt, callback) ->
@request "POST", path, body, opt, callback
# Private: do a PUT request against the API
put: (path, body, opt, callback) ->
@request "PUT", path, body, opt, callback
# }}}
# private request # {{{
request: (method, path, body, opt, callback) ->
optDefault =
"type": "json"
opt = _.extend(optDefault, opt)
headers =
"Content-Type": "application/json"
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/PI:KEY:<KEY>END_PI"
"X-Redmine-API-Key": @token
options =
"url" : "#{@url}#{path}"
"method" : method
"headers": headers
"timeout": 10000
"strictSSL": false
if method in ["POST", "PUT"]
if typeof(body) isnt "string"
body = JSON.stringify body
options.body = body
# options.headers["Content-Length"] = body.length
# console.log options.url
request options, (err, response, data) ->
if !err and response?.statusCode is 200
parsedData = data
try
parsedData = JSON.parse(data)
if opt.type is 'json'
callback null, (parsedData or { }), response
else if opt.type is 'atom'
rssparser.parseString data, {}, (error, feed) ->
# console.log feed
callback error, feed, response
else
console.log 'code: ' + response?.statusCode + ', url =>' + options.url
console.log err ||= response?.statusCode
callback err, data, response
# /private request }}}
# /Redmine }}}
module.exports = (robot) ->
redmine = new Redmine robot, process.env.HUBOT_REDMINE_SEND_ROOM, process.env.HUBOT_REDMINE_BASE_URL, process.env.HUBOT_REDMINE_TOKEN
# {{{ for cron
checkUpdate = () ->
getActivity()
getActivity = () ->
# console.log 'start Redmine getActivity!!!'
redmine.getActivity()
robot.respond /redmine activity/i, (msg) ->
getActivity()
checkJisseki = (date) ->
redmine.checkJisseki(date)
# *(sec) *(min) *(hour) *(day) *(month) *(day of the week)
new cronJob('*/10 * * * * *', () ->
checkUpdate()
).start()
new cronJob('0 15 9,12,15,18 * * *', () ->
date = getPrevKadobi(robot, Date.yesterday())
checkJisseki(date)
).start()
# }}}
robot.respond /redmine [\s]*([\S]*)[\s]*(?:は|を|の)?(?:実績)?(?:check|チェック)(?:実績)?(する|して|しない)?/i, (msg) -> # {{{
name = msg.match[1].replace /(実績|チェック)/, ''
flg = msg.match[2]
if name and flg
user = whoIsThis robot, name
return msg.send "#{name} は\"面通し\"されてない" unless user
isNotCheck = false
isNotCheck = true if flg.match /(しない)/
setUserInfo robot, user, 'IS_NOT_CHECK_JISSEKI', isNotCheck
msg.send "次から #{user} の実績チェック#{flg}!"
else
date = getPrevKadobi(@robot, Date.yesterday())
checkJisseki date
# }}}
robot.hear /.*(#(\d+)).*/, (msg) -> # {{{
id = msg.match[1].replace /#/, ""
return if isNaN id
redmine.Issue(id).show null, (err, issue) ->
return msg.send 'Error!: ' + err if err or issue is null
# console.log issue.children
url = "#{redmine.url}/issues/#{id}"
estimated_hours = issue.estimated_hours || 0
spent_hours = issue.spent_hours || 0
for i, v of issue.children
spent_hours += v.spent_hours || 0
msg.send "#{url} : #{issue.subject}(予: #{estimated_hours}h / 消: #{spent_hours}h) - #{issue.project.name}"
# }}}
robot.respond /redmine[\s]+([\S]*)[\s]*実績(詳細)?/, (msg) -> # {{{
command = msg.match[1]
return if msg.message.match /(check|チェック)/
d = getPrevKadobi(robot, Date.yesterday())
params =
from: d.toYMD()
to: d.toYMD()
isDetail = true if msg.match[2]
redmine.TimeEntry().get params, (err, timeEntries) ->
return msg.send 'Error!: ' + err if err or timeEntries is null
return msg.send "#{params.from} 〜 #{params.to} に誰も実績入れてません!" unless timeEntries.length
messages = {}
for k, v of timeEntries
id = v.user.id
messages[id] ||=
name: v.user.name
hours: 0
messages[id].hours += v.hours
if isDetail
messages[id].issues ||= {}
messages[id].issues[v.issue.id] ||=
hours: 0
comments: ''
messages[id].issues[v.issue.id].hours += v.hours
if v.comments
messages[id].issues[v.issue.id].comments += ',' if messages[id].issues[v.issue.id].comments
messages[id].issues[v.issue.id].comments += v.comments
reply = "#{params.from} 〜 #{params.to} の実績\n"
for id, m of messages
reply += "#{m.name}: #{m.hours}h\n"
if isDetail
for issueId, issue of m.issues
reply += " ##{issueId}: #{issue.hours}h #{issue.comments}\n"
msg.send reply
# }}}
robot.respond /redmine[\s]+(\d{2,4}(?:-|\/)\d{1,2}(?:-|\/)\d{1,2}[\s]+)?#(\d+)[\s]+(\d{1,2}(\.00?|\.25|\.50?|.75)?)[\s]*(?:h|時間)[\s]+([\S]+)(?:[\s]+"?([^"]+)"?)?/i, (msg) -> # {{{
userName = msg.message.user.name
user = whoIsThis robot, userName
return msg.send "誰?" unless user
[date, id, hours, hoursshosu, activity, userComments] = msg.match[1..6]
if date
date = new Date date
return msg.send "#{date} は日付じゃない" unless Date.validateDay(date.getDate(), date.getFullYear(), date.getMonth())
else
date = getPrevKadobi robot, Date.yesterday()
dateYMD = date.toYMD()
console.log dateYMD
if userComments?
comments = "#{userComments}"
else
comments = "Time logged by: #{msg.message.user.name}"
activityId = getActivityId activity
unless activityId
msg.reply "こんな\"活動\"はない > #{activity}\n"
msg.send " Usage: #{robot.name} redmine ##{id} #{hours}h 製造 #{activity}"
return
redmine.Users name:user, (err, data) =>
# console.log 'count:' + userName + ' ' + data.total_count
unless data.total_count > 0
msg.send "\"#{user}\" が redmine で見つけられない"
return false
redmineUser = resolveUsers(user, data.users)[0]
attributes =
issue_id: id
spent_on: dateYMD
hours: hours
comments: comments
su_userid: redmineUser.id
activity_id: activityId
redmine.TimeEntry().create attributes, (error, data, response) ->
if response?.statusCode == 201
msg.reply "よく頑張りました!(#{dateYMD} で登録)"
else
msg.reply "なんか失敗"
# }}}
|
[
{
"context": "map_y / ChunkMap.CHUNK_HEIGHT)\n chunk_key = \"#{chunk_x}x#{chunk_y}\"\n\n PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[par",
"end": 19483,
"score": 0.9890111684799194,
"start": 19460,
"tag": "KEY",
"value": "\"#{chunk_x}x#{chunk_y}\""
},
{
"context": "?\n\n chunk_key = \"#{query_parameters.chunk_x}x#{query_parameters.chunk_y}\"\n return _.cloneD",
"end": 20903,
"score": 0.8970201015472412,
"start": 20900,
"tag": "KEY",
"value": "x#{"
},
{
"context": "ery_parameters.chunk_x}x#{query_parameters.chunk_y}\"\n return _.cloneDeep {\n buildings:",
"end": 20927,
"score": 0.6291723251342773,
"start": 20927,
"tag": "KEY",
"value": ""
}
] | plugins/starpeace-client/api/mock-api-configuration.coffee | Eric1212/starpeace-website-client | 0 |
import moment from 'moment'
import _ from 'lodash'
import ChunkMap from '~/plugins/starpeace-client/map/chunk/chunk-map.coffee'
import TimeUtils from '~/plugins/starpeace-client/utils/time-utils.coffee'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
import BOOKMARKS_METADATA from '~/plugins/starpeace-client/api/mock-bookmarks-metadata.json'
import GALAXY_METADATA from '~/plugins/starpeace-client/api/mock-galaxy-metadata.json'
import PLANETS_DETAILS from '~/plugins/starpeace-client/api/mock-planet-details.json'
import TYCOON_METADATA from '~/plugins/starpeace-client/api/mock-tycoon-metadata.json'
import PLANET_1_MAP_BUILDINGS from '~/plugins/starpeace-client/api/mock-planet-1-map-buildings.json'
import PLANET_1_TYCOON_1_INVENTIONS from '~/plugins/starpeace-client/api/mock-planet-1-tycoon-1-inventions.json'
import PLANET_2_MAP_BUILDINGS from '~/plugins/starpeace-client/api/mock-planet-2-map-buildings.json'
PLANET_MAP_BUILDINGS = {
'planet-1': PLANET_1_MAP_BUILDINGS
'planet-2': PLANET_2_MAP_BUILDINGS
}
API_DELAY = 500
MAIL_METADATA = {}
MONTH_SEASONS = {
0: 'winter'
1: 'winter'
2: 'spring'
3: 'spring'
4: 'spring'
5: 'summer'
6: 'summer'
7: 'summer'
8: 'fall'
9: 'fall'
10: 'fall'
11: 'winter'
}
PLANET_ID_DATES = {}
for planet in GALAXY_METADATA.planets_metadata
if planet.enabled
PLANET_ID_DATES[planet.id] = moment('2235-01-01')
CORPORATION_ID_EVENTS = {}
COMPANY_ID_INFO = {}
COMPANY_ID_INVENTIONS = {}
for tycoon_id,tycoon of TYCOON_METADATA
for corporation in tycoon.corporations
planet = _.find(GALAXY_METADATA.planets_metadata || [], (planet) -> planet.id == corporation.planet_id)
if planet?.enabled
CORPORATION_ID_EVENTS[corporation.id] = {
cash: corporation.cash
companies_by_id: {}
cashflow: () -> _.reduce(_.values(@companies_by_id), ((sum, company) -> sum + company.cashflow), 0)
increment_cash: () -> @cash = @cash + 24 * @cashflow()
}
for company in corporation.companies
COMPANY_ID_INFO[company.id] = {
tycoon_id: tycoon_id
corporation_id: corporation.id
planet_id: corporation.planet_id
}
CORPORATION_ID_EVENTS[corporation.id].companies_by_id[company.id] = {
id: company.id
cashflow: company.cashflow
original_cashflow: company.cashflow
adjust_cashflow: (temporary_delta) -> @cashflow = @original_cashflow + (Math.floor(Math.random() * 500) - 250) + temporary_delta
}
for company_inventions in [PLANET_1_TYCOON_1_INVENTIONS]
if company_inventions[company.id]?
COMPANY_ID_INVENTIONS[company.id] = company_inventions[company.id]
COMPANY_ID_INVENTIONS[company.id].corporation_id = corporation.id
COMPANY_ID_INVENTIONS[company.id].tycoon_id = tycoon_id
COMPANY_ID_BUILDINGS = {}
BUILDING_ID_BUILDING = {}
for planet_id,planet_buildings of PLANET_MAP_BUILDINGS
for chunk_id,chunk_buildings of planet_buildings
for building in chunk_buildings
COMPANY_ID_BUILDINGS[building.company_id] = [] unless COMPANY_ID_BUILDINGS[building.company_id]?
COMPANY_ID_BUILDINGS[building.company_id].push building
BUILDING_ID_BUILDING[building.id] = building
SESSION_TOKENS = {}
valid_session = (token) -> SESSION_TOKENS[token]? && TimeUtils.within_minutes(SESSION_TOKENS[token], 60)
register_session = () ->
token = Utils.uuid()
SESSION_TOKENS[token] = moment()
token
cost_for_invention_id = (invention_id) ->
if window?.starpeace_client?.client_state?.core?.invention_library?
window.starpeace_client.client_state.core.invention_library.metadata_by_id[invention_id]?.properties?.price || 0
else
0
QUEUED_EVENTS = []
COMPANY_CONSTRUCTION_BUIDLINGS = {}
BUILDING_EVENTS = []
setInterval(=>
PLANET_ID_DATES[id].add(1, 'day') for id,date of PLANET_ID_DATES
for corp_id,corp_events of CORPORATION_ID_EVENTS
for company_id,company of corp_events.companies_by_id
cashflow_adjustment = 0
to_remove = []
for event,index in QUEUED_EVENTS
if event.company_id == company_id
to_remove.push index
if event.type == 'SELL_RESEARCH'
cashflow_adjustment += (cost_for_invention_id(event.invention_id) / 24)
else if event.type == 'CANCEL_RESEARCH'
cashflow_adjustment += (event.refund / 24)
QUEUED_EVENTS.splice(index, 1) for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
inventions = COMPANY_ID_INVENTIONS[company_id]
if inventions?.pending_inventions?.length
to_remove = []
for pending,index in inventions.pending_inventions
continue unless index == 0
unless pending.step_increment?
pending.cost = cost_for_invention_id(pending.id)
pending.step_increment = Math.max(50000, Math.round(pending.cost / 30))
pending.spent += pending.step_increment
cashflow_adjustment -= (pending.step_increment / 24)
pending.progress = Math.min(100, Math.round(pending.spent / pending.cost * 100))
if pending.spent >= pending.cost
to_remove.push index
inventions.completed_ids.push pending.id
for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
inventions.pending_inventions.splice(index, 1)
inventions.pending_inventions[index].order = index for index in [0...inventions.pending_inventions.length]
if COMPANY_CONSTRUCTION_BUIDLINGS[company_id]?.length
to_remove = []
for building,index in COMPANY_CONSTRUCTION_BUIDLINGS[company_id]
if building.stage == -1
building.progress = 22 + (building.progress || 0)
building.progress = 100 if building.progress > 100
cashflow_adjustment -= (5000 + Math.random() * 5000)
if building.progress == 100
building.stage = 0
BUILDING_EVENTS.push {'type':'stage', 'id':building.id, 'definition_id':building.key, 'x':building.x, 'y':building.y}
to_remove.push index
else
to_remove.push index
COMPANY_CONSTRUCTION_BUIDLINGS[company_id].splice(index, 1) for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
company.adjust_cashflow(cashflow_adjustment)
corp_events.increment_cash()
, 1000)
export default [
{
pattern: 'http://sandbox-galaxy.starpeace.io:19160(.*)'
fixtures: (match, params, headers, context) ->
throw new Error(404) if match[1] == '/404'
[root_path, query_string] = if match[1].indexOf('?') >= 0 then match[1].split('?') else [match[1], '']
query_parameters = Utils.parse_query(query_string)
context.delay = API_DELAY
if root_path == '/galaxy/metadata'
throw new Error(404) unless context.method == 'get'
return _.cloneDeep GALAXY_METADATA
if root_path == '/session/register'
throw new Error(404) unless context.method == 'post'
if params.type == 'visitor'
return _.cloneDeep {
session_token: register_session()
}
else if params.type == 'tycoon'
return _.cloneDeep {
session_token: register_session()
tycoon_id: 'tycoon-id-1'
}
else
throw new Error(400)
if root_path == '/planet/details'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(404) unless PLANETS_DETAILS[query_parameters.planet_id]?
details = PLANETS_DETAILS[query_parameters.planet_id]
details.date = PLANET_ID_DATES[query_parameters.planet_id].format('YYYY-MM-DD')
details.season = MONTH_SEASONS[PLANET_ID_DATES[query_parameters.planet_id].month()]
return _.cloneDeep {
planet: details
}
if root_path == '/planet/events'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(400) unless query_parameters.last_update?.length
throw new Error(404) unless PLANET_ID_DATES[query_parameters.planet_id]?
events = if BUILDING_EVENTS.length then BUILDING_EVENTS else []
BUILDING_EVENTS = [] if events.length
return _.cloneDeep {
planet: {
date: PLANET_ID_DATES[query_parameters.planet_id].format('YYYY-MM-DD')
season: MONTH_SEASONS[PLANET_ID_DATES[query_parameters.planet_id].month()]
building_events: events
}
}
if root_path == '/tycoon/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.tycoon_id?.length
throw new Error(404) unless TYCOON_METADATA[query_parameters.tycoon_id]?
return _.cloneDeep {
tycoon: TYCOON_METADATA[query_parameters.tycoon_id]
}
if root_path == '/corporation/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
for tycoon_id,tycoon of TYCOON_METADATA
for corporation in tycoon.corporations
if corporation.id == query_parameters.corporation_id
corporation.tycoon_id = tycoon_id unless corporation.tycoon_id?
return { corporation: corporation }
throw new Error(404)
if root_path == '/corporation/events'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
throw new Error(400) unless query_parameters.last_update?.length
throw new Error(404) unless CORPORATION_ID_EVENTS[query_parameters.corporation_id]?
corp_metadata = {
id: query_parameters.corporation_id
cash: CORPORATION_ID_EVENTS[query_parameters.corporation_id].cash
cashflow: CORPORATION_ID_EVENTS[query_parameters.corporation_id].cashflow()
companies: []
}
for company_id,company of CORPORATION_ID_EVENTS[query_parameters.corporation_id].companies_by_id
corp_metadata.companies.push {
id: company.id
cashflow: company.cashflow
}
return _.cloneDeep {
corporation: corp_metadata
}
if root_path == '/bookmarks/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
return _.cloneDeep {
bookmarks: BOOKMARKS_METADATA[query_parameters.corporation_id] || []
}
if root_path == '/bookmarks/update'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.corporation_id?.length
throw new Error(404) unless BOOKMARKS_METADATA[params.corporation_id]?.bookmarks?
updated = []
for delta in params.deltas
existing = _.find(BOOKMARKS_METADATA[params.corporation_id].bookmarks, (bookmark) -> bookmark.id == delta.id)
if existing?
existing.parent_id = delta.parent_id if delta.parent_id?
existing.order = delta.order if delta.order?
updated.push existing
return _.cloneDeep {
bookmarks: updated
}
if root_path == '/bookmarks/new'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.corporation_id?.length
throw new Error(400) unless params.parent_id?.length
throw new Error(400) unless params.name?.length
throw new Error(404) unless BOOKMARKS_METADATA[params.corporation_id]?.bookmarks?
order = _.filter(BOOKMARKS_METADATA[params.corporation_id].bookmarks, (bookmark) -> bookmark.parent_id == params.parent_id).length
if params.type == 'FOLDER'
item = {
type: 'FOLDER'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
}
else if params.type == 'LOCATION'
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
item = {
type: 'LOCATION'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
map_x: params.map_x
map_y: params.map_y
}
else if params.type == 'BUILDING'
throw new Error(400) unless params.building_id?.length
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
item = {
type: 'BUILDING'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
building_id: params.building_id
map_x: params.map_x
map_y: params.map_y
}
else
throw new Error(400)
BOOKMARKS_METADATA[params.corporation_id].bookmarks.push item
return _.cloneDeep {
bookmark: item
}
if root_path == '/mail/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
return _.cloneDeep {
mail: MAIL_METADATA[query_parameters.corporation_id] || []
}
if root_path == '/inventions/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.company_id?.length
return _.cloneDeep {
inventions: {
company_id: query_parameters.company_id
pending_inventions: (COMPANY_ID_INVENTIONS[query_parameters.company_id]?.pending_inventions || [])
completed_ids: (COMPANY_ID_INVENTIONS[query_parameters.company_id]?.completed_ids || [])
}
}
if root_path == '/inventions/sell'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.invention_id?.length
throw new Error(404) unless COMPANY_ID_INVENTIONS[params.company_id]?
inventions = COMPANY_ID_INVENTIONS[params.company_id]
completed_index = inventions.completed_ids.indexOf(params.invention_id)
pending_index = _.findIndex(inventions.pending_inventions, (pending) => pending.id == params.invention_id)
if completed_index >= 0
QUEUED_EVENTS.push { type: 'SELL_RESEARCH', company_id: params.company_id, invention_id: params.invention_id }
inventions.completed_ids.splice(completed_index, 1)
else if pending_index >= 0
QUEUED_EVENTS.push { type: 'CANCEL_RESEARCH', company_id: params.company_id, invention_id: params.invention_id, refund: inventions.pending_inventions[pending_index].spent }
inventions.pending_inventions[index].order -= 1 for index in [pending_index...inventions.pending_inventions.length]
inventions.pending_inventions.splice(pending_index, 1)
return _.cloneDeep {
inventions: {
company_id: params.company_id
pending_inventions: (inventions.pending_inventions || [])
completed_ids: (inventions.completed_ids || [])
}
}
if root_path == '/inventions/queue'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.invention_id?.length
throw new Error(404) unless COMPANY_ID_INVENTIONS[params.company_id]?
inventions = COMPANY_ID_INVENTIONS[params.company_id]
completed_index = inventions.completed_ids.indexOf(params.invention_id)
pending_index = _.findIndex(inventions.pending_inventions, (pending) => pending.id == params.invention_id)
if completed_index >= 0 || pending_index >= 0
throw new Error(404)
inventions.completed_ids.splice(completed_index, 1)
else
inventions.pending_inventions.push {
id: params.invention_id
progress: 0
order: inventions.pending_inventions.length
spent: 0
}
return _.cloneDeep {
inventions: {
company_id: params.company_id
pending_inventions: (inventions.pending_inventions || [])
completed_ids: (inventions.completed_ids || [])
}
}
return {} if root_path == '/inventions/status'
if root_path == '/buildings/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
buildings = []
if query_parameters.company_id?.length
buildings = COMPANY_ID_BUILDINGS[query_parameters.company_id] if COMPANY_ID_BUILDINGS[query_parameters.company_id]?
else if query_parameters.building_id?.length
buildings.push BUILDING_ID_BUILDING[query_parameters.building_id] if BUILDING_ID_BUILDING[query_parameters.building_id]?
else
throw new Error(400)
return _.cloneDeep {
buildings: buildings || []
}
if root_path == '/buildings/construct'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.definition_id?.length
throw new Error(400) unless params.name?.length
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
throw new Error(404) unless COMPANY_ID_INFO[params.company_id]?
throw new Error(404) unless PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id]?
building_info = {
id: Utils.uuid()
name: params.name
tycoon_id: COMPANY_ID_INFO[params.company_id].tycoon_id
corporation_id: COMPANY_ID_INFO[params.company_id].corporation_id
company_id: params.company_id
key: params.definition_id
x: params.map_x
y: params.map_y
stage: -1
progress: 0
}
chunk_x = Math.floor(params.map_x / ChunkMap.CHUNK_WIDTH)
chunk_y = Math.floor(params.map_y / ChunkMap.CHUNK_HEIGHT)
chunk_key = "#{chunk_x}x#{chunk_y}"
PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key] = [] unless PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key]?
PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key].push building_info
COMPANY_ID_BUILDINGS[params.company_id] = [] unless COMPANY_ID_BUILDINGS[params.company_id]?
COMPANY_ID_BUILDINGS[params.company_id].push building_info
BUILDING_ID_BUILDING[building_info.id] = building_info
COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id] = [] unless COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id]?
COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id].push building_info
BUILDING_EVENTS.push {'type':'construct', 'id':building_info.id, 'definition_id':building_info.key, 'x':building_info.x, 'y':building_info.y}
return _.cloneDeep {
building: building_info
}
if root_path == '/map/buildings'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(400) unless query_parameters.chunk_x? && query_parameters.chunk_y?
throw new Error(404) unless PLANET_MAP_BUILDINGS[query_parameters.planet_id]?
chunk_key = "#{query_parameters.chunk_x}x#{query_parameters.chunk_y}"
return _.cloneDeep {
buildings: PLANET_MAP_BUILDINGS[query_parameters.planet_id][chunk_key] || []
}
throw new Error(404)
get: (match, data) ->
return data
post: (match, data) ->
return data
}
]
| 79619 |
import moment from 'moment'
import _ from 'lodash'
import ChunkMap from '~/plugins/starpeace-client/map/chunk/chunk-map.coffee'
import TimeUtils from '~/plugins/starpeace-client/utils/time-utils.coffee'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
import BOOKMARKS_METADATA from '~/plugins/starpeace-client/api/mock-bookmarks-metadata.json'
import GALAXY_METADATA from '~/plugins/starpeace-client/api/mock-galaxy-metadata.json'
import PLANETS_DETAILS from '~/plugins/starpeace-client/api/mock-planet-details.json'
import TYCOON_METADATA from '~/plugins/starpeace-client/api/mock-tycoon-metadata.json'
import PLANET_1_MAP_BUILDINGS from '~/plugins/starpeace-client/api/mock-planet-1-map-buildings.json'
import PLANET_1_TYCOON_1_INVENTIONS from '~/plugins/starpeace-client/api/mock-planet-1-tycoon-1-inventions.json'
import PLANET_2_MAP_BUILDINGS from '~/plugins/starpeace-client/api/mock-planet-2-map-buildings.json'
PLANET_MAP_BUILDINGS = {
'planet-1': PLANET_1_MAP_BUILDINGS
'planet-2': PLANET_2_MAP_BUILDINGS
}
API_DELAY = 500
MAIL_METADATA = {}
MONTH_SEASONS = {
0: 'winter'
1: 'winter'
2: 'spring'
3: 'spring'
4: 'spring'
5: 'summer'
6: 'summer'
7: 'summer'
8: 'fall'
9: 'fall'
10: 'fall'
11: 'winter'
}
PLANET_ID_DATES = {}
for planet in GALAXY_METADATA.planets_metadata
if planet.enabled
PLANET_ID_DATES[planet.id] = moment('2235-01-01')
CORPORATION_ID_EVENTS = {}
COMPANY_ID_INFO = {}
COMPANY_ID_INVENTIONS = {}
for tycoon_id,tycoon of TYCOON_METADATA
for corporation in tycoon.corporations
planet = _.find(GALAXY_METADATA.planets_metadata || [], (planet) -> planet.id == corporation.planet_id)
if planet?.enabled
CORPORATION_ID_EVENTS[corporation.id] = {
cash: corporation.cash
companies_by_id: {}
cashflow: () -> _.reduce(_.values(@companies_by_id), ((sum, company) -> sum + company.cashflow), 0)
increment_cash: () -> @cash = @cash + 24 * @cashflow()
}
for company in corporation.companies
COMPANY_ID_INFO[company.id] = {
tycoon_id: tycoon_id
corporation_id: corporation.id
planet_id: corporation.planet_id
}
CORPORATION_ID_EVENTS[corporation.id].companies_by_id[company.id] = {
id: company.id
cashflow: company.cashflow
original_cashflow: company.cashflow
adjust_cashflow: (temporary_delta) -> @cashflow = @original_cashflow + (Math.floor(Math.random() * 500) - 250) + temporary_delta
}
for company_inventions in [PLANET_1_TYCOON_1_INVENTIONS]
if company_inventions[company.id]?
COMPANY_ID_INVENTIONS[company.id] = company_inventions[company.id]
COMPANY_ID_INVENTIONS[company.id].corporation_id = corporation.id
COMPANY_ID_INVENTIONS[company.id].tycoon_id = tycoon_id
COMPANY_ID_BUILDINGS = {}
BUILDING_ID_BUILDING = {}
for planet_id,planet_buildings of PLANET_MAP_BUILDINGS
for chunk_id,chunk_buildings of planet_buildings
for building in chunk_buildings
COMPANY_ID_BUILDINGS[building.company_id] = [] unless COMPANY_ID_BUILDINGS[building.company_id]?
COMPANY_ID_BUILDINGS[building.company_id].push building
BUILDING_ID_BUILDING[building.id] = building
SESSION_TOKENS = {}
valid_session = (token) -> SESSION_TOKENS[token]? && TimeUtils.within_minutes(SESSION_TOKENS[token], 60)
register_session = () ->
token = Utils.uuid()
SESSION_TOKENS[token] = moment()
token
cost_for_invention_id = (invention_id) ->
if window?.starpeace_client?.client_state?.core?.invention_library?
window.starpeace_client.client_state.core.invention_library.metadata_by_id[invention_id]?.properties?.price || 0
else
0
QUEUED_EVENTS = []
COMPANY_CONSTRUCTION_BUIDLINGS = {}
BUILDING_EVENTS = []
setInterval(=>
PLANET_ID_DATES[id].add(1, 'day') for id,date of PLANET_ID_DATES
for corp_id,corp_events of CORPORATION_ID_EVENTS
for company_id,company of corp_events.companies_by_id
cashflow_adjustment = 0
to_remove = []
for event,index in QUEUED_EVENTS
if event.company_id == company_id
to_remove.push index
if event.type == 'SELL_RESEARCH'
cashflow_adjustment += (cost_for_invention_id(event.invention_id) / 24)
else if event.type == 'CANCEL_RESEARCH'
cashflow_adjustment += (event.refund / 24)
QUEUED_EVENTS.splice(index, 1) for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
inventions = COMPANY_ID_INVENTIONS[company_id]
if inventions?.pending_inventions?.length
to_remove = []
for pending,index in inventions.pending_inventions
continue unless index == 0
unless pending.step_increment?
pending.cost = cost_for_invention_id(pending.id)
pending.step_increment = Math.max(50000, Math.round(pending.cost / 30))
pending.spent += pending.step_increment
cashflow_adjustment -= (pending.step_increment / 24)
pending.progress = Math.min(100, Math.round(pending.spent / pending.cost * 100))
if pending.spent >= pending.cost
to_remove.push index
inventions.completed_ids.push pending.id
for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
inventions.pending_inventions.splice(index, 1)
inventions.pending_inventions[index].order = index for index in [0...inventions.pending_inventions.length]
if COMPANY_CONSTRUCTION_BUIDLINGS[company_id]?.length
to_remove = []
for building,index in COMPANY_CONSTRUCTION_BUIDLINGS[company_id]
if building.stage == -1
building.progress = 22 + (building.progress || 0)
building.progress = 100 if building.progress > 100
cashflow_adjustment -= (5000 + Math.random() * 5000)
if building.progress == 100
building.stage = 0
BUILDING_EVENTS.push {'type':'stage', 'id':building.id, 'definition_id':building.key, 'x':building.x, 'y':building.y}
to_remove.push index
else
to_remove.push index
COMPANY_CONSTRUCTION_BUIDLINGS[company_id].splice(index, 1) for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
company.adjust_cashflow(cashflow_adjustment)
corp_events.increment_cash()
, 1000)
export default [
{
pattern: 'http://sandbox-galaxy.starpeace.io:19160(.*)'
fixtures: (match, params, headers, context) ->
throw new Error(404) if match[1] == '/404'
[root_path, query_string] = if match[1].indexOf('?') >= 0 then match[1].split('?') else [match[1], '']
query_parameters = Utils.parse_query(query_string)
context.delay = API_DELAY
if root_path == '/galaxy/metadata'
throw new Error(404) unless context.method == 'get'
return _.cloneDeep GALAXY_METADATA
if root_path == '/session/register'
throw new Error(404) unless context.method == 'post'
if params.type == 'visitor'
return _.cloneDeep {
session_token: register_session()
}
else if params.type == 'tycoon'
return _.cloneDeep {
session_token: register_session()
tycoon_id: 'tycoon-id-1'
}
else
throw new Error(400)
if root_path == '/planet/details'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(404) unless PLANETS_DETAILS[query_parameters.planet_id]?
details = PLANETS_DETAILS[query_parameters.planet_id]
details.date = PLANET_ID_DATES[query_parameters.planet_id].format('YYYY-MM-DD')
details.season = MONTH_SEASONS[PLANET_ID_DATES[query_parameters.planet_id].month()]
return _.cloneDeep {
planet: details
}
if root_path == '/planet/events'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(400) unless query_parameters.last_update?.length
throw new Error(404) unless PLANET_ID_DATES[query_parameters.planet_id]?
events = if BUILDING_EVENTS.length then BUILDING_EVENTS else []
BUILDING_EVENTS = [] if events.length
return _.cloneDeep {
planet: {
date: PLANET_ID_DATES[query_parameters.planet_id].format('YYYY-MM-DD')
season: MONTH_SEASONS[PLANET_ID_DATES[query_parameters.planet_id].month()]
building_events: events
}
}
if root_path == '/tycoon/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.tycoon_id?.length
throw new Error(404) unless TYCOON_METADATA[query_parameters.tycoon_id]?
return _.cloneDeep {
tycoon: TYCOON_METADATA[query_parameters.tycoon_id]
}
if root_path == '/corporation/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
for tycoon_id,tycoon of TYCOON_METADATA
for corporation in tycoon.corporations
if corporation.id == query_parameters.corporation_id
corporation.tycoon_id = tycoon_id unless corporation.tycoon_id?
return { corporation: corporation }
throw new Error(404)
if root_path == '/corporation/events'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
throw new Error(400) unless query_parameters.last_update?.length
throw new Error(404) unless CORPORATION_ID_EVENTS[query_parameters.corporation_id]?
corp_metadata = {
id: query_parameters.corporation_id
cash: CORPORATION_ID_EVENTS[query_parameters.corporation_id].cash
cashflow: CORPORATION_ID_EVENTS[query_parameters.corporation_id].cashflow()
companies: []
}
for company_id,company of CORPORATION_ID_EVENTS[query_parameters.corporation_id].companies_by_id
corp_metadata.companies.push {
id: company.id
cashflow: company.cashflow
}
return _.cloneDeep {
corporation: corp_metadata
}
if root_path == '/bookmarks/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
return _.cloneDeep {
bookmarks: BOOKMARKS_METADATA[query_parameters.corporation_id] || []
}
if root_path == '/bookmarks/update'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.corporation_id?.length
throw new Error(404) unless BOOKMARKS_METADATA[params.corporation_id]?.bookmarks?
updated = []
for delta in params.deltas
existing = _.find(BOOKMARKS_METADATA[params.corporation_id].bookmarks, (bookmark) -> bookmark.id == delta.id)
if existing?
existing.parent_id = delta.parent_id if delta.parent_id?
existing.order = delta.order if delta.order?
updated.push existing
return _.cloneDeep {
bookmarks: updated
}
if root_path == '/bookmarks/new'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.corporation_id?.length
throw new Error(400) unless params.parent_id?.length
throw new Error(400) unless params.name?.length
throw new Error(404) unless BOOKMARKS_METADATA[params.corporation_id]?.bookmarks?
order = _.filter(BOOKMARKS_METADATA[params.corporation_id].bookmarks, (bookmark) -> bookmark.parent_id == params.parent_id).length
if params.type == 'FOLDER'
item = {
type: 'FOLDER'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
}
else if params.type == 'LOCATION'
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
item = {
type: 'LOCATION'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
map_x: params.map_x
map_y: params.map_y
}
else if params.type == 'BUILDING'
throw new Error(400) unless params.building_id?.length
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
item = {
type: 'BUILDING'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
building_id: params.building_id
map_x: params.map_x
map_y: params.map_y
}
else
throw new Error(400)
BOOKMARKS_METADATA[params.corporation_id].bookmarks.push item
return _.cloneDeep {
bookmark: item
}
if root_path == '/mail/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
return _.cloneDeep {
mail: MAIL_METADATA[query_parameters.corporation_id] || []
}
if root_path == '/inventions/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.company_id?.length
return _.cloneDeep {
inventions: {
company_id: query_parameters.company_id
pending_inventions: (COMPANY_ID_INVENTIONS[query_parameters.company_id]?.pending_inventions || [])
completed_ids: (COMPANY_ID_INVENTIONS[query_parameters.company_id]?.completed_ids || [])
}
}
if root_path == '/inventions/sell'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.invention_id?.length
throw new Error(404) unless COMPANY_ID_INVENTIONS[params.company_id]?
inventions = COMPANY_ID_INVENTIONS[params.company_id]
completed_index = inventions.completed_ids.indexOf(params.invention_id)
pending_index = _.findIndex(inventions.pending_inventions, (pending) => pending.id == params.invention_id)
if completed_index >= 0
QUEUED_EVENTS.push { type: 'SELL_RESEARCH', company_id: params.company_id, invention_id: params.invention_id }
inventions.completed_ids.splice(completed_index, 1)
else if pending_index >= 0
QUEUED_EVENTS.push { type: 'CANCEL_RESEARCH', company_id: params.company_id, invention_id: params.invention_id, refund: inventions.pending_inventions[pending_index].spent }
inventions.pending_inventions[index].order -= 1 for index in [pending_index...inventions.pending_inventions.length]
inventions.pending_inventions.splice(pending_index, 1)
return _.cloneDeep {
inventions: {
company_id: params.company_id
pending_inventions: (inventions.pending_inventions || [])
completed_ids: (inventions.completed_ids || [])
}
}
if root_path == '/inventions/queue'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.invention_id?.length
throw new Error(404) unless COMPANY_ID_INVENTIONS[params.company_id]?
inventions = COMPANY_ID_INVENTIONS[params.company_id]
completed_index = inventions.completed_ids.indexOf(params.invention_id)
pending_index = _.findIndex(inventions.pending_inventions, (pending) => pending.id == params.invention_id)
if completed_index >= 0 || pending_index >= 0
throw new Error(404)
inventions.completed_ids.splice(completed_index, 1)
else
inventions.pending_inventions.push {
id: params.invention_id
progress: 0
order: inventions.pending_inventions.length
spent: 0
}
return _.cloneDeep {
inventions: {
company_id: params.company_id
pending_inventions: (inventions.pending_inventions || [])
completed_ids: (inventions.completed_ids || [])
}
}
return {} if root_path == '/inventions/status'
if root_path == '/buildings/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
buildings = []
if query_parameters.company_id?.length
buildings = COMPANY_ID_BUILDINGS[query_parameters.company_id] if COMPANY_ID_BUILDINGS[query_parameters.company_id]?
else if query_parameters.building_id?.length
buildings.push BUILDING_ID_BUILDING[query_parameters.building_id] if BUILDING_ID_BUILDING[query_parameters.building_id]?
else
throw new Error(400)
return _.cloneDeep {
buildings: buildings || []
}
if root_path == '/buildings/construct'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.definition_id?.length
throw new Error(400) unless params.name?.length
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
throw new Error(404) unless COMPANY_ID_INFO[params.company_id]?
throw new Error(404) unless PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id]?
building_info = {
id: Utils.uuid()
name: params.name
tycoon_id: COMPANY_ID_INFO[params.company_id].tycoon_id
corporation_id: COMPANY_ID_INFO[params.company_id].corporation_id
company_id: params.company_id
key: params.definition_id
x: params.map_x
y: params.map_y
stage: -1
progress: 0
}
chunk_x = Math.floor(params.map_x / ChunkMap.CHUNK_WIDTH)
chunk_y = Math.floor(params.map_y / ChunkMap.CHUNK_HEIGHT)
chunk_key = <KEY>
PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key] = [] unless PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key]?
PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key].push building_info
COMPANY_ID_BUILDINGS[params.company_id] = [] unless COMPANY_ID_BUILDINGS[params.company_id]?
COMPANY_ID_BUILDINGS[params.company_id].push building_info
BUILDING_ID_BUILDING[building_info.id] = building_info
COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id] = [] unless COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id]?
COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id].push building_info
BUILDING_EVENTS.push {'type':'construct', 'id':building_info.id, 'definition_id':building_info.key, 'x':building_info.x, 'y':building_info.y}
return _.cloneDeep {
building: building_info
}
if root_path == '/map/buildings'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(400) unless query_parameters.chunk_x? && query_parameters.chunk_y?
throw new Error(404) unless PLANET_MAP_BUILDINGS[query_parameters.planet_id]?
chunk_key = "#{query_parameters.chunk_x}<KEY>query_parameters.chunk_y<KEY>}"
return _.cloneDeep {
buildings: PLANET_MAP_BUILDINGS[query_parameters.planet_id][chunk_key] || []
}
throw new Error(404)
get: (match, data) ->
return data
post: (match, data) ->
return data
}
]
| true |
import moment from 'moment'
import _ from 'lodash'
import ChunkMap from '~/plugins/starpeace-client/map/chunk/chunk-map.coffee'
import TimeUtils from '~/plugins/starpeace-client/utils/time-utils.coffee'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
import BOOKMARKS_METADATA from '~/plugins/starpeace-client/api/mock-bookmarks-metadata.json'
import GALAXY_METADATA from '~/plugins/starpeace-client/api/mock-galaxy-metadata.json'
import PLANETS_DETAILS from '~/plugins/starpeace-client/api/mock-planet-details.json'
import TYCOON_METADATA from '~/plugins/starpeace-client/api/mock-tycoon-metadata.json'
import PLANET_1_MAP_BUILDINGS from '~/plugins/starpeace-client/api/mock-planet-1-map-buildings.json'
import PLANET_1_TYCOON_1_INVENTIONS from '~/plugins/starpeace-client/api/mock-planet-1-tycoon-1-inventions.json'
import PLANET_2_MAP_BUILDINGS from '~/plugins/starpeace-client/api/mock-planet-2-map-buildings.json'
PLANET_MAP_BUILDINGS = {
'planet-1': PLANET_1_MAP_BUILDINGS
'planet-2': PLANET_2_MAP_BUILDINGS
}
API_DELAY = 500
MAIL_METADATA = {}
MONTH_SEASONS = {
0: 'winter'
1: 'winter'
2: 'spring'
3: 'spring'
4: 'spring'
5: 'summer'
6: 'summer'
7: 'summer'
8: 'fall'
9: 'fall'
10: 'fall'
11: 'winter'
}
PLANET_ID_DATES = {}
for planet in GALAXY_METADATA.planets_metadata
if planet.enabled
PLANET_ID_DATES[planet.id] = moment('2235-01-01')
CORPORATION_ID_EVENTS = {}
COMPANY_ID_INFO = {}
COMPANY_ID_INVENTIONS = {}
for tycoon_id,tycoon of TYCOON_METADATA
for corporation in tycoon.corporations
planet = _.find(GALAXY_METADATA.planets_metadata || [], (planet) -> planet.id == corporation.planet_id)
if planet?.enabled
CORPORATION_ID_EVENTS[corporation.id] = {
cash: corporation.cash
companies_by_id: {}
cashflow: () -> _.reduce(_.values(@companies_by_id), ((sum, company) -> sum + company.cashflow), 0)
increment_cash: () -> @cash = @cash + 24 * @cashflow()
}
for company in corporation.companies
COMPANY_ID_INFO[company.id] = {
tycoon_id: tycoon_id
corporation_id: corporation.id
planet_id: corporation.planet_id
}
CORPORATION_ID_EVENTS[corporation.id].companies_by_id[company.id] = {
id: company.id
cashflow: company.cashflow
original_cashflow: company.cashflow
adjust_cashflow: (temporary_delta) -> @cashflow = @original_cashflow + (Math.floor(Math.random() * 500) - 250) + temporary_delta
}
for company_inventions in [PLANET_1_TYCOON_1_INVENTIONS]
if company_inventions[company.id]?
COMPANY_ID_INVENTIONS[company.id] = company_inventions[company.id]
COMPANY_ID_INVENTIONS[company.id].corporation_id = corporation.id
COMPANY_ID_INVENTIONS[company.id].tycoon_id = tycoon_id
COMPANY_ID_BUILDINGS = {}
BUILDING_ID_BUILDING = {}
for planet_id,planet_buildings of PLANET_MAP_BUILDINGS
for chunk_id,chunk_buildings of planet_buildings
for building in chunk_buildings
COMPANY_ID_BUILDINGS[building.company_id] = [] unless COMPANY_ID_BUILDINGS[building.company_id]?
COMPANY_ID_BUILDINGS[building.company_id].push building
BUILDING_ID_BUILDING[building.id] = building
SESSION_TOKENS = {}
valid_session = (token) -> SESSION_TOKENS[token]? && TimeUtils.within_minutes(SESSION_TOKENS[token], 60)
register_session = () ->
token = Utils.uuid()
SESSION_TOKENS[token] = moment()
token
cost_for_invention_id = (invention_id) ->
if window?.starpeace_client?.client_state?.core?.invention_library?
window.starpeace_client.client_state.core.invention_library.metadata_by_id[invention_id]?.properties?.price || 0
else
0
QUEUED_EVENTS = []
COMPANY_CONSTRUCTION_BUIDLINGS = {}
BUILDING_EVENTS = []
setInterval(=>
PLANET_ID_DATES[id].add(1, 'day') for id,date of PLANET_ID_DATES
for corp_id,corp_events of CORPORATION_ID_EVENTS
for company_id,company of corp_events.companies_by_id
cashflow_adjustment = 0
to_remove = []
for event,index in QUEUED_EVENTS
if event.company_id == company_id
to_remove.push index
if event.type == 'SELL_RESEARCH'
cashflow_adjustment += (cost_for_invention_id(event.invention_id) / 24)
else if event.type == 'CANCEL_RESEARCH'
cashflow_adjustment += (event.refund / 24)
QUEUED_EVENTS.splice(index, 1) for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
inventions = COMPANY_ID_INVENTIONS[company_id]
if inventions?.pending_inventions?.length
to_remove = []
for pending,index in inventions.pending_inventions
continue unless index == 0
unless pending.step_increment?
pending.cost = cost_for_invention_id(pending.id)
pending.step_increment = Math.max(50000, Math.round(pending.cost / 30))
pending.spent += pending.step_increment
cashflow_adjustment -= (pending.step_increment / 24)
pending.progress = Math.min(100, Math.round(pending.spent / pending.cost * 100))
if pending.spent >= pending.cost
to_remove.push index
inventions.completed_ids.push pending.id
for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
inventions.pending_inventions.splice(index, 1)
inventions.pending_inventions[index].order = index for index in [0...inventions.pending_inventions.length]
if COMPANY_CONSTRUCTION_BUIDLINGS[company_id]?.length
to_remove = []
for building,index in COMPANY_CONSTRUCTION_BUIDLINGS[company_id]
if building.stage == -1
building.progress = 22 + (building.progress || 0)
building.progress = 100 if building.progress > 100
cashflow_adjustment -= (5000 + Math.random() * 5000)
if building.progress == 100
building.stage = 0
BUILDING_EVENTS.push {'type':'stage', 'id':building.id, 'definition_id':building.key, 'x':building.x, 'y':building.y}
to_remove.push index
else
to_remove.push index
COMPANY_CONSTRUCTION_BUIDLINGS[company_id].splice(index, 1) for index in to_remove.sort((lhs, rhs) -> rhs - lhs)
company.adjust_cashflow(cashflow_adjustment)
corp_events.increment_cash()
, 1000)
export default [
{
pattern: 'http://sandbox-galaxy.starpeace.io:19160(.*)'
fixtures: (match, params, headers, context) ->
throw new Error(404) if match[1] == '/404'
[root_path, query_string] = if match[1].indexOf('?') >= 0 then match[1].split('?') else [match[1], '']
query_parameters = Utils.parse_query(query_string)
context.delay = API_DELAY
if root_path == '/galaxy/metadata'
throw new Error(404) unless context.method == 'get'
return _.cloneDeep GALAXY_METADATA
if root_path == '/session/register'
throw new Error(404) unless context.method == 'post'
if params.type == 'visitor'
return _.cloneDeep {
session_token: register_session()
}
else if params.type == 'tycoon'
return _.cloneDeep {
session_token: register_session()
tycoon_id: 'tycoon-id-1'
}
else
throw new Error(400)
if root_path == '/planet/details'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(404) unless PLANETS_DETAILS[query_parameters.planet_id]?
details = PLANETS_DETAILS[query_parameters.planet_id]
details.date = PLANET_ID_DATES[query_parameters.planet_id].format('YYYY-MM-DD')
details.season = MONTH_SEASONS[PLANET_ID_DATES[query_parameters.planet_id].month()]
return _.cloneDeep {
planet: details
}
if root_path == '/planet/events'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(400) unless query_parameters.last_update?.length
throw new Error(404) unless PLANET_ID_DATES[query_parameters.planet_id]?
events = if BUILDING_EVENTS.length then BUILDING_EVENTS else []
BUILDING_EVENTS = [] if events.length
return _.cloneDeep {
planet: {
date: PLANET_ID_DATES[query_parameters.planet_id].format('YYYY-MM-DD')
season: MONTH_SEASONS[PLANET_ID_DATES[query_parameters.planet_id].month()]
building_events: events
}
}
if root_path == '/tycoon/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.tycoon_id?.length
throw new Error(404) unless TYCOON_METADATA[query_parameters.tycoon_id]?
return _.cloneDeep {
tycoon: TYCOON_METADATA[query_parameters.tycoon_id]
}
if root_path == '/corporation/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
for tycoon_id,tycoon of TYCOON_METADATA
for corporation in tycoon.corporations
if corporation.id == query_parameters.corporation_id
corporation.tycoon_id = tycoon_id unless corporation.tycoon_id?
return { corporation: corporation }
throw new Error(404)
if root_path == '/corporation/events'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
throw new Error(400) unless query_parameters.last_update?.length
throw new Error(404) unless CORPORATION_ID_EVENTS[query_parameters.corporation_id]?
corp_metadata = {
id: query_parameters.corporation_id
cash: CORPORATION_ID_EVENTS[query_parameters.corporation_id].cash
cashflow: CORPORATION_ID_EVENTS[query_parameters.corporation_id].cashflow()
companies: []
}
for company_id,company of CORPORATION_ID_EVENTS[query_parameters.corporation_id].companies_by_id
corp_metadata.companies.push {
id: company.id
cashflow: company.cashflow
}
return _.cloneDeep {
corporation: corp_metadata
}
if root_path == '/bookmarks/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
return _.cloneDeep {
bookmarks: BOOKMARKS_METADATA[query_parameters.corporation_id] || []
}
if root_path == '/bookmarks/update'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.corporation_id?.length
throw new Error(404) unless BOOKMARKS_METADATA[params.corporation_id]?.bookmarks?
updated = []
for delta in params.deltas
existing = _.find(BOOKMARKS_METADATA[params.corporation_id].bookmarks, (bookmark) -> bookmark.id == delta.id)
if existing?
existing.parent_id = delta.parent_id if delta.parent_id?
existing.order = delta.order if delta.order?
updated.push existing
return _.cloneDeep {
bookmarks: updated
}
if root_path == '/bookmarks/new'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.corporation_id?.length
throw new Error(400) unless params.parent_id?.length
throw new Error(400) unless params.name?.length
throw new Error(404) unless BOOKMARKS_METADATA[params.corporation_id]?.bookmarks?
order = _.filter(BOOKMARKS_METADATA[params.corporation_id].bookmarks, (bookmark) -> bookmark.parent_id == params.parent_id).length
if params.type == 'FOLDER'
item = {
type: 'FOLDER'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
}
else if params.type == 'LOCATION'
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
item = {
type: 'LOCATION'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
map_x: params.map_x
map_y: params.map_y
}
else if params.type == 'BUILDING'
throw new Error(400) unless params.building_id?.length
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
item = {
type: 'BUILDING'
id: Utils.uuid()
parent_id: params.parent_id
name: params.name
order: order
building_id: params.building_id
map_x: params.map_x
map_y: params.map_y
}
else
throw new Error(400)
BOOKMARKS_METADATA[params.corporation_id].bookmarks.push item
return _.cloneDeep {
bookmark: item
}
if root_path == '/mail/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.corporation_id?.length
return _.cloneDeep {
mail: MAIL_METADATA[query_parameters.corporation_id] || []
}
if root_path == '/inventions/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.company_id?.length
return _.cloneDeep {
inventions: {
company_id: query_parameters.company_id
pending_inventions: (COMPANY_ID_INVENTIONS[query_parameters.company_id]?.pending_inventions || [])
completed_ids: (COMPANY_ID_INVENTIONS[query_parameters.company_id]?.completed_ids || [])
}
}
if root_path == '/inventions/sell'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.invention_id?.length
throw new Error(404) unless COMPANY_ID_INVENTIONS[params.company_id]?
inventions = COMPANY_ID_INVENTIONS[params.company_id]
completed_index = inventions.completed_ids.indexOf(params.invention_id)
pending_index = _.findIndex(inventions.pending_inventions, (pending) => pending.id == params.invention_id)
if completed_index >= 0
QUEUED_EVENTS.push { type: 'SELL_RESEARCH', company_id: params.company_id, invention_id: params.invention_id }
inventions.completed_ids.splice(completed_index, 1)
else if pending_index >= 0
QUEUED_EVENTS.push { type: 'CANCEL_RESEARCH', company_id: params.company_id, invention_id: params.invention_id, refund: inventions.pending_inventions[pending_index].spent }
inventions.pending_inventions[index].order -= 1 for index in [pending_index...inventions.pending_inventions.length]
inventions.pending_inventions.splice(pending_index, 1)
return _.cloneDeep {
inventions: {
company_id: params.company_id
pending_inventions: (inventions.pending_inventions || [])
completed_ids: (inventions.completed_ids || [])
}
}
if root_path == '/inventions/queue'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.invention_id?.length
throw new Error(404) unless COMPANY_ID_INVENTIONS[params.company_id]?
inventions = COMPANY_ID_INVENTIONS[params.company_id]
completed_index = inventions.completed_ids.indexOf(params.invention_id)
pending_index = _.findIndex(inventions.pending_inventions, (pending) => pending.id == params.invention_id)
if completed_index >= 0 || pending_index >= 0
throw new Error(404)
inventions.completed_ids.splice(completed_index, 1)
else
inventions.pending_inventions.push {
id: params.invention_id
progress: 0
order: inventions.pending_inventions.length
spent: 0
}
return _.cloneDeep {
inventions: {
company_id: params.company_id
pending_inventions: (inventions.pending_inventions || [])
completed_ids: (inventions.completed_ids || [])
}
}
return {} if root_path == '/inventions/status'
if root_path == '/buildings/metadata'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
buildings = []
if query_parameters.company_id?.length
buildings = COMPANY_ID_BUILDINGS[query_parameters.company_id] if COMPANY_ID_BUILDINGS[query_parameters.company_id]?
else if query_parameters.building_id?.length
buildings.push BUILDING_ID_BUILDING[query_parameters.building_id] if BUILDING_ID_BUILDING[query_parameters.building_id]?
else
throw new Error(400)
return _.cloneDeep {
buildings: buildings || []
}
if root_path == '/buildings/construct'
throw new Error(404) unless context.method == 'post'
throw new Error(401) unless valid_session(params.session_token)
throw new Error(400) unless params.company_id?.length
throw new Error(400) unless params.definition_id?.length
throw new Error(400) unless params.name?.length
throw new Error(400) unless params.map_x?
throw new Error(400) unless params.map_y?
throw new Error(404) unless COMPANY_ID_INFO[params.company_id]?
throw new Error(404) unless PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id]?
building_info = {
id: Utils.uuid()
name: params.name
tycoon_id: COMPANY_ID_INFO[params.company_id].tycoon_id
corporation_id: COMPANY_ID_INFO[params.company_id].corporation_id
company_id: params.company_id
key: params.definition_id
x: params.map_x
y: params.map_y
stage: -1
progress: 0
}
chunk_x = Math.floor(params.map_x / ChunkMap.CHUNK_WIDTH)
chunk_y = Math.floor(params.map_y / ChunkMap.CHUNK_HEIGHT)
chunk_key = PI:KEY:<KEY>END_PI
PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key] = [] unless PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key]?
PLANET_MAP_BUILDINGS[COMPANY_ID_INFO[params.company_id].planet_id][chunk_key].push building_info
COMPANY_ID_BUILDINGS[params.company_id] = [] unless COMPANY_ID_BUILDINGS[params.company_id]?
COMPANY_ID_BUILDINGS[params.company_id].push building_info
BUILDING_ID_BUILDING[building_info.id] = building_info
COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id] = [] unless COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id]?
COMPANY_CONSTRUCTION_BUIDLINGS[params.company_id].push building_info
BUILDING_EVENTS.push {'type':'construct', 'id':building_info.id, 'definition_id':building_info.key, 'x':building_info.x, 'y':building_info.y}
return _.cloneDeep {
building: building_info
}
if root_path == '/map/buildings'
throw new Error(404) unless context.method == 'get'
throw new Error(401) unless valid_session(query_parameters.session_token)
throw new Error(400) unless query_parameters.planet_id?.length
throw new Error(400) unless query_parameters.chunk_x? && query_parameters.chunk_y?
throw new Error(404) unless PLANET_MAP_BUILDINGS[query_parameters.planet_id]?
chunk_key = "#{query_parameters.chunk_x}PI:KEY:<KEY>END_PIquery_parameters.chunk_yPI:KEY:<KEY>END_PI}"
return _.cloneDeep {
buildings: PLANET_MAP_BUILDINGS[query_parameters.planet_id][chunk_key] || []
}
throw new Error(404)
get: (match, data) ->
return data
post: (match, data) ->
return data
}
]
|
[
{
"context": " Ember.belongsTo('Travis.Repo', key: 'repository_id')\n build: Ember.belongsTo('Travis.Build')\n com",
"end": 601,
"score": 0.6286887526512146,
"start": 599,
"tag": "KEY",
"value": "id"
},
{
"context": "'log').clear()\n\n sponsor: (->\n {\n name: \"Blue Box\"\n url: \"http://bluebox.net\"\n }\n ).proper",
"end": 1276,
"score": 0.9755209684371948,
"start": 1268,
"tag": "NAME",
"value": "Blue Box"
}
] | assets/scripts/app/models/job.coffee | rwjblue/travis-web | 0 | require 'travis/model'
@Travis.Job = Travis.Model.extend Travis.DurationCalculations,
repoId: Ember.attr('string', key: 'repository_id')
buildId: Ember.attr('string')
commitId: Ember.attr('string')
logId: Ember.attr('string')
queue: Ember.attr('string')
state: Ember.attr('string')
number: Ember.attr('string')
startedAt: Ember.attr('string')
finishedAt: Ember.attr('string')
allowFailure: Ember.attr('boolean')
repositorySlug: Ember.attr('string')
repo: Ember.belongsTo('Travis.Repo', key: 'repository_id')
build: Ember.belongsTo('Travis.Build')
commit: Ember.belongsTo('Travis.Commit')
_config: Ember.attr('object', key: 'config')
log: ( ->
@set('isLogAccessed', true)
Travis.Log.create(job: this)
).property()
repoSlug: (->
@get('repositorySlug')
).property('repositorySlug')
config: (->
Travis.Helpers.compact(@get('_config'))
).property('_config')
isFinished: (->
@get('state') in ['passed', 'failed', 'errored', 'canceled']
).property('state')
clearLog: ->
# This is needed if we don't want to fetch log just to clear it
if @get('isLogAccessed')
@get('log').clear()
sponsor: (->
{
name: "Blue Box"
url: "http://bluebox.net"
}
).property()
configValues: (->
config = @get('config')
keys = @get('build.rawConfigKeys')
if config && keys
keys.map (key) -> config[key]
else
[]
).property('config', 'build.rawConfigKeys.length')
canCancel: (->
!@get('isFinished')
).property('state')
cancel: (->
Travis.ajax.post "/jobs/#{@get('id')}/cancel"
)
requeue: ->
Travis.ajax.post '/requests', job_id: @get('id')
appendLog: (part) ->
@get('log').append part
subscribe: ->
return if @get('subscribed')
@set('subscribed', true)
if Travis.pusher
Travis.pusher.subscribe "job-#{@get('id')}"
unsubscribe: ->
return unless @get('subscribed')
@set('subscribed', false)
if Travis.pusher
Travis.pusher.unsubscribe "job-#{@get('id')}"
onStateChange: (->
if @get('state') == 'finished' && Travis.pusher
Travis.pusher.unsubscribe "job-#{@get('id')}"
).observes('state')
isPropertyLoaded: (key) ->
if ['finishedAt'].contains(key) && !@get('isFinished')
return true
else if key == 'startedAt' && @get('state') == 'created'
return true
else
@_super(key)
isFinished: (->
@get('state') in ['passed', 'failed', 'errored', 'canceled']
).property('state')
# TODO: such formattings should be done in controller, but in order
# to use it there easily, I would have to refactor job and build
# controllers
formattedFinishedAt: (->
if finishedAt = @get('finishedAt')
moment(finishedAt).format('lll')
).property('finishedAt')
@Travis.Job.reopenClass
queued: ->
filtered = Ember.FilteredRecordArray.create(
modelClass: Travis.Job
filterFunction: (job) ->
['created', 'queued'].indexOf(job.get('state')) != -1
filterProperties: ['state', 'queue']
)
@fetch().then (array) ->
filtered.updateFilter()
filtered.set('isLoaded', true)
filtered
running: ->
filtered = Ember.FilteredRecordArray.create(
modelClass: Travis.Job
filterFunction: (job) ->
job.get('state') == 'started'
filterProperties: ['state']
)
@fetch(state: 'started').then (array) ->
filtered.updateFilter()
filtered.set('isLoaded', true)
filtered
| 55575 | require 'travis/model'
@Travis.Job = Travis.Model.extend Travis.DurationCalculations,
repoId: Ember.attr('string', key: 'repository_id')
buildId: Ember.attr('string')
commitId: Ember.attr('string')
logId: Ember.attr('string')
queue: Ember.attr('string')
state: Ember.attr('string')
number: Ember.attr('string')
startedAt: Ember.attr('string')
finishedAt: Ember.attr('string')
allowFailure: Ember.attr('boolean')
repositorySlug: Ember.attr('string')
repo: Ember.belongsTo('Travis.Repo', key: 'repository_<KEY>')
build: Ember.belongsTo('Travis.Build')
commit: Ember.belongsTo('Travis.Commit')
_config: Ember.attr('object', key: 'config')
log: ( ->
@set('isLogAccessed', true)
Travis.Log.create(job: this)
).property()
repoSlug: (->
@get('repositorySlug')
).property('repositorySlug')
config: (->
Travis.Helpers.compact(@get('_config'))
).property('_config')
isFinished: (->
@get('state') in ['passed', 'failed', 'errored', 'canceled']
).property('state')
clearLog: ->
# This is needed if we don't want to fetch log just to clear it
if @get('isLogAccessed')
@get('log').clear()
sponsor: (->
{
name: "<NAME>"
url: "http://bluebox.net"
}
).property()
configValues: (->
config = @get('config')
keys = @get('build.rawConfigKeys')
if config && keys
keys.map (key) -> config[key]
else
[]
).property('config', 'build.rawConfigKeys.length')
canCancel: (->
!@get('isFinished')
).property('state')
cancel: (->
Travis.ajax.post "/jobs/#{@get('id')}/cancel"
)
requeue: ->
Travis.ajax.post '/requests', job_id: @get('id')
appendLog: (part) ->
@get('log').append part
subscribe: ->
return if @get('subscribed')
@set('subscribed', true)
if Travis.pusher
Travis.pusher.subscribe "job-#{@get('id')}"
unsubscribe: ->
return unless @get('subscribed')
@set('subscribed', false)
if Travis.pusher
Travis.pusher.unsubscribe "job-#{@get('id')}"
onStateChange: (->
if @get('state') == 'finished' && Travis.pusher
Travis.pusher.unsubscribe "job-#{@get('id')}"
).observes('state')
isPropertyLoaded: (key) ->
if ['finishedAt'].contains(key) && !@get('isFinished')
return true
else if key == 'startedAt' && @get('state') == 'created'
return true
else
@_super(key)
isFinished: (->
@get('state') in ['passed', 'failed', 'errored', 'canceled']
).property('state')
# TODO: such formattings should be done in controller, but in order
# to use it there easily, I would have to refactor job and build
# controllers
formattedFinishedAt: (->
if finishedAt = @get('finishedAt')
moment(finishedAt).format('lll')
).property('finishedAt')
@Travis.Job.reopenClass
queued: ->
filtered = Ember.FilteredRecordArray.create(
modelClass: Travis.Job
filterFunction: (job) ->
['created', 'queued'].indexOf(job.get('state')) != -1
filterProperties: ['state', 'queue']
)
@fetch().then (array) ->
filtered.updateFilter()
filtered.set('isLoaded', true)
filtered
running: ->
filtered = Ember.FilteredRecordArray.create(
modelClass: Travis.Job
filterFunction: (job) ->
job.get('state') == 'started'
filterProperties: ['state']
)
@fetch(state: 'started').then (array) ->
filtered.updateFilter()
filtered.set('isLoaded', true)
filtered
| true | require 'travis/model'
@Travis.Job = Travis.Model.extend Travis.DurationCalculations,
repoId: Ember.attr('string', key: 'repository_id')
buildId: Ember.attr('string')
commitId: Ember.attr('string')
logId: Ember.attr('string')
queue: Ember.attr('string')
state: Ember.attr('string')
number: Ember.attr('string')
startedAt: Ember.attr('string')
finishedAt: Ember.attr('string')
allowFailure: Ember.attr('boolean')
repositorySlug: Ember.attr('string')
repo: Ember.belongsTo('Travis.Repo', key: 'repository_PI:KEY:<KEY>END_PI')
build: Ember.belongsTo('Travis.Build')
commit: Ember.belongsTo('Travis.Commit')
_config: Ember.attr('object', key: 'config')
log: ( ->
@set('isLogAccessed', true)
Travis.Log.create(job: this)
).property()
repoSlug: (->
@get('repositorySlug')
).property('repositorySlug')
config: (->
Travis.Helpers.compact(@get('_config'))
).property('_config')
isFinished: (->
@get('state') in ['passed', 'failed', 'errored', 'canceled']
).property('state')
clearLog: ->
# This is needed if we don't want to fetch log just to clear it
if @get('isLogAccessed')
@get('log').clear()
sponsor: (->
{
name: "PI:NAME:<NAME>END_PI"
url: "http://bluebox.net"
}
).property()
configValues: (->
config = @get('config')
keys = @get('build.rawConfigKeys')
if config && keys
keys.map (key) -> config[key]
else
[]
).property('config', 'build.rawConfigKeys.length')
canCancel: (->
!@get('isFinished')
).property('state')
cancel: (->
Travis.ajax.post "/jobs/#{@get('id')}/cancel"
)
requeue: ->
Travis.ajax.post '/requests', job_id: @get('id')
appendLog: (part) ->
@get('log').append part
subscribe: ->
return if @get('subscribed')
@set('subscribed', true)
if Travis.pusher
Travis.pusher.subscribe "job-#{@get('id')}"
unsubscribe: ->
return unless @get('subscribed')
@set('subscribed', false)
if Travis.pusher
Travis.pusher.unsubscribe "job-#{@get('id')}"
onStateChange: (->
if @get('state') == 'finished' && Travis.pusher
Travis.pusher.unsubscribe "job-#{@get('id')}"
).observes('state')
isPropertyLoaded: (key) ->
if ['finishedAt'].contains(key) && !@get('isFinished')
return true
else if key == 'startedAt' && @get('state') == 'created'
return true
else
@_super(key)
isFinished: (->
@get('state') in ['passed', 'failed', 'errored', 'canceled']
).property('state')
# TODO: such formattings should be done in controller, but in order
# to use it there easily, I would have to refactor job and build
# controllers
formattedFinishedAt: (->
if finishedAt = @get('finishedAt')
moment(finishedAt).format('lll')
).property('finishedAt')
@Travis.Job.reopenClass
queued: ->
filtered = Ember.FilteredRecordArray.create(
modelClass: Travis.Job
filterFunction: (job) ->
['created', 'queued'].indexOf(job.get('state')) != -1
filterProperties: ['state', 'queue']
)
@fetch().then (array) ->
filtered.updateFilter()
filtered.set('isLoaded', true)
filtered
running: ->
filtered = Ember.FilteredRecordArray.create(
modelClass: Travis.Job
filterFunction: (job) ->
job.get('state') == 'started'
filterProperties: ['state']
)
@fetch(state: 'started').then (array) ->
filtered.updateFilter()
filtered.set('isLoaded', true)
filtered
|
[
{
"context": "exception\n assertUnreachable()\nassertEquals \"Capybara\", animal\n",
"end": 2688,
"score": 0.517824113368988,
"start": 2684,
"tag": "NAME",
"value": "bara"
}
] | deps/v8/test/mjsunit/debug-liveedit-stack-padding.coffee | lxe/io.coffee | 0 | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Flags: --expose-debug-as debug
# Get the Debug object exposed from the debug context global object.
listener = (event, exec_state, event_data, data) ->
if event is Debug.DebugEvent.Break
try
debugger_handler()
catch e
saved_exception = e
else
print "Other: " + event
return
Debug = debug.Debug
SlimFunction = eval("(function() {\n " + " return 'Cat';\n" + "})\n")
script = Debug.findScript(SlimFunction)
Debug.setScriptBreakPointById script.id, 1, 0
orig_animal = "'Cat'"
patch_pos = script.source.indexOf(orig_animal)
new_animal_patch = "'Capybara'"
debugger_handler = (->
already_called = false
->
return if already_called
already_called = true
change_log = new Array()
try
Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_animal.length, new_animal_patch, change_log
finally
print "Change log: " + JSON.stringify(change_log) + "\n"
return
)()
saved_exception = null
Debug.setListener listener
animal = SlimFunction()
if saved_exception
print "Exception: " + saved_exception
assertUnreachable()
assertEquals "Capybara", animal
| 155052 | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Flags: --expose-debug-as debug
# Get the Debug object exposed from the debug context global object.
listener = (event, exec_state, event_data, data) ->
if event is Debug.DebugEvent.Break
try
debugger_handler()
catch e
saved_exception = e
else
print "Other: " + event
return
Debug = debug.Debug
SlimFunction = eval("(function() {\n " + " return 'Cat';\n" + "})\n")
script = Debug.findScript(SlimFunction)
Debug.setScriptBreakPointById script.id, 1, 0
orig_animal = "'Cat'"
patch_pos = script.source.indexOf(orig_animal)
new_animal_patch = "'Capybara'"
debugger_handler = (->
already_called = false
->
return if already_called
already_called = true
change_log = new Array()
try
Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_animal.length, new_animal_patch, change_log
finally
print "Change log: " + JSON.stringify(change_log) + "\n"
return
)()
saved_exception = null
Debug.setListener listener
animal = SlimFunction()
if saved_exception
print "Exception: " + saved_exception
assertUnreachable()
assertEquals "Capy<NAME>", animal
| true | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Flags: --expose-debug-as debug
# Get the Debug object exposed from the debug context global object.
listener = (event, exec_state, event_data, data) ->
if event is Debug.DebugEvent.Break
try
debugger_handler()
catch e
saved_exception = e
else
print "Other: " + event
return
Debug = debug.Debug
SlimFunction = eval("(function() {\n " + " return 'Cat';\n" + "})\n")
script = Debug.findScript(SlimFunction)
Debug.setScriptBreakPointById script.id, 1, 0
orig_animal = "'Cat'"
patch_pos = script.source.indexOf(orig_animal)
new_animal_patch = "'Capybara'"
debugger_handler = (->
already_called = false
->
return if already_called
already_called = true
change_log = new Array()
try
Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_animal.length, new_animal_patch, change_log
finally
print "Change log: " + JSON.stringify(change_log) + "\n"
return
)()
saved_exception = null
Debug.setListener listener
animal = SlimFunction()
if saved_exception
print "Exception: " + saved_exception
assertUnreachable()
assertEquals "CapyPI:NAME:<NAME>END_PI", animal
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9979228377342224,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-crypto-certificate.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.
# Test Certificates
stripLineEndings = (obj) ->
obj.replace /\n/g, ""
common = require("../common")
assert = require("assert")
crypto = require("crypto")
crypto.DEFAULT_ENCODING = "buffer"
fs = require("fs")
path = require("path")
spkacValid = fs.readFileSync(common.fixturesDir + "/spkac.valid")
spkacFail = fs.readFileSync(common.fixturesDir + "/spkac.fail")
spkacPem = fs.readFileSync(common.fixturesDir + "/spkac.pem")
certificate = new crypto.Certificate()
assert.equal certificate.verifySpkac(spkacValid), true
assert.equal certificate.verifySpkac(spkacFail), false
assert.equal stripLineEndings(certificate.exportPublicKey(spkacValid).toString("utf8")), stripLineEndings(spkacPem.toString("utf8"))
assert.equal certificate.exportPublicKey(spkacFail), ""
assert.equal certificate.exportChallenge(spkacValid).toString("utf8"), "fb9ab814-6677-42a4-a60c-f905d1a6924d"
assert.equal certificate.exportChallenge(spkacFail), ""
| 52760 | # 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.
# Test Certificates
stripLineEndings = (obj) ->
obj.replace /\n/g, ""
common = require("../common")
assert = require("assert")
crypto = require("crypto")
crypto.DEFAULT_ENCODING = "buffer"
fs = require("fs")
path = require("path")
spkacValid = fs.readFileSync(common.fixturesDir + "/spkac.valid")
spkacFail = fs.readFileSync(common.fixturesDir + "/spkac.fail")
spkacPem = fs.readFileSync(common.fixturesDir + "/spkac.pem")
certificate = new crypto.Certificate()
assert.equal certificate.verifySpkac(spkacValid), true
assert.equal certificate.verifySpkac(spkacFail), false
assert.equal stripLineEndings(certificate.exportPublicKey(spkacValid).toString("utf8")), stripLineEndings(spkacPem.toString("utf8"))
assert.equal certificate.exportPublicKey(spkacFail), ""
assert.equal certificate.exportChallenge(spkacValid).toString("utf8"), "fb9ab814-6677-42a4-a60c-f905d1a6924d"
assert.equal certificate.exportChallenge(spkacFail), ""
| 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.
# Test Certificates
stripLineEndings = (obj) ->
obj.replace /\n/g, ""
common = require("../common")
assert = require("assert")
crypto = require("crypto")
crypto.DEFAULT_ENCODING = "buffer"
fs = require("fs")
path = require("path")
spkacValid = fs.readFileSync(common.fixturesDir + "/spkac.valid")
spkacFail = fs.readFileSync(common.fixturesDir + "/spkac.fail")
spkacPem = fs.readFileSync(common.fixturesDir + "/spkac.pem")
certificate = new crypto.Certificate()
assert.equal certificate.verifySpkac(spkacValid), true
assert.equal certificate.verifySpkac(spkacFail), false
assert.equal stripLineEndings(certificate.exportPublicKey(spkacValid).toString("utf8")), stripLineEndings(spkacPem.toString("utf8"))
assert.equal certificate.exportPublicKey(spkacFail), ""
assert.equal certificate.exportChallenge(spkacValid).toString("utf8"), "fb9ab814-6677-42a4-a60c-f905d1a6924d"
assert.equal certificate.exportChallenge(spkacFail), ""
|
[
{
"context": "requestHeaders =\n authorization: \"Basic c3R1YmJ5OnBhc3N3b3Jk\"\n\n createRequest @context\n\n waits",
"end": 6790,
"score": 0.8484594821929932,
"start": 6770,
"tag": "KEY",
"value": "c3R1YmJ5OnBhc3N3b3Jk"
},
{
"context": "requestHeaders =\n authorization: \"Basic c3R1YmJ5OnBhc3N3b3JkWjBy\"\n\n createRequest @context\n\n waits",
"end": 7425,
"score": 0.9143341779708862,
"start": 7401,
"tag": "KEY",
"value": "c3R1YmJ5OnBhc3N3b3JkWjBy"
}
] | spec/e2e.stubs.spec.coffee | bbc/stubby4node | 0 | Stubby = require('../lib/main').Stubby
fs = require 'fs'
yaml = require 'js-yaml'
ce = require 'cloneextend'
endpointData = yaml.load (fs.readFileSync 'spec/data/e2e.yaml', 'utf8').trim()
waitsFor = require './helpers/waits-for'
assert = require 'assert'
createRequest = require './helpers/create-request'
describe 'End 2 End Stubs Test Suite', ->
sut = null
port = 8882
stopStubby = (finish) ->
if sut? then return sut.stop finish
finish()
beforeEach (done) ->
@context =
done: false
port: port
finish = ->
sut = new Stubby()
sut.start data:endpointData, done
stopStubby finish
afterEach stopStubby
describe 'basics', ->
it 'should return a basic GET endpoint', (done) ->
@context.url = '/basic/get'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic PUT endpoint', (done) ->
@context.url = '/basic/put'
@context.method = 'put'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic POST endpoint', (done) ->
@context.url = '/basic/post'
@context.method = 'post'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic DELETE endpoint', (done) ->
@context.url = '/basic/delete'
@context.method = 'delete'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic HEAD endpoint', (done) ->
@context.url = '/basic/head'
@context.method = 'head'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a response for an endpoint with multiple methods', (done) ->
@context.url = '/basic/all'
@context.method = 'delete'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint delete to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'get'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint get to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'put'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint put to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'post'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint post to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return the CORS headers', (done) ->
expected = 'http://example.org'
@context.url = '/basic/get'
@context.method = 'get'
@context.requestHeaders =
'origin': expected
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
headers = @context.response.headers
assert headers['access-control-allow-origin'] is expected
assert headers['access-control-allow-credentials'] is 'true'
done()
it 'should return multiple headers with the same name', (done) ->
expected = ['type=ninja', 'language=coffeescript']
@context.url = '/duplicated/header'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
headers = @context.response.headers
assert.deepEqual headers['set-cookie'], expected
done()
describe 'GET', ->
it 'should return a body from a GET endpoint', (done) ->
@context.url = '/get/body'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.data is 'plain text'
done()
it 'should return a body from a json GET endpoint', (done) ->
@context.url = '/get/json'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.data.trim() is '{"property":"value"}'
assert @context.response.headers['content-type'] is 'application/json'
done()
it 'should return a 420 GET endpoint', (done) ->
@context.url = '/get/420'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 420
done()
it 'should be able to handle query params', (done) ->
@context.url = '/get/query'
@context.query =
first: 'value1 with spaces!'
second: 'value2'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return 404 if query params are not matched', (done) ->
@context.url = '/get/query'
@context.query =
first: 'invalid value'
second: 'value2'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 404
done()
describe 'post', ->
it 'should be able to handle authorized posts', (done) ->
@context.url = '/post/auth'
@context.method = 'post'
@context.post = 'some=data'
@context.requestHeaders =
authorization: "Basic c3R1YmJ5OnBhc3N3b3Jk"
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 201
assert @context.response.headers.location is '/some/endpoint/id'
assert @context.response.data is 'resource has been created'
done()
it 'should be able to handle authorized posts where the yaml wasnt pre-encoded', (done) ->
@context.url = '/post/auth/pair'
@context.method = 'post'
@context.post = 'some=data'
@context.requestHeaders =
authorization: "Basic c3R1YmJ5OnBhc3N3b3JkWjBy"
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 201
assert @context.response.headers.location is '/some/endpoint/id'
assert @context.response.data is 'resource has been created'
done()
describe 'put', ->
it 'should wait if a 2000ms latency is specified', (done) ->
@timeout 3500
@context.url = '/put/latency'
@context.method = 'put'
createRequest @context
waitsFor ( => @context.done ), 'latency-ridden request to finish', [2000, 3000], =>
assert @context.response.data is 'updated'
done()
describe 'file use', ->
describe 'response', ->
it 'should handle fallback to body if specified response file cannot be found', (done) ->
@context.url = '/file/body/missingfile'
createRequest @context
waitsFor ( => @context.done ), 'body-fallback request to finish', 1000, =>
assert @context.response.data is 'body contents!'
done()
it 'should handle file response when file can be found', (done) ->
@context.url = '/file/body'
createRequest @context
waitsFor ( => @context.done ), 'body-fallback request to finish', 1000, =>
assert @context.response.data.trim() is 'file contents!'
done()
describe 'request', ->
it 'should handle fallback to post if specified request file cannot be found', (done) ->
@context.url = '/file/post/missingfile'
@context.method = 'post'
@context.post = 'post contents!'
createRequest @context
waitsFor ( => @context.done ), 'post-fallback request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should handle file request when file can be found', (done) ->
@context.url = '/file/post'
@context.method = 'post'
@context.post = 'file contents!'
createRequest @context
waitsFor ( => @context.done ), 'post-fallback request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
| 223150 | Stubby = require('../lib/main').Stubby
fs = require 'fs'
yaml = require 'js-yaml'
ce = require 'cloneextend'
endpointData = yaml.load (fs.readFileSync 'spec/data/e2e.yaml', 'utf8').trim()
waitsFor = require './helpers/waits-for'
assert = require 'assert'
createRequest = require './helpers/create-request'
describe 'End 2 End Stubs Test Suite', ->
sut = null
port = 8882
stopStubby = (finish) ->
if sut? then return sut.stop finish
finish()
beforeEach (done) ->
@context =
done: false
port: port
finish = ->
sut = new Stubby()
sut.start data:endpointData, done
stopStubby finish
afterEach stopStubby
describe 'basics', ->
it 'should return a basic GET endpoint', (done) ->
@context.url = '/basic/get'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic PUT endpoint', (done) ->
@context.url = '/basic/put'
@context.method = 'put'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic POST endpoint', (done) ->
@context.url = '/basic/post'
@context.method = 'post'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic DELETE endpoint', (done) ->
@context.url = '/basic/delete'
@context.method = 'delete'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic HEAD endpoint', (done) ->
@context.url = '/basic/head'
@context.method = 'head'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a response for an endpoint with multiple methods', (done) ->
@context.url = '/basic/all'
@context.method = 'delete'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint delete to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'get'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint get to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'put'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint put to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'post'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint post to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return the CORS headers', (done) ->
expected = 'http://example.org'
@context.url = '/basic/get'
@context.method = 'get'
@context.requestHeaders =
'origin': expected
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
headers = @context.response.headers
assert headers['access-control-allow-origin'] is expected
assert headers['access-control-allow-credentials'] is 'true'
done()
it 'should return multiple headers with the same name', (done) ->
expected = ['type=ninja', 'language=coffeescript']
@context.url = '/duplicated/header'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
headers = @context.response.headers
assert.deepEqual headers['set-cookie'], expected
done()
describe 'GET', ->
it 'should return a body from a GET endpoint', (done) ->
@context.url = '/get/body'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.data is 'plain text'
done()
it 'should return a body from a json GET endpoint', (done) ->
@context.url = '/get/json'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.data.trim() is '{"property":"value"}'
assert @context.response.headers['content-type'] is 'application/json'
done()
it 'should return a 420 GET endpoint', (done) ->
@context.url = '/get/420'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 420
done()
it 'should be able to handle query params', (done) ->
@context.url = '/get/query'
@context.query =
first: 'value1 with spaces!'
second: 'value2'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return 404 if query params are not matched', (done) ->
@context.url = '/get/query'
@context.query =
first: 'invalid value'
second: 'value2'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 404
done()
describe 'post', ->
it 'should be able to handle authorized posts', (done) ->
@context.url = '/post/auth'
@context.method = 'post'
@context.post = 'some=data'
@context.requestHeaders =
authorization: "Basic <KEY>"
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 201
assert @context.response.headers.location is '/some/endpoint/id'
assert @context.response.data is 'resource has been created'
done()
it 'should be able to handle authorized posts where the yaml wasnt pre-encoded', (done) ->
@context.url = '/post/auth/pair'
@context.method = 'post'
@context.post = 'some=data'
@context.requestHeaders =
authorization: "Basic <KEY>"
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 201
assert @context.response.headers.location is '/some/endpoint/id'
assert @context.response.data is 'resource has been created'
done()
describe 'put', ->
it 'should wait if a 2000ms latency is specified', (done) ->
@timeout 3500
@context.url = '/put/latency'
@context.method = 'put'
createRequest @context
waitsFor ( => @context.done ), 'latency-ridden request to finish', [2000, 3000], =>
assert @context.response.data is 'updated'
done()
describe 'file use', ->
describe 'response', ->
it 'should handle fallback to body if specified response file cannot be found', (done) ->
@context.url = '/file/body/missingfile'
createRequest @context
waitsFor ( => @context.done ), 'body-fallback request to finish', 1000, =>
assert @context.response.data is 'body contents!'
done()
it 'should handle file response when file can be found', (done) ->
@context.url = '/file/body'
createRequest @context
waitsFor ( => @context.done ), 'body-fallback request to finish', 1000, =>
assert @context.response.data.trim() is 'file contents!'
done()
describe 'request', ->
it 'should handle fallback to post if specified request file cannot be found', (done) ->
@context.url = '/file/post/missingfile'
@context.method = 'post'
@context.post = 'post contents!'
createRequest @context
waitsFor ( => @context.done ), 'post-fallback request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should handle file request when file can be found', (done) ->
@context.url = '/file/post'
@context.method = 'post'
@context.post = 'file contents!'
createRequest @context
waitsFor ( => @context.done ), 'post-fallback request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
| true | Stubby = require('../lib/main').Stubby
fs = require 'fs'
yaml = require 'js-yaml'
ce = require 'cloneextend'
endpointData = yaml.load (fs.readFileSync 'spec/data/e2e.yaml', 'utf8').trim()
waitsFor = require './helpers/waits-for'
assert = require 'assert'
createRequest = require './helpers/create-request'
describe 'End 2 End Stubs Test Suite', ->
sut = null
port = 8882
stopStubby = (finish) ->
if sut? then return sut.stop finish
finish()
beforeEach (done) ->
@context =
done: false
port: port
finish = ->
sut = new Stubby()
sut.start data:endpointData, done
stopStubby finish
afterEach stopStubby
describe 'basics', ->
it 'should return a basic GET endpoint', (done) ->
@context.url = '/basic/get'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic PUT endpoint', (done) ->
@context.url = '/basic/put'
@context.method = 'put'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic POST endpoint', (done) ->
@context.url = '/basic/post'
@context.method = 'post'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic DELETE endpoint', (done) ->
@context.url = '/basic/delete'
@context.method = 'delete'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a basic HEAD endpoint', (done) ->
@context.url = '/basic/head'
@context.method = 'head'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return a response for an endpoint with multiple methods', (done) ->
@context.url = '/basic/all'
@context.method = 'delete'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint delete to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'get'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint get to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'put'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint put to finish', 1000, =>
assert @context.response.statusCode is 200
@context =
port: port
finished: false
url: "/basic/all"
method: 'post'
createRequest @context
waitsFor ( => @context.done ), 'all endpoint post to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return the CORS headers', (done) ->
expected = 'http://example.org'
@context.url = '/basic/get'
@context.method = 'get'
@context.requestHeaders =
'origin': expected
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
headers = @context.response.headers
assert headers['access-control-allow-origin'] is expected
assert headers['access-control-allow-credentials'] is 'true'
done()
it 'should return multiple headers with the same name', (done) ->
expected = ['type=ninja', 'language=coffeescript']
@context.url = '/duplicated/header'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
headers = @context.response.headers
assert.deepEqual headers['set-cookie'], expected
done()
describe 'GET', ->
it 'should return a body from a GET endpoint', (done) ->
@context.url = '/get/body'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.data is 'plain text'
done()
it 'should return a body from a json GET endpoint', (done) ->
@context.url = '/get/json'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.data.trim() is '{"property":"value"}'
assert @context.response.headers['content-type'] is 'application/json'
done()
it 'should return a 420 GET endpoint', (done) ->
@context.url = '/get/420'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 420
done()
it 'should be able to handle query params', (done) ->
@context.url = '/get/query'
@context.query =
first: 'value1 with spaces!'
second: 'value2'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should return 404 if query params are not matched', (done) ->
@context.url = '/get/query'
@context.query =
first: 'invalid value'
second: 'value2'
@context.method = 'get'
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 404
done()
describe 'post', ->
it 'should be able to handle authorized posts', (done) ->
@context.url = '/post/auth'
@context.method = 'post'
@context.post = 'some=data'
@context.requestHeaders =
authorization: "Basic PI:KEY:<KEY>END_PI"
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 201
assert @context.response.headers.location is '/some/endpoint/id'
assert @context.response.data is 'resource has been created'
done()
it 'should be able to handle authorized posts where the yaml wasnt pre-encoded', (done) ->
@context.url = '/post/auth/pair'
@context.method = 'post'
@context.post = 'some=data'
@context.requestHeaders =
authorization: "Basic PI:KEY:<KEY>END_PI"
createRequest @context
waitsFor ( => @context.done ), 'request to finish', 1000, =>
assert @context.response.statusCode is 201
assert @context.response.headers.location is '/some/endpoint/id'
assert @context.response.data is 'resource has been created'
done()
describe 'put', ->
it 'should wait if a 2000ms latency is specified', (done) ->
@timeout 3500
@context.url = '/put/latency'
@context.method = 'put'
createRequest @context
waitsFor ( => @context.done ), 'latency-ridden request to finish', [2000, 3000], =>
assert @context.response.data is 'updated'
done()
describe 'file use', ->
describe 'response', ->
it 'should handle fallback to body if specified response file cannot be found', (done) ->
@context.url = '/file/body/missingfile'
createRequest @context
waitsFor ( => @context.done ), 'body-fallback request to finish', 1000, =>
assert @context.response.data is 'body contents!'
done()
it 'should handle file response when file can be found', (done) ->
@context.url = '/file/body'
createRequest @context
waitsFor ( => @context.done ), 'body-fallback request to finish', 1000, =>
assert @context.response.data.trim() is 'file contents!'
done()
describe 'request', ->
it 'should handle fallback to post if specified request file cannot be found', (done) ->
@context.url = '/file/post/missingfile'
@context.method = 'post'
@context.post = 'post contents!'
createRequest @context
waitsFor ( => @context.done ), 'post-fallback request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
it 'should handle file request when file can be found', (done) ->
@context.url = '/file/post'
@context.method = 'post'
@context.post = 'file contents!'
createRequest @context
waitsFor ( => @context.done ), 'post-fallback request to finish', 1000, =>
assert @context.response.statusCode is 200
done()
|
[
{
"context": "reEach ->\n SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'\n ",
"end": 1210,
"score": 0.5208483338356018,
"start": 1210,
"tag": "EMAIL",
"value": ""
},
{
"context": "ch ->\n SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'\n Set",
"end": 1214,
"score": 0.5440700054168701,
"start": 1214,
"tag": "EMAIL",
"value": ""
}
] | spec/cloud-variables-view-spec.coffee | particle-iot/particle-dev-cloud-variables | 0 | {$} = require 'atom-space-pen-views'
SparkStub = require('particle-dev-spec-stubs').spark
CloudVariablesView = require '../lib/cloud-variables-view'
spark = require 'spark'
SettingsHelper = null
describe 'Cloud Variables View', ->
activationPromise = null
originalProfile = null
particleDev = null
cloudVariables = null
cloudVariablesView = null
workspaceElement = null
beforeEach ->
workspaceElement = atom.views.getView(atom.workspace)
activationPromise = atom.packages.activatePackage('particle-dev-cloud-variables').then ({mainModule}) ->
cloudVariables = mainModule
particleDevPromise = atom.packages.activatePackage('particle-dev').then ({mainModule}) ->
particleDev = mainModule
SettingsHelper = particleDev.SettingsHelper
waitsForPromise ->
activationPromise
waitsForPromise ->
particleDevPromise
runs ->
originalProfile = SettingsHelper.getProfile()
# For tests not to mess up our profile, we have to switch to test one...
SettingsHelper.setProfile 'particle-dev-test'
afterEach ->
SettingsHelper.setProfile originalProfile
describe '', ->
beforeEach ->
SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'
SettingsHelper.setCurrentCore '0123456789abcdef0123456789abcdef', 'Foo'
SettingsHelper.setLocal 'variables', {foo: 'int32'}
afterEach ->
SettingsHelper.clearCurrentCore()
SettingsHelper.clearCredentials()
SettingsHelper.setLocal 'variables', {}
it 'checks listing variables', ->
SparkStub.stubNoResolve spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
spyOn cloudVariablesView, 'refreshVariable'
SparkStub.stubSuccess spark, 'getVariable'
body = cloudVariablesView.find('#particle-dev-cloud-variables')
expect(body.find('table')).toExist()
expect(body.find('table > thead')).toExist()
expect(body.find('table > thead > tr')).toExist()
expect(body.find('table > thead > tr > th:eq(0)').text()).toEqual('Name')
expect(body.find('table > thead > tr > th:eq(1)').text()).toEqual('Type')
expect(body.find('table > thead > tr > th:eq(2)').text()).toEqual('Value')
expect(body.find('table > thead > tr > th:eq(3)').text()).toEqual('Refresh')
expect(body.find('table > tbody')).toExist()
expect(body.find('table > tbody > tr')).toExist()
expect(body.find('table > tbody > tr').length).toEqual(1)
expect(body.find('table > tbody > tr:eq(0) > td:eq(0)').text()).toEqual('foo')
expect(body.find('table > tbody > tr:eq(0) > td:eq(1)').text()).toEqual('int32')
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').text()).toEqual('')
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').hasClass('loading')).toBe(true)
expect(body.find('table > tbody > tr:eq(0) > td:eq(3) > button')).toExist()
expect(body.find('table > tbody > tr:eq(0) > td:eq(3) > button').hasClass('icon-sync')).toBe(true)
expect(body.find('table > tbody > tr:eq(0) > td:eq(4) > button')).toExist()
expect(body.find('table > tbody > tr:eq(0) > td:eq(4) > button').hasClass('icon-eye')).toBe(true)
# Test refresh button
body.find('table > tbody > tr:eq(0) > td:eq(3) > button').click()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalled()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalledWith('foo')
jasmine.unspy cloudVariablesView, 'refreshVariable'
it 'tests refreshing', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
body = cloudVariablesView.find('#particle-dev-cloud-variables')
waitsFor ->
body.find('table > tbody > tr:eq(0) > td:eq(2)').text() == '1'
runs ->
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').hasClass('loading')).toBe(false)
it 'checks event hooks', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
# Tests particle-dev:update-core-status
spyOn cloudVariablesView, 'listVariables'
spyOn cloudVariablesView, 'clearWatchers'
atom.commands.dispatch workspaceElement, 'particle-dev:core-status-updated'
expect(cloudVariablesView.listVariables).toHaveBeenCalled()
expect(cloudVariablesView.clearWatchers).toHaveBeenCalled()
jasmine.unspy cloudVariablesView, 'listVariables'
jasmine.unspy cloudVariablesView, 'clearWatchers'
# Tests particle-dev:logout
SettingsHelper.clearCredentials()
spyOn cloudVariablesView, 'close'
spyOn cloudVariablesView, 'clearWatchers'
atom.commands.dispatch workspaceElement, 'particle-dev:logout'
expect(cloudVariablesView.close).toHaveBeenCalled()
expect(cloudVariablesView.clearWatchers).toHaveBeenCalled()
jasmine.unspy cloudVariablesView, 'close'
jasmine.unspy cloudVariablesView, 'clearWatchers'
it 'check watching variable', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
row = cloudVariablesView.find('#particle-dev-cloud-variables table > tbody > tr:eq(0)')
watchButton = row.find('td:eq(4) > button')
refreshButton = row.find('td:eq(3) > button')
expect(refreshButton.attr('disabled')).not.toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(false)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
jasmine.Clock.useMock()
spyOn cloudVariablesView, 'refreshVariable'
watchButton.click()
expect(refreshButton.attr('disabled')).toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(true)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(1)
expect(Object.keys(cloudVariablesView.watchers)).toEqual(['foo'])
expect(cloudVariablesView.refreshVariable).not.toHaveBeenCalled()
watcher = cloudVariablesView.watchers['foo']
jasmine.Clock.tick(5001)
expect(cloudVariablesView.refreshVariable).toHaveBeenCalled()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalledWith('foo')
spyOn window, 'clearInterval'
expect(window.clearInterval).not.toHaveBeenCalled()
watchButton.click()
expect(refreshButton.attr('disabled')).not.toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(false)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
expect(window.clearInterval).toHaveBeenCalled()
expect(window.clearInterval).toHaveBeenCalledWith(watcher)
# TODO: Test clearing all watchers
jasmine.unspy window, 'clearInterval'
jasmine.unspy cloudVariablesView, 'refreshVariable'
it 'checks clearing watchers', ->
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
cloudVariablesView.watchers['foo'] = 'bar'
spyOn window, 'clearInterval'
expect(window.clearInterval).not.toHaveBeenCalled()
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(1)
cloudVariablesView.clearWatchers()
expect(window.clearInterval).toHaveBeenCalled()
expect(window.clearInterval).toHaveBeenCalledWith('bar')
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
jasmine.unspy window, 'clearInterval'
| 88544 | {$} = require 'atom-space-pen-views'
SparkStub = require('particle-dev-spec-stubs').spark
CloudVariablesView = require '../lib/cloud-variables-view'
spark = require 'spark'
SettingsHelper = null
describe 'Cloud Variables View', ->
activationPromise = null
originalProfile = null
particleDev = null
cloudVariables = null
cloudVariablesView = null
workspaceElement = null
beforeEach ->
workspaceElement = atom.views.getView(atom.workspace)
activationPromise = atom.packages.activatePackage('particle-dev-cloud-variables').then ({mainModule}) ->
cloudVariables = mainModule
particleDevPromise = atom.packages.activatePackage('particle-dev').then ({mainModule}) ->
particleDev = mainModule
SettingsHelper = particleDev.SettingsHelper
waitsForPromise ->
activationPromise
waitsForPromise ->
particleDevPromise
runs ->
originalProfile = SettingsHelper.getProfile()
# For tests not to mess up our profile, we have to switch to test one...
SettingsHelper.setProfile 'particle-dev-test'
afterEach ->
SettingsHelper.setProfile originalProfile
describe '', ->
beforeEach ->
SettingsHelper.setCredentials 'foo<EMAIL>@bar<EMAIL>.baz', '0123456789abcdef0123456789abcdef'
SettingsHelper.setCurrentCore '0123456789abcdef0123456789abcdef', 'Foo'
SettingsHelper.setLocal 'variables', {foo: 'int32'}
afterEach ->
SettingsHelper.clearCurrentCore()
SettingsHelper.clearCredentials()
SettingsHelper.setLocal 'variables', {}
it 'checks listing variables', ->
SparkStub.stubNoResolve spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
spyOn cloudVariablesView, 'refreshVariable'
SparkStub.stubSuccess spark, 'getVariable'
body = cloudVariablesView.find('#particle-dev-cloud-variables')
expect(body.find('table')).toExist()
expect(body.find('table > thead')).toExist()
expect(body.find('table > thead > tr')).toExist()
expect(body.find('table > thead > tr > th:eq(0)').text()).toEqual('Name')
expect(body.find('table > thead > tr > th:eq(1)').text()).toEqual('Type')
expect(body.find('table > thead > tr > th:eq(2)').text()).toEqual('Value')
expect(body.find('table > thead > tr > th:eq(3)').text()).toEqual('Refresh')
expect(body.find('table > tbody')).toExist()
expect(body.find('table > tbody > tr')).toExist()
expect(body.find('table > tbody > tr').length).toEqual(1)
expect(body.find('table > tbody > tr:eq(0) > td:eq(0)').text()).toEqual('foo')
expect(body.find('table > tbody > tr:eq(0) > td:eq(1)').text()).toEqual('int32')
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').text()).toEqual('')
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').hasClass('loading')).toBe(true)
expect(body.find('table > tbody > tr:eq(0) > td:eq(3) > button')).toExist()
expect(body.find('table > tbody > tr:eq(0) > td:eq(3) > button').hasClass('icon-sync')).toBe(true)
expect(body.find('table > tbody > tr:eq(0) > td:eq(4) > button')).toExist()
expect(body.find('table > tbody > tr:eq(0) > td:eq(4) > button').hasClass('icon-eye')).toBe(true)
# Test refresh button
body.find('table > tbody > tr:eq(0) > td:eq(3) > button').click()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalled()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalledWith('foo')
jasmine.unspy cloudVariablesView, 'refreshVariable'
it 'tests refreshing', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
body = cloudVariablesView.find('#particle-dev-cloud-variables')
waitsFor ->
body.find('table > tbody > tr:eq(0) > td:eq(2)').text() == '1'
runs ->
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').hasClass('loading')).toBe(false)
it 'checks event hooks', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
# Tests particle-dev:update-core-status
spyOn cloudVariablesView, 'listVariables'
spyOn cloudVariablesView, 'clearWatchers'
atom.commands.dispatch workspaceElement, 'particle-dev:core-status-updated'
expect(cloudVariablesView.listVariables).toHaveBeenCalled()
expect(cloudVariablesView.clearWatchers).toHaveBeenCalled()
jasmine.unspy cloudVariablesView, 'listVariables'
jasmine.unspy cloudVariablesView, 'clearWatchers'
# Tests particle-dev:logout
SettingsHelper.clearCredentials()
spyOn cloudVariablesView, 'close'
spyOn cloudVariablesView, 'clearWatchers'
atom.commands.dispatch workspaceElement, 'particle-dev:logout'
expect(cloudVariablesView.close).toHaveBeenCalled()
expect(cloudVariablesView.clearWatchers).toHaveBeenCalled()
jasmine.unspy cloudVariablesView, 'close'
jasmine.unspy cloudVariablesView, 'clearWatchers'
it 'check watching variable', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
row = cloudVariablesView.find('#particle-dev-cloud-variables table > tbody > tr:eq(0)')
watchButton = row.find('td:eq(4) > button')
refreshButton = row.find('td:eq(3) > button')
expect(refreshButton.attr('disabled')).not.toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(false)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
jasmine.Clock.useMock()
spyOn cloudVariablesView, 'refreshVariable'
watchButton.click()
expect(refreshButton.attr('disabled')).toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(true)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(1)
expect(Object.keys(cloudVariablesView.watchers)).toEqual(['foo'])
expect(cloudVariablesView.refreshVariable).not.toHaveBeenCalled()
watcher = cloudVariablesView.watchers['foo']
jasmine.Clock.tick(5001)
expect(cloudVariablesView.refreshVariable).toHaveBeenCalled()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalledWith('foo')
spyOn window, 'clearInterval'
expect(window.clearInterval).not.toHaveBeenCalled()
watchButton.click()
expect(refreshButton.attr('disabled')).not.toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(false)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
expect(window.clearInterval).toHaveBeenCalled()
expect(window.clearInterval).toHaveBeenCalledWith(watcher)
# TODO: Test clearing all watchers
jasmine.unspy window, 'clearInterval'
jasmine.unspy cloudVariablesView, 'refreshVariable'
it 'checks clearing watchers', ->
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
cloudVariablesView.watchers['foo'] = 'bar'
spyOn window, 'clearInterval'
expect(window.clearInterval).not.toHaveBeenCalled()
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(1)
cloudVariablesView.clearWatchers()
expect(window.clearInterval).toHaveBeenCalled()
expect(window.clearInterval).toHaveBeenCalledWith('bar')
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
jasmine.unspy window, 'clearInterval'
| true | {$} = require 'atom-space-pen-views'
SparkStub = require('particle-dev-spec-stubs').spark
CloudVariablesView = require '../lib/cloud-variables-view'
spark = require 'spark'
SettingsHelper = null
describe 'Cloud Variables View', ->
activationPromise = null
originalProfile = null
particleDev = null
cloudVariables = null
cloudVariablesView = null
workspaceElement = null
beforeEach ->
workspaceElement = atom.views.getView(atom.workspace)
activationPromise = atom.packages.activatePackage('particle-dev-cloud-variables').then ({mainModule}) ->
cloudVariables = mainModule
particleDevPromise = atom.packages.activatePackage('particle-dev').then ({mainModule}) ->
particleDev = mainModule
SettingsHelper = particleDev.SettingsHelper
waitsForPromise ->
activationPromise
waitsForPromise ->
particleDevPromise
runs ->
originalProfile = SettingsHelper.getProfile()
# For tests not to mess up our profile, we have to switch to test one...
SettingsHelper.setProfile 'particle-dev-test'
afterEach ->
SettingsHelper.setProfile originalProfile
describe '', ->
beforeEach ->
SettingsHelper.setCredentials 'fooPI:EMAIL:<EMAIL>END_PI@barPI:EMAIL:<EMAIL>END_PI.baz', '0123456789abcdef0123456789abcdef'
SettingsHelper.setCurrentCore '0123456789abcdef0123456789abcdef', 'Foo'
SettingsHelper.setLocal 'variables', {foo: 'int32'}
afterEach ->
SettingsHelper.clearCurrentCore()
SettingsHelper.clearCredentials()
SettingsHelper.setLocal 'variables', {}
it 'checks listing variables', ->
SparkStub.stubNoResolve spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
spyOn cloudVariablesView, 'refreshVariable'
SparkStub.stubSuccess spark, 'getVariable'
body = cloudVariablesView.find('#particle-dev-cloud-variables')
expect(body.find('table')).toExist()
expect(body.find('table > thead')).toExist()
expect(body.find('table > thead > tr')).toExist()
expect(body.find('table > thead > tr > th:eq(0)').text()).toEqual('Name')
expect(body.find('table > thead > tr > th:eq(1)').text()).toEqual('Type')
expect(body.find('table > thead > tr > th:eq(2)').text()).toEqual('Value')
expect(body.find('table > thead > tr > th:eq(3)').text()).toEqual('Refresh')
expect(body.find('table > tbody')).toExist()
expect(body.find('table > tbody > tr')).toExist()
expect(body.find('table > tbody > tr').length).toEqual(1)
expect(body.find('table > tbody > tr:eq(0) > td:eq(0)').text()).toEqual('foo')
expect(body.find('table > tbody > tr:eq(0) > td:eq(1)').text()).toEqual('int32')
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').text()).toEqual('')
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').hasClass('loading')).toBe(true)
expect(body.find('table > tbody > tr:eq(0) > td:eq(3) > button')).toExist()
expect(body.find('table > tbody > tr:eq(0) > td:eq(3) > button').hasClass('icon-sync')).toBe(true)
expect(body.find('table > tbody > tr:eq(0) > td:eq(4) > button')).toExist()
expect(body.find('table > tbody > tr:eq(0) > td:eq(4) > button').hasClass('icon-eye')).toBe(true)
# Test refresh button
body.find('table > tbody > tr:eq(0) > td:eq(3) > button').click()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalled()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalledWith('foo')
jasmine.unspy cloudVariablesView, 'refreshVariable'
it 'tests refreshing', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
body = cloudVariablesView.find('#particle-dev-cloud-variables')
waitsFor ->
body.find('table > tbody > tr:eq(0) > td:eq(2)').text() == '1'
runs ->
expect(body.find('table > tbody > tr:eq(0) > td:eq(2)').hasClass('loading')).toBe(false)
it 'checks event hooks', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
# Tests particle-dev:update-core-status
spyOn cloudVariablesView, 'listVariables'
spyOn cloudVariablesView, 'clearWatchers'
atom.commands.dispatch workspaceElement, 'particle-dev:core-status-updated'
expect(cloudVariablesView.listVariables).toHaveBeenCalled()
expect(cloudVariablesView.clearWatchers).toHaveBeenCalled()
jasmine.unspy cloudVariablesView, 'listVariables'
jasmine.unspy cloudVariablesView, 'clearWatchers'
# Tests particle-dev:logout
SettingsHelper.clearCredentials()
spyOn cloudVariablesView, 'close'
spyOn cloudVariablesView, 'clearWatchers'
atom.commands.dispatch workspaceElement, 'particle-dev:logout'
expect(cloudVariablesView.close).toHaveBeenCalled()
expect(cloudVariablesView.clearWatchers).toHaveBeenCalled()
jasmine.unspy cloudVariablesView, 'close'
jasmine.unspy cloudVariablesView, 'clearWatchers'
it 'check watching variable', ->
SparkStub.stubSuccess spark, 'getVariable'
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
row = cloudVariablesView.find('#particle-dev-cloud-variables table > tbody > tr:eq(0)')
watchButton = row.find('td:eq(4) > button')
refreshButton = row.find('td:eq(3) > button')
expect(refreshButton.attr('disabled')).not.toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(false)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
jasmine.Clock.useMock()
spyOn cloudVariablesView, 'refreshVariable'
watchButton.click()
expect(refreshButton.attr('disabled')).toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(true)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(1)
expect(Object.keys(cloudVariablesView.watchers)).toEqual(['foo'])
expect(cloudVariablesView.refreshVariable).not.toHaveBeenCalled()
watcher = cloudVariablesView.watchers['foo']
jasmine.Clock.tick(5001)
expect(cloudVariablesView.refreshVariable).toHaveBeenCalled()
expect(cloudVariablesView.refreshVariable).toHaveBeenCalledWith('foo')
spyOn window, 'clearInterval'
expect(window.clearInterval).not.toHaveBeenCalled()
watchButton.click()
expect(refreshButton.attr('disabled')).not.toEqual('disabled')
expect(watchButton.hasClass('selected')).toBe(false)
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
expect(window.clearInterval).toHaveBeenCalled()
expect(window.clearInterval).toHaveBeenCalledWith(watcher)
# TODO: Test clearing all watchers
jasmine.unspy window, 'clearInterval'
jasmine.unspy cloudVariablesView, 'refreshVariable'
it 'checks clearing watchers', ->
cloudVariablesView = new CloudVariablesView(null, particleDev)
cloudVariablesView.setup()
cloudVariablesView.watchers['foo'] = 'bar'
spyOn window, 'clearInterval'
expect(window.clearInterval).not.toHaveBeenCalled()
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(1)
cloudVariablesView.clearWatchers()
expect(window.clearInterval).toHaveBeenCalled()
expect(window.clearInterval).toHaveBeenCalledWith('bar')
expect(Object.keys(cloudVariablesView.watchers).length).toEqual(0)
jasmine.unspy window, 'clearInterval'
|
[
{
"context": "Role = ef.createJournalRole journal,\n name: \"Admin\"\n kind: \"admin\"\n can_administer_journal",
"end": 293,
"score": 0.6374794244766235,
"start": 288,
"tag": "NAME",
"value": "Admin"
}
] | test/javascripts/integration/flow_manager_admin_test.js.coffee | johan--/tahi | 1 | module 'Integration: Flow Manager Administration',
teardown: -> ETahi.reset()
setup: ->
setupApp integration: true
ef = ETahi.Factory
journal = ef.createRecord('AdminJournal')
TahiTest.journalId = journal.id
adminRole = ef.createJournalRole journal,
name: "Admin"
kind: "admin"
can_administer_journal: true
can_view_assigned_manuscript_managers: false
can_view_all_manuscript_managers: true
can_view_flow_manager: false
adminJournalPayload = ef.createPayload('adminJournal')
adminJournalPayload.addRecords([journal, adminRole])
server.respondWith 'GET', "/admin/journals/#{TahiTest.journalId}", [
200, "Content-Type": "application/json", JSON.stringify adminJournalPayload.toJSON()
]
server.respondWith 'GET', "/admin/journals/authorization", [
204, "Content-Type": "application/html", ""
]
server.respondWith 'GET', '/user_flows/authorization', [
204, 'content-type': 'application/html', 'tahi-authorization-check': true, ""
]
server.respondWith 'GET', "/admin/journal_users?journal_id=#{TahiTest.journalId}", [
200, "Content-Type": "application/json", JSON.stringify { admin_journal_users: [] }
]
test 'Flow manager edit link should show up on a role with permission in edit mode', ->
visit "/admin/journals/#{TahiTest.journalId}"
click('.admin-role-action-button')
andThen ->
ok !exists('a:contains("Edit Flows")'), "No flow manager link should show up without permission"
click('input[name="role[canViewFlowManager]"]')
andThen ->
ok exists('a:contains("Edit Flows")')
| 127900 | module 'Integration: Flow Manager Administration',
teardown: -> ETahi.reset()
setup: ->
setupApp integration: true
ef = ETahi.Factory
journal = ef.createRecord('AdminJournal')
TahiTest.journalId = journal.id
adminRole = ef.createJournalRole journal,
name: "<NAME>"
kind: "admin"
can_administer_journal: true
can_view_assigned_manuscript_managers: false
can_view_all_manuscript_managers: true
can_view_flow_manager: false
adminJournalPayload = ef.createPayload('adminJournal')
adminJournalPayload.addRecords([journal, adminRole])
server.respondWith 'GET', "/admin/journals/#{TahiTest.journalId}", [
200, "Content-Type": "application/json", JSON.stringify adminJournalPayload.toJSON()
]
server.respondWith 'GET', "/admin/journals/authorization", [
204, "Content-Type": "application/html", ""
]
server.respondWith 'GET', '/user_flows/authorization', [
204, 'content-type': 'application/html', 'tahi-authorization-check': true, ""
]
server.respondWith 'GET', "/admin/journal_users?journal_id=#{TahiTest.journalId}", [
200, "Content-Type": "application/json", JSON.stringify { admin_journal_users: [] }
]
test 'Flow manager edit link should show up on a role with permission in edit mode', ->
visit "/admin/journals/#{TahiTest.journalId}"
click('.admin-role-action-button')
andThen ->
ok !exists('a:contains("Edit Flows")'), "No flow manager link should show up without permission"
click('input[name="role[canViewFlowManager]"]')
andThen ->
ok exists('a:contains("Edit Flows")')
| true | module 'Integration: Flow Manager Administration',
teardown: -> ETahi.reset()
setup: ->
setupApp integration: true
ef = ETahi.Factory
journal = ef.createRecord('AdminJournal')
TahiTest.journalId = journal.id
adminRole = ef.createJournalRole journal,
name: "PI:NAME:<NAME>END_PI"
kind: "admin"
can_administer_journal: true
can_view_assigned_manuscript_managers: false
can_view_all_manuscript_managers: true
can_view_flow_manager: false
adminJournalPayload = ef.createPayload('adminJournal')
adminJournalPayload.addRecords([journal, adminRole])
server.respondWith 'GET', "/admin/journals/#{TahiTest.journalId}", [
200, "Content-Type": "application/json", JSON.stringify adminJournalPayload.toJSON()
]
server.respondWith 'GET', "/admin/journals/authorization", [
204, "Content-Type": "application/html", ""
]
server.respondWith 'GET', '/user_flows/authorization', [
204, 'content-type': 'application/html', 'tahi-authorization-check': true, ""
]
server.respondWith 'GET', "/admin/journal_users?journal_id=#{TahiTest.journalId}", [
200, "Content-Type": "application/json", JSON.stringify { admin_journal_users: [] }
]
test 'Flow manager edit link should show up on a role with permission in edit mode', ->
visit "/admin/journals/#{TahiTest.journalId}"
click('.admin-role-action-button')
andThen ->
ok !exists('a:contains("Edit Flows")'), "No flow manager link should show up without permission"
click('input[name="role[canViewFlowManager]"]')
andThen ->
ok exists('a:contains("Edit Flows")')
|
[
{
"context": " 'credentials')\n\n serviceReady: false\n userId: 'melis-user'\n\n setup: ( ->\n Logger.debug '[fpa] service s",
"end": 986,
"score": 0.9931619763374329,
"start": 976,
"tag": "USERNAME",
"value": "melis-user"
},
{
"context": " clientId: CLIENTID\n username: @get('userId')\n password: pin\n\n success = (result)",
"end": 2458,
"score": 0.9787178039550781,
"start": 2452,
"tag": "USERNAME",
"value": "userId"
},
{
"context": " username: @get('userId')\n password: pin\n\n success = (result) =>\n Logger.debug",
"end": 2482,
"score": 0.8314092755317688,
"start": 2479,
"tag": "PASSWORD",
"value": "pin"
},
{
"context": " clientId: CLIENTID\n username: @get('userId')\n token: token\n\n success = (result) ",
"end": 3180,
"score": 0.9852975606918335,
"start": 3174,
"tag": "USERNAME",
"value": "userId"
}
] | app/services/fingerprint-auth.coffee | melis-wallet/melis-cm-client | 1 | import Service, { inject as service } from '@ember/service'
import Evented from '@ember/object/evented'
import { alias } from '@ember/object/computed'
import { isBlank } from '@ember/utils'
import { get, set } from '@ember/object'
import RSVP from 'rsvp'
import subscribe from 'ember-cordova-events/utils/subscribe'
import { storageFor } from 'ember-local-storage'
import Logger from 'melis-cm-svcs/utils/logger'
CLIENTID = 'melis-cm-wallet'
FingerPrint = Service.extend(Evented,
cordova: service('ember-cordova/events')
platform: service('ember-cordova/platform')
cm: service('cm-session')
isAvailable: false
isHardwareDetected: false
hasEnrolledFingerprints: false
isSupported: alias('isAvailable')
walletstate: storageFor('wallet-state')
credentials: alias('walletstate.touchCreds')
successfullyEnrolled: ( ->
@get('isAvailable') && !isBlank(@get('credentials'))
).property('isAvailable', 'credentials')
serviceReady: false
userId: 'melis-user'
setup: ( ->
Logger.debug '[fpa] service started'
).on('init')
ready: subscribe('cordova.deviceready', ->
return unless @get('platform.isAndroid')
FingerprintAuth.isAvailable(( (result) =>
if result.isAvailable
Logger.debug('[fpa] fingerprint is available')
@setProperties(result)
if !@get('serviceReady')
@set('serviceReady', true)
@trigger('service-ready')
else
Logger.debug('[fpa] fingerprint is not available')
), ((error) ->
Logger.error('[fpa] fingerprint check error', error)
))
)
disable: ->
return if !@get('successfullyEnrolled') || isBlank(token = @get('credentials'))
new RSVP.Promise((resolve, reject) =>
Logger.debug "[fpa] deleting"
resolve() unless @get('isSupported')
info =
clientId: CLIENTID
username: @get('userId')
token: token
success = (result) =>
Logger.debug('[fpa] fingerprint delete SUCCESS', result)
resolve(result)
error = (error) =>
Logger.error('[fpa] fingerprint delete error', error)
reject(error)
@set('credentials', null)
FingerprintAuth.delete(info, success, error)
)
enroll: (pin) ->
new RSVP.Promise((resolve, reject) =>
Logger.debug "[fps] enrolling"
resolve() unless @get('isSupported')
enroll =
disableBackup: true
clientId: CLIENTID
username: @get('userId')
password: pin
success = (result) =>
Logger.debug('[fpa] fingerprint enroll SUCCESS', result)
if result && (token = get(result, 'token'))
@set('credentials', token)
resolve(result)
else
reject('no token')
error = (error) =>
Logger.error('[fpa] fingerprint enroll error', error)
reject(error)
FingerprintAuth.encrypt(enroll, success, error)
)
login: ->
return if !@get('successfullyEnrolled') || isBlank(token = @get('credentials'))
new RSVP.Promise((resolve, reject) =>
login =
disableBackup: true
language: @get('cm.locale')
clientId: CLIENTID
username: @get('userId')
token: token
success = (result) =>
Logger.debug('[fpa] fingerprint login SUCCESS', result)
if result && (password = get(result, 'password'))
result.pin ||= result.password
resolve(result)
else
reject('no password')
error = (error) =>
Logger.error('[fpa] fingerprint login error', error)
reject(error)
FingerprintAuth.decrypt(login, success, error)
)
)
export default FingerPrint
| 33834 | import Service, { inject as service } from '@ember/service'
import Evented from '@ember/object/evented'
import { alias } from '@ember/object/computed'
import { isBlank } from '@ember/utils'
import { get, set } from '@ember/object'
import RSVP from 'rsvp'
import subscribe from 'ember-cordova-events/utils/subscribe'
import { storageFor } from 'ember-local-storage'
import Logger from 'melis-cm-svcs/utils/logger'
CLIENTID = 'melis-cm-wallet'
FingerPrint = Service.extend(Evented,
cordova: service('ember-cordova/events')
platform: service('ember-cordova/platform')
cm: service('cm-session')
isAvailable: false
isHardwareDetected: false
hasEnrolledFingerprints: false
isSupported: alias('isAvailable')
walletstate: storageFor('wallet-state')
credentials: alias('walletstate.touchCreds')
successfullyEnrolled: ( ->
@get('isAvailable') && !isBlank(@get('credentials'))
).property('isAvailable', 'credentials')
serviceReady: false
userId: 'melis-user'
setup: ( ->
Logger.debug '[fpa] service started'
).on('init')
ready: subscribe('cordova.deviceready', ->
return unless @get('platform.isAndroid')
FingerprintAuth.isAvailable(( (result) =>
if result.isAvailable
Logger.debug('[fpa] fingerprint is available')
@setProperties(result)
if !@get('serviceReady')
@set('serviceReady', true)
@trigger('service-ready')
else
Logger.debug('[fpa] fingerprint is not available')
), ((error) ->
Logger.error('[fpa] fingerprint check error', error)
))
)
disable: ->
return if !@get('successfullyEnrolled') || isBlank(token = @get('credentials'))
new RSVP.Promise((resolve, reject) =>
Logger.debug "[fpa] deleting"
resolve() unless @get('isSupported')
info =
clientId: CLIENTID
username: @get('userId')
token: token
success = (result) =>
Logger.debug('[fpa] fingerprint delete SUCCESS', result)
resolve(result)
error = (error) =>
Logger.error('[fpa] fingerprint delete error', error)
reject(error)
@set('credentials', null)
FingerprintAuth.delete(info, success, error)
)
enroll: (pin) ->
new RSVP.Promise((resolve, reject) =>
Logger.debug "[fps] enrolling"
resolve() unless @get('isSupported')
enroll =
disableBackup: true
clientId: CLIENTID
username: @get('userId')
password: <PASSWORD>
success = (result) =>
Logger.debug('[fpa] fingerprint enroll SUCCESS', result)
if result && (token = get(result, 'token'))
@set('credentials', token)
resolve(result)
else
reject('no token')
error = (error) =>
Logger.error('[fpa] fingerprint enroll error', error)
reject(error)
FingerprintAuth.encrypt(enroll, success, error)
)
login: ->
return if !@get('successfullyEnrolled') || isBlank(token = @get('credentials'))
new RSVP.Promise((resolve, reject) =>
login =
disableBackup: true
language: @get('cm.locale')
clientId: CLIENTID
username: @get('userId')
token: token
success = (result) =>
Logger.debug('[fpa] fingerprint login SUCCESS', result)
if result && (password = get(result, 'password'))
result.pin ||= result.password
resolve(result)
else
reject('no password')
error = (error) =>
Logger.error('[fpa] fingerprint login error', error)
reject(error)
FingerprintAuth.decrypt(login, success, error)
)
)
export default FingerPrint
| true | import Service, { inject as service } from '@ember/service'
import Evented from '@ember/object/evented'
import { alias } from '@ember/object/computed'
import { isBlank } from '@ember/utils'
import { get, set } from '@ember/object'
import RSVP from 'rsvp'
import subscribe from 'ember-cordova-events/utils/subscribe'
import { storageFor } from 'ember-local-storage'
import Logger from 'melis-cm-svcs/utils/logger'
CLIENTID = 'melis-cm-wallet'
FingerPrint = Service.extend(Evented,
cordova: service('ember-cordova/events')
platform: service('ember-cordova/platform')
cm: service('cm-session')
isAvailable: false
isHardwareDetected: false
hasEnrolledFingerprints: false
isSupported: alias('isAvailable')
walletstate: storageFor('wallet-state')
credentials: alias('walletstate.touchCreds')
successfullyEnrolled: ( ->
@get('isAvailable') && !isBlank(@get('credentials'))
).property('isAvailable', 'credentials')
serviceReady: false
userId: 'melis-user'
setup: ( ->
Logger.debug '[fpa] service started'
).on('init')
ready: subscribe('cordova.deviceready', ->
return unless @get('platform.isAndroid')
FingerprintAuth.isAvailable(( (result) =>
if result.isAvailable
Logger.debug('[fpa] fingerprint is available')
@setProperties(result)
if !@get('serviceReady')
@set('serviceReady', true)
@trigger('service-ready')
else
Logger.debug('[fpa] fingerprint is not available')
), ((error) ->
Logger.error('[fpa] fingerprint check error', error)
))
)
disable: ->
return if !@get('successfullyEnrolled') || isBlank(token = @get('credentials'))
new RSVP.Promise((resolve, reject) =>
Logger.debug "[fpa] deleting"
resolve() unless @get('isSupported')
info =
clientId: CLIENTID
username: @get('userId')
token: token
success = (result) =>
Logger.debug('[fpa] fingerprint delete SUCCESS', result)
resolve(result)
error = (error) =>
Logger.error('[fpa] fingerprint delete error', error)
reject(error)
@set('credentials', null)
FingerprintAuth.delete(info, success, error)
)
enroll: (pin) ->
new RSVP.Promise((resolve, reject) =>
Logger.debug "[fps] enrolling"
resolve() unless @get('isSupported')
enroll =
disableBackup: true
clientId: CLIENTID
username: @get('userId')
password: PI:PASSWORD:<PASSWORD>END_PI
success = (result) =>
Logger.debug('[fpa] fingerprint enroll SUCCESS', result)
if result && (token = get(result, 'token'))
@set('credentials', token)
resolve(result)
else
reject('no token')
error = (error) =>
Logger.error('[fpa] fingerprint enroll error', error)
reject(error)
FingerprintAuth.encrypt(enroll, success, error)
)
login: ->
return if !@get('successfullyEnrolled') || isBlank(token = @get('credentials'))
new RSVP.Promise((resolve, reject) =>
login =
disableBackup: true
language: @get('cm.locale')
clientId: CLIENTID
username: @get('userId')
token: token
success = (result) =>
Logger.debug('[fpa] fingerprint login SUCCESS', result)
if result && (password = get(result, 'password'))
result.pin ||= result.password
resolve(result)
else
reject('no password')
error = (error) =>
Logger.error('[fpa] fingerprint login error', error)
reject(error)
FingerprintAuth.decrypt(login, success, error)
)
)
export default FingerPrint
|
[
{
"context": "etObject {Bucket: settings.bucketName, Key: 'admin/config.json'}, (err, data) ->\r\n if (err)\r\n ",
"end": 365,
"score": 0.5529837012290955,
"start": 365,
"tag": "KEY",
"value": ""
},
{
"context": "t {Bucket: settings.bucketName, Key: 'admin/config.json'}, (err, data) ->\r\n if (err)\r\n config = {",
"end": 377,
"score": 0.6609668731689453,
"start": 373,
"tag": "KEY",
"value": "json"
}
] | src/api/blogPost/index.coffee | syaku/LambdaBlog | 0 | aws = require('aws-sdk')
async = require('async')
yaml = require('js-yaml')
moment = require('moment')
_ = require('underscore')
s3 = new aws.S3()
settings = {
bucketName: 'www.sevenspirals.net'
prefix: 'admin/posts/'
suffix: '.yml'
}
exports.handler = (event, context) ->
#サイト情報取得
s3.getObject {Bucket: settings.bucketName, Key: 'admin/config.json'}, (err, data) ->
if (err)
config = {posts:{}}
else
config = JSON.parse data.Body.toString('UTF-8')
#投稿ファイル作成
s3.listObjects {Bucket: settings.bucketName, Prefix: settings.prefix, Delimiter: '/'}, (err, data) ->
async.each data.Contents,
(data, callback)->
if data.Size == 0
return callback()
key = data.Key
s3.getObject {Bucket: settings.bucketName, Key: key}, (err, data)->
post = yaml.safeLoad(data.Body.toString('UTF-8'))
post.timestamp = moment(post.timestamp).subtract(9, 'hour').utcOffset('+09:00').format()
key = key.replace(settings.prefix, '').replace(settings.suffix, '')
config.posts[key] = post
callback()
(err)->
config.category = _.chain(config.posts).each((post, key)->_.extend(post, {key: key})).groupBy((post)->if post.category then post.category else 'uncategorized').value()
config.calendar = _.chain(config.posts).each((post, key)->_.extend(post, {key: key})).groupBy((post)->moment(post.timestamp).format('YYYY/MM')).value()
s3.putObject {Bucket: settings.bucketName, Key: 'admin/config.json', Body: JSON.stringify(config)}, (err, data)->
if err
context.done(err)
else
context.succeed('done.')
| 93901 | aws = require('aws-sdk')
async = require('async')
yaml = require('js-yaml')
moment = require('moment')
_ = require('underscore')
s3 = new aws.S3()
settings = {
bucketName: 'www.sevenspirals.net'
prefix: 'admin/posts/'
suffix: '.yml'
}
exports.handler = (event, context) ->
#サイト情報取得
s3.getObject {Bucket: settings.bucketName, Key: 'admin<KEY>/config.<KEY>'}, (err, data) ->
if (err)
config = {posts:{}}
else
config = JSON.parse data.Body.toString('UTF-8')
#投稿ファイル作成
s3.listObjects {Bucket: settings.bucketName, Prefix: settings.prefix, Delimiter: '/'}, (err, data) ->
async.each data.Contents,
(data, callback)->
if data.Size == 0
return callback()
key = data.Key
s3.getObject {Bucket: settings.bucketName, Key: key}, (err, data)->
post = yaml.safeLoad(data.Body.toString('UTF-8'))
post.timestamp = moment(post.timestamp).subtract(9, 'hour').utcOffset('+09:00').format()
key = key.replace(settings.prefix, '').replace(settings.suffix, '')
config.posts[key] = post
callback()
(err)->
config.category = _.chain(config.posts).each((post, key)->_.extend(post, {key: key})).groupBy((post)->if post.category then post.category else 'uncategorized').value()
config.calendar = _.chain(config.posts).each((post, key)->_.extend(post, {key: key})).groupBy((post)->moment(post.timestamp).format('YYYY/MM')).value()
s3.putObject {Bucket: settings.bucketName, Key: 'admin/config.json', Body: JSON.stringify(config)}, (err, data)->
if err
context.done(err)
else
context.succeed('done.')
| true | aws = require('aws-sdk')
async = require('async')
yaml = require('js-yaml')
moment = require('moment')
_ = require('underscore')
s3 = new aws.S3()
settings = {
bucketName: 'www.sevenspirals.net'
prefix: 'admin/posts/'
suffix: '.yml'
}
exports.handler = (event, context) ->
#サイト情報取得
s3.getObject {Bucket: settings.bucketName, Key: 'adminPI:KEY:<KEY>END_PI/config.PI:KEY:<KEY>END_PI'}, (err, data) ->
if (err)
config = {posts:{}}
else
config = JSON.parse data.Body.toString('UTF-8')
#投稿ファイル作成
s3.listObjects {Bucket: settings.bucketName, Prefix: settings.prefix, Delimiter: '/'}, (err, data) ->
async.each data.Contents,
(data, callback)->
if data.Size == 0
return callback()
key = data.Key
s3.getObject {Bucket: settings.bucketName, Key: key}, (err, data)->
post = yaml.safeLoad(data.Body.toString('UTF-8'))
post.timestamp = moment(post.timestamp).subtract(9, 'hour').utcOffset('+09:00').format()
key = key.replace(settings.prefix, '').replace(settings.suffix, '')
config.posts[key] = post
callback()
(err)->
config.category = _.chain(config.posts).each((post, key)->_.extend(post, {key: key})).groupBy((post)->if post.category then post.category else 'uncategorized').value()
config.calendar = _.chain(config.posts).each((post, key)->_.extend(post, {key: key})).groupBy((post)->moment(post.timestamp).format('YYYY/MM')).value()
s3.putObject {Bucket: settings.bucketName, Key: 'admin/config.json', Body: JSON.stringify(config)}, (err, data)->
if err
context.done(err)
else
context.succeed('done.')
|
[
{
"context": " %> <%= pkg.version %> |\n @author Valtid Caushi\n @date <%= grunt.template.today(",
"end": 2586,
"score": 0.9998909831047058,
"start": 2573,
"tag": "NAME",
"value": "Valtid Caushi"
},
{
"context": " %> <%= pkg.version %> |\n @author Valtid Caushi\n @date <%= grunt.template.today(",
"end": 3205,
"score": 0.9998849034309387,
"start": 3192,
"tag": "NAME",
"value": "Valtid Caushi"
}
] | Gruntfile.coffee | valtido/ason-js | 0 | module.exports = (grunt) ->
require('load-grunt-tasks')(grunt)
readOptionalJSON = (filepath) ->
data = {}
try
data = grunt.file.readJSON(filepath)
catch e
data
gzip = require( "gzip-js" )
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
dst: readOptionalJSON "dist/.destination.json"
"compare_size":
files: [ "dist/<%= pkg.name %>.js", "dist/<%= pkg.name %>.min.js" ]
options:
compress:
gz: ( contents )-> return gzip.zip( contents, {} ).length
cache: "build/.sizecache.json"
clean:
files: [
'public/assets/js/jom.js'
'public/assets/js/jom.min.js'
'public/assets/js/jom.min.js.map'
'src/**/*.js'
'test/unit/**/*.js'
'dist/**/*'
'coverage'
]
coffee:
src:
options:
bare: true
expand: true
flatten: true
cwd: 'src'
src: ['*.coffee']
dest: 'src'
ext: '.js'
test:
options:
bare: true
expand: true
flatten: true
cwd: 'test/unit'
src: ['*.coffee']
dest: 'test/unit'
ext: '.js'
concat:
core:
src: [
# 'bower_components/jquery/dist/jquery.js'
'src/utils.js'
'public/bower_components/webcomponentsjs/webcomponents.js'
'public/assets/-/is-my-json-valid/is-my-json-valid.min.js'
'src/handle.js'
'src/observe_fallback.js'
'src/observe.js'
'src/asset.js'
'src/shadow.js'
'src/collection.js'
'src/component.js'
'src/template.js'
'src/schema.js'
'src/jom.js'
]
dest: 'dist/<%= pkg.name %>.js'
tests:
src: ["test/unit/**/*.js"]
dest: 'test/unit.js'
copy:
src: "<%= concat.core.src %>"
dest: 'public/assets/js/jom.js'
copy_min:
src: "dist/jom.min.js"
dest: 'public/assets/js/jom.min.js'
copy_map:
src: "dist/jom.min.js.map"
dest: 'public/assets/js/jom.min.js.map'
uglify:
core:
options:
preserveComments: false
sourceMap: true
# sourceMapName: "dist/jom.min.map"
report: "min"
mangle:
toplevel: false
beautify:
"ascii_only": true
banner: '/*! <%= pkg.name %> <%= pkg.version %> |
@author Valtid Caushi
@date <%= grunt.template.today("dd-mm-yyyy") %> */\n'
compress:
"hoist_funs": false
loops: false
unused: false
files:
'dist/<%= pkg.name %>.min.js': 'dist/<%= pkg.name %>.js'
tests:
options:
preserveComments: false
sourceMap: true
# sourceMapName: "test/unit/all.min.map"
report: "min"
mangle:
toplevel: false
beautify:
"ascii_only": true
banner: '/*! <%= pkg.name %> <%= pkg.version %> |
@author Valtid Caushi
@date <%= grunt.template.today("dd-mm-yyyy") %> */\n'
compress:
"hoist_funs": false
loops: false
unused: false
files:
'test/unit.min.js': 'test/unit.js'
karma:
ff:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['Firefox']
chrome:
configFile: 'test/karma.config.js'
singleRun: true
force: true
browsers: ['Chrome']
# browsers: ['chrome_without_security']
single:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['PhantomJS']
continuous:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['PhantomJS']
dev:
configFile: 'test/karma.config.js'
singleRun: false
browsers: ['Chrome']
unit:
configFile: 'test/karma.config.js'
background: true
singleRun: false
watch:
files: [ "src/**/*.coffee", "test/**/*.coffee" ]
tasks: ['build']
# Load the plugin that provides the "autoload" task.
grunt.registerTask "test",
['build',"karma:chrome"]
grunt.registerTask "clear", ["clean"]
grunt.registerTask "builder", ["build","watch"]
grunt.registerTask "dev", ["build", "karma:dev","watch"]
# grunt.registerTask "default", ["build", "karma:chrome"]
grunt.registerTask "build", ["clean",'coffee','concat','uglify','compare_size']
grunt.registerTask "default", ['test']
| 53656 | module.exports = (grunt) ->
require('load-grunt-tasks')(grunt)
readOptionalJSON = (filepath) ->
data = {}
try
data = grunt.file.readJSON(filepath)
catch e
data
gzip = require( "gzip-js" )
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
dst: readOptionalJSON "dist/.destination.json"
"compare_size":
files: [ "dist/<%= pkg.name %>.js", "dist/<%= pkg.name %>.min.js" ]
options:
compress:
gz: ( contents )-> return gzip.zip( contents, {} ).length
cache: "build/.sizecache.json"
clean:
files: [
'public/assets/js/jom.js'
'public/assets/js/jom.min.js'
'public/assets/js/jom.min.js.map'
'src/**/*.js'
'test/unit/**/*.js'
'dist/**/*'
'coverage'
]
coffee:
src:
options:
bare: true
expand: true
flatten: true
cwd: 'src'
src: ['*.coffee']
dest: 'src'
ext: '.js'
test:
options:
bare: true
expand: true
flatten: true
cwd: 'test/unit'
src: ['*.coffee']
dest: 'test/unit'
ext: '.js'
concat:
core:
src: [
# 'bower_components/jquery/dist/jquery.js'
'src/utils.js'
'public/bower_components/webcomponentsjs/webcomponents.js'
'public/assets/-/is-my-json-valid/is-my-json-valid.min.js'
'src/handle.js'
'src/observe_fallback.js'
'src/observe.js'
'src/asset.js'
'src/shadow.js'
'src/collection.js'
'src/component.js'
'src/template.js'
'src/schema.js'
'src/jom.js'
]
dest: 'dist/<%= pkg.name %>.js'
tests:
src: ["test/unit/**/*.js"]
dest: 'test/unit.js'
copy:
src: "<%= concat.core.src %>"
dest: 'public/assets/js/jom.js'
copy_min:
src: "dist/jom.min.js"
dest: 'public/assets/js/jom.min.js'
copy_map:
src: "dist/jom.min.js.map"
dest: 'public/assets/js/jom.min.js.map'
uglify:
core:
options:
preserveComments: false
sourceMap: true
# sourceMapName: "dist/jom.min.map"
report: "min"
mangle:
toplevel: false
beautify:
"ascii_only": true
banner: '/*! <%= pkg.name %> <%= pkg.version %> |
@author <NAME>
@date <%= grunt.template.today("dd-mm-yyyy") %> */\n'
compress:
"hoist_funs": false
loops: false
unused: false
files:
'dist/<%= pkg.name %>.min.js': 'dist/<%= pkg.name %>.js'
tests:
options:
preserveComments: false
sourceMap: true
# sourceMapName: "test/unit/all.min.map"
report: "min"
mangle:
toplevel: false
beautify:
"ascii_only": true
banner: '/*! <%= pkg.name %> <%= pkg.version %> |
@author <NAME>
@date <%= grunt.template.today("dd-mm-yyyy") %> */\n'
compress:
"hoist_funs": false
loops: false
unused: false
files:
'test/unit.min.js': 'test/unit.js'
karma:
ff:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['Firefox']
chrome:
configFile: 'test/karma.config.js'
singleRun: true
force: true
browsers: ['Chrome']
# browsers: ['chrome_without_security']
single:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['PhantomJS']
continuous:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['PhantomJS']
dev:
configFile: 'test/karma.config.js'
singleRun: false
browsers: ['Chrome']
unit:
configFile: 'test/karma.config.js'
background: true
singleRun: false
watch:
files: [ "src/**/*.coffee", "test/**/*.coffee" ]
tasks: ['build']
# Load the plugin that provides the "autoload" task.
grunt.registerTask "test",
['build',"karma:chrome"]
grunt.registerTask "clear", ["clean"]
grunt.registerTask "builder", ["build","watch"]
grunt.registerTask "dev", ["build", "karma:dev","watch"]
# grunt.registerTask "default", ["build", "karma:chrome"]
grunt.registerTask "build", ["clean",'coffee','concat','uglify','compare_size']
grunt.registerTask "default", ['test']
| true | module.exports = (grunt) ->
require('load-grunt-tasks')(grunt)
readOptionalJSON = (filepath) ->
data = {}
try
data = grunt.file.readJSON(filepath)
catch e
data
gzip = require( "gzip-js" )
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
dst: readOptionalJSON "dist/.destination.json"
"compare_size":
files: [ "dist/<%= pkg.name %>.js", "dist/<%= pkg.name %>.min.js" ]
options:
compress:
gz: ( contents )-> return gzip.zip( contents, {} ).length
cache: "build/.sizecache.json"
clean:
files: [
'public/assets/js/jom.js'
'public/assets/js/jom.min.js'
'public/assets/js/jom.min.js.map'
'src/**/*.js'
'test/unit/**/*.js'
'dist/**/*'
'coverage'
]
coffee:
src:
options:
bare: true
expand: true
flatten: true
cwd: 'src'
src: ['*.coffee']
dest: 'src'
ext: '.js'
test:
options:
bare: true
expand: true
flatten: true
cwd: 'test/unit'
src: ['*.coffee']
dest: 'test/unit'
ext: '.js'
concat:
core:
src: [
# 'bower_components/jquery/dist/jquery.js'
'src/utils.js'
'public/bower_components/webcomponentsjs/webcomponents.js'
'public/assets/-/is-my-json-valid/is-my-json-valid.min.js'
'src/handle.js'
'src/observe_fallback.js'
'src/observe.js'
'src/asset.js'
'src/shadow.js'
'src/collection.js'
'src/component.js'
'src/template.js'
'src/schema.js'
'src/jom.js'
]
dest: 'dist/<%= pkg.name %>.js'
tests:
src: ["test/unit/**/*.js"]
dest: 'test/unit.js'
copy:
src: "<%= concat.core.src %>"
dest: 'public/assets/js/jom.js'
copy_min:
src: "dist/jom.min.js"
dest: 'public/assets/js/jom.min.js'
copy_map:
src: "dist/jom.min.js.map"
dest: 'public/assets/js/jom.min.js.map'
uglify:
core:
options:
preserveComments: false
sourceMap: true
# sourceMapName: "dist/jom.min.map"
report: "min"
mangle:
toplevel: false
beautify:
"ascii_only": true
banner: '/*! <%= pkg.name %> <%= pkg.version %> |
@author PI:NAME:<NAME>END_PI
@date <%= grunt.template.today("dd-mm-yyyy") %> */\n'
compress:
"hoist_funs": false
loops: false
unused: false
files:
'dist/<%= pkg.name %>.min.js': 'dist/<%= pkg.name %>.js'
tests:
options:
preserveComments: false
sourceMap: true
# sourceMapName: "test/unit/all.min.map"
report: "min"
mangle:
toplevel: false
beautify:
"ascii_only": true
banner: '/*! <%= pkg.name %> <%= pkg.version %> |
@author PI:NAME:<NAME>END_PI
@date <%= grunt.template.today("dd-mm-yyyy") %> */\n'
compress:
"hoist_funs": false
loops: false
unused: false
files:
'test/unit.min.js': 'test/unit.js'
karma:
ff:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['Firefox']
chrome:
configFile: 'test/karma.config.js'
singleRun: true
force: true
browsers: ['Chrome']
# browsers: ['chrome_without_security']
single:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['PhantomJS']
continuous:
configFile: 'test/karma.config.js'
singleRun: true
browsers: ['PhantomJS']
dev:
configFile: 'test/karma.config.js'
singleRun: false
browsers: ['Chrome']
unit:
configFile: 'test/karma.config.js'
background: true
singleRun: false
watch:
files: [ "src/**/*.coffee", "test/**/*.coffee" ]
tasks: ['build']
# Load the plugin that provides the "autoload" task.
grunt.registerTask "test",
['build',"karma:chrome"]
grunt.registerTask "clear", ["clean"]
grunt.registerTask "builder", ["build","watch"]
grunt.registerTask "dev", ["build", "karma:dev","watch"]
# grunt.registerTask "default", ["build", "karma:chrome"]
grunt.registerTask "build", ["clean",'coffee','concat','uglify','compare_size']
grunt.registerTask "default", ['test']
|
[
{
"context": " @service = services.dropbox\n\n #@key = \"#{@path}#{@name}\"\n\n @name = @key.match(/[^\\/]+$/)[0]\n ",
"end": 112,
"score": 0.8959318399429321,
"start": 110,
"tag": "KEY",
"value": "#{"
}
] | src/coffee/files/dropbox-file.coffee | agiza/mondrian | 226 | class DropboxFile extends File
constructor: (@key) ->
@service = services.dropbox
#@key = "#{@path}#{@name}"
@name = @key.match(/[^\/]+$/)[0]
@path = @key.substring(0, @key.length - @name.length)
@displayLocation = @key
super @key, @name, @path, @thumbnail
load: (ok = ->) ->
@get ((data) =>
@contents = data.contents
archive.get()
@use(true) if @ == ui.file
ok(data)
), ((error) =>
@contents = io.makeFile()
@use(true) if @ == ui.file
)
@
put: (ok) ->
archive.put()
super ok
| 86094 | class DropboxFile extends File
constructor: (@key) ->
@service = services.dropbox
#@key = "#{@path}<KEY>@name}"
@name = @key.match(/[^\/]+$/)[0]
@path = @key.substring(0, @key.length - @name.length)
@displayLocation = @key
super @key, @name, @path, @thumbnail
load: (ok = ->) ->
@get ((data) =>
@contents = data.contents
archive.get()
@use(true) if @ == ui.file
ok(data)
), ((error) =>
@contents = io.makeFile()
@use(true) if @ == ui.file
)
@
put: (ok) ->
archive.put()
super ok
| true | class DropboxFile extends File
constructor: (@key) ->
@service = services.dropbox
#@key = "#{@path}PI:KEY:<KEY>END_PI@name}"
@name = @key.match(/[^\/]+$/)[0]
@path = @key.substring(0, @key.length - @name.length)
@displayLocation = @key
super @key, @name, @path, @thumbnail
load: (ok = ->) ->
@get ((data) =>
@contents = data.contents
archive.get()
@use(true) if @ == ui.file
ok(data)
), ((error) =>
@contents = io.makeFile()
@use(true) if @ == ui.file
)
@
put: (ok) ->
archive.put()
super ok
|
[
{
"context": "./index\")(robot)\n\n userInfo =\n name: \"atmos\",\n room: \"#zf-promo\"\n\n user = r",
"end": 476,
"score": 0.5608847737312317,
"start": 474,
"tag": "USERNAME",
"value": "at"
},
{
"context": "index\")(robot)\n\n userInfo =\n name: \"atmos\",\n room: \"#zf-promo\"\n\n user = robo",
"end": 479,
"score": 0.5911722183227539,
"start": 476,
"tag": "NAME",
"value": "mos"
}
] | test/scripts/http_test.coffee | JennerF/hubot-test | 0 | Path = require "path"
Robot = require "hubot/src/robot"
TextMessage = require("hubot/src/message").TextMessage
describe "Deployment Status HTTP Callbacks", () ->
user = null
robot = null
adapter = null
beforeEach (done) ->
robot = new Robot(null, "mock-adapter", true, "Hubot")
robot.adapter.on "connected", () ->
process.env.HUBOT_DEPLOY_RANDOM_REPLY = "sup-dude"
require("../../index")(robot)
userInfo =
name: "atmos",
room: "#zf-promo"
user = robot.brain.userForId "1", userInfo
adapter = robot.adapter
done()
robot.run()
afterEach () ->
robot.server.close()
robot.shutdown()
it "responds when greeted", (done) ->
adapter.on "reply", (envelope, strings) ->
assert.equal strings[0], "Why hello there! (ticker tape, ticker tape)"
done()
message = new TextMessage(user, process.env.HUBOT_DEPLOY_RANDOM_REPLY)
adapter.receive(message)
| 143248 | Path = require "path"
Robot = require "hubot/src/robot"
TextMessage = require("hubot/src/message").TextMessage
describe "Deployment Status HTTP Callbacks", () ->
user = null
robot = null
adapter = null
beforeEach (done) ->
robot = new Robot(null, "mock-adapter", true, "Hubot")
robot.adapter.on "connected", () ->
process.env.HUBOT_DEPLOY_RANDOM_REPLY = "sup-dude"
require("../../index")(robot)
userInfo =
name: "at<NAME>",
room: "#zf-promo"
user = robot.brain.userForId "1", userInfo
adapter = robot.adapter
done()
robot.run()
afterEach () ->
robot.server.close()
robot.shutdown()
it "responds when greeted", (done) ->
adapter.on "reply", (envelope, strings) ->
assert.equal strings[0], "Why hello there! (ticker tape, ticker tape)"
done()
message = new TextMessage(user, process.env.HUBOT_DEPLOY_RANDOM_REPLY)
adapter.receive(message)
| true | Path = require "path"
Robot = require "hubot/src/robot"
TextMessage = require("hubot/src/message").TextMessage
describe "Deployment Status HTTP Callbacks", () ->
user = null
robot = null
adapter = null
beforeEach (done) ->
robot = new Robot(null, "mock-adapter", true, "Hubot")
robot.adapter.on "connected", () ->
process.env.HUBOT_DEPLOY_RANDOM_REPLY = "sup-dude"
require("../../index")(robot)
userInfo =
name: "atPI:NAME:<NAME>END_PI",
room: "#zf-promo"
user = robot.brain.userForId "1", userInfo
adapter = robot.adapter
done()
robot.run()
afterEach () ->
robot.server.close()
robot.shutdown()
it "responds when greeted", (done) ->
adapter.on "reply", (envelope, strings) ->
assert.equal strings[0], "Why hello there! (ticker tape, ticker tape)"
done()
message = new TextMessage(user, process.env.HUBOT_DEPLOY_RANDOM_REPLY)
adapter.receive(message)
|
[
{
"context": "\"活动参与者\"\n\ticon: \"event\"\n\tfields:\n\t\tname:\n\t\t\tlabel:'姓名'\n\t\t\ttype:'text'\n\t\t\tomit:true\n\t\tstatus:\n\t\t\tlabel:'",
"end": 1031,
"score": 0.7636882066726685,
"start": 1029,
"tag": "NAME",
"value": "姓名"
}
] | packages/steedos-vip-card/models/vip_event_attendees.coffee | zonglu233/fuel-car | 42 |
remindTime = (alarm,start)->
remindtime = start.getTime()
if alarm!="Now"
miliseconds=0
if alarm[2]=='T'
if alarm[alarm.length-1]=='M'
i=3
mimutes=0
while i<alarm.length-1
mimutes=mimutes+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=mimutes*60*1000
else if alarm[alarm.length-1]=='S'
miliseconds = 0
else
i=3
hours=0
while i<alarm.length-1
hours=hours+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=hours*60*60*1000
else
if alarm[alarm.length-1]=='D'
i=2
days=0
while i<alarm.length-1
days=days+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=days*24*60*60*1000
else if alarm[3] == 'D'
miliseconds = alarm[2]*24*60*60*1000+15*60*60*1000
else
miliseconds = 15*60*60*1000
remindtime=moment(start).utc().valueOf()-miliseconds
return remindtime
Creator.Objects.vip_event_attendees =
name: "vip_event_attendees"
label: "活动参与者"
icon: "event"
fields:
name:
label:'姓名'
type:'text'
omit:true
status:
label:'接受状态'
type:'select'
options:[
{label:'已接受',value:'accepted'},
{label:'观望中',value:'pending'},
{label:'已拒绝',value:'rejected'}
]
event:
label:'活动名称'
type:'lookup'
reference_to:'vip_event'
is_wide:true
omit:true
index:true
comment:
label:'备注'
type:'textarea'
is_wide:true
alarms:
label:'提醒时间'
type:'select'
options:[
{label:'不提醒',value:'null'},
{label:'活动开始时',value:'Now'},
{label:'5分钟前',value:'-PT5M'},
{label:'10分钟前',value:'-PT10M'},
{label:'15分钟前',value:'-PT15M'},
{label:'30分钟前',value:'-PT30M'},
{label:'1小时前',value:'-PT1H'},
{label:'2小时前',value:'-PT2H'},
{label:'1天前',value:'-P1D'},
{label:'2天前',value:'-P2D'}
]
group:'-'
wx_form_id:
label:'表单'
type:'text'
omit:true
list_views:
all:
label: "所有"
columns: ["name","status"]
filter_scope: "space"
permission_set:
user:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
admin:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
member:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
guest:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: false
viewAllRecords: true
triggers:
"before.insert.server.event":
on: "server"
when: "before.insert"
todo: (userId, doc)->
if _.isEmpty(doc.event)
throw new Meteor.Error 500, "所属活动不能为空"
"after.insert.server.event":
on: "server"
when: "after.insert"
todo: (userId, doc)->
status = doc.status
if status
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
# 增加记录时,如果status值存在,则应该在对应的事件中把status数量加一
event_data = collection.findOne(selector,{fields:{name:1,start:1,location:1}})
start = event_data.start
remindtime = remindTime(doc.alarms,start)
inc = {}
inc["#{status}_count"] = 1
collection.update(selector, {$inc: inc})
"before.update.server.event":
on: "server"
when: "before.update"
todo: (userId, doc, fieldNames, modifier, options)->
if _.isEmpty(doc.event)
throw new Meteor.Error 500, "所属活动不能为空"
now_wx_form_id = doc.wx_form_id || modifier.$set.wx_form_id
alarm = doc.alarms || modifier.$set.alarms
appId = now_wx_form_id.split(':')[0]
formId = now_wx_form_id.split(':')[1]
if alarm and formId
if WeixinTemplateMessageQueue.collection.find({ 'info.form_id': formId, sent: false }).count() > 0
delete modifier.$set.wx_form_id
else
# 如果修改了status,则应该在对应的事件中把老的status数量减一,新的status数量加一
event_data = Creator.getCollection("vip_event").findOne(doc.event, { fields: { name: 1, start: 1, location: 1 } })
remindtime = remindTime(alarm,event_data.start)
start = moment(event_data.start).format("YYYY-MM-DD HH:mm")
data = {
"keyword1": {
"value": event_data.name
},
"keyword2": {
"value":start
},
"keyword3": {
"value": event_data.location.address
}
}
user = Creator.getCollection("users").findOne({_id:userId},{fields:{'services':1}})
if user
openids = user.services?.weixin?.openid
if openids
open_token = _.find(openids, (t)->
if t.appid == appId
return t._id
)
message = {
touser: open_token._id,
template_id: 'F3KbQYC0sN6LWNUokitLE2b4f_dZYTO2dyTS7SC543o',
page: 'pages/event/view?space_id='+ doc.space + '&event_id='+ doc.event,
form_id: formId,
data: data
}
WeixinTemplateMessageQueue.send(appId, message, remindtime)
"after.update.server.event":
on: "server"
when: "after.update"
todo: (userId, doc, fieldNames, modifier, options)->
status = doc.status
preStatus = this.previous.status
#
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
if preStatus != status
inc = {}
if preStatus
inc["#{preStatus}_count"] = -1
inc["#{status}_count"] = 1
collection.update(selector, {$inc: inc})
"after.remove.server.event":
on: "server"
when: "after.remove"
todo: (userId, doc)->
if _.isEmpty(doc.event)
return
status = doc.status
if status
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
# 删除记录时,如果status值存在,则应该在对应的事件中把status数量减一
inc = {}
inc["#{status}_count"] = -1
collection.update(selector, {$inc: inc}) | 27295 |
remindTime = (alarm,start)->
remindtime = start.getTime()
if alarm!="Now"
miliseconds=0
if alarm[2]=='T'
if alarm[alarm.length-1]=='M'
i=3
mimutes=0
while i<alarm.length-1
mimutes=mimutes+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=mimutes*60*1000
else if alarm[alarm.length-1]=='S'
miliseconds = 0
else
i=3
hours=0
while i<alarm.length-1
hours=hours+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=hours*60*60*1000
else
if alarm[alarm.length-1]=='D'
i=2
days=0
while i<alarm.length-1
days=days+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=days*24*60*60*1000
else if alarm[3] == 'D'
miliseconds = alarm[2]*24*60*60*1000+15*60*60*1000
else
miliseconds = 15*60*60*1000
remindtime=moment(start).utc().valueOf()-miliseconds
return remindtime
Creator.Objects.vip_event_attendees =
name: "vip_event_attendees"
label: "活动参与者"
icon: "event"
fields:
name:
label:'<NAME>'
type:'text'
omit:true
status:
label:'接受状态'
type:'select'
options:[
{label:'已接受',value:'accepted'},
{label:'观望中',value:'pending'},
{label:'已拒绝',value:'rejected'}
]
event:
label:'活动名称'
type:'lookup'
reference_to:'vip_event'
is_wide:true
omit:true
index:true
comment:
label:'备注'
type:'textarea'
is_wide:true
alarms:
label:'提醒时间'
type:'select'
options:[
{label:'不提醒',value:'null'},
{label:'活动开始时',value:'Now'},
{label:'5分钟前',value:'-PT5M'},
{label:'10分钟前',value:'-PT10M'},
{label:'15分钟前',value:'-PT15M'},
{label:'30分钟前',value:'-PT30M'},
{label:'1小时前',value:'-PT1H'},
{label:'2小时前',value:'-PT2H'},
{label:'1天前',value:'-P1D'},
{label:'2天前',value:'-P2D'}
]
group:'-'
wx_form_id:
label:'表单'
type:'text'
omit:true
list_views:
all:
label: "所有"
columns: ["name","status"]
filter_scope: "space"
permission_set:
user:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
admin:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
member:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
guest:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: false
viewAllRecords: true
triggers:
"before.insert.server.event":
on: "server"
when: "before.insert"
todo: (userId, doc)->
if _.isEmpty(doc.event)
throw new Meteor.Error 500, "所属活动不能为空"
"after.insert.server.event":
on: "server"
when: "after.insert"
todo: (userId, doc)->
status = doc.status
if status
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
# 增加记录时,如果status值存在,则应该在对应的事件中把status数量加一
event_data = collection.findOne(selector,{fields:{name:1,start:1,location:1}})
start = event_data.start
remindtime = remindTime(doc.alarms,start)
inc = {}
inc["#{status}_count"] = 1
collection.update(selector, {$inc: inc})
"before.update.server.event":
on: "server"
when: "before.update"
todo: (userId, doc, fieldNames, modifier, options)->
if _.isEmpty(doc.event)
throw new Meteor.Error 500, "所属活动不能为空"
now_wx_form_id = doc.wx_form_id || modifier.$set.wx_form_id
alarm = doc.alarms || modifier.$set.alarms
appId = now_wx_form_id.split(':')[0]
formId = now_wx_form_id.split(':')[1]
if alarm and formId
if WeixinTemplateMessageQueue.collection.find({ 'info.form_id': formId, sent: false }).count() > 0
delete modifier.$set.wx_form_id
else
# 如果修改了status,则应该在对应的事件中把老的status数量减一,新的status数量加一
event_data = Creator.getCollection("vip_event").findOne(doc.event, { fields: { name: 1, start: 1, location: 1 } })
remindtime = remindTime(alarm,event_data.start)
start = moment(event_data.start).format("YYYY-MM-DD HH:mm")
data = {
"keyword1": {
"value": event_data.name
},
"keyword2": {
"value":start
},
"keyword3": {
"value": event_data.location.address
}
}
user = Creator.getCollection("users").findOne({_id:userId},{fields:{'services':1}})
if user
openids = user.services?.weixin?.openid
if openids
open_token = _.find(openids, (t)->
if t.appid == appId
return t._id
)
message = {
touser: open_token._id,
template_id: 'F3KbQYC0sN6LWNUokitLE2b4f_dZYTO2dyTS7SC543o',
page: 'pages/event/view?space_id='+ doc.space + '&event_id='+ doc.event,
form_id: formId,
data: data
}
WeixinTemplateMessageQueue.send(appId, message, remindtime)
"after.update.server.event":
on: "server"
when: "after.update"
todo: (userId, doc, fieldNames, modifier, options)->
status = doc.status
preStatus = this.previous.status
#
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
if preStatus != status
inc = {}
if preStatus
inc["#{preStatus}_count"] = -1
inc["#{status}_count"] = 1
collection.update(selector, {$inc: inc})
"after.remove.server.event":
on: "server"
when: "after.remove"
todo: (userId, doc)->
if _.isEmpty(doc.event)
return
status = doc.status
if status
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
# 删除记录时,如果status值存在,则应该在对应的事件中把status数量减一
inc = {}
inc["#{status}_count"] = -1
collection.update(selector, {$inc: inc}) | true |
remindTime = (alarm,start)->
remindtime = start.getTime()
if alarm!="Now"
miliseconds=0
if alarm[2]=='T'
if alarm[alarm.length-1]=='M'
i=3
mimutes=0
while i<alarm.length-1
mimutes=mimutes+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=mimutes*60*1000
else if alarm[alarm.length-1]=='S'
miliseconds = 0
else
i=3
hours=0
while i<alarm.length-1
hours=hours+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=hours*60*60*1000
else
if alarm[alarm.length-1]=='D'
i=2
days=0
while i<alarm.length-1
days=days+alarm[i]*(Math.pow(10,alarm.length-2-i))
i++
miliseconds=days*24*60*60*1000
else if alarm[3] == 'D'
miliseconds = alarm[2]*24*60*60*1000+15*60*60*1000
else
miliseconds = 15*60*60*1000
remindtime=moment(start).utc().valueOf()-miliseconds
return remindtime
Creator.Objects.vip_event_attendees =
name: "vip_event_attendees"
label: "活动参与者"
icon: "event"
fields:
name:
label:'PI:NAME:<NAME>END_PI'
type:'text'
omit:true
status:
label:'接受状态'
type:'select'
options:[
{label:'已接受',value:'accepted'},
{label:'观望中',value:'pending'},
{label:'已拒绝',value:'rejected'}
]
event:
label:'活动名称'
type:'lookup'
reference_to:'vip_event'
is_wide:true
omit:true
index:true
comment:
label:'备注'
type:'textarea'
is_wide:true
alarms:
label:'提醒时间'
type:'select'
options:[
{label:'不提醒',value:'null'},
{label:'活动开始时',value:'Now'},
{label:'5分钟前',value:'-PT5M'},
{label:'10分钟前',value:'-PT10M'},
{label:'15分钟前',value:'-PT15M'},
{label:'30分钟前',value:'-PT30M'},
{label:'1小时前',value:'-PT1H'},
{label:'2小时前',value:'-PT2H'},
{label:'1天前',value:'-P1D'},
{label:'2天前',value:'-P2D'}
]
group:'-'
wx_form_id:
label:'表单'
type:'text'
omit:true
list_views:
all:
label: "所有"
columns: ["name","status"]
filter_scope: "space"
permission_set:
user:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
admin:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
member:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
guest:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: false
viewAllRecords: true
triggers:
"before.insert.server.event":
on: "server"
when: "before.insert"
todo: (userId, doc)->
if _.isEmpty(doc.event)
throw new Meteor.Error 500, "所属活动不能为空"
"after.insert.server.event":
on: "server"
when: "after.insert"
todo: (userId, doc)->
status = doc.status
if status
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
# 增加记录时,如果status值存在,则应该在对应的事件中把status数量加一
event_data = collection.findOne(selector,{fields:{name:1,start:1,location:1}})
start = event_data.start
remindtime = remindTime(doc.alarms,start)
inc = {}
inc["#{status}_count"] = 1
collection.update(selector, {$inc: inc})
"before.update.server.event":
on: "server"
when: "before.update"
todo: (userId, doc, fieldNames, modifier, options)->
if _.isEmpty(doc.event)
throw new Meteor.Error 500, "所属活动不能为空"
now_wx_form_id = doc.wx_form_id || modifier.$set.wx_form_id
alarm = doc.alarms || modifier.$set.alarms
appId = now_wx_form_id.split(':')[0]
formId = now_wx_form_id.split(':')[1]
if alarm and formId
if WeixinTemplateMessageQueue.collection.find({ 'info.form_id': formId, sent: false }).count() > 0
delete modifier.$set.wx_form_id
else
# 如果修改了status,则应该在对应的事件中把老的status数量减一,新的status数量加一
event_data = Creator.getCollection("vip_event").findOne(doc.event, { fields: { name: 1, start: 1, location: 1 } })
remindtime = remindTime(alarm,event_data.start)
start = moment(event_data.start).format("YYYY-MM-DD HH:mm")
data = {
"keyword1": {
"value": event_data.name
},
"keyword2": {
"value":start
},
"keyword3": {
"value": event_data.location.address
}
}
user = Creator.getCollection("users").findOne({_id:userId},{fields:{'services':1}})
if user
openids = user.services?.weixin?.openid
if openids
open_token = _.find(openids, (t)->
if t.appid == appId
return t._id
)
message = {
touser: open_token._id,
template_id: 'F3KbQYC0sN6LWNUokitLE2b4f_dZYTO2dyTS7SC543o',
page: 'pages/event/view?space_id='+ doc.space + '&event_id='+ doc.event,
form_id: formId,
data: data
}
WeixinTemplateMessageQueue.send(appId, message, remindtime)
"after.update.server.event":
on: "server"
when: "after.update"
todo: (userId, doc, fieldNames, modifier, options)->
status = doc.status
preStatus = this.previous.status
#
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
if preStatus != status
inc = {}
if preStatus
inc["#{preStatus}_count"] = -1
inc["#{status}_count"] = 1
collection.update(selector, {$inc: inc})
"after.remove.server.event":
on: "server"
when: "after.remove"
todo: (userId, doc)->
if _.isEmpty(doc.event)
return
status = doc.status
if status
collection = Creator.getCollection("vip_event")
eventId = doc.event
selector = {_id: eventId}
# 删除记录时,如果status值存在,则应该在对应的事件中把status数量减一
inc = {}
inc["#{status}_count"] = -1
collection.update(selector, {$inc: inc}) |
[
{
"context": "orage = require 'core/storage'\nGPLUS_TOKEN_KEY = 'gplusToken'\n\n# gplus user object props to\nuserPropsToSave =\n",
"end": 168,
"score": 0.7853267192840576,
"start": 158,
"tag": "KEY",
"value": "gplusToken"
},
{
"context": "t props to\nuserPropsToSave =\n 'name.givenName': 'firstName'\n 'name.familyName': 'lastName'\n 'gender': 'gen",
"end": 248,
"score": 0.9988301396369934,
"start": 239,
"tag": "NAME",
"value": "firstName"
},
{
"context": "ame.givenName': 'firstName'\n 'name.familyName': 'lastName'\n 'gender': 'gender'\n 'id': 'gplusID'\n\nfieldsTo",
"end": 280,
"score": 0.9975607991218567,
"start": 272,
"tag": "NAME",
"value": "lastName"
},
{
"context": "ogin: ->\n @onGPlusLogin({\n access_token: '1234'\n })\n\n onGPlusLogin: (e) ->\n return unless",
"end": 2884,
"score": 0.8550533652305603,
"start": 2880,
"tag": "PASSWORD",
"value": "1234"
}
] | app/core/social-handlers/GPlusHandler.coffee | teplyja1/codecombat | 0 | CocoClass = require 'core/CocoClass'
{me} = require 'core/auth'
{backboneFailure} = require 'core/errors'
storage = require 'core/storage'
GPLUS_TOKEN_KEY = 'gplusToken'
# gplus user object props to
userPropsToSave =
'name.givenName': 'firstName'
'name.familyName': 'lastName'
'gender': 'gender'
'id': 'gplusID'
fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id'
plusURL = '/plus/v1/people/me?fields='+fieldsToFetch
revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='
clientID = '800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com'
scope = 'https://www.googleapis.com/auth/plus.login email'
module.exports = GPlusHandler = class GPlusHandler extends CocoClass
constructor: ->
@accessToken = storage.load GPLUS_TOKEN_KEY, false
window.onGPlusLogin = _.bind(@onGPlusLogin, @)
super()
token: -> @accessToken?.access_token
loadAPI: ->
return if @loadedAPI
@loadedAPI = true
(=>
po = document.createElement('script')
po.type = 'text/javascript'
po.async = true
po.src = 'https://apis.google.com/js/client:platform.js?onload=onGPlusLoaded'
s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore po, s
window.onGPlusLoaded = _.bind(@onLoadAPI, @)
return
)()
onLoadAPI: ->
Backbone.Mediator.publish 'auth:gplus-api-loaded', {}
session_state = null
if @accessToken and me.get('gplusID')
# We need to check the current state, given our access token
gapi.auth.setToken 'token', @accessToken
session_state = @accessToken.session_state
gapi.auth.checkSessionState({client_id: clientID, session_state: session_state}, @onCheckedSessionState)
else
# If we ran checkSessionState, it might return true, that the user is logged into Google, but has not authorized us
@loggedIn = false
func = => @trigger 'checked-state'
setTimeout func, 1
renderLoginButtons: ->
return false unless gapi?.plusone?
gapi.plusone.go?() # Handles +1 button
if not gapi.signin?.render
console.warn 'Didn\'t have gapi.signin to render G+ login button. (DoNotTrackMe extension?)'
return
for gplusButton in $('.gplus-login-button')
params = {
callback: 'onGPlusLogin',
clientid: clientID,
cookiepolicy: 'single_host_origin',
scope: 'https://www.googleapis.com/auth/plus.login email',
height: 'short',
}
if gapi.signin?.render
gapi.signin.render(gplusButton, params)
@trigger 'render-login-buttons'
onCheckedSessionState: (@loggedIn) =>
@trigger 'checked-state'
reauthorize: ->
params =
'client_id' : clientID
'scope' : scope
gapi.auth.authorize params, @onGPlusLogin
fakeGPlusLogin: ->
@onGPlusLogin({
access_token: '1234'
})
onGPlusLogin: (e) ->
return unless e.access_token
@loggedIn = true
Backbone.Mediator.publish 'auth:logged-in-with-gplus', e
try
# Without removing this, we sometimes get a cross-domain error
d = _.omit(e, 'g-oauth-window')
storage.save(GPLUS_TOKEN_KEY, d, 0)
catch e
console.error 'Unable to save G+ token key', e
@accessToken = e
@trigger 'logged-in'
@trigger 'logged-into-google'
loadPerson: (options={}) ->
@reloadOnLogin = options.reloadOnLogin
# email and profile data loaded separately
gapi.client.load('plus', 'v1', =>
gapi.client.plus.people.get({userId: 'me'}).execute(@onPersonReceived))
onPersonReceived: (r) =>
attrs = {}
for gpProp, userProp of userPropsToSave
keys = gpProp.split('.')
value = r
for key in keys
value = value[key]
if value
attrs[userProp] = value
newEmail = r.emails?.length and r.emails[0] isnt me.get('email')
return unless newEmail or me.get('anonymous', true)
if r.emails?.length
attrs.email = r.emails[0].value
@trigger 'person-loaded', attrs
loadFriends: (friendsCallback) ->
return friendsCallback() unless @loggedIn
expiresIn = if @accessToken then parseInt(@accessToken.expires_at) - new Date().getTime()/1000 else -1
onReauthorized = => gapi.client.request({path: '/plus/v1/people/me/people/visible', callback: friendsCallback})
if expiresIn < 0
# TODO: this tries to open a popup window, which might not ever finish or work, so the callback may never be called.
@reauthorize()
@listenToOnce(@, 'logged-in', onReauthorized)
else
onReauthorized()
| 7989 | CocoClass = require 'core/CocoClass'
{me} = require 'core/auth'
{backboneFailure} = require 'core/errors'
storage = require 'core/storage'
GPLUS_TOKEN_KEY = '<KEY>'
# gplus user object props to
userPropsToSave =
'name.givenName': '<NAME>'
'name.familyName': '<NAME>'
'gender': 'gender'
'id': 'gplusID'
fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id'
plusURL = '/plus/v1/people/me?fields='+fieldsToFetch
revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='
clientID = '800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com'
scope = 'https://www.googleapis.com/auth/plus.login email'
module.exports = GPlusHandler = class GPlusHandler extends CocoClass
constructor: ->
@accessToken = storage.load GPLUS_TOKEN_KEY, false
window.onGPlusLogin = _.bind(@onGPlusLogin, @)
super()
token: -> @accessToken?.access_token
loadAPI: ->
return if @loadedAPI
@loadedAPI = true
(=>
po = document.createElement('script')
po.type = 'text/javascript'
po.async = true
po.src = 'https://apis.google.com/js/client:platform.js?onload=onGPlusLoaded'
s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore po, s
window.onGPlusLoaded = _.bind(@onLoadAPI, @)
return
)()
onLoadAPI: ->
Backbone.Mediator.publish 'auth:gplus-api-loaded', {}
session_state = null
if @accessToken and me.get('gplusID')
# We need to check the current state, given our access token
gapi.auth.setToken 'token', @accessToken
session_state = @accessToken.session_state
gapi.auth.checkSessionState({client_id: clientID, session_state: session_state}, @onCheckedSessionState)
else
# If we ran checkSessionState, it might return true, that the user is logged into Google, but has not authorized us
@loggedIn = false
func = => @trigger 'checked-state'
setTimeout func, 1
renderLoginButtons: ->
return false unless gapi?.plusone?
gapi.plusone.go?() # Handles +1 button
if not gapi.signin?.render
console.warn 'Didn\'t have gapi.signin to render G+ login button. (DoNotTrackMe extension?)'
return
for gplusButton in $('.gplus-login-button')
params = {
callback: 'onGPlusLogin',
clientid: clientID,
cookiepolicy: 'single_host_origin',
scope: 'https://www.googleapis.com/auth/plus.login email',
height: 'short',
}
if gapi.signin?.render
gapi.signin.render(gplusButton, params)
@trigger 'render-login-buttons'
onCheckedSessionState: (@loggedIn) =>
@trigger 'checked-state'
reauthorize: ->
params =
'client_id' : clientID
'scope' : scope
gapi.auth.authorize params, @onGPlusLogin
fakeGPlusLogin: ->
@onGPlusLogin({
access_token: '<PASSWORD>'
})
onGPlusLogin: (e) ->
return unless e.access_token
@loggedIn = true
Backbone.Mediator.publish 'auth:logged-in-with-gplus', e
try
# Without removing this, we sometimes get a cross-domain error
d = _.omit(e, 'g-oauth-window')
storage.save(GPLUS_TOKEN_KEY, d, 0)
catch e
console.error 'Unable to save G+ token key', e
@accessToken = e
@trigger 'logged-in'
@trigger 'logged-into-google'
loadPerson: (options={}) ->
@reloadOnLogin = options.reloadOnLogin
# email and profile data loaded separately
gapi.client.load('plus', 'v1', =>
gapi.client.plus.people.get({userId: 'me'}).execute(@onPersonReceived))
onPersonReceived: (r) =>
attrs = {}
for gpProp, userProp of userPropsToSave
keys = gpProp.split('.')
value = r
for key in keys
value = value[key]
if value
attrs[userProp] = value
newEmail = r.emails?.length and r.emails[0] isnt me.get('email')
return unless newEmail or me.get('anonymous', true)
if r.emails?.length
attrs.email = r.emails[0].value
@trigger 'person-loaded', attrs
loadFriends: (friendsCallback) ->
return friendsCallback() unless @loggedIn
expiresIn = if @accessToken then parseInt(@accessToken.expires_at) - new Date().getTime()/1000 else -1
onReauthorized = => gapi.client.request({path: '/plus/v1/people/me/people/visible', callback: friendsCallback})
if expiresIn < 0
# TODO: this tries to open a popup window, which might not ever finish or work, so the callback may never be called.
@reauthorize()
@listenToOnce(@, 'logged-in', onReauthorized)
else
onReauthorized()
| true | CocoClass = require 'core/CocoClass'
{me} = require 'core/auth'
{backboneFailure} = require 'core/errors'
storage = require 'core/storage'
GPLUS_TOKEN_KEY = 'PI:KEY:<KEY>END_PI'
# gplus user object props to
userPropsToSave =
'name.givenName': 'PI:NAME:<NAME>END_PI'
'name.familyName': 'PI:NAME:<NAME>END_PI'
'gender': 'gender'
'id': 'gplusID'
fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id'
plusURL = '/plus/v1/people/me?fields='+fieldsToFetch
revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='
clientID = '800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com'
scope = 'https://www.googleapis.com/auth/plus.login email'
module.exports = GPlusHandler = class GPlusHandler extends CocoClass
constructor: ->
@accessToken = storage.load GPLUS_TOKEN_KEY, false
window.onGPlusLogin = _.bind(@onGPlusLogin, @)
super()
token: -> @accessToken?.access_token
loadAPI: ->
return if @loadedAPI
@loadedAPI = true
(=>
po = document.createElement('script')
po.type = 'text/javascript'
po.async = true
po.src = 'https://apis.google.com/js/client:platform.js?onload=onGPlusLoaded'
s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore po, s
window.onGPlusLoaded = _.bind(@onLoadAPI, @)
return
)()
onLoadAPI: ->
Backbone.Mediator.publish 'auth:gplus-api-loaded', {}
session_state = null
if @accessToken and me.get('gplusID')
# We need to check the current state, given our access token
gapi.auth.setToken 'token', @accessToken
session_state = @accessToken.session_state
gapi.auth.checkSessionState({client_id: clientID, session_state: session_state}, @onCheckedSessionState)
else
# If we ran checkSessionState, it might return true, that the user is logged into Google, but has not authorized us
@loggedIn = false
func = => @trigger 'checked-state'
setTimeout func, 1
renderLoginButtons: ->
return false unless gapi?.plusone?
gapi.plusone.go?() # Handles +1 button
if not gapi.signin?.render
console.warn 'Didn\'t have gapi.signin to render G+ login button. (DoNotTrackMe extension?)'
return
for gplusButton in $('.gplus-login-button')
params = {
callback: 'onGPlusLogin',
clientid: clientID,
cookiepolicy: 'single_host_origin',
scope: 'https://www.googleapis.com/auth/plus.login email',
height: 'short',
}
if gapi.signin?.render
gapi.signin.render(gplusButton, params)
@trigger 'render-login-buttons'
onCheckedSessionState: (@loggedIn) =>
@trigger 'checked-state'
reauthorize: ->
params =
'client_id' : clientID
'scope' : scope
gapi.auth.authorize params, @onGPlusLogin
fakeGPlusLogin: ->
@onGPlusLogin({
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
})
onGPlusLogin: (e) ->
return unless e.access_token
@loggedIn = true
Backbone.Mediator.publish 'auth:logged-in-with-gplus', e
try
# Without removing this, we sometimes get a cross-domain error
d = _.omit(e, 'g-oauth-window')
storage.save(GPLUS_TOKEN_KEY, d, 0)
catch e
console.error 'Unable to save G+ token key', e
@accessToken = e
@trigger 'logged-in'
@trigger 'logged-into-google'
loadPerson: (options={}) ->
@reloadOnLogin = options.reloadOnLogin
# email and profile data loaded separately
gapi.client.load('plus', 'v1', =>
gapi.client.plus.people.get({userId: 'me'}).execute(@onPersonReceived))
onPersonReceived: (r) =>
attrs = {}
for gpProp, userProp of userPropsToSave
keys = gpProp.split('.')
value = r
for key in keys
value = value[key]
if value
attrs[userProp] = value
newEmail = r.emails?.length and r.emails[0] isnt me.get('email')
return unless newEmail or me.get('anonymous', true)
if r.emails?.length
attrs.email = r.emails[0].value
@trigger 'person-loaded', attrs
loadFriends: (friendsCallback) ->
return friendsCallback() unless @loggedIn
expiresIn = if @accessToken then parseInt(@accessToken.expires_at) - new Date().getTime()/1000 else -1
onReauthorized = => gapi.client.request({path: '/plus/v1/people/me/people/visible', callback: friendsCallback})
if expiresIn < 0
# TODO: this tries to open a popup window, which might not ever finish or work, so the callback may never be called.
@reauthorize()
@listenToOnce(@, 'logged-in', onReauthorized)
else
onReauthorized()
|
[
{
"context": "d = processor.validate {'nofile': true, 'args': [\"natalya\"]}\n test.ok valid, \"Should be valid!\"\n test",
"end": 217,
"score": 0.995901882648468,
"start": 210,
"tag": "USERNAME",
"value": "natalya"
},
{
"context": "le': true, 'batch': true, 'args': [\"kiara\", \"superPass\"]} \n test.ok processor.validate program, \"Shou",
"end": 439,
"score": 0.5903672575950623,
"start": 435,
"tag": "PASSWORD",
"value": "Pass"
}
] | zillow/node_modules/http-auth/node_modules/htpasswd/tests/test-processor.coffee | tspires/personal | 4 | # Importing module.
processor = require '../lib/processor'
module.exports =
# Test for validate only username.
testValidateUsername: (test) ->
valid = processor.validate {'nofile': true, 'args': ["natalya"]}
test.ok valid, "Should be valid!"
test.done()
# Test for validate only username, password.
testValidateUsernamePass: (test) ->
program = {'nofile': true, 'batch': true, 'args': ["kiara", "superPass"]}
test.ok processor.validate program, "Should be valid!"
test.done()
# Test for validate only username, password, file.
testValidateUsernamePassFile: (test) ->
program = {'batch': true, 'args': ["pass.txt", "anna", "userPass"]}
test.ok processor.validate program, "Should be valid!"
test.done()
# Test for validate only missing password.
testValidateInvalidPass: (test) ->
program = {'batch': true, 'args': ["super.txt", "rita"]}
test.ok not processor.validate program, "Should be invalid!"
test.done()
# Test for validate only missing file.
testValidateInvalidFile: (test) ->
valid = processor.validate {'args': ["rita"]}
test.ok not valid, "Should be invalid!"
test.done()
# Test for process password function.
testProcessPassword: (test) ->
processor.readPassword = () -> test.done()
program = {'nofile': true, 'args': ["lianna"]}
processor.process program
# Test for process help function.
testProcessHelp: (test) ->
program = {'args': ["klara"], 'help': () -> test.done()}
processor.process program | 190737 | # Importing module.
processor = require '../lib/processor'
module.exports =
# Test for validate only username.
testValidateUsername: (test) ->
valid = processor.validate {'nofile': true, 'args': ["natalya"]}
test.ok valid, "Should be valid!"
test.done()
# Test for validate only username, password.
testValidateUsernamePass: (test) ->
program = {'nofile': true, 'batch': true, 'args': ["kiara", "super<PASSWORD>"]}
test.ok processor.validate program, "Should be valid!"
test.done()
# Test for validate only username, password, file.
testValidateUsernamePassFile: (test) ->
program = {'batch': true, 'args': ["pass.txt", "anna", "userPass"]}
test.ok processor.validate program, "Should be valid!"
test.done()
# Test for validate only missing password.
testValidateInvalidPass: (test) ->
program = {'batch': true, 'args': ["super.txt", "rita"]}
test.ok not processor.validate program, "Should be invalid!"
test.done()
# Test for validate only missing file.
testValidateInvalidFile: (test) ->
valid = processor.validate {'args': ["rita"]}
test.ok not valid, "Should be invalid!"
test.done()
# Test for process password function.
testProcessPassword: (test) ->
processor.readPassword = () -> test.done()
program = {'nofile': true, 'args': ["lianna"]}
processor.process program
# Test for process help function.
testProcessHelp: (test) ->
program = {'args': ["klara"], 'help': () -> test.done()}
processor.process program | true | # Importing module.
processor = require '../lib/processor'
module.exports =
# Test for validate only username.
testValidateUsername: (test) ->
valid = processor.validate {'nofile': true, 'args': ["natalya"]}
test.ok valid, "Should be valid!"
test.done()
# Test for validate only username, password.
testValidateUsernamePass: (test) ->
program = {'nofile': true, 'batch': true, 'args': ["kiara", "superPI:PASSWORD:<PASSWORD>END_PI"]}
test.ok processor.validate program, "Should be valid!"
test.done()
# Test for validate only username, password, file.
testValidateUsernamePassFile: (test) ->
program = {'batch': true, 'args': ["pass.txt", "anna", "userPass"]}
test.ok processor.validate program, "Should be valid!"
test.done()
# Test for validate only missing password.
testValidateInvalidPass: (test) ->
program = {'batch': true, 'args': ["super.txt", "rita"]}
test.ok not processor.validate program, "Should be invalid!"
test.done()
# Test for validate only missing file.
testValidateInvalidFile: (test) ->
valid = processor.validate {'args': ["rita"]}
test.ok not valid, "Should be invalid!"
test.done()
# Test for process password function.
testProcessPassword: (test) ->
processor.readPassword = () -> test.done()
program = {'nofile': true, 'args': ["lianna"]}
processor.process program
# Test for process help function.
testProcessHelp: (test) ->
program = {'args': ["klara"], 'help': () -> test.done()}
processor.process program |
[
{
"context": "expect(loadedPlayers[0].summoner?.name).to.equal \"SummonerA\"\n\n expect(loadedPlayers[1].championId)",
"end": 2655,
"score": 0.6019388437271118,
"start": 2646,
"tag": "NAME",
"value": "SummonerA"
},
{
"context": "expect(loadedPlayers[1].summoner?.name).to.equal \"SummonerB\"\n\n it 'should work when IDs are specifi",
"end": 2905,
"score": 0.5902551412582397,
"start": 2899,
"tag": "NAME",
"value": "Summon"
},
{
"context": "oadedPlayers[1].summoner?.name).to.equal \"SummonerB\"\n\n it 'should work when IDs are specified'",
"end": 2908,
"score": 0.6123724579811096,
"start": 2907,
"tag": "NAME",
"value": "B"
},
{
"context": " players = [\n {championKey: \"Thresh\", team: \"blue\", summonerName: \"SummonerA\"}\n ",
"end": 4486,
"score": 0.7723158597946167,
"start": 4480,
"tag": "KEY",
"value": "Thresh"
},
{
"context": "ampionKey: \"Thresh\", team: \"blue\", summonerName: \"SummonerA\"}\n {championKey: \"Aatrox\", team: \"",
"end": 4527,
"score": 0.9868439435958862,
"start": 4518,
"tag": "NAME",
"value": "SummonerA"
},
{
"context": "Name: \"SummonerA\"}\n {championKey: \"Aatrox\", team: \"red\", summonerName: \"summonerb\"}\n ",
"end": 4567,
"score": 0.9713519811630249,
"start": 4561,
"tag": "KEY",
"value": "Aatrox"
},
{
"context": "ampionKey: \"Aatrox\", team: \"red\", summonerName: \"summonerb\"}\n ]\n\n client._loadPlayers ",
"end": 4608,
"score": 0.9875890612602234,
"start": 4599,
"tag": "NAME",
"value": "summonerb"
}
] | test/api/matchTest.coffee | jwalton/lol-js | 30 | {expect} = require 'chai'
testUtils = require '../testUtils'
lol = require '../../src/lol'
describe 'match API', ->
describe 'populateMatch()', ->
it 'should populate players in a match', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v2.2/match/1514152049?includeTimeline=false"
sampleFile: 'match/normal.json'
}
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1"
sampleFile: 'summoner/byId.json'
}
]
client.getMatch 'na', 1514152049
.then (match) ->
client.populateMatch 'na', match, [
{championId: 120, teamId: 100, summonerId: 1}
]
.then (populated) ->
expect(populated).to.equal 1
expect(match.participantIdentities[0].player.summonerName).to.equal "SummonerA"
it 'should populate players in a match and cache them', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v2.2/match/1514152049?includeTimeline=false"
sampleFile: 'match/normal.json'
}
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1"
sampleFile: 'summoner/byId.json'
}
]
client.getMatch 'na', 1514152049, {
players: [{championId: 120, teamId: 100, summonerId: 1}]
}
.then (match) ->
expect(match.participantIdentities[0].player.summonerName).to.equal "SummonerA"
# Try to fetch the match without populating it - should still be populated since
# we cached the populated version.
client.getMatch 'na', 1514152049
.then (cachedMatch) ->
expect(cachedMatch.participantIdentities[0].player.summonerName).to.equal "SummonerA"
describe '_loadPlayers()', ->
checkLoadedPlayers = (loadedPlayers) ->
expect(loadedPlayers.length).to.equal 2
expect(loadedPlayers[0].championId).to.equal 412
expect(loadedPlayers[0].teamId).to.equal 100
expect(loadedPlayers[0].summoner?.id).to.equal 1
expect(loadedPlayers[0].summoner?.name).to.equal "SummonerA"
expect(loadedPlayers[1].championId).to.equal 266
expect(loadedPlayers[1].teamId).to.equal 200
expect(loadedPlayers[1].summoner?.id).to.equal 2
expect(loadedPlayers[1].summoner?.name).to.equal "SummonerB"
it 'should work when IDs are specified', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1,2",
sampleFile: 'summoner/byId.json'
}
]
players = [
{championId: 412, teamId: 100, summonerId: 1}
{championId: 266, teamId: 200, summonerId: 2}
]
client._loadPlayers 'na', players
.then (loadedPlayers) ->
checkLoadedPlayers loadedPlayers
it 'should work when names are specified', ->
client = lol.client {apiKey: 'TESTKEY', cache: lol.lruCache(50)}
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/summonera,summonerb"
sampleFile: 'summoner/byName.json'
}
{
url: "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?dataById=false"
sampleFile: 'static/champions.json'
}
# FIXME: We see two requests to fetch champion data. :/
{
url: "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?dataById=false"
sampleFile: 'static/champions.json'
}
]
players = [
{championKey: "Thresh", team: "blue", summonerName: "SummonerA"}
{championKey: "Aatrox", team: "red", summonerName: "summonerb"}
]
client._loadPlayers 'na', players
.then (loadedPlayers) ->
checkLoadedPlayers loadedPlayers
describe 'getTeamIdForSummonerId', ->
client = lol.client {apiKey: 'TESTKEY', cache: lol.lruCache(50)}
match = require '../sampleResults/match/ranked.json'
it 'should find the correct team for a summoner', ->
teamId = client.getTeamIdForSummonerId match, 24125166
expect(teamId).to.equal 100
it 'should return null if the summoner is not on any team', ->
teamId = client.getTeamIdForSummonerId match, 3
expect(teamId).to.equal null
| 206359 | {expect} = require 'chai'
testUtils = require '../testUtils'
lol = require '../../src/lol'
describe 'match API', ->
describe 'populateMatch()', ->
it 'should populate players in a match', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v2.2/match/1514152049?includeTimeline=false"
sampleFile: 'match/normal.json'
}
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1"
sampleFile: 'summoner/byId.json'
}
]
client.getMatch 'na', 1514152049
.then (match) ->
client.populateMatch 'na', match, [
{championId: 120, teamId: 100, summonerId: 1}
]
.then (populated) ->
expect(populated).to.equal 1
expect(match.participantIdentities[0].player.summonerName).to.equal "SummonerA"
it 'should populate players in a match and cache them', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v2.2/match/1514152049?includeTimeline=false"
sampleFile: 'match/normal.json'
}
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1"
sampleFile: 'summoner/byId.json'
}
]
client.getMatch 'na', 1514152049, {
players: [{championId: 120, teamId: 100, summonerId: 1}]
}
.then (match) ->
expect(match.participantIdentities[0].player.summonerName).to.equal "SummonerA"
# Try to fetch the match without populating it - should still be populated since
# we cached the populated version.
client.getMatch 'na', 1514152049
.then (cachedMatch) ->
expect(cachedMatch.participantIdentities[0].player.summonerName).to.equal "SummonerA"
describe '_loadPlayers()', ->
checkLoadedPlayers = (loadedPlayers) ->
expect(loadedPlayers.length).to.equal 2
expect(loadedPlayers[0].championId).to.equal 412
expect(loadedPlayers[0].teamId).to.equal 100
expect(loadedPlayers[0].summoner?.id).to.equal 1
expect(loadedPlayers[0].summoner?.name).to.equal "<NAME>"
expect(loadedPlayers[1].championId).to.equal 266
expect(loadedPlayers[1].teamId).to.equal 200
expect(loadedPlayers[1].summoner?.id).to.equal 2
expect(loadedPlayers[1].summoner?.name).to.equal "<NAME>er<NAME>"
it 'should work when IDs are specified', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1,2",
sampleFile: 'summoner/byId.json'
}
]
players = [
{championId: 412, teamId: 100, summonerId: 1}
{championId: 266, teamId: 200, summonerId: 2}
]
client._loadPlayers 'na', players
.then (loadedPlayers) ->
checkLoadedPlayers loadedPlayers
it 'should work when names are specified', ->
client = lol.client {apiKey: 'TESTKEY', cache: lol.lruCache(50)}
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/summonera,summonerb"
sampleFile: 'summoner/byName.json'
}
{
url: "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?dataById=false"
sampleFile: 'static/champions.json'
}
# FIXME: We see two requests to fetch champion data. :/
{
url: "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?dataById=false"
sampleFile: 'static/champions.json'
}
]
players = [
{championKey: "<KEY>", team: "blue", summonerName: "<NAME>"}
{championKey: "<KEY>", team: "red", summonerName: "<NAME>"}
]
client._loadPlayers 'na', players
.then (loadedPlayers) ->
checkLoadedPlayers loadedPlayers
describe 'getTeamIdForSummonerId', ->
client = lol.client {apiKey: 'TESTKEY', cache: lol.lruCache(50)}
match = require '../sampleResults/match/ranked.json'
it 'should find the correct team for a summoner', ->
teamId = client.getTeamIdForSummonerId match, 24125166
expect(teamId).to.equal 100
it 'should return null if the summoner is not on any team', ->
teamId = client.getTeamIdForSummonerId match, 3
expect(teamId).to.equal null
| true | {expect} = require 'chai'
testUtils = require '../testUtils'
lol = require '../../src/lol'
describe 'match API', ->
describe 'populateMatch()', ->
it 'should populate players in a match', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v2.2/match/1514152049?includeTimeline=false"
sampleFile: 'match/normal.json'
}
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1"
sampleFile: 'summoner/byId.json'
}
]
client.getMatch 'na', 1514152049
.then (match) ->
client.populateMatch 'na', match, [
{championId: 120, teamId: 100, summonerId: 1}
]
.then (populated) ->
expect(populated).to.equal 1
expect(match.participantIdentities[0].player.summonerName).to.equal "SummonerA"
it 'should populate players in a match and cache them', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v2.2/match/1514152049?includeTimeline=false"
sampleFile: 'match/normal.json'
}
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1"
sampleFile: 'summoner/byId.json'
}
]
client.getMatch 'na', 1514152049, {
players: [{championId: 120, teamId: 100, summonerId: 1}]
}
.then (match) ->
expect(match.participantIdentities[0].player.summonerName).to.equal "SummonerA"
# Try to fetch the match without populating it - should still be populated since
# we cached the populated version.
client.getMatch 'na', 1514152049
.then (cachedMatch) ->
expect(cachedMatch.participantIdentities[0].player.summonerName).to.equal "SummonerA"
describe '_loadPlayers()', ->
checkLoadedPlayers = (loadedPlayers) ->
expect(loadedPlayers.length).to.equal 2
expect(loadedPlayers[0].championId).to.equal 412
expect(loadedPlayers[0].teamId).to.equal 100
expect(loadedPlayers[0].summoner?.id).to.equal 1
expect(loadedPlayers[0].summoner?.name).to.equal "PI:NAME:<NAME>END_PI"
expect(loadedPlayers[1].championId).to.equal 266
expect(loadedPlayers[1].teamId).to.equal 200
expect(loadedPlayers[1].summoner?.id).to.equal 2
expect(loadedPlayers[1].summoner?.name).to.equal "PI:NAME:<NAME>END_PIerPI:NAME:<NAME>END_PI"
it 'should work when IDs are specified', ->
client = lol.client { apiKey: 'TESTKEY', cache: lol.lruCache(50) }
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/1,2",
sampleFile: 'summoner/byId.json'
}
]
players = [
{championId: 412, teamId: 100, summonerId: 1}
{championId: 266, teamId: 200, summonerId: 2}
]
client._loadPlayers 'na', players
.then (loadedPlayers) ->
checkLoadedPlayers loadedPlayers
it 'should work when names are specified', ->
client = lol.client {apiKey: 'TESTKEY', cache: lol.lruCache(50)}
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/summonera,summonerb"
sampleFile: 'summoner/byName.json'
}
{
url: "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?dataById=false"
sampleFile: 'static/champions.json'
}
# FIXME: We see two requests to fetch champion data. :/
{
url: "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?dataById=false"
sampleFile: 'static/champions.json'
}
]
players = [
{championKey: "PI:KEY:<KEY>END_PI", team: "blue", summonerName: "PI:NAME:<NAME>END_PI"}
{championKey: "PI:KEY:<KEY>END_PI", team: "red", summonerName: "PI:NAME:<NAME>END_PI"}
]
client._loadPlayers 'na', players
.then (loadedPlayers) ->
checkLoadedPlayers loadedPlayers
describe 'getTeamIdForSummonerId', ->
client = lol.client {apiKey: 'TESTKEY', cache: lol.lruCache(50)}
match = require '../sampleResults/match/ranked.json'
it 'should find the correct team for a summoner', ->
teamId = client.getTeamIdForSummonerId match, 24125166
expect(teamId).to.equal 100
it 'should return null if the summoner is not on any team', ->
teamId = client.getTeamIdForSummonerId match, 3
expect(teamId).to.equal null
|
[
{
"context": "#\n# Ethan Mick\n# 2015\n#\n\nFuture = require('future-client')\nClien",
"end": 14,
"score": 0.9998190402984619,
"start": 4,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/models/future.coffee | ethanmick/mustached-octo-dubstep | 0 | #
# Ethan Mick
# 2015
#
Future = require('future-client')
Client = Future.Client
Client.connect()
Client.socket.on 'task', (task)->
console.log 'GOT TASK', task
action = require "../tasks/#{task.opts.action}"
console.log 'action', action
action(task.opts)
module.exports = Future
| 41739 | #
# <NAME>
# 2015
#
Future = require('future-client')
Client = Future.Client
Client.connect()
Client.socket.on 'task', (task)->
console.log 'GOT TASK', task
action = require "../tasks/#{task.opts.action}"
console.log 'action', action
action(task.opts)
module.exports = Future
| true | #
# PI:NAME:<NAME>END_PI
# 2015
#
Future = require('future-client')
Client = Future.Client
Client.connect()
Client.socket.on 'task', (task)->
console.log 'GOT TASK', task
action = require "../tasks/#{task.opts.action}"
console.log 'action', action
action(task.opts)
module.exports = Future
|
[
{
"context": "allback) =>\n App.User.create firstName: \"Lance\", (error, record) =>\n user = record\n ",
"end": 680,
"score": 0.9996236562728882,
"start": 675,
"tag": "NAME",
"value": "Lance"
},
{
"context": " (done) ->\n # App.User.create firstName: \"Lance\", (error, user) =>\n # user.dependentMem",
"end": 4840,
"score": 0.999618411064148,
"start": 4835,
"tag": "NAME",
"value": "Lance"
},
{
"context": " (done) ->\n user.groups().create {name: \"Starbucks\"}, {}, done\n \n test 'update all gro",
"end": 7905,
"score": 0.8612496256828308,
"start": 7896,
"tag": "NAME",
"value": "Starbucks"
},
{
"context": ", (done) ->\n user.groups().update name: \"Peet's\", =>\n user.groups().all (error, groups",
"end": 8015,
"score": 0.7318703532218933,
"start": 8009,
"tag": "NAME",
"value": "Peet's"
},
{
"context": " assert.equal group.get('name'), \"Peet's\"\n done()\n \n te",
"end": 8201,
"score": 0.6059509515762329,
"start": 8199,
"tag": "NAME",
"value": "et"
},
{
"context": "', (done) ->\n user.groups().where(name: \"Starbucks\").update name: \"Peet's\", =>\n user.grou",
"end": 8336,
"score": 0.7851092219352722,
"start": 8327,
"tag": "NAME",
"value": "Starbucks"
},
{
"context": "r.groups().where(name: \"Starbucks\").update name: \"Peet's\", =>\n user.groups().where(name: \"Peet'",
"end": 8359,
"score": 0.6247755885124207,
"start": 8353,
"tag": "NAME",
"value": "Peet's"
},
{
"context": "eet's\", =>\n user.groups().where(name: \"Peet's\").count (error, count) =>\n assert.eq",
"end": 8410,
"score": 0.6725339889526367,
"start": 8404,
"tag": "NAME",
"value": "Peet's"
},
{
"context": " (done) ->\n user.groups().create {name: \"Starbucks\"}, {}, done\n \n test 'destroy all gr",
"end": 8705,
"score": 0.8725324273109436,
"start": 8696,
"tag": "NAME",
"value": "Starbucks"
}
] | test/cases/model/relationTest.coffee | vjsingh/tower | 1 | require '../../config'
membership = null
group = null
user = null
_.toS = (array) ->
_.map array, (item) -> item.toString()
describeWith = (store) ->
describe 'Tower.Model.Relation', ->
beforeEach (done) ->
async.series [
(callback) =>
store.clean(callback)
(callback) =>
# maybe the store should be global...
App.Child.store(store)
App.Parent.store(store)
App.User.store(store)
App.Membership.store(store)
App.DependentMembership.store(store)
App.Group.store(store)
callback()
(callback) =>
App.User.create firstName: "Lance", (error, record) =>
user = record
callback()
(callback) =>
App.Group.create (error, record) =>
group = record
callback()
], done
afterEach ->
try App.Parent.create.restore()
try App.Group.create.restore()
try App.Membership.create.restore()
describe 'inverseOf', ->
test 'noInverse_noInverse', ->
assert.notEqual "noInverse_noInverse", try App.Parent.relation("noInverse_noInverse").inverse().name
test 'parent: noInverse_withInverse, child: withInverse_noInverse', ->
assert.equal "withInverse_noInverse", App.Parent.relation("noInverse_withInverse").inverse().name
test 'withInverse_withInverse', ->
assert.equal "withInverse_withInverse", App.Parent.relation("withInverse_withInverse").inverse().name
test 'parent: withInverse_noInverse, child: noInverse_withInverse', ->
assert.equal "noInverse_withInverse", App.Parent.relation("withInverse_noInverse").inverse().name
describe 'HasMany', ->
describe '.create', ->
test 'compileForCreate', ->
criteria = user.memberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'compileForCreate with cache: true', ->
criteria = user.cachedMemberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { }
test 'compileForCreate on polymorphic record', ->
criteria = user.polymorphicMemberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { joinableId: user.get('id'), joinableType: "User" }
test 'create relationship model', (done) ->
user.memberships().create groupId: group.get('id'), (error, membership) =>
assert.equal membership.get('userId').toString(), user.get('id').toString()
assert.equal membership.get('groupId').toString(), group.get('id').toString()
done()
#test 'create through model automatically', (done) ->
# sinon.spy App.Group.store(), "create"
# sinon.spy App.Membership.store(), "create"
#
# user.groups().create (error, group) =>
# #console.log App.Membership.store().create
# done()
describe '.update', ->
beforeEach (done) ->
App.Membership.create groupId: group.get('id'), =>
user.memberships().create groupId: group.get('id'), done
test 'compileForUpdate', ->
criteria = user.memberships().criteria
criteria.compileForUpdate()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'update relationship model', (done) ->
user.memberships().update kind: "guest", (error, memberships) =>
assert.equal memberships.length, 1
assert.equal memberships[0].get('kind'), 'guest'
App.Membership.count (error, count) =>
assert.equal count, 2
done()
describe '.destroy', ->
beforeEach (done) ->
App.Membership.create groupId: group.get('id'), =>
user.memberships().create groupId: group.get('id'), done
test 'compileForDestroy', ->
criteria = user.memberships().criteria
criteria.compileForDestroy()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'destroy relationship model', (done) ->
user.memberships().destroy (error, memberships) =>
assert.equal memberships.length, 1
App.Membership.count (error, count) =>
# since there were 2, but only one belonged to user
assert.equal count, 1
done()
#test 'destroy relationship model if parent is destroyed (dependent: true)', (done) ->
# App.User.create firstName: "Lance", (error, user) =>
# user.dependentMemberships().create =>
# user.destroy =>
# App.DependentMembership.count (error, count) =>
# assert.equal count, 0
# done()
describe 'HasMany(through: true)', ->
describe '.create', ->
# don't want it to have any data b/c all that data is stored on the relationship model.
test 'compileForCreate', ->
criteria = user.groups().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { }
test 'throughRelation', ->
criteria = user.groups().criteria
relation = criteria.relation
throughRelation = criteria.throughRelation
assert.equal throughRelation.type, "Membership"
assert.equal throughRelation.targetType, "Membership"
assert.equal throughRelation.name, "memberships"
assert.equal throughRelation.ownerType, "App.User"
assert.equal throughRelation.foreignKey, "userId"
inverseRelation = relation.inverseThrough(throughRelation)
assert.equal inverseRelation.name, "group"
assert.equal inverseRelation.type, "Group"
assert.equal inverseRelation.foreignKey, "groupId"
test 'createThroughRelation', (done) ->
criteria = user.groups().criteria
criteria.createThroughRelation group, (error, record) =>
assert.equal record.constructor.name, "Membership"
assert.equal record.get('groupId').toString(), group.get('id').toString()
assert.equal record.get('userId').toString(), user.get('id').toString()
done()
test 'all together now, create through model', (done) ->
user.groups().create (error, group) =>
#assert.equal group.get('id'), 2
user.memberships().all (error, memberships) =>
assert.equal memberships.length, 1
record = memberships[0]
assert.equal record.get('groupId').toString(), group.get('id').toString()
assert.equal record.get('userId').toString(), user.get('id').toString()
user.groups().all (error, groups) =>
assert.equal groups.length, 1
done()
test 'create 2 models and 2 through models as Arguments', (done) ->
user.groups().create {}, {}, (error, groups) =>
assert.equal groups.length, 2
App.Group.count (error, count) =>
assert.equal count, 3
user.memberships().count (error, count) =>
assert.equal count, 2
user.groups().count (error, count) =>
assert.equal count, 2
done()
describe '.update', ->
beforeEach (done) ->
user.groups().create {name: "Starbucks"}, {}, done
test 'update all groups', (done) ->
user.groups().update name: "Peet's", =>
user.groups().all (error, groups) =>
assert.equal groups.length, 2
for group in groups
assert.equal group.get('name'), "Peet's"
done()
test 'update matching groups', (done) ->
user.groups().where(name: "Starbucks").update name: "Peet's", =>
user.groups().where(name: "Peet's").count (error, count) =>
assert.equal count, 1
user.memberships().count (error, count) =>
assert.equal count, 2
done()
describe '.destroy', ->
beforeEach (done) ->
user.groups().create {name: "Starbucks"}, {}, done
test 'destroy all groups', (done) ->
user.groups().destroy =>
user.groups().count (error, count) =>
assert.equal count, 0
done()
#describe 'through relation has dependent: "destroy"', ->
# test 'destroy all through relations', (done) ->
# user.groups().destroy =>
# user.memberships().count (error, count) =>
# assert.equal count, 0
# done()
describe '.find', ->
beforeEach (done) ->
App.Group.create =>
App.Membership.create =>
user.memberships().create groupId: group.get('id'), (error, record) =>
membership = record
done()
test 'appendThroughConditions', (done) ->
criteria = user.groups().criteria
assert.deepEqual criteria.conditions(), { }
criteria.appendThroughConditions =>
assert.deepEqual criteria.conditions(), { id: $in: [group.get('id')] }
done()
describe 'finders', ->
beforeEach (done) ->
App.Group.create =>
App.Membership.create =>
user.groups().create {name: "A"}, {name: "B"}, {name: "C"}, done
describe 'relation (groups)', ->
test 'all', (done) ->
user.groups().all (error, records) =>
assert.equal records.length, 3
done()
test 'first', (done) ->
user.groups().desc("name").first (error, record) =>
assert.equal record.get('name'), "C"
done()
test 'last', (done) ->
user.groups().desc("name").last (error, record) =>
assert.equal record.get('name'), "A"
done()
test 'count', (done) ->
user.groups().count (error, count) =>
assert.equal count, 3
done()
test 'exists', (done) ->
user.groups().exists (error, value) =>
assert.equal value, true
done()
describe 'through relation (memberships)', ->
test 'all', (done) ->
user.memberships().all (error, records) =>
assert.equal records.length, 3
done()
test 'first', (done) ->
user.memberships().first (error, record) =>
assert.ok record
done()
test 'last', (done) ->
user.memberships().last (error, record) =>
assert.ok record
done()
test 'count', (done) ->
user.memberships().count (error, count) =>
assert.equal count, 3
done()
test 'exists', (done) ->
user.memberships().exists (error, value) =>
assert.equal value, true
done()
describe 'hasMany with idCache', ->
parent = null
beforeEach (done) ->
async.series [
(next) => App.Parent.create (error, record) =>
parent = record
next()
], done
describe 'Parent.idCacheTrue_idCacheFalse', ->
criteria = null
relation = null
beforeEach ->
relation = App.Parent.relations().idCacheTrue_idCacheFalse
criteria = parent.idCacheTrue_idCacheFalse().criteria
test 'relation', ->
assert.equal relation.idCache, true
assert.equal relation.idCacheKey, "idCacheTrue_idCacheFalse" + "Ids"
test 'default for idCacheKey should be array', ->
assert.ok _.isArray App.Parent.fields()[relation.idCacheKey]._default
test 'compileForCreate', (done) ->
criteria.compileForCreate()
# not sure if we want this or not... { parentId: parent.get('id') }
assert.deepEqual criteria.conditions(), { }
done()
test 'updateOwnerRecord', ->
assert.equal criteria.updateOwnerRecord(), true
test 'ownerAttributes', (done) ->
child = new App.Child(id: 20)
assert.deepEqual criteria.ownerAttributes(child), { '$addToSet': { idCacheTrue_idCacheFalseIds: child.get('id') } }
done()
describe 'persistence', ->
child = null
child2 = null
child3 = null
beforeEach (done) ->
async.series [
(next) =>
parent.idCacheTrue_idCacheFalse().create (error, record) =>
child = record
next()
(next) =>
parent.idCacheTrue_idCacheFalse().create (error, record) =>
child2 = record
next()
(next) =>
# create one without a parent at all
App.Child.create (error, record) =>
child3 = record
next()
(next) =>
App.Parent.find parent.get('id'), (error, record) =>
parent = record
next()
], done
test 'create', (done) ->
assert.equal child.get('parentId'), null
assert.deepEqual parent.get(relation.idCacheKey), [child.get('id'), child2.get('id')]
done()
test 'update(1)', (done) ->
parent.idCacheTrue_idCacheFalse().update child.get('id'), value: "something", =>
App.Child.find child.get('id'), (error, child) =>
assert.equal child.get('value'), 'something'
App.Child.find child2.get('id'), (error, child) =>
assert.equal child.get('value'), null
done()
test 'update()', (done) ->
parent.idCacheTrue_idCacheFalse().update value: "something", =>
App.Child.find child.get('id'), (error, child) =>
assert.equal child.get('value'), 'something'
App.Child.find child3.get('id'), (error, child) =>
assert.equal child.get('value'), null
done()
test 'destroy(1)', (done) ->
parent.idCacheTrue_idCacheFalse().destroy child.get('id'), =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual parent.get(relation.idCacheKey), [child2.get('id')]
App.Child.all (error, records) =>
assert.equal records.length, 2
done()
test 'destroy()', (done) ->
parent.idCacheTrue_idCacheFalse().destroy =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual parent.get(relation.idCacheKey), []
App.Child.all (error, records) =>
assert.equal records.length, 1
done()
test 'all', (done) ->
parent.idCacheTrue_idCacheFalse().all (error, records) =>
assert.equal records.length, 2
done()
test 'add to set', (done) ->
App.Child.create (error, newChild) =>
parent.idCacheTrue_idCacheFalse().add newChild, =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual _.toS(parent.get(relation.idCacheKey)), _.toS([child.get('id'), child2.get('id'), newChild.get('id')])
App.Child.all (error, records) =>
assert.equal records.length, 4
done()
#test 'remove from set', (done) ->
# parent.idCacheTrue_idCacheFalse().remove child, =>
# App.Parent.find parent.get('id'), (error, parent) =>
# assert.deepEqual _.toS(parent.get(relation.idCacheKey)), _.toS([child.get('id'), newChild.get('id')])
#
# App.Child.all (error, records) =>
# assert.equal records.length, 3
# done()
#describe 'inverseOf', ->
# test 'add to set', (done) ->
# App.Child.create (error, child) =>
# child.idCacheFalse_idCacheTrue
describeWith(Tower.Store.Memory)
describeWith(Tower.Store.MongoDB) | 3162 | require '../../config'
membership = null
group = null
user = null
_.toS = (array) ->
_.map array, (item) -> item.toString()
describeWith = (store) ->
describe 'Tower.Model.Relation', ->
beforeEach (done) ->
async.series [
(callback) =>
store.clean(callback)
(callback) =>
# maybe the store should be global...
App.Child.store(store)
App.Parent.store(store)
App.User.store(store)
App.Membership.store(store)
App.DependentMembership.store(store)
App.Group.store(store)
callback()
(callback) =>
App.User.create firstName: "<NAME>", (error, record) =>
user = record
callback()
(callback) =>
App.Group.create (error, record) =>
group = record
callback()
], done
afterEach ->
try App.Parent.create.restore()
try App.Group.create.restore()
try App.Membership.create.restore()
describe 'inverseOf', ->
test 'noInverse_noInverse', ->
assert.notEqual "noInverse_noInverse", try App.Parent.relation("noInverse_noInverse").inverse().name
test 'parent: noInverse_withInverse, child: withInverse_noInverse', ->
assert.equal "withInverse_noInverse", App.Parent.relation("noInverse_withInverse").inverse().name
test 'withInverse_withInverse', ->
assert.equal "withInverse_withInverse", App.Parent.relation("withInverse_withInverse").inverse().name
test 'parent: withInverse_noInverse, child: noInverse_withInverse', ->
assert.equal "noInverse_withInverse", App.Parent.relation("withInverse_noInverse").inverse().name
describe 'HasMany', ->
describe '.create', ->
test 'compileForCreate', ->
criteria = user.memberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'compileForCreate with cache: true', ->
criteria = user.cachedMemberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { }
test 'compileForCreate on polymorphic record', ->
criteria = user.polymorphicMemberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { joinableId: user.get('id'), joinableType: "User" }
test 'create relationship model', (done) ->
user.memberships().create groupId: group.get('id'), (error, membership) =>
assert.equal membership.get('userId').toString(), user.get('id').toString()
assert.equal membership.get('groupId').toString(), group.get('id').toString()
done()
#test 'create through model automatically', (done) ->
# sinon.spy App.Group.store(), "create"
# sinon.spy App.Membership.store(), "create"
#
# user.groups().create (error, group) =>
# #console.log App.Membership.store().create
# done()
describe '.update', ->
beforeEach (done) ->
App.Membership.create groupId: group.get('id'), =>
user.memberships().create groupId: group.get('id'), done
test 'compileForUpdate', ->
criteria = user.memberships().criteria
criteria.compileForUpdate()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'update relationship model', (done) ->
user.memberships().update kind: "guest", (error, memberships) =>
assert.equal memberships.length, 1
assert.equal memberships[0].get('kind'), 'guest'
App.Membership.count (error, count) =>
assert.equal count, 2
done()
describe '.destroy', ->
beforeEach (done) ->
App.Membership.create groupId: group.get('id'), =>
user.memberships().create groupId: group.get('id'), done
test 'compileForDestroy', ->
criteria = user.memberships().criteria
criteria.compileForDestroy()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'destroy relationship model', (done) ->
user.memberships().destroy (error, memberships) =>
assert.equal memberships.length, 1
App.Membership.count (error, count) =>
# since there were 2, but only one belonged to user
assert.equal count, 1
done()
#test 'destroy relationship model if parent is destroyed (dependent: true)', (done) ->
# App.User.create firstName: "<NAME>", (error, user) =>
# user.dependentMemberships().create =>
# user.destroy =>
# App.DependentMembership.count (error, count) =>
# assert.equal count, 0
# done()
describe 'HasMany(through: true)', ->
describe '.create', ->
# don't want it to have any data b/c all that data is stored on the relationship model.
test 'compileForCreate', ->
criteria = user.groups().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { }
test 'throughRelation', ->
criteria = user.groups().criteria
relation = criteria.relation
throughRelation = criteria.throughRelation
assert.equal throughRelation.type, "Membership"
assert.equal throughRelation.targetType, "Membership"
assert.equal throughRelation.name, "memberships"
assert.equal throughRelation.ownerType, "App.User"
assert.equal throughRelation.foreignKey, "userId"
inverseRelation = relation.inverseThrough(throughRelation)
assert.equal inverseRelation.name, "group"
assert.equal inverseRelation.type, "Group"
assert.equal inverseRelation.foreignKey, "groupId"
test 'createThroughRelation', (done) ->
criteria = user.groups().criteria
criteria.createThroughRelation group, (error, record) =>
assert.equal record.constructor.name, "Membership"
assert.equal record.get('groupId').toString(), group.get('id').toString()
assert.equal record.get('userId').toString(), user.get('id').toString()
done()
test 'all together now, create through model', (done) ->
user.groups().create (error, group) =>
#assert.equal group.get('id'), 2
user.memberships().all (error, memberships) =>
assert.equal memberships.length, 1
record = memberships[0]
assert.equal record.get('groupId').toString(), group.get('id').toString()
assert.equal record.get('userId').toString(), user.get('id').toString()
user.groups().all (error, groups) =>
assert.equal groups.length, 1
done()
test 'create 2 models and 2 through models as Arguments', (done) ->
user.groups().create {}, {}, (error, groups) =>
assert.equal groups.length, 2
App.Group.count (error, count) =>
assert.equal count, 3
user.memberships().count (error, count) =>
assert.equal count, 2
user.groups().count (error, count) =>
assert.equal count, 2
done()
describe '.update', ->
beforeEach (done) ->
user.groups().create {name: "<NAME>"}, {}, done
test 'update all groups', (done) ->
user.groups().update name: "<NAME>", =>
user.groups().all (error, groups) =>
assert.equal groups.length, 2
for group in groups
assert.equal group.get('name'), "Pe<NAME>'s"
done()
test 'update matching groups', (done) ->
user.groups().where(name: "<NAME>").update name: "<NAME>", =>
user.groups().where(name: "<NAME>").count (error, count) =>
assert.equal count, 1
user.memberships().count (error, count) =>
assert.equal count, 2
done()
describe '.destroy', ->
beforeEach (done) ->
user.groups().create {name: "<NAME>"}, {}, done
test 'destroy all groups', (done) ->
user.groups().destroy =>
user.groups().count (error, count) =>
assert.equal count, 0
done()
#describe 'through relation has dependent: "destroy"', ->
# test 'destroy all through relations', (done) ->
# user.groups().destroy =>
# user.memberships().count (error, count) =>
# assert.equal count, 0
# done()
describe '.find', ->
beforeEach (done) ->
App.Group.create =>
App.Membership.create =>
user.memberships().create groupId: group.get('id'), (error, record) =>
membership = record
done()
test 'appendThroughConditions', (done) ->
criteria = user.groups().criteria
assert.deepEqual criteria.conditions(), { }
criteria.appendThroughConditions =>
assert.deepEqual criteria.conditions(), { id: $in: [group.get('id')] }
done()
describe 'finders', ->
beforeEach (done) ->
App.Group.create =>
App.Membership.create =>
user.groups().create {name: "A"}, {name: "B"}, {name: "C"}, done
describe 'relation (groups)', ->
test 'all', (done) ->
user.groups().all (error, records) =>
assert.equal records.length, 3
done()
test 'first', (done) ->
user.groups().desc("name").first (error, record) =>
assert.equal record.get('name'), "C"
done()
test 'last', (done) ->
user.groups().desc("name").last (error, record) =>
assert.equal record.get('name'), "A"
done()
test 'count', (done) ->
user.groups().count (error, count) =>
assert.equal count, 3
done()
test 'exists', (done) ->
user.groups().exists (error, value) =>
assert.equal value, true
done()
describe 'through relation (memberships)', ->
test 'all', (done) ->
user.memberships().all (error, records) =>
assert.equal records.length, 3
done()
test 'first', (done) ->
user.memberships().first (error, record) =>
assert.ok record
done()
test 'last', (done) ->
user.memberships().last (error, record) =>
assert.ok record
done()
test 'count', (done) ->
user.memberships().count (error, count) =>
assert.equal count, 3
done()
test 'exists', (done) ->
user.memberships().exists (error, value) =>
assert.equal value, true
done()
describe 'hasMany with idCache', ->
parent = null
beforeEach (done) ->
async.series [
(next) => App.Parent.create (error, record) =>
parent = record
next()
], done
describe 'Parent.idCacheTrue_idCacheFalse', ->
criteria = null
relation = null
beforeEach ->
relation = App.Parent.relations().idCacheTrue_idCacheFalse
criteria = parent.idCacheTrue_idCacheFalse().criteria
test 'relation', ->
assert.equal relation.idCache, true
assert.equal relation.idCacheKey, "idCacheTrue_idCacheFalse" + "Ids"
test 'default for idCacheKey should be array', ->
assert.ok _.isArray App.Parent.fields()[relation.idCacheKey]._default
test 'compileForCreate', (done) ->
criteria.compileForCreate()
# not sure if we want this or not... { parentId: parent.get('id') }
assert.deepEqual criteria.conditions(), { }
done()
test 'updateOwnerRecord', ->
assert.equal criteria.updateOwnerRecord(), true
test 'ownerAttributes', (done) ->
child = new App.Child(id: 20)
assert.deepEqual criteria.ownerAttributes(child), { '$addToSet': { idCacheTrue_idCacheFalseIds: child.get('id') } }
done()
describe 'persistence', ->
child = null
child2 = null
child3 = null
beforeEach (done) ->
async.series [
(next) =>
parent.idCacheTrue_idCacheFalse().create (error, record) =>
child = record
next()
(next) =>
parent.idCacheTrue_idCacheFalse().create (error, record) =>
child2 = record
next()
(next) =>
# create one without a parent at all
App.Child.create (error, record) =>
child3 = record
next()
(next) =>
App.Parent.find parent.get('id'), (error, record) =>
parent = record
next()
], done
test 'create', (done) ->
assert.equal child.get('parentId'), null
assert.deepEqual parent.get(relation.idCacheKey), [child.get('id'), child2.get('id')]
done()
test 'update(1)', (done) ->
parent.idCacheTrue_idCacheFalse().update child.get('id'), value: "something", =>
App.Child.find child.get('id'), (error, child) =>
assert.equal child.get('value'), 'something'
App.Child.find child2.get('id'), (error, child) =>
assert.equal child.get('value'), null
done()
test 'update()', (done) ->
parent.idCacheTrue_idCacheFalse().update value: "something", =>
App.Child.find child.get('id'), (error, child) =>
assert.equal child.get('value'), 'something'
App.Child.find child3.get('id'), (error, child) =>
assert.equal child.get('value'), null
done()
test 'destroy(1)', (done) ->
parent.idCacheTrue_idCacheFalse().destroy child.get('id'), =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual parent.get(relation.idCacheKey), [child2.get('id')]
App.Child.all (error, records) =>
assert.equal records.length, 2
done()
test 'destroy()', (done) ->
parent.idCacheTrue_idCacheFalse().destroy =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual parent.get(relation.idCacheKey), []
App.Child.all (error, records) =>
assert.equal records.length, 1
done()
test 'all', (done) ->
parent.idCacheTrue_idCacheFalse().all (error, records) =>
assert.equal records.length, 2
done()
test 'add to set', (done) ->
App.Child.create (error, newChild) =>
parent.idCacheTrue_idCacheFalse().add newChild, =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual _.toS(parent.get(relation.idCacheKey)), _.toS([child.get('id'), child2.get('id'), newChild.get('id')])
App.Child.all (error, records) =>
assert.equal records.length, 4
done()
#test 'remove from set', (done) ->
# parent.idCacheTrue_idCacheFalse().remove child, =>
# App.Parent.find parent.get('id'), (error, parent) =>
# assert.deepEqual _.toS(parent.get(relation.idCacheKey)), _.toS([child.get('id'), newChild.get('id')])
#
# App.Child.all (error, records) =>
# assert.equal records.length, 3
# done()
#describe 'inverseOf', ->
# test 'add to set', (done) ->
# App.Child.create (error, child) =>
# child.idCacheFalse_idCacheTrue
describeWith(Tower.Store.Memory)
describeWith(Tower.Store.MongoDB) | true | require '../../config'
membership = null
group = null
user = null
_.toS = (array) ->
_.map array, (item) -> item.toString()
describeWith = (store) ->
describe 'Tower.Model.Relation', ->
beforeEach (done) ->
async.series [
(callback) =>
store.clean(callback)
(callback) =>
# maybe the store should be global...
App.Child.store(store)
App.Parent.store(store)
App.User.store(store)
App.Membership.store(store)
App.DependentMembership.store(store)
App.Group.store(store)
callback()
(callback) =>
App.User.create firstName: "PI:NAME:<NAME>END_PI", (error, record) =>
user = record
callback()
(callback) =>
App.Group.create (error, record) =>
group = record
callback()
], done
afterEach ->
try App.Parent.create.restore()
try App.Group.create.restore()
try App.Membership.create.restore()
describe 'inverseOf', ->
test 'noInverse_noInverse', ->
assert.notEqual "noInverse_noInverse", try App.Parent.relation("noInverse_noInverse").inverse().name
test 'parent: noInverse_withInverse, child: withInverse_noInverse', ->
assert.equal "withInverse_noInverse", App.Parent.relation("noInverse_withInverse").inverse().name
test 'withInverse_withInverse', ->
assert.equal "withInverse_withInverse", App.Parent.relation("withInverse_withInverse").inverse().name
test 'parent: withInverse_noInverse, child: noInverse_withInverse', ->
assert.equal "noInverse_withInverse", App.Parent.relation("withInverse_noInverse").inverse().name
describe 'HasMany', ->
describe '.create', ->
test 'compileForCreate', ->
criteria = user.memberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'compileForCreate with cache: true', ->
criteria = user.cachedMemberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { }
test 'compileForCreate on polymorphic record', ->
criteria = user.polymorphicMemberships().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { joinableId: user.get('id'), joinableType: "User" }
test 'create relationship model', (done) ->
user.memberships().create groupId: group.get('id'), (error, membership) =>
assert.equal membership.get('userId').toString(), user.get('id').toString()
assert.equal membership.get('groupId').toString(), group.get('id').toString()
done()
#test 'create through model automatically', (done) ->
# sinon.spy App.Group.store(), "create"
# sinon.spy App.Membership.store(), "create"
#
# user.groups().create (error, group) =>
# #console.log App.Membership.store().create
# done()
describe '.update', ->
beforeEach (done) ->
App.Membership.create groupId: group.get('id'), =>
user.memberships().create groupId: group.get('id'), done
test 'compileForUpdate', ->
criteria = user.memberships().criteria
criteria.compileForUpdate()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'update relationship model', (done) ->
user.memberships().update kind: "guest", (error, memberships) =>
assert.equal memberships.length, 1
assert.equal memberships[0].get('kind'), 'guest'
App.Membership.count (error, count) =>
assert.equal count, 2
done()
describe '.destroy', ->
beforeEach (done) ->
App.Membership.create groupId: group.get('id'), =>
user.memberships().create groupId: group.get('id'), done
test 'compileForDestroy', ->
criteria = user.memberships().criteria
criteria.compileForDestroy()
assert.deepEqual criteria.conditions(), { userId: user.get('id') }
test 'destroy relationship model', (done) ->
user.memberships().destroy (error, memberships) =>
assert.equal memberships.length, 1
App.Membership.count (error, count) =>
# since there were 2, but only one belonged to user
assert.equal count, 1
done()
#test 'destroy relationship model if parent is destroyed (dependent: true)', (done) ->
# App.User.create firstName: "PI:NAME:<NAME>END_PI", (error, user) =>
# user.dependentMemberships().create =>
# user.destroy =>
# App.DependentMembership.count (error, count) =>
# assert.equal count, 0
# done()
describe 'HasMany(through: true)', ->
describe '.create', ->
# don't want it to have any data b/c all that data is stored on the relationship model.
test 'compileForCreate', ->
criteria = user.groups().criteria
criteria.compileForCreate()
assert.deepEqual criteria.conditions(), { }
test 'throughRelation', ->
criteria = user.groups().criteria
relation = criteria.relation
throughRelation = criteria.throughRelation
assert.equal throughRelation.type, "Membership"
assert.equal throughRelation.targetType, "Membership"
assert.equal throughRelation.name, "memberships"
assert.equal throughRelation.ownerType, "App.User"
assert.equal throughRelation.foreignKey, "userId"
inverseRelation = relation.inverseThrough(throughRelation)
assert.equal inverseRelation.name, "group"
assert.equal inverseRelation.type, "Group"
assert.equal inverseRelation.foreignKey, "groupId"
test 'createThroughRelation', (done) ->
criteria = user.groups().criteria
criteria.createThroughRelation group, (error, record) =>
assert.equal record.constructor.name, "Membership"
assert.equal record.get('groupId').toString(), group.get('id').toString()
assert.equal record.get('userId').toString(), user.get('id').toString()
done()
test 'all together now, create through model', (done) ->
user.groups().create (error, group) =>
#assert.equal group.get('id'), 2
user.memberships().all (error, memberships) =>
assert.equal memberships.length, 1
record = memberships[0]
assert.equal record.get('groupId').toString(), group.get('id').toString()
assert.equal record.get('userId').toString(), user.get('id').toString()
user.groups().all (error, groups) =>
assert.equal groups.length, 1
done()
test 'create 2 models and 2 through models as Arguments', (done) ->
user.groups().create {}, {}, (error, groups) =>
assert.equal groups.length, 2
App.Group.count (error, count) =>
assert.equal count, 3
user.memberships().count (error, count) =>
assert.equal count, 2
user.groups().count (error, count) =>
assert.equal count, 2
done()
describe '.update', ->
beforeEach (done) ->
user.groups().create {name: "PI:NAME:<NAME>END_PI"}, {}, done
test 'update all groups', (done) ->
user.groups().update name: "PI:NAME:<NAME>END_PI", =>
user.groups().all (error, groups) =>
assert.equal groups.length, 2
for group in groups
assert.equal group.get('name'), "PePI:NAME:<NAME>END_PI's"
done()
test 'update matching groups', (done) ->
user.groups().where(name: "PI:NAME:<NAME>END_PI").update name: "PI:NAME:<NAME>END_PI", =>
user.groups().where(name: "PI:NAME:<NAME>END_PI").count (error, count) =>
assert.equal count, 1
user.memberships().count (error, count) =>
assert.equal count, 2
done()
describe '.destroy', ->
beforeEach (done) ->
user.groups().create {name: "PI:NAME:<NAME>END_PI"}, {}, done
test 'destroy all groups', (done) ->
user.groups().destroy =>
user.groups().count (error, count) =>
assert.equal count, 0
done()
#describe 'through relation has dependent: "destroy"', ->
# test 'destroy all through relations', (done) ->
# user.groups().destroy =>
# user.memberships().count (error, count) =>
# assert.equal count, 0
# done()
describe '.find', ->
beforeEach (done) ->
App.Group.create =>
App.Membership.create =>
user.memberships().create groupId: group.get('id'), (error, record) =>
membership = record
done()
test 'appendThroughConditions', (done) ->
criteria = user.groups().criteria
assert.deepEqual criteria.conditions(), { }
criteria.appendThroughConditions =>
assert.deepEqual criteria.conditions(), { id: $in: [group.get('id')] }
done()
describe 'finders', ->
beforeEach (done) ->
App.Group.create =>
App.Membership.create =>
user.groups().create {name: "A"}, {name: "B"}, {name: "C"}, done
describe 'relation (groups)', ->
test 'all', (done) ->
user.groups().all (error, records) =>
assert.equal records.length, 3
done()
test 'first', (done) ->
user.groups().desc("name").first (error, record) =>
assert.equal record.get('name'), "C"
done()
test 'last', (done) ->
user.groups().desc("name").last (error, record) =>
assert.equal record.get('name'), "A"
done()
test 'count', (done) ->
user.groups().count (error, count) =>
assert.equal count, 3
done()
test 'exists', (done) ->
user.groups().exists (error, value) =>
assert.equal value, true
done()
describe 'through relation (memberships)', ->
test 'all', (done) ->
user.memberships().all (error, records) =>
assert.equal records.length, 3
done()
test 'first', (done) ->
user.memberships().first (error, record) =>
assert.ok record
done()
test 'last', (done) ->
user.memberships().last (error, record) =>
assert.ok record
done()
test 'count', (done) ->
user.memberships().count (error, count) =>
assert.equal count, 3
done()
test 'exists', (done) ->
user.memberships().exists (error, value) =>
assert.equal value, true
done()
describe 'hasMany with idCache', ->
parent = null
beforeEach (done) ->
async.series [
(next) => App.Parent.create (error, record) =>
parent = record
next()
], done
describe 'Parent.idCacheTrue_idCacheFalse', ->
criteria = null
relation = null
beforeEach ->
relation = App.Parent.relations().idCacheTrue_idCacheFalse
criteria = parent.idCacheTrue_idCacheFalse().criteria
test 'relation', ->
assert.equal relation.idCache, true
assert.equal relation.idCacheKey, "idCacheTrue_idCacheFalse" + "Ids"
test 'default for idCacheKey should be array', ->
assert.ok _.isArray App.Parent.fields()[relation.idCacheKey]._default
test 'compileForCreate', (done) ->
criteria.compileForCreate()
# not sure if we want this or not... { parentId: parent.get('id') }
assert.deepEqual criteria.conditions(), { }
done()
test 'updateOwnerRecord', ->
assert.equal criteria.updateOwnerRecord(), true
test 'ownerAttributes', (done) ->
child = new App.Child(id: 20)
assert.deepEqual criteria.ownerAttributes(child), { '$addToSet': { idCacheTrue_idCacheFalseIds: child.get('id') } }
done()
describe 'persistence', ->
child = null
child2 = null
child3 = null
beforeEach (done) ->
async.series [
(next) =>
parent.idCacheTrue_idCacheFalse().create (error, record) =>
child = record
next()
(next) =>
parent.idCacheTrue_idCacheFalse().create (error, record) =>
child2 = record
next()
(next) =>
# create one without a parent at all
App.Child.create (error, record) =>
child3 = record
next()
(next) =>
App.Parent.find parent.get('id'), (error, record) =>
parent = record
next()
], done
test 'create', (done) ->
assert.equal child.get('parentId'), null
assert.deepEqual parent.get(relation.idCacheKey), [child.get('id'), child2.get('id')]
done()
test 'update(1)', (done) ->
parent.idCacheTrue_idCacheFalse().update child.get('id'), value: "something", =>
App.Child.find child.get('id'), (error, child) =>
assert.equal child.get('value'), 'something'
App.Child.find child2.get('id'), (error, child) =>
assert.equal child.get('value'), null
done()
test 'update()', (done) ->
parent.idCacheTrue_idCacheFalse().update value: "something", =>
App.Child.find child.get('id'), (error, child) =>
assert.equal child.get('value'), 'something'
App.Child.find child3.get('id'), (error, child) =>
assert.equal child.get('value'), null
done()
test 'destroy(1)', (done) ->
parent.idCacheTrue_idCacheFalse().destroy child.get('id'), =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual parent.get(relation.idCacheKey), [child2.get('id')]
App.Child.all (error, records) =>
assert.equal records.length, 2
done()
test 'destroy()', (done) ->
parent.idCacheTrue_idCacheFalse().destroy =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual parent.get(relation.idCacheKey), []
App.Child.all (error, records) =>
assert.equal records.length, 1
done()
test 'all', (done) ->
parent.idCacheTrue_idCacheFalse().all (error, records) =>
assert.equal records.length, 2
done()
test 'add to set', (done) ->
App.Child.create (error, newChild) =>
parent.idCacheTrue_idCacheFalse().add newChild, =>
App.Parent.find parent.get('id'), (error, parent) =>
assert.deepEqual _.toS(parent.get(relation.idCacheKey)), _.toS([child.get('id'), child2.get('id'), newChild.get('id')])
App.Child.all (error, records) =>
assert.equal records.length, 4
done()
#test 'remove from set', (done) ->
# parent.idCacheTrue_idCacheFalse().remove child, =>
# App.Parent.find parent.get('id'), (error, parent) =>
# assert.deepEqual _.toS(parent.get(relation.idCacheKey)), _.toS([child.get('id'), newChild.get('id')])
#
# App.Child.all (error, records) =>
# assert.equal records.length, 3
# done()
#describe 'inverseOf', ->
# test 'add to set', (done) ->
# App.Child.create (error, child) =>
# child.idCacheFalse_idCacheTrue
describeWith(Tower.Store.Memory)
describeWith(Tower.Store.MongoDB) |
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998559951782227,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/widgets/actionbutton.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.halloactionbutton',
button: null
isChecked: false
options:
uuid: ''
label: null
icon: null
editable: null
command: null
queryState: true
cssClass: null
_create: ->
# By default the icon is icon-command, but this doesn't
# always match with <http://fortawesome.github.com/Font-Awesome/#base-icons>
#@options.icon ?= "icon-#{@options.label.toLowerCase()}"
@options.text = false
@options.icons = { "primary": "ui-icon-#{@options.command}-p" }
id = "#{@options.uuid}-#{@options.label}"
@button = @_createButton id, @options.command, @options.label, @options.icon
@element.append @button
@button.button {"icons": @options.icons,"text": false}
@button.addClass @options.cssClass if @options.cssClass
@button.addClass 'btn-large' if @options.editable.options.touchScreen
@button.data 'hallo-command', @options.command
hoverclass = 'ui-state-hover'
@button.bind 'mouseenter', (event) =>
if @isEnabled()
@button.addClass hoverclass
@button.bind 'mouseleave', (event) =>
@button.removeClass hoverclass
_init: ->
@button = @_prepareButton() unless @button
@element.append @button
queryState = (event) =>
return unless @options.command
try
if ( @options.command == 'spellcheck' )
@checked @options.editable.element[0].spellcheck
else
@checked document.queryCommandState @options.command
catch e
return
if @options.action
@button.bind 'click', (event) =>
jQuery('.misspelled').remove()
@options.action(event)
queryState
return false
return unless @options.queryState
editableElement = @options.editable.element
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'halloenabled', =>
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'hallodisabled', =>
editableElement.unbind 'keyup paste change mouseup hallomodified', queryState
enable: ->
@button.removeAttr 'disabled'
disable: ->
@button.attr 'disabled', 'true'
isEnabled: ->
return @button.attr('disabled') != 'true'
refresh: ->
if @isChecked
@button.addClass 'ui-state-active_'
else
@button.removeClass 'ui-state-active_'
checked: (checked) ->
@isChecked = checked
@refresh()
_createButton: (id, command, label, icon) ->
button_str = "<button for=\"#{id}\""
button_str+= " class=\"#{command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " title=\"#{label}\""
button_str+= " rel=\"#{command}\""
button_str+= "></button>"
buttonEl = jQuery button_str
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
# could we switch this somehow?
# jQuery "<button for=\"#{id}\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only #{command}_button\" title=\"#{label}\"><span class=\"ui-button-text\"><i class=\"#{icon}\"></i></span></button>"
)(jQuery) | 133736 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.halloactionbutton',
button: null
isChecked: false
options:
uuid: ''
label: null
icon: null
editable: null
command: null
queryState: true
cssClass: null
_create: ->
# By default the icon is icon-command, but this doesn't
# always match with <http://fortawesome.github.com/Font-Awesome/#base-icons>
#@options.icon ?= "icon-#{@options.label.toLowerCase()}"
@options.text = false
@options.icons = { "primary": "ui-icon-#{@options.command}-p" }
id = "#{@options.uuid}-#{@options.label}"
@button = @_createButton id, @options.command, @options.label, @options.icon
@element.append @button
@button.button {"icons": @options.icons,"text": false}
@button.addClass @options.cssClass if @options.cssClass
@button.addClass 'btn-large' if @options.editable.options.touchScreen
@button.data 'hallo-command', @options.command
hoverclass = 'ui-state-hover'
@button.bind 'mouseenter', (event) =>
if @isEnabled()
@button.addClass hoverclass
@button.bind 'mouseleave', (event) =>
@button.removeClass hoverclass
_init: ->
@button = @_prepareButton() unless @button
@element.append @button
queryState = (event) =>
return unless @options.command
try
if ( @options.command == 'spellcheck' )
@checked @options.editable.element[0].spellcheck
else
@checked document.queryCommandState @options.command
catch e
return
if @options.action
@button.bind 'click', (event) =>
jQuery('.misspelled').remove()
@options.action(event)
queryState
return false
return unless @options.queryState
editableElement = @options.editable.element
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'halloenabled', =>
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'hallodisabled', =>
editableElement.unbind 'keyup paste change mouseup hallomodified', queryState
enable: ->
@button.removeAttr 'disabled'
disable: ->
@button.attr 'disabled', 'true'
isEnabled: ->
return @button.attr('disabled') != 'true'
refresh: ->
if @isChecked
@button.addClass 'ui-state-active_'
else
@button.removeClass 'ui-state-active_'
checked: (checked) ->
@isChecked = checked
@refresh()
_createButton: (id, command, label, icon) ->
button_str = "<button for=\"#{id}\""
button_str+= " class=\"#{command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " title=\"#{label}\""
button_str+= " rel=\"#{command}\""
button_str+= "></button>"
buttonEl = jQuery button_str
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
# could we switch this somehow?
# jQuery "<button for=\"#{id}\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only #{command}_button\" title=\"#{label}\"><span class=\"ui-button-text\"><i class=\"#{icon}\"></i></span></button>"
)(jQuery) | true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.halloactionbutton',
button: null
isChecked: false
options:
uuid: ''
label: null
icon: null
editable: null
command: null
queryState: true
cssClass: null
_create: ->
# By default the icon is icon-command, but this doesn't
# always match with <http://fortawesome.github.com/Font-Awesome/#base-icons>
#@options.icon ?= "icon-#{@options.label.toLowerCase()}"
@options.text = false
@options.icons = { "primary": "ui-icon-#{@options.command}-p" }
id = "#{@options.uuid}-#{@options.label}"
@button = @_createButton id, @options.command, @options.label, @options.icon
@element.append @button
@button.button {"icons": @options.icons,"text": false}
@button.addClass @options.cssClass if @options.cssClass
@button.addClass 'btn-large' if @options.editable.options.touchScreen
@button.data 'hallo-command', @options.command
hoverclass = 'ui-state-hover'
@button.bind 'mouseenter', (event) =>
if @isEnabled()
@button.addClass hoverclass
@button.bind 'mouseleave', (event) =>
@button.removeClass hoverclass
_init: ->
@button = @_prepareButton() unless @button
@element.append @button
queryState = (event) =>
return unless @options.command
try
if ( @options.command == 'spellcheck' )
@checked @options.editable.element[0].spellcheck
else
@checked document.queryCommandState @options.command
catch e
return
if @options.action
@button.bind 'click', (event) =>
jQuery('.misspelled').remove()
@options.action(event)
queryState
return false
return unless @options.queryState
editableElement = @options.editable.element
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'halloenabled', =>
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'hallodisabled', =>
editableElement.unbind 'keyup paste change mouseup hallomodified', queryState
enable: ->
@button.removeAttr 'disabled'
disable: ->
@button.attr 'disabled', 'true'
isEnabled: ->
return @button.attr('disabled') != 'true'
refresh: ->
if @isChecked
@button.addClass 'ui-state-active_'
else
@button.removeClass 'ui-state-active_'
checked: (checked) ->
@isChecked = checked
@refresh()
_createButton: (id, command, label, icon) ->
button_str = "<button for=\"#{id}\""
button_str+= " class=\"#{command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " title=\"#{label}\""
button_str+= " rel=\"#{command}\""
button_str+= "></button>"
buttonEl = jQuery button_str
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
# could we switch this somehow?
# jQuery "<button for=\"#{id}\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only #{command}_button\" title=\"#{label}\"><span class=\"ui-button-text\"><i class=\"#{icon}\"></i></span></button>"
)(jQuery) |
[
{
"context": "n\": 1, \"Exod\": 2, \"Lev\": 3, \"Num\": 4, \"Deut\": 5, \"Josh\": 6, \"Judg\": 7, \"Ruth\": 8, \"1Sam\": 9, \"2Sam\": 10,",
"end": 330,
"score": 0.8423445224761963,
"start": 326,
"tag": "NAME",
"value": "Josh"
},
{
"context": "\": 3, \"Num\": 4, \"Deut\": 5, \"Josh\": 6, \"Judg\": 7, \"Ruth\": 8, \"1Sam\": 9, \"2Sam\": 10, \"1Kgs\": 11, \"2Kgs\": 1",
"end": 352,
"score": 0.6215524077415466,
"start": 348,
"tag": "NAME",
"value": "Ruth"
},
{
"context": " \"1Kgs\": 11, \"2Kgs\": 12, \"1Chr\": 13, \"2Chr\": 14, \"Ezra\": 15, \"Neh\": 16, \"Esth\": 17, \"Job\": 18, \"Ps\": 19,",
"end": 434,
"score": 0.8171721696853638,
"start": 430,
"tag": "NAME",
"value": "Ezra"
},
{
"context": " \"2Kgs\": 12, \"1Chr\": 13, \"2Chr\": 14, \"Ezra\": 15, \"Neh\": 16, \"Esth\": 17, \"Job\": 18, \"Ps\": 19, \"Prov\": 20",
"end": 445,
"score": 0.7976799011230469,
"start": 442,
"tag": "NAME",
"value": "Neh"
},
{
"context": ", \"1Chr\": 13, \"2Chr\": 14, \"Ezra\": 15, \"Neh\": 16, \"Esth\": 17, \"Job\": 18, \"Ps\": 19, \"Prov\": 20, \"Eccl\": 21",
"end": 457,
"score": 0.6551540493965149,
"start": 453,
"tag": "NAME",
"value": "Esth"
},
{
"context": "8, \"Ps\": 19, \"Prov\": 20, \"Eccl\": 21, \"Song\": 22, \"Isa\": 23, \"Jer\": 24, \"Lam\": 25, \"Ezek\": 26, \"Dan\": 27",
"end": 525,
"score": 0.7085932493209839,
"start": 522,
"tag": "NAME",
"value": "Isa"
},
{
"context": ", \"Prov\": 20, \"Eccl\": 21, \"Song\": 22, \"Isa\": 23, \"Jer\": 24, \"Lam\": 25, \"Ezek\": 26, \"Dan\": 27, \"Hos\": 28",
"end": 536,
"score": 0.6676025390625,
"start": 533,
"tag": "NAME",
"value": "Jer"
},
{
"context": "21, \"Song\": 22, \"Isa\": 23, \"Jer\": 24, \"Lam\": 25, \"Ezek\": 26, \"Dan\": 27, \"Hos\": 28, \"Joel\": 29, \"Amos\": 3",
"end": 559,
"score": 0.7577743530273438,
"start": 555,
"tag": "NAME",
"value": "Ezek"
},
{
"context": "22, \"Isa\": 23, \"Jer\": 24, \"Lam\": 25, \"Ezek\": 26, \"Dan\": 27, \"Hos\": 28, \"Joel\": 29, \"Amos\": 30, \"Obad\": ",
"end": 570,
"score": 0.9681554436683655,
"start": 567,
"tag": "NAME",
"value": "Dan"
},
{
"context": "23, \"Jer\": 24, \"Lam\": 25, \"Ezek\": 26, \"Dan\": 27, \"Hos\": 28, \"Joel\": 29, \"Amos\": 30, \"Obad\": 31, \"Jonah\"",
"end": 581,
"score": 0.7780907154083252,
"start": 578,
"tag": "NAME",
"value": "Hos"
},
{
"context": "24, \"Lam\": 25, \"Ezek\": 26, \"Dan\": 27, \"Hos\": 28, \"Joel\": 29, \"Amos\": 30, \"Obad\": 31, \"Jonah\": 32, \"Mic\":",
"end": 593,
"score": 0.9543957710266113,
"start": 589,
"tag": "NAME",
"value": "Joel"
},
{
"context": "5, \"Ezek\": 26, \"Dan\": 27, \"Hos\": 28, \"Joel\": 29, \"Amos\": 30, \"Obad\": 31, \"Jonah\": 32, \"Mic\": 33, \"Nah\": ",
"end": 605,
"score": 0.9537649154663086,
"start": 601,
"tag": "NAME",
"value": "Amos"
},
{
"context": ", \"Hos\": 28, \"Joel\": 29, \"Amos\": 30, \"Obad\": 31, \"Jonah\": 32, \"Mic\": 33, \"Nah\": 34, \"Hab\": 35, \"Zeph\": 36",
"end": 630,
"score": 0.9720232486724854,
"start": 625,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "\"Joel\": 29, \"Amos\": 30, \"Obad\": 31, \"Jonah\": 32, \"Mic\": 33, \"Nah\": 34, \"Hab\": 35, \"Zeph\": 36, \"Hag\": 37",
"end": 641,
"score": 0.9595990777015686,
"start": 638,
"tag": "NAME",
"value": "Mic"
},
{
"context": " \"Amos\": 30, \"Obad\": 31, \"Jonah\": 32, \"Mic\": 33, \"Nah\": 34, \"Hab\": 35, \"Zeph\": 36, \"Hag\": 37, \"Zech\": 3",
"end": 652,
"score": 0.7875972986221313,
"start": 649,
"tag": "NAME",
"value": "Nah"
},
{
"context": "1, \"Jonah\": 32, \"Mic\": 33, \"Nah\": 34, \"Hab\": 35, \"Zeph\": 36, \"Hag\": 37, \"Zech\": 38, \"Mal\": 39, \"Matt\": 4",
"end": 675,
"score": 0.6886234283447266,
"start": 671,
"tag": "NAME",
"value": "Zeph"
},
{
"context": "32, \"Mic\": 33, \"Nah\": 34, \"Hab\": 35, \"Zeph\": 36, \"Hag\": 37, \"Zech\": 38, \"Mal\": 39, \"Matt\": 40, \"Mark\": ",
"end": 686,
"score": 0.7453076839447021,
"start": 683,
"tag": "NAME",
"value": "Hag"
},
{
"context": "5, \"Zeph\": 36, \"Hag\": 37, \"Zech\": 38, \"Mal\": 39, \"Matt\": 40, \"Mark\": 41, \"Luke\": 42, \"John\": 43, \"Acts\":",
"end": 721,
"score": 0.9595212340354919,
"start": 717,
"tag": "NAME",
"value": "Matt"
},
{
"context": "6, \"Hag\": 37, \"Zech\": 38, \"Mal\": 39, \"Matt\": 40, \"Mark\": 41, \"Luke\": 42, \"John\": 43, \"Acts\": 44, \"Rom\": ",
"end": 733,
"score": 0.9673516750335693,
"start": 729,
"tag": "NAME",
"value": "Mark"
},
{
"context": ", \"Zech\": 38, \"Mal\": 39, \"Matt\": 40, \"Mark\": 41, \"Luke\": 42, \"John\": 43, \"Acts\": 44, \"Rom\": 45, \"1Cor\": ",
"end": 745,
"score": 0.9121519327163696,
"start": 741,
"tag": "NAME",
"value": "Luke"
},
{
"context": ", \"Mal\": 39, \"Matt\": 40, \"Mark\": 41, \"Luke\": 42, \"John\": 43, \"Acts\": 44, \"Rom\": 45, \"1Cor\": 46, \"2Cor\": ",
"end": 757,
"score": 0.9178474545478821,
"start": 753,
"tag": "NAME",
"value": "John"
},
{
"context": "4, \"Rom\": 45, \"1Cor\": 46, \"2Cor\": 47, \"Gal\": 48, \"Eph\": 49, \"Phil\": 50, \"Col\": 51, \"1Thess\": 52, \"2Thes",
"end": 826,
"score": 0.6202398538589478,
"start": 823,
"tag": "NAME",
"value": "Eph"
},
{
"context": "5, \"1Cor\": 46, \"2Cor\": 47, \"Gal\": 48, \"Eph\": 49, \"Phil\": 50, \"Col\": 51, \"1Thess\": 52, \"2Thess\": 53, \"1Ti",
"end": 838,
"score": 0.7550227642059326,
"start": 834,
"tag": "NAME",
"value": "Phil"
},
{
"context": "hess\": 52, \"2Thess\": 53, \"1Tim\": 54, \"2Tim\": 55, \"Titus\": 56, \"Phlm\": 57, \"Heb\": 58, \"Jas\": 59, \"1Pet\": 6",
"end": 914,
"score": 0.6259822845458984,
"start": 909,
"tag": "NAME",
"value": "Titus"
},
{
"context": " \"2Tim\": 55, \"Titus\": 56, \"Phlm\": 57, \"Heb\": 58, \"Jas\": 59, \"1Pet\": 60, \"2Pet\": 61, \"1John\": 62, \"2John",
"end": 948,
"score": 0.6102697849273682,
"start": 945,
"tag": "NAME",
"value": "Jas"
},
{
"context": "Pet\": 61, \"1John\": 62, \"2John\": 63, \"3John\": 64, \"Jude\": 65, \"Rev\": 66, \"Tob\": 67, \"Jdt\": 68, \"GkEsth\": ",
"end": 1023,
"score": 0.6036783456802368,
"start": 1019,
"tag": "NAME",
"value": "Jude"
},
{
"context": "41,30,25,18,65,23,31,40,16,54,42,56,29,34,13]\n\t\t\t\"Deut\": [46,37,29,49,33,25,26,20,29,22,32,32,18,29,23,2",
"end": 1789,
"score": 0.7715519070625305,
"start": 1785,
"tag": "NAME",
"value": "Deut"
},
{
"context": "20,23,30,25,22,19,19,26,68,29,20,30,52,29,12]\n\t\t\t\"Josh\": [18,24,17,24,15,27,26,35,27,43,23,24,33,15,63,1",
"end": 1904,
"score": 0.9223624467849731,
"start": 1900,
"tag": "NAME",
"value": "Josh"
},
{
"context": ",43,23,24,33,15,63,10,18,28,51,9,45,34,16,33]\n\t\t\t\"Judg\": [36,23,31,24,31,40,25,35,57,18,40,15,25,20,20,3",
"end": 1988,
"score": 0.8839961886405945,
"start": 1984,
"tag": "NAME",
"value": "Judg"
},
{
"context": "25,35,57,18,40,15,25,20,20,31,13,31,30,48,25]\n\t\t\t\"Ruth\": [22,23,18,22]\n\t\t\t\"1Sam\": [28,36,21,22,12,21,17,",
"end": 2064,
"score": 0.7953260540962219,
"start": 2060,
"tag": "NAME",
"value": "Ruth"
},
{
"context": "15,12,17,13,12,21,14,21,22,11,12,19,12,25,24]\n\t\t\t\"Jer\": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,2",
"end": 3745,
"score": 0.9782229661941528,
"start": 3742,
"tag": "NAME",
"value": "Jer"
},
{
"context": "1,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]\n\t\t\t\"Lam\": [22,22,66,22,22]\n\t\t\t\"Ezek\": [28,10,27,17,17,14,",
"end": 3911,
"score": 0.9766004085540771,
"start": 3908,
"tag": "NAME",
"value": "Lam"
},
{
"context": ",7,47,39,46,64,34]\n\t\t\t\"Lam\": [22,22,66,22,22]\n\t\t\t\"Ezek\": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63",
"end": 3939,
"score": 0.9984890818595886,
"start": 3935,
"tag": "NAME",
"value": "Ezek"
},
{
"context": "31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]\n\t\t\t\"Dan\": [21,49,30,37,31,28,28,27,27,21,45,13]\n\t\t\t\"Hos\":",
"end": 4094,
"score": 0.9992566704750061,
"start": 4091,
"tag": "NAME",
"value": "Dan"
},
{
"context": "\t\"Dan\": [21,49,30,37,31,28,28,27,27,21,45,13]\n\t\t\t\"Hos\": [11,23,5,19,15,11,16,14,17,15,12,14,16,9]\n\t\t\t\"J",
"end": 4142,
"score": 0.9543228149414062,
"start": 4139,
"tag": "NAME",
"value": "Hos"
},
{
"context": "s\": [11,23,5,19,15,11,16,14,17,15,12,14,16,9]\n\t\t\t\"Joel\": [20,32,21]\n\t\t\t\"Amos\": [15,16,15,13,27,14,17,14,",
"end": 4195,
"score": 0.9960546493530273,
"start": 4191,
"tag": "NAME",
"value": "Joel"
},
{
"context": "16,14,17,15,12,14,16,9]\n\t\t\t\"Joel\": [20,32,21]\n\t\t\t\"Amos\": [15,16,15,13,27,14,17,14,15]\n\t\t\t\"Obad\": [21]\n\t\t",
"end": 4217,
"score": 0.9739891290664673,
"start": 4213,
"tag": "NAME",
"value": "Amos"
},
{
"context": "2,21]\n\t\t\t\"Amos\": [15,16,15,13,27,14,17,14,15]\n\t\t\t\"Obad\": [21]\n\t\t\t\"Jonah\": [17,10,10,11]\n\t\t\t\"Mic\": [16,13",
"end": 4257,
"score": 0.9958442449569702,
"start": 4253,
"tag": "NAME",
"value": "Obad"
},
{
"context": " [15,16,15,13,27,14,17,14,15]\n\t\t\t\"Obad\": [21]\n\t\t\t\"Jonah\": [17,10,10,11]\n\t\t\t\"Mic\": [16,13,12,13,15,16,20]\n",
"end": 4274,
"score": 0.9969210624694824,
"start": 4269,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "15]\n\t\t\t\"Obad\": [21]\n\t\t\t\"Jonah\": [17,10,10,11]\n\t\t\t\"Mic\": [16,13,12,13,15,16,20]\n\t\t\t\"Nah\": [15,13,19]\n\t\t\t",
"end": 4298,
"score": 0.9943275451660156,
"start": 4295,
"tag": "NAME",
"value": "Mic"
},
{
"context": "17,10,10,11]\n\t\t\t\"Mic\": [16,13,12,13,15,16,20]\n\t\t\t\"Nah\": [15,13,19]\n\t\t\t\"Hab\": [17,20,19]\n\t\t\t\"Zeph\": [18,",
"end": 4331,
"score": 0.9130817651748657,
"start": 4328,
"tag": "NAME",
"value": "Nah"
},
{
"context": ": [16,13,12,13,15,16,20]\n\t\t\t\"Nah\": [15,13,19]\n\t\t\t\"Hab\": [17,20,19]\n\t\t\t\"Zeph\": [18,15,20]\n\t\t\t\"Hag\": [15,",
"end": 4352,
"score": 0.7463047504425049,
"start": 4349,
"tag": "NAME",
"value": "Hab"
},
{
"context": "20]\n\t\t\t\"Nah\": [15,13,19]\n\t\t\t\"Hab\": [17,20,19]\n\t\t\t\"Zeph\": [18,15,20]\n\t\t\t\"Hag\": [15,23]\n\t\t\t\"Zech\": [21,13,",
"end": 4374,
"score": 0.8593950271606445,
"start": 4370,
"tag": "NAME",
"value": "Zeph"
},
{
"context": "9]\n\t\t\t\"Hab\": [17,20,19]\n\t\t\t\"Zeph\": [18,15,20]\n\t\t\t\"Hag\": [15,23]\n\t\t\t\"Zech\": [21,13,10,14,11,15,14,23,17,",
"end": 4395,
"score": 0.8152865171432495,
"start": 4392,
"tag": "NAME",
"value": "Hag"
},
{
"context": "0,19]\n\t\t\t\"Zeph\": [18,15,20]\n\t\t\t\"Hag\": [15,23]\n\t\t\t\"Zech\": [21,13,10,14,11,15,14,23,17,12,17,14,9,21]\n\t\t\t\"",
"end": 4414,
"score": 0.8204600811004639,
"start": 4410,
"tag": "NAME",
"value": "Zech"
},
{
"context": "4,23,17,12,17,14,9,21]\n\t\t\t\"Mal\": [14,17,18,6]\n\t\t\t\"Matt\": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,2",
"end": 4491,
"score": 0.9543755650520325,
"start": 4487,
"tag": "NAME",
"value": "Matt"
},
{
"context": "36,39,28,27,35,30,34,46,46,39,51,46,75,66,20]\n\t\t\t\"Mark\": [45,28,35,41,43,56,37,38,50,52,33,44,37,72,47,2",
"end": 4588,
"score": 0.9977117776870728,
"start": 4584,
"tag": "NAME",
"value": "Mark"
},
{
"context": "28,35,41,43,56,37,38,50,52,33,44,37,72,47,20]\n\t\t\t\"Luke\": [80,52,38,44,39,49,50,56,62,42,54,59,35,35,32,3",
"end": 4649,
"score": 0.8895555734634399,
"start": 4645,
"tag": "NAME",
"value": "Luke"
},
{
"context": "42,54,59,35,35,32,31,37,43,48,47,38,71,56,53]\n\t\t\t\"John\": [51,25,36,54,47,71,53,59,41,42,57,50,38,31,27,3",
"end": 4734,
"score": 0.9980543851852417,
"start": 4730,
"tag": "NAME",
"value": "John"
},
{
"context": "0,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]\n\t\t\t\"Ezek\": [28,9,27,17,17,14,27,18,11,22,25,28,23,23,8,63,",
"end": 8385,
"score": 0.8219309449195862,
"start": 8381,
"tag": "NAME",
"value": "Ezek"
},
{
"context": "31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]\n\t\t\t\"Dan\": [21,49,100,34,31,28,28,27,27,21,45,13,65,42]\n\t\t",
"end": 8539,
"score": 0.9966891407966614,
"start": 8536,
"tag": "NAME",
"value": "Dan"
},
{
"context": " [21,49,100,34,31,28,28,27,27,21,45,13,65,42]\n\t\t\t\"Hos\": [11,24,5,19,15,11,16,14,17,15,12,14,15,10]\n\t\t\t\"",
"end": 8594,
"score": 0.8382089138031006,
"start": 8591,
"tag": "NAME",
"value": "Hos"
},
{
"context": "\": [11,24,5,19,15,11,16,14,17,15,12,14,15,10]\n\t\t\t\"Amos\": [15,16,15,13,27,15,17,14,14]\n\t\t\t\"Jonah\": [16,11",
"end": 8648,
"score": 0.7572451233863831,
"start": 8644,
"tag": "NAME",
"value": "Amos"
},
{
"context": "5,10]\n\t\t\t\"Amos\": [15,16,15,13,27,15,17,14,14]\n\t\t\t\"Jonah\": [16,11,10,11]\n\t\t\t\"Mic\": [16,13,12,13,14,16,20]\n",
"end": 8689,
"score": 0.9301149845123291,
"start": 8684,
"tag": "NAME",
"value": "Jonah"
},
{
"context": ",13,27,15,17,14,14]\n\t\t\t\"Jonah\": [16,11,10,11]\n\t\t\t\"Mic\": [16,13,12,13,14,16,20]\n\t\t\t\"Hag\": [14,24]\n\t\t\t\"Ma",
"end": 8713,
"score": 0.9951940178871155,
"start": 8710,
"tag": "NAME",
"value": "Mic"
},
{
"context": "16,11,10,11]\n\t\t\t\"Mic\": [16,13,12,13,14,16,20]\n\t\t\t\"Hag\": [14,24]\n\t\t\t\"Matt\": [25,23,17,25,48,34,29,34,38,",
"end": 8746,
"score": 0.8040593862533569,
"start": 8743,
"tag": "NAME",
"value": "Hag"
},
{
"context": "ic\": [16,13,12,13,14,16,20]\n\t\t\t\"Hag\": [14,24]\n\t\t\t\"Matt\": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,2",
"end": 8765,
"score": 0.7980276346206665,
"start": 8761,
"tag": "NAME",
"value": "Matt"
},
{
"context": "36,39,28,26,35,30,34,46,46,39,51,46,75,66,20]\n\t\t\t\"Mark\": [45,28,35,40,43,56,37,39,49,52,33,44,37,72,47,2",
"end": 8862,
"score": 0.9941381812095642,
"start": 8858,
"tag": "NAME",
"value": "Mark"
},
{
"context": "n\": 1, \"Exod\": 2, \"Lev\": 3, \"Num\": 4, \"Deut\": 5, \"Josh\": 6, \"Judg\": 7, \"Ruth\": 8, \"1Sam\": 9, \"2Sam\": 10,",
"end": 10103,
"score": 0.8323280811309814,
"start": 10099,
"tag": "NAME",
"value": "Josh"
},
{
"context": "\"2Kgs\": 12, \"1Chr\": 13, \"2Chr\": 14, \"PrMan\": 15, \"Ezra\": 16, \"Neh\": 17, \"1Esd\": 18, \"2Esd\": 19, \"Tob\": 2",
"end": 10220,
"score": 0.7619500160217285,
"start": 10216,
"tag": "NAME",
"value": "Ezra"
},
{
"context": "\"1Chr\": 13, \"2Chr\": 14, \"PrMan\": 15, \"Ezra\": 16, \"Neh\": 17, \"1Esd\": 18, \"2Esd\": 19, \"Tob\": 20, \"Jdt\": 2",
"end": 10231,
"score": 0.5243434906005859,
"start": 10228,
"tag": "NAME",
"value": "Neh"
},
{
"context": "0, \"Eccl\": 31, \"Song\": 32, \"Wis\": 33, \"Sir\": 34, \"Isa\": 35, \"Jer\": 36, \"Lam\": 37, \"Bar\": 38, \"EpJer\": 3",
"end": 10445,
"score": 0.6285207271575928,
"start": 10442,
"tag": "NAME",
"value": "Isa"
},
{
"context": "5, \"Jer\": 36, \"Lam\": 37, \"Bar\": 38, \"EpJer\": 39, \"Ezek\": 40, \"Dan\": 41, \"PrAzar\": 42, \"Sus\": 43, \"Bel\": ",
"end": 10503,
"score": 0.5767474174499512,
"start": 10499,
"tag": "NAME",
"value": "Ezek"
},
{
"context": ", \"Lam\": 37, \"Bar\": 38, \"EpJer\": 39, \"Ezek\": 40, \"Dan\": 41, \"PrAzar\": 42, \"Sus\": 43, \"Bel\": 44, \"SgThre",
"end": 10514,
"score": 0.8994872570037842,
"start": 10511,
"tag": "NAME",
"value": "Dan"
},
{
"context": "\"Bar\": 38, \"EpJer\": 39, \"Ezek\": 40, \"Dan\": 41, \"PrAzar\": 42, \"Sus\": 43, \"Bel\": 44, \"SgThree\": 45, \"Hos\":",
"end": 10528,
"score": 0.5254359245300293,
"start": 10524,
"tag": "NAME",
"value": "Azar"
},
{
"context": "EpJer\": 39, \"Ezek\": 40, \"Dan\": 41, \"PrAzar\": 42, \"Sus\": 43, \"Bel\": 44, \"SgThree\": 45, \"Hos\": 46, \"Joel\"",
"end": 10539,
"score": 0.7578369379043579,
"start": 10536,
"tag": "NAME",
"value": "Sus"
},
{
"context": "rAzar\": 42, \"Sus\": 43, \"Bel\": 44, \"SgThree\": 45, \"Hos\": 46, \"Joel\": 47, \"Amos\": 48, \"Obad\": 49, \"Jonah\"",
"end": 10576,
"score": 0.678678035736084,
"start": 10573,
"tag": "NAME",
"value": "Hos"
},
{
"context": " \"Sus\": 43, \"Bel\": 44, \"SgThree\": 45, \"Hos\": 46, \"Joel\": 47, \"Amos\": 48, \"Obad\": 49, \"Jonah\": 50, \"Mic\":",
"end": 10588,
"score": 0.9376505613327026,
"start": 10584,
"tag": "NAME",
"value": "Joel"
},
{
"context": "\"Bel\": 44, \"SgThree\": 45, \"Hos\": 46, \"Joel\": 47, \"Amos\": 48, \"Obad\": 49, \"Jonah\": 50, \"Mic\": 51, \"Nah\": ",
"end": 10600,
"score": 0.840169370174408,
"start": 10596,
"tag": "NAME",
"value": "Amos"
},
{
"context": ", \"Hos\": 46, \"Joel\": 47, \"Amos\": 48, \"Obad\": 49, \"Jonah\": 50, \"Mic\": 51, \"Nah\": 52, \"Hab\": 53, \"Zeph\": 54",
"end": 10625,
"score": 0.971860408782959,
"start": 10620,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "\"Joel\": 47, \"Amos\": 48, \"Obad\": 49, \"Jonah\": 50, \"Mic\": 51, \"Nah\": 52, \"Hab\": 53, \"Zeph\": 54, \"Hag\": 55",
"end": 10636,
"score": 0.8103215098381042,
"start": 10633,
"tag": "NAME",
"value": "Mic"
},
{
"context": "9, \"Jonah\": 50, \"Mic\": 51, \"Nah\": 52, \"Hab\": 53, \"Zeph\": 54, \"Hag\": 55, \"Zech\": 56, \"Mal\": 57, \"Matt\": 5",
"end": 10670,
"score": 0.7319335341453552,
"start": 10666,
"tag": "NAME",
"value": "Zeph"
},
{
"context": "50, \"Mic\": 51, \"Nah\": 52, \"Hab\": 53, \"Zeph\": 54, \"Hag\": 55, \"Zech\": 56, \"Mal\": 57, \"Matt\": 58, \"Mark\": ",
"end": 10681,
"score": 0.6409615278244019,
"start": 10678,
"tag": "NAME",
"value": "Hag"
},
{
"context": "3, \"Zeph\": 54, \"Hag\": 55, \"Zech\": 56, \"Mal\": 57, \"Matt\": 58, \"Mark\": 59, \"Luke\": 60, \"John\": 61, \"Acts\":",
"end": 10716,
"score": 0.9790107011795044,
"start": 10712,
"tag": "NAME",
"value": "Matt"
},
{
"context": "4, \"Hag\": 55, \"Zech\": 56, \"Mal\": 57, \"Matt\": 58, \"Mark\": 59, \"Luke\": 60, \"John\": 61, \"Acts\": 62, \"Rom\": ",
"end": 10728,
"score": 0.9883863925933838,
"start": 10724,
"tag": "NAME",
"value": "Mark"
},
{
"context": ", \"Zech\": 56, \"Mal\": 57, \"Matt\": 58, \"Mark\": 59, \"Luke\": 60, \"John\": 61, \"Acts\": 62, \"Rom\": 63, \"1Cor\": ",
"end": 10740,
"score": 0.906348466873169,
"start": 10736,
"tag": "NAME",
"value": "Luke"
},
{
"context": ", \"Mal\": 57, \"Matt\": 58, \"Mark\": 59, \"Luke\": 60, \"John\": 61, \"Acts\": 62, \"Rom\": 63, \"1Cor\": 64, \"2Cor\": ",
"end": 10752,
"score": 0.9774163961410522,
"start": 10748,
"tag": "NAME",
"value": "John"
},
{
"context": "2, \"Rom\": 63, \"1Cor\": 64, \"2Cor\": 65, \"Gal\": 66, \"Eph\": 67, \"Phil\": 68, \"Col\": 69, \"1Thess\": 70, \"2Thes",
"end": 10821,
"score": 0.9791450500488281,
"start": 10818,
"tag": "NAME",
"value": "Eph"
},
{
"context": "3, \"1Cor\": 64, \"2Cor\": 65, \"Gal\": 66, \"Eph\": 67, \"Phil\": 68, \"Col\": 69, \"1Thess\": 70, \"2Thess\": 71, \"1Ti",
"end": 10833,
"score": 0.969751238822937,
"start": 10829,
"tag": "NAME",
"value": "Phil"
},
{
"context": "4, \"2Cor\": 65, \"Gal\": 66, \"Eph\": 67, \"Phil\": 68, \"Col\": 69, \"1Thess\": 70, \"2Thess\": 71, \"1Tim\": 72, \"2T",
"end": 10844,
"score": 0.8991681337356567,
"start": 10841,
"tag": "NAME",
"value": "Col"
},
{
"context": "5, \"Gal\": 66, \"Eph\": 67, \"Phil\": 68, \"Col\": 69, \"1Thess\": 70, \"2Thess\": 71, \"1Tim\": 72, \"2Tim\": 73, \"Titu",
"end": 10858,
"score": 0.5733073949813843,
"start": 10853,
"tag": "NAME",
"value": "Thess"
},
{
"context": "\"Eph\": 67, \"Phil\": 68, \"Col\": 69, \"1Thess\": 70, \"2Thess\": 71, \"1Tim\": 72, \"2Tim\": 73, \"Titus\": 74, \"Phlm\"",
"end": 10872,
"score": 0.5797224640846252,
"start": 10867,
"tag": "NAME",
"value": "Thess"
},
{
"context": "il\": 68, \"Col\": 69, \"1Thess\": 70, \"2Thess\": 71, \"1Tim\": 72, \"2Tim\": 73, \"Titus\": 74, \"Phlm\": 75, \"Heb\":",
"end": 10884,
"score": 0.4268709719181061,
"start": 10881,
"tag": "NAME",
"value": "Tim"
},
{
"context": "l\": 69, \"1Thess\": 70, \"2Thess\": 71, \"1Tim\": 72, \"2Tim\": 73, \"Titus\": 74, \"Phlm\": 75, \"Heb\": 76, \"Jas\": ",
"end": 10896,
"score": 0.48505881428718567,
"start": 10893,
"tag": "NAME",
"value": "Tim"
},
{
"context": "hess\": 70, \"2Thess\": 71, \"1Tim\": 72, \"2Tim\": 73, \"Titus\": 74, \"Phlm\": 75, \"Heb\": 76, \"Jas\": 77, \"1Pet\": 7",
"end": 10909,
"score": 0.9051213264465332,
"start": 10904,
"tag": "NAME",
"value": "Titus"
},
{
"context": "Thess\": 71, \"1Tim\": 72, \"2Tim\": 73, \"Titus\": 74, \"Phlm\": 75, \"Heb\": 76, \"Jas\": 77, \"1Pet\": 78, \"2Pet\": 7",
"end": 10921,
"score": 0.7475380897521973,
"start": 10917,
"tag": "NAME",
"value": "Phlm"
},
{
"context": "\"1Tim\": 72, \"2Tim\": 73, \"Titus\": 74, \"Phlm\": 75, \"Heb\": 76, \"Jas\": 77, \"1Pet\": 78, \"2Pet\": 79, \"1John\":",
"end": 10932,
"score": 0.9246286153793335,
"start": 10929,
"tag": "NAME",
"value": "Heb"
},
{
"context": " \"2Tim\": 73, \"Titus\": 74, \"Phlm\": 75, \"Heb\": 76, \"Jas\": 77, \"1Pet\": 78, \"2Pet\": 79, \"1John\": 80, \"2John",
"end": 10943,
"score": 0.9532470703125,
"start": 10940,
"tag": "NAME",
"value": "Jas"
},
{
"context": " \"Titus\": 74, \"Phlm\": 75, \"Heb\": 76, \"Jas\": 77, \"1Pet\": 78, \"2Pet\": 79, \"1John\": 80, \"2John\": 81, \"3Joh",
"end": 10955,
"score": 0.6359276175498962,
"start": 10952,
"tag": "NAME",
"value": "Pet"
},
{
"context": ", \"Phlm\": 75, \"Heb\": 76, \"Jas\": 77, \"1Pet\": 78, \"2Pet\": 79, \"1John\": 80, \"2John\": 81, \"3John\": 82, \"Jud",
"end": 10967,
"score": 0.570819616317749,
"start": 10964,
"tag": "NAME",
"value": "Pet"
},
{
"context": ", \"Heb\": 76, \"Jas\": 77, \"1Pet\": 78, \"2Pet\": 79, \"1John\": 80, \"2John\": 81, \"3John\": 82, \"Jude\": 83, \"Rev\"",
"end": 10980,
"score": 0.41160833835601807,
"start": 10976,
"tag": "NAME",
"value": "John"
},
{
"context": "\"Jas\": 77, \"1Pet\": 78, \"2Pet\": 79, \"1John\": 80, \"2John\": 81, \"3John\": 82, \"Jude\": 83, \"Rev\": 84\n\t\tchapte",
"end": 10993,
"score": 0.43542471528053284,
"start": 10989,
"tag": "NAME",
"value": "John"
},
{
"context": "1Pet\": 78, \"2Pet\": 79, \"1John\": 80, \"2John\": 81, \"3John\": 82, \"Jude\": 83, \"Rev\": 84\n\t\tchapters:\n\t\t\t\"Gen\":",
"end": 11006,
"score": 0.6324236392974854,
"start": 11001,
"tag": "NAME",
"value": "3John"
},
{
"context": "Pet\": 79, \"1John\": 80, \"2John\": 81, \"3John\": 82, \"Jude\": 83, \"Rev\": 84\n\t\tchapters:\n\t\t\t\"Gen\": [31,25,24,2",
"end": 11018,
"score": 0.8942146301269531,
"start": 11014,
"tag": "NAME",
"value": "Jude"
},
{
"context": "15,12,17,13,12,21,14,21,22,11,12,19,11,25,24]\n\t\t\t\"Jer\": [19,37,25,31,31,30,34,23,25,25,23,17,27,22,21,2",
"end": 13146,
"score": 0.9980745315551758,
"start": 13143,
"tag": "NAME",
"value": "Jer"
},
{
"context": "1,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]\n\t\t\t\"Ezek\": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63",
"end": 13313,
"score": 0.9963361620903015,
"start": 13309,
"tag": "NAME",
"value": "Ezek"
},
{
"context": "31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]\n\t\t\t\"Dan\": [21,49,100,34,30,29,28,27,27,21,45,13,64,42]\n\t\t",
"end": 13468,
"score": 0.998824417591095,
"start": 13465,
"tag": "NAME",
"value": "Dan"
},
{
"context": " [21,49,100,34,30,29,28,27,27,21,45,13,64,42]\n\t\t\t\"Hos\": [9,25,5,19,15,11,16,14,17,15,11,15,15,10]\n\t\t\t\"J",
"end": 13523,
"score": 0.979362964630127,
"start": 13520,
"tag": "NAME",
"value": "Hos"
},
{
"context": "s\": [9,25,5,19,15,11,16,14,17,15,11,15,15,10]\n\t\t\t\"Joel\": [20,27,5,21]\n\t\t\t\"Jonah\": [16,11,10,11]\n\t\t\t\"Mic\"",
"end": 13576,
"score": 0.9977221488952637,
"start": 13572,
"tag": "NAME",
"value": "Joel"
},
{
"context": "14,17,15,11,15,15,10]\n\t\t\t\"Joel\": [20,27,5,21]\n\t\t\t\"Jonah\": [16,11,10,11]\n\t\t\t\"Mic\": [16,13,12,14,14,16,20]\n",
"end": 13601,
"score": 0.998670220375061,
"start": 13596,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "Joel\": [20,27,5,21]\n\t\t\t\"Jonah\": [16,11,10,11]\n\t\t\t\"Mic\": [16,13,12,14,14,16,20]\n\t\t\t\"Nah\": [14,14,19]\n\t\t\t",
"end": 13625,
"score": 0.9060078859329224,
"start": 13622,
"tag": "NAME",
"value": "Mic"
},
{
"context": "16,11,10,11]\n\t\t\t\"Mic\": [16,13,12,14,14,16,20]\n\t\t\t\"Nah\": [14,14,19]\n\t\t\t\"Zech\": [17,17,10,14,11,15,14,2",
"end": 13656,
"score": 0.8507212400436401,
"start": 13655,
"tag": "NAME",
"value": "N"
}
] | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/jv/translations.coffee | saiba-mais/bible-lessons | 149 | # When adding a new translation, add it both here and bcv_parser::translations.aliases
bcv_parser::regexps.translations = ///(?:
(?:JVNT)
)\b///gi
bcv_parser::translations =
aliases:
default:
osis: ""
alias: "default"
alternates: {}
default:
order:
"Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "Josh": 6, "Judg": 7, "Ruth": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "Ezra": 15, "Neh": 16, "Esth": 17, "Job": 18, "Ps": 19, "Prov": 20, "Eccl": 21, "Song": 22, "Isa": 23, "Jer": 24, "Lam": 25, "Ezek": 26, "Dan": 27, "Hos": 28, "Joel": 29, "Amos": 30, "Obad": 31, "Jonah": 32, "Mic": 33, "Nah": 34, "Hab": 35, "Zeph": 36, "Hag": 37, "Zech": 38, "Mal": 39, "Matt": 40, "Mark": 41, "Luke": 42, "John": 43, "Acts": 44, "Rom": 45, "1Cor": 46, "2Cor": 47, "Gal": 48, "Eph": 49, "Phil": 50, "Col": 51, "1Thess": 52, "2Thess": 53, "1Tim": 54, "2Tim": 55, "Titus": 56, "Phlm": 57, "Heb": 58, "Jas": 59, "1Pet": 60, "2Pet": 61, "1John": 62, "2John": 63, "3John": 64, "Jude": 65, "Rev": 66, "Tob": 67, "Jdt": 68, "GkEsth": 69, "Wis": 70, "Sir": 71, "Bar": 72, "PrAzar": 73, "Sus": 74, "Bel": 75, "SgThree": 76, "EpJer": 77, "1Macc": 78, "2Macc": 79, "3Macc": 80, "4Macc": 81, "1Esd": 82, "2Esd": 83, "PrMan": 84
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26]
"Exod": [22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38]
"Lev": [17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34]
"Num": [54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,50,13,32,22,29,35,41,30,25,18,65,23,31,40,16,54,42,56,29,34,13]
"Deut": [46,37,29,49,33,25,26,20,29,22,32,32,18,29,23,22,20,22,21,20,23,30,25,22,19,19,26,68,29,20,30,52,29,12]
"Josh": [18,24,17,24,15,27,26,35,27,43,23,24,33,15,63,10,18,28,51,9,45,34,16,33]
"Judg": [36,23,31,24,31,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,25]
"Ruth": [22,23,18,22]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,15,23,29,22,44,25,12,25,11,31,13]
"2Sam": [27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,33,43,26,22,51,39,25]
"1Kgs": [53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,53]
"2Kgs": [18,25,27,44,27,33,20,29,37,36,21,21,25,29,38,20,41,37,37,21,26,20,37,20,30]
"1Chr": [54,55,24,43,26,81,40,40,44,14,47,40,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30]
"2Chr": [17,18,17,22,14,42,22,18,31,19,23,16,22,15,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23]
"Ezra": [11,70,13,24,17,22,28,36,15,44]
"Neh": [11,20,32,23,19,19,73,18,38,39,36,47,31]
"Esth": [22,23,15,17,14,14,10,17,32,3]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,24,34,17]
"Ps": [6,12,8,8,12,10,17,9,20,18,7,8,6,7,5,11,15,50,14,9,13,31,6,10,22,12,14,9,11,12,24,11,22,22,28,12,40,22,13,17,13,11,5,26,17,11,9,14,20,23,19,9,6,7,23,13,11,11,17,12,8,12,11,10,13,20,7,35,36,5,24,20,28,23,10,12,20,72,13,19,16,8,18,12,13,17,7,18,52,17,16,15,5,23,11,13,12,9,9,5,8,28,22,35,45,48,43,13,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,13,10,7,12,15,21,10,20,14,9,6]
"Prov": [33,22,35,27,23,35,27,36,18,32,31,28,25,35,33,33,28,24,29,30,31,29,35,34,28,28,27,28,27,33,31]
"Eccl": [18,26,22,16,20,12,29,17,18,20,10,14]
"Song": [17,17,11,16,16,13,13,14]
"Isa": [31,22,26,6,30,13,25,22,21,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,12,25,24]
"Jer": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"Lam": [22,22,66,22,22]
"Ezek": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"Dan": [21,49,30,37,31,28,28,27,27,21,45,13]
"Hos": [11,23,5,19,15,11,16,14,17,15,12,14,16,9]
"Joel": [20,32,21]
"Amos": [15,16,15,13,27,14,17,14,15]
"Obad": [21]
"Jonah": [17,10,10,11]
"Mic": [16,13,12,13,15,16,20]
"Nah": [15,13,19]
"Hab": [17,20,19]
"Zeph": [18,15,20]
"Hag": [15,23]
"Zech": [21,13,10,14,11,15,14,23,17,12,17,14,9,21]
"Mal": [14,17,18,6]
"Matt": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,27,35,30,34,46,46,39,51,46,75,66,20]
"Mark": [45,28,35,41,43,56,37,38,50,52,33,44,37,72,47,20]
"Luke": [80,52,38,44,39,49,50,56,62,42,54,59,35,35,32,31,37,43,48,47,38,71,56,53]
"John": [51,25,36,54,47,71,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25]
"Acts": [26,47,26,37,42,15,60,40,43,48,30,25,52,28,41,40,34,28,41,38,40,30,35,27,27,32,44,31]
"Rom": [32,29,31,25,21,23,25,39,33,21,36,21,14,23,33,27]
"1Cor": [31,16,23,21,13,20,40,13,27,33,34,31,13,40,58,24]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,14]
"Gal": [24,21,29,31,26,18]
"Eph": [23,22,21,32,33,24]
"Phil": [30,30,21,23]
"Col": [29,23,25,18]
"1Thess": [10,20,13,18,28]
"2Thess": [12,17,18]
"1Tim": [20,15,16,16,25,21]
"2Tim": [18,26,17,22]
"Titus": [16,15,15]
"Phlm": [25]
"Heb": [14,18,19,16,14,20,28,13,28,39,40,29,25]
"Jas": [27,26,18,17,20]
"1Pet": [25,25,22,19,14]
"2Pet": [21,22,18]
"1John": [10,29,24,21,21]
"2John": [13]
"3John": [15]
"Jude": [25]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,17,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,16,21,6,13,18,22,17,15]
"Jdt": [16,28,10,15,24,21,32,36,14,23,23,20,20,19,14,25]
"GkEsth": [22,23,15,17,14,14,10,17,32,13,12,6,18,19,16,24]
"Wis": [16,24,19,20,23,25,30,21,18,21,26,27,19,31,19,29,21,25,22]
"Sir": [30,18,31,31,15,37,36,19,18,31,34,18,26,27,20,30,32,33,30,31,28,27,27,34,26,29,30,26,28,25,31,24,33,31,26,31,31,34,35,30,22,25,33,23,26,20,25,25,16,29,30]
"Bar": [22,35,37,37,9]
"PrAzar": [68]
"Sus": [64]
"Bel": [42]
"SgThree": [39]
"EpJer": [73]
"1Macc": [64,70,60,61,68,63,50,32,73,89,74,53,53,49,41,24]
"2Macc": [36,32,40,50,27,31,42,36,29,38,38,45,26,46,39]
"3Macc": [29,33,30,21,51,41,23]
"4Macc": [35,24,21,26,38,35,23,29,32,21,27,19,27,20,32,25,24,24]
"1Esd": [58,30,24,63,73,34,15,96,55]
"2Esd": [40,48,36,52,56,59,70,63,47,59,46,51,58,48,63,78]
"PrMan": [15]
"Ps151": [7] #Never actually a book--we add this to Psalms if needed.
vulgate:
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,32,25]
"Exod": [22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,36]
"Lev": [17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,45,34]
"Num": [54,34,51,49,31,27,89,26,23,36,34,15,34,45,41,50,13,32,22,30,35,41,30,25,18,65,23,31,39,17,54,42,56,29,34,13]
"Josh": [18,24,17,25,16,27,26,35,27,44,23,24,33,15,63,10,18,28,51,9,43,34,16,33]
"Judg": [36,23,31,24,32,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,24]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,43,15,23,28,23,44,25,12,25,11,31,13]
"1Kgs": [53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,54]
"1Chr": [54,55,24,43,26,81,40,40,44,14,46,40,14,17,29,43,27,17,19,7,30,19,32,31,31,32,34,21,30]
"Neh": [11,20,31,23,19,19,73,18,38,39,36,46,31]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,23,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,35,28,25,16]
"Ps": [6,13,9,10,13,11,18,10,39,8,9,6,7,5,10,15,51,15,10,14,32,6,10,22,12,14,9,11,13,25,11,22,23,28,13,40,23,14,18,14,12,5,26,18,12,10,15,21,23,21,11,7,9,24,13,12,12,18,14,9,13,12,11,14,20,8,36,37,6,24,20,28,23,11,13,21,72,13,20,17,8,19,13,14,17,7,19,53,17,16,16,5,23,11,13,12,9,9,5,8,29,22,35,45,48,43,14,31,7,10,10,9,26,9,10,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,14,10,8,12,15,21,10,11,9,14,9,6]
"Eccl": [18,26,22,17,19,11,30,17,18,20,10,14]
"Song": [16,17,11,16,17,12,13,14]
"Jer": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,20,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"Ezek": [28,9,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"Dan": [21,49,100,34,31,28,28,27,27,21,45,13,65,42]
"Hos": [11,24,5,19,15,11,16,14,17,15,12,14,15,10]
"Amos": [15,16,15,13,27,15,17,14,14]
"Jonah": [16,11,10,11]
"Mic": [16,13,12,13,14,16,20]
"Hag": [14,24]
"Matt": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,26,35,30,34,46,46,39,51,46,75,66,20]
"Mark": [45,28,35,40,43,56,37,39,49,52,33,44,37,72,47,20]
"John": [51,25,36,54,47,72,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25]
"Acts": [26,47,26,37,42,15,59,40,43,48,30,25,52,27,41,40,34,28,40,38,40,30,35,27,27,32,44,31]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [25,23,25,23,28,22,20,24,12,13,21,22,23,17]
"Jdt": [12,18,15,17,29,21,25,34,19,20,21,20,31,18,15,31]
"Wis": [16,25,19,20,24,27,30,21,19,21,27,27,19,31,19,29,20,25,20]
"Sir": [40,23,34,36,18,37,40,22,25,34,36,19,32,27,22,31,31,33,28,33,31,33,38,47,36,28,33,30,35,27,42,28,33,31,26,28,34,39,41,32,28,26,37,27,31,23,31,28,19,31,38,13]
"Bar": [22,35,38,37,9,72]
"1Macc": [67,70,60,61,68,63,50,32,73,89,74,54,54,49,41,24]
"2Macc": [36,33,40,50,27,31,42,36,29,38,38,46,26,46,40]
ceb:
chapters:
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,16,21,6,13,18,22,18,15]
"PrAzar": [67]
"EpJer": [72]
"1Esd": [55,26,24,63,71,33,15,92,55]
kjv:
chapters:
"3John": [14]
nab:
order:
"Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "Josh": 6, "Judg": 7, "Ruth": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "PrMan": 15, "Ezra": 16, "Neh": 17, "1Esd": 18, "2Esd": 19, "Tob": 20, "Jdt": 21, "Esth": 22, "GkEsth": 23, "1Macc": 24, "2Macc": 25, "3Macc": 26, "4Macc": 27, "Job": 28, "Ps": 29, "Prov": 30, "Eccl": 31, "Song": 32, "Wis": 33, "Sir": 34, "Isa": 35, "Jer": 36, "Lam": 37, "Bar": 38, "EpJer": 39, "Ezek": 40, "Dan": 41, "PrAzar": 42, "Sus": 43, "Bel": 44, "SgThree": 45, "Hos": 46, "Joel": 47, "Amos": 48, "Obad": 49, "Jonah": 50, "Mic": 51, "Nah": 52, "Hab": 53, "Zeph": 54, "Hag": 55, "Zech": 56, "Mal": 57, "Matt": 58, "Mark": 59, "Luke": 60, "John": 61, "Acts": 62, "Rom": 63, "1Cor": 64, "2Cor": 65, "Gal": 66, "Eph": 67, "Phil": 68, "Col": 69, "1Thess": 70, "2Thess": 71, "1Tim": 72, "2Tim": 73, "Titus": 74, "Phlm": 75, "Heb": 76, "Jas": 77, "1Pet": 78, "2Pet": 79, "1John": 80, "2John": 81, "3John": 82, "Jude": 83, "Rev": 84
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,54,33,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26]
"Exod": [22,25,22,31,23,30,29,28,35,29,10,51,22,31,27,36,16,27,25,26,37,30,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38]
"Lev": [17,16,17,35,26,23,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34]
"Num": [54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,35,28,32,22,29,35,41,30,25,19,65,23,31,39,17,54,42,56,29,34,13]
"Deut": [46,37,29,49,33,25,26,20,29,22,32,31,19,29,23,22,20,22,21,20,23,29,26,22,19,19,26,69,28,20,30,52,29,12]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,16,23,28,23,44,25,12,25,11,31,13]
"2Sam": [27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,32,44,26,22,51,39,25]
"1Kgs": [53,46,28,20,32,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,54]
"2Kgs": [18,25,27,44,27,33,20,29,37,36,20,22,25,29,38,20,41,37,37,21,26,20,37,20,30]
"1Chr": [54,55,24,43,41,66,40,40,44,14,47,41,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30]
"2Chr": [18,17,17,22,14,42,22,18,31,19,23,16,23,14,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23]
"Neh": [11,20,38,17,19,19,72,18,37,40,36,47,31]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,32,26,17]
"Ps": [6,11,9,9,13,11,18,10,21,18,7,9,6,7,5,11,15,51,15,10,14,32,6,10,22,12,14,9,11,13,25,11,22,23,28,13,40,23,14,18,14,12,5,27,18,12,10,15,21,23,21,11,7,9,24,14,12,12,18,14,9,13,12,11,14,20,8,36,37,6,24,20,28,23,11,13,21,72,13,20,17,8,19,13,14,17,7,19,53,17,16,16,5,23,11,13,12,9,9,5,8,29,22,35,45,48,43,14,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,14,10,8,12,15,21,10,20,14,9,6]
"Eccl": [18,26,22,17,19,12,29,17,18,20,10,14]
"Song": [17,17,11,16,16,12,14,14]
"Isa": [31,22,26,6,30,13,25,23,20,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,11,25,24]
"Jer": [19,37,25,31,31,30,34,23,25,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"Ezek": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,44,37,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"Dan": [21,49,100,34,30,29,28,27,27,21,45,13,64,42]
"Hos": [9,25,5,19,15,11,16,14,17,15,11,15,15,10]
"Joel": [20,27,5,21]
"Jonah": [16,11,10,11]
"Mic": [16,13,12,14,14,16,20]
"Nah": [14,14,19]
"Zech": [17,17,10,14,11,15,14,23,17,12,17,14,9,21]
"Mal": [14,17,24]
"Acts": [26,47,26,37,42,15,60,40,43,49,30,25,52,28,41,40,34,28,40,38,40,30,35,27,27,32,44,31]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,17,21,6,13,18,22,18,15]
"Sir": [30,18,31,31,15,37,36,19,18,31,34,18,26,27,20,30,32,33,30,31,28,27,27,33,26,29,30,26,28,25,31,24,33,31,26,31,31,34,35,30,22,25,33,23,26,20,25,25,16,29,30]
"Bar": [22,35,38,37,9,72]
"2Macc": [36,32,40,50,27,31,42,36,29,38,38,46,26,46,39]
nlt:
chapters:
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
nrsv:
chapters:
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
bcv_parser::languages = ["jv"]
| 160518 | # When adding a new translation, add it both here and bcv_parser::translations.aliases
bcv_parser::regexps.translations = ///(?:
(?:JVNT)
)\b///gi
bcv_parser::translations =
aliases:
default:
osis: ""
alias: "default"
alternates: {}
default:
order:
"Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "<NAME>": 6, "Judg": 7, "<NAME>": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "<NAME>": 15, "<NAME>": 16, "<NAME>": 17, "Job": 18, "Ps": 19, "Prov": 20, "Eccl": 21, "Song": 22, "<NAME>": 23, "<NAME>": 24, "Lam": 25, "<NAME>": 26, "<NAME>": 27, "<NAME>": 28, "<NAME>": 29, "<NAME>": 30, "Obad": 31, "<NAME>": 32, "<NAME>": 33, "<NAME>": 34, "Hab": 35, "<NAME>": 36, "<NAME>": 37, "Zech": 38, "Mal": 39, "<NAME>": 40, "<NAME>": 41, "<NAME>": 42, "<NAME>": 43, "Acts": 44, "Rom": 45, "1Cor": 46, "2Cor": 47, "Gal": 48, "<NAME>": 49, "<NAME>": 50, "Col": 51, "1Thess": 52, "2Thess": 53, "1Tim": 54, "2Tim": 55, "<NAME>": 56, "Phlm": 57, "Heb": 58, "<NAME>": 59, "1Pet": 60, "2Pet": 61, "1John": 62, "2John": 63, "3John": 64, "<NAME>": 65, "Rev": 66, "Tob": 67, "Jdt": 68, "GkEsth": 69, "Wis": 70, "Sir": 71, "Bar": 72, "PrAzar": 73, "Sus": 74, "Bel": 75, "SgThree": 76, "EpJer": 77, "1Macc": 78, "2Macc": 79, "3Macc": 80, "4Macc": 81, "1Esd": 82, "2Esd": 83, "PrMan": 84
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26]
"Exod": [22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38]
"Lev": [17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34]
"Num": [54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,50,13,32,22,29,35,41,30,25,18,65,23,31,40,16,54,42,56,29,34,13]
"<NAME>": [46,37,29,49,33,25,26,20,29,22,32,32,18,29,23,22,20,22,21,20,23,30,25,22,19,19,26,68,29,20,30,52,29,12]
"<NAME>": [18,24,17,24,15,27,26,35,27,43,23,24,33,15,63,10,18,28,51,9,45,34,16,33]
"<NAME>": [36,23,31,24,31,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,25]
"<NAME>": [22,23,18,22]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,15,23,29,22,44,25,12,25,11,31,13]
"2Sam": [27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,33,43,26,22,51,39,25]
"1Kgs": [53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,53]
"2Kgs": [18,25,27,44,27,33,20,29,37,36,21,21,25,29,38,20,41,37,37,21,26,20,37,20,30]
"1Chr": [54,55,24,43,26,81,40,40,44,14,47,40,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30]
"2Chr": [17,18,17,22,14,42,22,18,31,19,23,16,22,15,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23]
"Ezra": [11,70,13,24,17,22,28,36,15,44]
"Neh": [11,20,32,23,19,19,73,18,38,39,36,47,31]
"Esth": [22,23,15,17,14,14,10,17,32,3]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,24,34,17]
"Ps": [6,12,8,8,12,10,17,9,20,18,7,8,6,7,5,11,15,50,14,9,13,31,6,10,22,12,14,9,11,12,24,11,22,22,28,12,40,22,13,17,13,11,5,26,17,11,9,14,20,23,19,9,6,7,23,13,11,11,17,12,8,12,11,10,13,20,7,35,36,5,24,20,28,23,10,12,20,72,13,19,16,8,18,12,13,17,7,18,52,17,16,15,5,23,11,13,12,9,9,5,8,28,22,35,45,48,43,13,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,13,10,7,12,15,21,10,20,14,9,6]
"Prov": [33,22,35,27,23,35,27,36,18,32,31,28,25,35,33,33,28,24,29,30,31,29,35,34,28,28,27,28,27,33,31]
"Eccl": [18,26,22,16,20,12,29,17,18,20,10,14]
"Song": [17,17,11,16,16,13,13,14]
"Isa": [31,22,26,6,30,13,25,22,21,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,12,25,24]
"<NAME>": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"<NAME>": [22,22,66,22,22]
"<NAME>": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"<NAME>": [21,49,30,37,31,28,28,27,27,21,45,13]
"<NAME>": [11,23,5,19,15,11,16,14,17,15,12,14,16,9]
"<NAME>": [20,32,21]
"<NAME>": [15,16,15,13,27,14,17,14,15]
"<NAME>": [21]
"<NAME>": [17,10,10,11]
"<NAME>": [16,13,12,13,15,16,20]
"<NAME>": [15,13,19]
"<NAME>": [17,20,19]
"<NAME>": [18,15,20]
"<NAME>": [15,23]
"<NAME>": [21,13,10,14,11,15,14,23,17,12,17,14,9,21]
"Mal": [14,17,18,6]
"<NAME>": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,27,35,30,34,46,46,39,51,46,75,66,20]
"<NAME>": [45,28,35,41,43,56,37,38,50,52,33,44,37,72,47,20]
"<NAME>": [80,52,38,44,39,49,50,56,62,42,54,59,35,35,32,31,37,43,48,47,38,71,56,53]
"<NAME>": [51,25,36,54,47,71,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25]
"Acts": [26,47,26,37,42,15,60,40,43,48,30,25,52,28,41,40,34,28,41,38,40,30,35,27,27,32,44,31]
"Rom": [32,29,31,25,21,23,25,39,33,21,36,21,14,23,33,27]
"1Cor": [31,16,23,21,13,20,40,13,27,33,34,31,13,40,58,24]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,14]
"Gal": [24,21,29,31,26,18]
"Eph": [23,22,21,32,33,24]
"Phil": [30,30,21,23]
"Col": [29,23,25,18]
"1Thess": [10,20,13,18,28]
"2Thess": [12,17,18]
"1Tim": [20,15,16,16,25,21]
"2Tim": [18,26,17,22]
"Titus": [16,15,15]
"Phlm": [25]
"Heb": [14,18,19,16,14,20,28,13,28,39,40,29,25]
"Jas": [27,26,18,17,20]
"1Pet": [25,25,22,19,14]
"2Pet": [21,22,18]
"1John": [10,29,24,21,21]
"2John": [13]
"3John": [15]
"Jude": [25]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,17,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,16,21,6,13,18,22,17,15]
"Jdt": [16,28,10,15,24,21,32,36,14,23,23,20,20,19,14,25]
"GkEsth": [22,23,15,17,14,14,10,17,32,13,12,6,18,19,16,24]
"Wis": [16,24,19,20,23,25,30,21,18,21,26,27,19,31,19,29,21,25,22]
"Sir": [30,18,31,31,15,37,36,19,18,31,34,18,26,27,20,30,32,33,30,31,28,27,27,34,26,29,30,26,28,25,31,24,33,31,26,31,31,34,35,30,22,25,33,23,26,20,25,25,16,29,30]
"Bar": [22,35,37,37,9]
"PrAzar": [68]
"Sus": [64]
"Bel": [42]
"SgThree": [39]
"EpJer": [73]
"1Macc": [64,70,60,61,68,63,50,32,73,89,74,53,53,49,41,24]
"2Macc": [36,32,40,50,27,31,42,36,29,38,38,45,26,46,39]
"3Macc": [29,33,30,21,51,41,23]
"4Macc": [35,24,21,26,38,35,23,29,32,21,27,19,27,20,32,25,24,24]
"1Esd": [58,30,24,63,73,34,15,96,55]
"2Esd": [40,48,36,52,56,59,70,63,47,59,46,51,58,48,63,78]
"PrMan": [15]
"Ps151": [7] #Never actually a book--we add this to Psalms if needed.
vulgate:
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,32,25]
"Exod": [22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,36]
"Lev": [17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,45,34]
"Num": [54,34,51,49,31,27,89,26,23,36,34,15,34,45,41,50,13,32,22,30,35,41,30,25,18,65,23,31,39,17,54,42,56,29,34,13]
"Josh": [18,24,17,25,16,27,26,35,27,44,23,24,33,15,63,10,18,28,51,9,43,34,16,33]
"Judg": [36,23,31,24,32,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,24]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,43,15,23,28,23,44,25,12,25,11,31,13]
"1Kgs": [53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,54]
"1Chr": [54,55,24,43,26,81,40,40,44,14,46,40,14,17,29,43,27,17,19,7,30,19,32,31,31,32,34,21,30]
"Neh": [11,20,31,23,19,19,73,18,38,39,36,46,31]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,23,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,35,28,25,16]
"Ps": [6,13,9,10,13,11,18,10,39,8,9,6,7,5,10,15,51,15,10,14,32,6,10,22,12,14,9,11,13,25,11,22,23,28,13,40,23,14,18,14,12,5,26,18,12,10,15,21,23,21,11,7,9,24,13,12,12,18,14,9,13,12,11,14,20,8,36,37,6,24,20,28,23,11,13,21,72,13,20,17,8,19,13,14,17,7,19,53,17,16,16,5,23,11,13,12,9,9,5,8,29,22,35,45,48,43,14,31,7,10,10,9,26,9,10,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,14,10,8,12,15,21,10,11,9,14,9,6]
"Eccl": [18,26,22,17,19,11,30,17,18,20,10,14]
"Song": [16,17,11,16,17,12,13,14]
"Jer": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,20,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"<NAME>": [28,9,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"<NAME>": [21,49,100,34,31,28,28,27,27,21,45,13,65,42]
"<NAME>": [11,24,5,19,15,11,16,14,17,15,12,14,15,10]
"<NAME>": [15,16,15,13,27,15,17,14,14]
"<NAME>": [16,11,10,11]
"<NAME>": [16,13,12,13,14,16,20]
"<NAME>": [14,24]
"<NAME>": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,26,35,30,34,46,46,39,51,46,75,66,20]
"<NAME>": [45,28,35,40,43,56,37,39,49,52,33,44,37,72,47,20]
"John": [51,25,36,54,47,72,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25]
"Acts": [26,47,26,37,42,15,59,40,43,48,30,25,52,27,41,40,34,28,40,38,40,30,35,27,27,32,44,31]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [25,23,25,23,28,22,20,24,12,13,21,22,23,17]
"Jdt": [12,18,15,17,29,21,25,34,19,20,21,20,31,18,15,31]
"Wis": [16,25,19,20,24,27,30,21,19,21,27,27,19,31,19,29,20,25,20]
"Sir": [40,23,34,36,18,37,40,22,25,34,36,19,32,27,22,31,31,33,28,33,31,33,38,47,36,28,33,30,35,27,42,28,33,31,26,28,34,39,41,32,28,26,37,27,31,23,31,28,19,31,38,13]
"Bar": [22,35,38,37,9,72]
"1Macc": [67,70,60,61,68,63,50,32,73,89,74,54,54,49,41,24]
"2Macc": [36,33,40,50,27,31,42,36,29,38,38,46,26,46,40]
ceb:
chapters:
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,16,21,6,13,18,22,18,15]
"PrAzar": [67]
"EpJer": [72]
"1Esd": [55,26,24,63,71,33,15,92,55]
kjv:
chapters:
"3John": [14]
nab:
order:
"Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "<NAME>": 6, "Judg": 7, "Ruth": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "PrMan": 15, "<NAME>": 16, "<NAME>": 17, "1Esd": 18, "2Esd": 19, "Tob": 20, "Jdt": 21, "Esth": 22, "GkEsth": 23, "1Macc": 24, "2Macc": 25, "3Macc": 26, "4Macc": 27, "Job": 28, "Ps": 29, "Prov": 30, "Eccl": 31, "Song": 32, "Wis": 33, "Sir": 34, "<NAME>": 35, "Jer": 36, "Lam": 37, "Bar": 38, "EpJer": 39, "<NAME>": 40, "<NAME>": 41, "Pr<NAME>": 42, "<NAME>": 43, "Bel": 44, "SgThree": 45, "<NAME>": 46, "<NAME>": 47, "<NAME>": 48, "Obad": 49, "<NAME>": 50, "<NAME>": 51, "Nah": 52, "Hab": 53, "<NAME>": 54, "<NAME>": 55, "Zech": 56, "Mal": 57, "<NAME>": 58, "<NAME>": 59, "<NAME>": 60, "<NAME>": 61, "Acts": 62, "Rom": 63, "1Cor": 64, "2Cor": 65, "Gal": 66, "<NAME>": 67, "<NAME>": 68, "<NAME>": 69, "1<NAME>": 70, "2<NAME>": 71, "1<NAME>": 72, "2<NAME>": 73, "<NAME>": 74, "<NAME>": 75, "<NAME>": 76, "<NAME>": 77, "1<NAME>": 78, "2<NAME>": 79, "1<NAME>": 80, "2<NAME>": 81, "<NAME>": 82, "<NAME>": 83, "Rev": 84
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,54,33,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26]
"Exod": [22,25,22,31,23,30,29,28,35,29,10,51,22,31,27,36,16,27,25,26,37,30,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38]
"Lev": [17,16,17,35,26,23,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34]
"Num": [54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,35,28,32,22,29,35,41,30,25,19,65,23,31,39,17,54,42,56,29,34,13]
"Deut": [46,37,29,49,33,25,26,20,29,22,32,31,19,29,23,22,20,22,21,20,23,29,26,22,19,19,26,69,28,20,30,52,29,12]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,16,23,28,23,44,25,12,25,11,31,13]
"2Sam": [27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,32,44,26,22,51,39,25]
"1Kgs": [53,46,28,20,32,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,54]
"2Kgs": [18,25,27,44,27,33,20,29,37,36,20,22,25,29,38,20,41,37,37,21,26,20,37,20,30]
"1Chr": [54,55,24,43,41,66,40,40,44,14,47,41,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30]
"2Chr": [18,17,17,22,14,42,22,18,31,19,23,16,23,14,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23]
"Neh": [11,20,38,17,19,19,72,18,37,40,36,47,31]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,32,26,17]
"Ps": [6,11,9,9,13,11,18,10,21,18,7,9,6,7,5,11,15,51,15,10,14,32,6,10,22,12,14,9,11,13,25,11,22,23,28,13,40,23,14,18,14,12,5,27,18,12,10,15,21,23,21,11,7,9,24,14,12,12,18,14,9,13,12,11,14,20,8,36,37,6,24,20,28,23,11,13,21,72,13,20,17,8,19,13,14,17,7,19,53,17,16,16,5,23,11,13,12,9,9,5,8,29,22,35,45,48,43,14,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,14,10,8,12,15,21,10,20,14,9,6]
"Eccl": [18,26,22,17,19,12,29,17,18,20,10,14]
"Song": [17,17,11,16,16,12,14,14]
"Isa": [31,22,26,6,30,13,25,23,20,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,11,25,24]
"<NAME>": [19,37,25,31,31,30,34,23,25,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"<NAME>": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,44,37,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"<NAME>": [21,49,100,34,30,29,28,27,27,21,45,13,64,42]
"<NAME>": [9,25,5,19,15,11,16,14,17,15,11,15,15,10]
"<NAME>": [20,27,5,21]
"<NAME>": [16,11,10,11]
"<NAME>": [16,13,12,14,14,16,20]
"<NAME>ah": [14,14,19]
"Zech": [17,17,10,14,11,15,14,23,17,12,17,14,9,21]
"Mal": [14,17,24]
"Acts": [26,47,26,37,42,15,60,40,43,49,30,25,52,28,41,40,34,28,40,38,40,30,35,27,27,32,44,31]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,17,21,6,13,18,22,18,15]
"Sir": [30,18,31,31,15,37,36,19,18,31,34,18,26,27,20,30,32,33,30,31,28,27,27,33,26,29,30,26,28,25,31,24,33,31,26,31,31,34,35,30,22,25,33,23,26,20,25,25,16,29,30]
"Bar": [22,35,38,37,9,72]
"2Macc": [36,32,40,50,27,31,42,36,29,38,38,46,26,46,39]
nlt:
chapters:
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
nrsv:
chapters:
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
bcv_parser::languages = ["jv"]
| true | # When adding a new translation, add it both here and bcv_parser::translations.aliases
bcv_parser::regexps.translations = ///(?:
(?:JVNT)
)\b///gi
bcv_parser::translations =
aliases:
default:
osis: ""
alias: "default"
alternates: {}
default:
order:
"Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "PI:NAME:<NAME>END_PI": 6, "Judg": 7, "PI:NAME:<NAME>END_PI": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "PI:NAME:<NAME>END_PI": 15, "PI:NAME:<NAME>END_PI": 16, "PI:NAME:<NAME>END_PI": 17, "Job": 18, "Ps": 19, "Prov": 20, "Eccl": 21, "Song": 22, "PI:NAME:<NAME>END_PI": 23, "PI:NAME:<NAME>END_PI": 24, "Lam": 25, "PI:NAME:<NAME>END_PI": 26, "PI:NAME:<NAME>END_PI": 27, "PI:NAME:<NAME>END_PI": 28, "PI:NAME:<NAME>END_PI": 29, "PI:NAME:<NAME>END_PI": 30, "Obad": 31, "PI:NAME:<NAME>END_PI": 32, "PI:NAME:<NAME>END_PI": 33, "PI:NAME:<NAME>END_PI": 34, "Hab": 35, "PI:NAME:<NAME>END_PI": 36, "PI:NAME:<NAME>END_PI": 37, "Zech": 38, "Mal": 39, "PI:NAME:<NAME>END_PI": 40, "PI:NAME:<NAME>END_PI": 41, "PI:NAME:<NAME>END_PI": 42, "PI:NAME:<NAME>END_PI": 43, "Acts": 44, "Rom": 45, "1Cor": 46, "2Cor": 47, "Gal": 48, "PI:NAME:<NAME>END_PI": 49, "PI:NAME:<NAME>END_PI": 50, "Col": 51, "1Thess": 52, "2Thess": 53, "1Tim": 54, "2Tim": 55, "PI:NAME:<NAME>END_PI": 56, "Phlm": 57, "Heb": 58, "PI:NAME:<NAME>END_PI": 59, "1Pet": 60, "2Pet": 61, "1John": 62, "2John": 63, "3John": 64, "PI:NAME:<NAME>END_PI": 65, "Rev": 66, "Tob": 67, "Jdt": 68, "GkEsth": 69, "Wis": 70, "Sir": 71, "Bar": 72, "PrAzar": 73, "Sus": 74, "Bel": 75, "SgThree": 76, "EpJer": 77, "1Macc": 78, "2Macc": 79, "3Macc": 80, "4Macc": 81, "1Esd": 82, "2Esd": 83, "PrMan": 84
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26]
"Exod": [22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38]
"Lev": [17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34]
"Num": [54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,50,13,32,22,29,35,41,30,25,18,65,23,31,40,16,54,42,56,29,34,13]
"PI:NAME:<NAME>END_PI": [46,37,29,49,33,25,26,20,29,22,32,32,18,29,23,22,20,22,21,20,23,30,25,22,19,19,26,68,29,20,30,52,29,12]
"PI:NAME:<NAME>END_PI": [18,24,17,24,15,27,26,35,27,43,23,24,33,15,63,10,18,28,51,9,45,34,16,33]
"PI:NAME:<NAME>END_PI": [36,23,31,24,31,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,25]
"PI:NAME:<NAME>END_PI": [22,23,18,22]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,15,23,29,22,44,25,12,25,11,31,13]
"2Sam": [27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,33,43,26,22,51,39,25]
"1Kgs": [53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,53]
"2Kgs": [18,25,27,44,27,33,20,29,37,36,21,21,25,29,38,20,41,37,37,21,26,20,37,20,30]
"1Chr": [54,55,24,43,26,81,40,40,44,14,47,40,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30]
"2Chr": [17,18,17,22,14,42,22,18,31,19,23,16,22,15,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23]
"Ezra": [11,70,13,24,17,22,28,36,15,44]
"Neh": [11,20,32,23,19,19,73,18,38,39,36,47,31]
"Esth": [22,23,15,17,14,14,10,17,32,3]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,24,34,17]
"Ps": [6,12,8,8,12,10,17,9,20,18,7,8,6,7,5,11,15,50,14,9,13,31,6,10,22,12,14,9,11,12,24,11,22,22,28,12,40,22,13,17,13,11,5,26,17,11,9,14,20,23,19,9,6,7,23,13,11,11,17,12,8,12,11,10,13,20,7,35,36,5,24,20,28,23,10,12,20,72,13,19,16,8,18,12,13,17,7,18,52,17,16,15,5,23,11,13,12,9,9,5,8,28,22,35,45,48,43,13,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,13,10,7,12,15,21,10,20,14,9,6]
"Prov": [33,22,35,27,23,35,27,36,18,32,31,28,25,35,33,33,28,24,29,30,31,29,35,34,28,28,27,28,27,33,31]
"Eccl": [18,26,22,16,20,12,29,17,18,20,10,14]
"Song": [17,17,11,16,16,13,13,14]
"Isa": [31,22,26,6,30,13,25,22,21,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,12,25,24]
"PI:NAME:<NAME>END_PI": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"PI:NAME:<NAME>END_PI": [22,22,66,22,22]
"PI:NAME:<NAME>END_PI": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"PI:NAME:<NAME>END_PI": [21,49,30,37,31,28,28,27,27,21,45,13]
"PI:NAME:<NAME>END_PI": [11,23,5,19,15,11,16,14,17,15,12,14,16,9]
"PI:NAME:<NAME>END_PI": [20,32,21]
"PI:NAME:<NAME>END_PI": [15,16,15,13,27,14,17,14,15]
"PI:NAME:<NAME>END_PI": [21]
"PI:NAME:<NAME>END_PI": [17,10,10,11]
"PI:NAME:<NAME>END_PI": [16,13,12,13,15,16,20]
"PI:NAME:<NAME>END_PI": [15,13,19]
"PI:NAME:<NAME>END_PI": [17,20,19]
"PI:NAME:<NAME>END_PI": [18,15,20]
"PI:NAME:<NAME>END_PI": [15,23]
"PI:NAME:<NAME>END_PI": [21,13,10,14,11,15,14,23,17,12,17,14,9,21]
"Mal": [14,17,18,6]
"PI:NAME:<NAME>END_PI": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,27,35,30,34,46,46,39,51,46,75,66,20]
"PI:NAME:<NAME>END_PI": [45,28,35,41,43,56,37,38,50,52,33,44,37,72,47,20]
"PI:NAME:<NAME>END_PI": [80,52,38,44,39,49,50,56,62,42,54,59,35,35,32,31,37,43,48,47,38,71,56,53]
"PI:NAME:<NAME>END_PI": [51,25,36,54,47,71,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25]
"Acts": [26,47,26,37,42,15,60,40,43,48,30,25,52,28,41,40,34,28,41,38,40,30,35,27,27,32,44,31]
"Rom": [32,29,31,25,21,23,25,39,33,21,36,21,14,23,33,27]
"1Cor": [31,16,23,21,13,20,40,13,27,33,34,31,13,40,58,24]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,14]
"Gal": [24,21,29,31,26,18]
"Eph": [23,22,21,32,33,24]
"Phil": [30,30,21,23]
"Col": [29,23,25,18]
"1Thess": [10,20,13,18,28]
"2Thess": [12,17,18]
"1Tim": [20,15,16,16,25,21]
"2Tim": [18,26,17,22]
"Titus": [16,15,15]
"Phlm": [25]
"Heb": [14,18,19,16,14,20,28,13,28,39,40,29,25]
"Jas": [27,26,18,17,20]
"1Pet": [25,25,22,19,14]
"2Pet": [21,22,18]
"1John": [10,29,24,21,21]
"2John": [13]
"3John": [15]
"Jude": [25]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,17,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,16,21,6,13,18,22,17,15]
"Jdt": [16,28,10,15,24,21,32,36,14,23,23,20,20,19,14,25]
"GkEsth": [22,23,15,17,14,14,10,17,32,13,12,6,18,19,16,24]
"Wis": [16,24,19,20,23,25,30,21,18,21,26,27,19,31,19,29,21,25,22]
"Sir": [30,18,31,31,15,37,36,19,18,31,34,18,26,27,20,30,32,33,30,31,28,27,27,34,26,29,30,26,28,25,31,24,33,31,26,31,31,34,35,30,22,25,33,23,26,20,25,25,16,29,30]
"Bar": [22,35,37,37,9]
"PrAzar": [68]
"Sus": [64]
"Bel": [42]
"SgThree": [39]
"EpJer": [73]
"1Macc": [64,70,60,61,68,63,50,32,73,89,74,53,53,49,41,24]
"2Macc": [36,32,40,50,27,31,42,36,29,38,38,45,26,46,39]
"3Macc": [29,33,30,21,51,41,23]
"4Macc": [35,24,21,26,38,35,23,29,32,21,27,19,27,20,32,25,24,24]
"1Esd": [58,30,24,63,73,34,15,96,55]
"2Esd": [40,48,36,52,56,59,70,63,47,59,46,51,58,48,63,78]
"PrMan": [15]
"Ps151": [7] #Never actually a book--we add this to Psalms if needed.
vulgate:
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,32,25]
"Exod": [22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,36]
"Lev": [17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,45,34]
"Num": [54,34,51,49,31,27,89,26,23,36,34,15,34,45,41,50,13,32,22,30,35,41,30,25,18,65,23,31,39,17,54,42,56,29,34,13]
"Josh": [18,24,17,25,16,27,26,35,27,44,23,24,33,15,63,10,18,28,51,9,43,34,16,33]
"Judg": [36,23,31,24,32,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,24]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,43,15,23,28,23,44,25,12,25,11,31,13]
"1Kgs": [53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,54]
"1Chr": [54,55,24,43,26,81,40,40,44,14,46,40,14,17,29,43,27,17,19,7,30,19,32,31,31,32,34,21,30]
"Neh": [11,20,31,23,19,19,73,18,38,39,36,46,31]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,23,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,35,28,25,16]
"Ps": [6,13,9,10,13,11,18,10,39,8,9,6,7,5,10,15,51,15,10,14,32,6,10,22,12,14,9,11,13,25,11,22,23,28,13,40,23,14,18,14,12,5,26,18,12,10,15,21,23,21,11,7,9,24,13,12,12,18,14,9,13,12,11,14,20,8,36,37,6,24,20,28,23,11,13,21,72,13,20,17,8,19,13,14,17,7,19,53,17,16,16,5,23,11,13,12,9,9,5,8,29,22,35,45,48,43,14,31,7,10,10,9,26,9,10,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,14,10,8,12,15,21,10,11,9,14,9,6]
"Eccl": [18,26,22,17,19,11,30,17,18,20,10,14]
"Song": [16,17,11,16,17,12,13,14]
"Jer": [19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,20,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"PI:NAME:<NAME>END_PI": [28,9,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"PI:NAME:<NAME>END_PI": [21,49,100,34,31,28,28,27,27,21,45,13,65,42]
"PI:NAME:<NAME>END_PI": [11,24,5,19,15,11,16,14,17,15,12,14,15,10]
"PI:NAME:<NAME>END_PI": [15,16,15,13,27,15,17,14,14]
"PI:NAME:<NAME>END_PI": [16,11,10,11]
"PI:NAME:<NAME>END_PI": [16,13,12,13,14,16,20]
"PI:NAME:<NAME>END_PI": [14,24]
"PI:NAME:<NAME>END_PI": [25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,26,35,30,34,46,46,39,51,46,75,66,20]
"PI:NAME:<NAME>END_PI": [45,28,35,40,43,56,37,39,49,52,33,44,37,72,47,20]
"John": [51,25,36,54,47,72,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25]
"Acts": [26,47,26,37,42,15,59,40,43,48,30,25,52,27,41,40,34,28,40,38,40,30,35,27,27,32,44,31]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [25,23,25,23,28,22,20,24,12,13,21,22,23,17]
"Jdt": [12,18,15,17,29,21,25,34,19,20,21,20,31,18,15,31]
"Wis": [16,25,19,20,24,27,30,21,19,21,27,27,19,31,19,29,20,25,20]
"Sir": [40,23,34,36,18,37,40,22,25,34,36,19,32,27,22,31,31,33,28,33,31,33,38,47,36,28,33,30,35,27,42,28,33,31,26,28,34,39,41,32,28,26,37,27,31,23,31,28,19,31,38,13]
"Bar": [22,35,38,37,9,72]
"1Macc": [67,70,60,61,68,63,50,32,73,89,74,54,54,49,41,24]
"2Macc": [36,33,40,50,27,31,42,36,29,38,38,46,26,46,40]
ceb:
chapters:
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,16,21,6,13,18,22,18,15]
"PrAzar": [67]
"EpJer": [72]
"1Esd": [55,26,24,63,71,33,15,92,55]
kjv:
chapters:
"3John": [14]
nab:
order:
"Gen": 1, "Exod": 2, "Lev": 3, "Num": 4, "Deut": 5, "PI:NAME:<NAME>END_PI": 6, "Judg": 7, "Ruth": 8, "1Sam": 9, "2Sam": 10, "1Kgs": 11, "2Kgs": 12, "1Chr": 13, "2Chr": 14, "PrMan": 15, "PI:NAME:<NAME>END_PI": 16, "PI:NAME:<NAME>END_PI": 17, "1Esd": 18, "2Esd": 19, "Tob": 20, "Jdt": 21, "Esth": 22, "GkEsth": 23, "1Macc": 24, "2Macc": 25, "3Macc": 26, "4Macc": 27, "Job": 28, "Ps": 29, "Prov": 30, "Eccl": 31, "Song": 32, "Wis": 33, "Sir": 34, "PI:NAME:<NAME>END_PI": 35, "Jer": 36, "Lam": 37, "Bar": 38, "EpJer": 39, "PI:NAME:<NAME>END_PI": 40, "PI:NAME:<NAME>END_PI": 41, "PrPI:NAME:<NAME>END_PI": 42, "PI:NAME:<NAME>END_PI": 43, "Bel": 44, "SgThree": 45, "PI:NAME:<NAME>END_PI": 46, "PI:NAME:<NAME>END_PI": 47, "PI:NAME:<NAME>END_PI": 48, "Obad": 49, "PI:NAME:<NAME>END_PI": 50, "PI:NAME:<NAME>END_PI": 51, "Nah": 52, "Hab": 53, "PI:NAME:<NAME>END_PI": 54, "PI:NAME:<NAME>END_PI": 55, "Zech": 56, "Mal": 57, "PI:NAME:<NAME>END_PI": 58, "PI:NAME:<NAME>END_PI": 59, "PI:NAME:<NAME>END_PI": 60, "PI:NAME:<NAME>END_PI": 61, "Acts": 62, "Rom": 63, "1Cor": 64, "2Cor": 65, "Gal": 66, "PI:NAME:<NAME>END_PI": 67, "PI:NAME:<NAME>END_PI": 68, "PI:NAME:<NAME>END_PI": 69, "1PI:NAME:<NAME>END_PI": 70, "2PI:NAME:<NAME>END_PI": 71, "1PI:NAME:<NAME>END_PI": 72, "2PI:NAME:<NAME>END_PI": 73, "PI:NAME:<NAME>END_PI": 74, "PI:NAME:<NAME>END_PI": 75, "PI:NAME:<NAME>END_PI": 76, "PI:NAME:<NAME>END_PI": 77, "1PI:NAME:<NAME>END_PI": 78, "2PI:NAME:<NAME>END_PI": 79, "1PI:NAME:<NAME>END_PI": 80, "2PI:NAME:<NAME>END_PI": 81, "PI:NAME:<NAME>END_PI": 82, "PI:NAME:<NAME>END_PI": 83, "Rev": 84
chapters:
"Gen": [31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,54,33,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26]
"Exod": [22,25,22,31,23,30,29,28,35,29,10,51,22,31,27,36,16,27,25,26,37,30,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38]
"Lev": [17,16,17,35,26,23,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34]
"Num": [54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,35,28,32,22,29,35,41,30,25,19,65,23,31,39,17,54,42,56,29,34,13]
"Deut": [46,37,29,49,33,25,26,20,29,22,32,31,19,29,23,22,20,22,21,20,23,29,26,22,19,19,26,69,28,20,30,52,29,12]
"1Sam": [28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,16,23,28,23,44,25,12,25,11,31,13]
"2Sam": [27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,32,44,26,22,51,39,25]
"1Kgs": [53,46,28,20,32,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,54]
"2Kgs": [18,25,27,44,27,33,20,29,37,36,20,22,25,29,38,20,41,37,37,21,26,20,37,20,30]
"1Chr": [54,55,24,43,41,66,40,40,44,14,47,41,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30]
"2Chr": [18,17,17,22,14,42,22,18,31,19,23,16,23,14,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23]
"Neh": [11,20,38,17,19,19,72,18,37,40,36,47,31]
"Job": [22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,32,26,17]
"Ps": [6,11,9,9,13,11,18,10,21,18,7,9,6,7,5,11,15,51,15,10,14,32,6,10,22,12,14,9,11,13,25,11,22,23,28,13,40,23,14,18,14,12,5,27,18,12,10,15,21,23,21,11,7,9,24,14,12,12,18,14,9,13,12,11,14,20,8,36,37,6,24,20,28,23,11,13,21,72,13,20,17,8,19,13,14,17,7,19,53,17,16,16,5,23,11,13,12,9,9,5,8,29,22,35,45,48,43,14,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,14,10,8,12,15,21,10,20,14,9,6]
"Eccl": [18,26,22,17,19,12,29,17,18,20,10,14]
"Song": [17,17,11,16,16,12,14,14]
"Isa": [31,22,26,6,30,13,25,23,20,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,11,25,24]
"PI:NAME:<NAME>END_PI": [19,37,25,31,31,30,34,23,25,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34]
"PI:NAME:<NAME>END_PI": [28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,44,37,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35]
"PI:NAME:<NAME>END_PI": [21,49,100,34,30,29,28,27,27,21,45,13,64,42]
"PI:NAME:<NAME>END_PI": [9,25,5,19,15,11,16,14,17,15,11,15,15,10]
"PI:NAME:<NAME>END_PI": [20,27,5,21]
"PI:NAME:<NAME>END_PI": [16,11,10,11]
"PI:NAME:<NAME>END_PI": [16,13,12,14,14,16,20]
"PI:NAME:<NAME>END_PIah": [14,14,19]
"Zech": [17,17,10,14,11,15,14,23,17,12,17,14,9,21]
"Mal": [14,17,24]
"Acts": [26,47,26,37,42,15,60,40,43,49,30,25,52,28,41,40,34,28,40,38,40,30,35,27,27,32,44,31]
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
"Tob": [22,14,17,21,22,18,17,21,6,13,18,22,18,15]
"Sir": [30,18,31,31,15,37,36,19,18,31,34,18,26,27,20,30,32,33,30,31,28,27,27,33,26,29,30,26,28,25,31,24,33,31,26,31,31,34,35,30,22,25,33,23,26,20,25,25,16,29,30]
"Bar": [22,35,38,37,9,72]
"2Macc": [36,32,40,50,27,31,42,36,29,38,38,46,26,46,39]
nlt:
chapters:
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
nrsv:
chapters:
"2Cor": [24,17,18,18,21,18,16,24,15,18,33,21,13]
"Rev": [20,29,22,11,14,17,17,13,21,11,19,18,18,20,8,21,18,24,21,15,27,21]
bcv_parser::languages = ["jv"]
|
[
{
"context": " query:\n domain: \"test_domain_2\"\n my_key: \"2017\"\nquery2:\n query:\n domain: \"test_domain_2\"\n ",
"end": 63,
"score": 0.9991161227226257,
"start": 59,
"tag": "KEY",
"value": "2017"
}
] | tests/cson/config.test.cson | cle-b/tt_demo | 0 | query1:
query:
domain: "test_domain_2"
my_key: "2017"
query2:
query:
domain: "test_domain_2"
my_key: "{{filter}}"
aggregate:
query:[
$match:
domain:"test_domain_2"
,
$group:
_id: "$my_key"
my_key:
$sum: 1
] | 77009 | query1:
query:
domain: "test_domain_2"
my_key: "<KEY>"
query2:
query:
domain: "test_domain_2"
my_key: "{{filter}}"
aggregate:
query:[
$match:
domain:"test_domain_2"
,
$group:
_id: "$my_key"
my_key:
$sum: 1
] | true | query1:
query:
domain: "test_domain_2"
my_key: "PI:KEY:<KEY>END_PI"
query2:
query:
domain: "test_domain_2"
my_key: "{{filter}}"
aggregate:
query:[
$match:
domain:"test_domain_2"
,
$group:
_id: "$my_key"
my_key:
$sum: 1
] |
[
{
"context": " of tickets_Data.by_Ticket\n if key.contains 'x24h'\n need_Room = need_Room.concat value.names",
"end": 883,
"score": 0.9841164350509644,
"start": 879,
"tag": "KEY",
"value": "x24h"
}
] | src/server/src/Tickets.coffee | shooking/owasp-summit-2017 | 101 |
class Tickets
constructor: (jekyll_Data)->
@.jekyll_Data = jekyll_Data
@.file_Json_Lodges = @.jekyll_Data.folder_Data_Mapped.path_Combine 'lodges.json'
@.file_Yaml_Lodges = @.jekyll_Data.folder_Data_Mapped.path_Combine 'lodges.yml'
@.file_Json_Tickets = @.jekyll_Data.folder_Data_Mapped.path_Combine 'tickets.json'
@.file_Yaml_Tickets = @.jekyll_Data.folder_Data_Mapped.path_Combine 'tickets.yml'
map_Lodges: ->
ids = ['OK413','OK414','OK415','OK416','OK426','OK427','OK428','OK309','OK310','OK312','OK313','OK314','OK315','OK316','OK319','OK320','OK321']
data =
ids : ids
lodges : {}
pre_Summit : {}
day_delegates: []
# Summit tickets
tickets_Data = @.file_Json_Tickets.load_Json()
need_Room = []
for key,value of tickets_Data.by_Ticket
if key.contains 'x24h'
need_Room = need_Room.concat value.names
else
for name in value.names
first_Name = name.before(' ')
last_Name = name.after(' ')
data.day_delegates.add first_Name : first_Name, last_Name : last_Name
while need_Room.size() >0
id = ids.pop()
data.lodges[id] =
id : id
names: need_Room.splice(0,6)
for id in ids
data.lodges[id] =
id : id
names: []
# PreSummit
names = []
for key,value of @.jekyll_Data.participants_Data
if value.metadata['pre-summit']
names.add name: key, when: value.metadata['pre-summit']
data.pre_Summit['OK314'] = names.splice(0,6)
data.pre_Summit['OK315'] = names.splice(0,6)
data.pre_Summit['TBD'] = names.splice(0,6)
@.jekyll_Data.save_Data data, @.file_Json_Lodges, @.file_Yaml_Lodges
return data
map_Tickets: ->
data = {}
data =
stats: { count: 0 , no_regonline: 0}
by_Type: '24h': [] , '8h': []
by_Ticket : {}
by_Participant : {}
for key,value of @.jekyll_Data.participants_Data
if value.metadata.type is 'participant' and value.metadata.ticket
data.stats.count++
data.stats.no_regonline++ if value.metadata.regonline is 'No'
# add data to the csv.
if value.metadata.ticket.contains('24h')
data.by_Type['24h'].add "#{key}, #{value.metadata?['job-title'].before(',') || ''}, #{value.metadata['company'] || ''}\n"
else
data.by_Type['8h'].add "#{key}, #{value.metadata?['job-title'].before(',') || ''}, #{value.metadata['company'] || ''}\n"
data.by_Ticket[value.metadata.ticket] ?= { stats: { count:0 }, names: []}
using data.by_Ticket[value.metadata.ticket], ->
@.stats.count++
@.names.add key
first_Name = key.before(' ')
last_Names = key.after(' ')
if first_Name and last_Names
regonline_Name = "#{last_Names}, #{first_Name}"
else
regonline_Name = key
mapping =
name : key,
url : value.url
ticket : value.metadata.ticket
first_Name : first_Name
last_Names : last_Names
regonline_Name : regonline_Name
regonline : value.metadata.regonline || ''
ticket : value.metadata.ticket || ''
'when-day' : value.metadata['when-day'] || ''
data.by_Participant[regonline_Name] = mapping
data.by_Participant = @.jekyll_Data.sort_By_Key data.by_Participant
@.jekyll_Data.save_Data data, @.file_Json_Tickets, @.file_Yaml_Tickets
return data
module.exports = Tickets
| 164905 |
class Tickets
constructor: (jekyll_Data)->
@.jekyll_Data = jekyll_Data
@.file_Json_Lodges = @.jekyll_Data.folder_Data_Mapped.path_Combine 'lodges.json'
@.file_Yaml_Lodges = @.jekyll_Data.folder_Data_Mapped.path_Combine 'lodges.yml'
@.file_Json_Tickets = @.jekyll_Data.folder_Data_Mapped.path_Combine 'tickets.json'
@.file_Yaml_Tickets = @.jekyll_Data.folder_Data_Mapped.path_Combine 'tickets.yml'
map_Lodges: ->
ids = ['OK413','OK414','OK415','OK416','OK426','OK427','OK428','OK309','OK310','OK312','OK313','OK314','OK315','OK316','OK319','OK320','OK321']
data =
ids : ids
lodges : {}
pre_Summit : {}
day_delegates: []
# Summit tickets
tickets_Data = @.file_Json_Tickets.load_Json()
need_Room = []
for key,value of tickets_Data.by_Ticket
if key.contains '<KEY>'
need_Room = need_Room.concat value.names
else
for name in value.names
first_Name = name.before(' ')
last_Name = name.after(' ')
data.day_delegates.add first_Name : first_Name, last_Name : last_Name
while need_Room.size() >0
id = ids.pop()
data.lodges[id] =
id : id
names: need_Room.splice(0,6)
for id in ids
data.lodges[id] =
id : id
names: []
# PreSummit
names = []
for key,value of @.jekyll_Data.participants_Data
if value.metadata['pre-summit']
names.add name: key, when: value.metadata['pre-summit']
data.pre_Summit['OK314'] = names.splice(0,6)
data.pre_Summit['OK315'] = names.splice(0,6)
data.pre_Summit['TBD'] = names.splice(0,6)
@.jekyll_Data.save_Data data, @.file_Json_Lodges, @.file_Yaml_Lodges
return data
map_Tickets: ->
data = {}
data =
stats: { count: 0 , no_regonline: 0}
by_Type: '24h': [] , '8h': []
by_Ticket : {}
by_Participant : {}
for key,value of @.jekyll_Data.participants_Data
if value.metadata.type is 'participant' and value.metadata.ticket
data.stats.count++
data.stats.no_regonline++ if value.metadata.regonline is 'No'
# add data to the csv.
if value.metadata.ticket.contains('24h')
data.by_Type['24h'].add "#{key}, #{value.metadata?['job-title'].before(',') || ''}, #{value.metadata['company'] || ''}\n"
else
data.by_Type['8h'].add "#{key}, #{value.metadata?['job-title'].before(',') || ''}, #{value.metadata['company'] || ''}\n"
data.by_Ticket[value.metadata.ticket] ?= { stats: { count:0 }, names: []}
using data.by_Ticket[value.metadata.ticket], ->
@.stats.count++
@.names.add key
first_Name = key.before(' ')
last_Names = key.after(' ')
if first_Name and last_Names
regonline_Name = "#{last_Names}, #{first_Name}"
else
regonline_Name = key
mapping =
name : key,
url : value.url
ticket : value.metadata.ticket
first_Name : first_Name
last_Names : last_Names
regonline_Name : regonline_Name
regonline : value.metadata.regonline || ''
ticket : value.metadata.ticket || ''
'when-day' : value.metadata['when-day'] || ''
data.by_Participant[regonline_Name] = mapping
data.by_Participant = @.jekyll_Data.sort_By_Key data.by_Participant
@.jekyll_Data.save_Data data, @.file_Json_Tickets, @.file_Yaml_Tickets
return data
module.exports = Tickets
| true |
class Tickets
constructor: (jekyll_Data)->
@.jekyll_Data = jekyll_Data
@.file_Json_Lodges = @.jekyll_Data.folder_Data_Mapped.path_Combine 'lodges.json'
@.file_Yaml_Lodges = @.jekyll_Data.folder_Data_Mapped.path_Combine 'lodges.yml'
@.file_Json_Tickets = @.jekyll_Data.folder_Data_Mapped.path_Combine 'tickets.json'
@.file_Yaml_Tickets = @.jekyll_Data.folder_Data_Mapped.path_Combine 'tickets.yml'
map_Lodges: ->
ids = ['OK413','OK414','OK415','OK416','OK426','OK427','OK428','OK309','OK310','OK312','OK313','OK314','OK315','OK316','OK319','OK320','OK321']
data =
ids : ids
lodges : {}
pre_Summit : {}
day_delegates: []
# Summit tickets
tickets_Data = @.file_Json_Tickets.load_Json()
need_Room = []
for key,value of tickets_Data.by_Ticket
if key.contains 'PI:KEY:<KEY>END_PI'
need_Room = need_Room.concat value.names
else
for name in value.names
first_Name = name.before(' ')
last_Name = name.after(' ')
data.day_delegates.add first_Name : first_Name, last_Name : last_Name
while need_Room.size() >0
id = ids.pop()
data.lodges[id] =
id : id
names: need_Room.splice(0,6)
for id in ids
data.lodges[id] =
id : id
names: []
# PreSummit
names = []
for key,value of @.jekyll_Data.participants_Data
if value.metadata['pre-summit']
names.add name: key, when: value.metadata['pre-summit']
data.pre_Summit['OK314'] = names.splice(0,6)
data.pre_Summit['OK315'] = names.splice(0,6)
data.pre_Summit['TBD'] = names.splice(0,6)
@.jekyll_Data.save_Data data, @.file_Json_Lodges, @.file_Yaml_Lodges
return data
map_Tickets: ->
data = {}
data =
stats: { count: 0 , no_regonline: 0}
by_Type: '24h': [] , '8h': []
by_Ticket : {}
by_Participant : {}
for key,value of @.jekyll_Data.participants_Data
if value.metadata.type is 'participant' and value.metadata.ticket
data.stats.count++
data.stats.no_regonline++ if value.metadata.regonline is 'No'
# add data to the csv.
if value.metadata.ticket.contains('24h')
data.by_Type['24h'].add "#{key}, #{value.metadata?['job-title'].before(',') || ''}, #{value.metadata['company'] || ''}\n"
else
data.by_Type['8h'].add "#{key}, #{value.metadata?['job-title'].before(',') || ''}, #{value.metadata['company'] || ''}\n"
data.by_Ticket[value.metadata.ticket] ?= { stats: { count:0 }, names: []}
using data.by_Ticket[value.metadata.ticket], ->
@.stats.count++
@.names.add key
first_Name = key.before(' ')
last_Names = key.after(' ')
if first_Name and last_Names
regonline_Name = "#{last_Names}, #{first_Name}"
else
regonline_Name = key
mapping =
name : key,
url : value.url
ticket : value.metadata.ticket
first_Name : first_Name
last_Names : last_Names
regonline_Name : regonline_Name
regonline : value.metadata.regonline || ''
ticket : value.metadata.ticket || ''
'when-day' : value.metadata['when-day'] || ''
data.by_Participant[regonline_Name] = mapping
data.by_Participant = @.jekyll_Data.sort_By_Key data.by_Participant
@.jekyll_Data.save_Data data, @.file_Json_Tickets, @.file_Yaml_Tickets
return data
module.exports = Tickets
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2012 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998542666435242,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | ifs-web-service/ifs-web-core/src/main/resources/static/js/vendor/wysiwyg-editor/hallo-src/src/plugins/cleanhtml.coffee | adambirse/innovation-funding-service | 40 | # Hallo - a rich text editing jQuery UI widget
# (c) 2012 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
# This plugin will tidy up pasted content with help of
# the jquery-clean plugin (https://code.google.com/p/jquery-clean/).
# Also the selection save and restore module from rangy
# (https://code.google.com/p/rangy/wiki/SelectionSaveRestoreModule)
# is required in order to resolve cross browser bugs for pasting.
# The plugins have to be accessible or an error will be thrown.
#
# Usage (example):
#
#jQuery('.editable').hallo({
# plugins: {
# 'hallocleanhtml': {
# format: false,
# allowedTags: [
# 'p',
# 'em',
# 'strong',
# 'br',
# 'div',
# 'ol',
# 'ul',
# 'li',
# 'a'],
# allowedAttributes: ['style']
# }
# },
# });
#
# The plugin options correspond to the available jquery-clean plugin options.
#
# Tested in IE 10 + 9, Chrome 25, FF 19
((jQuery) ->
rangyMessage = 'The hallocleanhtml plugin requires the selection save and
restore module from Rangy'
jQuery.widget 'IKS.hallocleanhtml',
_create: ->
if jQuery.htmlClean is undefined
throw new Error 'The hallocleanhtml plugin requires jQuery.htmlClean'
return
editor = this.element
# bind paste handler on first call
editor.bind 'paste', this, (event) =>
# TODO: find out why this check always fails when placed directly
# after jQuery.htmlClean check
if rangy.saveSelection is undefined
throw new Error rangyMessage
return
widget = event.data
# bugfix for overwriting selected text in ie
widget.options.editable.getSelection().deleteContents()
lastRange = rangy.saveSelection()
# make sure content will be pasted _empty_ editor and save old contents
# (because we cannot access clipboard data in all browsers)
lastContent = editor.html()
editor.html ''
setTimeout =>
pasted = editor.html()
cleanPasted = jQuery.htmlClean pasted, @options
#console.log "content before: " + lastContent
#console.log "pasted content: " + pasted
#console.log "tidy pasted content: " + cleanPasted
# back in timne to the state before pasting
editor.html lastContent
rangy.restoreSelection lastRange
# paste tidy pasted content back
# TODO: set cursor _behind_ pasted content
if cleanPasted != ''
if (document.queryCommandSupported('insertHTML'))
document.execCommand 'insertHTML', false, cleanPasted
else
# most likely ie
range = widget.options.editable.getSelection()
range.insertNode range.createContextualFragment(cleanPasted)
, 4
) jQuery
| 76868 | # Hallo - a rich text editing jQuery UI widget
# (c) 2012 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
# This plugin will tidy up pasted content with help of
# the jquery-clean plugin (https://code.google.com/p/jquery-clean/).
# Also the selection save and restore module from rangy
# (https://code.google.com/p/rangy/wiki/SelectionSaveRestoreModule)
# is required in order to resolve cross browser bugs for pasting.
# The plugins have to be accessible or an error will be thrown.
#
# Usage (example):
#
#jQuery('.editable').hallo({
# plugins: {
# 'hallocleanhtml': {
# format: false,
# allowedTags: [
# 'p',
# 'em',
# 'strong',
# 'br',
# 'div',
# 'ol',
# 'ul',
# 'li',
# 'a'],
# allowedAttributes: ['style']
# }
# },
# });
#
# The plugin options correspond to the available jquery-clean plugin options.
#
# Tested in IE 10 + 9, Chrome 25, FF 19
((jQuery) ->
rangyMessage = 'The hallocleanhtml plugin requires the selection save and
restore module from Rangy'
jQuery.widget 'IKS.hallocleanhtml',
_create: ->
if jQuery.htmlClean is undefined
throw new Error 'The hallocleanhtml plugin requires jQuery.htmlClean'
return
editor = this.element
# bind paste handler on first call
editor.bind 'paste', this, (event) =>
# TODO: find out why this check always fails when placed directly
# after jQuery.htmlClean check
if rangy.saveSelection is undefined
throw new Error rangyMessage
return
widget = event.data
# bugfix for overwriting selected text in ie
widget.options.editable.getSelection().deleteContents()
lastRange = rangy.saveSelection()
# make sure content will be pasted _empty_ editor and save old contents
# (because we cannot access clipboard data in all browsers)
lastContent = editor.html()
editor.html ''
setTimeout =>
pasted = editor.html()
cleanPasted = jQuery.htmlClean pasted, @options
#console.log "content before: " + lastContent
#console.log "pasted content: " + pasted
#console.log "tidy pasted content: " + cleanPasted
# back in timne to the state before pasting
editor.html lastContent
rangy.restoreSelection lastRange
# paste tidy pasted content back
# TODO: set cursor _behind_ pasted content
if cleanPasted != ''
if (document.queryCommandSupported('insertHTML'))
document.execCommand 'insertHTML', false, cleanPasted
else
# most likely ie
range = widget.options.editable.getSelection()
range.insertNode range.createContextualFragment(cleanPasted)
, 4
) jQuery
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2012 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
# This plugin will tidy up pasted content with help of
# the jquery-clean plugin (https://code.google.com/p/jquery-clean/).
# Also the selection save and restore module from rangy
# (https://code.google.com/p/rangy/wiki/SelectionSaveRestoreModule)
# is required in order to resolve cross browser bugs for pasting.
# The plugins have to be accessible or an error will be thrown.
#
# Usage (example):
#
#jQuery('.editable').hallo({
# plugins: {
# 'hallocleanhtml': {
# format: false,
# allowedTags: [
# 'p',
# 'em',
# 'strong',
# 'br',
# 'div',
# 'ol',
# 'ul',
# 'li',
# 'a'],
# allowedAttributes: ['style']
# }
# },
# });
#
# The plugin options correspond to the available jquery-clean plugin options.
#
# Tested in IE 10 + 9, Chrome 25, FF 19
((jQuery) ->
rangyMessage = 'The hallocleanhtml plugin requires the selection save and
restore module from Rangy'
jQuery.widget 'IKS.hallocleanhtml',
_create: ->
if jQuery.htmlClean is undefined
throw new Error 'The hallocleanhtml plugin requires jQuery.htmlClean'
return
editor = this.element
# bind paste handler on first call
editor.bind 'paste', this, (event) =>
# TODO: find out why this check always fails when placed directly
# after jQuery.htmlClean check
if rangy.saveSelection is undefined
throw new Error rangyMessage
return
widget = event.data
# bugfix for overwriting selected text in ie
widget.options.editable.getSelection().deleteContents()
lastRange = rangy.saveSelection()
# make sure content will be pasted _empty_ editor and save old contents
# (because we cannot access clipboard data in all browsers)
lastContent = editor.html()
editor.html ''
setTimeout =>
pasted = editor.html()
cleanPasted = jQuery.htmlClean pasted, @options
#console.log "content before: " + lastContent
#console.log "pasted content: " + pasted
#console.log "tidy pasted content: " + cleanPasted
# back in timne to the state before pasting
editor.html lastContent
rangy.restoreSelection lastRange
# paste tidy pasted content back
# TODO: set cursor _behind_ pasted content
if cleanPasted != ''
if (document.queryCommandSupported('insertHTML'))
document.execCommand 'insertHTML', false, cleanPasted
else
# most likely ie
range = widget.options.editable.getSelection()
range.insertNode range.createContextualFragment(cleanPasted)
, 4
) jQuery
|
[
{
"context": "ound missingPercent}% NA\"\n\n columnLabels\n\nkey = [64, 14, 190, 99, 77, 107, 95, 26, 211, 235, 41, 125, 110, 237, 151, 148]\nencryptPassword = (password)",
"end": 5387,
"score": 0.9874954223632812,
"start": 5336,
"tag": "KEY",
"value": "64, 14, 190, 99, 77, 107, 95, 26, 211, 235, 41, 125"
}
] | src/ext/modules/util.coffee | appigge/h2o-flow | 0 | validateFileExtension = (filename, extension) ->
-1 isnt filename.indexOf extension, filename.length - extension.length
getFileBaseName = (filename, extension) ->
Flow.Util.sanitizeName filename.substr 0, filename.length - extension.length
createListControl = (parameter) ->
MaxItemsPerPage = 100
_searchTerm = signal ''
_ignoreNATerm = signal ''
_values = signal []
_selectionCount = signal 0
_isUpdatingSelectionCount = no
blockSelectionUpdates = (f) ->
_isUpdatingSelectionCount = yes
f()
_isUpdatingSelectionCount = no
incrementSelectionCount = (amount) ->
_selectionCount _selectionCount() + amount
createEntry = (value) ->
isSelected = signal no
react isSelected, (isSelected) ->
unless _isUpdatingSelectionCount
if isSelected
incrementSelectionCount 1
else
incrementSelectionCount -1
return
isSelected: isSelected
value: value.value
type: value.type
missingLabel: value.missingLabel
missingPercent: value.missingPercent
_entries = lift _values, (values) -> map values, createEntry
_filteredItems = signal []
_visibleItems = signal []
_hasFilteredItems = lift _filteredItems, (entries) -> entries.length > 0
_currentPage = signal 0
_maxPages = lift _filteredItems, (entries) -> Math.ceil entries.length / MaxItemsPerPage
_canGoToPreviousPage = lift _currentPage, (index) -> index > 0
_canGoToNextPage = lift _maxPages, _currentPage, (maxPages, index) -> index < maxPages - 1
_searchCaption = lift _entries, _filteredItems, _selectionCount, _currentPage, _maxPages, (entries, filteredItems, selectionCount, currentPage, maxPages) ->
caption = if maxPages is 0 then '' else "Showing page #{currentPage + 1} of #{maxPages}."
if filteredItems.length isnt entries.length
caption += " Filtered #{filteredItems.length} of #{entries.length}."
if selectionCount isnt 0
caption += " #{selectionCount} ignored."
caption
react _entries, -> filterItems yes
_lastUsedSearchTerm = null
_lastUsedIgnoreNaTerm = null
filterItems = (force=no) ->
searchTerm = _searchTerm().trim()
ignoreNATerm = _ignoreNATerm().trim()
if force or searchTerm isnt _lastUsedSearchTerm or ignoreNATerm isnt _lastUsedIgnoreNaTerm
filteredItems = []
for entry, i in _entries()
missingPercent = parseFloat ignoreNATerm
hide = no
if (searchTerm isnt '') and -1 is entry.value.toLowerCase().indexOf searchTerm.toLowerCase()
hide = yes
else if (not isNaN missingPercent) and (missingPercent isnt 0) and entry.missingPercent <= missingPercent
hide = yes
unless hide
filteredItems.push entry
_lastUsedSearchTerm = searchTerm
_lastUsedIgnoreNaTerm = ignoreNATerm
_currentPage 0
_filteredItems filteredItems
start = _currentPage() * MaxItemsPerPage
_visibleItems _filteredItems().slice start, start + MaxItemsPerPage
return
changeSelection = (source, value) ->
for entry in source
entry.isSelected value
return
selectFiltered = ->
entries = _filteredItems()
blockSelectionUpdates -> changeSelection entries, yes
_selectionCount entries.length
deselectFiltered = ->
blockSelectionUpdates -> changeSelection _filteredItems(), no
_selectionCount 0
goToPreviousPage = ->
if _canGoToPreviousPage()
_currentPage _currentPage() - 1
filterItems()
return
goToNextPage = ->
if _canGoToNextPage()
_currentPage _currentPage() + 1
filterItems()
return
react _searchTerm, throttle filterItems, 500
react _ignoreNATerm, throttle filterItems, 500
control = createControl 'list', parameter
control.values = _values
control.entries = _visibleItems
control.hasFilteredItems = _hasFilteredItems
control.searchCaption = _searchCaption
control.searchTerm = _searchTerm
control.ignoreNATerm = _ignoreNATerm
control.value = _entries
control.selectFiltered = selectFiltered
control.deselectFiltered = deselectFiltered
control.goToPreviousPage = goToPreviousPage
control.goToNextPage = goToNextPage
control.canGoToPreviousPage = _canGoToPreviousPage
control.canGoToNextPage = _canGoToNextPage
control
createControl = (kind, parameter) ->
_hasError = signal no
_hasWarning = signal no
_hasInfo = signal no
_message = signal ''
_hasMessage = lift _message, (message) -> if message then yes else no
_isVisible = signal yes
_isGrided = signal no
_isNotGrided = lift _isGrided, (value) -> not value
kind: kind
name: parameter.name
label: parameter.label
description: parameter.help
isRequired: parameter.required
hasError: _hasError
hasWarning: _hasWarning
hasInfo: _hasInfo
message: _message
hasMessage: _hasMessage
isVisible: _isVisible
isGridable: parameter.gridable
isGrided: _isGrided
isNotGrided: _isNotGrided
columnLabelsFromFrame = (frame) ->
columnLabels = map frame.columns, (column) ->
missingPercent = 100 * column.missing_count / frame.rows
type: if column.type is 'enum' then "enum(#{column.domain_cardinality})" else column.type
value: column.label
missingPercent: missingPercent
missingLabel: if missingPercent is 0 then '' else "#{round missingPercent}% NA"
columnLabels
key = [64, 14, 190, 99, 77, 107, 95, 26, 211, 235, 41, 125, 110, 237, 151, 148]
encryptPassword = (password) ->
aesCtr = new aesjs.ModeOfOperation.ctr key, new aesjs.Counter 5;
passwordBytes = aesjs.utils.utf8.toBytes password
encryptedBytes = aesCtr.encrypt passwordBytes
aesjs.utils.hex.fromBytes encryptedBytes
decryptPassword = (encrypted) ->
aesCtr = new aesjs.ModeOfOperation.ctr key, new aesjs.Counter 5;
encryptedBytes = aesjs.utils.hex.toBytes encrypted
passwordBytes = aesCtr.decrypt encryptedBytes
aesjs.utils.utf8.fromBytes passwordBytes
H2O.Util =
validateFileExtension: validateFileExtension
getFileBaseName: getFileBaseName
createListControl: createListControl
createControl: createControl
columnLabelsFromFrame: columnLabelsFromFrame
encryptPassword: encryptPassword
decryptPassword: decryptPassword | 71738 | validateFileExtension = (filename, extension) ->
-1 isnt filename.indexOf extension, filename.length - extension.length
getFileBaseName = (filename, extension) ->
Flow.Util.sanitizeName filename.substr 0, filename.length - extension.length
createListControl = (parameter) ->
MaxItemsPerPage = 100
_searchTerm = signal ''
_ignoreNATerm = signal ''
_values = signal []
_selectionCount = signal 0
_isUpdatingSelectionCount = no
blockSelectionUpdates = (f) ->
_isUpdatingSelectionCount = yes
f()
_isUpdatingSelectionCount = no
incrementSelectionCount = (amount) ->
_selectionCount _selectionCount() + amount
createEntry = (value) ->
isSelected = signal no
react isSelected, (isSelected) ->
unless _isUpdatingSelectionCount
if isSelected
incrementSelectionCount 1
else
incrementSelectionCount -1
return
isSelected: isSelected
value: value.value
type: value.type
missingLabel: value.missingLabel
missingPercent: value.missingPercent
_entries = lift _values, (values) -> map values, createEntry
_filteredItems = signal []
_visibleItems = signal []
_hasFilteredItems = lift _filteredItems, (entries) -> entries.length > 0
_currentPage = signal 0
_maxPages = lift _filteredItems, (entries) -> Math.ceil entries.length / MaxItemsPerPage
_canGoToPreviousPage = lift _currentPage, (index) -> index > 0
_canGoToNextPage = lift _maxPages, _currentPage, (maxPages, index) -> index < maxPages - 1
_searchCaption = lift _entries, _filteredItems, _selectionCount, _currentPage, _maxPages, (entries, filteredItems, selectionCount, currentPage, maxPages) ->
caption = if maxPages is 0 then '' else "Showing page #{currentPage + 1} of #{maxPages}."
if filteredItems.length isnt entries.length
caption += " Filtered #{filteredItems.length} of #{entries.length}."
if selectionCount isnt 0
caption += " #{selectionCount} ignored."
caption
react _entries, -> filterItems yes
_lastUsedSearchTerm = null
_lastUsedIgnoreNaTerm = null
filterItems = (force=no) ->
searchTerm = _searchTerm().trim()
ignoreNATerm = _ignoreNATerm().trim()
if force or searchTerm isnt _lastUsedSearchTerm or ignoreNATerm isnt _lastUsedIgnoreNaTerm
filteredItems = []
for entry, i in _entries()
missingPercent = parseFloat ignoreNATerm
hide = no
if (searchTerm isnt '') and -1 is entry.value.toLowerCase().indexOf searchTerm.toLowerCase()
hide = yes
else if (not isNaN missingPercent) and (missingPercent isnt 0) and entry.missingPercent <= missingPercent
hide = yes
unless hide
filteredItems.push entry
_lastUsedSearchTerm = searchTerm
_lastUsedIgnoreNaTerm = ignoreNATerm
_currentPage 0
_filteredItems filteredItems
start = _currentPage() * MaxItemsPerPage
_visibleItems _filteredItems().slice start, start + MaxItemsPerPage
return
changeSelection = (source, value) ->
for entry in source
entry.isSelected value
return
selectFiltered = ->
entries = _filteredItems()
blockSelectionUpdates -> changeSelection entries, yes
_selectionCount entries.length
deselectFiltered = ->
blockSelectionUpdates -> changeSelection _filteredItems(), no
_selectionCount 0
goToPreviousPage = ->
if _canGoToPreviousPage()
_currentPage _currentPage() - 1
filterItems()
return
goToNextPage = ->
if _canGoToNextPage()
_currentPage _currentPage() + 1
filterItems()
return
react _searchTerm, throttle filterItems, 500
react _ignoreNATerm, throttle filterItems, 500
control = createControl 'list', parameter
control.values = _values
control.entries = _visibleItems
control.hasFilteredItems = _hasFilteredItems
control.searchCaption = _searchCaption
control.searchTerm = _searchTerm
control.ignoreNATerm = _ignoreNATerm
control.value = _entries
control.selectFiltered = selectFiltered
control.deselectFiltered = deselectFiltered
control.goToPreviousPage = goToPreviousPage
control.goToNextPage = goToNextPage
control.canGoToPreviousPage = _canGoToPreviousPage
control.canGoToNextPage = _canGoToNextPage
control
createControl = (kind, parameter) ->
_hasError = signal no
_hasWarning = signal no
_hasInfo = signal no
_message = signal ''
_hasMessage = lift _message, (message) -> if message then yes else no
_isVisible = signal yes
_isGrided = signal no
_isNotGrided = lift _isGrided, (value) -> not value
kind: kind
name: parameter.name
label: parameter.label
description: parameter.help
isRequired: parameter.required
hasError: _hasError
hasWarning: _hasWarning
hasInfo: _hasInfo
message: _message
hasMessage: _hasMessage
isVisible: _isVisible
isGridable: parameter.gridable
isGrided: _isGrided
isNotGrided: _isNotGrided
columnLabelsFromFrame = (frame) ->
columnLabels = map frame.columns, (column) ->
missingPercent = 100 * column.missing_count / frame.rows
type: if column.type is 'enum' then "enum(#{column.domain_cardinality})" else column.type
value: column.label
missingPercent: missingPercent
missingLabel: if missingPercent is 0 then '' else "#{round missingPercent}% NA"
columnLabels
key = [<KEY>, 110, 237, 151, 148]
encryptPassword = (password) ->
aesCtr = new aesjs.ModeOfOperation.ctr key, new aesjs.Counter 5;
passwordBytes = aesjs.utils.utf8.toBytes password
encryptedBytes = aesCtr.encrypt passwordBytes
aesjs.utils.hex.fromBytes encryptedBytes
decryptPassword = (encrypted) ->
aesCtr = new aesjs.ModeOfOperation.ctr key, new aesjs.Counter 5;
encryptedBytes = aesjs.utils.hex.toBytes encrypted
passwordBytes = aesCtr.decrypt encryptedBytes
aesjs.utils.utf8.fromBytes passwordBytes
H2O.Util =
validateFileExtension: validateFileExtension
getFileBaseName: getFileBaseName
createListControl: createListControl
createControl: createControl
columnLabelsFromFrame: columnLabelsFromFrame
encryptPassword: encryptPassword
decryptPassword: decryptPassword | true | validateFileExtension = (filename, extension) ->
-1 isnt filename.indexOf extension, filename.length - extension.length
getFileBaseName = (filename, extension) ->
Flow.Util.sanitizeName filename.substr 0, filename.length - extension.length
createListControl = (parameter) ->
MaxItemsPerPage = 100
_searchTerm = signal ''
_ignoreNATerm = signal ''
_values = signal []
_selectionCount = signal 0
_isUpdatingSelectionCount = no
blockSelectionUpdates = (f) ->
_isUpdatingSelectionCount = yes
f()
_isUpdatingSelectionCount = no
incrementSelectionCount = (amount) ->
_selectionCount _selectionCount() + amount
createEntry = (value) ->
isSelected = signal no
react isSelected, (isSelected) ->
unless _isUpdatingSelectionCount
if isSelected
incrementSelectionCount 1
else
incrementSelectionCount -1
return
isSelected: isSelected
value: value.value
type: value.type
missingLabel: value.missingLabel
missingPercent: value.missingPercent
_entries = lift _values, (values) -> map values, createEntry
_filteredItems = signal []
_visibleItems = signal []
_hasFilteredItems = lift _filteredItems, (entries) -> entries.length > 0
_currentPage = signal 0
_maxPages = lift _filteredItems, (entries) -> Math.ceil entries.length / MaxItemsPerPage
_canGoToPreviousPage = lift _currentPage, (index) -> index > 0
_canGoToNextPage = lift _maxPages, _currentPage, (maxPages, index) -> index < maxPages - 1
_searchCaption = lift _entries, _filteredItems, _selectionCount, _currentPage, _maxPages, (entries, filteredItems, selectionCount, currentPage, maxPages) ->
caption = if maxPages is 0 then '' else "Showing page #{currentPage + 1} of #{maxPages}."
if filteredItems.length isnt entries.length
caption += " Filtered #{filteredItems.length} of #{entries.length}."
if selectionCount isnt 0
caption += " #{selectionCount} ignored."
caption
react _entries, -> filterItems yes
_lastUsedSearchTerm = null
_lastUsedIgnoreNaTerm = null
filterItems = (force=no) ->
searchTerm = _searchTerm().trim()
ignoreNATerm = _ignoreNATerm().trim()
if force or searchTerm isnt _lastUsedSearchTerm or ignoreNATerm isnt _lastUsedIgnoreNaTerm
filteredItems = []
for entry, i in _entries()
missingPercent = parseFloat ignoreNATerm
hide = no
if (searchTerm isnt '') and -1 is entry.value.toLowerCase().indexOf searchTerm.toLowerCase()
hide = yes
else if (not isNaN missingPercent) and (missingPercent isnt 0) and entry.missingPercent <= missingPercent
hide = yes
unless hide
filteredItems.push entry
_lastUsedSearchTerm = searchTerm
_lastUsedIgnoreNaTerm = ignoreNATerm
_currentPage 0
_filteredItems filteredItems
start = _currentPage() * MaxItemsPerPage
_visibleItems _filteredItems().slice start, start + MaxItemsPerPage
return
changeSelection = (source, value) ->
for entry in source
entry.isSelected value
return
selectFiltered = ->
entries = _filteredItems()
blockSelectionUpdates -> changeSelection entries, yes
_selectionCount entries.length
deselectFiltered = ->
blockSelectionUpdates -> changeSelection _filteredItems(), no
_selectionCount 0
goToPreviousPage = ->
if _canGoToPreviousPage()
_currentPage _currentPage() - 1
filterItems()
return
goToNextPage = ->
if _canGoToNextPage()
_currentPage _currentPage() + 1
filterItems()
return
react _searchTerm, throttle filterItems, 500
react _ignoreNATerm, throttle filterItems, 500
control = createControl 'list', parameter
control.values = _values
control.entries = _visibleItems
control.hasFilteredItems = _hasFilteredItems
control.searchCaption = _searchCaption
control.searchTerm = _searchTerm
control.ignoreNATerm = _ignoreNATerm
control.value = _entries
control.selectFiltered = selectFiltered
control.deselectFiltered = deselectFiltered
control.goToPreviousPage = goToPreviousPage
control.goToNextPage = goToNextPage
control.canGoToPreviousPage = _canGoToPreviousPage
control.canGoToNextPage = _canGoToNextPage
control
createControl = (kind, parameter) ->
_hasError = signal no
_hasWarning = signal no
_hasInfo = signal no
_message = signal ''
_hasMessage = lift _message, (message) -> if message then yes else no
_isVisible = signal yes
_isGrided = signal no
_isNotGrided = lift _isGrided, (value) -> not value
kind: kind
name: parameter.name
label: parameter.label
description: parameter.help
isRequired: parameter.required
hasError: _hasError
hasWarning: _hasWarning
hasInfo: _hasInfo
message: _message
hasMessage: _hasMessage
isVisible: _isVisible
isGridable: parameter.gridable
isGrided: _isGrided
isNotGrided: _isNotGrided
columnLabelsFromFrame = (frame) ->
columnLabels = map frame.columns, (column) ->
missingPercent = 100 * column.missing_count / frame.rows
type: if column.type is 'enum' then "enum(#{column.domain_cardinality})" else column.type
value: column.label
missingPercent: missingPercent
missingLabel: if missingPercent is 0 then '' else "#{round missingPercent}% NA"
columnLabels
key = [PI:KEY:<KEY>END_PI, 110, 237, 151, 148]
encryptPassword = (password) ->
aesCtr = new aesjs.ModeOfOperation.ctr key, new aesjs.Counter 5;
passwordBytes = aesjs.utils.utf8.toBytes password
encryptedBytes = aesCtr.encrypt passwordBytes
aesjs.utils.hex.fromBytes encryptedBytes
decryptPassword = (encrypted) ->
aesCtr = new aesjs.ModeOfOperation.ctr key, new aesjs.Counter 5;
encryptedBytes = aesjs.utils.hex.toBytes encrypted
passwordBytes = aesCtr.decrypt encryptedBytes
aesjs.utils.utf8.fromBytes passwordBytes
H2O.Util =
validateFileExtension: validateFileExtension
getFileBaseName: getFileBaseName
createListControl: createListControl
createControl: createControl
columnLabelsFromFrame: columnLabelsFromFrame
encryptPassword: encryptPassword
decryptPassword: decryptPassword |
[
{
"context": " # _id: id\n\n\n _sess: (id, value) ->\n key = \"_ironTable_\" + @_collectionName() + id\n if value?\n Session.set(key, value)\n e",
"end": 2763,
"score": 0.9987639784812927,
"start": 2724,
"tag": "KEY",
"value": "\"_ironTable_\" + @_collectionName() + id"
},
{
"context": " _id: record._id\n recordName: record[@_colToUseForName()]\n recordDisplayName: @_recordName() + ' ",
"end": 8642,
"score": 0.9650694727897644,
"start": 8627,
"tag": "USERNAME",
"value": "colToUseForName"
},
{
"context": "recordDisplayName: @_recordName() + ' ' + record[@_colToUseForName()]\n editOk: @collection().editOk?(record)\n",
"end": 8720,
"score": 0.9283462762832642,
"start": 8705,
"tag": "USERNAME",
"value": "colToUseForName"
}
] | shared/ironTableController.coffee | pfafman/meteor-iron-table | 1 |
#
# Iron Table Controller
#
DEBUG = false
# Capitalize first letter in string
String::capitalize = ->
@charAt(0).toUpperCase() + @slice(1)
class @IronTableController extends RouteController
classID: 'IronTableController'
increment : 20
sortColumn : '_id'
sortDirection : 1
template : 'ironTable'
rowTemplate : 'ironTableRow'
headerTemplate : 'ironTableHeader'
formTemplate : 'ironTableForm'
loadingTemplate : 'ironTableLoading'
defaultSelect : {}
showFilter : false
errorMessage : ''
cursor : null
_subscriptionComplete: false
constructor: ->
super
@reset()
reset: ->
#console.log("reset")
if Meteor.isClient
@_sess("recordCount", "...")
@_sessDefault('skip', 0)
@_sessDefault('sortColumn', @sortColumn)
@_sessDefault('sortDirection', @sortDirection)
@_sessDefault('filterColumn', null)
@_sessDefault('filterValue', '')
@fetchingCount = null
@errorMessage = ''
fetchRecordCount: ->
if not @collection().publishCounts and not @fetchingCount
@fetchingCount = true
# TODO: Set a timeout ?!?!
Meteor.call 'ironTable_' + @_collectionName() + '_recordCount', @_select(), (error, number) =>
@fetchingCount = false
if not error and not @_sessEquals("recordCount", number)
@_sess("recordCount", number)
else if error
console.log('ironTable_' + @_collectionName() + '_recordCount error:', error)
downloadRecords: (callback) ->
fields = {}
if @collection().downloadFields?
fields = @collection().downloadFields
else
for key, col of @_cols()
dataKey = col.dataKey or col.sortKey or key
fields[dataKey] = 1
Meteor.call "ironTable_" + @_collectionName() + "_getCSV", @_select(), fields, callback
# Pain in the ass to set up.... Not using
setupEditRoute: ->
# Set Up Edit Path
editRoutePath = @route.originalPath.replace(/\/[^\/]+$/ , '') + "/edit/:_id"
editRouteName = 'edit' + @collection()._name.capitalize()
@editRouteName = editRouteName
console.log("setup edit route", @editRouteName) if DEBUG
Router.map ->
@route editRouteName,
path: editRoutePath
waitOn: ->
Meteor.subscribe(@collection()._name + 'OneRecord', @params._id)
data: ->
data = @collection()?.findOne
_id: @params._id
data.returnPath = @route.originalPath
getEditRoute: (id) =>
@editRecordRoute
#console.log("getEditRoute", @editRecordRoute, id)
#if @editRecordRoute? and Router.routes[@editRecordRoute]?
# Router.go
# _id: id
_sess: (id, value) ->
key = "_ironTable_" + @_collectionName() + id
if value?
Session.set(key, value)
else
Session.get(key)
_sessEquals: (id, value) ->
Session.equals("_ironTable_" + @_collectionName() + id, value)
_sessNull: (id) ->
Session.set("_ironTable_" + @_collectionName() + id, null)
_sessDefault: (id, value) ->
Session.setDefault("_ironTable_" + @_collectionName() + id, value)
#editOk: (record) ->
# false
#deleteOk: (record) ->
# false
#onBeforeAction: (pause) ->
# console.log("onBeforeAction")
onRun: ->
#console.log("onRun", @_collectionName())
@reset()
@next()
onStop: ->
$('[rel="tooltip"]')?.tooltip('destroy')
$('[rel="popover"]')?.popover('destroy')
@unsubscribe()
@reset()
getTableTitle: ->
if not @doNotShowTitle or @showTitleLargeOnly
@tableTitle or @_collectionName()
getSubTitle: ->
@subTitle
_collectionName: ->
@collectionName or @collection()._name
_recordName: ->
@recordName or @collection().recordName or @collection()._name
_recordsName: ->
@recordsName or @collection().recordsName or @_recordName()+'s'
_colToUseForName: ->
@colToUseForName or @collection().colToUseForName or '_id'
doRowLink: ->
@collection()?.doRowLink
_cols: ->
theCol = @cols or @collection()?.schema
if theCol instanceof Array
colObj = {}
for col in theCol
colObj[col] = {}
else
colObj = theCol
colObj
filterHeaders: =>
rtn = []
for key, col of @_cols()
#if not (col.hide?() or col.hide)
dataKey = col.dataKey or col.sortKey or key
if col.canFilterOn? and not col.hide?()
canFilterOn = col.canFilterOn
else
canFilterOn = false
colName = col.header or key
if T9n?
colName = T9n.get(colName)
rtn.push
key: key
dataKey: dataKey
colName: colName
column: col
filterOnThisCol: dataKey is @_sess('filterColumn')
canFilterOn: canFilterOn
hide: col.hide?()
rtn
headers: =>
rtn = []
for key, col of @_cols()
#if not (col.hide?() or col.hide)
dataKey = col.dataKey or col.sortKey or key
if col.canFilterOn? and not col.hide?()
canFilterOn = col.canFilterOn
else
canFilterOn = false
colName = col.header or key
if T9n?
colName = T9n.get(colName)
rtn.push
key: key
dataKey: dataKey
colName: colName
column: col
noSort: col.noSort
sort: dataKey is @_sess('sortColumn')
desc: @_sess('sortDirection') is -1
#sortDirection: if dataKey is @_sess('sortColumn') then -@sortDirection else @sortDirection
filterOnThisCol: dataKey is @_sess('filterColumn')
canFilterOn: canFilterOn
hide: col.hide?()
rtn
limit: ->
@increment
skip: ->
@_sess('skip')
setSort: (dataKey) ->
if dataKey is @_sess('sortColumn')
@_sess('sortDirection', -@_sess('sortDirection'))
@_sess('skip', 0)
else
@_sess('sortColumn', dataKey)
@_sess('sortDirection', @sortDirection)
@_sess('skip', 0)
sort: ->
rtn = {}
rtn[@_sess('sortColumn')] = @_sess('sortDirection')
rtn
subscriptions: -> # was waitOn
#console.log('subscriptions')
@subscribe()
publicationName: ->
@collection().publicationName?() or 'ironTable_publish_'+ @_collectionName()
subscribe: ->
@_subscriptionId = Meteor.subscribe(@publicationName(), @_select(), @sort(), @limit(), @skip())
unsubscribe: ->
@_subscriptionId?.stop?()
@_subscriptionId = null
_select: ->
select = _.extend({}, @select())
filterColumn = @_sess('filterColumn')
filterValue = @_sess('filterValue')
col = @_cols()[filterColumn]
if filterColumn and filterColumn isnt "_none_"
dataKey = col.dataKey or col.sortKey or filterColumn
if col.type is 'boolean'
if filterValue
select[dataKey] = filterValue
else
select[dataKey] =
$ne: true
else if filterValue and col and filterValue isnt ''
select[dataKey] =
$regex: ".*#{filterValue}.*"
$options: 'i'
select
select: ->
@defaultSelect
valueFromRecord: (key, col, record) ->
if record?
if col?.valueFunc?
value = col.valueFunc?(record[key], record)
else if col?.dataKey?
subElements = col.dataKey.split('.')
value = record
for subElement in subElements
value = value?[subElement]
value
else if record[key]?
record[key]
records: ->
@cursor = @collection()?.find @_select(),
sort: @sort()
limit: @limit()
@afterCursor?(@cursor)
@cursor.fetch()
recordsData: ->
recordsData = []
cols = @_cols()
for record in @records()
colData = []
for key, col of cols
dataKey = col.dataKey or col.sortKey or key
if not col.hide?()
value = @valueFromRecord(key, col, record)
if col.display?
value = col.display(value, record, @params)
if col.type is 'boolean' and not col.template?
col.template = 'ironTableCheckbox'
else if col.type is 'select' and not col.template?
col.template = 'ironTableSelect'
colData.push
type : col.type
template : col.template
record : record # Link to full record if we need it
value : value
aLink : col.link?(value, record)
title : col.title?(value, record) or col.title
column : col
dataKey : dataKey
select : col.select
recordsData.push
colData: colData
_id: record._id
recordName: record[@_colToUseForName()]
recordDisplayName: @_recordName() + ' ' + record[@_colToUseForName()]
editOk: @collection().editOk?(record)
deleteOk: @collection().deleteOk?(record)
#extraControls: @extraControls?(record)
recordsData
haveData: ->
@recordCount() > 0 or (not @collection().publishCounts and @records().length > 0)
docsReady: ->
if @collection().publishCounts
@recordCount()?
else
@ready()
recordDisplayStop: ->
@skip() + @records().length
recordDisplayStart: ->
@skip() + 1
recordCount: ->
if @collection().publishCounts
Counts.get(@collection().countName())
else
if @_sess("recordCount") is '...'
@fetchRecordCount()
@_sess("recordCount")
data: ->
# console.log("ironTableController data")
# {}
theData =
increment: @increment
_.extend(theData, @params)
getRecordsName: ->
@_recordsName()
getRecordName: ->
@_recordName()
getNext: ->
if (@skip() + @increment < @recordCount())
@_sess('skip', @skip() + @increment)
nextPathClass: ->
if (@skip() + @increment >= @recordCount())
"disabled"
#else
# "waves-effect "
getPrevious: ->
@_sess('skip', Math.max(@skip() - @increment, 0))
previousPathClass: ->
if (@skip() <= 0)
"disabled"
#else
# "waves-effect"
removeRecord: (rec) ->
name = rec.recordDisplayName
if @collection().methodOnRemove
Meteor.call @collection().methodOnRemove, rec._id, (error) =>
if error
console.log("Error deleting #{name}", error)
Materialize.toast("Error deleting #{name}: #{error.reason}", 3000, 'red')
else
Materialize.toast("Deleted #{name}", 3000, 'green')
@fetchRecordCount()
else
@collection().remove rec._id, (error) =>
if error
console.log("Error deleting #{name}", error)
Materialize.toast("Error deleting #{name}: #{error.reason}", 3000, 'red')
else
Materialize.toast("Deleted #{name}", 3000, 'green')
@fetchRecordCount()
checkFields: (rec, type="insert") ->
@errorMessage = ''
for key, col of @_cols()
try
dataKey = col.dataKey or col.sortKey or key
if type isnt "inlineUpdate" and col.required and (not rec[dataKey]? or rec[dataKey] is '')
col.header = (col.header || key).capitalize()
@errorMessage = ':' + "#{col.header} is required"
return false
else if type is 'insert' and col.onInsert?
rec[dataKey] = col.onInsert()
else if type in ['update', 'inlineUpdate'] and col.onUpdate?
rec[dataKey] = col.onUpdate()
catch error
@errorMessage = ':' + error.reason or error
return false
true
formData: (type, id = null) ->
if type is 'edit' and id?
record = @collection().findOne(id)
else
record = null
if @extraFormData?
_.extend(record, @extraFormData(type))
if @formTemplate is 'ironTableForm'
recordData = []
for key, col of @_cols()
dataKey = col.dataKey or col.sortKey or key
localCol = _.clone(col)
if col[type]?(record) or (col[type] is true) or col["staticOn_#{type}"] or col["hiddenOn_#{type}"]
if col["hiddenOn_#{type}"]
col.type = 'hidden'
if not col.type?
col.type = 'text'
localCol.displayType = col.type
localCol.checkbox = false
localCol.checked = false
value = @valueFromRecord(key, col, record)
if col.type is 'boolean'
localCol.displayType = 'checkbox'
localCol.checkbox = true
if record?[dataKey]?
if record[dataKey]
localCol.checked = true
else if col.default
localCol.checked = true
else if value?
localCol.value = value
else if col.default?
localCol.value = col.default
localCol.realValue = value
if col["staticOn_#{type}"]
localCol.static = true
localCol.value = value
if col?.valueFunc?
localCol.realValue = record[key]
if col["hiddenOn_#{type}"]
localCol.hidden = true
localCol.value = value
if col?.valueFunc?
localCol.realValue = record[key]
localCol.header = (col.header or key).capitalize()
localCol.key = key
localCol.dataKey = dataKey
recordData.push localCol
columns: recordData
else
record
editRecordTitle: ->
'Edit ' + @_recordName().capitalize()
editRecord: (_id) ->
@_sess("currentRecordId", _id)
MaterializeModal.form
bodyTemplate: @formTemplate
title: @editRecordTitle()
columns: @formData('edit', _id).columns
callback: @updateRecord
fullscreen: Meteor.isCordova
fixedFooter: true
updateRecord: (yesNo, rec) =>
@errorMessage = ''
if yesNo
rec = {} unless rec
rec._id = @_sess("currentRecordId") unless rec._id?
if @collection().editOk(rec)
@updateThisRecord(@_sess("currentRecordId"), rec)
updateThisRecord: (recId, rec, type="update") =>
console.log("updateThisRecord", recId, rec)
if @checkFields(rec, type)
if @collection().methodOnUpdate
Meteor.call @collection().methodOnUpdate, recId, rec, (error) =>
if error
console.log("Error updating " + @_recordName(), error)
Materialize.toast("Error updating " + @_recordName() + " : #{error.reason}", 3000, 'red')
else if type isnt "inlineUpdate"
Materialize.toast(@_recordName() + " saved", 3000, 'green')
@fetchRecordCount()
else
delete rec._id
@collection().update recId,
$set: rec
, (error, effectedCount) =>
if error
console.log("Error updating " + @_recordName(), error)
Materialize.toast("Error updating " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
if type isnt "inlineUpdate"
Materialize.toast(@_recordName() + " updated", 3000, 'green')
@fetchRecordCount()
else
Materialize.toast("Error could not update " + @_recordName() + " " + @errorMessage, 3000, 'red')
newRecord: ->
if @newRecordPath?
Router.go(@newRecordPath)
else
MaterializeModal.form
bodyTemplate: @formTemplate
title: 'New ' + @_recordName().capitalize()
columns: @formData('insert').columns
callback: @insertRecord
fullscreen: Meteor.isCordova
fixedFooter: true
insertRecord: (yesNo, rec) =>
@errorMessage = ''
if yesNo
if @collection().insertOk(rec) and @checkFields(rec, 'insert')
if @collection().methodOnInsert
Meteor.call @collection().methodOnInsert, rec, (error) =>
if error
console.log("Error saving " + @_recordName(), error)
Materialize.toast("Error saving " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
Materialize.toast(@_recordName() + " created", 3000, 'green')
@fetchRecordCount()
@newRecordCallback?(rec)
else
@collection().insert rec, (error, effectedCount) =>
if error
console.log("Error saving " + @_recordName(), error)
Materialize.toast("Error saving " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
Materialize.toast(@_recordName() + " created", 3000, 'green')
@fetchRecordCount()
@newRecordCallback?(effectedCount)
else
Materialize.toast("Error could not save " + @_recordName() + " " + @errorMessage, 3000, 'red')
setFilterColumn: (col) ->
if @_sess('filterColumn') isnt col
@_sess('filterColumn', col)
@_sess('filterValue', '')
@_sess('skip', 0)
@fetchRecordCount()
setFilterValue: (value) ->
console.log("setFilterValue", value) if DEBUG
if @_sess('filterValue') isnt value
@_sess('filterValue', value)
@_sess('skip', 0)
@fetchRecordCount()
getFilterValue: ->
@_sess('filterValue')
getSelectedFilterType: ->
filterColumn = @_sess('filterColumn')
if filterColumn?
switch (@_cols()?[filterColumn]?.type)
when 'boolean'
'checkbox'
else
'text'
else
'text'
| 43072 |
#
# Iron Table Controller
#
DEBUG = false
# Capitalize first letter in string
String::capitalize = ->
@charAt(0).toUpperCase() + @slice(1)
class @IronTableController extends RouteController
classID: 'IronTableController'
increment : 20
sortColumn : '_id'
sortDirection : 1
template : 'ironTable'
rowTemplate : 'ironTableRow'
headerTemplate : 'ironTableHeader'
formTemplate : 'ironTableForm'
loadingTemplate : 'ironTableLoading'
defaultSelect : {}
showFilter : false
errorMessage : ''
cursor : null
_subscriptionComplete: false
constructor: ->
super
@reset()
reset: ->
#console.log("reset")
if Meteor.isClient
@_sess("recordCount", "...")
@_sessDefault('skip', 0)
@_sessDefault('sortColumn', @sortColumn)
@_sessDefault('sortDirection', @sortDirection)
@_sessDefault('filterColumn', null)
@_sessDefault('filterValue', '')
@fetchingCount = null
@errorMessage = ''
fetchRecordCount: ->
if not @collection().publishCounts and not @fetchingCount
@fetchingCount = true
# TODO: Set a timeout ?!?!
Meteor.call 'ironTable_' + @_collectionName() + '_recordCount', @_select(), (error, number) =>
@fetchingCount = false
if not error and not @_sessEquals("recordCount", number)
@_sess("recordCount", number)
else if error
console.log('ironTable_' + @_collectionName() + '_recordCount error:', error)
downloadRecords: (callback) ->
fields = {}
if @collection().downloadFields?
fields = @collection().downloadFields
else
for key, col of @_cols()
dataKey = col.dataKey or col.sortKey or key
fields[dataKey] = 1
Meteor.call "ironTable_" + @_collectionName() + "_getCSV", @_select(), fields, callback
# Pain in the ass to set up.... Not using
setupEditRoute: ->
# Set Up Edit Path
editRoutePath = @route.originalPath.replace(/\/[^\/]+$/ , '') + "/edit/:_id"
editRouteName = 'edit' + @collection()._name.capitalize()
@editRouteName = editRouteName
console.log("setup edit route", @editRouteName) if DEBUG
Router.map ->
@route editRouteName,
path: editRoutePath
waitOn: ->
Meteor.subscribe(@collection()._name + 'OneRecord', @params._id)
data: ->
data = @collection()?.findOne
_id: @params._id
data.returnPath = @route.originalPath
getEditRoute: (id) =>
@editRecordRoute
#console.log("getEditRoute", @editRecordRoute, id)
#if @editRecordRoute? and Router.routes[@editRecordRoute]?
# Router.go
# _id: id
_sess: (id, value) ->
key = <KEY>
if value?
Session.set(key, value)
else
Session.get(key)
_sessEquals: (id, value) ->
Session.equals("_ironTable_" + @_collectionName() + id, value)
_sessNull: (id) ->
Session.set("_ironTable_" + @_collectionName() + id, null)
_sessDefault: (id, value) ->
Session.setDefault("_ironTable_" + @_collectionName() + id, value)
#editOk: (record) ->
# false
#deleteOk: (record) ->
# false
#onBeforeAction: (pause) ->
# console.log("onBeforeAction")
onRun: ->
#console.log("onRun", @_collectionName())
@reset()
@next()
onStop: ->
$('[rel="tooltip"]')?.tooltip('destroy')
$('[rel="popover"]')?.popover('destroy')
@unsubscribe()
@reset()
getTableTitle: ->
if not @doNotShowTitle or @showTitleLargeOnly
@tableTitle or @_collectionName()
getSubTitle: ->
@subTitle
_collectionName: ->
@collectionName or @collection()._name
_recordName: ->
@recordName or @collection().recordName or @collection()._name
_recordsName: ->
@recordsName or @collection().recordsName or @_recordName()+'s'
_colToUseForName: ->
@colToUseForName or @collection().colToUseForName or '_id'
doRowLink: ->
@collection()?.doRowLink
_cols: ->
theCol = @cols or @collection()?.schema
if theCol instanceof Array
colObj = {}
for col in theCol
colObj[col] = {}
else
colObj = theCol
colObj
filterHeaders: =>
rtn = []
for key, col of @_cols()
#if not (col.hide?() or col.hide)
dataKey = col.dataKey or col.sortKey or key
if col.canFilterOn? and not col.hide?()
canFilterOn = col.canFilterOn
else
canFilterOn = false
colName = col.header or key
if T9n?
colName = T9n.get(colName)
rtn.push
key: key
dataKey: dataKey
colName: colName
column: col
filterOnThisCol: dataKey is @_sess('filterColumn')
canFilterOn: canFilterOn
hide: col.hide?()
rtn
headers: =>
rtn = []
for key, col of @_cols()
#if not (col.hide?() or col.hide)
dataKey = col.dataKey or col.sortKey or key
if col.canFilterOn? and not col.hide?()
canFilterOn = col.canFilterOn
else
canFilterOn = false
colName = col.header or key
if T9n?
colName = T9n.get(colName)
rtn.push
key: key
dataKey: dataKey
colName: colName
column: col
noSort: col.noSort
sort: dataKey is @_sess('sortColumn')
desc: @_sess('sortDirection') is -1
#sortDirection: if dataKey is @_sess('sortColumn') then -@sortDirection else @sortDirection
filterOnThisCol: dataKey is @_sess('filterColumn')
canFilterOn: canFilterOn
hide: col.hide?()
rtn
limit: ->
@increment
skip: ->
@_sess('skip')
setSort: (dataKey) ->
if dataKey is @_sess('sortColumn')
@_sess('sortDirection', -@_sess('sortDirection'))
@_sess('skip', 0)
else
@_sess('sortColumn', dataKey)
@_sess('sortDirection', @sortDirection)
@_sess('skip', 0)
sort: ->
rtn = {}
rtn[@_sess('sortColumn')] = @_sess('sortDirection')
rtn
subscriptions: -> # was waitOn
#console.log('subscriptions')
@subscribe()
publicationName: ->
@collection().publicationName?() or 'ironTable_publish_'+ @_collectionName()
subscribe: ->
@_subscriptionId = Meteor.subscribe(@publicationName(), @_select(), @sort(), @limit(), @skip())
unsubscribe: ->
@_subscriptionId?.stop?()
@_subscriptionId = null
_select: ->
select = _.extend({}, @select())
filterColumn = @_sess('filterColumn')
filterValue = @_sess('filterValue')
col = @_cols()[filterColumn]
if filterColumn and filterColumn isnt "_none_"
dataKey = col.dataKey or col.sortKey or filterColumn
if col.type is 'boolean'
if filterValue
select[dataKey] = filterValue
else
select[dataKey] =
$ne: true
else if filterValue and col and filterValue isnt ''
select[dataKey] =
$regex: ".*#{filterValue}.*"
$options: 'i'
select
select: ->
@defaultSelect
valueFromRecord: (key, col, record) ->
if record?
if col?.valueFunc?
value = col.valueFunc?(record[key], record)
else if col?.dataKey?
subElements = col.dataKey.split('.')
value = record
for subElement in subElements
value = value?[subElement]
value
else if record[key]?
record[key]
records: ->
@cursor = @collection()?.find @_select(),
sort: @sort()
limit: @limit()
@afterCursor?(@cursor)
@cursor.fetch()
recordsData: ->
recordsData = []
cols = @_cols()
for record in @records()
colData = []
for key, col of cols
dataKey = col.dataKey or col.sortKey or key
if not col.hide?()
value = @valueFromRecord(key, col, record)
if col.display?
value = col.display(value, record, @params)
if col.type is 'boolean' and not col.template?
col.template = 'ironTableCheckbox'
else if col.type is 'select' and not col.template?
col.template = 'ironTableSelect'
colData.push
type : col.type
template : col.template
record : record # Link to full record if we need it
value : value
aLink : col.link?(value, record)
title : col.title?(value, record) or col.title
column : col
dataKey : dataKey
select : col.select
recordsData.push
colData: colData
_id: record._id
recordName: record[@_colToUseForName()]
recordDisplayName: @_recordName() + ' ' + record[@_colToUseForName()]
editOk: @collection().editOk?(record)
deleteOk: @collection().deleteOk?(record)
#extraControls: @extraControls?(record)
recordsData
haveData: ->
@recordCount() > 0 or (not @collection().publishCounts and @records().length > 0)
docsReady: ->
if @collection().publishCounts
@recordCount()?
else
@ready()
recordDisplayStop: ->
@skip() + @records().length
recordDisplayStart: ->
@skip() + 1
recordCount: ->
if @collection().publishCounts
Counts.get(@collection().countName())
else
if @_sess("recordCount") is '...'
@fetchRecordCount()
@_sess("recordCount")
data: ->
# console.log("ironTableController data")
# {}
theData =
increment: @increment
_.extend(theData, @params)
getRecordsName: ->
@_recordsName()
getRecordName: ->
@_recordName()
getNext: ->
if (@skip() + @increment < @recordCount())
@_sess('skip', @skip() + @increment)
nextPathClass: ->
if (@skip() + @increment >= @recordCount())
"disabled"
#else
# "waves-effect "
getPrevious: ->
@_sess('skip', Math.max(@skip() - @increment, 0))
previousPathClass: ->
if (@skip() <= 0)
"disabled"
#else
# "waves-effect"
removeRecord: (rec) ->
name = rec.recordDisplayName
if @collection().methodOnRemove
Meteor.call @collection().methodOnRemove, rec._id, (error) =>
if error
console.log("Error deleting #{name}", error)
Materialize.toast("Error deleting #{name}: #{error.reason}", 3000, 'red')
else
Materialize.toast("Deleted #{name}", 3000, 'green')
@fetchRecordCount()
else
@collection().remove rec._id, (error) =>
if error
console.log("Error deleting #{name}", error)
Materialize.toast("Error deleting #{name}: #{error.reason}", 3000, 'red')
else
Materialize.toast("Deleted #{name}", 3000, 'green')
@fetchRecordCount()
checkFields: (rec, type="insert") ->
@errorMessage = ''
for key, col of @_cols()
try
dataKey = col.dataKey or col.sortKey or key
if type isnt "inlineUpdate" and col.required and (not rec[dataKey]? or rec[dataKey] is '')
col.header = (col.header || key).capitalize()
@errorMessage = ':' + "#{col.header} is required"
return false
else if type is 'insert' and col.onInsert?
rec[dataKey] = col.onInsert()
else if type in ['update', 'inlineUpdate'] and col.onUpdate?
rec[dataKey] = col.onUpdate()
catch error
@errorMessage = ':' + error.reason or error
return false
true
formData: (type, id = null) ->
if type is 'edit' and id?
record = @collection().findOne(id)
else
record = null
if @extraFormData?
_.extend(record, @extraFormData(type))
if @formTemplate is 'ironTableForm'
recordData = []
for key, col of @_cols()
dataKey = col.dataKey or col.sortKey or key
localCol = _.clone(col)
if col[type]?(record) or (col[type] is true) or col["staticOn_#{type}"] or col["hiddenOn_#{type}"]
if col["hiddenOn_#{type}"]
col.type = 'hidden'
if not col.type?
col.type = 'text'
localCol.displayType = col.type
localCol.checkbox = false
localCol.checked = false
value = @valueFromRecord(key, col, record)
if col.type is 'boolean'
localCol.displayType = 'checkbox'
localCol.checkbox = true
if record?[dataKey]?
if record[dataKey]
localCol.checked = true
else if col.default
localCol.checked = true
else if value?
localCol.value = value
else if col.default?
localCol.value = col.default
localCol.realValue = value
if col["staticOn_#{type}"]
localCol.static = true
localCol.value = value
if col?.valueFunc?
localCol.realValue = record[key]
if col["hiddenOn_#{type}"]
localCol.hidden = true
localCol.value = value
if col?.valueFunc?
localCol.realValue = record[key]
localCol.header = (col.header or key).capitalize()
localCol.key = key
localCol.dataKey = dataKey
recordData.push localCol
columns: recordData
else
record
editRecordTitle: ->
'Edit ' + @_recordName().capitalize()
editRecord: (_id) ->
@_sess("currentRecordId", _id)
MaterializeModal.form
bodyTemplate: @formTemplate
title: @editRecordTitle()
columns: @formData('edit', _id).columns
callback: @updateRecord
fullscreen: Meteor.isCordova
fixedFooter: true
updateRecord: (yesNo, rec) =>
@errorMessage = ''
if yesNo
rec = {} unless rec
rec._id = @_sess("currentRecordId") unless rec._id?
if @collection().editOk(rec)
@updateThisRecord(@_sess("currentRecordId"), rec)
updateThisRecord: (recId, rec, type="update") =>
console.log("updateThisRecord", recId, rec)
if @checkFields(rec, type)
if @collection().methodOnUpdate
Meteor.call @collection().methodOnUpdate, recId, rec, (error) =>
if error
console.log("Error updating " + @_recordName(), error)
Materialize.toast("Error updating " + @_recordName() + " : #{error.reason}", 3000, 'red')
else if type isnt "inlineUpdate"
Materialize.toast(@_recordName() + " saved", 3000, 'green')
@fetchRecordCount()
else
delete rec._id
@collection().update recId,
$set: rec
, (error, effectedCount) =>
if error
console.log("Error updating " + @_recordName(), error)
Materialize.toast("Error updating " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
if type isnt "inlineUpdate"
Materialize.toast(@_recordName() + " updated", 3000, 'green')
@fetchRecordCount()
else
Materialize.toast("Error could not update " + @_recordName() + " " + @errorMessage, 3000, 'red')
newRecord: ->
if @newRecordPath?
Router.go(@newRecordPath)
else
MaterializeModal.form
bodyTemplate: @formTemplate
title: 'New ' + @_recordName().capitalize()
columns: @formData('insert').columns
callback: @insertRecord
fullscreen: Meteor.isCordova
fixedFooter: true
insertRecord: (yesNo, rec) =>
@errorMessage = ''
if yesNo
if @collection().insertOk(rec) and @checkFields(rec, 'insert')
if @collection().methodOnInsert
Meteor.call @collection().methodOnInsert, rec, (error) =>
if error
console.log("Error saving " + @_recordName(), error)
Materialize.toast("Error saving " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
Materialize.toast(@_recordName() + " created", 3000, 'green')
@fetchRecordCount()
@newRecordCallback?(rec)
else
@collection().insert rec, (error, effectedCount) =>
if error
console.log("Error saving " + @_recordName(), error)
Materialize.toast("Error saving " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
Materialize.toast(@_recordName() + " created", 3000, 'green')
@fetchRecordCount()
@newRecordCallback?(effectedCount)
else
Materialize.toast("Error could not save " + @_recordName() + " " + @errorMessage, 3000, 'red')
setFilterColumn: (col) ->
if @_sess('filterColumn') isnt col
@_sess('filterColumn', col)
@_sess('filterValue', '')
@_sess('skip', 0)
@fetchRecordCount()
setFilterValue: (value) ->
console.log("setFilterValue", value) if DEBUG
if @_sess('filterValue') isnt value
@_sess('filterValue', value)
@_sess('skip', 0)
@fetchRecordCount()
getFilterValue: ->
@_sess('filterValue')
getSelectedFilterType: ->
filterColumn = @_sess('filterColumn')
if filterColumn?
switch (@_cols()?[filterColumn]?.type)
when 'boolean'
'checkbox'
else
'text'
else
'text'
| true |
#
# Iron Table Controller
#
DEBUG = false
# Capitalize first letter in string
String::capitalize = ->
@charAt(0).toUpperCase() + @slice(1)
class @IronTableController extends RouteController
classID: 'IronTableController'
increment : 20
sortColumn : '_id'
sortDirection : 1
template : 'ironTable'
rowTemplate : 'ironTableRow'
headerTemplate : 'ironTableHeader'
formTemplate : 'ironTableForm'
loadingTemplate : 'ironTableLoading'
defaultSelect : {}
showFilter : false
errorMessage : ''
cursor : null
_subscriptionComplete: false
constructor: ->
super
@reset()
reset: ->
#console.log("reset")
if Meteor.isClient
@_sess("recordCount", "...")
@_sessDefault('skip', 0)
@_sessDefault('sortColumn', @sortColumn)
@_sessDefault('sortDirection', @sortDirection)
@_sessDefault('filterColumn', null)
@_sessDefault('filterValue', '')
@fetchingCount = null
@errorMessage = ''
fetchRecordCount: ->
if not @collection().publishCounts and not @fetchingCount
@fetchingCount = true
# TODO: Set a timeout ?!?!
Meteor.call 'ironTable_' + @_collectionName() + '_recordCount', @_select(), (error, number) =>
@fetchingCount = false
if not error and not @_sessEquals("recordCount", number)
@_sess("recordCount", number)
else if error
console.log('ironTable_' + @_collectionName() + '_recordCount error:', error)
downloadRecords: (callback) ->
fields = {}
if @collection().downloadFields?
fields = @collection().downloadFields
else
for key, col of @_cols()
dataKey = col.dataKey or col.sortKey or key
fields[dataKey] = 1
Meteor.call "ironTable_" + @_collectionName() + "_getCSV", @_select(), fields, callback
# Pain in the ass to set up.... Not using
setupEditRoute: ->
# Set Up Edit Path
editRoutePath = @route.originalPath.replace(/\/[^\/]+$/ , '') + "/edit/:_id"
editRouteName = 'edit' + @collection()._name.capitalize()
@editRouteName = editRouteName
console.log("setup edit route", @editRouteName) if DEBUG
Router.map ->
@route editRouteName,
path: editRoutePath
waitOn: ->
Meteor.subscribe(@collection()._name + 'OneRecord', @params._id)
data: ->
data = @collection()?.findOne
_id: @params._id
data.returnPath = @route.originalPath
getEditRoute: (id) =>
@editRecordRoute
#console.log("getEditRoute", @editRecordRoute, id)
#if @editRecordRoute? and Router.routes[@editRecordRoute]?
# Router.go
# _id: id
_sess: (id, value) ->
key = PI:KEY:<KEY>END_PI
if value?
Session.set(key, value)
else
Session.get(key)
_sessEquals: (id, value) ->
Session.equals("_ironTable_" + @_collectionName() + id, value)
_sessNull: (id) ->
Session.set("_ironTable_" + @_collectionName() + id, null)
_sessDefault: (id, value) ->
Session.setDefault("_ironTable_" + @_collectionName() + id, value)
#editOk: (record) ->
# false
#deleteOk: (record) ->
# false
#onBeforeAction: (pause) ->
# console.log("onBeforeAction")
onRun: ->
#console.log("onRun", @_collectionName())
@reset()
@next()
onStop: ->
$('[rel="tooltip"]')?.tooltip('destroy')
$('[rel="popover"]')?.popover('destroy')
@unsubscribe()
@reset()
getTableTitle: ->
if not @doNotShowTitle or @showTitleLargeOnly
@tableTitle or @_collectionName()
getSubTitle: ->
@subTitle
_collectionName: ->
@collectionName or @collection()._name
_recordName: ->
@recordName or @collection().recordName or @collection()._name
_recordsName: ->
@recordsName or @collection().recordsName or @_recordName()+'s'
_colToUseForName: ->
@colToUseForName or @collection().colToUseForName or '_id'
doRowLink: ->
@collection()?.doRowLink
_cols: ->
theCol = @cols or @collection()?.schema
if theCol instanceof Array
colObj = {}
for col in theCol
colObj[col] = {}
else
colObj = theCol
colObj
filterHeaders: =>
rtn = []
for key, col of @_cols()
#if not (col.hide?() or col.hide)
dataKey = col.dataKey or col.sortKey or key
if col.canFilterOn? and not col.hide?()
canFilterOn = col.canFilterOn
else
canFilterOn = false
colName = col.header or key
if T9n?
colName = T9n.get(colName)
rtn.push
key: key
dataKey: dataKey
colName: colName
column: col
filterOnThisCol: dataKey is @_sess('filterColumn')
canFilterOn: canFilterOn
hide: col.hide?()
rtn
headers: =>
rtn = []
for key, col of @_cols()
#if not (col.hide?() or col.hide)
dataKey = col.dataKey or col.sortKey or key
if col.canFilterOn? and not col.hide?()
canFilterOn = col.canFilterOn
else
canFilterOn = false
colName = col.header or key
if T9n?
colName = T9n.get(colName)
rtn.push
key: key
dataKey: dataKey
colName: colName
column: col
noSort: col.noSort
sort: dataKey is @_sess('sortColumn')
desc: @_sess('sortDirection') is -1
#sortDirection: if dataKey is @_sess('sortColumn') then -@sortDirection else @sortDirection
filterOnThisCol: dataKey is @_sess('filterColumn')
canFilterOn: canFilterOn
hide: col.hide?()
rtn
limit: ->
@increment
skip: ->
@_sess('skip')
setSort: (dataKey) ->
if dataKey is @_sess('sortColumn')
@_sess('sortDirection', -@_sess('sortDirection'))
@_sess('skip', 0)
else
@_sess('sortColumn', dataKey)
@_sess('sortDirection', @sortDirection)
@_sess('skip', 0)
sort: ->
rtn = {}
rtn[@_sess('sortColumn')] = @_sess('sortDirection')
rtn
subscriptions: -> # was waitOn
#console.log('subscriptions')
@subscribe()
publicationName: ->
@collection().publicationName?() or 'ironTable_publish_'+ @_collectionName()
subscribe: ->
@_subscriptionId = Meteor.subscribe(@publicationName(), @_select(), @sort(), @limit(), @skip())
unsubscribe: ->
@_subscriptionId?.stop?()
@_subscriptionId = null
_select: ->
select = _.extend({}, @select())
filterColumn = @_sess('filterColumn')
filterValue = @_sess('filterValue')
col = @_cols()[filterColumn]
if filterColumn and filterColumn isnt "_none_"
dataKey = col.dataKey or col.sortKey or filterColumn
if col.type is 'boolean'
if filterValue
select[dataKey] = filterValue
else
select[dataKey] =
$ne: true
else if filterValue and col and filterValue isnt ''
select[dataKey] =
$regex: ".*#{filterValue}.*"
$options: 'i'
select
select: ->
@defaultSelect
valueFromRecord: (key, col, record) ->
if record?
if col?.valueFunc?
value = col.valueFunc?(record[key], record)
else if col?.dataKey?
subElements = col.dataKey.split('.')
value = record
for subElement in subElements
value = value?[subElement]
value
else if record[key]?
record[key]
records: ->
@cursor = @collection()?.find @_select(),
sort: @sort()
limit: @limit()
@afterCursor?(@cursor)
@cursor.fetch()
recordsData: ->
recordsData = []
cols = @_cols()
for record in @records()
colData = []
for key, col of cols
dataKey = col.dataKey or col.sortKey or key
if not col.hide?()
value = @valueFromRecord(key, col, record)
if col.display?
value = col.display(value, record, @params)
if col.type is 'boolean' and not col.template?
col.template = 'ironTableCheckbox'
else if col.type is 'select' and not col.template?
col.template = 'ironTableSelect'
colData.push
type : col.type
template : col.template
record : record # Link to full record if we need it
value : value
aLink : col.link?(value, record)
title : col.title?(value, record) or col.title
column : col
dataKey : dataKey
select : col.select
recordsData.push
colData: colData
_id: record._id
recordName: record[@_colToUseForName()]
recordDisplayName: @_recordName() + ' ' + record[@_colToUseForName()]
editOk: @collection().editOk?(record)
deleteOk: @collection().deleteOk?(record)
#extraControls: @extraControls?(record)
recordsData
haveData: ->
@recordCount() > 0 or (not @collection().publishCounts and @records().length > 0)
docsReady: ->
if @collection().publishCounts
@recordCount()?
else
@ready()
recordDisplayStop: ->
@skip() + @records().length
recordDisplayStart: ->
@skip() + 1
recordCount: ->
if @collection().publishCounts
Counts.get(@collection().countName())
else
if @_sess("recordCount") is '...'
@fetchRecordCount()
@_sess("recordCount")
data: ->
# console.log("ironTableController data")
# {}
theData =
increment: @increment
_.extend(theData, @params)
getRecordsName: ->
@_recordsName()
getRecordName: ->
@_recordName()
getNext: ->
if (@skip() + @increment < @recordCount())
@_sess('skip', @skip() + @increment)
nextPathClass: ->
if (@skip() + @increment >= @recordCount())
"disabled"
#else
# "waves-effect "
getPrevious: ->
@_sess('skip', Math.max(@skip() - @increment, 0))
previousPathClass: ->
if (@skip() <= 0)
"disabled"
#else
# "waves-effect"
removeRecord: (rec) ->
name = rec.recordDisplayName
if @collection().methodOnRemove
Meteor.call @collection().methodOnRemove, rec._id, (error) =>
if error
console.log("Error deleting #{name}", error)
Materialize.toast("Error deleting #{name}: #{error.reason}", 3000, 'red')
else
Materialize.toast("Deleted #{name}", 3000, 'green')
@fetchRecordCount()
else
@collection().remove rec._id, (error) =>
if error
console.log("Error deleting #{name}", error)
Materialize.toast("Error deleting #{name}: #{error.reason}", 3000, 'red')
else
Materialize.toast("Deleted #{name}", 3000, 'green')
@fetchRecordCount()
checkFields: (rec, type="insert") ->
@errorMessage = ''
for key, col of @_cols()
try
dataKey = col.dataKey or col.sortKey or key
if type isnt "inlineUpdate" and col.required and (not rec[dataKey]? or rec[dataKey] is '')
col.header = (col.header || key).capitalize()
@errorMessage = ':' + "#{col.header} is required"
return false
else if type is 'insert' and col.onInsert?
rec[dataKey] = col.onInsert()
else if type in ['update', 'inlineUpdate'] and col.onUpdate?
rec[dataKey] = col.onUpdate()
catch error
@errorMessage = ':' + error.reason or error
return false
true
formData: (type, id = null) ->
if type is 'edit' and id?
record = @collection().findOne(id)
else
record = null
if @extraFormData?
_.extend(record, @extraFormData(type))
if @formTemplate is 'ironTableForm'
recordData = []
for key, col of @_cols()
dataKey = col.dataKey or col.sortKey or key
localCol = _.clone(col)
if col[type]?(record) or (col[type] is true) or col["staticOn_#{type}"] or col["hiddenOn_#{type}"]
if col["hiddenOn_#{type}"]
col.type = 'hidden'
if not col.type?
col.type = 'text'
localCol.displayType = col.type
localCol.checkbox = false
localCol.checked = false
value = @valueFromRecord(key, col, record)
if col.type is 'boolean'
localCol.displayType = 'checkbox'
localCol.checkbox = true
if record?[dataKey]?
if record[dataKey]
localCol.checked = true
else if col.default
localCol.checked = true
else if value?
localCol.value = value
else if col.default?
localCol.value = col.default
localCol.realValue = value
if col["staticOn_#{type}"]
localCol.static = true
localCol.value = value
if col?.valueFunc?
localCol.realValue = record[key]
if col["hiddenOn_#{type}"]
localCol.hidden = true
localCol.value = value
if col?.valueFunc?
localCol.realValue = record[key]
localCol.header = (col.header or key).capitalize()
localCol.key = key
localCol.dataKey = dataKey
recordData.push localCol
columns: recordData
else
record
editRecordTitle: ->
'Edit ' + @_recordName().capitalize()
editRecord: (_id) ->
@_sess("currentRecordId", _id)
MaterializeModal.form
bodyTemplate: @formTemplate
title: @editRecordTitle()
columns: @formData('edit', _id).columns
callback: @updateRecord
fullscreen: Meteor.isCordova
fixedFooter: true
updateRecord: (yesNo, rec) =>
@errorMessage = ''
if yesNo
rec = {} unless rec
rec._id = @_sess("currentRecordId") unless rec._id?
if @collection().editOk(rec)
@updateThisRecord(@_sess("currentRecordId"), rec)
updateThisRecord: (recId, rec, type="update") =>
console.log("updateThisRecord", recId, rec)
if @checkFields(rec, type)
if @collection().methodOnUpdate
Meteor.call @collection().methodOnUpdate, recId, rec, (error) =>
if error
console.log("Error updating " + @_recordName(), error)
Materialize.toast("Error updating " + @_recordName() + " : #{error.reason}", 3000, 'red')
else if type isnt "inlineUpdate"
Materialize.toast(@_recordName() + " saved", 3000, 'green')
@fetchRecordCount()
else
delete rec._id
@collection().update recId,
$set: rec
, (error, effectedCount) =>
if error
console.log("Error updating " + @_recordName(), error)
Materialize.toast("Error updating " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
if type isnt "inlineUpdate"
Materialize.toast(@_recordName() + " updated", 3000, 'green')
@fetchRecordCount()
else
Materialize.toast("Error could not update " + @_recordName() + " " + @errorMessage, 3000, 'red')
newRecord: ->
if @newRecordPath?
Router.go(@newRecordPath)
else
MaterializeModal.form
bodyTemplate: @formTemplate
title: 'New ' + @_recordName().capitalize()
columns: @formData('insert').columns
callback: @insertRecord
fullscreen: Meteor.isCordova
fixedFooter: true
insertRecord: (yesNo, rec) =>
@errorMessage = ''
if yesNo
if @collection().insertOk(rec) and @checkFields(rec, 'insert')
if @collection().methodOnInsert
Meteor.call @collection().methodOnInsert, rec, (error) =>
if error
console.log("Error saving " + @_recordName(), error)
Materialize.toast("Error saving " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
Materialize.toast(@_recordName() + " created", 3000, 'green')
@fetchRecordCount()
@newRecordCallback?(rec)
else
@collection().insert rec, (error, effectedCount) =>
if error
console.log("Error saving " + @_recordName(), error)
Materialize.toast("Error saving " + @_recordName() + " : #{error.reason}", 3000, 'red')
else
Materialize.toast(@_recordName() + " created", 3000, 'green')
@fetchRecordCount()
@newRecordCallback?(effectedCount)
else
Materialize.toast("Error could not save " + @_recordName() + " " + @errorMessage, 3000, 'red')
setFilterColumn: (col) ->
if @_sess('filterColumn') isnt col
@_sess('filterColumn', col)
@_sess('filterValue', '')
@_sess('skip', 0)
@fetchRecordCount()
setFilterValue: (value) ->
console.log("setFilterValue", value) if DEBUG
if @_sess('filterValue') isnt value
@_sess('filterValue', value)
@_sess('skip', 0)
@fetchRecordCount()
getFilterValue: ->
@_sess('filterValue')
getSelectedFilterType: ->
filterColumn = @_sess('filterColumn')
if filterColumn?
switch (@_cols()?[filterColumn]?.type)
when 'boolean'
'checkbox'
else
'text'
else
'text'
|
[
{
"context": "\n params = @request.body\n fields = [\n 'firstName'\n 'middleName'\n 'lastName'\n 'phone",
"end": 1641,
"score": 0.9933337569236755,
"start": 1632,
"tag": "NAME",
"value": "firstName"
},
{
"context": "uest.body\n fields = [\n 'firstName'\n 'middleName'\n 'lastName'\n 'phone'\n 'dob'\n ",
"end": 1656,
"score": 0.994255006313324,
"start": 1650,
"tag": "NAME",
"value": "middle"
},
{
"context": "s = [\n 'firstName'\n 'middleName'\n 'lastName'\n 'phone'\n 'dob'\n 'ssn'\n 'sta",
"end": 1677,
"score": 0.9952671527862549,
"start": 1669,
"tag": "NAME",
"value": "lastName"
},
{
"context": "yield return\n\n edit: () ->\n fields = [\n 'firstName'\n 'middleName'\n 'lastName'\n 'phone",
"end": 2420,
"score": 0.8811227679252625,
"start": 2411,
"tag": "NAME",
"value": "firstName"
},
{
"context": "it: () ->\n fields = [\n 'firstName'\n 'middleName'\n 'lastName'\n 'phone'\n 'dob'\n ",
"end": 2435,
"score": 0.8763083219528198,
"start": 2429,
"tag": "NAME",
"value": "middle"
},
{
"context": "s = [\n 'firstName'\n 'middleName'\n 'lastName'\n 'phone'\n 'dob'\n 'ssn'\n 'sta",
"end": 2456,
"score": 0.9202032089233398,
"start": 2448,
"tag": "NAME",
"value": "lastName"
}
] | src/controllers/client.coffee | evanhuang8/teresa | 0 | moment = require 'moment-timezone'
db = require '../db'
Client = db.model 'Client'
Checkup = db.model 'Checkup'
Referral = db.model 'Referral'
Service = db.model 'Service'
Organization = db.model 'Organization'
sequelize = require 'sequelize'
SqlString = require 'sequelize/lib/sql-string'
queue = require '../tasks/queue'
CURD = require '../utils/curd'
module.exports =
index: () ->
id = @request.query.id
client = yield Client.findById id
if client?
referrals = yield Referral.findAll
include: [
model: Service
as: 'service'
,
model: Organization
as: 'referee'
,
model: Organization
as: 'referer'
]
where:
clientId: client.id
order: [
['createdAt', 'DESC']
]
@render 'client/index',
user: @passport.user
client: client
referrals: referrals
else
@render 'client/list',
user: @passport.user
yield return
list: () ->
keyword = @request.query.keyword
@render 'client/list',
user: @passport.user
keyword: keyword
yield return
add: () ->
@render 'client/add',
user: @passport.user
yield return
update: () ->
id = @request.query.id
client = yield Client.findById id
if not client?
@status = 404
return
@render 'client/edit',
client: client,
user: @passport.user
yield return
create: () ->
if not @passport.user?
@status = 403
return
user = @passport.user
params = @request.body
fields = [
'firstName'
'middleName'
'lastName'
'phone'
'dob'
'ssn'
'stage'
]
client = Client.build()
for field in fields
client[field] = params[field]
yield client.save()
@status = 201
if params.checkupAt?
start = moment.tz params.checkupAt, 'US/Central'
checkup = yield Checkup.create
start: new Date start.valueOf()
clientId: client.id
organizationId: user.organizationId
task = yield queue.add
name: 'general'
params:
type: 'scheduleCheckup'
id: checkup.id
eta: start.clone()
checkup.task = task.id
yield checkup.save()
@body =
status: 'OK'
obj: client
yield return
edit: () ->
fields = [
'firstName'
'middleName'
'lastName'
'phone'
'dob'
'ssn'
'stage'
]
yield CURD.update.call this, Client, fields
return
fetch: () ->
keyword = @request.body.keyword
page = 0
if @request.body.page?
page = parseInt @request.body.page
if not (page > 0)
page = 0
limit = 20
offset = limit * page
query = "
SELECT `Clients`.* FROM `Clients`
"
if keyword?
query += "
WHERE `Clients`.`firstName` LIKE #{SqlString.escape('%' + keyword + '%')}
OR `Clients`.`lastName` LIKE #{SqlString.escape('%' + keyword + '%')}
"
query += "
ORDER BY `Clients`.`lastName` ASC
"
totalQuery = "SELECT Count(*) AS total FROM (#{query}) AS tq"
totalResults = yield db.client.query totalQuery,
type: sequelize.QueryTypes.SELECT
query += ' '
query += "
LIMIT #{limit}
OFFSET #{offset}
"
clients = yield db.client.query query,
type: sequelize.QueryTypes.SELECT
@body =
status: 'OK'
clients: clients
total: totalResults[0].total/limit
yield return
fetch_single: () ->
id = @request.body.id
client = yield Client.findById id
if not client?
@body =
status: 'FAIL'
message: 'The client does not exist'
return
@body =
status: 'OK'
client: client
yield return
| 2026 | moment = require 'moment-timezone'
db = require '../db'
Client = db.model 'Client'
Checkup = db.model 'Checkup'
Referral = db.model 'Referral'
Service = db.model 'Service'
Organization = db.model 'Organization'
sequelize = require 'sequelize'
SqlString = require 'sequelize/lib/sql-string'
queue = require '../tasks/queue'
CURD = require '../utils/curd'
module.exports =
index: () ->
id = @request.query.id
client = yield Client.findById id
if client?
referrals = yield Referral.findAll
include: [
model: Service
as: 'service'
,
model: Organization
as: 'referee'
,
model: Organization
as: 'referer'
]
where:
clientId: client.id
order: [
['createdAt', 'DESC']
]
@render 'client/index',
user: @passport.user
client: client
referrals: referrals
else
@render 'client/list',
user: @passport.user
yield return
list: () ->
keyword = @request.query.keyword
@render 'client/list',
user: @passport.user
keyword: keyword
yield return
add: () ->
@render 'client/add',
user: @passport.user
yield return
update: () ->
id = @request.query.id
client = yield Client.findById id
if not client?
@status = 404
return
@render 'client/edit',
client: client,
user: @passport.user
yield return
create: () ->
if not @passport.user?
@status = 403
return
user = @passport.user
params = @request.body
fields = [
'<NAME>'
'<NAME>Name'
'<NAME>'
'phone'
'dob'
'ssn'
'stage'
]
client = Client.build()
for field in fields
client[field] = params[field]
yield client.save()
@status = 201
if params.checkupAt?
start = moment.tz params.checkupAt, 'US/Central'
checkup = yield Checkup.create
start: new Date start.valueOf()
clientId: client.id
organizationId: user.organizationId
task = yield queue.add
name: 'general'
params:
type: 'scheduleCheckup'
id: checkup.id
eta: start.clone()
checkup.task = task.id
yield checkup.save()
@body =
status: 'OK'
obj: client
yield return
edit: () ->
fields = [
'<NAME>'
'<NAME>Name'
'<NAME>'
'phone'
'dob'
'ssn'
'stage'
]
yield CURD.update.call this, Client, fields
return
fetch: () ->
keyword = @request.body.keyword
page = 0
if @request.body.page?
page = parseInt @request.body.page
if not (page > 0)
page = 0
limit = 20
offset = limit * page
query = "
SELECT `Clients`.* FROM `Clients`
"
if keyword?
query += "
WHERE `Clients`.`firstName` LIKE #{SqlString.escape('%' + keyword + '%')}
OR `Clients`.`lastName` LIKE #{SqlString.escape('%' + keyword + '%')}
"
query += "
ORDER BY `Clients`.`lastName` ASC
"
totalQuery = "SELECT Count(*) AS total FROM (#{query}) AS tq"
totalResults = yield db.client.query totalQuery,
type: sequelize.QueryTypes.SELECT
query += ' '
query += "
LIMIT #{limit}
OFFSET #{offset}
"
clients = yield db.client.query query,
type: sequelize.QueryTypes.SELECT
@body =
status: 'OK'
clients: clients
total: totalResults[0].total/limit
yield return
fetch_single: () ->
id = @request.body.id
client = yield Client.findById id
if not client?
@body =
status: 'FAIL'
message: 'The client does not exist'
return
@body =
status: 'OK'
client: client
yield return
| true | moment = require 'moment-timezone'
db = require '../db'
Client = db.model 'Client'
Checkup = db.model 'Checkup'
Referral = db.model 'Referral'
Service = db.model 'Service'
Organization = db.model 'Organization'
sequelize = require 'sequelize'
SqlString = require 'sequelize/lib/sql-string'
queue = require '../tasks/queue'
CURD = require '../utils/curd'
module.exports =
index: () ->
id = @request.query.id
client = yield Client.findById id
if client?
referrals = yield Referral.findAll
include: [
model: Service
as: 'service'
,
model: Organization
as: 'referee'
,
model: Organization
as: 'referer'
]
where:
clientId: client.id
order: [
['createdAt', 'DESC']
]
@render 'client/index',
user: @passport.user
client: client
referrals: referrals
else
@render 'client/list',
user: @passport.user
yield return
list: () ->
keyword = @request.query.keyword
@render 'client/list',
user: @passport.user
keyword: keyword
yield return
add: () ->
@render 'client/add',
user: @passport.user
yield return
update: () ->
id = @request.query.id
client = yield Client.findById id
if not client?
@status = 404
return
@render 'client/edit',
client: client,
user: @passport.user
yield return
create: () ->
if not @passport.user?
@status = 403
return
user = @passport.user
params = @request.body
fields = [
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PIName'
'PI:NAME:<NAME>END_PI'
'phone'
'dob'
'ssn'
'stage'
]
client = Client.build()
for field in fields
client[field] = params[field]
yield client.save()
@status = 201
if params.checkupAt?
start = moment.tz params.checkupAt, 'US/Central'
checkup = yield Checkup.create
start: new Date start.valueOf()
clientId: client.id
organizationId: user.organizationId
task = yield queue.add
name: 'general'
params:
type: 'scheduleCheckup'
id: checkup.id
eta: start.clone()
checkup.task = task.id
yield checkup.save()
@body =
status: 'OK'
obj: client
yield return
edit: () ->
fields = [
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PIName'
'PI:NAME:<NAME>END_PI'
'phone'
'dob'
'ssn'
'stage'
]
yield CURD.update.call this, Client, fields
return
fetch: () ->
keyword = @request.body.keyword
page = 0
if @request.body.page?
page = parseInt @request.body.page
if not (page > 0)
page = 0
limit = 20
offset = limit * page
query = "
SELECT `Clients`.* FROM `Clients`
"
if keyword?
query += "
WHERE `Clients`.`firstName` LIKE #{SqlString.escape('%' + keyword + '%')}
OR `Clients`.`lastName` LIKE #{SqlString.escape('%' + keyword + '%')}
"
query += "
ORDER BY `Clients`.`lastName` ASC
"
totalQuery = "SELECT Count(*) AS total FROM (#{query}) AS tq"
totalResults = yield db.client.query totalQuery,
type: sequelize.QueryTypes.SELECT
query += ' '
query += "
LIMIT #{limit}
OFFSET #{offset}
"
clients = yield db.client.query query,
type: sequelize.QueryTypes.SELECT
@body =
status: 'OK'
clients: clients
total: totalResults[0].total/limit
yield return
fetch_single: () ->
id = @request.body.id
client = yield Client.findById id
if not client?
@body =
status: 'FAIL'
message: 'The client does not exist'
return
@body =
status: 'OK'
client: client
yield return
|
[
{
"context": "nnel.control.indexOf(client) > -1 && password == \"delete\"\n channel.destroy(client)\n return clien",
"end": 4885,
"score": 0.9974399209022522,
"start": 4879,
"tag": "PASSWORD",
"value": "delete"
},
{
"context": "client.ack()\n else\n if channel.password == password\n channel.subscribe(client)\n channel",
"end": 4989,
"score": 0.8535166382789612,
"start": 4981,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " ch.persisted.set(\"password\", if new_password then new_password else undefined)\n revoke = UTIL.st",
"end": 17114,
"score": 0.5086035132408142,
"start": 17111,
"tag": "PASSWORD",
"value": "new"
}
] | src/server/commands.coffee | 2called-chaos/synctube_node | 0 | COLORS = require("./colors.js")
UTIL = require("./util.js")
Channel = require("./channel.js").Class
Client = require("./client.js").Class
x = module.exports =
handleMessage: (server, client, message, msg) ->
try
return @Server["packet"].call(server, client, m[1]) if m = msg.match(/^!packet:(.+)$/i)
chunks = []
cmd = null
if msg && msg.charAt(0) == "/"
chunks = UTIL.shellSplit(msg.substr(1))
cmd = chunks.shift()
return if cmd && @Server[cmd]?.call(server, client, chunks...)
if ch = client.subscribed
return if cmd && @Channel[cmd]?.call(ch, client, chunks...)
ch.broadcastChat(client, msg, null, ch.clientColor(client))
return client.ack()
return client.ack()
catch err
server.error err
client.sendSystemMessage("Sorry, the server encountered an error")
return client.ack()
addCommand: (parent, cmds..., proc) ->
for cmd in cmds
do (cmd) =>
console.warn("[ST-WARN] ", new Date, "Overwriting handler for existing command #{parent}.#{cmd}") if x[parent][cmd]
x[parent][cmd] = proc
Server: {}
Channel: {}
x.addCommand "Server", "clip", (client) ->
client.sendCode("ui_clipboard_poll", action: "permission")
client.ack()
x.addCommand "Server", "clear", (client) ->
client.sendCode("ui_clear", component: "chat")
client.ack()
x.addCommand "Server", "tc", "togglechat", (client) ->
client.sendCode("ui_chat", action: "toggle")
client.ack()
x.addCommand "Server", "tpl", "togglepl", "toggleplaylist", (client) ->
client.sendCode("ui_playlist", action: "toggle")
client.ack()
x.addCommand "Server", "packet", (client, jdata) ->
try
json = JSON.parse(jdata)
catch error
@error "Invalid JSON", jdata, error
return
client.lastPacket = new Date
ch = client.subscribed
if ch && (!client.state || (JSON.stringify(client.state) != jdata))
json.time = new Date
json.timestamp = UTIL.videoTimestamp(json.seek, json.playtime) if json.seek? && json.playtime?
client.state = json
ch.broadcastCode(client, "update_single_subscriber", channel: ch.name, data: ch.getSubscriberData(client, client, client.index))
if client == ch.control[ch.host] && ch.desired.url == json.url
seek_was = ch.desired.seek
if json.state == "ended" && ch.desired.state != json.state
ch.desired.state = json.state
ch.playlistManager?.handleEnded()
ch.desired.seek = json.seek
ch.desired.seek_update = new Date()
ch.broadcastCode(false, "desired", Object.assign({}, ch.desired, { force: Math.abs(ch.desired.seek - seek_was) > (@opts.packetInterval + 0.75) }))
else
client.sendCode("desired", ch.desired) if ch
return true
x.addCommand "Server", "rpc", (client, args...) ->
key = UTIL.extractArg(args, ["-k", "--key"], 1)?[0]
channel = UTIL.extractArg(args, ["-c", "--channel"], 1)?[0]
# authentication
if channel
if cobj = @channels[channel]
if key? && key == cobj.getRPCKey()
cobj.debug "granted control to RPC client ##{client.index}(#{client.ip})"
cobj.control.push(client)
client.control = cobj
else
client.sendRPCResponse error: "Authentication failed"
return
else
client.sendRPCResponse error: "No such channel"
return
else if !channel
client.sendRPCResponse error: "Server RPC not allowed"
return
# available actions
action = args.shift()
try
switch action
when "play", "yt", "youtube"
module.exports.Channel.youtube.call(cobj, client, args...)
when "browse", "url"
module.exports.Channel.browse.call(cobj, client, args...)
when "vid", "video", "mp4", "webp"
module.exports.Channel.video.call(cobj, client, args...)
when "img", "image", "pic", "picture", "gif", "png", "jpg"
module.exports.Channel.image.call(cobj, client, args...)
else
client.sendRPCResponse error: "Unknown RPC action"
catch err
@error "[RPC]", err
client.sendRPCResponse error: "Unknown RPC error"
return client.ack()
x.addCommand "Server", "join", (client, chname) ->
if channel = @channels[chname]
channel.subscribe(client)
else if chname
client.sendSystemMessage("I don't know about this channel, sorry!")
client.sendSystemMessage("<small>You can create it with <strong>/control #{UTIL.htmlEntities(chname)} [password]</strong></small>", COLORS.info)
else
client.sendSystemMessage("Usage: /join <channel>")
return client.ack()
x.addCommand "Server", "control", (client, name, password) ->
chname = UTIL.htmlEntities(name || client.subscribed?.name || "")
unless chname
client.sendSystemMessage("Channel name required", COLORS.red)
return client.ack()
if channel = @channels[chname]
if channel.control.indexOf(client) > -1 && password == "delete"
channel.destroy(client)
return client.ack()
else
if channel.password == password
channel.subscribe(client)
channel.grantControl(client)
else
client.sendSystemMessage("Password incorrect", COLORS.red)
else
@channels[chname] = new Channel(this, chname, password)
client.sendSystemMessage("Channel created!", COLORS.green)
@channels[chname].subscribe(client)
@channels[chname].grantControl(client)
return client.ack()
x.addCommand "Server", "dc", "disconnect", (client) ->
client.sendSystemMessage("disconnecting...")
client.sendCode("disconnected")
client.connection.close()
x.addCommand "Server", "rename", (client, name_parts...) ->
if new_name = name_parts.join(" ")
client.old_name = client.name
client.setUsername(new_name)
else
client.sendSystemMessage "Usage: /rename <new_name>"
return client.ack()
x.addCommand "Server", "system", (client, subaction, args...) ->
unless client.isSystemAdmin
if subaction == "auth"
if UTIL.argsToStr(args) == @opts.systemPassword
client.isSystemAdmin = true
client.sendSystemMessage("Authenticated successfully!", COLORS.green)
else
client.sendSystemMessage "invalid password"
else
client.sendSystemMessage "system commands require you to `/system auth <syspw>` first!"
return client.ack()
switch subaction
when "restart"
@eachClient "sendSystemMessage", "Server restart: #{reason}" if reason = UTIL.argsToStr(args)
client.sendSystemMessage "See ya!"
return process.exit(1)
when "gracefulRestart"
if args[0] == "cancel"
if @pendingRestart?
@eachClient "sendSystemMessage", "Restart canceled"
@pendingRestart = null
@pendingRestartReason = null
clearTimeout(@pendingRestartTimeout)
else
client.sendSystemMessage("No pending restart")
else
success = true
try
dur = UTIL.parseEasyDuration(args.shift())
time = new Date((new Date).getTime() + UTIL.timestamp2Seconds(dur.toString()) * 1000)
catch e
success = false
client.sendSystemMessage("Invalid duration format (timestamp or EasyDuration)")
if success
clearTimeout(@pendingRestartTimeout)
@pendingRestart = time
@pendingRestartReason = UTIL.argsToStr(args)
@handlePendingRestart(true)
when "message"
@eachClient "sendSystemMessage", "#{UTIL.argsToStr(args)}"
when "chmessage"
channel = args.shift()
if ch = @channels[channel]
ch.broadcast({name: "system"}, UTIL.argsToStr(args), COLORS.red, COLORS.red)
else
client.sendSystemMessage "The channel could not be found!"
when "chkill"
channel = args.shift()
if ch = @channels[channel]
ch.destroy(client, UTIL.argsToStr(args))
client.sendSystemMessage "Channel destroyed!"
else
client.sendSystemMessage "The channel could not be found!"
when "status"
client.sendSystemMessage "======================"
nulled = 0
nulled += 1 for c in @clients when c is null
client.sendSystemMessage "Running with pid #{process.pid} for #{UTIL.secondsToTimestamp(process.uptime())} (on #{process.platform})"
client.sendSystemMessage "#{@clients.length - nulled} active sessions (#{@clients.length} total, #{nulled}/#{@opts.sessionReindex} nulled)"
client.sendSystemMessage "#{UTIL.microToHuman(process.cpuUsage().user)}/#{UTIL.microToHuman(process.cpuUsage().system)} CPU (usr/sys)"
client.sendSystemMessage "#{UTIL.bytesToHuman process.memoryUsage().rss} memory (RSS)"
client.sendSystemMessage "======================"
when "clients"
client.sendSystemMessage "======================"
for c in @clients when c?
client.sendSystemMessage """
<span class="soft_elli" style="min-width: 45px">[##{c.index}]</span>
<span class="elli" style="width: 100px; margin-bottom: -4px">#{c.name || "<em>unnamed</em>"}</span>
<span>#{c.ip}</span>
"""
client.sendSystemMessage "======================"
when "banip"
ip = args.shift()
unless ip?
client.sendSystemMessage("Usage: /system banip <ip> [duration] [message]")
return client.ack()
dur = args.shift()
reason = args.join(" ")
dur = -1 if dur == "permanent"
dur = UTIL.parseEasyDuration(dur)
seconds = try UTIL.timestamp2Seconds("#{dur}") catch e then UTIL.timestamp2Seconds("1:00:00")
stamp = if dur == -1 then "eternity" else UTIL.secondsToTimestamp(seconds, false)
@banIp(ip, dur, reason)
amsg = "Banned IP #{ip} (#{reason || "no reason"}) for #{stamp}"
@info amsg
client.sendSystemMessage(amsg)
when "unbanip"
ip = args[0]
if b = @banned.get(ip)
client.sendSystemMessage("Removed ban for IP #{ip} with expiry #{if b then b else "never"}")
@banned.purge(ip)
else
client.sendSystemMessage("No ban found for IP #{ip}")
when "invoke"
target = client
if x = UTIL.extractArg(args, ["-t", "--target"], 1)
Client = require("./client.js").Class
who = if typeof x[0] == "string" then x[0] else x[0].pattern
target = Client.find(client, who, @clients)
return true unless target
which = args.shift()
iargs = UTIL.argsToStr(args) || "{}"
client.sendCode(which, JSON.parse(iargs))
when "kick"
who = args.shift()
target = Client = require("./client.js").Class.find(client, who, @clients)
return true unless target
amsg = "Kicked ##{target.index} #{target.name} (#{target.ip}) from server"
@info amsg
client.sendSystemMessage(amsg)
msg = "You got kicked from the server#{if m = UTIL.argsToStr(args) then " (#{m})" else ""}"
target.sendCode("session_kicked", reason: msg)
target.sendSystemMessage(msg)
target.connection.close()
when "dump"
what = args[0]
detail = args[1]
if what == "client"
console.log if detail then @clients[parseInt(detail)] else client
else if what == "channel"
console.log if detail then @channels[detail] else if client.subscribed then client.subscribed else @channels
else if what == "commands"
console.log module.exports
return client.ack()
x.addCommand "Channel", "retry", (client) ->
return unless ch = client.subscribed
ch.revokeControl(client)
ch.unsubscribe(client)
ch.subscribe(client)
return client.ack()
x.addCommand "Channel", "p", "pause", (client) ->
return client.permissionDenied("pause") unless @control.indexOf(client) > -1
@desired.state = "pause"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "r", "resume", (client) ->
return client.permissionDenied("resume") unless @control.indexOf(client) > -1
@desired.state = "play"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "t", "toggle", (client) ->
return client.permissionDenied("toggle") unless @control.indexOf(client) > -1
@desired.state = if @desired.state == "play" then "pause" else "play"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "s", "seek", (client, to) ->
return client.permissionDenied("seek") unless @control.indexOf(client) > -1
if to?.charAt(0) == "-"
to = @desired.seek - UTIL.timestamp2Seconds(to.slice(1))
else if to?.charAt(0) == "+"
to = @desired.seek + UTIL.timestamp2Seconds(to.slice(1))
else if to
to = UTIL.timestamp2Seconds(to)
else
client.sendSystemMessage("Number required (absolute or +/-)")
return client.ack()
@desired.seek = parseFloat(to)
@desired.state = "play" if @desired.state == "ended"
@broadcastCode(false, "desired", Object.assign({}, @desired, { force: true }))
return client.ack()
x.addCommand "Channel", "sync", "resync", (client, args...) ->
target = [client]
instant = UTIL.extractArg(args, ["-i", "--instant"])
if x = UTIL.extractArg(args, ["-t", "--target"], 1)
return client.permissionDenied("resync-target") unless @control.indexOf(client) > -1
Client = require("./client.js").Class
found = Client.find(client, x[0], @subscribers)
target = if found == client then false else [found]
if UTIL.extractArg(args, ["-a", "--all"])
return client.permissionDenied("resync-all") unless @control.indexOf(client) > -1
target = @subscribers
if target && target.length
for t in target
if instant
t?.sendCode("desired", Object.assign({}, @desired, {force: true}))
else
t?.sendCode("video_action", action: "sync")
else
client.sendSystemMessage("Found no targets")
return client.ack()
x.addCommand "Channel", "ready", (client) ->
return client.ack() unless @ready
@ready.push(client) unless @ready.indexOf(client) > -1
if @ready.length == @subscribers.length
@ready = false
clearTimeout(@ready_timeout)
@desired.state = "play"
@broadcastCode(false, "video_action", action: "resume", reason: "allReady", cancelPauseEnsured: true)
return client.ack()
x.addCommand "Channel", "play", "yt", "youtube", (client, args...) ->
return client.permissionDenied("play") unless @control.indexOf(client) > -1
return client.ack() if @playlistManager.ensurePlaylistQuota(client)
playNext = UTIL.extractArg(args, ["-n", "--next"])
intermission = UTIL.extractArg(args, ["-i", "--intermission"])
url = args.join(" ")
if m = url.match(/([A-Za-z-0-9_\-]{11})/)
@play("Youtube", m[1], playNext, intermission)
client.sendRPCResponse(success: "Video successfully added to playlist")
else
client.sendRPCResponse(error: "I don't recognize this URL/YTID format, sorry")
client.sendSystemMessage("I don't recognize this URL/YTID format, sorry")
return client.ack()
x.addCommand "Channel", "loop", (client, what) ->
if what || @control.indexOf(client) > -1
return client.permissionDenied("loop") unless @control.indexOf(client) > -1
what = UTIL.strbool(what, !@desired.loop)
if @desired.loop == what
client.sendSystemMessage("Loop is already #{if @desired.loop then "enabled" else "disabled"}!")
else
@desired.loop = what
@broadcastCode(false, "desired", @desired)
@broadcast(client, "<strong>#{if @desired.loop then "enabled" else "disabled"} loop!</strong>", COLORS.warning, @clientColor(client))
else
client.sendSystemMessage("Loop is currently #{if @desired.loop then "enabled" else "disabled"}", if @desired.loop then COLORS.green else COLORS.red)
return client.ack()
x.addCommand "Channel", "url", "browse", (client, args...) ->
return client.permissionDenied("browse-#{ctype}") unless @control.indexOf(client) > -1
return client.ack() if @playlistManager.ensurePlaylistQuota(client)
playNext = UTIL.extractArg(args, ["-n", "--next"])
intermission = UTIL.extractArg(args, ["-i", "--intermission"])
ctype = "HtmlFrame"
ctype = "HtmlImage" if UTIL.extractArg(args, ["--x-HtmlImage"])
ctype = "HtmlVideo" if UTIL.extractArg(args, ["--x-HtmlVideo"])
url = args.join(" ")
url = "https://#{url}" unless UTIL.startsWith(url, "http://", "https://")
@play(ctype, url, playNext, intermission)
return client.ack()
x.addCommand "Channel", "img", "image", "pic", "picture", "gif", "png", "jpg", (client, args...) ->
module.exports.Channel.browse.call(this, client, args..., "--x-HtmlImage")
x.addCommand "Channel", "vid", "video", "mp4", "webp", (client, args...) ->
module.exports.Channel.browse.call(this, client, args..., "--x-HtmlVideo")
x.addCommand "Channel", "leave", "quit", (client) ->
if ch = client.subscribed
ch.unsubscribe(client)
client.sendCode("desired", ctype: "StuiCreateForm")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "password", (client, new_password, revoke) ->
if ch = client.subscribed
if ch.control.indexOf(client) > -1
if typeof new_password == "string"
ch.persisted.set("password", if new_password then new_password else undefined)
revoke = UTIL.strbool(revoke, false)
client.sendSystemMessage("Password changed#{if revoke then ", revoked all but you" else ""}!")
if revoke
for cu in ch.control
continue if cu == client
ch.revokeControl(cu, true, "channel password changed")
else
client.sendSystemMessage("New password required! (you can use \"\")")
else
client.sendSystemMessage("You are not in control!")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "kick", (client, who, args...) ->
if ch = client.subscribed
if ch.control.indexOf(client) > -1
target = Client = require("./client.js").Class.find(client, who, ch.subscribers)
return true unless target
if target == client
client.sendSystemMessage("You want to kick yourself?")
return client.ack()
amsg = "Kicked ##{target.index} #{target.name} (#{target.ip}) from channel #{ch.name}"
@info amsg
client.sendSystemMessage(amsg)
msg = "You got kicked from the channel#{if m = UTIL.argsToStr(args) then " (#{m})" else ""}"
ch.unsubscribe(target)
target.sendCode("kicked", reason: msg)
target.sendSystemMessage(msg)
else
client.sendSystemMessage("You are not in control!")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "host", (client, who) ->
return client.permissionDenied("host") unless @control.indexOf(client) > -1
return false unless who = @findClient(client, who)
if who == @control[@host]
client.sendSystemMessage("#{who?.name || "Target"} is already host")
else if @control.indexOf(who) > -1
@debug "Switching host to #", who.index
wasHostI = @host
wasHost = @control[wasHostI]
newHostI = @control.indexOf(who)
newHost = @control[newHostI]
@control[wasHostI] = newHost
@control[newHostI] = wasHost
newHost.sendCode("taken_host", channel: @name)
wasHost.sendCode("lost_host", channel: @name)
@updateSubscriberList(client)
else
client.sendSystemMessage("#{who?.name || "Target"} is not in control and thereby can't be host")
return client.ack()
x.addCommand "Channel", "grant", (client, who) ->
return client.permissionDenied("grantControl") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if @control.indexOf(who) > -1
client.sendSystemMessage("#{who?.name || "Target"} is already in control")
else
@grantControl(who)
client.sendSystemMessage("#{who?.name || "Target"} is now in control!", COLORS.green)
return client.ack()
x.addCommand "Channel", "revoke", (client, who) ->
return client.permissionDenied("revokeControl") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if @control.indexOf(who) > -1
@revokeControl(who)
client.sendSystemMessage("#{who?.name || "Target"} is no longer in control!", COLORS.green)
else
client.sendSystemMessage("#{who?.name || "Target"} was not in control")
return client.ack()
x.addCommand "Channel", "rpckey", (client) ->
return client.permissionDenied("rpckey") unless @control.indexOf(client) > -1
client.sendSystemMessage("RPC-Key for this channel: #{@getRPCKey()}")
client.sendSystemMessage("The key will change with the channel password!", COLORS.warning)
return client.ack()
x.addCommand "Channel", "bookmarklet", (client, args...) ->
return client.permissionDenied("bookmarklet") unless @control.indexOf(client) > -1
showHelp = UTIL.extractArg(args, ["-h", "--help"])
withNotification = UTIL.extractArg(args, ["-n", "--notifications"])
desiredAction = UTIL.extractArg(args, ["-a", "--action"], 1)?[0] || "yt"
label = UTIL.extractArg(args, ["-l", "--label"], 1)?[0] || "+ SyncTube (#{desiredAction.toUpperCase()})"
if showHelp
client.sendSystemMessage("Usage: /bookmarklet [-h --help] | [-a --action=youtube] [-n --notifications] [-l --label LABEL]", COLORS.info)
client.sendSystemMessage(" Action might be one of: youtube video image url", COLORS.white)
client.sendSystemMessage(" Notifications will show you the result if enabled for youtube.com", COLORS.white)
client.sendSystemMessage(" Label is the name of the button, you can change that in your browser too", COLORS.white)
client.sendSystemMessage("The embedded key will change with the channel password!", COLORS.warning)
return client.ack()
if withNotification
script = """(function(b){n=Notification;x=function(a){h="%wsurl%";s="https://statics.bmonkeys.net/img/rpcico/";w=window;w.stwsb=w.stwsb||[];if(w.stwsc){if(w.stwsc.readyState!=1){w.stwsb.push(a)}else{w.stwsc.send(a)}}else{w.stwsb.push("rpc_client");w.stwsb.push(a);w.stwsc=new WebSocket(h);w.stwsc.onmessage=function(m){j=JSON.parse(m.data);if(j.type=="rpc_response"){new n("SyncTube",{body:j.data.message,icon:s+j.data.type+".png"})}};w.stwsc.onopen=function(){while(w.stwsb.length){w.stwsc.send(w.stwsb.shift())}};w.stwsc.onerror=function(){alert("stwscError: failed to connect to "+h);console.error(arguments[0])};w.stwsc.onclose=function(){w.stwsc=null}}};if(n.permission==="granted"||n.permission==="denied"){x(b)}else{n.requestPermission().then(function(result){x(b)})}})("/rpc -k %key% -c %channel% %action% "+window.location)"""
else
script = """(function(a){h="%wsurl%";w=window;w.stwsb=w.stwsb||[];if(w.stwsc){if(w.stwsc.readyState!=1){w.stwsb.push(a)}else{w.stwsc.send(a)}}else{w.stwsb.push("rpc_client");w.stwsb.push(a);w.stwsc=new WebSocket(h);w.stwsc.onopen=function(){while(w.stwsb.length){w.stwsc.send(w.stwsb.shift())}};w.stwsc.onerror=function(){alert("stwscError: failed to connect to "+h);console.error(arguments[0])};w.stwsc.onclose=function(){w.stwsc=null}}})("/rpc -k %key% -c %channel% %action% "+window.location)"""
wsurl = client.request.origin.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://")
wsurl += "/#{client.request.resourceURL.pathname}"
script = script.replace "%wsurl%", wsurl
script = script.replace "%channel%", @name
script = script.replace "%key%", @getRPCKey()
script = script.replace "%action%", desiredAction
client.sendSystemMessage("""
The embedded key will change with the channel password!<br>
<span style="color: #{COLORS.info}">Drag the following button to your bookmark bar:</span>
<a href="javascript:#{encodeURIComponent script}" class="btn btn-primary btn-xs" style="font-size: 10px">#{label}</a>
""", COLORS.warning)
return client.ack()
x.addCommand "Channel", "copt", (client, opt, value) ->
return client.permissionDenied("copt") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if opt
if @options.hasOwnProperty(opt)
ok = opt
ov = @options[opt]
ot = typeof ov
if value?
try
if ot == "number"
nv = if !isNaN(x = Number(value)) then x else throw "value must be a number"
else if ot == "boolean"
nv = if (x = UTIL.strbool(value, null))? then x else throw "value must be a boolean(like)"
else if ot == "string"
nv = value
else
throw "unknown option value type (#{ot})"
throw "value hasn't changed" if nv == ov
@options[opt] = nv
@sendSettings()
c.sendSystemMessage("""
<span style="color: #{COLORS.warning}">CHANGED</span> channel option
<span style="color: #{COLORS.info}">#{ok}</span>
from <span style="color: #{COLORS.magenta}">#{ov}</span>
to <span style="color: #{COLORS.magenta}">#{nv}</span>
""", COLORS.white) for c in @control
catch err
client.sendSystemMessage("Failed to change channel option: #{err}")
else
client.sendSystemMessage("""
<span style="color: #{COLORS.info}">#{ok}</span>
is currently set to <span style="color: #{COLORS.magenta}">#{ov}</span>
<em style="color: #{COLORS.muted}">(#{ot})</em>
""", COLORS.white)
else
client.sendSystemMessage("Unknown option!")
else
cols = ["The following channel options are available:"]
for ok, ov of @options
cols.push """
<span style="color: #{COLORS.info}">#{ok}</span>
<span style="color: #{COLORS.magenta}">#{ov}</span>
<em style="color: #{COLORS.muted}">#{typeof ov}</em>
"""
client.sendSystemMessage(cols.join("<br>"), COLORS.white)
return client.ack()
| 192392 | COLORS = require("./colors.js")
UTIL = require("./util.js")
Channel = require("./channel.js").Class
Client = require("./client.js").Class
x = module.exports =
handleMessage: (server, client, message, msg) ->
try
return @Server["packet"].call(server, client, m[1]) if m = msg.match(/^!packet:(.+)$/i)
chunks = []
cmd = null
if msg && msg.charAt(0) == "/"
chunks = UTIL.shellSplit(msg.substr(1))
cmd = chunks.shift()
return if cmd && @Server[cmd]?.call(server, client, chunks...)
if ch = client.subscribed
return if cmd && @Channel[cmd]?.call(ch, client, chunks...)
ch.broadcastChat(client, msg, null, ch.clientColor(client))
return client.ack()
return client.ack()
catch err
server.error err
client.sendSystemMessage("Sorry, the server encountered an error")
return client.ack()
addCommand: (parent, cmds..., proc) ->
for cmd in cmds
do (cmd) =>
console.warn("[ST-WARN] ", new Date, "Overwriting handler for existing command #{parent}.#{cmd}") if x[parent][cmd]
x[parent][cmd] = proc
Server: {}
Channel: {}
x.addCommand "Server", "clip", (client) ->
client.sendCode("ui_clipboard_poll", action: "permission")
client.ack()
x.addCommand "Server", "clear", (client) ->
client.sendCode("ui_clear", component: "chat")
client.ack()
x.addCommand "Server", "tc", "togglechat", (client) ->
client.sendCode("ui_chat", action: "toggle")
client.ack()
x.addCommand "Server", "tpl", "togglepl", "toggleplaylist", (client) ->
client.sendCode("ui_playlist", action: "toggle")
client.ack()
x.addCommand "Server", "packet", (client, jdata) ->
try
json = JSON.parse(jdata)
catch error
@error "Invalid JSON", jdata, error
return
client.lastPacket = new Date
ch = client.subscribed
if ch && (!client.state || (JSON.stringify(client.state) != jdata))
json.time = new Date
json.timestamp = UTIL.videoTimestamp(json.seek, json.playtime) if json.seek? && json.playtime?
client.state = json
ch.broadcastCode(client, "update_single_subscriber", channel: ch.name, data: ch.getSubscriberData(client, client, client.index))
if client == ch.control[ch.host] && ch.desired.url == json.url
seek_was = ch.desired.seek
if json.state == "ended" && ch.desired.state != json.state
ch.desired.state = json.state
ch.playlistManager?.handleEnded()
ch.desired.seek = json.seek
ch.desired.seek_update = new Date()
ch.broadcastCode(false, "desired", Object.assign({}, ch.desired, { force: Math.abs(ch.desired.seek - seek_was) > (@opts.packetInterval + 0.75) }))
else
client.sendCode("desired", ch.desired) if ch
return true
x.addCommand "Server", "rpc", (client, args...) ->
key = UTIL.extractArg(args, ["-k", "--key"], 1)?[0]
channel = UTIL.extractArg(args, ["-c", "--channel"], 1)?[0]
# authentication
if channel
if cobj = @channels[channel]
if key? && key == cobj.getRPCKey()
cobj.debug "granted control to RPC client ##{client.index}(#{client.ip})"
cobj.control.push(client)
client.control = cobj
else
client.sendRPCResponse error: "Authentication failed"
return
else
client.sendRPCResponse error: "No such channel"
return
else if !channel
client.sendRPCResponse error: "Server RPC not allowed"
return
# available actions
action = args.shift()
try
switch action
when "play", "yt", "youtube"
module.exports.Channel.youtube.call(cobj, client, args...)
when "browse", "url"
module.exports.Channel.browse.call(cobj, client, args...)
when "vid", "video", "mp4", "webp"
module.exports.Channel.video.call(cobj, client, args...)
when "img", "image", "pic", "picture", "gif", "png", "jpg"
module.exports.Channel.image.call(cobj, client, args...)
else
client.sendRPCResponse error: "Unknown RPC action"
catch err
@error "[RPC]", err
client.sendRPCResponse error: "Unknown RPC error"
return client.ack()
x.addCommand "Server", "join", (client, chname) ->
if channel = @channels[chname]
channel.subscribe(client)
else if chname
client.sendSystemMessage("I don't know about this channel, sorry!")
client.sendSystemMessage("<small>You can create it with <strong>/control #{UTIL.htmlEntities(chname)} [password]</strong></small>", COLORS.info)
else
client.sendSystemMessage("Usage: /join <channel>")
return client.ack()
x.addCommand "Server", "control", (client, name, password) ->
chname = UTIL.htmlEntities(name || client.subscribed?.name || "")
unless chname
client.sendSystemMessage("Channel name required", COLORS.red)
return client.ack()
if channel = @channels[chname]
if channel.control.indexOf(client) > -1 && password == "<PASSWORD>"
channel.destroy(client)
return client.ack()
else
if channel.password == <PASSWORD>
channel.subscribe(client)
channel.grantControl(client)
else
client.sendSystemMessage("Password incorrect", COLORS.red)
else
@channels[chname] = new Channel(this, chname, password)
client.sendSystemMessage("Channel created!", COLORS.green)
@channels[chname].subscribe(client)
@channels[chname].grantControl(client)
return client.ack()
x.addCommand "Server", "dc", "disconnect", (client) ->
client.sendSystemMessage("disconnecting...")
client.sendCode("disconnected")
client.connection.close()
x.addCommand "Server", "rename", (client, name_parts...) ->
if new_name = name_parts.join(" ")
client.old_name = client.name
client.setUsername(new_name)
else
client.sendSystemMessage "Usage: /rename <new_name>"
return client.ack()
x.addCommand "Server", "system", (client, subaction, args...) ->
unless client.isSystemAdmin
if subaction == "auth"
if UTIL.argsToStr(args) == @opts.systemPassword
client.isSystemAdmin = true
client.sendSystemMessage("Authenticated successfully!", COLORS.green)
else
client.sendSystemMessage "invalid password"
else
client.sendSystemMessage "system commands require you to `/system auth <syspw>` first!"
return client.ack()
switch subaction
when "restart"
@eachClient "sendSystemMessage", "Server restart: #{reason}" if reason = UTIL.argsToStr(args)
client.sendSystemMessage "See ya!"
return process.exit(1)
when "gracefulRestart"
if args[0] == "cancel"
if @pendingRestart?
@eachClient "sendSystemMessage", "Restart canceled"
@pendingRestart = null
@pendingRestartReason = null
clearTimeout(@pendingRestartTimeout)
else
client.sendSystemMessage("No pending restart")
else
success = true
try
dur = UTIL.parseEasyDuration(args.shift())
time = new Date((new Date).getTime() + UTIL.timestamp2Seconds(dur.toString()) * 1000)
catch e
success = false
client.sendSystemMessage("Invalid duration format (timestamp or EasyDuration)")
if success
clearTimeout(@pendingRestartTimeout)
@pendingRestart = time
@pendingRestartReason = UTIL.argsToStr(args)
@handlePendingRestart(true)
when "message"
@eachClient "sendSystemMessage", "#{UTIL.argsToStr(args)}"
when "chmessage"
channel = args.shift()
if ch = @channels[channel]
ch.broadcast({name: "system"}, UTIL.argsToStr(args), COLORS.red, COLORS.red)
else
client.sendSystemMessage "The channel could not be found!"
when "chkill"
channel = args.shift()
if ch = @channels[channel]
ch.destroy(client, UTIL.argsToStr(args))
client.sendSystemMessage "Channel destroyed!"
else
client.sendSystemMessage "The channel could not be found!"
when "status"
client.sendSystemMessage "======================"
nulled = 0
nulled += 1 for c in @clients when c is null
client.sendSystemMessage "Running with pid #{process.pid} for #{UTIL.secondsToTimestamp(process.uptime())} (on #{process.platform})"
client.sendSystemMessage "#{@clients.length - nulled} active sessions (#{@clients.length} total, #{nulled}/#{@opts.sessionReindex} nulled)"
client.sendSystemMessage "#{UTIL.microToHuman(process.cpuUsage().user)}/#{UTIL.microToHuman(process.cpuUsage().system)} CPU (usr/sys)"
client.sendSystemMessage "#{UTIL.bytesToHuman process.memoryUsage().rss} memory (RSS)"
client.sendSystemMessage "======================"
when "clients"
client.sendSystemMessage "======================"
for c in @clients when c?
client.sendSystemMessage """
<span class="soft_elli" style="min-width: 45px">[##{c.index}]</span>
<span class="elli" style="width: 100px; margin-bottom: -4px">#{c.name || "<em>unnamed</em>"}</span>
<span>#{c.ip}</span>
"""
client.sendSystemMessage "======================"
when "banip"
ip = args.shift()
unless ip?
client.sendSystemMessage("Usage: /system banip <ip> [duration] [message]")
return client.ack()
dur = args.shift()
reason = args.join(" ")
dur = -1 if dur == "permanent"
dur = UTIL.parseEasyDuration(dur)
seconds = try UTIL.timestamp2Seconds("#{dur}") catch e then UTIL.timestamp2Seconds("1:00:00")
stamp = if dur == -1 then "eternity" else UTIL.secondsToTimestamp(seconds, false)
@banIp(ip, dur, reason)
amsg = "Banned IP #{ip} (#{reason || "no reason"}) for #{stamp}"
@info amsg
client.sendSystemMessage(amsg)
when "unbanip"
ip = args[0]
if b = @banned.get(ip)
client.sendSystemMessage("Removed ban for IP #{ip} with expiry #{if b then b else "never"}")
@banned.purge(ip)
else
client.sendSystemMessage("No ban found for IP #{ip}")
when "invoke"
target = client
if x = UTIL.extractArg(args, ["-t", "--target"], 1)
Client = require("./client.js").Class
who = if typeof x[0] == "string" then x[0] else x[0].pattern
target = Client.find(client, who, @clients)
return true unless target
which = args.shift()
iargs = UTIL.argsToStr(args) || "{}"
client.sendCode(which, JSON.parse(iargs))
when "kick"
who = args.shift()
target = Client = require("./client.js").Class.find(client, who, @clients)
return true unless target
amsg = "Kicked ##{target.index} #{target.name} (#{target.ip}) from server"
@info amsg
client.sendSystemMessage(amsg)
msg = "You got kicked from the server#{if m = UTIL.argsToStr(args) then " (#{m})" else ""}"
target.sendCode("session_kicked", reason: msg)
target.sendSystemMessage(msg)
target.connection.close()
when "dump"
what = args[0]
detail = args[1]
if what == "client"
console.log if detail then @clients[parseInt(detail)] else client
else if what == "channel"
console.log if detail then @channels[detail] else if client.subscribed then client.subscribed else @channels
else if what == "commands"
console.log module.exports
return client.ack()
x.addCommand "Channel", "retry", (client) ->
return unless ch = client.subscribed
ch.revokeControl(client)
ch.unsubscribe(client)
ch.subscribe(client)
return client.ack()
x.addCommand "Channel", "p", "pause", (client) ->
return client.permissionDenied("pause") unless @control.indexOf(client) > -1
@desired.state = "pause"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "r", "resume", (client) ->
return client.permissionDenied("resume") unless @control.indexOf(client) > -1
@desired.state = "play"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "t", "toggle", (client) ->
return client.permissionDenied("toggle") unless @control.indexOf(client) > -1
@desired.state = if @desired.state == "play" then "pause" else "play"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "s", "seek", (client, to) ->
return client.permissionDenied("seek") unless @control.indexOf(client) > -1
if to?.charAt(0) == "-"
to = @desired.seek - UTIL.timestamp2Seconds(to.slice(1))
else if to?.charAt(0) == "+"
to = @desired.seek + UTIL.timestamp2Seconds(to.slice(1))
else if to
to = UTIL.timestamp2Seconds(to)
else
client.sendSystemMessage("Number required (absolute or +/-)")
return client.ack()
@desired.seek = parseFloat(to)
@desired.state = "play" if @desired.state == "ended"
@broadcastCode(false, "desired", Object.assign({}, @desired, { force: true }))
return client.ack()
x.addCommand "Channel", "sync", "resync", (client, args...) ->
target = [client]
instant = UTIL.extractArg(args, ["-i", "--instant"])
if x = UTIL.extractArg(args, ["-t", "--target"], 1)
return client.permissionDenied("resync-target") unless @control.indexOf(client) > -1
Client = require("./client.js").Class
found = Client.find(client, x[0], @subscribers)
target = if found == client then false else [found]
if UTIL.extractArg(args, ["-a", "--all"])
return client.permissionDenied("resync-all") unless @control.indexOf(client) > -1
target = @subscribers
if target && target.length
for t in target
if instant
t?.sendCode("desired", Object.assign({}, @desired, {force: true}))
else
t?.sendCode("video_action", action: "sync")
else
client.sendSystemMessage("Found no targets")
return client.ack()
x.addCommand "Channel", "ready", (client) ->
return client.ack() unless @ready
@ready.push(client) unless @ready.indexOf(client) > -1
if @ready.length == @subscribers.length
@ready = false
clearTimeout(@ready_timeout)
@desired.state = "play"
@broadcastCode(false, "video_action", action: "resume", reason: "allReady", cancelPauseEnsured: true)
return client.ack()
x.addCommand "Channel", "play", "yt", "youtube", (client, args...) ->
return client.permissionDenied("play") unless @control.indexOf(client) > -1
return client.ack() if @playlistManager.ensurePlaylistQuota(client)
playNext = UTIL.extractArg(args, ["-n", "--next"])
intermission = UTIL.extractArg(args, ["-i", "--intermission"])
url = args.join(" ")
if m = url.match(/([A-Za-z-0-9_\-]{11})/)
@play("Youtube", m[1], playNext, intermission)
client.sendRPCResponse(success: "Video successfully added to playlist")
else
client.sendRPCResponse(error: "I don't recognize this URL/YTID format, sorry")
client.sendSystemMessage("I don't recognize this URL/YTID format, sorry")
return client.ack()
x.addCommand "Channel", "loop", (client, what) ->
if what || @control.indexOf(client) > -1
return client.permissionDenied("loop") unless @control.indexOf(client) > -1
what = UTIL.strbool(what, !@desired.loop)
if @desired.loop == what
client.sendSystemMessage("Loop is already #{if @desired.loop then "enabled" else "disabled"}!")
else
@desired.loop = what
@broadcastCode(false, "desired", @desired)
@broadcast(client, "<strong>#{if @desired.loop then "enabled" else "disabled"} loop!</strong>", COLORS.warning, @clientColor(client))
else
client.sendSystemMessage("Loop is currently #{if @desired.loop then "enabled" else "disabled"}", if @desired.loop then COLORS.green else COLORS.red)
return client.ack()
x.addCommand "Channel", "url", "browse", (client, args...) ->
return client.permissionDenied("browse-#{ctype}") unless @control.indexOf(client) > -1
return client.ack() if @playlistManager.ensurePlaylistQuota(client)
playNext = UTIL.extractArg(args, ["-n", "--next"])
intermission = UTIL.extractArg(args, ["-i", "--intermission"])
ctype = "HtmlFrame"
ctype = "HtmlImage" if UTIL.extractArg(args, ["--x-HtmlImage"])
ctype = "HtmlVideo" if UTIL.extractArg(args, ["--x-HtmlVideo"])
url = args.join(" ")
url = "https://#{url}" unless UTIL.startsWith(url, "http://", "https://")
@play(ctype, url, playNext, intermission)
return client.ack()
x.addCommand "Channel", "img", "image", "pic", "picture", "gif", "png", "jpg", (client, args...) ->
module.exports.Channel.browse.call(this, client, args..., "--x-HtmlImage")
x.addCommand "Channel", "vid", "video", "mp4", "webp", (client, args...) ->
module.exports.Channel.browse.call(this, client, args..., "--x-HtmlVideo")
x.addCommand "Channel", "leave", "quit", (client) ->
if ch = client.subscribed
ch.unsubscribe(client)
client.sendCode("desired", ctype: "StuiCreateForm")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "password", (client, new_password, revoke) ->
if ch = client.subscribed
if ch.control.indexOf(client) > -1
if typeof new_password == "string"
ch.persisted.set("password", if new_password then <PASSWORD>_password else undefined)
revoke = UTIL.strbool(revoke, false)
client.sendSystemMessage("Password changed#{if revoke then ", revoked all but you" else ""}!")
if revoke
for cu in ch.control
continue if cu == client
ch.revokeControl(cu, true, "channel password changed")
else
client.sendSystemMessage("New password required! (you can use \"\")")
else
client.sendSystemMessage("You are not in control!")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "kick", (client, who, args...) ->
if ch = client.subscribed
if ch.control.indexOf(client) > -1
target = Client = require("./client.js").Class.find(client, who, ch.subscribers)
return true unless target
if target == client
client.sendSystemMessage("You want to kick yourself?")
return client.ack()
amsg = "Kicked ##{target.index} #{target.name} (#{target.ip}) from channel #{ch.name}"
@info amsg
client.sendSystemMessage(amsg)
msg = "You got kicked from the channel#{if m = UTIL.argsToStr(args) then " (#{m})" else ""}"
ch.unsubscribe(target)
target.sendCode("kicked", reason: msg)
target.sendSystemMessage(msg)
else
client.sendSystemMessage("You are not in control!")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "host", (client, who) ->
return client.permissionDenied("host") unless @control.indexOf(client) > -1
return false unless who = @findClient(client, who)
if who == @control[@host]
client.sendSystemMessage("#{who?.name || "Target"} is already host")
else if @control.indexOf(who) > -1
@debug "Switching host to #", who.index
wasHostI = @host
wasHost = @control[wasHostI]
newHostI = @control.indexOf(who)
newHost = @control[newHostI]
@control[wasHostI] = newHost
@control[newHostI] = wasHost
newHost.sendCode("taken_host", channel: @name)
wasHost.sendCode("lost_host", channel: @name)
@updateSubscriberList(client)
else
client.sendSystemMessage("#{who?.name || "Target"} is not in control and thereby can't be host")
return client.ack()
x.addCommand "Channel", "grant", (client, who) ->
return client.permissionDenied("grantControl") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if @control.indexOf(who) > -1
client.sendSystemMessage("#{who?.name || "Target"} is already in control")
else
@grantControl(who)
client.sendSystemMessage("#{who?.name || "Target"} is now in control!", COLORS.green)
return client.ack()
x.addCommand "Channel", "revoke", (client, who) ->
return client.permissionDenied("revokeControl") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if @control.indexOf(who) > -1
@revokeControl(who)
client.sendSystemMessage("#{who?.name || "Target"} is no longer in control!", COLORS.green)
else
client.sendSystemMessage("#{who?.name || "Target"} was not in control")
return client.ack()
x.addCommand "Channel", "rpckey", (client) ->
return client.permissionDenied("rpckey") unless @control.indexOf(client) > -1
client.sendSystemMessage("RPC-Key for this channel: #{@getRPCKey()}")
client.sendSystemMessage("The key will change with the channel password!", COLORS.warning)
return client.ack()
x.addCommand "Channel", "bookmarklet", (client, args...) ->
return client.permissionDenied("bookmarklet") unless @control.indexOf(client) > -1
showHelp = UTIL.extractArg(args, ["-h", "--help"])
withNotification = UTIL.extractArg(args, ["-n", "--notifications"])
desiredAction = UTIL.extractArg(args, ["-a", "--action"], 1)?[0] || "yt"
label = UTIL.extractArg(args, ["-l", "--label"], 1)?[0] || "+ SyncTube (#{desiredAction.toUpperCase()})"
if showHelp
client.sendSystemMessage("Usage: /bookmarklet [-h --help] | [-a --action=youtube] [-n --notifications] [-l --label LABEL]", COLORS.info)
client.sendSystemMessage(" Action might be one of: youtube video image url", COLORS.white)
client.sendSystemMessage(" Notifications will show you the result if enabled for youtube.com", COLORS.white)
client.sendSystemMessage(" Label is the name of the button, you can change that in your browser too", COLORS.white)
client.sendSystemMessage("The embedded key will change with the channel password!", COLORS.warning)
return client.ack()
if withNotification
script = """(function(b){n=Notification;x=function(a){h="%wsurl%";s="https://statics.bmonkeys.net/img/rpcico/";w=window;w.stwsb=w.stwsb||[];if(w.stwsc){if(w.stwsc.readyState!=1){w.stwsb.push(a)}else{w.stwsc.send(a)}}else{w.stwsb.push("rpc_client");w.stwsb.push(a);w.stwsc=new WebSocket(h);w.stwsc.onmessage=function(m){j=JSON.parse(m.data);if(j.type=="rpc_response"){new n("SyncTube",{body:j.data.message,icon:s+j.data.type+".png"})}};w.stwsc.onopen=function(){while(w.stwsb.length){w.stwsc.send(w.stwsb.shift())}};w.stwsc.onerror=function(){alert("stwscError: failed to connect to "+h);console.error(arguments[0])};w.stwsc.onclose=function(){w.stwsc=null}}};if(n.permission==="granted"||n.permission==="denied"){x(b)}else{n.requestPermission().then(function(result){x(b)})}})("/rpc -k %key% -c %channel% %action% "+window.location)"""
else
script = """(function(a){h="%wsurl%";w=window;w.stwsb=w.stwsb||[];if(w.stwsc){if(w.stwsc.readyState!=1){w.stwsb.push(a)}else{w.stwsc.send(a)}}else{w.stwsb.push("rpc_client");w.stwsb.push(a);w.stwsc=new WebSocket(h);w.stwsc.onopen=function(){while(w.stwsb.length){w.stwsc.send(w.stwsb.shift())}};w.stwsc.onerror=function(){alert("stwscError: failed to connect to "+h);console.error(arguments[0])};w.stwsc.onclose=function(){w.stwsc=null}}})("/rpc -k %key% -c %channel% %action% "+window.location)"""
wsurl = client.request.origin.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://")
wsurl += "/#{client.request.resourceURL.pathname}"
script = script.replace "%wsurl%", wsurl
script = script.replace "%channel%", @name
script = script.replace "%key%", @getRPCKey()
script = script.replace "%action%", desiredAction
client.sendSystemMessage("""
The embedded key will change with the channel password!<br>
<span style="color: #{COLORS.info}">Drag the following button to your bookmark bar:</span>
<a href="javascript:#{encodeURIComponent script}" class="btn btn-primary btn-xs" style="font-size: 10px">#{label}</a>
""", COLORS.warning)
return client.ack()
x.addCommand "Channel", "copt", (client, opt, value) ->
return client.permissionDenied("copt") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if opt
if @options.hasOwnProperty(opt)
ok = opt
ov = @options[opt]
ot = typeof ov
if value?
try
if ot == "number"
nv = if !isNaN(x = Number(value)) then x else throw "value must be a number"
else if ot == "boolean"
nv = if (x = UTIL.strbool(value, null))? then x else throw "value must be a boolean(like)"
else if ot == "string"
nv = value
else
throw "unknown option value type (#{ot})"
throw "value hasn't changed" if nv == ov
@options[opt] = nv
@sendSettings()
c.sendSystemMessage("""
<span style="color: #{COLORS.warning}">CHANGED</span> channel option
<span style="color: #{COLORS.info}">#{ok}</span>
from <span style="color: #{COLORS.magenta}">#{ov}</span>
to <span style="color: #{COLORS.magenta}">#{nv}</span>
""", COLORS.white) for c in @control
catch err
client.sendSystemMessage("Failed to change channel option: #{err}")
else
client.sendSystemMessage("""
<span style="color: #{COLORS.info}">#{ok}</span>
is currently set to <span style="color: #{COLORS.magenta}">#{ov}</span>
<em style="color: #{COLORS.muted}">(#{ot})</em>
""", COLORS.white)
else
client.sendSystemMessage("Unknown option!")
else
cols = ["The following channel options are available:"]
for ok, ov of @options
cols.push """
<span style="color: #{COLORS.info}">#{ok}</span>
<span style="color: #{COLORS.magenta}">#{ov}</span>
<em style="color: #{COLORS.muted}">#{typeof ov}</em>
"""
client.sendSystemMessage(cols.join("<br>"), COLORS.white)
return client.ack()
| true | COLORS = require("./colors.js")
UTIL = require("./util.js")
Channel = require("./channel.js").Class
Client = require("./client.js").Class
x = module.exports =
handleMessage: (server, client, message, msg) ->
try
return @Server["packet"].call(server, client, m[1]) if m = msg.match(/^!packet:(.+)$/i)
chunks = []
cmd = null
if msg && msg.charAt(0) == "/"
chunks = UTIL.shellSplit(msg.substr(1))
cmd = chunks.shift()
return if cmd && @Server[cmd]?.call(server, client, chunks...)
if ch = client.subscribed
return if cmd && @Channel[cmd]?.call(ch, client, chunks...)
ch.broadcastChat(client, msg, null, ch.clientColor(client))
return client.ack()
return client.ack()
catch err
server.error err
client.sendSystemMessage("Sorry, the server encountered an error")
return client.ack()
addCommand: (parent, cmds..., proc) ->
for cmd in cmds
do (cmd) =>
console.warn("[ST-WARN] ", new Date, "Overwriting handler for existing command #{parent}.#{cmd}") if x[parent][cmd]
x[parent][cmd] = proc
Server: {}
Channel: {}
x.addCommand "Server", "clip", (client) ->
client.sendCode("ui_clipboard_poll", action: "permission")
client.ack()
x.addCommand "Server", "clear", (client) ->
client.sendCode("ui_clear", component: "chat")
client.ack()
x.addCommand "Server", "tc", "togglechat", (client) ->
client.sendCode("ui_chat", action: "toggle")
client.ack()
x.addCommand "Server", "tpl", "togglepl", "toggleplaylist", (client) ->
client.sendCode("ui_playlist", action: "toggle")
client.ack()
x.addCommand "Server", "packet", (client, jdata) ->
try
json = JSON.parse(jdata)
catch error
@error "Invalid JSON", jdata, error
return
client.lastPacket = new Date
ch = client.subscribed
if ch && (!client.state || (JSON.stringify(client.state) != jdata))
json.time = new Date
json.timestamp = UTIL.videoTimestamp(json.seek, json.playtime) if json.seek? && json.playtime?
client.state = json
ch.broadcastCode(client, "update_single_subscriber", channel: ch.name, data: ch.getSubscriberData(client, client, client.index))
if client == ch.control[ch.host] && ch.desired.url == json.url
seek_was = ch.desired.seek
if json.state == "ended" && ch.desired.state != json.state
ch.desired.state = json.state
ch.playlistManager?.handleEnded()
ch.desired.seek = json.seek
ch.desired.seek_update = new Date()
ch.broadcastCode(false, "desired", Object.assign({}, ch.desired, { force: Math.abs(ch.desired.seek - seek_was) > (@opts.packetInterval + 0.75) }))
else
client.sendCode("desired", ch.desired) if ch
return true
x.addCommand "Server", "rpc", (client, args...) ->
key = UTIL.extractArg(args, ["-k", "--key"], 1)?[0]
channel = UTIL.extractArg(args, ["-c", "--channel"], 1)?[0]
# authentication
if channel
if cobj = @channels[channel]
if key? && key == cobj.getRPCKey()
cobj.debug "granted control to RPC client ##{client.index}(#{client.ip})"
cobj.control.push(client)
client.control = cobj
else
client.sendRPCResponse error: "Authentication failed"
return
else
client.sendRPCResponse error: "No such channel"
return
else if !channel
client.sendRPCResponse error: "Server RPC not allowed"
return
# available actions
action = args.shift()
try
switch action
when "play", "yt", "youtube"
module.exports.Channel.youtube.call(cobj, client, args...)
when "browse", "url"
module.exports.Channel.browse.call(cobj, client, args...)
when "vid", "video", "mp4", "webp"
module.exports.Channel.video.call(cobj, client, args...)
when "img", "image", "pic", "picture", "gif", "png", "jpg"
module.exports.Channel.image.call(cobj, client, args...)
else
client.sendRPCResponse error: "Unknown RPC action"
catch err
@error "[RPC]", err
client.sendRPCResponse error: "Unknown RPC error"
return client.ack()
x.addCommand "Server", "join", (client, chname) ->
if channel = @channels[chname]
channel.subscribe(client)
else if chname
client.sendSystemMessage("I don't know about this channel, sorry!")
client.sendSystemMessage("<small>You can create it with <strong>/control #{UTIL.htmlEntities(chname)} [password]</strong></small>", COLORS.info)
else
client.sendSystemMessage("Usage: /join <channel>")
return client.ack()
x.addCommand "Server", "control", (client, name, password) ->
chname = UTIL.htmlEntities(name || client.subscribed?.name || "")
unless chname
client.sendSystemMessage("Channel name required", COLORS.red)
return client.ack()
if channel = @channels[chname]
if channel.control.indexOf(client) > -1 && password == "PI:PASSWORD:<PASSWORD>END_PI"
channel.destroy(client)
return client.ack()
else
if channel.password == PI:PASSWORD:<PASSWORD>END_PI
channel.subscribe(client)
channel.grantControl(client)
else
client.sendSystemMessage("Password incorrect", COLORS.red)
else
@channels[chname] = new Channel(this, chname, password)
client.sendSystemMessage("Channel created!", COLORS.green)
@channels[chname].subscribe(client)
@channels[chname].grantControl(client)
return client.ack()
x.addCommand "Server", "dc", "disconnect", (client) ->
client.sendSystemMessage("disconnecting...")
client.sendCode("disconnected")
client.connection.close()
x.addCommand "Server", "rename", (client, name_parts...) ->
if new_name = name_parts.join(" ")
client.old_name = client.name
client.setUsername(new_name)
else
client.sendSystemMessage "Usage: /rename <new_name>"
return client.ack()
x.addCommand "Server", "system", (client, subaction, args...) ->
unless client.isSystemAdmin
if subaction == "auth"
if UTIL.argsToStr(args) == @opts.systemPassword
client.isSystemAdmin = true
client.sendSystemMessage("Authenticated successfully!", COLORS.green)
else
client.sendSystemMessage "invalid password"
else
client.sendSystemMessage "system commands require you to `/system auth <syspw>` first!"
return client.ack()
switch subaction
when "restart"
@eachClient "sendSystemMessage", "Server restart: #{reason}" if reason = UTIL.argsToStr(args)
client.sendSystemMessage "See ya!"
return process.exit(1)
when "gracefulRestart"
if args[0] == "cancel"
if @pendingRestart?
@eachClient "sendSystemMessage", "Restart canceled"
@pendingRestart = null
@pendingRestartReason = null
clearTimeout(@pendingRestartTimeout)
else
client.sendSystemMessage("No pending restart")
else
success = true
try
dur = UTIL.parseEasyDuration(args.shift())
time = new Date((new Date).getTime() + UTIL.timestamp2Seconds(dur.toString()) * 1000)
catch e
success = false
client.sendSystemMessage("Invalid duration format (timestamp or EasyDuration)")
if success
clearTimeout(@pendingRestartTimeout)
@pendingRestart = time
@pendingRestartReason = UTIL.argsToStr(args)
@handlePendingRestart(true)
when "message"
@eachClient "sendSystemMessage", "#{UTIL.argsToStr(args)}"
when "chmessage"
channel = args.shift()
if ch = @channels[channel]
ch.broadcast({name: "system"}, UTIL.argsToStr(args), COLORS.red, COLORS.red)
else
client.sendSystemMessage "The channel could not be found!"
when "chkill"
channel = args.shift()
if ch = @channels[channel]
ch.destroy(client, UTIL.argsToStr(args))
client.sendSystemMessage "Channel destroyed!"
else
client.sendSystemMessage "The channel could not be found!"
when "status"
client.sendSystemMessage "======================"
nulled = 0
nulled += 1 for c in @clients when c is null
client.sendSystemMessage "Running with pid #{process.pid} for #{UTIL.secondsToTimestamp(process.uptime())} (on #{process.platform})"
client.sendSystemMessage "#{@clients.length - nulled} active sessions (#{@clients.length} total, #{nulled}/#{@opts.sessionReindex} nulled)"
client.sendSystemMessage "#{UTIL.microToHuman(process.cpuUsage().user)}/#{UTIL.microToHuman(process.cpuUsage().system)} CPU (usr/sys)"
client.sendSystemMessage "#{UTIL.bytesToHuman process.memoryUsage().rss} memory (RSS)"
client.sendSystemMessage "======================"
when "clients"
client.sendSystemMessage "======================"
for c in @clients when c?
client.sendSystemMessage """
<span class="soft_elli" style="min-width: 45px">[##{c.index}]</span>
<span class="elli" style="width: 100px; margin-bottom: -4px">#{c.name || "<em>unnamed</em>"}</span>
<span>#{c.ip}</span>
"""
client.sendSystemMessage "======================"
when "banip"
ip = args.shift()
unless ip?
client.sendSystemMessage("Usage: /system banip <ip> [duration] [message]")
return client.ack()
dur = args.shift()
reason = args.join(" ")
dur = -1 if dur == "permanent"
dur = UTIL.parseEasyDuration(dur)
seconds = try UTIL.timestamp2Seconds("#{dur}") catch e then UTIL.timestamp2Seconds("1:00:00")
stamp = if dur == -1 then "eternity" else UTIL.secondsToTimestamp(seconds, false)
@banIp(ip, dur, reason)
amsg = "Banned IP #{ip} (#{reason || "no reason"}) for #{stamp}"
@info amsg
client.sendSystemMessage(amsg)
when "unbanip"
ip = args[0]
if b = @banned.get(ip)
client.sendSystemMessage("Removed ban for IP #{ip} with expiry #{if b then b else "never"}")
@banned.purge(ip)
else
client.sendSystemMessage("No ban found for IP #{ip}")
when "invoke"
target = client
if x = UTIL.extractArg(args, ["-t", "--target"], 1)
Client = require("./client.js").Class
who = if typeof x[0] == "string" then x[0] else x[0].pattern
target = Client.find(client, who, @clients)
return true unless target
which = args.shift()
iargs = UTIL.argsToStr(args) || "{}"
client.sendCode(which, JSON.parse(iargs))
when "kick"
who = args.shift()
target = Client = require("./client.js").Class.find(client, who, @clients)
return true unless target
amsg = "Kicked ##{target.index} #{target.name} (#{target.ip}) from server"
@info amsg
client.sendSystemMessage(amsg)
msg = "You got kicked from the server#{if m = UTIL.argsToStr(args) then " (#{m})" else ""}"
target.sendCode("session_kicked", reason: msg)
target.sendSystemMessage(msg)
target.connection.close()
when "dump"
what = args[0]
detail = args[1]
if what == "client"
console.log if detail then @clients[parseInt(detail)] else client
else if what == "channel"
console.log if detail then @channels[detail] else if client.subscribed then client.subscribed else @channels
else if what == "commands"
console.log module.exports
return client.ack()
x.addCommand "Channel", "retry", (client) ->
return unless ch = client.subscribed
ch.revokeControl(client)
ch.unsubscribe(client)
ch.subscribe(client)
return client.ack()
x.addCommand "Channel", "p", "pause", (client) ->
return client.permissionDenied("pause") unless @control.indexOf(client) > -1
@desired.state = "pause"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "r", "resume", (client) ->
return client.permissionDenied("resume") unless @control.indexOf(client) > -1
@desired.state = "play"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "t", "toggle", (client) ->
return client.permissionDenied("toggle") unless @control.indexOf(client) > -1
@desired.state = if @desired.state == "play" then "pause" else "play"
@broadcastCode(false, "desired", @desired)
return client.ack()
x.addCommand "Channel", "s", "seek", (client, to) ->
return client.permissionDenied("seek") unless @control.indexOf(client) > -1
if to?.charAt(0) == "-"
to = @desired.seek - UTIL.timestamp2Seconds(to.slice(1))
else if to?.charAt(0) == "+"
to = @desired.seek + UTIL.timestamp2Seconds(to.slice(1))
else if to
to = UTIL.timestamp2Seconds(to)
else
client.sendSystemMessage("Number required (absolute or +/-)")
return client.ack()
@desired.seek = parseFloat(to)
@desired.state = "play" if @desired.state == "ended"
@broadcastCode(false, "desired", Object.assign({}, @desired, { force: true }))
return client.ack()
x.addCommand "Channel", "sync", "resync", (client, args...) ->
target = [client]
instant = UTIL.extractArg(args, ["-i", "--instant"])
if x = UTIL.extractArg(args, ["-t", "--target"], 1)
return client.permissionDenied("resync-target") unless @control.indexOf(client) > -1
Client = require("./client.js").Class
found = Client.find(client, x[0], @subscribers)
target = if found == client then false else [found]
if UTIL.extractArg(args, ["-a", "--all"])
return client.permissionDenied("resync-all") unless @control.indexOf(client) > -1
target = @subscribers
if target && target.length
for t in target
if instant
t?.sendCode("desired", Object.assign({}, @desired, {force: true}))
else
t?.sendCode("video_action", action: "sync")
else
client.sendSystemMessage("Found no targets")
return client.ack()
x.addCommand "Channel", "ready", (client) ->
return client.ack() unless @ready
@ready.push(client) unless @ready.indexOf(client) > -1
if @ready.length == @subscribers.length
@ready = false
clearTimeout(@ready_timeout)
@desired.state = "play"
@broadcastCode(false, "video_action", action: "resume", reason: "allReady", cancelPauseEnsured: true)
return client.ack()
x.addCommand "Channel", "play", "yt", "youtube", (client, args...) ->
return client.permissionDenied("play") unless @control.indexOf(client) > -1
return client.ack() if @playlistManager.ensurePlaylistQuota(client)
playNext = UTIL.extractArg(args, ["-n", "--next"])
intermission = UTIL.extractArg(args, ["-i", "--intermission"])
url = args.join(" ")
if m = url.match(/([A-Za-z-0-9_\-]{11})/)
@play("Youtube", m[1], playNext, intermission)
client.sendRPCResponse(success: "Video successfully added to playlist")
else
client.sendRPCResponse(error: "I don't recognize this URL/YTID format, sorry")
client.sendSystemMessage("I don't recognize this URL/YTID format, sorry")
return client.ack()
x.addCommand "Channel", "loop", (client, what) ->
if what || @control.indexOf(client) > -1
return client.permissionDenied("loop") unless @control.indexOf(client) > -1
what = UTIL.strbool(what, !@desired.loop)
if @desired.loop == what
client.sendSystemMessage("Loop is already #{if @desired.loop then "enabled" else "disabled"}!")
else
@desired.loop = what
@broadcastCode(false, "desired", @desired)
@broadcast(client, "<strong>#{if @desired.loop then "enabled" else "disabled"} loop!</strong>", COLORS.warning, @clientColor(client))
else
client.sendSystemMessage("Loop is currently #{if @desired.loop then "enabled" else "disabled"}", if @desired.loop then COLORS.green else COLORS.red)
return client.ack()
x.addCommand "Channel", "url", "browse", (client, args...) ->
return client.permissionDenied("browse-#{ctype}") unless @control.indexOf(client) > -1
return client.ack() if @playlistManager.ensurePlaylistQuota(client)
playNext = UTIL.extractArg(args, ["-n", "--next"])
intermission = UTIL.extractArg(args, ["-i", "--intermission"])
ctype = "HtmlFrame"
ctype = "HtmlImage" if UTIL.extractArg(args, ["--x-HtmlImage"])
ctype = "HtmlVideo" if UTIL.extractArg(args, ["--x-HtmlVideo"])
url = args.join(" ")
url = "https://#{url}" unless UTIL.startsWith(url, "http://", "https://")
@play(ctype, url, playNext, intermission)
return client.ack()
x.addCommand "Channel", "img", "image", "pic", "picture", "gif", "png", "jpg", (client, args...) ->
module.exports.Channel.browse.call(this, client, args..., "--x-HtmlImage")
x.addCommand "Channel", "vid", "video", "mp4", "webp", (client, args...) ->
module.exports.Channel.browse.call(this, client, args..., "--x-HtmlVideo")
x.addCommand "Channel", "leave", "quit", (client) ->
if ch = client.subscribed
ch.unsubscribe(client)
client.sendCode("desired", ctype: "StuiCreateForm")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "password", (client, new_password, revoke) ->
if ch = client.subscribed
if ch.control.indexOf(client) > -1
if typeof new_password == "string"
ch.persisted.set("password", if new_password then PI:PASSWORD:<PASSWORD>END_PI_password else undefined)
revoke = UTIL.strbool(revoke, false)
client.sendSystemMessage("Password changed#{if revoke then ", revoked all but you" else ""}!")
if revoke
for cu in ch.control
continue if cu == client
ch.revokeControl(cu, true, "channel password changed")
else
client.sendSystemMessage("New password required! (you can use \"\")")
else
client.sendSystemMessage("You are not in control!")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "kick", (client, who, args...) ->
if ch = client.subscribed
if ch.control.indexOf(client) > -1
target = Client = require("./client.js").Class.find(client, who, ch.subscribers)
return true unless target
if target == client
client.sendSystemMessage("You want to kick yourself?")
return client.ack()
amsg = "Kicked ##{target.index} #{target.name} (#{target.ip}) from channel #{ch.name}"
@info amsg
client.sendSystemMessage(amsg)
msg = "You got kicked from the channel#{if m = UTIL.argsToStr(args) then " (#{m})" else ""}"
ch.unsubscribe(target)
target.sendCode("kicked", reason: msg)
target.sendSystemMessage(msg)
else
client.sendSystemMessage("You are not in control!")
else
client.sendSystemMessage("You are not in any channel!")
return client.ack()
x.addCommand "Channel", "host", (client, who) ->
return client.permissionDenied("host") unless @control.indexOf(client) > -1
return false unless who = @findClient(client, who)
if who == @control[@host]
client.sendSystemMessage("#{who?.name || "Target"} is already host")
else if @control.indexOf(who) > -1
@debug "Switching host to #", who.index
wasHostI = @host
wasHost = @control[wasHostI]
newHostI = @control.indexOf(who)
newHost = @control[newHostI]
@control[wasHostI] = newHost
@control[newHostI] = wasHost
newHost.sendCode("taken_host", channel: @name)
wasHost.sendCode("lost_host", channel: @name)
@updateSubscriberList(client)
else
client.sendSystemMessage("#{who?.name || "Target"} is not in control and thereby can't be host")
return client.ack()
x.addCommand "Channel", "grant", (client, who) ->
return client.permissionDenied("grantControl") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if @control.indexOf(who) > -1
client.sendSystemMessage("#{who?.name || "Target"} is already in control")
else
@grantControl(who)
client.sendSystemMessage("#{who?.name || "Target"} is now in control!", COLORS.green)
return client.ack()
x.addCommand "Channel", "revoke", (client, who) ->
return client.permissionDenied("revokeControl") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if @control.indexOf(who) > -1
@revokeControl(who)
client.sendSystemMessage("#{who?.name || "Target"} is no longer in control!", COLORS.green)
else
client.sendSystemMessage("#{who?.name || "Target"} was not in control")
return client.ack()
x.addCommand "Channel", "rpckey", (client) ->
return client.permissionDenied("rpckey") unless @control.indexOf(client) > -1
client.sendSystemMessage("RPC-Key for this channel: #{@getRPCKey()}")
client.sendSystemMessage("The key will change with the channel password!", COLORS.warning)
return client.ack()
x.addCommand "Channel", "bookmarklet", (client, args...) ->
return client.permissionDenied("bookmarklet") unless @control.indexOf(client) > -1
showHelp = UTIL.extractArg(args, ["-h", "--help"])
withNotification = UTIL.extractArg(args, ["-n", "--notifications"])
desiredAction = UTIL.extractArg(args, ["-a", "--action"], 1)?[0] || "yt"
label = UTIL.extractArg(args, ["-l", "--label"], 1)?[0] || "+ SyncTube (#{desiredAction.toUpperCase()})"
if showHelp
client.sendSystemMessage("Usage: /bookmarklet [-h --help] | [-a --action=youtube] [-n --notifications] [-l --label LABEL]", COLORS.info)
client.sendSystemMessage(" Action might be one of: youtube video image url", COLORS.white)
client.sendSystemMessage(" Notifications will show you the result if enabled for youtube.com", COLORS.white)
client.sendSystemMessage(" Label is the name of the button, you can change that in your browser too", COLORS.white)
client.sendSystemMessage("The embedded key will change with the channel password!", COLORS.warning)
return client.ack()
if withNotification
script = """(function(b){n=Notification;x=function(a){h="%wsurl%";s="https://statics.bmonkeys.net/img/rpcico/";w=window;w.stwsb=w.stwsb||[];if(w.stwsc){if(w.stwsc.readyState!=1){w.stwsb.push(a)}else{w.stwsc.send(a)}}else{w.stwsb.push("rpc_client");w.stwsb.push(a);w.stwsc=new WebSocket(h);w.stwsc.onmessage=function(m){j=JSON.parse(m.data);if(j.type=="rpc_response"){new n("SyncTube",{body:j.data.message,icon:s+j.data.type+".png"})}};w.stwsc.onopen=function(){while(w.stwsb.length){w.stwsc.send(w.stwsb.shift())}};w.stwsc.onerror=function(){alert("stwscError: failed to connect to "+h);console.error(arguments[0])};w.stwsc.onclose=function(){w.stwsc=null}}};if(n.permission==="granted"||n.permission==="denied"){x(b)}else{n.requestPermission().then(function(result){x(b)})}})("/rpc -k %key% -c %channel% %action% "+window.location)"""
else
script = """(function(a){h="%wsurl%";w=window;w.stwsb=w.stwsb||[];if(w.stwsc){if(w.stwsc.readyState!=1){w.stwsb.push(a)}else{w.stwsc.send(a)}}else{w.stwsb.push("rpc_client");w.stwsb.push(a);w.stwsc=new WebSocket(h);w.stwsc.onopen=function(){while(w.stwsb.length){w.stwsc.send(w.stwsb.shift())}};w.stwsc.onerror=function(){alert("stwscError: failed to connect to "+h);console.error(arguments[0])};w.stwsc.onclose=function(){w.stwsc=null}}})("/rpc -k %key% -c %channel% %action% "+window.location)"""
wsurl = client.request.origin.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://")
wsurl += "/#{client.request.resourceURL.pathname}"
script = script.replace "%wsurl%", wsurl
script = script.replace "%channel%", @name
script = script.replace "%key%", @getRPCKey()
script = script.replace "%action%", desiredAction
client.sendSystemMessage("""
The embedded key will change with the channel password!<br>
<span style="color: #{COLORS.info}">Drag the following button to your bookmark bar:</span>
<a href="javascript:#{encodeURIComponent script}" class="btn btn-primary btn-xs" style="font-size: 10px">#{label}</a>
""", COLORS.warning)
return client.ack()
x.addCommand "Channel", "copt", (client, opt, value) ->
return client.permissionDenied("copt") unless @control.indexOf(client) > -1
return true unless who = @findClient(client, who)
if opt
if @options.hasOwnProperty(opt)
ok = opt
ov = @options[opt]
ot = typeof ov
if value?
try
if ot == "number"
nv = if !isNaN(x = Number(value)) then x else throw "value must be a number"
else if ot == "boolean"
nv = if (x = UTIL.strbool(value, null))? then x else throw "value must be a boolean(like)"
else if ot == "string"
nv = value
else
throw "unknown option value type (#{ot})"
throw "value hasn't changed" if nv == ov
@options[opt] = nv
@sendSettings()
c.sendSystemMessage("""
<span style="color: #{COLORS.warning}">CHANGED</span> channel option
<span style="color: #{COLORS.info}">#{ok}</span>
from <span style="color: #{COLORS.magenta}">#{ov}</span>
to <span style="color: #{COLORS.magenta}">#{nv}</span>
""", COLORS.white) for c in @control
catch err
client.sendSystemMessage("Failed to change channel option: #{err}")
else
client.sendSystemMessage("""
<span style="color: #{COLORS.info}">#{ok}</span>
is currently set to <span style="color: #{COLORS.magenta}">#{ov}</span>
<em style="color: #{COLORS.muted}">(#{ot})</em>
""", COLORS.white)
else
client.sendSystemMessage("Unknown option!")
else
cols = ["The following channel options are available:"]
for ok, ov of @options
cols.push """
<span style="color: #{COLORS.info}">#{ok}</span>
<span style="color: #{COLORS.magenta}">#{ov}</span>
<em style="color: #{COLORS.muted}">#{typeof ov}</em>
"""
client.sendSystemMessage(cols.join("<br>"), COLORS.white)
return client.ack()
|
[
{
"context": "by_2013_%282%29.jpg'\n @page.should.containEql 'Elena Soboleva'\n @page.should.not.containEql 'has-contributin",
"end": 1109,
"score": 0.990456759929657,
"start": 1095,
"tag": "NAME",
"value": "Elena Soboleva"
},
{
"context": "e correctly', ->\n @article.set('author', {id: '456', name: 'Artsy Editorial'})\n @page = jade.comp",
"end": 1256,
"score": 0.9808318018913269,
"start": 1253,
"tag": "USERNAME",
"value": "456"
},
{
"context": " ->\n @article.set('author', {id: '456', name: 'Artsy Editorial'})\n @page = jade.compile(fs.readFileSync(@file",
"end": 1281,
"score": 0.9990477561950684,
"start": 1266,
"tag": "NAME",
"value": "Artsy Editorial"
},
{
"context": "uthors', [{id: '523783258b3b815f7100055a', name: 'Casey Lesser'}])\n @article.set('author', {id: '456', name: ",
"end": 1613,
"score": 0.7907151579856873,
"start": 1601,
"tag": "NAME",
"value": "Casey Lesser"
},
{
"context": ")\n @article.set('author', {id: '456', name: 'Artsy Editorial'})\n @page = jade.compile(fs.readFil",
"end": 1668,
"score": 0.5836140513420105,
"start": 1666,
"tag": "NAME",
"value": "ts"
},
{
"context": ", [\n {id: '523783258b3b815f7100055a', name: 'Casey Lesser'}\n {id: '532783258b3b815f7100055b', name: 'M",
"end": 2064,
"score": 0.9832338690757751,
"start": 2052,
"tag": "NAME",
"value": "Casey Lesser"
},
{
"context": "r'}\n {id: '532783258b3b815f7100055b', name: 'Molly Gottschalk'}\n ])\n @article.set('author', {id: '456', n",
"end": 2129,
"score": 0.9998186230659485,
"start": 2113,
"tag": "NAME",
"value": "Molly Gottschalk"
},
{
"context": " ])\n @article.set('author', {id: '456', name: 'Artsy Editorial'})\n @page = jade.compile(fs.readFile",
"end": 2190,
"score": 0.5896596908569336,
"start": 2185,
"tag": "NAME",
"value": "Artsy"
},
{
"context": ", [\n {id: '523783258b3b815f7100055a', name: 'Casey Lesser'}\n {id: '532783258b3b815f7100055b', name: 'M",
"end": 2650,
"score": 0.9930071830749512,
"start": 2638,
"tag": "NAME",
"value": "Casey Lesser"
},
{
"context": "r'}\n {id: '532783258b3b815f7100055b', name: 'Molly Gottschalk'}\n {id: '532783258b3b815f7100055c', name: 'D",
"end": 2715,
"score": 0.9997008442878723,
"start": 2699,
"tag": "NAME",
"value": "Molly Gottschalk"
},
{
"context": "k'}\n {id: '532783258b3b815f7100055c', name: 'Demie Kim'}\n ])\n @article.set('author', {id: '456', n",
"end": 2773,
"score": 0.9998435974121094,
"start": 2764,
"tag": "NAME",
"value": "Demie Kim"
},
{
"context": ")\n @article.set('author', {id: '456', name: 'Artsy Editorial'})\n @page = jade.compile(fs.readFile",
"end": 2834,
"score": 0.6337190866470337,
"start": 2831,
"tag": "NAME",
"value": "tsy"
},
{
"context": "ntributing-name\">By'\n @page.should.containEql 'Casey Lesser, '\n @page.should.containEql 'Molly Gottsch",
"end": 3081,
"score": 0.9768224358558655,
"start": 3069,
"tag": "NAME",
"value": "Casey Lesser"
},
{
"context": "'Casey Lesser, '\n @page.should.containEql 'Molly Gottschalk and '\n @page.should.containEql 'Demie ",
"end": 3134,
"score": 0.9998723268508911,
"start": 3118,
"tag": "NAME",
"value": "Molly Gottschalk"
},
{
"context": "schalk and '\n @page.should.containEql 'Demie Kim'\n",
"end": 3187,
"score": 0.9998852610588074,
"start": 3178,
"tag": "NAME",
"value": "Demie Kim"
}
] | src/mobile/apps/fair_organizer/test/templates/articles.test.coffee | xtina-starr/force | 1 | _ = require 'underscore'
jade = require 'jade'
path = require 'path'
fs = require 'fs'
Backbone = require 'backbone'
Article = require '../../../../models/article'
fixtures = require '../../../../test/helpers/fixtures'
describe 'Article template', ->
beforeEach ->
@filename = path.resolve __dirname, "../../templates/articles.jade"
@article = new Article _.extend(
_.clone(fixtures.article)
slug: 'ten-booths-miart-2014'
thumbnail_image: 'https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg'
)
@props = {
articles: [@article]
sd: { ARTSY_EDITORIAL_CHANNEL: '123' }
}
it 'renders a non-editorial article correctly', ->
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
# FIXME: @page.should.containEql 'Top Ten Booths at miart 2014'
@page.should.containEql '/article/ten-booths-miart-2014'
@page.should.containEql 'https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg'
@page.should.containEql 'Elena Soboleva'
@page.should.not.containEql 'has-contributing-author'
it 'renders an editorial article correctly', ->
@article.set('author', {id: '456', name: 'Artsy Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.not.containEql 'has-contributing-author'
it 'renders a single contributing author', ->
@article.set('contributing_authors', [{id: '523783258b3b815f7100055a', name: 'Casey Lesser'}])
@article.set('author', {id: '456', name: 'Artsy Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'Casey Lesser'
@page.should.containEql 'article-item-contributing-name">By'
it 'renders two contributing authors', ->
@article.set('contributing_authors', [
{id: '523783258b3b815f7100055a', name: 'Casey Lesser'}
{id: '532783258b3b815f7100055b', name: 'Molly Gottschalk'}
])
@article.set('author', {id: '456', name: 'Artsy Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'article-item-contributing-name">By'
@page.should.containEql 'Casey Lesser and '
@page.should.containEql 'Molly Gottschalk'
it 'renders multiple contributing authors', ->
@article.set('contributing_authors', [
{id: '523783258b3b815f7100055a', name: 'Casey Lesser'}
{id: '532783258b3b815f7100055b', name: 'Molly Gottschalk'}
{id: '532783258b3b815f7100055c', name: 'Demie Kim'}
])
@article.set('author', {id: '456', name: 'Artsy Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'article-item-contributing-name">By'
@page.should.containEql 'Casey Lesser, '
@page.should.containEql 'Molly Gottschalk and '
@page.should.containEql 'Demie Kim'
| 82752 | _ = require 'underscore'
jade = require 'jade'
path = require 'path'
fs = require 'fs'
Backbone = require 'backbone'
Article = require '../../../../models/article'
fixtures = require '../../../../test/helpers/fixtures'
describe 'Article template', ->
beforeEach ->
@filename = path.resolve __dirname, "../../templates/articles.jade"
@article = new Article _.extend(
_.clone(fixtures.article)
slug: 'ten-booths-miart-2014'
thumbnail_image: 'https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg'
)
@props = {
articles: [@article]
sd: { ARTSY_EDITORIAL_CHANNEL: '123' }
}
it 'renders a non-editorial article correctly', ->
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
# FIXME: @page.should.containEql 'Top Ten Booths at miart 2014'
@page.should.containEql '/article/ten-booths-miart-2014'
@page.should.containEql 'https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg'
@page.should.containEql '<NAME>'
@page.should.not.containEql 'has-contributing-author'
it 'renders an editorial article correctly', ->
@article.set('author', {id: '456', name: '<NAME>'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.not.containEql 'has-contributing-author'
it 'renders a single contributing author', ->
@article.set('contributing_authors', [{id: '523783258b3b815f7100055a', name: '<NAME>'}])
@article.set('author', {id: '456', name: 'Ar<NAME>y Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'Casey Lesser'
@page.should.containEql 'article-item-contributing-name">By'
it 'renders two contributing authors', ->
@article.set('contributing_authors', [
{id: '523783258b3b815f7100055a', name: '<NAME>'}
{id: '532783258b3b815f7100055b', name: '<NAME>'}
])
@article.set('author', {id: '456', name: '<NAME> Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'article-item-contributing-name">By'
@page.should.containEql 'Casey Lesser and '
@page.should.containEql 'Molly Gottschalk'
it 'renders multiple contributing authors', ->
@article.set('contributing_authors', [
{id: '523783258b3b815f7100055a', name: '<NAME>'}
{id: '532783258b3b815f7100055b', name: '<NAME>'}
{id: '532783258b3b815f7100055c', name: '<NAME>'}
])
@article.set('author', {id: '456', name: 'Ar<NAME> Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'article-item-contributing-name">By'
@page.should.containEql '<NAME>, '
@page.should.containEql '<NAME> and '
@page.should.containEql '<NAME>'
| true | _ = require 'underscore'
jade = require 'jade'
path = require 'path'
fs = require 'fs'
Backbone = require 'backbone'
Article = require '../../../../models/article'
fixtures = require '../../../../test/helpers/fixtures'
describe 'Article template', ->
beforeEach ->
@filename = path.resolve __dirname, "../../templates/articles.jade"
@article = new Article _.extend(
_.clone(fixtures.article)
slug: 'ten-booths-miart-2014'
thumbnail_image: 'https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg'
)
@props = {
articles: [@article]
sd: { ARTSY_EDITORIAL_CHANNEL: '123' }
}
it 'renders a non-editorial article correctly', ->
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
# FIXME: @page.should.containEql 'Top Ten Booths at miart 2014'
@page.should.containEql '/article/ten-booths-miart-2014'
@page.should.containEql 'https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg'
@page.should.containEql 'PI:NAME:<NAME>END_PI'
@page.should.not.containEql 'has-contributing-author'
it 'renders an editorial article correctly', ->
@article.set('author', {id: '456', name: 'PI:NAME:<NAME>END_PI'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.not.containEql 'has-contributing-author'
it 'renders a single contributing author', ->
@article.set('contributing_authors', [{id: '523783258b3b815f7100055a', name: 'PI:NAME:<NAME>END_PI'}])
@article.set('author', {id: '456', name: 'ArPI:NAME:<NAME>END_PIy Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'Casey Lesser'
@page.should.containEql 'article-item-contributing-name">By'
it 'renders two contributing authors', ->
@article.set('contributing_authors', [
{id: '523783258b3b815f7100055a', name: 'PI:NAME:<NAME>END_PI'}
{id: '532783258b3b815f7100055b', name: 'PI:NAME:<NAME>END_PI'}
])
@article.set('author', {id: '456', name: 'PI:NAME:<NAME>END_PI Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'article-item-contributing-name">By'
@page.should.containEql 'Casey Lesser and '
@page.should.containEql 'Molly Gottschalk'
it 'renders multiple contributing authors', ->
@article.set('contributing_authors', [
{id: '523783258b3b815f7100055a', name: 'PI:NAME:<NAME>END_PI'}
{id: '532783258b3b815f7100055b', name: 'PI:NAME:<NAME>END_PI'}
{id: '532783258b3b815f7100055c', name: 'PI:NAME:<NAME>END_PI'}
])
@article.set('author', {id: '456', name: 'ArPI:NAME:<NAME>END_PI Editorial'})
@page = jade.compile(fs.readFileSync(@filename), filename: @filename) @props
@page.should.containEql 'Artsy Editorial'
@page.should.containEql 'article-item-contributing-name">By'
@page.should.containEql 'PI:NAME:<NAME>END_PI, '
@page.should.containEql 'PI:NAME:<NAME>END_PI and '
@page.should.containEql 'PI:NAME:<NAME>END_PI'
|
[
{
"context": "t be undone.'\n body_class: ''\n password: false\n prompt: 'Type <strong>%s</strong> to contin",
"end": 882,
"score": 0.9990584254264832,
"start": 877,
"tag": "PASSWORD",
"value": "false"
},
{
"context": "end(confirm_button)\n\n if (password = option 'password')\n confirm_label =\n (option 'prom",
"end": 3308,
"score": 0.8845402598381042,
"start": 3300,
"tag": "PASSWORD",
"value": "password"
}
] | admin/vendor/assets/javascripts/confirm_with_reveal.js.coffee | okbreathe/push_type | 314 | # Examples using Rails’ link_to helper
#
# Basic usage:
# = link_to 'Delete', foo_path(foo), method: :delete, data: { confirm: true }
#
# Customization of individual links/buttons via JSON in data-confirm:
# = link_to 'Delete', foo_path(foo), method: :delete, data: {
# confirm: {
# title: 'You might want to think twice about this!',
# body: 'If you click “Simon Says Delete” there will be no takebacks!',
# ok: 'Simon Says Delete'
# }
# }
#
# Fall back to window.confirm() when confirm is a plain string:
# = link_to 'Delete', foo_path(foo), method: :delete, confirm: 'Are you sure?'
$ = this.jQuery
$.fn.extend
confirmWithReveal: (options = {}) ->
defaults =
modal_class: 'medium'
title: 'Are you sure?'
title_class: ''
body: 'This action cannot be undone.'
body_class: ''
password: false
prompt: 'Type <strong>%s</strong> to continue:'
footer_class: ''
ok: 'Confirm'
ok_class: 'button alert'
cancel: 'Cancel'
cancel_class: 'button secondary'
settings = $.extend {}, defaults, options
do_confirm = ($el) ->
el_options = $el.data('confirm')
# The confirmation is actually triggered again when hitting "OK"
# (or whatever) in the modal (since we clone the original link in),
# but since we strip off the 'confirm' data attribute, we can tell
# whether this is the first confirmation or a subsequent one.
return true if !el_options
if (typeof el_options == 'string') and (el_options.length > 0)
return ($.rails?.confirm || window.confirm).call(window, el_options)
option = (name) ->
el_options[name] || settings[name]
# TODO: allow caller to pass in a template (DOM element to clone?)
modal = $("""
<div data-reveal class='reveal-modal #{option 'modal_class'}'>
<h2 data-confirm-title class='#{option 'title_class'}'></h2>
<p data-confirm-body class='#{option 'body_class'}'></p>
<div data-confirm-footer class='#{option 'footer_class'}'>
<a data-confirm-cancel class='#{option 'cancel_class'}'></a>
</div>
</div>
""")
confirm_button = if $el.is('a') then $el.clone() else $('<a/>')
confirm_button
.removeAttr('data-confirm')
.attr('class', option 'ok_class')
.html(option 'ok')
.on 'click', (e) ->
return false if $(this).prop('disabled')
# TODO: Handlers of this event cannot stop the confirmation from
# going through (e.g. chaining additional validation). Fix TBD.
$el.trigger('confirm.reveal', e)
if $el.is('form, :input')
$el
.closest('form')
.removeAttr('data-confirm')
.submit()
modal
.find('[data-confirm-title]')
.html(option 'title')
modal
.find('[data-confirm-body]')
.html(option 'body')
modal
.find('[data-confirm-cancel]')
.html(option 'cancel')
.on 'click', (e) ->
modal.foundation('reveal', 'close')
$el.trigger('cancel.reveal', e)
modal
.find('[data-confirm-footer]')
.append(confirm_button)
if (password = option 'password')
confirm_label =
(option 'prompt')
.replace '%s', password
confirm_html = """
<label>
#{confirm_label}
<input data-confirm-password type='text'/>
</label>
"""
modal
.find('[data-confirm-body]')
.after($(confirm_html))
modal
.find('[data-confirm-password]')
.on 'keyup', (e) ->
disabled = $(this).val() != password
confirm_button
.toggleClass('disabled', disabled)
.prop('disabled', disabled)
.trigger('keyup')
modal
.appendTo($('body'))
.foundation()
.foundation('reveal', 'open')
.on 'closed.fndtn.reveal', (e) ->
modal.remove()
return false
if $.rails
# We do NOT do the event binding if $.rails exists, because jquery_ujs
# has already done it for us
$.rails.allowAction = (link) -> do_confirm $(link)
return $(this)
else
handler = (e) ->
unless (do_confirm $(this))
e.preventDefault()
e.stopImmediatePropagation()
return @each () ->
$el = $(this)
$el.on 'click', 'a[data-confirm], :input[data-confirm]', handler
$el.on 'submit', 'form[data-confirm]', handler
$el | 16021 | # Examples using Rails’ link_to helper
#
# Basic usage:
# = link_to 'Delete', foo_path(foo), method: :delete, data: { confirm: true }
#
# Customization of individual links/buttons via JSON in data-confirm:
# = link_to 'Delete', foo_path(foo), method: :delete, data: {
# confirm: {
# title: 'You might want to think twice about this!',
# body: 'If you click “Simon Says Delete” there will be no takebacks!',
# ok: 'Simon Says Delete'
# }
# }
#
# Fall back to window.confirm() when confirm is a plain string:
# = link_to 'Delete', foo_path(foo), method: :delete, confirm: 'Are you sure?'
$ = this.jQuery
$.fn.extend
confirmWithReveal: (options = {}) ->
defaults =
modal_class: 'medium'
title: 'Are you sure?'
title_class: ''
body: 'This action cannot be undone.'
body_class: ''
password: <PASSWORD>
prompt: 'Type <strong>%s</strong> to continue:'
footer_class: ''
ok: 'Confirm'
ok_class: 'button alert'
cancel: 'Cancel'
cancel_class: 'button secondary'
settings = $.extend {}, defaults, options
do_confirm = ($el) ->
el_options = $el.data('confirm')
# The confirmation is actually triggered again when hitting "OK"
# (or whatever) in the modal (since we clone the original link in),
# but since we strip off the 'confirm' data attribute, we can tell
# whether this is the first confirmation or a subsequent one.
return true if !el_options
if (typeof el_options == 'string') and (el_options.length > 0)
return ($.rails?.confirm || window.confirm).call(window, el_options)
option = (name) ->
el_options[name] || settings[name]
# TODO: allow caller to pass in a template (DOM element to clone?)
modal = $("""
<div data-reveal class='reveal-modal #{option 'modal_class'}'>
<h2 data-confirm-title class='#{option 'title_class'}'></h2>
<p data-confirm-body class='#{option 'body_class'}'></p>
<div data-confirm-footer class='#{option 'footer_class'}'>
<a data-confirm-cancel class='#{option 'cancel_class'}'></a>
</div>
</div>
""")
confirm_button = if $el.is('a') then $el.clone() else $('<a/>')
confirm_button
.removeAttr('data-confirm')
.attr('class', option 'ok_class')
.html(option 'ok')
.on 'click', (e) ->
return false if $(this).prop('disabled')
# TODO: Handlers of this event cannot stop the confirmation from
# going through (e.g. chaining additional validation). Fix TBD.
$el.trigger('confirm.reveal', e)
if $el.is('form, :input')
$el
.closest('form')
.removeAttr('data-confirm')
.submit()
modal
.find('[data-confirm-title]')
.html(option 'title')
modal
.find('[data-confirm-body]')
.html(option 'body')
modal
.find('[data-confirm-cancel]')
.html(option 'cancel')
.on 'click', (e) ->
modal.foundation('reveal', 'close')
$el.trigger('cancel.reveal', e)
modal
.find('[data-confirm-footer]')
.append(confirm_button)
if (password = option '<PASSWORD>')
confirm_label =
(option 'prompt')
.replace '%s', password
confirm_html = """
<label>
#{confirm_label}
<input data-confirm-password type='text'/>
</label>
"""
modal
.find('[data-confirm-body]')
.after($(confirm_html))
modal
.find('[data-confirm-password]')
.on 'keyup', (e) ->
disabled = $(this).val() != password
confirm_button
.toggleClass('disabled', disabled)
.prop('disabled', disabled)
.trigger('keyup')
modal
.appendTo($('body'))
.foundation()
.foundation('reveal', 'open')
.on 'closed.fndtn.reveal', (e) ->
modal.remove()
return false
if $.rails
# We do NOT do the event binding if $.rails exists, because jquery_ujs
# has already done it for us
$.rails.allowAction = (link) -> do_confirm $(link)
return $(this)
else
handler = (e) ->
unless (do_confirm $(this))
e.preventDefault()
e.stopImmediatePropagation()
return @each () ->
$el = $(this)
$el.on 'click', 'a[data-confirm], :input[data-confirm]', handler
$el.on 'submit', 'form[data-confirm]', handler
$el | true | # Examples using Rails’ link_to helper
#
# Basic usage:
# = link_to 'Delete', foo_path(foo), method: :delete, data: { confirm: true }
#
# Customization of individual links/buttons via JSON in data-confirm:
# = link_to 'Delete', foo_path(foo), method: :delete, data: {
# confirm: {
# title: 'You might want to think twice about this!',
# body: 'If you click “Simon Says Delete” there will be no takebacks!',
# ok: 'Simon Says Delete'
# }
# }
#
# Fall back to window.confirm() when confirm is a plain string:
# = link_to 'Delete', foo_path(foo), method: :delete, confirm: 'Are you sure?'
$ = this.jQuery
$.fn.extend
confirmWithReveal: (options = {}) ->
defaults =
modal_class: 'medium'
title: 'Are you sure?'
title_class: ''
body: 'This action cannot be undone.'
body_class: ''
password: PI:PASSWORD:<PASSWORD>END_PI
prompt: 'Type <strong>%s</strong> to continue:'
footer_class: ''
ok: 'Confirm'
ok_class: 'button alert'
cancel: 'Cancel'
cancel_class: 'button secondary'
settings = $.extend {}, defaults, options
do_confirm = ($el) ->
el_options = $el.data('confirm')
# The confirmation is actually triggered again when hitting "OK"
# (or whatever) in the modal (since we clone the original link in),
# but since we strip off the 'confirm' data attribute, we can tell
# whether this is the first confirmation or a subsequent one.
return true if !el_options
if (typeof el_options == 'string') and (el_options.length > 0)
return ($.rails?.confirm || window.confirm).call(window, el_options)
option = (name) ->
el_options[name] || settings[name]
# TODO: allow caller to pass in a template (DOM element to clone?)
modal = $("""
<div data-reveal class='reveal-modal #{option 'modal_class'}'>
<h2 data-confirm-title class='#{option 'title_class'}'></h2>
<p data-confirm-body class='#{option 'body_class'}'></p>
<div data-confirm-footer class='#{option 'footer_class'}'>
<a data-confirm-cancel class='#{option 'cancel_class'}'></a>
</div>
</div>
""")
confirm_button = if $el.is('a') then $el.clone() else $('<a/>')
confirm_button
.removeAttr('data-confirm')
.attr('class', option 'ok_class')
.html(option 'ok')
.on 'click', (e) ->
return false if $(this).prop('disabled')
# TODO: Handlers of this event cannot stop the confirmation from
# going through (e.g. chaining additional validation). Fix TBD.
$el.trigger('confirm.reveal', e)
if $el.is('form, :input')
$el
.closest('form')
.removeAttr('data-confirm')
.submit()
modal
.find('[data-confirm-title]')
.html(option 'title')
modal
.find('[data-confirm-body]')
.html(option 'body')
modal
.find('[data-confirm-cancel]')
.html(option 'cancel')
.on 'click', (e) ->
modal.foundation('reveal', 'close')
$el.trigger('cancel.reveal', e)
modal
.find('[data-confirm-footer]')
.append(confirm_button)
if (password = option 'PI:PASSWORD:<PASSWORD>END_PI')
confirm_label =
(option 'prompt')
.replace '%s', password
confirm_html = """
<label>
#{confirm_label}
<input data-confirm-password type='text'/>
</label>
"""
modal
.find('[data-confirm-body]')
.after($(confirm_html))
modal
.find('[data-confirm-password]')
.on 'keyup', (e) ->
disabled = $(this).val() != password
confirm_button
.toggleClass('disabled', disabled)
.prop('disabled', disabled)
.trigger('keyup')
modal
.appendTo($('body'))
.foundation()
.foundation('reveal', 'open')
.on 'closed.fndtn.reveal', (e) ->
modal.remove()
return false
if $.rails
# We do NOT do the event binding if $.rails exists, because jquery_ujs
# has already done it for us
$.rails.allowAction = (link) -> do_confirm $(link)
return $(this)
else
handler = (e) ->
unless (do_confirm $(this))
e.preventDefault()
e.stopImmediatePropagation()
return @each () ->
$el = $(this)
$el.on 'click', 'a[data-confirm], :input[data-confirm]', handler
$el.on 'submit', 'form[data-confirm]', handler
$el |
[
{
"context": "phoneType: 'FIXED_LINE'\n ]\n }\n {\n should: 'Cardiff number'\n number: ['+44 29 1234 5678']\n e",
"end": 682,
"score": 0.5752971768379211,
"start": 678,
"tag": "NAME",
"value": "Card"
}
] | test/valid-data/international-test-uk-numbers.coffee | fbatroni/phone-format | 1 | InternationalUKTestNumbers = [
{
should: 'mobile GB number w/spaces and plus sign'
number: ['+44(0)777 55 55 613']
expect: [
countryCode: 'GB'
phoneType: 'MOBILE'
]
}
{
should: 'mobile GB number - no spaces - w/ country code'
number: ['+44(0)7775555613']
expect: [
countryCode: 'GB'
phoneType: 'MOBILE'
]
}
{
should: 'London number'
number: ['+44 20 7529 4600']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'London number'
number: ['+44 (0) 20 7529 4600']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Cardiff number'
number: ['+44 29 1234 5678']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Leeds number'
number: ['+44 113 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Leicester number'
number: ['+44 116 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Edinburgh number'
number: ['+44 131 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Liverpool number'
number: ['+44 151 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Evesham number'
number: ['+44 1386 234567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Oxford number'
number: ['+44 1865 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Swansea number'
number: ['+44 1792 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Bolton number'
number: ['+44 1204 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Sedbergh number'
number: ['+44 15396 12345']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Brampton number'
number: ['+44 16977 12345']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
]
module.exports = InternationalUKTestNumbers
| 143184 | InternationalUKTestNumbers = [
{
should: 'mobile GB number w/spaces and plus sign'
number: ['+44(0)777 55 55 613']
expect: [
countryCode: 'GB'
phoneType: 'MOBILE'
]
}
{
should: 'mobile GB number - no spaces - w/ country code'
number: ['+44(0)7775555613']
expect: [
countryCode: 'GB'
phoneType: 'MOBILE'
]
}
{
should: 'London number'
number: ['+44 20 7529 4600']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'London number'
number: ['+44 (0) 20 7529 4600']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: '<NAME>iff number'
number: ['+44 29 1234 5678']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Leeds number'
number: ['+44 113 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Leicester number'
number: ['+44 116 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Edinburgh number'
number: ['+44 131 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Liverpool number'
number: ['+44 151 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Evesham number'
number: ['+44 1386 234567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Oxford number'
number: ['+44 1865 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Swansea number'
number: ['+44 1792 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Bolton number'
number: ['+44 1204 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Sedbergh number'
number: ['+44 15396 12345']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Brampton number'
number: ['+44 16977 12345']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
]
module.exports = InternationalUKTestNumbers
| true | InternationalUKTestNumbers = [
{
should: 'mobile GB number w/spaces and plus sign'
number: ['+44(0)777 55 55 613']
expect: [
countryCode: 'GB'
phoneType: 'MOBILE'
]
}
{
should: 'mobile GB number - no spaces - w/ country code'
number: ['+44(0)7775555613']
expect: [
countryCode: 'GB'
phoneType: 'MOBILE'
]
}
{
should: 'London number'
number: ['+44 20 7529 4600']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'London number'
number: ['+44 (0) 20 7529 4600']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'PI:NAME:<NAME>END_PIiff number'
number: ['+44 29 1234 5678']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Leeds number'
number: ['+44 113 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Leicester number'
number: ['+44 116 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Edinburgh number'
number: ['+44 131 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Liverpool number'
number: ['+44 151 123 4567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Evesham number'
number: ['+44 1386 234567']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Oxford number'
number: ['+44 1865 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Swansea number'
number: ['+44 1792 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Bolton number'
number: ['+44 1204 123456']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Sedbergh number'
number: ['+44 15396 12345']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
{
should: 'Brampton number'
number: ['+44 16977 12345']
expect: [
countryCode: 'GB'
phoneType: 'FIXED_LINE'
]
}
]
module.exports = InternationalUKTestNumbers
|
[
{
"context": "\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"Jonah\"]\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book}",
"end": 14621,
"score": 0.8336039781570435,
"start": 14619,
"tag": "NAME",
"value": "ah"
}
] | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/cs/regexps.coffee | saiba-mais/bible-lessons | 149 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| titul (?! [a-z] ) #could be followed by a number
| kapitola | kapitoly | ver[šs]e | kapitol | kap | srv | ff | - | a
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* titul
| \d \W* ff (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Prvn[íi]|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Druh[áa]|Druh[ýy]|2|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:T[řr]et[íi]|3|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:a|srv)|-)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|G(?:enesis|n|en)|[1I]\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Prvn[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Ex(?:odus|od)?|(?:II|2)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Druh[ay\xE1\xFD][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[e\xE9]l(?:[\s\xa0]*a[\s\xa0]*drak)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|L(?:eviti(?:cusi|kus)|v|ev(?:iticus)?)|(?:III|3)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|T[rř]et[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Nu(?:meri|m)?|(?:IV|4)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|[CČ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S[i\xED]rachovec|Ecclesiasticus|S[i\xED]r|Kniha[\s\xa0]*S[i\xED]rachovcova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kniha[\s\xa0]*(?:moudrost[i\xED]|Moudrosti)|Wis|M(?:oudrost(?:[\s\xa0]*[SŠ]alomounova)?|dr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pl(?:[a\xE1][cč][\s\xa0]*Jerem[ij][a\xE1][sš][uů]v)?|Kniha[\s\xa0]*n[a\xE1][rř]k[uů]|Lam)|(?:Pl[a\xE1][cč])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:List[\s\xa0]*Jeremj[a\xE1][sš][uů]v|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zj(?:even(?:i(?:[\s\xa0]*(?:svat[e\xE9]ho[\s\xa0]*Jana|Janovo))?|\xED(?:[\s\xa0]*Janovo)?))?|Kniha[\s\xa0]*Zjeven[i\xED]|Rev|Apokalypsa)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Modlitbu[\s\xa0]*Manasse|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[5V][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|D(?:euteronomium|t|eut)|[5V]\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|P[a\xE1]t[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o(?:z(?:ue)?|sh)|z))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:oudc[uů]|dc?)|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:\xFA?t|uth?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Ezdr[a\xE1][sš]|1Esd|[1I]\.[\s\xa0]*Ezdr[a\xE1][sš]|Prvn[i\xED][\s\xa0]*Ezdr[a\xE1][sš])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Ezdr[a\xE1][sš]|2Esd|(?:II|2)\.[\s\xa0]*Ezdr[a\xE1][sš]|Druh[ay\xE1\xFD][\s\xa0]*Ezdr[a\xE1][sš])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:z(?:a[ij][a\xE1][sš])?|sa))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.|II|2|Druh[ay\xE1\xFD])[\s\xa0]*Samuelova)|(?:(?:II|2)[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|2Sam|(?:II|2)\.[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|Druh[ay\xE1\xFD][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:Prvn[i\xED]|[1I]\.|[1I])[\s\xa0]*Samuelova)|(?:[1I][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|1Sam|[1I]\.[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|Prvn[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|2Kgs|(?:II|2)\.[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|Druh[ay\xE1\xFD][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|1Kgs|[1I]\.[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|Prvn[i\xED][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|2Chr|(?:II|2)\.[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|Druh[ay\xE1\xFD][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|1Chr|[1I]\.[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|Prvn[i\xED][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:d(?:r[a\xE1][sš])?|ra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:em[ij][a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ester[\s\xa0]*(?:[rř]eck[e\xE9][\s\xa0]*(?:[cč][a\xE1]sti|dodatky)|\(řeck\xE9[\s\xa0]*(?:č\xE1sti|dodatky)\))|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J[o\xF3]?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[ZŽ]almy)|(?:Kniha[\s\xa0]*[zž]alm[uů]|[ZŽ]alm|Ps|[ZŽ])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarj[a\xE1][sš]ova[\s\xa0]*modlitba|PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P(?:r(?:[i\xED]s(?:lov[i\xED][\s\xa0]*[SŠ]alomounova)?|ov)?|ř(?:[i\xED]s(?:lov[i\xED][\s\xa0]*[SŠ]alomounova)?)?))|(?:P[rř][i\xED]slov[i\xED])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:az(?:atel)?|ohelet)|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P[i\xED]se[nň][\s\xa0]*ml[a\xE1]denc[uů][\s\xa0]*v[\s\xa0]*ho[rř][i\xED]c[i\xED][\s\xa0]*peci|T[rř]i[\s\xa0]*mu[zž]i[\s\xa0]*v[\s\xa0]*rozp[a\xE1]len[e\xE9][\s\xa0]*peci|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P[i\xED]s(?:e[nň][\s\xa0]*(?:p[i\xED]sn[i\xED]|[SŠ]alamounova))?|Song)|(?:P[i\xED]se[nň])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:er(?:em[ij][a\xE1][sš])?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:chiel|k))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Da(?:n(?:iel)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oz(?:e[a\xE1][sš])?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:(?:\xF3e)?l|o(?:el)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:os)?|\xC1mos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Abd(?:i(?:j[a\xE1][sš]|[a\xE1][sš]))?|Obad(?:j[a\xE1][sš]|j[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:\xE1[sš]|a[hsš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:c(?:h(?:[ae][a\xE1][sš])?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Na(?:h(?:um)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:aku)?k|Hab)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ofon[ij][a\xE1][sš]|f)|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:geus|eus)?|Hag)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:char[ij][a\xE1][sš])?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:achi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:ou[sš]ovo[\s\xa0]*evangelium|t)|t|at(?:ou[sš])?)|Evangelium[\s\xa0]*podle[\s\xa0]*Matou[sš]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar(?:kovo[\s\xa0]*evangelium|ek)|k|ark)|Evangelium[\s\xa0]*podle[\s\xa0]*Marka)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:uk(?:[a\xE1][sš]ovo[\s\xa0]*evangelium|e)|k|uk[a\xE1][sš])?|Evangelium[\s\xa0]*podle[\s\xa0]*Luk[a\xE1][sš]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Jan[uů]v|1John|[1I]\.[\s\xa0]*Jan[uů]v|Prvn[i\xED][\s\xa0]*Jan[uů]v)|(?:[1I]\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|[1I][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|Prvn[i\xED][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Jan[uů]v|2John|(?:II|2)\.[\s\xa0]*Jan[uů]v|Druh[ay\xE1\xFD][\s\xa0]*Jan[uů]v)|(?:(?:II|2)\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|(?:II|2)[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|Druh[ay\xE1\xFD][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Jan[uů]v|3John|(?:III|3)\.[\s\xa0]*Jan[uů]v|T[rř]et[i\xED][\s\xa0]*Jan[uů]v)|(?:(?:III|3)\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|(?:III|3)[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|T[rř]et[i\xED][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:anovo[\s\xa0]*evangelium|ohn|an)?|Evangelium[\s\xa0]*podle[\s\xa0]*Jana)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sk(?:utky(?:[\s\xa0]*apo[sš]tol(?:sk[e\xE9]|[u\xFCů]))?)?|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:R[io\xED]|Ř[i\xED])m|[RŘ]|List[\s\xa0]*[RŘ][i\xED]man[uů]m)|(?:[RŘ][i\xED]man[uů]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Korintsk[y\xFD]m)|(?:II[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|2[\s\xa0]*list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|2(?:[CK]|[\s\xa0]*K)or|IIK|2[\s\xa0]*?K|(?:II|2)\.(?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|K)|Druh[ay\xE1\xFD](?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|K))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|1(?:Cor|K)|IK|[1I]\.(?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|K)|Prvn[i\xED](?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|K))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ga(?:latsk[y\xFD]m|l)?|List[\s\xa0]*Galatsk[y\xFD]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:List[\s\xa0]*Ef(?:ez(?:sk[y\xFD]|an[uů])|\xE9zsk[y\xFD])m|E(?:fez?sk[y\xFD]m|ph|f))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filipsk[y\xFD]m|Phil|Fp|Filipensk[y\xFD]m|List[\s\xa0]*Filipsk[y\xFD]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kolosan[uů]m)|(?:Kolos(?:sens|ens)?k[y\xFD]m|Kol?|Col|List[\s\xa0]*Kolos(?:k[y\xFD]|an[uů])m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.[\s\xa0]*Tesalonick[y\xFD]|(?:II|2)[\s\xa0]*Tesalonick[y\xFD]|Druh[ay\xE1\xFD][\s\xa0]*Tesalonick[y\xFD])m)|(?:(?:II|2)[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|2Thess|(?:II|2)\.[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|Druh[ay\xE1\xFD][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[1I]\.[\s\xa0]*Tesalonick[y\xFD]|[1I][\s\xa0]*Tesalonick[y\xFD]|Prvn[i\xED][\s\xa0]*Tesalonick[y\xFD])m)|(?:[1I][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|1Thess|[1I]\.[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|Prvn[i\xED][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.[\s\xa0]*Timotej?|(?:II|2)[\s\xa0]*Timotej?|Druh[ay\xE1\xFD][\s\xa0]*Timotej?)ovi)|(?:(?:II|2)[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im))|2Tim|(?:II|2)\.[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im))|Druh[ay\xE1\xFD][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[1I]\.[\s\xa0]*Timotej?|[1I][\s\xa0]*Timotej?|Prvn[i\xED][\s\xa0]*Timotej?)ovi)|(?:[1I][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im))|1Tim|[1I]\.[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im))|Prvn[i\xED][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Titovi)|(?:T(?:itus|t|it)|List[\s\xa0]*Titovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filemonovi)|(?:F(?:ilemon|l?m)|Phlm|List[\s\xa0]*Filemonovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hebrej[uů]m)|(?:List[\s\xa0]*(?:Hebrej[uů]|[ZŽ]id[uů])m|[ZŽ]id[uů]m|[ZŽ]d|Heb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jakub[uů]v)|(?:J(?:a(?:kub|s)|k|ak)|List[\s\xa0]*Jakub[uů]v)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Petr[uů]v|2Pet|(?:II|2)\.[\s\xa0]*Petr[uů]v|Druh[ay\xE1\xFD][\s\xa0]*Petr[uů]v)|(?:(?:II|2)\.[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|(?:II|2)[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|Druh[ay\xE1\xFD][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Petr[uů]v|1Pet|[1I]\.[\s\xa0]*Petr[uů]v|Prvn[i\xED][\s\xa0]*Petr[uů]v)|(?:[1I]\.[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|[1I][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|Prvn[i\xED][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jud[uů]v)|(?:J(?:ud(?:[ae]|ova)|d|u)|List[\s\xa0]*Jud[uů]v)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:i(?:[a\xE1][sš]|t|j[a\xE1][sš]))?|\xF3bi(?:j[a\xE1][sš]|t)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:[u\xFA]d(?:it)?|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B(?:[a\xE1]ru(?:ch|k)|[a\xE1]r)|Kniha[\s\xa0]*B[a\xE1]ru(?:ch|k)ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zuz(?:ana)?|Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Mak(?:abejsk[a\xE1])?|2Macc|(?:II|2)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|Druh[ay\xE1\xFD][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Mak(?:abejsk[a\xE1])?|3Macc|(?:III|3)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|T[rř]et[i\xED][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*Mak(?:abejsk[a\xE1])?|4Macc|(?:IV|4)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|[CČ]tvrt[a\xE1][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Mak(?:abejsk[a\xE1])?|1Macc|[1I]\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|Prvn[i\xED][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| 1212 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| titul (?! [a-z] ) #could be followed by a number
| kapitola | kapitoly | ver[šs]e | kapitol | kap | srv | ff | - | a
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* titul
| \d \W* ff (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Prvn[íi]|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Druh[áa]|Druh[ýy]|2|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:T[řr]et[íi]|3|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:a|srv)|-)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|G(?:enesis|n|en)|[1I]\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Prvn[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Ex(?:odus|od)?|(?:II|2)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Druh[ay\xE1\xFD][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[e\xE9]l(?:[\s\xa0]*a[\s\xa0]*drak)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|L(?:eviti(?:cusi|kus)|v|ev(?:iticus)?)|(?:III|3)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|T[rř]et[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Nu(?:meri|m)?|(?:IV|4)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|[CČ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S[i\xED]rachovec|Ecclesiasticus|S[i\xED]r|Kniha[\s\xa0]*S[i\xED]rachovcova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kniha[\s\xa0]*(?:moudrost[i\xED]|Moudrosti)|Wis|M(?:oudrost(?:[\s\xa0]*[SŠ]alomounova)?|dr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pl(?:[a\xE1][cč][\s\xa0]*Jerem[ij][a\xE1][sš][uů]v)?|Kniha[\s\xa0]*n[a\xE1][rř]k[uů]|Lam)|(?:Pl[a\xE1][cč])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:List[\s\xa0]*Jeremj[a\xE1][sš][uů]v|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zj(?:even(?:i(?:[\s\xa0]*(?:svat[e\xE9]ho[\s\xa0]*Jana|Janovo))?|\xED(?:[\s\xa0]*Janovo)?))?|Kniha[\s\xa0]*Zjeven[i\xED]|Rev|Apokalypsa)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Modlitbu[\s\xa0]*Manasse|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[5V][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|D(?:euteronomium|t|eut)|[5V]\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|P[a\xE1]t[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o(?:z(?:ue)?|sh)|z))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:oudc[uů]|dc?)|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:\xFA?t|uth?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Ezdr[a\xE1][sš]|1Esd|[1I]\.[\s\xa0]*Ezdr[a\xE1][sš]|Prvn[i\xED][\s\xa0]*Ezdr[a\xE1][sš])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Ezdr[a\xE1][sš]|2Esd|(?:II|2)\.[\s\xa0]*Ezdr[a\xE1][sš]|Druh[ay\xE1\xFD][\s\xa0]*Ezdr[a\xE1][sš])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:z(?:a[ij][a\xE1][sš])?|sa))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.|II|2|Druh[ay\xE1\xFD])[\s\xa0]*Samuelova)|(?:(?:II|2)[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|2Sam|(?:II|2)\.[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|Druh[ay\xE1\xFD][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:Prvn[i\xED]|[1I]\.|[1I])[\s\xa0]*Samuelova)|(?:[1I][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|1Sam|[1I]\.[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|Prvn[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|2Kgs|(?:II|2)\.[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|Druh[ay\xE1\xFD][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|1Kgs|[1I]\.[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|Prvn[i\xED][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|2Chr|(?:II|2)\.[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|Druh[ay\xE1\xFD][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|1Chr|[1I]\.[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|Prvn[i\xED][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:d(?:r[a\xE1][sš])?|ra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:em[ij][a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ester[\s\xa0]*(?:[rř]eck[e\xE9][\s\xa0]*(?:[cč][a\xE1]sti|dodatky)|\(řeck\xE9[\s\xa0]*(?:č\xE1sti|dodatky)\))|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J[o\xF3]?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[ZŽ]almy)|(?:Kniha[\s\xa0]*[zž]alm[uů]|[ZŽ]alm|Ps|[ZŽ])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarj[a\xE1][sš]ova[\s\xa0]*modlitba|PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P(?:r(?:[i\xED]s(?:lov[i\xED][\s\xa0]*[SŠ]alomounova)?|ov)?|ř(?:[i\xED]s(?:lov[i\xED][\s\xa0]*[SŠ]alomounova)?)?))|(?:P[rř][i\xED]slov[i\xED])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:az(?:atel)?|ohelet)|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P[i\xED]se[nň][\s\xa0]*ml[a\xE1]denc[uů][\s\xa0]*v[\s\xa0]*ho[rř][i\xED]c[i\xED][\s\xa0]*peci|T[rř]i[\s\xa0]*mu[zž]i[\s\xa0]*v[\s\xa0]*rozp[a\xE1]len[e\xE9][\s\xa0]*peci|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P[i\xED]s(?:e[nň][\s\xa0]*(?:p[i\xED]sn[i\xED]|[SŠ]alamounova))?|Song)|(?:P[i\xED]se[nň])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:er(?:em[ij][a\xE1][sš])?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:chiel|k))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Da(?:n(?:iel)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oz(?:e[a\xE1][sš])?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:(?:\xF3e)?l|o(?:el)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:os)?|\xC1mos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Abd(?:i(?:j[a\xE1][sš]|[a\xE1][sš]))?|Obad(?:j[a\xE1][sš]|j[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jon<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:\xE1[sš]|a[hsš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:c(?:h(?:[ae][a\xE1][sš])?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Na(?:h(?:um)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:aku)?k|Hab)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ofon[ij][a\xE1][sš]|f)|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:geus|eus)?|Hag)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:char[ij][a\xE1][sš])?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:achi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:ou[sš]ovo[\s\xa0]*evangelium|t)|t|at(?:ou[sš])?)|Evangelium[\s\xa0]*podle[\s\xa0]*Matou[sš]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar(?:kovo[\s\xa0]*evangelium|ek)|k|ark)|Evangelium[\s\xa0]*podle[\s\xa0]*Marka)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:uk(?:[a\xE1][sš]ovo[\s\xa0]*evangelium|e)|k|uk[a\xE1][sš])?|Evangelium[\s\xa0]*podle[\s\xa0]*Luk[a\xE1][sš]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Jan[uů]v|1John|[1I]\.[\s\xa0]*Jan[uů]v|Prvn[i\xED][\s\xa0]*Jan[uů]v)|(?:[1I]\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|[1I][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|Prvn[i\xED][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Jan[uů]v|2John|(?:II|2)\.[\s\xa0]*Jan[uů]v|Druh[ay\xE1\xFD][\s\xa0]*Jan[uů]v)|(?:(?:II|2)\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|(?:II|2)[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|Druh[ay\xE1\xFD][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Jan[uů]v|3John|(?:III|3)\.[\s\xa0]*Jan[uů]v|T[rř]et[i\xED][\s\xa0]*Jan[uů]v)|(?:(?:III|3)\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|(?:III|3)[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|T[rř]et[i\xED][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:anovo[\s\xa0]*evangelium|ohn|an)?|Evangelium[\s\xa0]*podle[\s\xa0]*Jana)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sk(?:utky(?:[\s\xa0]*apo[sš]tol(?:sk[e\xE9]|[u\xFCů]))?)?|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:R[io\xED]|Ř[i\xED])m|[RŘ]|List[\s\xa0]*[RŘ][i\xED]man[uů]m)|(?:[RŘ][i\xED]man[uů]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Korintsk[y\xFD]m)|(?:II[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|2[\s\xa0]*list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|2(?:[CK]|[\s\xa0]*K)or|IIK|2[\s\xa0]*?K|(?:II|2)\.(?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|K)|Druh[ay\xE1\xFD](?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|K))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|1(?:Cor|K)|IK|[1I]\.(?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|K)|Prvn[i\xED](?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|K))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ga(?:latsk[y\xFD]m|l)?|List[\s\xa0]*Galatsk[y\xFD]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:List[\s\xa0]*Ef(?:ez(?:sk[y\xFD]|an[uů])|\xE9zsk[y\xFD])m|E(?:fez?sk[y\xFD]m|ph|f))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filipsk[y\xFD]m|Phil|Fp|Filipensk[y\xFD]m|List[\s\xa0]*Filipsk[y\xFD]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kolosan[uů]m)|(?:Kolos(?:sens|ens)?k[y\xFD]m|Kol?|Col|List[\s\xa0]*Kolos(?:k[y\xFD]|an[uů])m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.[\s\xa0]*Tesalonick[y\xFD]|(?:II|2)[\s\xa0]*Tesalonick[y\xFD]|Druh[ay\xE1\xFD][\s\xa0]*Tesalonick[y\xFD])m)|(?:(?:II|2)[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|2Thess|(?:II|2)\.[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|Druh[ay\xE1\xFD][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[1I]\.[\s\xa0]*Tesalonick[y\xFD]|[1I][\s\xa0]*Tesalonick[y\xFD]|Prvn[i\xED][\s\xa0]*Tesalonick[y\xFD])m)|(?:[1I][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|1Thess|[1I]\.[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|Prvn[i\xED][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.[\s\xa0]*Timotej?|(?:II|2)[\s\xa0]*Timotej?|Druh[ay\xE1\xFD][\s\xa0]*Timotej?)ovi)|(?:(?:II|2)[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im))|2Tim|(?:II|2)\.[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im))|Druh[ay\xE1\xFD][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[1I]\.[\s\xa0]*Timotej?|[1I][\s\xa0]*Timotej?|Prvn[i\xED][\s\xa0]*Timotej?)ovi)|(?:[1I][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im))|1Tim|[1I]\.[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im))|Prvn[i\xED][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Titovi)|(?:T(?:itus|t|it)|List[\s\xa0]*Titovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filemonovi)|(?:F(?:ilemon|l?m)|Phlm|List[\s\xa0]*Filemonovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hebrej[uů]m)|(?:List[\s\xa0]*(?:Hebrej[uů]|[ZŽ]id[uů])m|[ZŽ]id[uů]m|[ZŽ]d|Heb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jakub[uů]v)|(?:J(?:a(?:kub|s)|k|ak)|List[\s\xa0]*Jakub[uů]v)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Petr[uů]v|2Pet|(?:II|2)\.[\s\xa0]*Petr[uů]v|Druh[ay\xE1\xFD][\s\xa0]*Petr[uů]v)|(?:(?:II|2)\.[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|(?:II|2)[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|Druh[ay\xE1\xFD][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Petr[uů]v|1Pet|[1I]\.[\s\xa0]*Petr[uů]v|Prvn[i\xED][\s\xa0]*Petr[uů]v)|(?:[1I]\.[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|[1I][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|Prvn[i\xED][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jud[uů]v)|(?:J(?:ud(?:[ae]|ova)|d|u)|List[\s\xa0]*Jud[uů]v)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:i(?:[a\xE1][sš]|t|j[a\xE1][sš]))?|\xF3bi(?:j[a\xE1][sš]|t)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:[u\xFA]d(?:it)?|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B(?:[a\xE1]ru(?:ch|k)|[a\xE1]r)|Kniha[\s\xa0]*B[a\xE1]ru(?:ch|k)ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zuz(?:ana)?|Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Mak(?:abejsk[a\xE1])?|2Macc|(?:II|2)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|Druh[ay\xE1\xFD][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Mak(?:abejsk[a\xE1])?|3Macc|(?:III|3)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|T[rř]et[i\xED][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*Mak(?:abejsk[a\xE1])?|4Macc|(?:IV|4)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|[CČ]tvrt[a\xE1][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Mak(?:abejsk[a\xE1])?|1Macc|[1I]\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|Prvn[i\xED][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| true | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| titul (?! [a-z] ) #could be followed by a number
| kapitola | kapitoly | ver[šs]e | kapitol | kap | srv | ff | - | a
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* titul
| \d \W* ff (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Prvn[íi]|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Druh[áa]|Druh[ýy]|2|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:T[řr]et[íi]|3|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:a|srv)|-)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|G(?:enesis|n|en)|[1I]\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Prvn[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Ex(?:odus|od)?|(?:II|2)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Druh[ay\xE1\xFD][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[e\xE9]l(?:[\s\xa0]*a[\s\xa0]*drak)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|L(?:eviti(?:cusi|kus)|v|ev(?:iticus)?)|(?:III|3)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|T[rř]et[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|Nu(?:meri|m)?|(?:IV|4)\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|[CČ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S[i\xED]rachovec|Ecclesiasticus|S[i\xED]r|Kniha[\s\xa0]*S[i\xED]rachovcova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kniha[\s\xa0]*(?:moudrost[i\xED]|Moudrosti)|Wis|M(?:oudrost(?:[\s\xa0]*[SŠ]alomounova)?|dr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pl(?:[a\xE1][cč][\s\xa0]*Jerem[ij][a\xE1][sš][uů]v)?|Kniha[\s\xa0]*n[a\xE1][rř]k[uů]|Lam)|(?:Pl[a\xE1][cč])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:List[\s\xa0]*Jeremj[a\xE1][sš][uů]v|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zj(?:even(?:i(?:[\s\xa0]*(?:svat[e\xE9]ho[\s\xa0]*Jana|Janovo))?|\xED(?:[\s\xa0]*Janovo)?))?|Kniha[\s\xa0]*Zjeven[i\xED]|Rev|Apokalypsa)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Modlitbu[\s\xa0]*Manasse|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[5V][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|D(?:euteronomium|t|eut)|[5V]\.[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova|P[a\xE1]t[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž][i\xED][sš]|Moj[zž][i\xED][sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o(?:z(?:ue)?|sh)|z))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:oudc[uů]|dc?)|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:\xFA?t|uth?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Ezdr[a\xE1][sš]|1Esd|[1I]\.[\s\xa0]*Ezdr[a\xE1][sš]|Prvn[i\xED][\s\xa0]*Ezdr[a\xE1][sš])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Ezdr[a\xE1][sš]|2Esd|(?:II|2)\.[\s\xa0]*Ezdr[a\xE1][sš]|Druh[ay\xE1\xFD][\s\xa0]*Ezdr[a\xE1][sš])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:z(?:a[ij][a\xE1][sš])?|sa))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.|II|2|Druh[ay\xE1\xFD])[\s\xa0]*Samuelova)|(?:(?:II|2)[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|2Sam|(?:II|2)\.[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|Druh[ay\xE1\xFD][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:Prvn[i\xED]|[1I]\.|[1I])[\s\xa0]*Samuelova)|(?:[1I][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|1Sam|[1I]\.[\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?)|Prvn[i\xED][\s\xa0]*(?:kniha[\s\xa0]*Samuelova|S(?:amuel|am)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|2Kgs|(?:II|2)\.[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|Druh[ay\xE1\xFD][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|1Kgs|[1I]\.[\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1])|Prvn[i\xED][\s\xa0]*(?:Kr(?:[a\xE1]lovsk[a\xE1]|[a\xE1]l)?|kniha[\s\xa0]*kr[a\xE1]lovsk[a\xE1]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|2Chr|(?:II|2)\.[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|Druh[ay\xE1\xFD][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|1Chr|[1I]\.[\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?)|Prvn[i\xED][\s\xa0]*(?:Letopis[uů]|Kronik|kniha[\s\xa0]*kronik|Pa(?:ralipomenon)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:d(?:r[a\xE1][sš])?|ra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:em[ij][a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ester[\s\xa0]*(?:[rř]eck[e\xE9][\s\xa0]*(?:[cč][a\xE1]sti|dodatky)|\(řeck\xE9[\s\xa0]*(?:č\xE1sti|dodatky)\))|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J[o\xF3]?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[ZŽ]almy)|(?:Kniha[\s\xa0]*[zž]alm[uů]|[ZŽ]alm|Ps|[ZŽ])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarj[a\xE1][sš]ova[\s\xa0]*modlitba|PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P(?:r(?:[i\xED]s(?:lov[i\xED][\s\xa0]*[SŠ]alomounova)?|ov)?|ř(?:[i\xED]s(?:lov[i\xED][\s\xa0]*[SŠ]alomounova)?)?))|(?:P[rř][i\xED]slov[i\xED])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:az(?:atel)?|ohelet)|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P[i\xED]se[nň][\s\xa0]*ml[a\xE1]denc[uů][\s\xa0]*v[\s\xa0]*ho[rř][i\xED]c[i\xED][\s\xa0]*peci|T[rř]i[\s\xa0]*mu[zž]i[\s\xa0]*v[\s\xa0]*rozp[a\xE1]len[e\xE9][\s\xa0]*peci|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:P[i\xED]s(?:e[nň][\s\xa0]*(?:p[i\xED]sn[i\xED]|[SŠ]alamounova))?|Song)|(?:P[i\xED]se[nň])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:er(?:em[ij][a\xE1][sš])?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:chiel|k))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Da(?:n(?:iel)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Oz(?:e[a\xE1][sš])?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:(?:\xF3e)?l|o(?:el)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:os)?|\xC1mos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Abd(?:i(?:j[a\xE1][sš]|[a\xE1][sš]))?|Obad(?:j[a\xE1][sš]|j[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["JonPI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:\xE1[sš]|a[hsš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:c(?:h(?:[ae][a\xE1][sš])?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Na(?:h(?:um)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:aku)?k|Hab)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ofon[ij][a\xE1][sš]|f)|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:geus|eus)?|Hag)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:char[ij][a\xE1][sš])?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:achi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:ou[sš]ovo[\s\xa0]*evangelium|t)|t|at(?:ou[sš])?)|Evangelium[\s\xa0]*podle[\s\xa0]*Matou[sš]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar(?:kovo[\s\xa0]*evangelium|ek)|k|ark)|Evangelium[\s\xa0]*podle[\s\xa0]*Marka)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:uk(?:[a\xE1][sš]ovo[\s\xa0]*evangelium|e)|k|uk[a\xE1][sš])?|Evangelium[\s\xa0]*podle[\s\xa0]*Luk[a\xE1][sš]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Jan[uů]v|1John|[1I]\.[\s\xa0]*Jan[uů]v|Prvn[i\xED][\s\xa0]*Jan[uů]v)|(?:[1I]\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|[1I][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|Prvn[i\xED][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Jan[uů]v|2John|(?:II|2)\.[\s\xa0]*Jan[uů]v|Druh[ay\xE1\xFD][\s\xa0]*Jan[uů]v)|(?:(?:II|2)\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|(?:II|2)[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|Druh[ay\xE1\xFD][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Jan[uů]v|3John|(?:III|3)\.[\s\xa0]*Jan[uů]v|T[rř]et[i\xED][\s\xa0]*Jan[uů]v)|(?:(?:III|3)\.[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|(?:III|3)[\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v)|T[rř]et[i\xED][\s\xa0]*(?:J(?:anova|an)?|list[\s\xa0]*Jan[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:anovo[\s\xa0]*evangelium|ohn|an)?|Evangelium[\s\xa0]*podle[\s\xa0]*Jana)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sk(?:utky(?:[\s\xa0]*apo[sš]tol(?:sk[e\xE9]|[u\xFCů]))?)?|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:R[io\xED]|Ř[i\xED])m|[RŘ]|List[\s\xa0]*[RŘ][i\xED]man[uů]m)|(?:[RŘ][i\xED]man[uů]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Korintsk[y\xFD]m)|(?:II[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|2[\s\xa0]*list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|2(?:[CK]|[\s\xa0]*K)or|IIK|2[\s\xa0]*?K|(?:II|2)\.(?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|K)|Druh[ay\xE1\xFD](?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m)?)|K))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|1(?:Cor|K)|IK|[1I]\.(?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|K)|Prvn[i\xED](?:[\s\xa0]*(?:list[\s\xa0]*Korin(?:tsk[y\xFD]|sk[y\xFD])m|K(?:orintsk[y\xFD]m|or)?)|K))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ga(?:latsk[y\xFD]m|l)?|List[\s\xa0]*Galatsk[y\xFD]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:List[\s\xa0]*Ef(?:ez(?:sk[y\xFD]|an[uů])|\xE9zsk[y\xFD])m|E(?:fez?sk[y\xFD]m|ph|f))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filipsk[y\xFD]m|Phil|Fp|Filipensk[y\xFD]m|List[\s\xa0]*Filipsk[y\xFD]m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kolosan[uů]m)|(?:Kolos(?:sens|ens)?k[y\xFD]m|Kol?|Col|List[\s\xa0]*Kolos(?:k[y\xFD]|an[uů])m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.[\s\xa0]*Tesalonick[y\xFD]|(?:II|2)[\s\xa0]*Tesalonick[y\xFD]|Druh[ay\xE1\xFD][\s\xa0]*Tesalonick[y\xFD])m)|(?:(?:II|2)[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|2Thess|(?:II|2)\.[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|Druh[ay\xE1\xFD][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[1I]\.[\s\xa0]*Tesalonick[y\xFD]|[1I][\s\xa0]*Tesalonick[y\xFD]|Prvn[i\xED][\s\xa0]*Tesalonick[y\xFD])m)|(?:[1I][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|1Thess|[1I]\.[\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te)|Prvn[i\xED][\s\xa0]*(?:list[\s\xa0]*(?:Solu[nň]sk[y\xFD]|Tesalonick[y\xFD])m|(?:Tessalonicen|Solu[nň])sk[y\xFD]m|Sol|Te))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:II|2)\.[\s\xa0]*Timotej?|(?:II|2)[\s\xa0]*Timotej?|Druh[ay\xE1\xFD][\s\xa0]*Timotej?)ovi)|(?:(?:II|2)[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im))|2Tim|(?:II|2)\.[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im))|Druh[ay\xE1\xFD][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|etej)ovi|T(?:imoteus|m|im)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[1I]\.[\s\xa0]*Timotej?|[1I][\s\xa0]*Timotej?|Prvn[i\xED][\s\xa0]*Timotej?)ovi)|(?:[1I][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im))|1Tim|[1I]\.[\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im))|Prvn[i\xED][\s\xa0]*(?:list[\s\xa0]*Tim(?:otej?|ete)ovi|T(?:imoteus|m|im)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Titovi)|(?:T(?:itus|t|it)|List[\s\xa0]*Titovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filemonovi)|(?:F(?:ilemon|l?m)|Phlm|List[\s\xa0]*Filemonovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hebrej[uů]m)|(?:List[\s\xa0]*(?:Hebrej[uů]|[ZŽ]id[uů])m|[ZŽ]id[uů]m|[ZŽ]d|Heb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jakub[uů]v)|(?:J(?:a(?:kub|s)|k|ak)|List[\s\xa0]*Jakub[uů]v)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Petr[uů]v|2Pet|(?:II|2)\.[\s\xa0]*Petr[uů]v|Druh[ay\xE1\xFD][\s\xa0]*Petr[uů]v)|(?:(?:II|2)\.[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|(?:II|2)[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|Druh[ay\xE1\xFD][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Petr[uů]v|1Pet|[1I]\.[\s\xa0]*Petr[uů]v|Prvn[i\xED][\s\xa0]*Petr[uů]v)|(?:[1I]\.[\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|[1I][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v)|Prvn[i\xED][\s\xa0]*(?:P(?:etrova|t|etr)?|list[\s\xa0]*Petr[uů]v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jud[uů]v)|(?:J(?:ud(?:[ae]|ova)|d|u)|List[\s\xa0]*Jud[uů]v)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:i(?:[a\xE1][sš]|t|j[a\xE1][sš]))?|\xF3bi(?:j[a\xE1][sš]|t)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:[u\xFA]d(?:it)?|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B(?:[a\xE1]ru(?:ch|k)|[a\xE1]r)|Kniha[\s\xa0]*B[a\xE1]ru(?:ch|k)ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zuz(?:ana)?|Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:II|2)[\s\xa0]*Mak(?:abejsk[a\xE1])?|2Macc|(?:II|2)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|Druh[ay\xE1\xFD][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Mak(?:abejsk[a\xE1])?|3Macc|(?:III|3)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|T[rř]et[i\xED][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*Mak(?:abejsk[a\xE1])?|4Macc|(?:IV|4)\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|[CČ]tvrt[a\xE1][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[1I][\s\xa0]*Mak(?:abejsk[a\xE1])?|1Macc|[1I]\.[\s\xa0]*Mak(?:abejsk[a\xE1])?|Prvn[i\xED][\s\xa0]*Mak(?:abejsk[a\xE1])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
|
[
{
"context": "\n session.set\n email : 'user@example.com'\n password : '$ecre8'\n r",
"end": 748,
"score": 0.9999191164970398,
"start": 732,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": " : 'user@example.com'\n password : '$ecre8'\n rememberMe : true\n\n it 'is v",
"end": 783,
"score": 0.9993667006492615,
"start": 776,
"tag": "PASSWORD",
"value": "'$ecre8"
},
{
"context": "beforeEach ->\n session.set password : '$ecre8'\n\n it 'is invalid', ->\n e",
"end": 1068,
"score": 0.9993671774864197,
"start": 1061,
"tag": "PASSWORD",
"value": "'$ecre8"
},
{
"context": " email : ''\n password : '$ecre8'\n\n it 'is invalid', ->\n e",
"end": 1378,
"score": 0.999369204044342,
"start": 1371,
"tag": "PASSWORD",
"value": "'$ecre8"
},
{
"context": " beforeEach ->\n session.set email : 'user@example.com'\n\n it 'is invalid', ->\n e",
"end": 1692,
"score": 0.9999178647994995,
"start": 1676,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": " session.set\n email : 'user@example.com'\n password : ''\n\n it '",
"end": 1984,
"score": 0.9999200701713562,
"start": 1968,
"tag": "EMAIL",
"value": "user@example.com"
}
] | source/TextUml/Scripts/specs/application/models/session.coffee | marufsiddiqui/textuml-dotnet | 1 | define (require) ->
_ = require 'underscore'
Session = require '../../../application/models/session'
describe 'models/session', ->
session = null
beforeEach -> session = new Session
describe '#defaults', ->
it 'has #email', ->
expect(session.defaults()).to.have.property 'email'
it 'has #password', ->
expect(session.defaults()).to.have.property 'password'
it 'has #rememberMe', ->
expect(session.defaults()).to.have.property 'rememberMe'
describe '#url', ->
it 'is set', -> expect(session.url).to.exist
describe 'validation', ->
describe 'valid', ->
beforeEach ->
session.set
email : 'user@example.com'
password : '$ecre8'
rememberMe : true
it 'is valid', -> expect(session.isValid()).to.be.ok
describe 'invalid', ->
describe '#email', ->
describe 'missing', ->
beforeEach ->
session.set password : '$ecre8'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'email'
describe 'blank', ->
beforeEach ->
session.set
email : ''
password : '$ecre8'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'email'
describe '#password', ->
describe 'missing', ->
beforeEach ->
session.set email : 'user@example.com'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'password'
describe 'blank', ->
beforeEach ->
session.set
email : 'user@example.com'
password : ''
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'password' | 184245 | define (require) ->
_ = require 'underscore'
Session = require '../../../application/models/session'
describe 'models/session', ->
session = null
beforeEach -> session = new Session
describe '#defaults', ->
it 'has #email', ->
expect(session.defaults()).to.have.property 'email'
it 'has #password', ->
expect(session.defaults()).to.have.property 'password'
it 'has #rememberMe', ->
expect(session.defaults()).to.have.property 'rememberMe'
describe '#url', ->
it 'is set', -> expect(session.url).to.exist
describe 'validation', ->
describe 'valid', ->
beforeEach ->
session.set
email : '<EMAIL>'
password : <PASSWORD>'
rememberMe : true
it 'is valid', -> expect(session.isValid()).to.be.ok
describe 'invalid', ->
describe '#email', ->
describe 'missing', ->
beforeEach ->
session.set password : <PASSWORD>'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'email'
describe 'blank', ->
beforeEach ->
session.set
email : ''
password : <PASSWORD>'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'email'
describe '#password', ->
describe 'missing', ->
beforeEach ->
session.set email : '<EMAIL>'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'password'
describe 'blank', ->
beforeEach ->
session.set
email : '<EMAIL>'
password : ''
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'password' | true | define (require) ->
_ = require 'underscore'
Session = require '../../../application/models/session'
describe 'models/session', ->
session = null
beforeEach -> session = new Session
describe '#defaults', ->
it 'has #email', ->
expect(session.defaults()).to.have.property 'email'
it 'has #password', ->
expect(session.defaults()).to.have.property 'password'
it 'has #rememberMe', ->
expect(session.defaults()).to.have.property 'rememberMe'
describe '#url', ->
it 'is set', -> expect(session.url).to.exist
describe 'validation', ->
describe 'valid', ->
beforeEach ->
session.set
email : 'PI:EMAIL:<EMAIL>END_PI'
password : PI:PASSWORD:<PASSWORD>END_PI'
rememberMe : true
it 'is valid', -> expect(session.isValid()).to.be.ok
describe 'invalid', ->
describe '#email', ->
describe 'missing', ->
beforeEach ->
session.set password : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'email'
describe 'blank', ->
beforeEach ->
session.set
email : ''
password : PI:PASSWORD:<PASSWORD>END_PI'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'email'
describe '#password', ->
describe 'missing', ->
beforeEach ->
session.set email : 'PI:EMAIL:<EMAIL>END_PI'
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'password'
describe 'blank', ->
beforeEach ->
session.set
email : 'PI:EMAIL:<EMAIL>END_PI'
password : ''
it 'is invalid', ->
expect(session.isValid()).to.not.be.ok
expect(session.validationError).to.have.property 'password' |
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998904466629028,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhakim RAFIK\n * @date \t\tMar 2021\n###\n\n{ DataTypes, Model } \t= ",
"end": 129,
"score": 0.9998831152915955,
"start": 113,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
}
] | src/app/models/orders.coffee | AbdelhakimRafik/Pharmalogy-API | 0 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date Mar 2021
###
{ DataTypes, Model } = require 'sequelize'
{ sequelize } = require '../../database'
###
Order model
###
class Order extends Model
# initialize model
Order.init
user:
allowNull: false
type: Sequelize.INTEGER
pharmacy:
allowNull: false,
type: Sequelize.INTEGER
status:
allowNull: false,
type: Sequelize.BOOLEAN
defaultValue: 0
createdAt:
allowNull: false
type: Sequelize.DATE
updatedAt:
allowNull: false
type: Sequelize.DATE | 149140 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date Mar 2021
###
{ DataTypes, Model } = require 'sequelize'
{ sequelize } = require '../../database'
###
Order model
###
class Order extends Model
# initialize model
Order.init
user:
allowNull: false
type: Sequelize.INTEGER
pharmacy:
allowNull: false,
type: Sequelize.INTEGER
status:
allowNull: false,
type: Sequelize.BOOLEAN
defaultValue: 0
createdAt:
allowNull: false
type: Sequelize.DATE
updatedAt:
allowNull: false
type: Sequelize.DATE | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date Mar 2021
###
{ DataTypes, Model } = require 'sequelize'
{ sequelize } = require '../../database'
###
Order model
###
class Order extends Model
# initialize model
Order.init
user:
allowNull: false
type: Sequelize.INTEGER
pharmacy:
allowNull: false,
type: Sequelize.INTEGER
status:
allowNull: false,
type: Sequelize.BOOLEAN
defaultValue: 0
createdAt:
allowNull: false
type: Sequelize.DATE
updatedAt:
allowNull: false
type: Sequelize.DATE |
[
{
"context": " (email, password) ->\n {email: email, password: password}\n\n _userChanged: ->\n if @user\n @email = ",
"end": 965,
"score": 0.9988742470741272,
"start": 957,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " password) ->\n {\"id\": userId, \"user[password]\": password, \"user[password_confirmation]\": password}\n\n _pas",
"end": 1697,
"score": 0.9556840658187866,
"start": 1689,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ssword]\": password, \"user[password_confirmation]\": password}\n\n _passwordChangeSucceeded: ->\n @$.passwordD",
"end": 1738,
"score": 0.9545297026634216,
"start": 1730,
"tag": "PASSWORD",
"value": "password"
}
] | app/elements/caretaker-session-manager/caretaker-session-manager.coffee | grappendorf/caretaker-webapp | 0 | Polymer
is: 'caretaker-session-manager'
behaviors: [Grapp.I18NJsBehavior]
properties:
apiUrl: {type: String }
user: {type: Object, value: {email: '', roles: [], isAdmin: false}, notify: true, observer: '_userChanged'}
token: {type: String, value: null, notify: true}
connect: ->
@$.loginDialog.show()
disconnect: ->
@logout()
reconnect: ->
@disconnect()
@connect()
login: ->
@$.loginDialog.processing = true
@$.signInRequest.generateRequest()
logout: ->
@token = null
@user =
email: @user.email
roles: []
isAdmin: false
editProfile: ->
@$.profileDialog.show().then =>
@$.profileDialog.processing = true
editPassword: ->
@$.passwordDialog.show().then =>
@$.passwordDialog.processing = true
@$.changePasswordRequest.generateRequest()
_tokenLoaded: ->
@fire 'loaded'
_signInParams: (email, password) ->
{email: email, password: password}
_userChanged: ->
if @user
@email = @user.email
@set 'user.isAdmin', @_userHasRole 'admin'
_userHasRole: (role) ->
role in @user.roles
_loginSucceeded: (e) ->
@$.loginDialog.processing = false
@$.loginDialog.hide()
@password = ''
e.detail.response.user.isAdmin = 'admin' in e.detail.response.user.roles
@user = e.detail.response.user
@token = e.detail.response.token
_loginFailed: (e) ->
@$.loginDialog.processing = false
@$.loginDialog.error = @i18n('message.error_wrong_password_or_user_name')
@password = ''
_changePasswordPath: (userId) ->
"/users/#{userId}"
_changePasswordParams: (userId, password) ->
{"id": userId, "user[password]": password, "user[password_confirmation]": password}
_passwordChangeSucceeded: ->
@$.passwordDialog.processing = false
@$.passwordDialog.hide()
_passwordChangeFailed: (e) ->
@$.passwordDialog.processing = false
@$.passwordDialog.error = e.detail.response.message
| 31187 | Polymer
is: 'caretaker-session-manager'
behaviors: [Grapp.I18NJsBehavior]
properties:
apiUrl: {type: String }
user: {type: Object, value: {email: '', roles: [], isAdmin: false}, notify: true, observer: '_userChanged'}
token: {type: String, value: null, notify: true}
connect: ->
@$.loginDialog.show()
disconnect: ->
@logout()
reconnect: ->
@disconnect()
@connect()
login: ->
@$.loginDialog.processing = true
@$.signInRequest.generateRequest()
logout: ->
@token = null
@user =
email: @user.email
roles: []
isAdmin: false
editProfile: ->
@$.profileDialog.show().then =>
@$.profileDialog.processing = true
editPassword: ->
@$.passwordDialog.show().then =>
@$.passwordDialog.processing = true
@$.changePasswordRequest.generateRequest()
_tokenLoaded: ->
@fire 'loaded'
_signInParams: (email, password) ->
{email: email, password: <PASSWORD>}
_userChanged: ->
if @user
@email = @user.email
@set 'user.isAdmin', @_userHasRole 'admin'
_userHasRole: (role) ->
role in @user.roles
_loginSucceeded: (e) ->
@$.loginDialog.processing = false
@$.loginDialog.hide()
@password = ''
e.detail.response.user.isAdmin = 'admin' in e.detail.response.user.roles
@user = e.detail.response.user
@token = e.detail.response.token
_loginFailed: (e) ->
@$.loginDialog.processing = false
@$.loginDialog.error = @i18n('message.error_wrong_password_or_user_name')
@password = ''
_changePasswordPath: (userId) ->
"/users/#{userId}"
_changePasswordParams: (userId, password) ->
{"id": userId, "user[password]": <PASSWORD>, "user[password_confirmation]": <PASSWORD>}
_passwordChangeSucceeded: ->
@$.passwordDialog.processing = false
@$.passwordDialog.hide()
_passwordChangeFailed: (e) ->
@$.passwordDialog.processing = false
@$.passwordDialog.error = e.detail.response.message
| true | Polymer
is: 'caretaker-session-manager'
behaviors: [Grapp.I18NJsBehavior]
properties:
apiUrl: {type: String }
user: {type: Object, value: {email: '', roles: [], isAdmin: false}, notify: true, observer: '_userChanged'}
token: {type: String, value: null, notify: true}
connect: ->
@$.loginDialog.show()
disconnect: ->
@logout()
reconnect: ->
@disconnect()
@connect()
login: ->
@$.loginDialog.processing = true
@$.signInRequest.generateRequest()
logout: ->
@token = null
@user =
email: @user.email
roles: []
isAdmin: false
editProfile: ->
@$.profileDialog.show().then =>
@$.profileDialog.processing = true
editPassword: ->
@$.passwordDialog.show().then =>
@$.passwordDialog.processing = true
@$.changePasswordRequest.generateRequest()
_tokenLoaded: ->
@fire 'loaded'
_signInParams: (email, password) ->
{email: email, password: PI:PASSWORD:<PASSWORD>END_PI}
_userChanged: ->
if @user
@email = @user.email
@set 'user.isAdmin', @_userHasRole 'admin'
_userHasRole: (role) ->
role in @user.roles
_loginSucceeded: (e) ->
@$.loginDialog.processing = false
@$.loginDialog.hide()
@password = ''
e.detail.response.user.isAdmin = 'admin' in e.detail.response.user.roles
@user = e.detail.response.user
@token = e.detail.response.token
_loginFailed: (e) ->
@$.loginDialog.processing = false
@$.loginDialog.error = @i18n('message.error_wrong_password_or_user_name')
@password = ''
_changePasswordPath: (userId) ->
"/users/#{userId}"
_changePasswordParams: (userId, password) ->
{"id": userId, "user[password]": PI:PASSWORD:<PASSWORD>END_PI, "user[password_confirmation]": PI:PASSWORD:<PASSWORD>END_PI}
_passwordChangeSucceeded: ->
@$.passwordDialog.processing = false
@$.passwordDialog.hide()
_passwordChangeFailed: (e) ->
@$.passwordDialog.processing = false
@$.passwordDialog.error = e.detail.response.message
|
[
{
"context": "\n\n renderFullName: (account, query) ->\n\n { firstName, lastName, nickname } = account.profile\n ret",
"end": 1237,
"score": 0.9741612672805786,
"start": 1228,
"tag": "NAME",
"value": "firstName"
},
{
"context": "rFullName: (account, query) ->\n\n { firstName, lastName, nickname } = account.profile\n return unles",
"end": 1247,
"score": 0.9721895456314087,
"start": 1239,
"tag": "NAME",
"value": "lastName"
},
{
"context": " shouldHighlight = findNameByQuery([ nickname, firstName, lastName ], query) isnt nickname\n\n <span cl",
"end": 1761,
"score": 0.8849071860313416,
"start": 1752,
"tag": "NAME",
"value": "firstName"
},
{
"context": "Highlight = findNameByQuery([ nickname, firstName, lastName ], query) isnt nickname\n\n <span className={f",
"end": 1771,
"score": 0.7514247298240662,
"start": 1763,
"tag": "NAME",
"value": "lastName"
},
{
"context": "ameClass}>\n { helper.renderFullNameItem \"#{firstName} \", shouldHighlight, query }\n { helper.ren",
"end": 1884,
"score": 0.582496702671051,
"start": 1875,
"tag": "NAME",
"value": "firstName"
}
] | client/activity/lib/components/chatinputwidget/mentiondropbox/useritem.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
React = require 'kd-react'
immutable = require 'immutable'
classnames = require 'classnames'
DropboxItem = require 'activity/components/dropboxitem'
Avatar = require 'app/components/profile/avatar'
highlightQueryInWord = require 'activity/util/highlightQueryInWord'
findNameByQuery = require 'activity/util/findNameByQuery'
module.exports = class UserMentionItem extends React.Component
@defaultProps =
item : immutable.Map()
isSelected : no
index : 0
query : ''
render: ->
{ item, query } = @props
account = item.toJS()
className = 'DropboxItem-singleLine DropboxItem-separated MentionDropboxItem UserMentionItem'
<DropboxItem {...@props} className={className}>
<Avatar width='25' height='25' account={account} />
<div className='MentionDropboxItem-names'>
<span className='UserMentionItem-nickname'>
{ account.profile.nickname }
</span>
{ helper.renderFullName account, query }
</div>
<div className='clearfix' />
</DropboxItem>
helper =
renderFullName: (account, query) ->
{ firstName, lastName, nickname } = account.profile
return unless firstName and lastName
fullNameClass = classnames
'MentionDropboxItem-secondaryText' : yes
'UserMentionItem-fullName' : yes
# Do not highlight query in any name, if it's found in nickname.
# Highlighting in first and last name is intended to show
# why mention is selected via search when it's found not by nickname
# but by first or last names
shouldHighlight = findNameByQuery([ nickname, firstName, lastName ], query) isnt nickname
<span className={fullNameClass}>
{ helper.renderFullNameItem "#{firstName} ", shouldHighlight, query }
{ helper.renderFullNameItem lastName, shouldHighlight, query }
</span>
renderFullNameItem: (text, shouldHighlight, query) ->
if shouldHighlight
then highlightQueryInWord text, query
else text
| 100601 | kd = require 'kd'
React = require 'kd-react'
immutable = require 'immutable'
classnames = require 'classnames'
DropboxItem = require 'activity/components/dropboxitem'
Avatar = require 'app/components/profile/avatar'
highlightQueryInWord = require 'activity/util/highlightQueryInWord'
findNameByQuery = require 'activity/util/findNameByQuery'
module.exports = class UserMentionItem extends React.Component
@defaultProps =
item : immutable.Map()
isSelected : no
index : 0
query : ''
render: ->
{ item, query } = @props
account = item.toJS()
className = 'DropboxItem-singleLine DropboxItem-separated MentionDropboxItem UserMentionItem'
<DropboxItem {...@props} className={className}>
<Avatar width='25' height='25' account={account} />
<div className='MentionDropboxItem-names'>
<span className='UserMentionItem-nickname'>
{ account.profile.nickname }
</span>
{ helper.renderFullName account, query }
</div>
<div className='clearfix' />
</DropboxItem>
helper =
renderFullName: (account, query) ->
{ <NAME>, <NAME>, nickname } = account.profile
return unless firstName and lastName
fullNameClass = classnames
'MentionDropboxItem-secondaryText' : yes
'UserMentionItem-fullName' : yes
# Do not highlight query in any name, if it's found in nickname.
# Highlighting in first and last name is intended to show
# why mention is selected via search when it's found not by nickname
# but by first or last names
shouldHighlight = findNameByQuery([ nickname, <NAME>, <NAME> ], query) isnt nickname
<span className={fullNameClass}>
{ helper.renderFullNameItem "#{<NAME>} ", shouldHighlight, query }
{ helper.renderFullNameItem lastName, shouldHighlight, query }
</span>
renderFullNameItem: (text, shouldHighlight, query) ->
if shouldHighlight
then highlightQueryInWord text, query
else text
| true | kd = require 'kd'
React = require 'kd-react'
immutable = require 'immutable'
classnames = require 'classnames'
DropboxItem = require 'activity/components/dropboxitem'
Avatar = require 'app/components/profile/avatar'
highlightQueryInWord = require 'activity/util/highlightQueryInWord'
findNameByQuery = require 'activity/util/findNameByQuery'
module.exports = class UserMentionItem extends React.Component
@defaultProps =
item : immutable.Map()
isSelected : no
index : 0
query : ''
render: ->
{ item, query } = @props
account = item.toJS()
className = 'DropboxItem-singleLine DropboxItem-separated MentionDropboxItem UserMentionItem'
<DropboxItem {...@props} className={className}>
<Avatar width='25' height='25' account={account} />
<div className='MentionDropboxItem-names'>
<span className='UserMentionItem-nickname'>
{ account.profile.nickname }
</span>
{ helper.renderFullName account, query }
</div>
<div className='clearfix' />
</DropboxItem>
helper =
renderFullName: (account, query) ->
{ PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, nickname } = account.profile
return unless firstName and lastName
fullNameClass = classnames
'MentionDropboxItem-secondaryText' : yes
'UserMentionItem-fullName' : yes
# Do not highlight query in any name, if it's found in nickname.
# Highlighting in first and last name is intended to show
# why mention is selected via search when it's found not by nickname
# but by first or last names
shouldHighlight = findNameByQuery([ nickname, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ], query) isnt nickname
<span className={fullNameClass}>
{ helper.renderFullNameItem "#{PI:NAME:<NAME>END_PI} ", shouldHighlight, query }
{ helper.renderFullNameItem lastName, shouldHighlight, query }
</span>
renderFullNameItem: (text, shouldHighlight, query) ->
if shouldHighlight
then highlightQueryInWord text, query
else text
|
[
{
"context": "').success (data) ->\n\t\tscope.series = [\n\t\t\tname: \"Apple\"\n\t\t\tdata: data\n\t\t]\n\t\tscope.chartReady = yes\n\n]",
"end": 977,
"score": 0.970344066619873,
"start": 972,
"tag": "NAME",
"value": "Apple"
}
] | test/scripts/test.coffee | TheHippo/angular-highcharts | 1 | app = angular.module 'test-angular-highcharts', ['angular-highcharts']
app.config ['HighchartsGlobalConfigProvider', (highchartsGlobalConfigProvider) ->
highchartsGlobalConfigProvider.setGlobal
useUTC: yes
highchartsGlobalConfigProvider.setLang
decimalPoint: ','
]
app.controller 'Chart1', ['$scope', '$http', (scope, http) ->
console.log "Chart1"
scope.type = "bar"
scope.title = "Charttitle"
scope.chartReady = no
http.get('data.json').success (data) ->
scope.series = data
scope.chartReady = yes
scope.xconfig =
categories: ['Apples', 'Bananas', 'Oranges']
]
app.controller 'Chart2', ['$scope', (scope) ->
console.log "Chart2"
scope.chartData = [['Section 1',1],['Section 2', 2],['Large Section', 4]]
]
app.controller 'Chart3', ['$http', '$scope', (http, scope) ->
scope.chartReady = no
http.jsonp('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSON_CALLBACK').success (data) ->
scope.series = [
name: "Apple"
data: data
]
scope.chartReady = yes
] | 93389 | app = angular.module 'test-angular-highcharts', ['angular-highcharts']
app.config ['HighchartsGlobalConfigProvider', (highchartsGlobalConfigProvider) ->
highchartsGlobalConfigProvider.setGlobal
useUTC: yes
highchartsGlobalConfigProvider.setLang
decimalPoint: ','
]
app.controller 'Chart1', ['$scope', '$http', (scope, http) ->
console.log "Chart1"
scope.type = "bar"
scope.title = "Charttitle"
scope.chartReady = no
http.get('data.json').success (data) ->
scope.series = data
scope.chartReady = yes
scope.xconfig =
categories: ['Apples', 'Bananas', 'Oranges']
]
app.controller 'Chart2', ['$scope', (scope) ->
console.log "Chart2"
scope.chartData = [['Section 1',1],['Section 2', 2],['Large Section', 4]]
]
app.controller 'Chart3', ['$http', '$scope', (http, scope) ->
scope.chartReady = no
http.jsonp('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSON_CALLBACK').success (data) ->
scope.series = [
name: "<NAME>"
data: data
]
scope.chartReady = yes
] | true | app = angular.module 'test-angular-highcharts', ['angular-highcharts']
app.config ['HighchartsGlobalConfigProvider', (highchartsGlobalConfigProvider) ->
highchartsGlobalConfigProvider.setGlobal
useUTC: yes
highchartsGlobalConfigProvider.setLang
decimalPoint: ','
]
app.controller 'Chart1', ['$scope', '$http', (scope, http) ->
console.log "Chart1"
scope.type = "bar"
scope.title = "Charttitle"
scope.chartReady = no
http.get('data.json').success (data) ->
scope.series = data
scope.chartReady = yes
scope.xconfig =
categories: ['Apples', 'Bananas', 'Oranges']
]
app.controller 'Chart2', ['$scope', (scope) ->
console.log "Chart2"
scope.chartData = [['Section 1',1],['Section 2', 2],['Large Section', 4]]
]
app.controller 'Chart3', ['$http', '$scope', (http, scope) ->
scope.chartReady = no
http.jsonp('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSON_CALLBACK').success (data) ->
scope.series = [
name: "PI:NAME:<NAME>END_PI"
data: data
]
scope.chartReady = yes
] |
[
{
"context": "ons)\n expect(@instance._data_key).to.equal('a_select_data')\n\n it 'creates @_timestamp_key', -",
"end": 2591,
"score": 0.6981313824653625,
"start": 2591,
"tag": "KEY",
"value": ""
},
{
"context": " expect(@instance._data_key).to.equal('a_select_data')\n\n it 'creates @_timestamp_key', ->\n @in",
"end": 2603,
"score": 0.643032968044281,
"start": 2599,
"tag": "KEY",
"value": "data"
},
{
"context": " expect(@instance._last_modified_key).to.equal('a_select_last_modified')\n\n it 'creates @_data', ->\n ",
"end": 2912,
"score": 0.6093288064002991,
"start": 2905,
"tag": "KEY",
"value": "select_"
},
{
"context": "stance._last_modified_key).to.equal('a_select_last_modified')\n\n it 'creates @_data', ->\n @ins",
"end": 2916,
"score": 0.5147212743759155,
"start": 2916,
"tag": "KEY",
"value": ""
},
{
"context": "JSON.parse(@shops_json).concat([{ id: 100, name: \"Ofarmakopoiosmou\" }]))\n\n # Last-Modified set to 1 hour ",
"end": 13166,
"score": 0.8671540021896362,
"start": 13150,
"tag": "NAME",
"value": "Ofarmakopoiosmou"
},
{
"context": "akers_data = [\n {\n 'id': 'asdasd0',\n 'name': 'asdasd0'\n ",
"end": 22597,
"score": 0.6353827118873596,
"start": 22595,
"tag": "NAME",
"value": "as"
},
{
"context": " 'id': 'asdasd0',\n 'name': 'asdasd0'\n },\n {\n 'id':",
"end": 22635,
"score": 0.928783118724823,
"start": 22628,
"tag": "NAME",
"value": "asdasd0"
},
{
"context": " 'id': 'asdasd3',\n 'name': 'asdasd3'\n },\n {\n 'id'",
"end": 22726,
"score": 0.6941449642181396,
"start": 22720,
"tag": "NAME",
"value": "asdasd"
},
{
"context": " 'id': 'asdasd4',\n 'name': 'asdasd4'\n },\n {\n ",
"end": 22814,
"score": 0.6962343454360962,
"start": 22812,
"tag": "NAME",
"value": "as"
},
{
"context": " 'id': 'asdasd5',\n 'name': 'asdasd5'\n },\n {\n ",
"end": 22906,
"score": 0.733893096446991,
"start": 22904,
"tag": "NAME",
"value": "as"
},
{
"context": " @clock.restore()\n @respondJSON(@makers_json)\n\n it 'updates @_data', (done)->\n ",
"end": 24590,
"score": 0.7475600242614746,
"start": 24586,
"tag": "USERNAME",
"value": "json"
},
{
"context": " @clock.restore()\n @respondJSON(@makers_json)\n\n it 'triggers \"dbsearch_results\" eve",
"end": 25009,
"score": 0.6066558361053467,
"start": 25009,
"tag": "USERNAME",
"value": ""
},
{
"context": "\n @clock.restore()\n @respondJSON(@makers_json)\n\n it 'triggers \"dbsearch_resul",
"end": 25438,
"score": 0.5897245407104492,
"start": 25438,
"tag": "USERNAME",
"value": ""
},
{
"context": " @clock.restore()\n @respondJSON(@makers_json)\n\n it 'triggers \"dbsearch_results\" eve",
"end": 25447,
"score": 0.6325579285621643,
"start": 25443,
"tag": "USERNAME",
"value": "ers_"
},
{
"context": "\n @clock.restore()\n @respondJSON(@makers_json)\n\n it 'triggers \"dbsearch_resul",
"end": 25846,
"score": 0.5897416472434998,
"start": 25846,
"tag": "USERNAME",
"value": ""
},
{
"context": " @clock.restore()\n @respondJSON(@makers_json)\n\n it 'triggers \"dbsearch_results\" event a",
"end": 25859,
"score": 0.6339359283447266,
"start": 25851,
"tag": "USERNAME",
"value": "ers_json"
},
{
"context": "\n @clock.restore()\n @respondJSON(@makers_json)\n\n it 'sorts results', (done)->\n ",
"end": 26254,
"score": 0.7377548217773438,
"start": 26242,
"tag": "USERNAME",
"value": "@makers_json"
},
{
"context": "\n @clock.restore()\n @respondJSON(@makers_json)\n\n it 'slices results', (done)->\n ",
"end": 26621,
"score": 0.7358301877975464,
"start": 26609,
"tag": "USERNAME",
"value": "@makers_json"
},
{
"context": "\n @clock.restore()\n @respondJSON(@makers_json)\n\n context 'when a new remote request starts b",
"end": 27033,
"score": 0.8229424357414246,
"start": 27021,
"tag": "USERNAME",
"value": "@makers_json"
}
] | spec/storagefreak_spec.coffee | skroutz/selectorablium | 7 | cleanup_tests = ->
it 'triggers "dbremote_search_reset" event', ->
spy = sinon.spy()
@instance.on 'dbremote_search_reset', spy
@instance.search(@query)
expect(spy).to.be.calledOnce
context 'when a timeout is pending', ->
it 'clears the timeout', ->
spy = sinon.spy(window, 'clearTimeout')
timeout_val = @instance.timeout
@instance.search(@query)
expect(spy.args[0][0]).to.equal(timeout_val)
spy.restore()
context 'when an XHR has already been triggered', ->
it 'aborts the XHR', ->
@clock.tick(@instance.config.XHRTimeout + 100)
spy = sinon.spy @instance.XHR_dfd, 'abort'
@instance.search(@query)
expect(spy).to.be.calledOnce
spy.restore()
describe 'StorageFreak', ->
@timeout(0)
before (done)->
@respondJSON = (json_data, headers)->
headers ||= {}
headers = $.extend { "Content-Type": "application/json" }, headers
@requests[0].respond 200, headers, json_data
[@shops_obj, @makers_obj] = fixture.load('shops.json', 'makers.json')
@makers_json = JSON.stringify @makers_obj
@shops_json = JSON.stringify @shops_obj
@init_options =
url : 'dummy_url'
name : 'a_select'
query : 'get_param_key'
app_name : 'test'
maxResultsNum: 5
XHRTimeout : 650
localCacheTimeout : 6000
minCharsForRemoteSearch : 5
list_of_replacable_chars : [
['ά', 'α'],
['έ', 'ε'],
['ή', 'η'],
['ί', 'ι'],
['ό', 'ο'],
['ύ', 'υ'],
['ώ', 'ω']
]
require [
'storage_freak'
'shims/local_storage_shim'
], (StorageFreak, LocalStorageShim)=>
@LocalStorageShim = LocalStorageShim
@StorageFreak = StorageFreak
done()
beforeEach ->
@requests = []
@xhr = sinon.useFakeXMLHttpRequest()
@xhr.onCreate = (xhr)=> @requests.push xhr
afterEach ->
@xhr.restore()
@instance and @instance.cleanup()
localStorage and localStorage.clear()
describe '.constructor', ->
it 'returns an instance when called without new', ->
@instance = @StorageFreak(@init_options)
expect(@instance).to.be.instanceof(@StorageFreak)
it 'throws if not all required options are given', ->
expect(@StorageFreak).to.throw(/option is required/)
it 'creates @_db_prefix', ->
@instance = @StorageFreak(@init_options)
expect(@instance._db_prefix).to.equal('selectorablium.test')
it 'creates @_data_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._data_key).to.equal('a_select_data')
it 'creates @_timestamp_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._timestamp_key).to.equal('a_select_timestamp')
it 'creates @_last_modified_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._last_modified_key).to.equal('a_select_last_modified')
it 'creates @_data', ->
@instance = @StorageFreak(@init_options)
expect(@instance._data).to.eql({})
it 'creates @_events', ->
@instance = @StorageFreak(@init_options)
expect(@instance._events).to.eql({})
it 'gets @_storage', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.be.empty
it 'binds config functions to instance', ->
jquery_proxy_spy = sinon.spy $, 'proxy'
a_config_function = -> ''
@instance = @StorageFreak($.extend @init_options, some_option: a_config_function)
expect(jquery_proxy_spy).to.be.calledWith a_config_function
jquery_proxy_spy.restore()
context 'when window.localStorage is available', ->
beforeEach ->
if !window.localStorage
@prev = window.localStorage
window.localStorage = null
afterEach ->
@prev and window.localStorage = @prev
it 'references @_storage to localStorage', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.equal(window.localStorage)
xcontext 'when window.localStorage is not available', ->
beforeEach ->
## DOES NOT WORK
@prev = window.localStorage
window.localStorage = null
afterEach ->
window.localStorage = @prev
it 'references @_storage to localStorageShim', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.be.instanceof(@LocalStorageShim)
describe 'on', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@event_name = 'event_name'
@func = ->
it 'registers data', ->
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: null
it 'registers third argument as context', ->
test_obj = {koko:'lala'}
@instance.on @event_name, @func, test_obj
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: test_obj
it 'defaults context to null', ->
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: null
it 'registers multiple calls with the same event_name', ->
@instance.on @event_name, @func
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.to.have.length(2)
describe 'init', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
context 'when storage has no data', ->
beforeEach ->
@instance._storage.clear()
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.equal(false)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.equal(false)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@respondJSON(@shops_json)
# Ensure that XHR callbacks (which resolve @result) have finished
# so that expectations have been fullfilled
@result.then -> done()
it 'adds data to storage', ->
expect(@instance._get(@instance._data_key))
.to.not.equal(false)
it 'adds data_timestamp to storage', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.equal(false)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when storage has data that have expired', ->
beforeEach ->
@timestamp = new Date().getTime()
@timestamp = @timestamp - (2 * @instance.config.localCacheTimeout)
@instance._set @instance._data_key, @makers_obj
@old_data = @instance._get @instance._data_key
@instance._set @instance._timestamp_key, @timestamp
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.eql(@old_data)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@respondJSON(@shops_json)
# Ensure that XHR callbacks (which resolve @result) have finished
# so that expectations have been fullfilled
@result.then -> done()
it 'adds old data in storage with new', ->
expect(@instance._get(@instance._data_key))
.to.not.eql(@old_data)
it 'replaces old data_timestamp in storage with new', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.eql(@timestamp)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when storage has data', ->
beforeEach ->
@instance._updateDB(@shops_obj)
@ret = @instance.init()
it 'returns a Deferred object', ->
expect(@ret).to.respondTo('then')
it 'does not make an XHR', ->
expect(@requests).to.have.length(0)
it 'retrieves data from storage', ->
expect(@instance._data).eql(@shops_obj)
it 'resolves returned deferred', (done)->
@ret.then ->
expect(true).to.be.true
done()
context 'when storage has data and @config.cache_revalidate option is enabled', ->
beforeEach ->
@instance = @StorageFreak($.extend {}, @init_options, { cache_revalidate: true })
@timestamp = new Date().getTime()
@instance._updateDB(@shops_obj)
@instance._set @instance._timestamp_key, @timestamp
@old_data = @instance._get @instance._data_key
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'when storage has a last_modified timestamp', ->
beforeEach ->
@instance._set @instance._last_modified_key, @timestamp
it 'includes the If-Modified-Since header to the GET JSON XHR', ->
@instance.init()
expect(@requests[0].requestHeaders['If-Modified-Since'])
.to.equal(new Date(@timestamp).toUTCString())
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.eql(@shops_obj)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
context 'when remote responds with data', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@shops_updated_json = JSON.stringify(
JSON.parse(@shops_json).concat([{ id: 100, name: "Ofarmakopoiosmou" }]))
# Last-Modified set to 1 hour later than local timestamp
# Milliseconds are deliberately set to 0 as httpdates do not contain them
last_modified_date = new Date(@timestamp + 60 * 60 * 1000)
last_modified_date.setMilliseconds(0)
@last_modified = last_modified_date.getTime()
@respondJSON(@shops_updated_json,
{ 'Last-Modified': new Date(@last_modified).toUTCString() })
@result.then -> done()
it 'adds old data in storage with new', ->
expect(@instance._get(@instance._data_key))
.to.not.eql(@old_data)
it 'includes updated data in storage', ->
expect(@instance._get(@instance._data_key))
.to.include({ Ofarmakopoiosmou: 100 })
it 'replaces old data_timestamp in storage with new', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.eql(@timestamp)
it 'updates last_modified timestamp in storage', ->
expect(@instance._get(@instance._last_modified_key))
.to.eql(@last_modified)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when remote responds with Not Modified', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@requests[0].respond 304
@result.then -> done()
it 'retrieves data from storage', ->
expect(@instance._data).to.eql(@shops_obj)
it 'does not update data timestamp in storage', ->
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
describe 'add', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
obj =
koko: 'lala'
koko2: 'lala2'
@instance._data = obj
@instance._updateDB obj
@data = @instance._get @instance._data_key
@timestamp = @instance._get @instance._timestamp_key
it 'expects key as first argument and value as second', ->
@instance.add('koko', 'lala')
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'appends data to localStorage', ->
@instance.add('koko', 'lala')
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'appends data to @_data', ->
@instance.add('koko', 'lala')
expect(@instance._data).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'triggers "dbupdated" event', (done)->
@instance.on 'dbupdated', ->
expect(true).to.be.true
done()
@instance.add('koko', 'lala')
context 'when key exists', ->
beforeEach ->
@instance.add('different_value', 'koko')
it 'does not update key with new value in localStorage', ->
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
it 'does not update key with new value in @instance._data', ->
expect(@instance._data).to.eql
koko: 'lala'
koko2: 'lala2'
describe 'searchByValue', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@instance._data = {
koko: 'lala'
}
it 'returns value for searched value', ->
expect(@instance.searchByValue('lala')).to.equal('koko')
it 'returns false if nothing is found', ->
expect(@instance.searchByValue('koko')).to.equal(false)
it 'does not make an XHR', ->
expect(@requests).to.have.length(0)
describe 'search', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
it 'does not search storage', ->
spy = sinon.spy @instance._storage, 'getItem'
@instance.search('as')
expect(spy).to.not.be.called
it 'matches only infix data by default', (done)->
@instance._data = {
addasjjjj: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(3)
done()
@instance.search("as")
context 'with search_type option set to prefix', ->
beforeEach ->
@init_options.search_type = 'prefix'
@instance = @StorageFreak(@init_options)
it 'matches prefix', (done)->
@instance._data = {
addas: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'searches in-memory data', (done)->
@instance._data = {
add: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'matches accented characters ignoring their accent', (done)->
@instance._data = {
λολο: 'as'
λόλο: 'asd'
λαλα: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('λολο')
it 'matches special regex characters', (done)->
@instance._data = {
'pc++': 'special'
}
@instance.on 'dbsearch_results', (data)->
expect(data).to.deep.equal [
{ id: 'special', name: 'pc++' }
]
done()
@instance.search('pc++')
it 'triggers "dbsearch_results" event and passes results', (done)->
@instance._data = {
as: 'as'
asd: 'asd'
add: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'also passes original query as second argument to the event callback', (done)->
@instance._data = {
as: 'as'
asd: 'asd'
add: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(query).to.equal('as')
done()
@instance.search('as')
it 'sorts results by absolute matches, token matches, prefix matches', (done)->
@instance._data =
skyram: 'k1'
abraram: 'k2'
'mr ram': 'k3'
babaoram: 'k4'
rambo: 'k5'
'ram mania': 'k6'
ram: 'k7'
@instance.config.maxResultsNum = 7
@instance.on 'dbsearch_results', (data)->
expect(data).to.deep.equal [
{ id: 'k7', name: 'ram' },
{ id: 'k6', name: 'ram mania' },
{ id: 'k3', name: 'mr ram' }
{ id: 'k5', name: 'rambo' }
{ id: 'k2', name: 'abraram' }
{ id: 'k4', name: 'babaoram' }
{ id: 'k1', name: 'skyram' }
]
done()
@instance.search('ram')
it 'slices results', (done)->
@instance._data =
asd: 'asd'
add: 'add'
as: 'as'
asd1: 'asd1'
add1: 'add1'
as1: 'as1'
asd2: 'asd2'
add2: 'add2'
as3: 'as2'
@instance.on 'dbsearch_results', (data)=>
expect(data).to.have.length @instance.config.maxResultsNum
done()
@instance.search('as')
it 'triggers "dbremote_search_reset" event', (done)->
@instance.on 'dbremote_search_reset', ->
expect(true).to.be.true
done()
@instance.search('as')
context 'when query is smaller than @config.minCharsForRemoteSearch', ->
it 'does not make an XHR', ->
@instance.search('asdasd')
expect(@requests).to.have.length(0)
context 'when query is bigger or equal to @config.minCharsForRemoteSearch', ->
beforeEach ->
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
afterEach ->
@clock.restore()
it 'registers XHR to occur after timeout', ->
spy = sinon.spy(window, 'setTimeout')
@instance.search(@query)
expect(spy.args[0][1]).to.equal(@instance.config.XHRTimeout)
spy.restore()
context 'before timeout', ->
it 'triggers "dbremote_search_in" event and passes @config.XHRTimeout', (done)->
@instance.on 'dbremote_search_in', (timeout)=>
expect(timeout).to.equal(@instance.config.XHRTimeout)
done()
@instance.search(@query)
context 'after timeout', ->
eventually = (done, expectation) ->
try
expectation()
done()
catch e
done(e)
beforeEach ->
@expected_makers_data = [
{
'id': 'asdasd0',
'name': 'asdasd0'
},
{
'id': 'asdasd3',
'name': 'asdasd3'
},
{
'id': 'asdasd4',
'name': 'asdasd4'
},
{
'id': 'asdasd5',
'name': 'asdasd5'
},
{
'id': 'asdasd6',
'name': 'asdasd6'
}
]
it 'makes an XHR', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(@requests).to.have.length(1)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@shops_json)
context 'when storage has a last_modified timestamp', ->
beforeEach ->
last_modified = new Date().getTime() - 60 * 60 * 1000 # 1 hour before
@instance._set @instance._last_modified_key, last_modified
it 'does not add If-Modified-Since header', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(@requests[0].requestHeaders).to.not.have.property('If-Modified-Since')
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@shops_json)
it 'updates storage', (done)->
@instance._set @instance._data_key, @makers_obj
old_data = @instance._get @instance._data_key
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(@instance._get(@instance._data_key)).to.not.eql(old_data)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'updates @_data', (done)->
data = {koko:'lala'}
@instance._data = data
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(@instance._data).to.not.eql(data)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes results from updated data as first arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(results).to.deep.eql @expected_makers_data
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes original query as second arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(query).to.equal(@query)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes "xhr" as third arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(xhr).to.equal('xhr')
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'sorts results', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(results).to.deep.eql @expected_makers_data
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'slices results', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(results).to.be.an('array').with.length(@instance.config.maxResultsNum)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
context 'when a new remote request starts before the previous finishes', ->
beforeEach ->
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
@instance.search(@query)
afterEach ->
@clock.restore()
cleanup_tests()
describe 'cleanup', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
@instance.search(@query)
afterEach ->
@clock.restore()
cleanup_tests()
| 218358 | cleanup_tests = ->
it 'triggers "dbremote_search_reset" event', ->
spy = sinon.spy()
@instance.on 'dbremote_search_reset', spy
@instance.search(@query)
expect(spy).to.be.calledOnce
context 'when a timeout is pending', ->
it 'clears the timeout', ->
spy = sinon.spy(window, 'clearTimeout')
timeout_val = @instance.timeout
@instance.search(@query)
expect(spy.args[0][0]).to.equal(timeout_val)
spy.restore()
context 'when an XHR has already been triggered', ->
it 'aborts the XHR', ->
@clock.tick(@instance.config.XHRTimeout + 100)
spy = sinon.spy @instance.XHR_dfd, 'abort'
@instance.search(@query)
expect(spy).to.be.calledOnce
spy.restore()
describe 'StorageFreak', ->
@timeout(0)
before (done)->
@respondJSON = (json_data, headers)->
headers ||= {}
headers = $.extend { "Content-Type": "application/json" }, headers
@requests[0].respond 200, headers, json_data
[@shops_obj, @makers_obj] = fixture.load('shops.json', 'makers.json')
@makers_json = JSON.stringify @makers_obj
@shops_json = JSON.stringify @shops_obj
@init_options =
url : 'dummy_url'
name : 'a_select'
query : 'get_param_key'
app_name : 'test'
maxResultsNum: 5
XHRTimeout : 650
localCacheTimeout : 6000
minCharsForRemoteSearch : 5
list_of_replacable_chars : [
['ά', 'α'],
['έ', 'ε'],
['ή', 'η'],
['ί', 'ι'],
['ό', 'ο'],
['ύ', 'υ'],
['ώ', 'ω']
]
require [
'storage_freak'
'shims/local_storage_shim'
], (StorageFreak, LocalStorageShim)=>
@LocalStorageShim = LocalStorageShim
@StorageFreak = StorageFreak
done()
beforeEach ->
@requests = []
@xhr = sinon.useFakeXMLHttpRequest()
@xhr.onCreate = (xhr)=> @requests.push xhr
afterEach ->
@xhr.restore()
@instance and @instance.cleanup()
localStorage and localStorage.clear()
describe '.constructor', ->
it 'returns an instance when called without new', ->
@instance = @StorageFreak(@init_options)
expect(@instance).to.be.instanceof(@StorageFreak)
it 'throws if not all required options are given', ->
expect(@StorageFreak).to.throw(/option is required/)
it 'creates @_db_prefix', ->
@instance = @StorageFreak(@init_options)
expect(@instance._db_prefix).to.equal('selectorablium.test')
it 'creates @_data_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._data_key).to.equal('a<KEY>_select_<KEY>')
it 'creates @_timestamp_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._timestamp_key).to.equal('a_select_timestamp')
it 'creates @_last_modified_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._last_modified_key).to.equal('a_<KEY>last<KEY>_modified')
it 'creates @_data', ->
@instance = @StorageFreak(@init_options)
expect(@instance._data).to.eql({})
it 'creates @_events', ->
@instance = @StorageFreak(@init_options)
expect(@instance._events).to.eql({})
it 'gets @_storage', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.be.empty
it 'binds config functions to instance', ->
jquery_proxy_spy = sinon.spy $, 'proxy'
a_config_function = -> ''
@instance = @StorageFreak($.extend @init_options, some_option: a_config_function)
expect(jquery_proxy_spy).to.be.calledWith a_config_function
jquery_proxy_spy.restore()
context 'when window.localStorage is available', ->
beforeEach ->
if !window.localStorage
@prev = window.localStorage
window.localStorage = null
afterEach ->
@prev and window.localStorage = @prev
it 'references @_storage to localStorage', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.equal(window.localStorage)
xcontext 'when window.localStorage is not available', ->
beforeEach ->
## DOES NOT WORK
@prev = window.localStorage
window.localStorage = null
afterEach ->
window.localStorage = @prev
it 'references @_storage to localStorageShim', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.be.instanceof(@LocalStorageShim)
describe 'on', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@event_name = 'event_name'
@func = ->
it 'registers data', ->
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: null
it 'registers third argument as context', ->
test_obj = {koko:'lala'}
@instance.on @event_name, @func, test_obj
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: test_obj
it 'defaults context to null', ->
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: null
it 'registers multiple calls with the same event_name', ->
@instance.on @event_name, @func
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.to.have.length(2)
describe 'init', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
context 'when storage has no data', ->
beforeEach ->
@instance._storage.clear()
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.equal(false)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.equal(false)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@respondJSON(@shops_json)
# Ensure that XHR callbacks (which resolve @result) have finished
# so that expectations have been fullfilled
@result.then -> done()
it 'adds data to storage', ->
expect(@instance._get(@instance._data_key))
.to.not.equal(false)
it 'adds data_timestamp to storage', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.equal(false)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when storage has data that have expired', ->
beforeEach ->
@timestamp = new Date().getTime()
@timestamp = @timestamp - (2 * @instance.config.localCacheTimeout)
@instance._set @instance._data_key, @makers_obj
@old_data = @instance._get @instance._data_key
@instance._set @instance._timestamp_key, @timestamp
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.eql(@old_data)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@respondJSON(@shops_json)
# Ensure that XHR callbacks (which resolve @result) have finished
# so that expectations have been fullfilled
@result.then -> done()
it 'adds old data in storage with new', ->
expect(@instance._get(@instance._data_key))
.to.not.eql(@old_data)
it 'replaces old data_timestamp in storage with new', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.eql(@timestamp)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when storage has data', ->
beforeEach ->
@instance._updateDB(@shops_obj)
@ret = @instance.init()
it 'returns a Deferred object', ->
expect(@ret).to.respondTo('then')
it 'does not make an XHR', ->
expect(@requests).to.have.length(0)
it 'retrieves data from storage', ->
expect(@instance._data).eql(@shops_obj)
it 'resolves returned deferred', (done)->
@ret.then ->
expect(true).to.be.true
done()
context 'when storage has data and @config.cache_revalidate option is enabled', ->
beforeEach ->
@instance = @StorageFreak($.extend {}, @init_options, { cache_revalidate: true })
@timestamp = new Date().getTime()
@instance._updateDB(@shops_obj)
@instance._set @instance._timestamp_key, @timestamp
@old_data = @instance._get @instance._data_key
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'when storage has a last_modified timestamp', ->
beforeEach ->
@instance._set @instance._last_modified_key, @timestamp
it 'includes the If-Modified-Since header to the GET JSON XHR', ->
@instance.init()
expect(@requests[0].requestHeaders['If-Modified-Since'])
.to.equal(new Date(@timestamp).toUTCString())
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.eql(@shops_obj)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
context 'when remote responds with data', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@shops_updated_json = JSON.stringify(
JSON.parse(@shops_json).concat([{ id: 100, name: "<NAME>" }]))
# Last-Modified set to 1 hour later than local timestamp
# Milliseconds are deliberately set to 0 as httpdates do not contain them
last_modified_date = new Date(@timestamp + 60 * 60 * 1000)
last_modified_date.setMilliseconds(0)
@last_modified = last_modified_date.getTime()
@respondJSON(@shops_updated_json,
{ 'Last-Modified': new Date(@last_modified).toUTCString() })
@result.then -> done()
it 'adds old data in storage with new', ->
expect(@instance._get(@instance._data_key))
.to.not.eql(@old_data)
it 'includes updated data in storage', ->
expect(@instance._get(@instance._data_key))
.to.include({ Ofarmakopoiosmou: 100 })
it 'replaces old data_timestamp in storage with new', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.eql(@timestamp)
it 'updates last_modified timestamp in storage', ->
expect(@instance._get(@instance._last_modified_key))
.to.eql(@last_modified)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when remote responds with Not Modified', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@requests[0].respond 304
@result.then -> done()
it 'retrieves data from storage', ->
expect(@instance._data).to.eql(@shops_obj)
it 'does not update data timestamp in storage', ->
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
describe 'add', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
obj =
koko: 'lala'
koko2: 'lala2'
@instance._data = obj
@instance._updateDB obj
@data = @instance._get @instance._data_key
@timestamp = @instance._get @instance._timestamp_key
it 'expects key as first argument and value as second', ->
@instance.add('koko', 'lala')
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'appends data to localStorage', ->
@instance.add('koko', 'lala')
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'appends data to @_data', ->
@instance.add('koko', 'lala')
expect(@instance._data).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'triggers "dbupdated" event', (done)->
@instance.on 'dbupdated', ->
expect(true).to.be.true
done()
@instance.add('koko', 'lala')
context 'when key exists', ->
beforeEach ->
@instance.add('different_value', 'koko')
it 'does not update key with new value in localStorage', ->
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
it 'does not update key with new value in @instance._data', ->
expect(@instance._data).to.eql
koko: 'lala'
koko2: 'lala2'
describe 'searchByValue', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@instance._data = {
koko: 'lala'
}
it 'returns value for searched value', ->
expect(@instance.searchByValue('lala')).to.equal('koko')
it 'returns false if nothing is found', ->
expect(@instance.searchByValue('koko')).to.equal(false)
it 'does not make an XHR', ->
expect(@requests).to.have.length(0)
describe 'search', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
it 'does not search storage', ->
spy = sinon.spy @instance._storage, 'getItem'
@instance.search('as')
expect(spy).to.not.be.called
it 'matches only infix data by default', (done)->
@instance._data = {
addasjjjj: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(3)
done()
@instance.search("as")
context 'with search_type option set to prefix', ->
beforeEach ->
@init_options.search_type = 'prefix'
@instance = @StorageFreak(@init_options)
it 'matches prefix', (done)->
@instance._data = {
addas: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'searches in-memory data', (done)->
@instance._data = {
add: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'matches accented characters ignoring their accent', (done)->
@instance._data = {
λολο: 'as'
λόλο: 'asd'
λαλα: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('λολο')
it 'matches special regex characters', (done)->
@instance._data = {
'pc++': 'special'
}
@instance.on 'dbsearch_results', (data)->
expect(data).to.deep.equal [
{ id: 'special', name: 'pc++' }
]
done()
@instance.search('pc++')
it 'triggers "dbsearch_results" event and passes results', (done)->
@instance._data = {
as: 'as'
asd: 'asd'
add: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'also passes original query as second argument to the event callback', (done)->
@instance._data = {
as: 'as'
asd: 'asd'
add: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(query).to.equal('as')
done()
@instance.search('as')
it 'sorts results by absolute matches, token matches, prefix matches', (done)->
@instance._data =
skyram: 'k1'
abraram: 'k2'
'mr ram': 'k3'
babaoram: 'k4'
rambo: 'k5'
'ram mania': 'k6'
ram: 'k7'
@instance.config.maxResultsNum = 7
@instance.on 'dbsearch_results', (data)->
expect(data).to.deep.equal [
{ id: 'k7', name: 'ram' },
{ id: 'k6', name: 'ram mania' },
{ id: 'k3', name: 'mr ram' }
{ id: 'k5', name: 'rambo' }
{ id: 'k2', name: 'abraram' }
{ id: 'k4', name: 'babaoram' }
{ id: 'k1', name: 'skyram' }
]
done()
@instance.search('ram')
it 'slices results', (done)->
@instance._data =
asd: 'asd'
add: 'add'
as: 'as'
asd1: 'asd1'
add1: 'add1'
as1: 'as1'
asd2: 'asd2'
add2: 'add2'
as3: 'as2'
@instance.on 'dbsearch_results', (data)=>
expect(data).to.have.length @instance.config.maxResultsNum
done()
@instance.search('as')
it 'triggers "dbremote_search_reset" event', (done)->
@instance.on 'dbremote_search_reset', ->
expect(true).to.be.true
done()
@instance.search('as')
context 'when query is smaller than @config.minCharsForRemoteSearch', ->
it 'does not make an XHR', ->
@instance.search('asdasd')
expect(@requests).to.have.length(0)
context 'when query is bigger or equal to @config.minCharsForRemoteSearch', ->
beforeEach ->
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
afterEach ->
@clock.restore()
it 'registers XHR to occur after timeout', ->
spy = sinon.spy(window, 'setTimeout')
@instance.search(@query)
expect(spy.args[0][1]).to.equal(@instance.config.XHRTimeout)
spy.restore()
context 'before timeout', ->
it 'triggers "dbremote_search_in" event and passes @config.XHRTimeout', (done)->
@instance.on 'dbremote_search_in', (timeout)=>
expect(timeout).to.equal(@instance.config.XHRTimeout)
done()
@instance.search(@query)
context 'after timeout', ->
eventually = (done, expectation) ->
try
expectation()
done()
catch e
done(e)
beforeEach ->
@expected_makers_data = [
{
'id': '<NAME>dasd0',
'name': '<NAME>'
},
{
'id': 'asdasd3',
'name': '<NAME>3'
},
{
'id': 'asdasd4',
'name': '<NAME>dasd4'
},
{
'id': 'asdasd5',
'name': '<NAME>dasd5'
},
{
'id': 'asdasd6',
'name': 'asdasd6'
}
]
it 'makes an XHR', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(@requests).to.have.length(1)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@shops_json)
context 'when storage has a last_modified timestamp', ->
beforeEach ->
last_modified = new Date().getTime() - 60 * 60 * 1000 # 1 hour before
@instance._set @instance._last_modified_key, last_modified
it 'does not add If-Modified-Since header', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(@requests[0].requestHeaders).to.not.have.property('If-Modified-Since')
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@shops_json)
it 'updates storage', (done)->
@instance._set @instance._data_key, @makers_obj
old_data = @instance._get @instance._data_key
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(@instance._get(@instance._data_key)).to.not.eql(old_data)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'updates @_data', (done)->
data = {koko:'lala'}
@instance._data = data
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(@instance._data).to.not.eql(data)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes results from updated data as first arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(results).to.deep.eql @expected_makers_data
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes original query as second arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(query).to.equal(@query)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes "xhr" as third arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(xhr).to.equal('xhr')
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'sorts results', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(results).to.deep.eql @expected_makers_data
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'slices results', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(results).to.be.an('array').with.length(@instance.config.maxResultsNum)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
context 'when a new remote request starts before the previous finishes', ->
beforeEach ->
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
@instance.search(@query)
afterEach ->
@clock.restore()
cleanup_tests()
describe 'cleanup', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
@instance.search(@query)
afterEach ->
@clock.restore()
cleanup_tests()
| true | cleanup_tests = ->
it 'triggers "dbremote_search_reset" event', ->
spy = sinon.spy()
@instance.on 'dbremote_search_reset', spy
@instance.search(@query)
expect(spy).to.be.calledOnce
context 'when a timeout is pending', ->
it 'clears the timeout', ->
spy = sinon.spy(window, 'clearTimeout')
timeout_val = @instance.timeout
@instance.search(@query)
expect(spy.args[0][0]).to.equal(timeout_val)
spy.restore()
context 'when an XHR has already been triggered', ->
it 'aborts the XHR', ->
@clock.tick(@instance.config.XHRTimeout + 100)
spy = sinon.spy @instance.XHR_dfd, 'abort'
@instance.search(@query)
expect(spy).to.be.calledOnce
spy.restore()
describe 'StorageFreak', ->
@timeout(0)
before (done)->
@respondJSON = (json_data, headers)->
headers ||= {}
headers = $.extend { "Content-Type": "application/json" }, headers
@requests[0].respond 200, headers, json_data
[@shops_obj, @makers_obj] = fixture.load('shops.json', 'makers.json')
@makers_json = JSON.stringify @makers_obj
@shops_json = JSON.stringify @shops_obj
@init_options =
url : 'dummy_url'
name : 'a_select'
query : 'get_param_key'
app_name : 'test'
maxResultsNum: 5
XHRTimeout : 650
localCacheTimeout : 6000
minCharsForRemoteSearch : 5
list_of_replacable_chars : [
['ά', 'α'],
['έ', 'ε'],
['ή', 'η'],
['ί', 'ι'],
['ό', 'ο'],
['ύ', 'υ'],
['ώ', 'ω']
]
require [
'storage_freak'
'shims/local_storage_shim'
], (StorageFreak, LocalStorageShim)=>
@LocalStorageShim = LocalStorageShim
@StorageFreak = StorageFreak
done()
beforeEach ->
@requests = []
@xhr = sinon.useFakeXMLHttpRequest()
@xhr.onCreate = (xhr)=> @requests.push xhr
afterEach ->
@xhr.restore()
@instance and @instance.cleanup()
localStorage and localStorage.clear()
describe '.constructor', ->
it 'returns an instance when called without new', ->
@instance = @StorageFreak(@init_options)
expect(@instance).to.be.instanceof(@StorageFreak)
it 'throws if not all required options are given', ->
expect(@StorageFreak).to.throw(/option is required/)
it 'creates @_db_prefix', ->
@instance = @StorageFreak(@init_options)
expect(@instance._db_prefix).to.equal('selectorablium.test')
it 'creates @_data_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._data_key).to.equal('aPI:KEY:<KEY>END_PI_select_PI:KEY:<KEY>END_PI')
it 'creates @_timestamp_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._timestamp_key).to.equal('a_select_timestamp')
it 'creates @_last_modified_key', ->
@instance = @StorageFreak(@init_options)
expect(@instance._last_modified_key).to.equal('a_PI:KEY:<KEY>END_PIlastPI:KEY:<KEY>END_PI_modified')
it 'creates @_data', ->
@instance = @StorageFreak(@init_options)
expect(@instance._data).to.eql({})
it 'creates @_events', ->
@instance = @StorageFreak(@init_options)
expect(@instance._events).to.eql({})
it 'gets @_storage', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.be.empty
it 'binds config functions to instance', ->
jquery_proxy_spy = sinon.spy $, 'proxy'
a_config_function = -> ''
@instance = @StorageFreak($.extend @init_options, some_option: a_config_function)
expect(jquery_proxy_spy).to.be.calledWith a_config_function
jquery_proxy_spy.restore()
context 'when window.localStorage is available', ->
beforeEach ->
if !window.localStorage
@prev = window.localStorage
window.localStorage = null
afterEach ->
@prev and window.localStorage = @prev
it 'references @_storage to localStorage', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.equal(window.localStorage)
xcontext 'when window.localStorage is not available', ->
beforeEach ->
## DOES NOT WORK
@prev = window.localStorage
window.localStorage = null
afterEach ->
window.localStorage = @prev
it 'references @_storage to localStorageShim', ->
@instance = @StorageFreak(@init_options)
expect(@instance._storage).to.be.instanceof(@LocalStorageShim)
describe 'on', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@event_name = 'event_name'
@func = ->
it 'registers data', ->
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: null
it 'registers third argument as context', ->
test_obj = {koko:'lala'}
@instance.on @event_name, @func, test_obj
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: test_obj
it 'defaults context to null', ->
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.with.deep.property('[0]')
.to.include
callback: @func
context: null
it 'registers multiple calls with the same event_name', ->
@instance.on @event_name, @func
@instance.on @event_name, @func
expect(@instance._events)
.to.have.property(@event_name)
.that.is.an('array')
.to.have.length(2)
describe 'init', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
context 'when storage has no data', ->
beforeEach ->
@instance._storage.clear()
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.equal(false)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.equal(false)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@respondJSON(@shops_json)
# Ensure that XHR callbacks (which resolve @result) have finished
# so that expectations have been fullfilled
@result.then -> done()
it 'adds data to storage', ->
expect(@instance._get(@instance._data_key))
.to.not.equal(false)
it 'adds data_timestamp to storage', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.equal(false)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when storage has data that have expired', ->
beforeEach ->
@timestamp = new Date().getTime()
@timestamp = @timestamp - (2 * @instance.config.localCacheTimeout)
@instance._set @instance._data_key, @makers_obj
@old_data = @instance._get @instance._data_key
@instance._set @instance._timestamp_key, @timestamp
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.eql(@old_data)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@respondJSON(@shops_json)
# Ensure that XHR callbacks (which resolve @result) have finished
# so that expectations have been fullfilled
@result.then -> done()
it 'adds old data in storage with new', ->
expect(@instance._get(@instance._data_key))
.to.not.eql(@old_data)
it 'replaces old data_timestamp in storage with new', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.eql(@timestamp)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when storage has data', ->
beforeEach ->
@instance._updateDB(@shops_obj)
@ret = @instance.init()
it 'returns a Deferred object', ->
expect(@ret).to.respondTo('then')
it 'does not make an XHR', ->
expect(@requests).to.have.length(0)
it 'retrieves data from storage', ->
expect(@instance._data).eql(@shops_obj)
it 'resolves returned deferred', (done)->
@ret.then ->
expect(true).to.be.true
done()
context 'when storage has data and @config.cache_revalidate option is enabled', ->
beforeEach ->
@instance = @StorageFreak($.extend {}, @init_options, { cache_revalidate: true })
@timestamp = new Date().getTime()
@instance._updateDB(@shops_obj)
@instance._set @instance._timestamp_key, @timestamp
@old_data = @instance._get @instance._data_key
it 'returns a Deferred object', ->
result = @instance.init()
expect(result).to.respondTo('then')
it 'makes a GET JSON XHR', ->
@instance.init()
expect(@requests).to.have.length(1)
context 'when storage has a last_modified timestamp', ->
beforeEach ->
@instance._set @instance._last_modified_key, @timestamp
it 'includes the If-Modified-Since header to the GET JSON XHR', ->
@instance.init()
expect(@requests[0].requestHeaders['If-Modified-Since'])
.to.equal(new Date(@timestamp).toUTCString())
context 'before the XHR resolves', ->
it 'triggers a "dbcreate_start" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_start', spy
@instance.init()
expect(spy).to.be.calledOnce
it 'does not add new data to storage', ->
@instance.init()
expect(@instance._get(@instance._data_key))
.to.eql(@shops_obj)
it 'does not add data_timestamp to storage', ->
@instance.init()
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'does not trigger a "dbcreate_end" event', ->
spy = sinon.spy()
@instance.on 'dbcreate_end', spy
@instance.init()
expect(spy).to.not.be.called
it 'does not resolve the returned deferred', ->
result = @instance.init()
expect(result.state()).to.equal('pending')
context 'after the XHR resolves', ->
context 'when remote responds with data', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@shops_updated_json = JSON.stringify(
JSON.parse(@shops_json).concat([{ id: 100, name: "PI:NAME:<NAME>END_PI" }]))
# Last-Modified set to 1 hour later than local timestamp
# Milliseconds are deliberately set to 0 as httpdates do not contain them
last_modified_date = new Date(@timestamp + 60 * 60 * 1000)
last_modified_date.setMilliseconds(0)
@last_modified = last_modified_date.getTime()
@respondJSON(@shops_updated_json,
{ 'Last-Modified': new Date(@last_modified).toUTCString() })
@result.then -> done()
it 'adds old data in storage with new', ->
expect(@instance._get(@instance._data_key))
.to.not.eql(@old_data)
it 'includes updated data in storage', ->
expect(@instance._get(@instance._data_key))
.to.include({ Ofarmakopoiosmou: 100 })
it 'replaces old data_timestamp in storage with new', ->
expect(@instance._get(@instance._timestamp_key))
.to.not.eql(@timestamp)
it 'updates last_modified timestamp in storage', ->
expect(@instance._get(@instance._last_modified_key))
.to.eql(@last_modified)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
context 'when remote responds with Not Modified', ->
beforeEach (done)->
@spy_end = sinon.spy()
@instance.on 'dbcreate_end', @spy_end
@result = @instance.init()
@requests[0].respond 304
@result.then -> done()
it 'retrieves data from storage', ->
expect(@instance._data).to.eql(@shops_obj)
it 'does not update data timestamp in storage', ->
expect(@instance._get(@instance._timestamp_key))
.to.eql(@timestamp)
it 'triggers a "dbcreate_end" event', ->
expect(@spy_end).to.be.calledOnce
it 'resolves the returned deferred', (done)->
@result.then ->
expect(true).to.be.true
done()
describe 'add', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
obj =
koko: 'lala'
koko2: 'lala2'
@instance._data = obj
@instance._updateDB obj
@data = @instance._get @instance._data_key
@timestamp = @instance._get @instance._timestamp_key
it 'expects key as first argument and value as second', ->
@instance.add('koko', 'lala')
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'appends data to localStorage', ->
@instance.add('koko', 'lala')
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'appends data to @_data', ->
@instance.add('koko', 'lala')
expect(@instance._data).to.eql
koko: 'lala'
koko2: 'lala2'
lala: 'koko'
it 'triggers "dbupdated" event', (done)->
@instance.on 'dbupdated', ->
expect(true).to.be.true
done()
@instance.add('koko', 'lala')
context 'when key exists', ->
beforeEach ->
@instance.add('different_value', 'koko')
it 'does not update key with new value in localStorage', ->
expect(@instance._get @instance._data_key).to.eql
koko: 'lala'
koko2: 'lala2'
it 'does not update key with new value in @instance._data', ->
expect(@instance._data).to.eql
koko: 'lala'
koko2: 'lala2'
describe 'searchByValue', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@instance._data = {
koko: 'lala'
}
it 'returns value for searched value', ->
expect(@instance.searchByValue('lala')).to.equal('koko')
it 'returns false if nothing is found', ->
expect(@instance.searchByValue('koko')).to.equal(false)
it 'does not make an XHR', ->
expect(@requests).to.have.length(0)
describe 'search', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
it 'does not search storage', ->
spy = sinon.spy @instance._storage, 'getItem'
@instance.search('as')
expect(spy).to.not.be.called
it 'matches only infix data by default', (done)->
@instance._data = {
addasjjjj: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(3)
done()
@instance.search("as")
context 'with search_type option set to prefix', ->
beforeEach ->
@init_options.search_type = 'prefix'
@instance = @StorageFreak(@init_options)
it 'matches prefix', (done)->
@instance._data = {
addas: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'searches in-memory data', (done)->
@instance._data = {
add: 'add'
asd: 'asd'
as: 'as'
}
@instance.on 'dbsearch_results', (data, query, remote = false)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'matches accented characters ignoring their accent', (done)->
@instance._data = {
λολο: 'as'
λόλο: 'asd'
λαλα: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('λολο')
it 'matches special regex characters', (done)->
@instance._data = {
'pc++': 'special'
}
@instance.on 'dbsearch_results', (data)->
expect(data).to.deep.equal [
{ id: 'special', name: 'pc++' }
]
done()
@instance.search('pc++')
it 'triggers "dbsearch_results" event and passes results', (done)->
@instance._data = {
as: 'as'
asd: 'asd'
add: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(data)
.to.be.an('array')
.to.have.length(2)
done()
@instance.search('as')
it 'also passes original query as second argument to the event callback', (done)->
@instance._data = {
as: 'as'
asd: 'asd'
add: 'add'
}
@instance.on 'dbsearch_results', (data, query)->
expect(query).to.equal('as')
done()
@instance.search('as')
it 'sorts results by absolute matches, token matches, prefix matches', (done)->
@instance._data =
skyram: 'k1'
abraram: 'k2'
'mr ram': 'k3'
babaoram: 'k4'
rambo: 'k5'
'ram mania': 'k6'
ram: 'k7'
@instance.config.maxResultsNum = 7
@instance.on 'dbsearch_results', (data)->
expect(data).to.deep.equal [
{ id: 'k7', name: 'ram' },
{ id: 'k6', name: 'ram mania' },
{ id: 'k3', name: 'mr ram' }
{ id: 'k5', name: 'rambo' }
{ id: 'k2', name: 'abraram' }
{ id: 'k4', name: 'babaoram' }
{ id: 'k1', name: 'skyram' }
]
done()
@instance.search('ram')
it 'slices results', (done)->
@instance._data =
asd: 'asd'
add: 'add'
as: 'as'
asd1: 'asd1'
add1: 'add1'
as1: 'as1'
asd2: 'asd2'
add2: 'add2'
as3: 'as2'
@instance.on 'dbsearch_results', (data)=>
expect(data).to.have.length @instance.config.maxResultsNum
done()
@instance.search('as')
it 'triggers "dbremote_search_reset" event', (done)->
@instance.on 'dbremote_search_reset', ->
expect(true).to.be.true
done()
@instance.search('as')
context 'when query is smaller than @config.minCharsForRemoteSearch', ->
it 'does not make an XHR', ->
@instance.search('asdasd')
expect(@requests).to.have.length(0)
context 'when query is bigger or equal to @config.minCharsForRemoteSearch', ->
beforeEach ->
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
afterEach ->
@clock.restore()
it 'registers XHR to occur after timeout', ->
spy = sinon.spy(window, 'setTimeout')
@instance.search(@query)
expect(spy.args[0][1]).to.equal(@instance.config.XHRTimeout)
spy.restore()
context 'before timeout', ->
it 'triggers "dbremote_search_in" event and passes @config.XHRTimeout', (done)->
@instance.on 'dbremote_search_in', (timeout)=>
expect(timeout).to.equal(@instance.config.XHRTimeout)
done()
@instance.search(@query)
context 'after timeout', ->
eventually = (done, expectation) ->
try
expectation()
done()
catch e
done(e)
beforeEach ->
@expected_makers_data = [
{
'id': 'PI:NAME:<NAME>END_PIdasd0',
'name': 'PI:NAME:<NAME>END_PI'
},
{
'id': 'asdasd3',
'name': 'PI:NAME:<NAME>END_PI3'
},
{
'id': 'asdasd4',
'name': 'PI:NAME:<NAME>END_PIdasd4'
},
{
'id': 'asdasd5',
'name': 'PI:NAME:<NAME>END_PIdasd5'
},
{
'id': 'asdasd6',
'name': 'asdasd6'
}
]
it 'makes an XHR', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(@requests).to.have.length(1)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@shops_json)
context 'when storage has a last_modified timestamp', ->
beforeEach ->
last_modified = new Date().getTime() - 60 * 60 * 1000 # 1 hour before
@instance._set @instance._last_modified_key, last_modified
it 'does not add If-Modified-Since header', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(@requests[0].requestHeaders).to.not.have.property('If-Modified-Since')
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@shops_json)
it 'updates storage', (done)->
@instance._set @instance._data_key, @makers_obj
old_data = @instance._get @instance._data_key
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(@instance._get(@instance._data_key)).to.not.eql(old_data)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'updates @_data', (done)->
data = {koko:'lala'}
@instance._data = data
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(@instance._data).to.not.eql(data)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes results from updated data as first arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(results).to.deep.eql @expected_makers_data
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes original query as second arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(query).to.equal(@query)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'triggers "dbsearch_results" event and passes "xhr" as third arg', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(xhr).to.equal('xhr')
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'sorts results', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, => expect(results).to.deep.eql @expected_makers_data
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
it 'slices results', (done)->
@instance.on 'dbsearch_results', (results, query, xhr = false)=>
if xhr
eventually done, =>
expect(results).to.be.an('array').with.length(@instance.config.maxResultsNum)
@instance.search(@query)
@clock.tick(@instance.config.XHRTimeout)
@clock.restore()
@respondJSON(@makers_json)
context 'when a new remote request starts before the previous finishes', ->
beforeEach ->
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
@instance.search(@query)
afterEach ->
@clock.restore()
cleanup_tests()
describe 'cleanup', ->
beforeEach ->
@instance = @StorageFreak(@init_options)
@query = 'asdasd'
@instance._data =
asdasd0: 'asdasd0'
@clock = sinon.useFakeTimers()
@instance.search(@query)
afterEach ->
@clock.restore()
cleanup_tests()
|
[
{
"context": "h credentials to follow the {name: 'user', pass: 'pass'}\n * format of node-basic-auth\n *\n * @private\n * ",
"end": 1249,
"score": 0.9978294372558594,
"start": 1245,
"tag": "PASSWORD",
"value": "pass"
}
] | lib/index.coffee | carrot/publicist-middleware | 2 | basicAuth = require 'basic-auth'
minimatch = require 'minimatch'
_ = require 'lodash'
###*
* Configures options and returns a middleware function.
*
* Options:
* - auth: A basic auth user/pass in the format of 'user:password'.
*
* @param {Object} opts - options object, described above
* @return {Function} middleware function
###
module.exports = (opts) ->
if typeof opts == 'string'
match = {'**': opts}
else if typeof opts == 'object' and opts.hasOwnProperty('user')
match = {'**': opts.user + ':' + opts.pass}
else
match = opts
return (req, res, next) ->
if not opts then return next()
_.keys(match).some (matcher) =>
@match = if minimatch(req.url, matcher) then matcher else false
# the current route did not match a globstar, carry on
if not @match then return next()
# check if auth_headers are accurate, otherwise prompt authentication
auth_headers = JSON.stringify(basicAuth(req))
if auth_headers == format_auth_option(match[@match])
return next()
else
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"')
res.end('Not Authorized')
###*
* Formats auth credentials to follow the {name: 'user', pass: 'pass'}
* format of node-basic-auth
*
* @private
* @param {String} auth - a username:password string
* @return {String} a stringified JSON object with 'name' and 'pass' keys
###
format_auth_option = (auth) ->
auth = auth.split(':')
JSON.stringify({ name: auth[0], pass: auth[1] })
| 189845 | basicAuth = require 'basic-auth'
minimatch = require 'minimatch'
_ = require 'lodash'
###*
* Configures options and returns a middleware function.
*
* Options:
* - auth: A basic auth user/pass in the format of 'user:password'.
*
* @param {Object} opts - options object, described above
* @return {Function} middleware function
###
module.exports = (opts) ->
if typeof opts == 'string'
match = {'**': opts}
else if typeof opts == 'object' and opts.hasOwnProperty('user')
match = {'**': opts.user + ':' + opts.pass}
else
match = opts
return (req, res, next) ->
if not opts then return next()
_.keys(match).some (matcher) =>
@match = if minimatch(req.url, matcher) then matcher else false
# the current route did not match a globstar, carry on
if not @match then return next()
# check if auth_headers are accurate, otherwise prompt authentication
auth_headers = JSON.stringify(basicAuth(req))
if auth_headers == format_auth_option(match[@match])
return next()
else
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"')
res.end('Not Authorized')
###*
* Formats auth credentials to follow the {name: 'user', pass: '<PASSWORD>'}
* format of node-basic-auth
*
* @private
* @param {String} auth - a username:password string
* @return {String} a stringified JSON object with 'name' and 'pass' keys
###
format_auth_option = (auth) ->
auth = auth.split(':')
JSON.stringify({ name: auth[0], pass: auth[1] })
| true | basicAuth = require 'basic-auth'
minimatch = require 'minimatch'
_ = require 'lodash'
###*
* Configures options and returns a middleware function.
*
* Options:
* - auth: A basic auth user/pass in the format of 'user:password'.
*
* @param {Object} opts - options object, described above
* @return {Function} middleware function
###
module.exports = (opts) ->
if typeof opts == 'string'
match = {'**': opts}
else if typeof opts == 'object' and opts.hasOwnProperty('user')
match = {'**': opts.user + ':' + opts.pass}
else
match = opts
return (req, res, next) ->
if not opts then return next()
_.keys(match).some (matcher) =>
@match = if minimatch(req.url, matcher) then matcher else false
# the current route did not match a globstar, carry on
if not @match then return next()
# check if auth_headers are accurate, otherwise prompt authentication
auth_headers = JSON.stringify(basicAuth(req))
if auth_headers == format_auth_option(match[@match])
return next()
else
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"')
res.end('Not Authorized')
###*
* Formats auth credentials to follow the {name: 'user', pass: 'PI:PASSWORD:<PASSWORD>END_PI'}
* format of node-basic-auth
*
* @private
* @param {String} auth - a username:password string
* @return {String} a stringified JSON object with 'name' and 'pass' keys
###
format_auth_option = (auth) ->
auth = auth.split(':')
JSON.stringify({ name: auth[0], pass: auth[1] })
|
[
{
"context": "vascript\", src: \"https://www.google.com/jsapi?key=ABQIAAAAV88HHyf8NBcAL3aio53OixSEBwhbzDd0F998UkbSll3boCkrihTFj2uO3yETr_J5z25r2aIc4YCVpQ\"\n #script type: \"text/javascript\", src: \"htt",
"end": 239,
"score": 0.9995309710502625,
"start": 153,
"tag": "KEY",
"value": "ABQIAAAAV88HHyf8NBcAL3aio53OixSEBwhbzDd0F998UkbSll3boCkrihTFj2uO3yETr_J5z25r2aIc4YCVpQ"
},
{
"context": " text \" | \"\n a href: \"/user/#{@current_user.username}\", class: \"username\", -> @current_user.username\n ",
"end": 1264,
"score": 0.947554886341095,
"start": 1242,
"tag": "USERNAME",
"value": "@current_user.username"
},
{
"context": "{@current_user.username}\", class: \"username\", -> @current_user.username\n text \" | \"\n a hre",
"end": 1303,
"score": 0.7988963723182678,
"start": 1291,
"tag": "USERNAME",
"value": "current_user"
},
{
"context": "r.username}\", class: \"username\", -> @current_user.username\n text \" | \"\n a href: \"/logo",
"end": 1312,
"score": 0.7962879538536072,
"start": 1304,
"tag": "USERNAME",
"value": "username"
},
{
"context": "e\", 'data-id': @current_user._id, 'data-username': @current_user.username\n",
"end": 1847,
"score": 0.9942821860313416,
"start": 1825,
"tag": "USERNAME",
"value": "@current_user.username"
}
] | templates/layout.coffee | jaekwon/YCatalyst | 3 | exports.template = ->
doctype 5
html ->
head ->
title @title
#script type: "text/javascript", src: "https://www.google.com/jsapi?key=ABQIAAAAV88HHyf8NBcAL3aio53OixSEBwhbzDd0F998UkbSll3boCkrihTFj2uO3yETr_J5z25r2aIc4YCVpQ"
#script type: "text/javascript", src: "https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
for file in ["jquery-1.4.2.min.js", "underscore.js", "client.js", "coffeekup.js", "markz.js", "record.js"]
script type: "text/javascript", src: static_file(file)
link type: "text/css", rel: "stylesheet", href: static_file("main.css")
body ->
div id: "headerbar", ->
if typeof @headerbar_text != "undefined"
span class: "logo", -> @headerbar_text
else
a class: "logo", href: "/", ->
img src: "/static/logo.png"
span class: "links", ->
a href: "/submit", -> "submit"
text " | "
a href: "/submit?type=poll", -> "poll"
if @current_user
text " | "
a href: "/inbox", -> "inbox"
div style: "float: right", ->
if @current_user
a href: "/refer", -> "refer a friend"
text " | "
a href: "/user/#{@current_user.username}", class: "username", -> @current_user.username
text " | "
a href: "/logout", class: "logout", -> "logout"
else
a href: "/apply", -> "apply"
text " | "
span class: "username", -> "anonymous"
text " | "
a href: "/login", class: "login", -> "login"
div id: "body_contents", ->
text render(@body_template, @body_context)
if @current_user
div id: 'current_user', style: "display: none", 'data-id': @current_user._id, 'data-username': @current_user.username
| 179398 | exports.template = ->
doctype 5
html ->
head ->
title @title
#script type: "text/javascript", src: "https://www.google.com/jsapi?key=<KEY>"
#script type: "text/javascript", src: "https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
for file in ["jquery-1.4.2.min.js", "underscore.js", "client.js", "coffeekup.js", "markz.js", "record.js"]
script type: "text/javascript", src: static_file(file)
link type: "text/css", rel: "stylesheet", href: static_file("main.css")
body ->
div id: "headerbar", ->
if typeof @headerbar_text != "undefined"
span class: "logo", -> @headerbar_text
else
a class: "logo", href: "/", ->
img src: "/static/logo.png"
span class: "links", ->
a href: "/submit", -> "submit"
text " | "
a href: "/submit?type=poll", -> "poll"
if @current_user
text " | "
a href: "/inbox", -> "inbox"
div style: "float: right", ->
if @current_user
a href: "/refer", -> "refer a friend"
text " | "
a href: "/user/#{@current_user.username}", class: "username", -> @current_user.username
text " | "
a href: "/logout", class: "logout", -> "logout"
else
a href: "/apply", -> "apply"
text " | "
span class: "username", -> "anonymous"
text " | "
a href: "/login", class: "login", -> "login"
div id: "body_contents", ->
text render(@body_template, @body_context)
if @current_user
div id: 'current_user', style: "display: none", 'data-id': @current_user._id, 'data-username': @current_user.username
| true | exports.template = ->
doctype 5
html ->
head ->
title @title
#script type: "text/javascript", src: "https://www.google.com/jsapi?key=PI:KEY:<KEY>END_PI"
#script type: "text/javascript", src: "https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
for file in ["jquery-1.4.2.min.js", "underscore.js", "client.js", "coffeekup.js", "markz.js", "record.js"]
script type: "text/javascript", src: static_file(file)
link type: "text/css", rel: "stylesheet", href: static_file("main.css")
body ->
div id: "headerbar", ->
if typeof @headerbar_text != "undefined"
span class: "logo", -> @headerbar_text
else
a class: "logo", href: "/", ->
img src: "/static/logo.png"
span class: "links", ->
a href: "/submit", -> "submit"
text " | "
a href: "/submit?type=poll", -> "poll"
if @current_user
text " | "
a href: "/inbox", -> "inbox"
div style: "float: right", ->
if @current_user
a href: "/refer", -> "refer a friend"
text " | "
a href: "/user/#{@current_user.username}", class: "username", -> @current_user.username
text " | "
a href: "/logout", class: "logout", -> "logout"
else
a href: "/apply", -> "apply"
text " | "
span class: "username", -> "anonymous"
text " | "
a href: "/login", class: "login", -> "login"
div id: "body_contents", ->
text render(@body_template, @body_context)
if @current_user
div id: 'current_user', style: "display: none", 'data-id': @current_user._id, 'data-username': @current_user.username
|
[
{
"context": "\nmodule.exports = () ->\n describe 'User', ->\n\n alice = null\n bob = null\n\n userModel =\n name",
"end": 221,
"score": 0.5906455516815186,
"start": 216,
"tag": "NAME",
"value": "alice"
},
{
"context": " () ->\n describe 'User', ->\n\n alice = null\n bob = null\n\n userModel =\n name: 'users'\n ",
"end": 236,
"score": 0.8405412435531616,
"start": 233,
"tag": "NAME",
"value": "bob"
},
{
"context": "erFactory userModel, crudControllerFactory\n alice =\n firstName: 'Alice'\n password",
"end": 920,
"score": 0.7349389791488647,
"start": 915,
"tag": "NAME",
"value": "alice"
},
{
"context": "llerFactory\n alice =\n firstName: 'Alice'\n password: '123'\n \n bob =\n ",
"end": 950,
"score": 0.9591304659843445,
"start": 945,
"tag": "NAME",
"value": "Alice"
},
{
"context": " firstName: 'Alice'\n password: '123'\n \n bob =\n firstName: 'Bob'\n ",
"end": 976,
"score": 0.9993767142295837,
"start": 973,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "me: 'Alice'\n password: '123'\n \n bob =\n firstName: 'Bob'\n password: ",
"end": 994,
"score": 0.5681726932525635,
"start": 991,
"tag": "NAME",
"value": "bob"
},
{
"context": "d: '123'\n \n bob =\n firstName: 'Bob'\n password: '456'\n\n describe 'Stand",
"end": 1022,
"score": 0.9627811908721924,
"start": 1019,
"tag": "NAME",
"value": "Bob"
},
{
"context": "=\n firstName: 'Bob'\n password: '456'\n\n describe 'Standard Crud', ->\n it '",
"end": 1048,
"score": 0.999373733997345,
"start": 1045,
"tag": "PASSWORD",
"value": "456"
},
{
"context": "done) ->\n res =\n giResult: alice\n json: (code, result) ->\n ",
"end": 2536,
"score": 0.5607225894927979,
"start": 2531,
"tag": "NAME",
"value": "alice"
},
{
"context": " giResult: [\n {message: \"ok\", obj: alice}\n {message: \"ok\", obj: bob}\n ",
"end": 2923,
"score": 0.955428421497345,
"start": 2918,
"tag": "NAME",
"value": "alice"
},
{
"context": ", obj: alice}\n {message: \"ok\", obj: bob}\n ]\n giResultCode: 200\n",
"end": 2965,
"score": 0.9656470417976379,
"start": 2962,
"tag": "NAME",
"value": "bob"
},
{
"context": "Result: [\n {message: \"not ok\", obj: alice}\n {message: \"ok\", obj: bob}\n ",
"end": 3485,
"score": 0.9745292663574219,
"start": 3480,
"tag": "NAME",
"value": "alice"
},
{
"context": ", obj: alice}\n {message: \"ok\", obj: bob}\n ]\n giResultCode: 500\n",
"end": 3527,
"score": 0.9697946906089783,
"start": 3524,
"tag": "NAME",
"value": "bob"
},
{
"context": " _id: '123'\n password: 'a password'\n res =\n json: (code, res",
"end": 5908,
"score": 0.9992415904998779,
"start": 5898,
"tag": "PASSWORD",
"value": "a password"
}
] | test/unit/server/mocha/controllers/user.coffee | valueflowquality/gi-security-update | 0 | _ = require 'underscore'
path = require 'path'
expect = require('chai').expect
sinon = require 'sinon'
dir = path.normalize __dirname + '../../../../../../server'
module.exports = () ->
describe 'User', ->
alice = null
bob = null
userModel =
name: 'users'
create: (json, cb) ->
cb null, json
find: (options, cb) ->
cb null, [alice, bob]
findById: (id, systemId, cb) ->
cb null, alice
update: (id, json, cb) ->
cb null, json
controllerFactory = require dir + '/controllers/user'
describe 'Exports', ->
controller = null
crudController =
create: ->
index: ->
show: ->
update: ->
destroy: 'crud destroy'
crudControllerFactory = () ->
crudController
beforeEach ->
controller = controllerFactory userModel, crudControllerFactory
alice =
firstName: 'Alice'
password: '123'
bob =
firstName: 'Bob'
password: '456'
describe 'Standard Crud', ->
it 'destroy: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'destroy'
expect(controller.destroy).to.equal 'crud destroy'
done()
describe 'Overridden Crud', ->
it 'index: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'index'
done()
describe 'Index', ->
beforeEach ->
sinon.stub crudController, "index"
crudController.index.callsArg 2
afterEach ->
crudController.index.restore()
it 'Does not transmit passwords', (done) ->
req =
query:
max: 3
res =
giResult: [alice, bob]
json: (code, result) ->
_.each result, (user) ->
expect(user.password).to.not.exist
expect(user).to.not.have.property 'password'
done()
controller.index req, res
it 'create: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'create'
done()
describe 'Create', ->
beforeEach ->
sinon.stub crudController, "create"
crudController.create.callsArg 2
afterEach ->
crudController.create.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: alice
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.create null, res
it 'Does not transmit password after sucessful bulk create', (done) ->
res =
giResult: [
{message: "ok", obj: alice}
{message: "ok", obj: bob}
]
giResultCode: 200
json: (code, result) ->
expect(code).to.equal 200
_.each result, (r) ->
expect(r.obj.password).to.not.exist
expect(r.obj).to.not.have.property 'password'
done()
controller.create null, res
it 'Does not transmit password after failed bulk create', (done) ->
res =
giResult: [
{message: "not ok", obj: alice}
{message: "ok", obj: bob}
]
giResultCode: 500
json: (code, result) ->
expect(code).to.equal 500
_.each result, (r) ->
expect(r.obj.password).to.not.exist
expect(r.obj).to.not.have.property 'password'
done()
controller.create null, res
it 'update: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'update'
done()
describe 'Update', ->
beforeEach ->
sinon.stub crudController, "update"
crudController.update.callsArg 2
afterEach ->
crudController.update.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: bob
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.update null, res
it 'show: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'show'
done()
describe 'Show', ->
beforeEach ->
sinon.stub crudController, "show"
crudController.show.callsArg 2
afterEach ->
crudController.show.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: alice
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.show null, res
describe 'Other', ->
describe 'showMe: function(req, res)', ->
it 'Does not transmit passwords', (done) ->
req =
user:
id: 'validId'
res =
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.showMe req, res
describe 'updateme: function(req, res)', ->
it 'Does not transmit passwords', (done) ->
req =
user:
id: '123'
body:
_id: '123'
password: 'a password'
res =
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.updateMe req, res | 12461 | _ = require 'underscore'
path = require 'path'
expect = require('chai').expect
sinon = require 'sinon'
dir = path.normalize __dirname + '../../../../../../server'
module.exports = () ->
describe 'User', ->
<NAME> = null
<NAME> = null
userModel =
name: 'users'
create: (json, cb) ->
cb null, json
find: (options, cb) ->
cb null, [alice, bob]
findById: (id, systemId, cb) ->
cb null, alice
update: (id, json, cb) ->
cb null, json
controllerFactory = require dir + '/controllers/user'
describe 'Exports', ->
controller = null
crudController =
create: ->
index: ->
show: ->
update: ->
destroy: 'crud destroy'
crudControllerFactory = () ->
crudController
beforeEach ->
controller = controllerFactory userModel, crudControllerFactory
<NAME> =
firstName: '<NAME>'
password: '<PASSWORD>'
<NAME> =
firstName: '<NAME>'
password: '<PASSWORD>'
describe 'Standard Crud', ->
it 'destroy: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'destroy'
expect(controller.destroy).to.equal 'crud destroy'
done()
describe 'Overridden Crud', ->
it 'index: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'index'
done()
describe 'Index', ->
beforeEach ->
sinon.stub crudController, "index"
crudController.index.callsArg 2
afterEach ->
crudController.index.restore()
it 'Does not transmit passwords', (done) ->
req =
query:
max: 3
res =
giResult: [alice, bob]
json: (code, result) ->
_.each result, (user) ->
expect(user.password).to.not.exist
expect(user).to.not.have.property 'password'
done()
controller.index req, res
it 'create: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'create'
done()
describe 'Create', ->
beforeEach ->
sinon.stub crudController, "create"
crudController.create.callsArg 2
afterEach ->
crudController.create.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: <NAME>
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.create null, res
it 'Does not transmit password after sucessful bulk create', (done) ->
res =
giResult: [
{message: "ok", obj: <NAME>}
{message: "ok", obj: <NAME>}
]
giResultCode: 200
json: (code, result) ->
expect(code).to.equal 200
_.each result, (r) ->
expect(r.obj.password).to.not.exist
expect(r.obj).to.not.have.property 'password'
done()
controller.create null, res
it 'Does not transmit password after failed bulk create', (done) ->
res =
giResult: [
{message: "not ok", obj: <NAME>}
{message: "ok", obj: <NAME>}
]
giResultCode: 500
json: (code, result) ->
expect(code).to.equal 500
_.each result, (r) ->
expect(r.obj.password).to.not.exist
expect(r.obj).to.not.have.property 'password'
done()
controller.create null, res
it 'update: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'update'
done()
describe 'Update', ->
beforeEach ->
sinon.stub crudController, "update"
crudController.update.callsArg 2
afterEach ->
crudController.update.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: bob
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.update null, res
it 'show: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'show'
done()
describe 'Show', ->
beforeEach ->
sinon.stub crudController, "show"
crudController.show.callsArg 2
afterEach ->
crudController.show.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: alice
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.show null, res
describe 'Other', ->
describe 'showMe: function(req, res)', ->
it 'Does not transmit passwords', (done) ->
req =
user:
id: 'validId'
res =
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.showMe req, res
describe 'updateme: function(req, res)', ->
it 'Does not transmit passwords', (done) ->
req =
user:
id: '123'
body:
_id: '123'
password: '<PASSWORD>'
res =
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.updateMe req, res | true | _ = require 'underscore'
path = require 'path'
expect = require('chai').expect
sinon = require 'sinon'
dir = path.normalize __dirname + '../../../../../../server'
module.exports = () ->
describe 'User', ->
PI:NAME:<NAME>END_PI = null
PI:NAME:<NAME>END_PI = null
userModel =
name: 'users'
create: (json, cb) ->
cb null, json
find: (options, cb) ->
cb null, [alice, bob]
findById: (id, systemId, cb) ->
cb null, alice
update: (id, json, cb) ->
cb null, json
controllerFactory = require dir + '/controllers/user'
describe 'Exports', ->
controller = null
crudController =
create: ->
index: ->
show: ->
update: ->
destroy: 'crud destroy'
crudControllerFactory = () ->
crudController
beforeEach ->
controller = controllerFactory userModel, crudControllerFactory
PI:NAME:<NAME>END_PI =
firstName: 'PI:NAME:<NAME>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
PI:NAME:<NAME>END_PI =
firstName: 'PI:NAME:<NAME>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'Standard Crud', ->
it 'destroy: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'destroy'
expect(controller.destroy).to.equal 'crud destroy'
done()
describe 'Overridden Crud', ->
it 'index: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'index'
done()
describe 'Index', ->
beforeEach ->
sinon.stub crudController, "index"
crudController.index.callsArg 2
afterEach ->
crudController.index.restore()
it 'Does not transmit passwords', (done) ->
req =
query:
max: 3
res =
giResult: [alice, bob]
json: (code, result) ->
_.each result, (user) ->
expect(user.password).to.not.exist
expect(user).to.not.have.property 'password'
done()
controller.index req, res
it 'create: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'create'
done()
describe 'Create', ->
beforeEach ->
sinon.stub crudController, "create"
crudController.create.callsArg 2
afterEach ->
crudController.create.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: PI:NAME:<NAME>END_PI
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.create null, res
it 'Does not transmit password after sucessful bulk create', (done) ->
res =
giResult: [
{message: "ok", obj: PI:NAME:<NAME>END_PI}
{message: "ok", obj: PI:NAME:<NAME>END_PI}
]
giResultCode: 200
json: (code, result) ->
expect(code).to.equal 200
_.each result, (r) ->
expect(r.obj.password).to.not.exist
expect(r.obj).to.not.have.property 'password'
done()
controller.create null, res
it 'Does not transmit password after failed bulk create', (done) ->
res =
giResult: [
{message: "not ok", obj: PI:NAME:<NAME>END_PI}
{message: "ok", obj: PI:NAME:<NAME>END_PI}
]
giResultCode: 500
json: (code, result) ->
expect(code).to.equal 500
_.each result, (r) ->
expect(r.obj.password).to.not.exist
expect(r.obj).to.not.have.property 'password'
done()
controller.create null, res
it 'update: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'update'
done()
describe 'Update', ->
beforeEach ->
sinon.stub crudController, "update"
crudController.update.callsArg 2
afterEach ->
crudController.update.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: bob
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.update null, res
it 'show: function(req, res)', (done) ->
expect(controller).to.have.ownProperty 'show'
done()
describe 'Show', ->
beforeEach ->
sinon.stub crudController, "show"
crudController.show.callsArg 2
afterEach ->
crudController.show.restore()
it 'Does not transmit passwords', (done) ->
res =
giResult: alice
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.show null, res
describe 'Other', ->
describe 'showMe: function(req, res)', ->
it 'Does not transmit passwords', (done) ->
req =
user:
id: 'validId'
res =
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.showMe req, res
describe 'updateme: function(req, res)', ->
it 'Does not transmit passwords', (done) ->
req =
user:
id: '123'
body:
_id: '123'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
res =
json: (code, result) ->
expect(result.password).to.not.exist
expect(result).to.not.have.property 'password'
done()
controller.updateMe req, res |
[
{
"context": ".send\n name: 'zack'\n password: '123'\n .end (err, res) ->\n entity = re",
"end": 528,
"score": 0.999300479888916,
"start": 525,
"tag": "PASSWORD",
"value": "123"
}
] | node_modules/node-odata/test/model.hidden.field.coffee | hurzelpurzel/bookstoreajs | 0 | should = require('should')
request = require('supertest')
odata = require('../.')
PORT = 0
entity = undefined
describe 'model.hidden.field', ->
before (done) ->
server = odata('mongodb://localhost/odata-test')
server.resource 'hidden-field',
name: String
password:
type: String
select: false
s = server.listen PORT, ->
PORT = s.address().port
request("http://localhost:#{PORT}")
.post('/hidden-field')
.send
name: 'zack'
password: '123'
.end (err, res) ->
entity = res.body
done()
it "should work when get entity", (done) ->
request("http://localhost:#{PORT}")
.get("/hidden-field(#{entity.id})")
.expect(200)
.end (err, res) ->
return done(err) if(err)
res.body.should.be.have.property('name')
res.body.name.should.be.equal('zack')
res.body.should.be.not.have.property('password')
done()
it 'should work when get entities list', (done) ->
request("http://localhost:#{PORT}")
.get('/hidden-field')
.expect(200)
.end (err, res) ->
return done(err) if(err)
res.body.value[0].should.be.have.property('id')
res.body.value[0].should.be.have.property('name')
res.body.value[0].should.be.not.have.property('password')
done()
# TODO: unknown error: timeout for test.
# it 'should work when get entities list even it is selected', (done) ->
# request("http://localhost:#{PORT}")
# .get('/hidden-field?$select=name, password')
# .expect(200)
# .end (err, res) ->
# res.body.value[0].should.be.not.have.property('id')
# res.body.value[0].should.be.have.property('name')
# res.body.value[0].should.be.not.have.property('password')
# done()
it 'should work when get entities list even only it is selected', (done) ->
request("http://localhost:#{PORT}")
.get('/hidden-field?$select=password')
.expect(200)
.end (err, res) ->
res.body.value[0].should.be.have.property('id')
res.body.value[0].should.be.have.property('name')
res.body.value[0].should.be.not.have.property('password')
done()
| 124822 | should = require('should')
request = require('supertest')
odata = require('../.')
PORT = 0
entity = undefined
describe 'model.hidden.field', ->
before (done) ->
server = odata('mongodb://localhost/odata-test')
server.resource 'hidden-field',
name: String
password:
type: String
select: false
s = server.listen PORT, ->
PORT = s.address().port
request("http://localhost:#{PORT}")
.post('/hidden-field')
.send
name: 'zack'
password: '<PASSWORD>'
.end (err, res) ->
entity = res.body
done()
it "should work when get entity", (done) ->
request("http://localhost:#{PORT}")
.get("/hidden-field(#{entity.id})")
.expect(200)
.end (err, res) ->
return done(err) if(err)
res.body.should.be.have.property('name')
res.body.name.should.be.equal('zack')
res.body.should.be.not.have.property('password')
done()
it 'should work when get entities list', (done) ->
request("http://localhost:#{PORT}")
.get('/hidden-field')
.expect(200)
.end (err, res) ->
return done(err) if(err)
res.body.value[0].should.be.have.property('id')
res.body.value[0].should.be.have.property('name')
res.body.value[0].should.be.not.have.property('password')
done()
# TODO: unknown error: timeout for test.
# it 'should work when get entities list even it is selected', (done) ->
# request("http://localhost:#{PORT}")
# .get('/hidden-field?$select=name, password')
# .expect(200)
# .end (err, res) ->
# res.body.value[0].should.be.not.have.property('id')
# res.body.value[0].should.be.have.property('name')
# res.body.value[0].should.be.not.have.property('password')
# done()
it 'should work when get entities list even only it is selected', (done) ->
request("http://localhost:#{PORT}")
.get('/hidden-field?$select=password')
.expect(200)
.end (err, res) ->
res.body.value[0].should.be.have.property('id')
res.body.value[0].should.be.have.property('name')
res.body.value[0].should.be.not.have.property('password')
done()
| true | should = require('should')
request = require('supertest')
odata = require('../.')
PORT = 0
entity = undefined
describe 'model.hidden.field', ->
before (done) ->
server = odata('mongodb://localhost/odata-test')
server.resource 'hidden-field',
name: String
password:
type: String
select: false
s = server.listen PORT, ->
PORT = s.address().port
request("http://localhost:#{PORT}")
.post('/hidden-field')
.send
name: 'zack'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
.end (err, res) ->
entity = res.body
done()
it "should work when get entity", (done) ->
request("http://localhost:#{PORT}")
.get("/hidden-field(#{entity.id})")
.expect(200)
.end (err, res) ->
return done(err) if(err)
res.body.should.be.have.property('name')
res.body.name.should.be.equal('zack')
res.body.should.be.not.have.property('password')
done()
it 'should work when get entities list', (done) ->
request("http://localhost:#{PORT}")
.get('/hidden-field')
.expect(200)
.end (err, res) ->
return done(err) if(err)
res.body.value[0].should.be.have.property('id')
res.body.value[0].should.be.have.property('name')
res.body.value[0].should.be.not.have.property('password')
done()
# TODO: unknown error: timeout for test.
# it 'should work when get entities list even it is selected', (done) ->
# request("http://localhost:#{PORT}")
# .get('/hidden-field?$select=name, password')
# .expect(200)
# .end (err, res) ->
# res.body.value[0].should.be.not.have.property('id')
# res.body.value[0].should.be.have.property('name')
# res.body.value[0].should.be.not.have.property('password')
# done()
it 'should work when get entities list even only it is selected', (done) ->
request("http://localhost:#{PORT}")
.get('/hidden-field?$select=password')
.expect(200)
.end (err, res) ->
res.body.value[0].should.be.have.property('id')
res.body.value[0].should.be.have.property('name')
res.body.value[0].should.be.not.have.property('password')
done()
|
[
{
"context": "bj) ->\n pairs = []\n pairs = (\"#{key}=\\\"#{val}\\\"\" for own key, val of obj)\n \" [#{pairs.join(\",",
"end": 376,
"score": 0.5916498303413391,
"start": 376,
"tag": "KEY",
"value": ""
}
] | src/graphviz.coffee | automatthew/djinn | 4 |
# Graphviz formatting helpers
Graphviz =
digraph_preamble: (name) ->
"""
digraph #{name} {\n
rankdir=LR;\n
node [shape=circle,fontsize=10]
edge [fontsize=16]
"""
dotEdge: (from, to) ->
[from, to].join(" -> ")
dotNode: (node, attrs) ->
"#{node}#{@dotAttrs(attrs)};\n"
dotAttrs: (obj) ->
pairs = []
pairs = ("#{key}=\"#{val}\"" for own key, val of obj)
" [#{pairs.join(", ")}]"
module.exports = Graphviz
| 202987 |
# Graphviz formatting helpers
Graphviz =
digraph_preamble: (name) ->
"""
digraph #{name} {\n
rankdir=LR;\n
node [shape=circle,fontsize=10]
edge [fontsize=16]
"""
dotEdge: (from, to) ->
[from, to].join(" -> ")
dotNode: (node, attrs) ->
"#{node}#{@dotAttrs(attrs)};\n"
dotAttrs: (obj) ->
pairs = []
pairs = ("#{key}=\"#{val<KEY>}\"" for own key, val of obj)
" [#{pairs.join(", ")}]"
module.exports = Graphviz
| true |
# Graphviz formatting helpers
Graphviz =
digraph_preamble: (name) ->
"""
digraph #{name} {\n
rankdir=LR;\n
node [shape=circle,fontsize=10]
edge [fontsize=16]
"""
dotEdge: (from, to) ->
[from, to].join(" -> ")
dotNode: (node, attrs) ->
"#{node}#{@dotAttrs(attrs)};\n"
dotAttrs: (obj) ->
pairs = []
pairs = ("#{key}=\"#{valPI:KEY:<KEY>END_PI}\"" for own key, val of obj)
" [#{pairs.join(", ")}]"
module.exports = Graphviz
|
[
{
"context": ": 'AND'\n\n initialize: ->\n @preconditionKey = \"precondition_#{@precondition.id}\"\n @parentPreconditionKey = \"p",
"end": 286,
"score": 0.9431840181350708,
"start": 271,
"tag": "KEY",
"value": "precondition_#{"
},
{
"context": "alize: ->\n @preconditionKey = \"precondition_#{@precondition.id}\"\n @parentPreconditionKey = \"preco",
"end": 290,
"score": 0.5683372020721436,
"start": 287,
"tag": "KEY",
"value": "pre"
},
{
"context": " @preconditionKey = \"precondition_#{@precondition.id}\"\n @parentPreconditionKey = \"precondition_#{@par",
"end": 304,
"score": 0.8079228401184082,
"start": 300,
"tag": "KEY",
"value": "id}\""
},
{
"context": "{@precondition.id}\"\n @parentPreconditionKey = \"precondition_#{@parentPrecondition.id}\"\n @conjunction = @trans",
"end": 350,
"score": 0.9201018810272217,
"start": 335,
"tag": "KEY",
"value": "precondition_#{"
},
{
"context": "conditionKey = \"precondition_#{@parentPrecondition.id}\"\n @conjunction = @translate_conjunction(@parent",
"end": 374,
"score": 0.772728681564331,
"start": 370,
"tag": "KEY",
"value": "id}\""
}
] | app/assets/javascripts/views/logic/precondition_logic_view.js.coffee | okeefm/bonnie | 0 | class Thorax.Views.PreconditionLogic extends Thorax.Views.BonnieView
template: JST['logic/precondition']
conjunction_map:
'allTrue':'AND'
'atLeastOneTrue':'OR'
flip_conjunction_map:
'AND': 'OR'
'OR': 'AND'
initialize: ->
@preconditionKey = "precondition_#{@precondition.id}"
@parentPreconditionKey = "precondition_#{@parentPrecondition.id}"
@conjunction = @translate_conjunction(@parentPrecondition.conjunction_code)
@suppress = true if @precondition.negation && @precondition.preconditions?.length == 1
@conjunction = @flip_conjunction_map[@conjunction] if @parentNegation
@comments = @precondition.comments
if @precondition.reference
dataCriteria = @measure.get('data_criteria')[@precondition.reference]
@comments = _(@comments || []).union(dataCriteria?.comments || [])
translate_conjunction: (conjunction) ->
@conjunction_map[conjunction]
| 159797 | class Thorax.Views.PreconditionLogic extends Thorax.Views.BonnieView
template: JST['logic/precondition']
conjunction_map:
'allTrue':'AND'
'atLeastOneTrue':'OR'
flip_conjunction_map:
'AND': 'OR'
'OR': 'AND'
initialize: ->
@preconditionKey = "<KEY>@<KEY>condition.<KEY>
@parentPreconditionKey = "<KEY>@parentPrecondition.<KEY>
@conjunction = @translate_conjunction(@parentPrecondition.conjunction_code)
@suppress = true if @precondition.negation && @precondition.preconditions?.length == 1
@conjunction = @flip_conjunction_map[@conjunction] if @parentNegation
@comments = @precondition.comments
if @precondition.reference
dataCriteria = @measure.get('data_criteria')[@precondition.reference]
@comments = _(@comments || []).union(dataCriteria?.comments || [])
translate_conjunction: (conjunction) ->
@conjunction_map[conjunction]
| true | class Thorax.Views.PreconditionLogic extends Thorax.Views.BonnieView
template: JST['logic/precondition']
conjunction_map:
'allTrue':'AND'
'atLeastOneTrue':'OR'
flip_conjunction_map:
'AND': 'OR'
'OR': 'AND'
initialize: ->
@preconditionKey = "PI:KEY:<KEY>END_PI@PI:KEY:<KEY>END_PIcondition.PI:KEY:<KEY>END_PI
@parentPreconditionKey = "PI:KEY:<KEY>END_PI@parentPrecondition.PI:KEY:<KEY>END_PI
@conjunction = @translate_conjunction(@parentPrecondition.conjunction_code)
@suppress = true if @precondition.negation && @precondition.preconditions?.length == 1
@conjunction = @flip_conjunction_map[@conjunction] if @parentNegation
@comments = @precondition.comments
if @precondition.reference
dataCriteria = @measure.get('data_criteria')[@precondition.reference]
@comments = _(@comments || []).union(dataCriteria?.comments || [])
translate_conjunction: (conjunction) ->
@conjunction_map[conjunction]
|
[
{
"context": " if @current_suggestions[@current_highlighted_suggestion]?\n @show_suggestio",
"end": 53931,
"score": 0.6408464908599854,
"start": 53909,
"tag": "USERNAME",
"value": "highlighted_suggestion"
},
{
"context": " suggestion_to_write: @current_suggestions[@current_highlighted_suggestion] # Auto complete with the highlighted suggestion\n",
"end": 54280,
"score": 0.7323571443557739,
"start": 54250,
"tag": "USERNAME",
"value": "current_highlighted_suggestion"
},
{
"context": "ry)\n @results_view_wrapper.render_error(@query, err, true)\n @save_query\n ",
"end": 126336,
"score": 0.9974727630615234,
"start": 126330,
"tag": "USERNAME",
"value": "@query"
},
{
"context": " @parent.container.state.last_columns_size[@col_resizing] = Math.max 5, @start_width-@start_x+event.pageX ",
"end": 148312,
"score": 0.9806597828865051,
"start": 148300,
"tag": "USERNAME",
"value": "col_resizing"
},
{
"context": "izing, @parent.container.state.last_columns_size[@col_resizing] # Resize\n\n resize_column: (col, size) =>\n ",
"end": 148488,
"score": 0.9608656764030457,
"start": 148476,
"tag": "USERNAME",
"value": "col_resizing"
},
{
"context": "explorer-cursor_timed_out.hbs')\n primitive_key: '_-primitive value-_--' # We suppose that there is no key with such valu",
"end": 164822,
"score": 0.9993423819541931,
"start": 164800,
"tag": "KEY",
"value": "'_-primitive value-_--"
}
] | admin/static/coffee/dataexplorer.coffee | zadcha/rethinkdb | 21,684 | # Copyright 2010-2015 RethinkDB, all rights reserved.
app = require('./app.coffee')
system_db = app.system_db
driver = app.driver
util = require('./util.coffee')
r = require('rethinkdb')
DEFAULTS =
current_query: null
query_result: null
cursor_timed_out: true
view: 'tree'
history_state: 'hidden'
last_keys: []
last_columns_size: {}
options_state: 'hidden'
options:
suggestions: true
electric_punctuation: false
profiler: false
query_limit: 40
history: []
focus_on_codemirror: true
Object.freeze(DEFAULTS)
Object.freeze(DEFAULTS.options)
# state is initially a mutable version of defaults. It's modified later
dataexplorer_state = _.extend({}, DEFAULTS)
# This class represents the results of a query.
#
# If there is a profile, `profile` is set. After a 'ready' event,
# one of `error`, `value` or `cursor` is always set, `type`
# indicates which. `ended` indicates whether there are any more
# results to read.
#
# It triggers the following events:
# * ready: The first response has been received
# * add: Another row has been received from a cursor
# * error: An error has occurred
# * end: There are no more documents to fetch
# * discard: The results have been discarded
class QueryResult
_.extend @::, Backbone.Events
constructor: (options) ->
@has_profile = options.has_profile
@current_query = options.current_query
@raw_query = options.raw_query
@driver_handler = options.driver_handler
@ready = false
@position = 0
@server_duration = null
if options.events?
for own event, handler of options.events
@on event, handler
# Can be used as a callback to run
set: (error, result) =>
if error?
@set_error error
else if not @discard_results
if @has_profile
@profile = result.profile
@server_duration = result.profile.reduce(((total, prof) ->
total + (prof['duration(ms)'] or prof['mean_duration(ms)'])), 0)
value = result.value
else
@profile = null
@server_duration = result?.profile[0]['duration(ms)']
value = result.value
if value? and typeof value._next is 'function' and value not instanceof Array # if it's a cursor
@type = 'cursor'
@results = []
@results_offset = 0
@cursor = value
@is_feed = @cursor.toString().match(/\[object .*Feed\]/)
@missing = 0
@ended = false
@server_duration = null # ignore server time if batched response
else
@type = 'value'
@value = value
@ended = true
@ready = true
@trigger 'ready', @
# Discard the results
discard: =>
@trigger 'discard', @
@off()
@type = 'discarded'
@discard_results = true
delete @profile
delete @value
delete @results
delete @results_offset
@cursor?.close().catch?(() -> null)
delete @cursor
# Gets the next result from the cursor
fetch_next: =>
if not @ended
try
@driver_handler.cursor_next @cursor,
end: () =>
@ended = true
@trigger 'end', @
error: (error) =>
if not @ended
@set_error error
row: (row) =>
if @discard_results
return
@results.push row
@trigger 'add', @, row
catch error
@set_error error
set_error: (error) =>
@type = 'error'
@error = error
@trigger 'error', @, error
@discard_results = true
@ended = true
size: =>
switch @type
when 'value'
if @value instanceof Array
return @value.length
else
return 1
when 'cursor'
return @results.length + @results_offset
force_end_gracefully: =>
if @is_feed
@ended = true
@cursor?.close().catch(() -> null)
@trigger 'end', @
drop_before: (n) =>
if n > @results_offset
@results = @results[n - @results_offset ..]
@results_offset = n
slice: (from, to) =>
if from < 0
from = @results.length + from
else
from = from - @results_offset
from = Math.max 0, from
if to?
if to < 0
to = @results.length + to
else
to = to - @results_offset
to = Math.min @results.length, to
return @results[from .. to]
else
return @results[from ..]
at_beginning: =>
if @results_offset?
return @results_offset == 0
else
return true
class Container extends Backbone.View
id: 'dataexplorer'
template: require('../handlebars/dataexplorer_view.hbs')
input_query_template: require('../handlebars/dataexplorer_input_query.hbs')
description_template: require('../handlebars/dataexplorer-description.hbs')
template_suggestion_name: require('../handlebars/dataexplorer_suggestion_name_li.hbs')
description_with_example_template: require('../handlebars/dataexplorer-description_with_example.hbs')
alert_connection_fail_template: require('../handlebars/alert-connection_fail.hbs')
databases_suggestions_template: require('../handlebars/dataexplorer-databases_suggestions.hbs')
tables_suggestions_template: require('../handlebars/dataexplorer-tables_suggestions.hbs')
reason_dataexplorer_broken_template: require('../handlebars/dataexplorer-reason_broken.hbs')
query_error_template: require('../handlebars/dataexplorer-query_error.hbs')
# Constants
line_height: 13 # Define the height of a line (used for a line is too long)
size_history: 50
max_size_stack: 100 # If the stack of the query (including function, string, object etc. is greater than @max_size_stack, we stop parsing the query
max_size_query: 1000 # If the query is more than 1000 char, we don't show suggestion (codemirror doesn't highlight/parse if the query is more than 1000 characdd_ters too
delay_toggle_abort: 70 # If a query didn't return during this period (ms) we let people abort the query
events:
'mouseup .CodeMirror': 'handle_click'
'mousedown .suggestion_name_li': 'select_suggestion' # Keep mousedown to compete with blur on .input_query
'mouseover .suggestion_name_li' : 'mouseover_suggestion'
'mouseout .suggestion_name_li' : 'mouseout_suggestion'
'click .clear_query': 'clear_query'
'click .execute_query': 'execute_query'
'click .abort_query': 'abort_query'
'click .change_size': 'toggle_size'
'click #rerun_query': 'execute_query'
'click .close': 'close_alert'
'click .clear_queries_link': 'clear_history_view'
'click .close_queries_link': 'toggle_history'
'click .toggle_options_link': 'toggle_options'
'mousedown .nano_border_bottom': 'start_resize_history'
# Let people click on the description and select text
'mousedown .suggestion_description': 'mouse_down_description'
'click .suggestion_description': 'stop_propagation'
'mouseup .suggestion_description': 'mouse_up_description'
'mousedown .suggestion_full_container': 'mouse_down_description'
'click .suggestion_full_container': 'stop_propagation'
'mousedown .CodeMirror': 'mouse_down_description'
'click .CodeMirror': 'stop_propagation'
mouse_down_description: (event) =>
@keep_suggestions_on_blur = true
@stop_propagation event
stop_propagation: (event) =>
event.stopPropagation()
mouse_up_description: (event) =>
@keep_suggestions_on_blur = false
@stop_propagation event
start_resize_history: (event) =>
@history_view.start_resize event
clear_history_view: (event) =>
that = @
@clear_history() # Delete from localstorage
@history_view.clear_history event
# Method that make sure that just one button (history or option) is active
# We give this button an "active" class that make it looks like it's pressed.
toggle_pressed_buttons: =>
if @history_view.state is 'visible'
dataexplorer_state.history_state = 'visible'
@$('.clear_queries_link').fadeIn 'fast'
@$('.close_queries_link').addClass 'active'
else
dataexplorer_state.history_state = 'hidden'
@$('.clear_queries_link').fadeOut 'fast'
@$('.close_queries_link').removeClass 'active'
if @options_view.state is 'visible'
dataexplorer_state.options_state = 'visible'
@$('.toggle_options_link').addClass 'active'
else
dataexplorer_state.options_state = 'hidden'
@$('.toggle_options_link').removeClass 'active'
# Show/hide the history view
toggle_history: (args) =>
that = @
@deactivate_overflow()
if args.no_animation is true
# We just show the history
@history_view.state = 'visible'
@$('.content').html @history_view.render(true).$el
@move_arrow
type: 'history'
move_arrow: 'show'
@adjust_collapsible_panel_height
no_animation: true
is_at_bottom: true
else if @options_view.state is 'visible'
@options_view.state = 'hidden'
@move_arrow
type: 'history'
move_arrow: 'animate'
@options_view.$el.fadeOut 'fast', ->
that.$('.content').html that.history_view.render(false).$el
that.history_view.state = 'visible'
that.history_view.$el.fadeIn 'fast'
that.adjust_collapsible_panel_height
is_at_bottom: true
that.toggle_pressed_buttons() # Re-execute toggle_pressed_buttons because we delay the fadeIn
else if @history_view.state is 'hidden'
@history_view.state = 'visible'
@$('.content').html @history_view.render(true).$el
@history_view.delegateEvents()
@move_arrow
type: 'history'
move_arrow: 'show'
@adjust_collapsible_panel_height
is_at_bottom: true
else if @history_view.state is 'visible'
@history_view.state = 'hidden'
@hide_collapsible_panel 'history'
@toggle_pressed_buttons()
# Show/hide the options view
toggle_options: (args) =>
that = @
@deactivate_overflow()
if args?.no_animation is true
@options_view.state = 'visible'
@$('.content').html @options_view.render(true).$el
@options_view.delegateEvents()
@move_arrow
type: 'options'
move_arrow: 'show'
@adjust_collapsible_panel_height
no_animation: true
is_at_bottom: true
else if @history_view.state is 'visible'
@history_view.state = 'hidden'
@move_arrow
type: 'options'
move_arrow: 'animate'
@history_view.$el.fadeOut 'fast', ->
that.$('.content').html that.options_view.render(false).$el
that.options_view.state = 'visible'
that.options_view.$el.fadeIn 'fast'
that.adjust_collapsible_panel_height()
that.toggle_pressed_buttons()
that.$('.profiler_enabled').css 'visibility', 'hidden'
that.$('.profiler_enabled').hide()
else if @options_view.state is 'hidden'
@options_view.state = 'visible'
@$('.content').html @options_view.render(true).$el
@options_view.delegateEvents()
@move_arrow
type: 'options'
move_arrow: 'show'
@adjust_collapsible_panel_height
cb: args?.cb
else if @options_view.state is 'visible'
@options_view.state = 'hidden'
@hide_collapsible_panel 'options'
@toggle_pressed_buttons()
# Hide the collapsible_panel whether it contains the option or history view
hide_collapsible_panel: (type) =>
that = @
@deactivate_overflow()
@$('.nano').animate
height: 0
, 200
, ->
that.activate_overflow()
# We don't want to hide the view if the user changed the state of the view while it was being animated
if (type is 'history' and that.history_view.state is 'hidden') or (type is 'options' and that.options_view.state is 'hidden')
that.$('.nano_border').hide() # In case the user trigger hide/show really fast
that.$('.arrow_dataexplorer').hide() # In case the user trigger hide/show really fast
that.$(@).css 'visibility', 'hidden'
@$('.nano_border').slideUp 'fast'
@$('.arrow_dataexplorer').slideUp 'fast'
# Move the arrow that points to the active button (on top of the collapsible panel). In case the user switch from options to history (or the opposite), we need to animate it
move_arrow: (args) =>
# args =
# type: 'options'/'history'
# move_arrow: 'show'/'animate'
if args.type is 'options'
margin_right = 74
else if args.type is 'history'
margin_right = 154
if args.move_arrow is 'show'
@$('.arrow_dataexplorer').css 'margin-right', margin_right
@$('.arrow_dataexplorer').show()
else if args.move_arrow is 'animate'
@$('.arrow_dataexplorer').animate
'margin-right': margin_right
, 200
@$('.nano_border').show()
# Adjust the height of the container of the history/option view
# Arguments:
# size: size of the collapsible panel we want // If not specified, we are going to try to figure it out ourselves
# no_animation: boolean (do we need to animate things or just to show it)
# is_at_bottom: boolean (if we were at the bottom, we want to scroll down once we have added elements in)
# delay_scroll: boolean, true if we just added a query - It speficied if we adjust the height then scroll or do both at the same time
adjust_collapsible_panel_height: (args) =>
that = @
if args?.size?
size = args.size
else
if args?.extra?
size = Math.min @$('.content > div').height()+args.extra, @history_view.height_history
else
size = Math.min @$('.content > div').height(), @history_view.height_history
@deactivate_overflow()
duration = Math.max 150, size
duration = Math.min duration, 250
#@$('.nano').stop(true, true).animate
@$('.nano').css 'visibility', 'visible' # In case the user trigger hide/show really fast
if args?.no_animation is true
@$('.nano').height size
@$('.nano > .content').scrollTop @$('.nano > .content > div').height()
@$('.nano').css 'visibility', 'visible' # In case the user trigger hide/show really fast
@$('.arrow_dataexplorer').show() # In case the user trigger hide/show really fast
@$('.nano_border').show() # In case the user trigger hide/show really fast
if args?.no_animation is true
@$('.nano').nanoScroller({preventPageScrolling: true})
@activate_overflow()
else
@$('.nano').animate
height: size
, duration
, ->
that.$(@).css 'visibility', 'visible' # In case the user trigger hide/show really fast
that.$('.arrow_dataexplorer').show() # In case the user trigger hide/show really fast
that.$('.nano_border').show() # In case the user trigger hide/show really fast
that.$(@).nanoScroller({preventPageScrolling: true})
that.activate_overflow()
if args? and args.delay_scroll is true and args.is_at_bottom is true
that.$('.nano > .content').animate
scrollTop: that.$('.nano > .content > div').height()
, 200
if args?.cb?
args.cb()
if args? and args.delay_scroll isnt true and args.is_at_bottom is true
that.$('.nano > .content').animate
scrollTop: that.$('.nano > .content > div').height()
, 200
# We deactivate the scrollbar (if there isn't) while animating to have a smoother experience. We´ll put back the scrollbar once the animation is done.
deactivate_overflow: =>
if $(window).height() >= $(document).height()
$('body').css 'overflow', 'hidden'
activate_overflow: =>
$('body').css 'overflow', 'auto'
displaying_full_view: false # Boolean for the full view (true if full view)
# Method to close an alert/warning/arror
close_alert: (event) ->
event.preventDefault()
$(event.currentTarget).parent().slideUp('fast', -> $(this).remove())
# Build the suggestions
map_state: # Map function -> state
'': ''
descriptions: {}
suggestions: {} # Suggestions[state] = function for this state
types:
value: ['number', 'bool', 'string', 'array', 'object', 'time', 'binary', 'line', 'point', 'polygon']
any: ['number', 'bool', 'string', 'array', 'object', 'stream', 'selection', 'table', 'db', 'r', 'error', 'binary', 'line', 'point', 'polygon']
geometry: ['line', 'point', 'polygon']
sequence: ['table', 'selection', 'stream', 'array']
stream: ['table', 'selection']
grouped_stream: ['stream', 'array']
# Convert meta types (value, any or sequence) to an array of types or return an array composed of just the type
convert_type: (type) =>
if @types[type]?
return @types[type]
else
return [type]
# Flatten an array
expand_types: (ar) =>
result = []
if _.isArray(ar)
for element in ar
result.concat @convert_type element
else
result.concat @convert_type element
return result
# Once we are done moving the doc, we could generate a .js in the makefile file with the data so we don't have to do an ajax request+all this stuff
set_doc_description: (command, tag, suggestions) =>
if command['body']?
# The body of `bracket` uses `()` and not `bracket()`
# so we manually set the variables dont_need_parenthesis and full_tag
if tag is 'bracket'
dont_need_parenthesis = false
full_tag = tag+'('
else
dont_need_parenthesis = not (new RegExp(tag+'\\(')).test(command['body'])
if dont_need_parenthesis
full_tag = tag # Here full_tag is just the name of the tag
else
full_tag = tag+'(' # full tag is the name plus a parenthesis (we will match the parenthesis too)
@descriptions[full_tag] = (grouped_data) =>
name: tag
args: /.*(\(.*\))/.exec(command['body'])?[1]
description:
@description_with_example_template
description: command['description']
example: command['example']
grouped_data: grouped_data is true and full_tag isnt 'group(' and full_tag isnt 'ungroup('
parents = {}
returns = []
for pair in command.io ? []
parent_values = if (pair[0] == null) then '' else pair[0]
return_values = pair[1]
parent_values = @convert_type parent_values
return_values = @convert_type return_values
returns = returns.concat return_values
for parent_value in parent_values
parents[parent_value] = true
if full_tag isnt '('
for parent_value of parents
if not suggestions[parent_value]?
suggestions[parent_value] = []
suggestions[parent_value].push full_tag
@map_state[full_tag] = returns # We use full_tag because we need to differentiate between r. and r(
# All the commands we are going to ignore
ignored_commands:
'connect': true
'close': true
'reconnect': true
'use': true
'runp': true
'next': true
'collect': true
'run': true
'EventEmitter\'s methods': true
# Method called on the content of reql_docs.json
# Load the suggestions in @suggestions, @map_state, @descriptions
set_docs: (data) =>
for key of data
command = data[key]
tag = command['name']
if tag of @ignored_commands
continue
if tag is '() (bracket)' # The parentheses will be added later
# Add `(attr)`
tag = ''
@set_doc_description command, tag, @suggestions
# Add `bracket(sttr)`
tag = 'bracket'
else if tag is 'toJsonString, toJSON'
# Add the `toJsonString()` alias
tag = 'toJsonString'
@set_doc_description command, tag, @suggestions
# Also add `toJSON()`
tag = 'toJSON'
@set_doc_description command, tag, @suggestions
relations = data['types']
for state of @suggestions
@suggestions[state].sort()
if Container.prototype.focus_on_codemirror is true
# "@" refers to prototype -_-
# In case we give focus to codemirror then load the docs, we show the suggestion
app.main.router.current_view.handle_keypress()
# Save the query in the history
# The size of the history is infinite per session. But we will just save @size_history queries in localStorage
save_query: (args) =>
query = args.query
broken_query = args.broken_query
# Remove empty lines
query = query.replace(/^\s*$[\n\r]{1,}/gm, '')
query = query.replace(/\s*$/, '') # Remove the white spaces at the end of the query (like newline/space/tab)
if window.localStorage?
if dataexplorer_state.history.length is 0 or dataexplorer_state.history[dataexplorer_state.history.length-1].query isnt query and @regex.white.test(query) is false
dataexplorer_state.history.push
query: query
broken_query: broken_query
if dataexplorer_state.history.length>@size_history
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history.slice dataexplorer_state.history.length-@size_history
else
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history
@history_view.add_query
query: query
broken_query: broken_query
clear_history: =>
dataexplorer_state.history.length = 0
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history
# Save the current query (the one in codemirror) in local storage
save_current_query: =>
if window.localStorage?
window.localStorage.current_query = JSON.stringify @codemirror.getValue()
initialize: (args) =>
@TermBaseConstructor = r.expr(1).constructor.__super__.constructor.__super__.constructor
@state = args.state
@executing = false
# Load options from local storage
if window.localStorage?
try
@state.options = JSON.parse(window.localStorage.options)
# Ensure no keys are without a default value in the
# options object
_.defaults(@state.options, DEFAULTS.options)
catch err
window.localStorage.removeItem 'options'
# Whatever the case with default values, we need to sync
# up with the current application's idea of the options
window.localStorage.options = JSON.stringify(@state.options)
# Load the query that was written in code mirror (that may not have been executed before)
if typeof window.localStorage?.current_query is 'string'
try
dataexplorer_state.current_query = JSON.parse window.localStorage.current_query
catch err
window.localStorage.removeItem 'current_query'
if window.localStorage?.rethinkdb_history?
try
dataexplorer_state.history = JSON.parse window.localStorage.rethinkdb_history
catch err
window.localStorage.removeItem 'rethinkdb_history'
@query_has_changed = dataexplorer_state.query_result?.current_query isnt dataexplorer_state.current_query
# Index used to navigate through history with the keyboard
@history_displayed_id = 0 # 0 means we are showing the draft, n>0 means we are showing the nth query in the history
# We escape the last function because we are building a regex on top of it.
# Structure: [ [ pattern, replacement], [pattern, replacement], ... ]
@unsafe_to_safe_regexstr = [
[/\\/g, '\\\\'] # This one has to be first
[/\(/g, '\\(']
[/\)/g, '\\)']
[/\^/g, '\\^']
[/\$/g, '\\$']
[/\*/g, '\\*']
[/\+/g, '\\+']
[/\?/g, '\\?']
[/\./g, '\\.']
[/\|/g, '\\|']
[/\{/g, '\\{']
[/\}/g, '\\}']
[/\[/g, '\\[']
]
@results_view_wrapper = new ResultViewWrapper
container: @
view: dataexplorer_state.view
@options_view = new OptionsView
container: @
options: dataexplorer_state.options
@history_view = new HistoryView
container: @
history: dataexplorer_state.history
@driver_handler = new DriverHandler
container: @
# These events were caught here to avoid being bound and unbound every time
# The results changed. It should ideally be caught in the individual result views
# that actually need it.
$(window).mousemove @handle_mousemove
$(window).mouseup @handle_mouseup
$(window).mousedown @handle_mousedown
@keep_suggestions_on_blur = false
@databases_available = {}
@fetch_data()
fetch_data: =>
# We fetch all "proper" tables from `table_config`. In addition, we need
# to fetch the list of system tables separately.
query = r.db(system_db).table('table_config')
.pluck('db', 'name')
.group('db')
.ungroup()
.map((group) -> [group("group"), group("reduction")("name").orderBy( (x) -> x )])
.coerceTo "OBJECT"
.merge(r.object(system_db, r.db(system_db).tableList().coerceTo("ARRAY")))
@timer = driver.run query, 5000, (error, result) =>
if error?
# Nothing bad, we'll try again, let's just log the error
console.log "Error: Could not fetch databases and tables"
console.log error
else
@databases_available = result
handle_mousemove: (event) =>
@results_view_wrapper.handle_mousemove event
@history_view.handle_mousemove event
handle_mouseup: (event) =>
@results_view_wrapper.handle_mouseup event
@history_view.handle_mouseup event
handle_mousedown: (event) =>
# $(window) caught a mousedown event, so it wasn't caught by $('.suggestion_description')
# Let's hide the suggestion/description
@keep_suggestions_on_blur = false
@hide_suggestion_and_description()
render: =>
@$el.html @template()
@$('.input_query_full_container').html @input_query_template()
# Check if the browser supports the JavaScript driver
# We do not support internet explorer (even IE 10) and old browsers.
if navigator?.appName is 'Microsoft Internet Explorer'
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
is_internet_explorer: true
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
else if (not DataView?) or (not Uint8Array?) # The main two components that the javascript driver requires.
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
else if not r? # In case the javascript driver is not found (if build from source for example)
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
no_driver: true
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
# Let's bring back the data explorer to its old state (if there was)
if dataexplorer_state?.query_result?
@results_view_wrapper.set_query_result
query_result: dataexplorer_state.query_result
@$('.results_container').html @results_view_wrapper.render(query_has_changed: @query_has_changed).$el
# The query in code mirror is set in init_after_dom_rendered (because we can't set it now)
return @
# This method has to be called AFTER the el element has been inserted in the DOM tree, mostly for codemirror
init_after_dom_rendered: =>
@codemirror = CodeMirror.fromTextArea document.getElementById('input_query'),
mode:
name: 'javascript'
onKeyEvent: @handle_keypress
lineNumbers: true
lineWrapping: true
matchBrackets: true
tabSize: 2
@codemirror.on 'blur', @on_blur
@codemirror.on 'gutterClick', @handle_gutter_click
@codemirror.setSize '100%', 'auto'
if dataexplorer_state.current_query?
@codemirror.setValue dataexplorer_state.current_query
@codemirror.focus() # Give focus
# Track if the focus is on codemirror
# We use it to refresh the docs once the reql_docs.json is loaded
dataexplorer_state.focus_on_codemirror = true
@codemirror.setCursor @codemirror.lineCount(), 0
if @codemirror.getValue() is '' # We show suggestion for an empty query only
@handle_keypress()
@results_view_wrapper.init_after_dom_rendered()
@draft = @codemirror.getValue()
if dataexplorer_state.history_state is 'visible' # If the history was visible, we show it
@toggle_history
no_animation: true
if dataexplorer_state.options_state is 'visible' # If the history was visible, we show it
@toggle_options
no_animation: true
on_blur: =>
dataexplorer_state.focus_on_codemirror = false
# We hide the description only if the user isn't selecting text from a description.
if @keep_suggestions_on_blur is false
@hide_suggestion_and_description()
# We have to keep track of a lot of things because web-kit browsers handle the events keydown, keyup, blur etc... in a strange way.
current_suggestions: []
current_highlighted_suggestion: -1
current_conpleted_query: ''
query_first_part: ''
query_last_part: ''
mouse_type_event:
click: true
dblclick: true
mousedown: true
mouseup: true
mouseover: true
mouseout: true
mousemove: true
char_breakers:
'.': true
'}': true
')': true
',': true
';': true
']': true
handle_click: (event) =>
@handle_keypress null, event
# Pair ', ", {, [, (
# Return true if we want code mirror to ignore the key event
pair_char: (event, stack) =>
if event?.which?
# If there is a selection and the user hit a quote, we wrap the seleciton in quotes
if @codemirror.getSelection() isnt '' and event.type is 'keypress' # This is madness. If we look for keydown, shift+right arrow match a single quote...
char_to_insert = String.fromCharCode event.which
if char_to_insert? and char_to_insert is '"' or char_to_insert is "'"
@codemirror.replaceSelection(char_to_insert+@codemirror.getSelection()+char_to_insert)
event.preventDefault()
return true
if event.which is 8 # Backspace
if event.type isnt 'keydown'
return true
previous_char = @get_previous_char()
if previous_char is null
return true
# If the user remove the opening bracket and the next char is the closing bracket, we delete both
if previous_char of @matching_opening_bracket
next_char = @get_next_char()
if next_char is @matching_opening_bracket[previous_char]
num_not_closed_bracket = @count_not_closed_brackets previous_char
if num_not_closed_bracket <= 0
@remove_next()
return true
# If the user remove the first quote of an empty string, we remove both quotes
else if previous_char is '"' or previous_char is "'"
next_char = @get_next_char()
if next_char is previous_char and @get_previous_char(2) isnt '\\'
num_quote = @count_char char_to_insert
if num_quote%2 is 0
@remove_next()
return true
return true
if event.type isnt 'keypress' # We catch keypress because single and double quotes have not the same keyCode on keydown/keypres #thisIsMadness
return true
char_to_insert = String.fromCharCode event.which
if char_to_insert? # and event.which isnt 91 # 91 map to [ on OS X
if @codemirror.getSelection() isnt ''
if (char_to_insert of @matching_opening_bracket or char_to_insert of @matching_closing_bracket)
@codemirror.replaceSelection ''
else
return true
last_element_incomplete_type = @last_element_type_if_incomplete(stack)
if char_to_insert is '"' or char_to_insert is "'"
num_quote = @count_char char_to_insert
next_char = @get_next_char()
if next_char is char_to_insert # Next char is a single quote
if num_quote%2 is 0
if last_element_incomplete_type is 'string' or last_element_incomplete_type is 'object_key' # We are at the end of a string and the user just wrote a quote
@move_cursor 1
event.preventDefault()
return true
else
# We are at the begining of a string, so let's just add one quote
return true
else
# Let's add the closing/opening quote missing
return true
else
if num_quote%2 is 0 # Next char is not a single quote and the user has an even number of quotes.
# Let's keep a number of quote even, so we add one extra quote
last_key = @get_last_key(stack)
if last_element_incomplete_type is 'string'
return true
else if last_element_incomplete_type is 'object_key' and (last_key isnt '' and @create_safe_regex(char_to_insert).test(last_key) is true) # A key in an object can be seen as a string
return true
else
@insert_next char_to_insert
else # Else we'll just insert one quote
return true
else if last_element_incomplete_type isnt 'string'
next_char = @get_next_char()
if char_to_insert of @matching_opening_bracket
num_not_closed_bracket = @count_not_closed_brackets char_to_insert
if num_not_closed_bracket >= 0 # We insert a closing bracket only if it help having a balanced number of opened/closed brackets
@insert_next @matching_opening_bracket[char_to_insert]
return true
return true
else if char_to_insert of @matching_closing_bracket
opening_char = @matching_closing_bracket[char_to_insert]
num_not_closed_bracket = @count_not_closed_brackets opening_char
if next_char is char_to_insert
if num_not_closed_bracket <= 0 # g(f(...|) In this case we add a closing parenthesis. Same behavior as in Ace
@move_cursor 1
event.preventDefault()
return true
return false
get_next_char: =>
cursor_end = @codemirror.getCursor()
cursor_end.ch++
return @codemirror.getRange @codemirror.getCursor(), cursor_end
get_previous_char: (less_value) =>
cursor_start = @codemirror.getCursor()
cursor_end = @codemirror.getCursor()
if less_value?
cursor_start.ch -= less_value
cursor_end.ch -= (less_value-1)
else
cursor_start.ch--
if cursor_start.ch < 0
return null
return @codemirror.getRange cursor_start, cursor_end
# Insert str after the cursor in codemirror
insert_next: (str) =>
@codemirror.replaceRange str, @codemirror.getCursor()
@move_cursor -1
remove_next: =>
end_cursor = @codemirror.getCursor()
end_cursor.ch++
@codemirror.replaceRange '', @codemirror.getCursor(), end_cursor
# Move cursor of move_value
# A negative value move the cursor to the left
move_cursor: (move_value) =>
cursor = @codemirror.getCursor()
cursor.ch += move_value
if cursor.ch < 0
cursor.ch = 0
@codemirror.setCursor cursor
# Count how many time char_to_count appeared ignoring strings and comments
count_char: (char_to_count) =>
query = @codemirror.getValue()
is_parsing_string = false
to_skip = 0
result = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
if char is char_to_count
result++
else # if element.is_parsing_string is false
if char is char_to_count
result++
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
return result
matching_opening_bracket:
'(': ')'
'{': '}'
'[': ']'
matching_closing_bracket:
')': '('
'}': '{'
']': '['
# opening_char has to be in @matching_bracket
# Count how many time opening_char has been opened but not closed
# A result < 0 means that the closing char has been found more often than the opening one
count_not_closed_brackets: (opening_char) =>
query = @codemirror.getValue()
is_parsing_string = false
to_skip = 0
result = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
else # if element.is_parsing_string is false
if char is opening_char
result++
else if char is @matching_opening_bracket[opening_char]
result--
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
return result
# Handle events on codemirror
# Return true if we want code mirror to ignore the event
handle_keypress: (editor, event) =>
if @ignored_next_keyup is true
if event?.type is 'keyup' and event?.which isnt 9
@ignored_next_keyup = false
return true
dataexplorer_state.focus_on_codemirror = true
# Let's hide the tooltip if the user just clicked on the textarea. We'll only display later the suggestions if there are (no description)
if event?.type is 'mouseup'
@hide_suggestion_and_description()
# Save the last query (even incomplete)
dataexplorer_state.current_query = @codemirror.getValue()
@save_current_query()
# Look for special commands
if event?.which?
if event.type isnt 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32)
# Because on event.type == 'keydown' we are going to change the state (hidden or displayed) of @$('.suggestion_description') and @$('.suggestion_name_list'), we don't want to fire this event a second time
return true
if event.which is 27 or (event.type is 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32) and (@$('.suggestion_description').css('display') isnt 'none' or @$('.suggestion_name_list').css('display') isnt 'none'))
# We caugh ESC or (Ctrl/Cmd+space with suggestion/description being displayed)
event.preventDefault() # Keep focus on code mirror
@hide_suggestion_and_description()
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
query_after_cursor = @codemirror.getRange @codemirror.getCursor(), {line:@codemirror.lineCount()+1, ch: 0}
# Compute the structure of the query written by the user.
# We compute it earlier than before because @pair_char also listen on keydown and needs stack
stack = @extract_data_from_query
size_stack: 0
query: query_before_cursor
position: 0
if stack is null # Stack is null if the query was too big for us to parse
@ignore_tab_keyup = false
@hide_suggestion_and_description()
return false
@current_highlighted_suggestion = -1
@current_highlighted_extra_suggestion = -1
@$('.suggestion_name_list').empty()
# Valid step, let's save the data
@query_last_part = query_after_cursor
@current_suggestions = []
@current_element = ''
@current_extra_suggestion = ''
@written_suggestion = null
@cursor_for_auto_completion = @codemirror.getCursor()
@description = null
result =
status: null
# create_suggestion is going to fill to_complete and to_describe
#to_complete: undefined
#to_describe: undefined
# Create the suggestion/description
@create_suggestion
stack: stack
query: query_before_cursor
result: result
result.suggestions = @uniq result.suggestions
@grouped_data = @count_group_level(stack).count_group > 0
if result.suggestions?.length > 0
for suggestion, i in result.suggestions
if suggestion isnt 'ungroup(' or @grouped_data is true # We add the suggestion for `ungroup` only if we are in a group_stream/data (using the flag @grouped_data)
result.suggestions.sort() # We could eventually sort things earlier with a merge sort but for now that should be enough
@current_suggestions.push suggestion
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
else if result.description?
@description = result.description
return true
else if event.which is 13 and (event.shiftKey is false and event.ctrlKey is false and event.metaKey is false)
if event.type is 'keydown'
if @current_highlighted_suggestion > -1
event.preventDefault()
@handle_keypress()
return true
previous_char = @get_previous_char()
if previous_char of @matching_opening_bracket
next_char = @get_next_char()
if @matching_opening_bracket[previous_char] is next_char
cursor = @codemirror.getCursor()
@insert_next '\n'
@codemirror.indentLine cursor.line+1, 'smart'
@codemirror.setCursor cursor
return false
else if (event.which is 9 and event.ctrlKey is false) or (event.type is 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32) and (@$('.suggestion_description').css('display') is 'none' and @.$('.suggestion_name_list').css('display') is 'none'))
# If the user just hit tab, we are going to show the suggestions if they are hidden
# or if they suggestions are already shown, we are going to cycle through them.
#
# If the user just hit Ctrl/Cmd+space with suggestion/description being hidden we show the suggestions
# Note that the user cannot cycle through suggestions because we make sure in the IF condition that suggestion/description are hidden
# If the suggestions/description are visible, the event will be caught earlier with ESC
event.preventDefault()
if event.type isnt 'keydown'
return false
else
if @current_suggestions?.length > 0
if @$('.suggestion_name_list').css('display') is 'none'
@show_suggestion()
return true
else
# We can retrieve the content of codemirror only on keyup events. The users may write "r." then hit "d" then "tab" If the events are triggered this way
# keydown d - keydown tab - keyup d - keyup tab
# We want to only show the suggestions for r.d
if @written_suggestion is null
cached_query = @query_first_part+@current_element+@query_last_part
else
cached_query = @query_first_part+@written_suggestion+@query_last_part
if cached_query isnt @codemirror.getValue() # We fired a keydown tab before a keyup, so our suggestions are not up to date
@current_element = @codemirror.getValue().slice @query_first_part.length, @codemirror.getValue().length-@query_last_part.length
regex = @create_safe_regex @current_element
new_suggestions = []
new_highlighted_suggestion = -1
for suggestion, index in @current_suggestions
if index < @current_highlighted_suggestion
new_highlighted_suggestion = new_suggestions.length
if regex.test(suggestion) is true
new_suggestions.push suggestion
@current_suggestions = new_suggestions
@current_highlighted_suggestion = new_highlighted_suggestion
if @current_suggestions.length > 0
@$('.suggestion_name_list').empty()
for suggestion, i in @current_suggestions
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
@ignored_next_keyup = true
else
@hide_suggestion_and_description()
# Switch throught the suggestions
if event.shiftKey
@current_highlighted_suggestion--
if @current_highlighted_suggestion < -1
@current_highlighted_suggestion = @current_suggestions.length-1
else if @current_highlighted_suggestion < 0
@show_suggestion_without_moving()
@remove_highlight_suggestion()
@write_suggestion
suggestion_to_write: @current_element
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
return true
else
@current_highlighted_suggestion++
if @current_highlighted_suggestion >= @current_suggestions.length
@show_suggestion_without_moving()
@remove_highlight_suggestion()
@write_suggestion
suggestion_to_write: @current_element
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
@current_highlighted_suggestion = -1
return true
if @current_suggestions[@current_highlighted_suggestion]?
@show_suggestion_without_moving()
@highlight_suggestion @current_highlighted_suggestion # Highlight the current suggestion
@write_suggestion
suggestion_to_write: @current_suggestions[@current_highlighted_suggestion] # Auto complete with the highlighted suggestion
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
return true
else if @description?
if @$('.suggestion_description').css('display') is 'none'
# We show it once only because we don't want to move the cursor around
@show_description()
return true
if @extra_suggestions? and @extra_suggestions.length > 0 and @extra_suggestion.start_body is @extra_suggestion.start_body
# Trim suggestion
if @extra_suggestion?.body?[0]?.type is 'string'
if @extra_suggestion.body[0].complete is true
@extra_suggestions = []
else
# Remove quotes around the table/db name
current_name = @extra_suggestion.body[0].name.replace(/^\s*('|")/, '').replace(/('|")\s*$/, '')
regex = @create_safe_regex current_name
new_extra_suggestions = []
for suggestion in @extra_suggestions
if regex.test(suggestion) is true
new_extra_suggestions.push suggestion
@extra_suggestions = new_extra_suggestions
if @extra_suggestions.length > 0 # If there are still some valid suggestions
query = @codemirror.getValue()
# We did not parse what is after the cursor, so let's take a look
start_search = @extra_suggestion.start_body
if @extra_suggestion.body?[0]?.name.length?
start_search += @extra_suggestion.body[0].name.length
# Define @query_first_part and @query_last_part
# Note that ) is not a valid character for a db/table name
end_body = query.indexOf ')', start_search
@query_last_part = ''
if end_body isnt -1
@query_last_part = query.slice end_body
@query_first_part = query.slice 0, @extra_suggestion.start_body
lines = @query_first_part.split('\n')
if event.shiftKey is true
@current_highlighted_extra_suggestion--
else
@current_highlighted_extra_suggestion++
if @current_highlighted_extra_suggestion >= @extra_suggestions.length
@current_highlighted_extra_suggestion = -1
else if @current_highlighted_extra_suggestion < -1
@current_highlighted_extra_suggestion = @extra_suggestions.length-1
# Create the next suggestion
suggestion = ''
if @current_highlighted_extra_suggestion is -1
if @current_extra_suggestion?
if /^\s*'/.test(@current_extra_suggestion) is true
suggestion = @current_extra_suggestion+"'"
else if /^\s*"/.test(@current_extra_suggestion) is true
suggestion = @current_extra_suggestion+'"'
else
if dataexplorer_state.options.electric_punctuation is false
move_outside = true
if /^\s*'/.test(@current_extra_suggestion) is true
string_delimiter = "'"
else if /^\s*"/.test(@current_extra_suggestion) is true
string_delimiter = '"'
else
string_delimiter = "'"
move_outside = true
suggestion = string_delimiter+@extra_suggestions[@current_highlighted_extra_suggestion]+string_delimiter
@write_suggestion
move_outside: move_outside
suggestion_to_write: suggestion
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
# If the user hit enter and (Ctrl or Shift)
if event.which is 13 and (event.shiftKey or event.ctrlKey or event.metaKey)
@hide_suggestion_and_description()
event.preventDefault()
if event.type isnt 'keydown'
return true
@execute_query()
return true
# Ctrl/Cmd + V
else if (event.ctrlKey or event.metaKey) and event.which is 86 and event.type is 'keydown'
@last_action_is_paste = true
@num_released_keys = 0 # We want to know when the user release Ctrl AND V
if event.metaKey
@num_released_keys++ # Because on OS X, the keyup event is not fired when the metaKey is pressed (true for Firefox, Chrome, Safari at least...)
@hide_suggestion_and_description()
return true
# When the user release Ctrl/Cmd after a Ctrl/Cmd + V
else if event.type is 'keyup' and @last_action_is_paste is true and (event.which is 17 or event.which is 91)
@num_released_keys++
if @num_released_keys is 2
@last_action_is_paste = false
@hide_suggestion_and_description()
return true
# When the user release V after a Ctrl/Cmd + V
else if event.type is 'keyup' and @last_action_is_paste is true and event.which is 86
@num_released_keys++
if @num_released_keys is 2
@last_action_is_paste = false
@hide_suggestion_and_description()
return true
# Catching history navigation
else if event.type is 'keyup' and event.altKey and event.which is 38 # Key up
if @history_displayed_id < dataexplorer_state.history.length
@history_displayed_id++
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if event.type is 'keyup' and event.altKey and event.which is 40 # Key down
if @history_displayed_id > 1
@history_displayed_id--
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if @history_displayed_id is 1
@history_displayed_id--
@codemirror.setValue @draft
@codemirror.setCursor @codemirror.lineCount(), 0 # We hit the draft and put the cursor at the end
else if event.type is 'keyup' and event.altKey and event.which is 33 # Page up
@history_displayed_id = dataexplorer_state.history.length
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if event.type is 'keyup' and event.altKey and event.which is 34 # Page down
@history_displayed_id = @history.length
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
@codemirror.setCursor @codemirror.lineCount(), 0 # We hit the draft and put the cursor at the end
event.preventDefault()
return true
# If there is a hilighted suggestion, we want to catch enter
if @$('.suggestion_name_li_hl').length > 0
if event?.which is 13
event.preventDefault()
@handle_keypress()
return true
# We are scrolling in history
if @history_displayed_id isnt 0 and event?
# We catch ctrl, shift, alt and command
if event.ctrlKey or event.shiftKey or event.altKey or event.which is 16 or event.which is 17 or event.which is 18 or event.which is 20 or (event.which is 91 and event.type isnt 'keypress') or event.which is 92 or event.type of @mouse_type_event
return false
# We catch ctrl, shift, alt and command but don't look for active key (active key here refer to ctrl, shift, alt being pressed and hold)
if event? and (event.which is 16 or event.which is 17 or event.which is 18 or event.which is 20 or (event.which is 91 and event.type isnt 'keypress') or event.which is 92)
return false
# Avoid arrows+home+end+page down+pageup
# if event? and (event.which is 24 or event.which is ..)
# 0 is for firefox...
if not event? or (event.which isnt 37 and event.which isnt 38 and event.which isnt 39 and event.which isnt 40 and event.which isnt 33 and event.which isnt 34 and event.which isnt 35 and event.which isnt 36 and event.which isnt 0)
@history_displayed_id = 0
@draft = @codemirror.getValue()
# The expensive operations are coming. If the query is too long, we just don't parse the query
if @codemirror.getValue().length > @max_size_query
# Return true or false will break the event propagation
return undefined
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
query_after_cursor = @codemirror.getRange @codemirror.getCursor(), {line:@codemirror.lineCount()+1, ch: 0}
# Compute the structure of the query written by the user.
# We compute it earlier than before because @pair_char also listen on keydown and needs stack
stack = @extract_data_from_query
size_stack: 0
query: query_before_cursor
position: 0
if stack is null # Stack is null if the query was too big for us to parse
@ignore_tab_keyup = false
@hide_suggestion_and_description()
return false
if dataexplorer_state.options.electric_punctuation is true
@pair_char(event, stack) # Pair brackets/quotes
# We just look at key up so we don't fire the call 3 times
if event?.type? and event.type isnt 'keyup' and event.which isnt 9 and event.type isnt 'mouseup'
return false
if event?.which is 16 # We don't do anything with Shift.
return false
# Tab is an exception, we let it pass (tab bring back suggestions) - What we want is to catch keydown
if @ignore_tab_keyup is true and event?.which is 9
if event.type is 'keyup'
@ignore_tab_keyup = false
return true
@current_highlighted_suggestion = -1
@current_highlighted_extra_suggestion = -1
@$('.suggestion_name_list').empty()
# Valid step, let's save the data
@query_last_part = query_after_cursor
# If a selection is active, we just catch shift+enter
if @codemirror.getSelection() isnt ''
@hide_suggestion_and_description()
if event? and event.which is 13 and (event.shiftKey or event.ctrlKey or event.metaKey) # If the user hit enter and (Ctrl or Shift or Cmd)
@hide_suggestion_and_description()
if event.type isnt 'keydown'
return true
@execute_query()
return true # We do not replace the selection with a new line
# If the user select something and end somehwere with suggestion
if event?.type isnt 'mouseup'
return false
else
return true
@current_suggestions = []
@current_element = ''
@current_extra_suggestion = ''
@written_suggestion = null
@cursor_for_auto_completion = @codemirror.getCursor()
@description = null
result =
status: null
# create_suggestion is going to fill to_complete and to_describe
#to_complete: undefined
#to_describe: undefined
# If we are in the middle of a function (text after the cursor - that is not an element in @char_breakers or a comment), we just show a description, not a suggestion
result_non_white_char_after_cursor = @regex.get_first_non_white_char.exec(query_after_cursor)
if result_non_white_char_after_cursor isnt null and not(result_non_white_char_after_cursor[1]?[0] of @char_breakers or result_non_white_char_after_cursor[1]?.match(/^((\/\/)|(\/\*))/) isnt null)
result.status = 'break_and_look_for_description'
@hide_suggestion()
else
result_last_char_is_white = @regex.last_char_is_white.exec(query_before_cursor[query_before_cursor.length-1])
if result_last_char_is_white isnt null
result.status = 'break_and_look_for_description'
@hide_suggestion()
# Create the suggestion/description
@create_suggestion
stack: stack
query: query_before_cursor
result: result
result.suggestions = @uniq result.suggestions
@grouped_data = @count_group_level(stack).count_group > 0
if result.suggestions?.length > 0
show_suggestion = false
for suggestion, i in result.suggestions
if suggestion isnt 'ungroup(' or @grouped_data is true # We add the suggestion for `ungroup` only if we are in a group_stream/data (using the flag @grouped_data)
show_suggestion = true
@current_suggestions.push suggestion
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
if dataexplorer_state.options.suggestions is true and show_suggestion is true
@show_suggestion()
else
@hide_suggestion()
@hide_description()
else if result.description?
@hide_suggestion()
@description = result.description
if dataexplorer_state.options.suggestions is true and event?.type isnt 'mouseup'
@show_description()
else
@hide_description()
else
@hide_suggestion_and_description()
if event?.which is 9 # Catch tab
# If you're in a string, you add a TAB. If you're at the beginning of a newline with preceding whitespace, you add a TAB. If it's any other case do nothing.
if @last_element_type_if_incomplete(stack) isnt 'string' and @regex.white_or_empty.test(@codemirror.getLine(@codemirror.getCursor().line).slice(0, @codemirror.getCursor().ch)) isnt true
return true
else
return false
return true
# Similar to underscore's uniq but faster with a hashmap
uniq: (ar) ->
if not ar? or ar.length is 0
return ar
result = []
hash = {}
for element in ar
hash[element] = true
for key of hash
result.push key
result.sort()
return result
# Extract information from the current query
# Regex used
regex:
anonymous:/^(\s)*function\s*\(([a-zA-Z0-9,\s]*)\)(\s)*{/
loop:/^(\s)*(for|while)(\s)*\(([^\)]*)\)(\s)*{/
method: /^(\s)*([a-zA-Z0-9]*)\(/ # forEach( merge( filter(
row: /^(\s)*row\(/
method_var: /^(\s)*(\d*[a-zA-Z][a-zA-Z0-9]*)\./ # r. r.row. (r.count will be caught later)
return : /^(\s)*return(\s)*/
object: /^(\s)*{(\s)*/
array: /^(\s)*\[(\s)*/
white: /^(\s)+$/
white_or_empty: /^(\s)*$/
white_replace: /\s/g
white_start: /^(\s)+/
comma: /^(\s)*,(\s)*/
semicolon: /^(\s)*;(\s)*/
number: /^[0-9]+\.?[0-9]*/
inline_comment: /^(\s)*\/\/.*(\n|$)/
multiple_line_comment: /^(\s)*\/\*[^(\*\/)]*\*\//
get_first_non_white_char: /\s*(\S+)/
last_char_is_white: /.*(\s+)$/
stop_char: # Just for performance (we look for a stop_char in constant time - which is better than having 3 and conditions) and cleaner code
opening:
'(': ')'
'{': '}'
'[': ']'
closing:
')': '(' # Match the opening character
'}': '{'
']': '['
# Return the type of the last incomplete object or an empty string
last_element_type_if_incomplete: (stack) =>
if (not stack?) or stack.length is 0
return ''
element = stack[stack.length-1]
if element.body?
return @last_element_type_if_incomplete(element.body)
else
if element.complete is false
return element.type
else
return ''
# Get the last key if the last element is a key of an object
get_last_key: (stack) =>
if (not stack?) or stack.length is 0
return ''
element = stack[stack.length-1]
if element.body?
return @get_last_key(element.body)
else
if element.complete is false and element.key?
return element.key
else
return ''
# We build a stack of the query.
# Chained functions are in the same array, arguments/inner queries are in a nested array
# element.type in ['string', 'function', 'var', 'separator', 'anonymous_function', 'object', 'array_entry', 'object_key' 'array']
extract_data_from_query: (args) =>
size_stack = args.size_stack
query = args.query
context = if args.context? then util.deep_copy(args.context) else {}
position = args.position
stack = []
element =
type: null
context: context
complete: false
start = 0
is_parsing_string = false
to_skip = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
if element.type is 'string'
element.name = query.slice start, i+1
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+1
else # if element.is_parsing_string is false
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
if element.type is null
element.type = 'string'
start = i
continue
if element.type is null
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
start += result_inline_comment[0].length
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
start += result_multiple_line_comment[0].length
continue
if start is i
result_white = @regex.white_start.exec query.slice i
if result_white?
to_skip = result_white[0].length-1
start += result_white[0].length
continue
# Check for anonymous function
result_regex = @regex.anonymous.exec query.slice i
if result_regex isnt null
element.type = 'anonymous_function'
list_args = result_regex[2]?.split(',')
element.args = []
new_context = util.deep_copy context
for arg in list_args
arg = arg.replace(/(^\s*)|(\s*$)/gi,"") # Removing leading/trailing spaces
new_context[arg] = true
element.args.push arg
element.context = new_context
to_skip = result_regex[0].length
body_start = i+result_regex[0].length
stack_stop_char = ['{']
continue
# Check for a for loop
result_regex = @regex.loop.exec query.slice i
if result_regex isnt null
element.type = 'loop'
element.context = context
to_skip = result_regex[0].length
body_start = i+result_regex[0].length
stack_stop_char = ['{']
continue
# Check for return
result_regex = @regex.return.exec query.slice i
if result_regex isnt null
# I'm not sure we need to keep track of return, but let's keep it for now
element.type = 'return'
element.complete = true
to_skip = result_regex[0].length-1
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length
continue
# Check for object
result_regex = @regex.object.exec query.slice i
if result_regex isnt null
element.type = 'object'
element.next_key = null
element.body = [] # We need to keep tracker of the order of pairs
element.current_key_start = i+result_regex[0].length
to_skip = result_regex[0].length-1
stack_stop_char = ['{']
continue
# Check for array
result_regex = @regex.array.exec query.slice i
if result_regex isnt null
element.type = 'array'
element.next_key = null
element.body = []
entry_start = i+result_regex[0].length
to_skip = result_regex[0].length-1
stack_stop_char = ['[']
continue
if char is '.'
new_start = i+1
else
new_start = i
# Check for a standard method
result_regex = @regex.method.exec query.slice new_start
if result_regex isnt null
result_regex_row = @regex.row.exec query.slice new_start
if result_regex_row isnt null
position_opening_parenthesis = result_regex_row[0].indexOf('(')
element.type = 'function' # TODO replace with function
element.name = 'row'
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: 'function'
name: '('
position: position+3+1
context: context
complete: 'false'
stack_stop_char = ['(']
start += position_opening_parenthesis
to_skip = result_regex[0].length-1+new_start-i
continue
else
if stack[stack.length-1]?.type is 'function' or stack[stack.length-1]?.type is 'var' # We want the query to start with r. or arg.
element.type = 'function'
element.name = result_regex[0]
element.position = position+new_start
start += new_start-i
to_skip = result_regex[0].length-1+new_start-i
stack_stop_char = ['(']
continue
else
position_opening_parenthesis = result_regex[0].indexOf('(')
if position_opening_parenthesis isnt -1 and result_regex[0].slice(0, position_opening_parenthesis) of context
# Save the var
element.real_type = @types.value
element.type = 'var'
element.name = result_regex[0].slice(0, position_opening_parenthesis)
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: 'function'
name: '('
position: position+position_opening_parenthesis+1
context: context
complete: 'false'
stack_stop_char = ['(']
start = position_opening_parenthesis
to_skip = result_regex[0].length-1
continue
###
# This last condition is a special case for r(expr)
else if position_opening_parenthesis isnt -1 and result_regex[0].slice(0, position_opening_parenthesis) is 'r'
element.type = 'var'
element.name = 'r'
element.real_type = @types.value
element.position = position+new_start
start += new_start-i
to_skip = result_regex[0].length-1+new_start-i
stack_stop_char = ['(']
continue
###
# Check for method without parenthesis r., r.row., doc.
result_regex = @regex.method_var.exec query.slice new_start
if result_regex isnt null
if result_regex[0].slice(0, result_regex[0].length-1) of context
element.type = 'var'
element.real_type = @types.value
else
element.type = 'function'
element.position = position+new_start
element.name = result_regex[0].slice(0, result_regex[0].length-1).replace(/\s/, '')
element.complete = true
to_skip = element.name.length-1+new_start-i
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = new_start+to_skip+1
start -= new_start-i
continue
# Look for a comma
result_regex = @regex.comma.exec query.slice i
if result_regex isnt null
# element should have been pushed in stack. If not, the query is malformed
element.complete = true
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1+1
to_skip = result_regex[0].length-1
continue
# Look for a semi colon
result_regex = @regex.semicolon.exec query.slice i
if result_regex isnt null
# element should have been pushed in stack. If not, the query is malformed
element.complete = true
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1+1
to_skip = result_regex[0].length-1
continue
#else # if element.start isnt i
# We caught the white spaces, so there is nothing to do here
else
if char is ';'
# We just encountered a semi colon. We have an unknown element
# So We just got a random javascript statement, let's just ignore it
start = i+1
else # element.type isnt null
# Catch separator like for groupedMapReduce
result_regex = @regex.comma.exec(query.slice(i))
if result_regex isnt null and stack_stop_char.length < 1
# element should have been pushed in stack. If not, the query is malformed
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
position: position+i
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1
to_skip = result_regex[0].length-1
continue
# Catch for anonymous function
else if element.type is 'anonymous_function'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start, i
context: element.context
position: position+body_start
if element.body is null
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
#else the written query is broken here. The user forgot to close something?
#TODO Default behavior? Wait for Brackets/Ace to see how we handle errors
else if element.type is 'loop'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start, i
context: element.context
position: position+body_start
if element.body
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
# Catch for function
else if element.type is 'function'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice start+element.name.length, i
context: element.context
position: position+start+element.name.length
if element.body is null
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
# Catch for object
else if element.type is 'object'
# Since we are sure that we are not in a string, we can just look for colon and comma
# Still, we need to check the stack_stop_char since we can have { key: { inner: 'test, 'other_inner'}, other_key: 'other_value'}
keys_values = []
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
# We just reach a }, it's the end of the object
if element.next_key?
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start, i
context: element.context
position: position+element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
complete: false
body: body
element.body[element.body.length-1] = new_element
element.next_key = null # No more next_key
element.complete = true
# if not element.next_key?
# The next key is not defined, this is a broken query.
# TODO show error once brackets/ace will be used
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
continue
if not element.next_key?
if stack_stop_char.length is 1 and char is ':'
new_element =
type: 'object_key'
key: query.slice element.current_key_start, i
key_complete: true
if element.body.length is 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
else
element.body[element.body.length-1] = new_element
element.next_key = query.slice element.current_key_start, i
element.current_value_start = i+1
else
result_regex = @regex.comma.exec query.slice i
if stack_stop_char.length is 1 and result_regex isnt null #We reached the end of a value
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start, i
context: element.context
position: element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
body: body
element.body[element.body.length-1] = new_element
to_skip = result_regex[0].length-1
element.next_key = null
element.current_key_start = i+result_regex[0].length
# Catch for array
else if element.type is 'array'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
# We just reach a ], it's the end of the object
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start, i
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: true
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
continue
if stack_stop_char.length is 1 and char is ','
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start, i
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: true
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
entry_start = i+1
# We just reached the end, let's try to find the type of the incomplete element
if element.type isnt null
element.complete = false
if element.type is 'function'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice start+element.name.length
context: element.context
position: position+start+element.name.length
if element.body is null
return null
else if element.type is 'anonymous_function'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start
context: element.context
position: position+body_start
if element.body is null
return null
else if element.type is 'loop'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start
context: element.context
position: position+body_start
if element.body is null
return null
else if element.type is 'string'
element.name = query.slice start
else if element.type is 'object'
if not element.next_key? # Key not defined yet
new_element =
type: 'object_key'
key: query.slice element.current_key_start
key_complete: false
complete: false
element.body.push new_element # They key was not defined, so we add a new element
size_stack++
if size_stack > @max_size_stack
return null
element.next_key = query.slice element.current_key_start
else
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start
context: element.context
position: position+element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
complete: false
body: body
element.body[element.body.length-1] = new_element
element.next_key = null # No more next_key
else if element.type is 'array'
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: false
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
else if start isnt i
if query.slice(start) of element.context
element.name = query.slice start
element.type = 'var'
element.real_type = @types.value
element.complete = true
else if @regex.number.test(query.slice(start)) is true
element.type = 'number'
element.name = query.slice start
element.complete = true
else if query[start] is '.'
element.type = 'function'
element.position = position+start
element.name = query.slice start+1
element.complete = false
else
element.name = query.slice start
element.position = position+start
element.complete = false
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
return stack
# Count the number of `group` commands minus `ungroup` commands in the current level
# We count per level because we don't want to report a positive number of group for nested queries, e.g:
# r.table("foo").group("bar").map(function(doc) { doc.merge(
#
# We return an object with two fields
# - count_group: number of `group` commands minus the number of `ungroup` commands
# - parse_level: should we keep parsing the same level
count_group_level: (stack) =>
count_group = 0
if stack.length > 0
# Flag for whether or not we should keep looking for group/ungroup
# we want the warning to appear only at the same level
parse_level = true
element = stack[stack.length-1]
if element.body? and element.body.length > 0 and element.complete is false
parse_body = @count_group_level element.body
count_group += parse_body.count_group
parse_level = parse_body.parse_level
if element.body[0].type is 'return'
parse_level = false
if element.body[element.body.length-1].type is 'function'
parse_level = false
if parse_level is true
for i in [stack.length-1..0] by -1
if stack[i].type is 'function' and stack[i].name is 'ungroup('
count_group -= 1
else if stack[i].type is 'function' and stack[i].name is 'group('
count_group += 1
count_group: count_group
parse_level: parse_level
# Decide if we have to show a suggestion or a description
# Mainly use the stack created by extract_data_from_query
create_suggestion: (args) =>
stack = args.stack
query = args.query
result = args.result
# No stack, ie an empty query
if result.status is null and stack.length is 0
result.suggestions = []
result.status = 'done'
@query_first_part = ''
if @suggestions['']? # The docs may not have loaded
for suggestion in @suggestions['']
result.suggestions.push suggestion
for i in [stack.length-1..0] by -1
element = stack[i]
if element.body? and element.body.length > 0 and element.complete is false
@create_suggestion
stack: element.body
query: args?.query
result: args.result
if result.status is 'done'
continue
if result.status is null
# Top of the stack
if element.complete is true
if element.type is 'function'
if element.complete is true or element.name is ''
result.suggestions = null
result.status = 'look_for_description'
break
else
result.suggestions = null
result.description = element.name
#Define the current argument we have. It's the suggestion whose index is -1
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.status = 'done'
else if element.type is 'anonymous_function' or element.type is 'separator' or element.type is 'object' or element.type is 'object_key' or element.type is 'return' or 'element.type' is 'array'
# element.type === 'object' is impossible I think with the current implementation of extract_data_from_query
result.suggestions = null
result.status = 'look_for_description'
break # We want to look in the upper levels
#else type cannot be null (because not complete)
else # if element.complete is false
if element.type is 'function'
if element.body? # It means that element.body.length === 0
# We just opened a new function, so let's just show the description
result.suggestions = null
result.description = element.name # That means we are going to describe the function named element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.status = 'done'
break
else
# function not complete, need suggestion
result.suggestions = []
result.suggestions_regex = @create_safe_regex element.name # That means we are going to give all the suggestions that match element.name and that are in the good group (not yet defined)
result.description = null
@query_first_part = query.slice 0, element.position+1
@current_element = element.name
@cursor_for_auto_completion.ch -= element.name.length
@current_query
if i isnt 0
result.status = 'look_for_state'
else
result.state = ''
else if element.type is 'anonymous_function' or element.type is 'object_key' or element.type is 'string' or element.type is 'separator' or element.type is 'array'
result.suggestions = null
result.status = 'look_for_description'
break
#else if element.type is 'object' # Not possible
#else if element.type is 'var' # Not possible because we require a . or ( to asssess that it's a var
else if element.type is null
result.suggestions = []
result.status = 'look_for_description'
break
else if result.status is 'look_for_description'
if element.type is 'function'
result.description = element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.suggestions = null
result.status = 'done'
else
break
if result.status is 'break_and_look_for_description'
if element.type is 'function' and element.complete is false and element.name.indexOf('(') isnt -1
result.description = element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.suggestions = null
result.status = 'done'
else
if element.type isnt 'function'
break
else
result.status = 'look_for_description'
break
else if result.status is 'look_for_state'
if element.type is 'function' and element.complete is true
result.state = element.name
if @map_state[element.name]?
for state in @map_state[element.name]
if @suggestions[state]?
for suggestion in @suggestions[state]
if result.suggestions_regex.test(suggestion) is true
result.suggestions.push suggestion
#else # This is a non valid ReQL function.
# It may be a personalized function defined in the data explorer...
result.status = 'done'
else if element.type is 'var' and element.complete is true
result.state = element.real_type
for type in result.state
if @suggestions[type]?
for suggestion in @suggestions[type]
if result.suggestions_regex.test(suggestion) is true
result.suggestions.push suggestion
result.status = 'done'
#else # Is that possible? A function can only be preceded by a function (except for r)
# Create regex based on the user input. We make it safe
create_safe_regex: (str) =>
for char in @unsafe_to_safe_regexstr
str = str.replace char[0], char[1]
return new RegExp('^('+str+')', 'i')
# Show suggestion and determine where to put the box
show_suggestion: =>
@move_suggestion()
margin = (parseInt(@$('.CodeMirror-cursor').css('top').replace('px', ''))+@line_height)+'px'
@$('.suggestion_full_container').css 'margin-top', margin
@$('.arrow').css 'margin-top', margin
@$('.suggestion_name_list').show()
@$('.arrow').show()
# If want to show suggestion without moving the arrow
show_suggestion_without_moving: =>
@$('.arrow').show()
@$('.suggestion_name_list').show()
# Show description and determine where to put it
show_description: =>
if @descriptions[@description]? # Just for safety
margin = (parseInt(@$('.CodeMirror-cursor').css('top').replace('px', ''))+@line_height)+'px'
@$('.suggestion_full_container').css 'margin-top', margin
@$('.arrow').css 'margin-top', margin
@$('.suggestion_description').html @description_template @extend_description @description
@$('.suggestion_description').show()
@move_suggestion()
@show_or_hide_arrow()
else
@hide_description()
hide_suggestion: =>
@$('.suggestion_name_list').hide()
@show_or_hide_arrow()
hide_description: =>
@$('.suggestion_description').hide()
@show_or_hide_arrow()
hide_suggestion_and_description: =>
@hide_suggestion()
@hide_description()
# Show the arrow if suggestion or/and description is being displayed
show_or_hide_arrow: =>
if @$('.suggestion_name_list').css('display') is 'none' and @$('.suggestion_description').css('display') is 'none'
@$('.arrow').hide()
else
@$('.arrow').show()
# Move the suggestion. We have steps of 200 pixels and try not to overlaps button if we can. If we cannot, we just hide them all since their total width is less than 200 pixels
move_suggestion: =>
margin_left = parseInt(@$('.CodeMirror-cursor').css('left').replace('px', ''))+23
@$('.arrow').css 'margin-left', margin_left
if margin_left < 200
@$('.suggestion_full_container').css 'left', '0px'
else
max_margin = @$('.CodeMirror-scroll').width()-418
margin_left_bloc = Math.min max_margin, Math.floor(margin_left/200)*200
if margin_left > max_margin+418-150-23 # We are really at the end
@$('.suggestion_full_container').css 'left', (max_margin-34)+'px'
else if margin_left_bloc > max_margin-150-23
@$('.suggestion_full_container').css 'left', (max_margin-34-150)+'px'
else
@$('.suggestion_full_container').css 'left', (margin_left_bloc-100)+'px'
#Highlight suggestion. Method called when the user hit tab or mouseover
highlight_suggestion: (id) =>
@remove_highlight_suggestion()
@$('.suggestion_name_li').eq(id).addClass 'suggestion_name_li_hl'
@$('.suggestion_description').html @description_template @extend_description @current_suggestions[id]
@$('.suggestion_description').show()
remove_highlight_suggestion: =>
@$('.suggestion_name_li').removeClass 'suggestion_name_li_hl'
# Write the suggestion in the code mirror
write_suggestion: (args) =>
suggestion_to_write = args.suggestion_to_write
move_outside = args.move_outside is true # So default value is false
ch = @cursor_for_auto_completion.ch+suggestion_to_write.length
if dataexplorer_state.options.electric_punctuation is true
if suggestion_to_write[suggestion_to_write.length-1] is '(' and @count_not_closed_brackets('(') >= 0
@codemirror.setValue @query_first_part+suggestion_to_write+')'+@query_last_part
@written_suggestion = suggestion_to_write+')'
else
@codemirror.setValue @query_first_part+suggestion_to_write+@query_last_part
@written_suggestion = suggestion_to_write
if (move_outside is false) and (suggestion_to_write[suggestion_to_write.length-1] is '"' or suggestion_to_write[suggestion_to_write.length-1] is "'")
ch--
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
@codemirror.setCursor
line: @cursor_for_auto_completion.line
ch:ch
else
@codemirror.setValue @query_first_part+suggestion_to_write+@query_last_part
@written_suggestion = suggestion_to_write
if (move_outside is false) and (suggestion_to_write[suggestion_to_write.length-1] is '"' or suggestion_to_write[suggestion_to_write.length-1] is "'")
ch--
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
@codemirror.setCursor
line: @cursor_for_auto_completion.line
ch:ch
# Select the suggestion. Called by mousdown .suggestion_name_li
select_suggestion: (event) =>
suggestion_to_write = @$(event.target).html()
@write_suggestion
suggestion_to_write: suggestion_to_write
# Give back focus to code mirror
@hide_suggestion()
# Put back in the stack
setTimeout =>
@handle_keypress() # That's going to describe the function the user just selected
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
, 0 # Useful if the user used the mouse to select a suggestion
# Highlight a suggestion in case of a mouseover
mouseover_suggestion: (event) =>
@highlight_suggestion event.target.dataset.id
# Hide suggestion in case of a mouse out
mouseout_suggestion: (event) =>
@hide_description()
# Extend description for .db() and .table() with dbs/tables names
extend_description: (fn) =>
if fn is 'db(' or fn is 'dbDrop('
description = _.extend {}, @descriptions[fn]()
if _.keys(@databases_available).length is 0
data =
no_database: true
else
databases_available = _.keys @databases_available
data =
no_database: false
databases_available: databases_available
description.description = @databases_suggestions_template(data)+description.description
@extra_suggestions= databases_available # @extra_suggestions store the suggestions for arguments. So far they are just for db(), dbDrop(), table(), tableDrop()
else if fn is 'table(' or fn is 'tableDrop('
# Look for the argument of the previous db()
database_used = @extract_database_used()
description = _.extend {}, @descriptions[fn]()
if database_used.error is false
data =
tables_available: @databases_available[database_used.name]
no_table: @databases_available[database_used.name].length is 0
if database_used.name?
data.database_name = database_used.name
else
data =
error: database_used.error
description.description = @tables_suggestions_template(data) + description.description
@extra_suggestions = @databases_available[database_used.name]
else
description = @descriptions[fn] @grouped_data
@extra_suggestions= null
return description
# We could create a new stack with @extract_data_from_query, but that would be a more expensive for not that much
# We can not use the previous stack too since autocompletion doesn't validate the query until you hit enter (or another key than tab)
extract_database_used: =>
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
# We cannot have ".db(" in a db name
last_db_position = query_before_cursor.lastIndexOf('.db(')
if last_db_position is -1
found = false
if @databases_available['test']?
return {
db_found: true
error: false
name: 'test'
}
else
return {
db_found: false
error: true
}
else
arg = query_before_cursor.slice last_db_position+5 # +4 for .db(
char = query_before_cursor.slice last_db_position+4, last_db_position+5 # ' or " used for the argument of db()
end_arg_position = arg.indexOf char # Check for the next quote or apostrophe
if end_arg_position is -1
return {
db_found: false
error: true
}
db_name = arg.slice 0, end_arg_position
if @databases_available[db_name]?
return {
db_found: true
error: false
name: db_name
}
else
return {
db_found: false
error: true
}
abort_query: =>
@disable_toggle_executing = false
@toggle_executing false
dataexplorer_state.query_result?.force_end_gracefully()
@driver_handler.close_connection()
# Function that execute the queries in a synchronous way.
execute_query: =>
# We don't let people execute more than one query at a time on the same connection
# While we remove the button run, `execute_query` could still be called with Shift+Enter
if @executing is true
@abort_query
# Hide the option, if already hidden, nothing happens.
@$('.profiler_enabled').slideUp 'fast'
# The user just executed a query, so we reset cursor_timed_out to false
dataexplorer_state.cursor_timed_out = false
dataexplorer_state.query_has_changed = false
@raw_query = @codemirror.getSelection() or @codemirror.getValue()
@query = @clean_query @raw_query # Save it because we'll use it in @callback_multilples_queries
# Execute the query
try
dataexplorer_state.query_result?.discard()
# Separate queries
@non_rethinkdb_query = '' # Store the statements that don't return a rethinkdb query (like "var a = 1;")
@index = 0 # index of the query currently being executed
@raw_queries = @separate_queries @raw_query # We first split raw_queries
@queries = @separate_queries @query
if @queries.length is 0
error = @query_error_template
no_query: true
@results_view_wrapper.render_error(null, error, true)
else
@execute_portion()
catch err
# Missing brackets, so we display everything (we don't know if we properly splitted the query)
@results_view_wrapper.render_error(@query, err, true)
@save_query
query: @raw_query
broken_query: true
toggle_executing: (executing) =>
if executing == @executing
if executing and dataexplorer_state.query_result?.is_feed
@$('.loading_query_img').hide()
return
if @disable_toggle_executing
return
@executing = executing
if @timeout_toggle_abort?
clearTimeout @timeout_toggle_abort
if executing
@timeout_toggle_abort = setTimeout =>
@timeout_toggle_abort = null
if not dataexplorer_state.query_result?.is_feed
@$('.loading_query_img').show()
@$('.execute_query').hide()
@$('.abort_query').show()
, @delay_toggle_abort
else
@timeout_toggle_abort = setTimeout =>
@timeout_toggle_abort = null
@$('.loading_query_img').hide()
@$('.execute_query').show()
@$('.abort_query').hide()
, @delay_toggle_abort
# A portion is one query of the whole input.
execute_portion: =>
dataexplorer_state.query_result = null
while @queries[@index]?
full_query = @non_rethinkdb_query
full_query += @queries[@index]
try
rdb_query = @evaluate(full_query)
catch err
if @queries.length > 1
@results_view_wrapper.render_error(@raw_queries[@index], err, true)
else
@results_view_wrapper.render_error(null, err, true)
@save_query
query: @raw_query
broken_query: true
return false
@index++
if rdb_query instanceof @TermBaseConstructor
final_query = @index is @queries.length
@start_time = new Date()
if final_query
query_result = new QueryResult
has_profile: dataexplorer_state.options.profiler
current_query: @raw_query
raw_query: @raw_queries[@index]
driver_handler: @driver_handler
events:
error: (query_result, err) =>
@results_view_wrapper.render_error(@query, err)
ready: (query_result) =>
dataexplorer_state.pause_at = null
if query_result.is_feed
@toggle_executing true
@disable_toggle_executing = true
for event in ['end', 'discard', 'error']
query_result.on event, () =>
@disable_toggle_executing = false
@toggle_executing false
dataexplorer_state.query_result = query_result
@results_view_wrapper.set_query_result
query_result: dataexplorer_state.query_result
@disable_toggle_executing = false
@driver_handler.run_with_new_connection rdb_query,
optargs:
binaryFormat: "raw"
timeFormat: "raw"
profile: dataexplorer_state.options.profiler
connection_error: (error) =>
@save_query
query: @raw_query
broken_query: true
@error_on_connect error
callback: (error, result) =>
if final_query
@save_query
query: @raw_query
broken_query: false
query_result.set error, result
else if error
@save_query
query: @raw_query
broken_query: true
@results_view_wrapper.render_error(@query, err)
else
@execute_portion()
return true
else
@non_rethinkdb_query += @queries[@index-1]
if @index is @queries.length
error = @query_error_template
last_non_query: true
@results_view_wrapper.render_error(@raw_queries[@index-1], error, true)
@save_query
query: @raw_query
broken_query: true
# Evaluate the query
# We cannot force eval to a local scope, but "use strict" will declare variables in the scope at least
evaluate: (query) =>
"use strict"
return eval(query)
# In a string \n becomes \\n, outside a string we just remove \n, so
# r
# .expr('hello
# world')
# becomes
# r.expr('hello\nworld')
# We also remove comments from the query
clean_query: (query) ->
is_parsing_string = false
start = 0
result_query = ''
for char, i in query
if to_skip > 0
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\'
result_query += query.slice(start, i+1).replace(/\n/g, '\\n')
start = i+1
is_parsing_string = false
continue
else # if element.is_parsing_string is false
if char is '\'' or char is '"'
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
to_skip = result_inline_comment[0].length-1
start += result_inline_comment[0].length
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
to_skip = result_multiple_line_comment[0].length-1
start += result_multiple_line_comment[0].length
continue
if is_parsing_string
result_query += query.slice(start, i).replace(/\n/g, '\\\\n')
else
result_query += query.slice(start, i).replace(/\n/g, '')
return result_query
# Split input in queries. We use semi colon, pay attention to string, brackets and comments
separate_queries: (query) =>
queries = []
is_parsing_string = false
stack = []
start = 0
position =
char: 0
line: 1
for char, i in query
if char is '\n'
position.line++
position.char = 0
else
position.char++
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\'
is_parsing_string = false
continue
else # if element.is_parsing_string is false
if char is '\'' or char is '"'
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
if char of @stop_char.opening
stack.push char
else if char of @stop_char.closing
if stack[stack.length-1] isnt @stop_char.closing[char]
throw @query_error_template
syntax_error: true
bracket: char
line: position.line
position: position.char
else
stack.pop()
else if char is ';' and stack.length is 0
queries.push query.slice start, i+1
start = i+1
if start < query.length-1
last_query = query.slice start
if @regex.white.test(last_query) is false
queries.push last_query
return queries
# Clear the input
clear_query: =>
@codemirror.setValue ''
@codemirror.focus()
# Called if there is any on the connection
error_on_connect: (error) =>
if /^(Unexpected token)/.test(error.message)
# Unexpected token, the server couldn't parse the message
# The truth is we don't know which query failed (unexpected token), but it seems safe to suppose in 99% that the last one failed.
@results_view_wrapper.render_error(null, error)
# We save the query since the callback will never be called.
@save_query
query: @raw_query
broken_query: true
else
@results_view_wrapper.cursor_timed_out()
# We fail to connect, so we display a message except if we were already disconnected and we are not trying to manually reconnect
# So if the user fails to reconnect after a failure, the alert will still flash
@$('#user-alert-space').hide()
@$('#user-alert-space').html @alert_connection_fail_template({})
@$('#user-alert-space').slideDown 'fast'
handle_gutter_click: (editor, line) =>
start =
line: line
ch: 0
end =
line: line
ch: @codemirror.getLine(line).length
@codemirror.setSelection start, end
# Switch between full view and normal view
toggle_size: =>
if @displaying_full_view is true
@display_normal()
$(window).off 'resize', @display_full
@displaying_full_view = false
else
@display_full()
$(window).on 'resize', @display_full
@displaying_full_view = true
@results_view_wrapper.set_scrollbar()
display_normal: =>
$('#cluster').addClass 'container'
$('#cluster').removeClass 'cluster_with_margin'
@$('.wrapper_scrollbar').css 'width', '888px'
@$('.option_icon').removeClass 'fullscreen_exit'
@$('.option_icon').addClass 'fullscreen'
display_full: =>
$('#cluster').removeClass 'container'
$('#cluster').addClass 'cluster_with_margin'
@$('.wrapper_scrollbar').css 'width', ($(window).width()-92)+'px'
@$('.option_icon').removeClass 'fullscreen'
@$('.option_icon').addClass 'fullscreen_exit'
remove: =>
@results_view_wrapper.remove()
@history_view.remove()
@driver_handler.remove()
@display_normal()
$(window).off 'resize', @display_full
$(document).unbind 'mousemove', @handle_mousemove
$(document).unbind 'mouseup', @handle_mouseup
clearTimeout @timeout_driver_connect
driver.stop_timer @timer
# We do not destroy the cursor, because the user might come back and use it.
super()
# An abstract base class
class ResultView extends Backbone.View
tree_large_container_template: require('../handlebars/dataexplorer_large_result_json_tree_container.hbs')
tree_container_template: require('../handlebars/dataexplorer_result_json_tree_container.hbs')
events: ->
'click .jt_arrow': 'toggle_collapse'
'click .jta_arrow_h': 'expand_tree_in_table'
'mousedown': 'parent_pause_feed'
initialize: (args) =>
@_patched_already = false
@parent = args.parent
@query_result = args.query_result
@render()
@listenTo @query_result, 'end', =>
if not @query_result.is_feed
@render()
@fetch_batch_rows()
remove: =>
@removed_self = true
super()
max_datum_threshold: 1000
# Return whether there are too many datums
# If there are too many, we will disable syntax highlighting to avoid freezing the page
has_too_many_datums: (result) ->
if @has_too_many_datums_helper(result) > @max_datum_threshold
return true
return false
json_to_tree: (result) =>
# If the results are too large, we just display the raw indented JSON to avoid freezing the interface
if @has_too_many_datums(result)
return @tree_large_container_template
json_data: JSON.stringify(result, null, 4)
else
return @tree_container_template
tree: util.json_to_node(result)
# Return the number of datums if there are less than @max_datum_threshold
# Or return a number greater than @max_datum_threshold
has_too_many_datums_helper: (result) ->
if Object::toString.call(result) is '[object Object]'
count = 0
for key of result
count += @has_too_many_datums_helper result[key]
if count > @max_datum_threshold
return count
return count
else if Array.isArray(result)
count = 0
for element in result
count += @has_too_many_datums_helper element
if count > @max_datum_threshold
return count
return count
return 1
toggle_collapse: (event) =>
@$(event.target).nextAll('.jt_collapsible').toggleClass('jt_collapsed')
@$(event.target).nextAll('.jt_points').toggleClass('jt_points_collapsed')
@$(event.target).nextAll('.jt_b').toggleClass('jt_b_collapsed')
@$(event.target).toggleClass('jt_arrow_hidden')
@parent.set_scrollbar()
expand_tree_in_table: (event) =>
dom_element = @$(event.target).parent()
@$(event.target).remove()
data = dom_element.data('json_data')
result = @json_to_tree data
dom_element.html result
classname_to_change = dom_element.parent().attr('class').split(' ')[0]
$('.'+classname_to_change).css 'max-width', 'none'
classname_to_change = dom_element.parent().parent().attr('class')
$('.'+classname_to_change).css 'max-width', 'none'
dom_element.css 'max-width', 'none'
@parent.set_scrollbar()
parent_pause_feed: (event) =>
@parent.pause_feed()
pause_feed: =>
unless @parent.container.state.pause_at?
@parent.container.state.pause_at = @query_result.size()
unpause_feed: =>
if @parent.container.state.pause_at?
@parent.container.state.pause_at = null
@render()
current_batch: =>
switch @query_result.type
when 'value'
return @query_result.value
when 'cursor'
if @query_result.is_feed
pause_at = @parent.container.state.pause_at
if pause_at?
latest = @query_result.slice(Math.min(0, pause_at - @parent.container.state.options.query_limit), pause_at - 1)
else
latest = @query_result.slice(-@parent.container.state.options.query_limit)
latest.reverse()
return latest
else
return @query_result.slice(@query_result.position, @query_result.position + @parent.container.state.options.query_limit)
current_batch_size: =>
return @current_batch()?.length ? 0
setStackSize: =>
# In some versions of firefox, the effective recursion
# limit gets hit sometimes by the driver. Here we patch
# the driver's built in stackSize to 12 (normally it's
# 100). The driver will invoke callbacks with setImmediate
# vs directly invoking themif the stackSize limit is
# exceeded, which keeps the stack size manageable (but
# results in worse tracebacks).
if @_patched_already
return
iterableProto = @query_result.cursor?.__proto__?.__proto__?.constructor?.prototype
if iterableProto?.stackSize > 12
console.log "Patching stack limit on cursors to 12"
iterableProto.stackSize = 12
@_patched_already = true
# TODO: rate limit events to avoid freezing the browser when there are too many
fetch_batch_rows: =>
if @query_result.type is not 'cursor'
return
@setStackSize()
if @query_result.is_feed or @query_result.size() < @query_result.position + @parent.container.state.options.query_limit
@query_result.once 'add', (query_result, row) =>
if @removed_self
return
if @query_result.is_feed
if not @parent.container.state.pause_at?
if not @paused_at?
@query_result.drop_before(@query_result.size() - @parent.container.state.options.query_limit)
@add_row row
@parent.update_feed_metadata()
@fetch_batch_rows()
@query_result.fetch_next()
else
@parent.render()
@render()
show_next_batch: =>
@query_result.position += @parent.container.state.options.query_limit
@query_result.drop_before @parent.container.state.options.query_limit
@render()
@parent.render()
@fetch_batch_rows()
add_row: (row) =>
# TODO: Don't render the whole view on every change
@render()
class TreeView extends ResultView
className: 'results tree_view_container'
templates:
wrapper: require('../handlebars/dataexplorer_result_tree.hbs')
no_result: require('../handlebars/dataexplorer_result_empty.hbs')
render: =>
if @query_result.results?.length == 0
@$el.html @templates.wrapper tree: @templates.no_result
ended: @query_result.ended
at_beginning: @query_result.at_beginning()
return @
switch @query_result.type
when 'value'
@$el.html @templates.wrapper tree: @json_to_tree @query_result.value
when 'cursor'
@$el.html @templates.wrapper tree: []
tree_container = @$('.json_tree_container')
for row in @current_batch()
tree_container.append @json_to_tree row
return @
add_row: (row, noflash) =>
tree_container = @$('.json_tree_container')
node = $(@json_to_tree(row)).prependTo(tree_container)
if not noflash
node.addClass 'flash'
children = tree_container.children()
if children.length > @parent.container.state.options.query_limit
children.last().remove()
class TableView extends ResultView
className: 'results table_view_container'
templates:
wrapper: require('../handlebars/dataexplorer_result_table.hbs')
container: require('../handlebars/dataexplorer_result_json_table_container.hbs')
tr_attr: require('../handlebars/dataexplorer_result_json_table_tr_attr.hbs')
td_attr: require('../handlebars/dataexplorer_result_json_table_td_attr.hbs')
tr_value: require('../handlebars/dataexplorer_result_json_table_tr_value.hbs')
td_value: require('../handlebars/dataexplorer_result_json_table_td_value.hbs')
td_value_content: require('../handlebars/dataexplorer_result_json_table_td_value_content.hbs')
data_inline: require('../handlebars/dataexplorer_result_json_table_data_inline.hbs')
no_result: require('../handlebars/dataexplorer_result_empty.hbs')
default_size_column: 310 # max-width value of a cell of a table (as defined in the css file)
mouse_down: false
events: -> _.extend super(),
'mousedown .click_detector': 'handle_mousedown'
initialize: (args) =>
super args
@last_keys = @parent.container.state.last_keys # Arrays of the last keys displayed
@last_columns_size = @parent.container.state.last_columns_size # Size of the columns displayed. Undefined if a column has the default size
@listenTo @query_result, 'end', =>
if @current_batch_size() == 0
@render()
handle_mousedown: (event) =>
if event?.target?.className is 'click_detector'
@col_resizing = @$(event.target).parent().data('col')
@start_width = @$(event.target).parent().width()
@start_x = event.pageX
@mouse_down = true
$('body').toggleClass('resizing', true)
handle_mousemove: (event) =>
if @mouse_down
@parent.container.state.last_columns_size[@col_resizing] = Math.max 5, @start_width-@start_x+event.pageX # Save the personalized size
@resize_column @col_resizing, @parent.container.state.last_columns_size[@col_resizing] # Resize
resize_column: (col, size) =>
@$('.col-'+col).css 'max-width', size
@$('.value-'+col).css 'max-width', size-20
@$('.col-'+col).css 'width', size
@$('.value-'+col).css 'width', size-20
if size < 20
@$('.value-'+col).css 'padding-left', (size-5)+'px'
@$('.value-'+col).css 'visibility', 'hidden'
else
@$('.value-'+col).css 'padding-left', '15px'
@$('.value-'+col).css 'visibility', 'visible'
handle_mouseup: (event) =>
if @mouse_down is true
@mouse_down = false
$('body').toggleClass('resizing', false)
@parent.set_scrollbar()
###
keys =
primitive_value_count: <int>
object:
key_1: <keys>
key_2: <keys>
###
build_map_keys: (args) =>
keys_count = args.keys_count
result = args.result
if jQuery.isPlainObject(result)
if result.$reql_type$ is 'TIME'
keys_count.primitive_value_count++
else if result.$reql_type$ is 'BINARY'
keys_count.primitive_value_count++
else
for key, row of result
if not keys_count['object']?
keys_count['object'] = {} # That's define only if there are keys!
if not keys_count['object'][key]?
keys_count['object'][key] =
primitive_value_count: 0
@build_map_keys
keys_count: keys_count['object'][key]
result: row
else
keys_count.primitive_value_count++
# Compute occurrence of each key. The occurence can be a float since we compute the average occurence of all keys for an object
compute_occurrence: (keys_count) =>
if not keys_count['object']? # That means we are accessing only a primitive value
keys_count.occurrence = keys_count.primitive_value_count
else
count_key = if keys_count.primitive_value_count > 0 then 1 else 0
count_occurrence = keys_count.primitive_value_count
for key, row of keys_count['object']
count_key++
@compute_occurrence row
count_occurrence += row.occurrence
keys_count.occurrence = count_occurrence/count_key # count_key cannot be 0
# Sort the keys per level
order_keys: (keys) =>
copy_keys = []
if keys.object?
for key, value of keys.object
if jQuery.isPlainObject(value)
@order_keys value
copy_keys.push
key: key
value: value.occurrence
# If we could know if a key is a primary key, that would be awesome
copy_keys.sort (a, b) ->
if b.value-a.value
return b.value-a.value
else
if a.key > b.key
return 1
else # We cannot have two times the same key
return -1
keys.sorted_keys = _.map copy_keys, (d) -> return d.key
if keys.primitive_value_count > 0
keys.sorted_keys.unshift @primitive_key
# Flatten the object returns by build_map_keys().
# We get back an array of keys
get_all_attr: (args) =>
keys_count = args.keys_count
attr = args.attr
prefix = args.prefix
prefix_str = args.prefix_str
for key in keys_count.sorted_keys
if key is @primitive_key
new_prefix_str = prefix_str # prefix_str without the last dot
if new_prefix_str.length > 0
new_prefix_str = new_prefix_str.slice(0, -1)
attr.push
prefix: prefix
prefix_str: new_prefix_str
is_primitive: true
else
if keys_count['object'][key]['object']?
new_prefix = util.deep_copy(prefix)
new_prefix.push key
@get_all_attr
keys_count: keys_count.object[key]
attr: attr
prefix: new_prefix
prefix_str: (if prefix_str? then prefix_str else '')+key+'.'
else
attr.push
prefix: prefix
prefix_str: prefix_str
key: key
json_to_table_get_attr: (flatten_attr) =>
return @templates.tr_attr
attr: flatten_attr
json_to_table_get_values: (args) =>
result = args.result
flatten_attr = args.flatten_attr
document_list = []
for single_result, i in result
new_document =
cells: []
for attr_obj, col in flatten_attr
key = attr_obj.key
value = single_result
for prefix in attr_obj.prefix
value = value?[prefix]
if attr_obj.is_primitive isnt true
if value?
value = value[key]
else
value = undefined
new_document.cells.push @json_to_table_get_td_value value, col
index = if @query_result.is_feed then @query_result.size() - i else i + 1
@tag_record new_document, index
document_list.push new_document
return @templates.tr_value
document: document_list
json_to_table_get_td_value: (value, col) =>
data = @compute_data_for_type(value, col)
return @templates.td_value
col: col
cell_content: @templates.td_value_content data
compute_data_for_type: (value, col) =>
data =
value: value
class_value: 'value-'+col
value_type = typeof value
if value is null
data['value'] = 'null'
data['classname'] = 'jta_null'
else if value is undefined
data['value'] = 'undefined'
data['classname'] = 'jta_undefined'
else if value.constructor? and value.constructor is Array
if value.length is 0
data['value'] = '[ ]'
data['classname'] = 'empty array'
else
data['value'] = '[ ... ]'
data['data_to_expand'] = JSON.stringify(value)
else if Object::toString.call(value) is '[object Object]' and value.$reql_type$ is 'TIME'
data['value'] = util.date_to_string(value)
data['classname'] = 'jta_date'
else if Object::toString.call(value) is '[object Object]' and value.$reql_type$ is 'BINARY'
data['value'] = util.binary_to_string value
data['classname'] = 'jta_bin'
else if Object::toString.call(value) is '[object Object]'
data['value'] = '{ ... }'
data['is_object'] = true
else if value_type is 'number'
data['classname'] = 'jta_num'
else if value_type is 'string'
if /^(http|https):\/\/[^\s]+$/i.test(value)
data['classname'] = 'jta_url'
else if /^[a-z0-9]+@[a-z0-9]+.[a-z0-9]{2,4}/i.test(value) # We don't handle .museum extension and special characters
data['classname'] = 'jta_email'
else
data['classname'] = 'jta_string'
else if value_type is 'boolean'
data['classname'] = 'jta_bool'
data.value = if value is true then 'true' else 'false'
return data
# Helper for expanding a table when showing an object (creating new columns)
join_table: (data) =>
result = ''
for value, i in data
data_cell = @compute_data_for_type(value, 'float')
data_cell['is_inline'] = true
if i isnt data.length-1
data_cell['need_comma'] = true
result += @templates.data_inline data_cell
return result
# Build the table
# We order by the most frequent keys then by alphabetic order
json_to_table: (result) =>
# While an Array type is never returned by the driver, we still build an Array in the data explorer
# when a cursor is returned (since we just print @limit results)
if not result.constructor? or result.constructor isnt Array
result = [result]
keys_count =
primitive_value_count: 0
for result_entry in result
@build_map_keys
keys_count: keys_count
result: result_entry
@compute_occurrence keys_count
@order_keys keys_count
flatten_attr = []
@get_all_attr # fill attr[]
keys_count: keys_count
attr: flatten_attr
prefix: []
prefix_str: ''
for value, index in flatten_attr
value.col = index
@last_keys = flatten_attr.map (attr, i) ->
if attr.prefix_str isnt ''
return attr.prefix_str+attr.key
return attr.key
@parent.container.state.last_keys = @last_keys
return @templates.container
table_attr: @json_to_table_get_attr flatten_attr
table_data: @json_to_table_get_values
result: result
flatten_attr: flatten_attr
tag_record: (doc, i) =>
doc.record = @query_result.position + i
render: =>
previous_keys = @parent.container.state.last_keys # Save previous keys. @last_keys will be updated in @json_to_table
results = @current_batch()
if Object::toString.call(results) is '[object Array]'
if results.length is 0
@$el.html @templates.wrapper content: @templates.no_result
ended: @query_result.ended
at_beginning: @query_result.at_beginning()
else
@$el.html @templates.wrapper content: @json_to_table results
else
if results is undefined
@$el.html ''
else
@$el.html @templates.wrapper content: @json_to_table [results]
if @query_result.is_feed
# TODO: highlight all new rows, not just the latest one
first_row = @$('.jta_tr').eq(1).find('td:not(:first)')
first_row.css 'background-color': '#eeeeff'
first_row.animate 'background-color': '#fbfbfb'
# Check if the keys are the same
if @parent.container.state.last_keys.length isnt previous_keys.length
same_keys = false
else
same_keys = true
for keys, index in @parent.container.state.last_keys
if @parent.container.state.last_keys[index] isnt previous_keys[index]
same_keys = false
# TODO we should just check if previous_keys is included in last_keys
# If the keys are the same, we are going to resize the columns as they were before
if same_keys is true
for col, value of @parent.container.state.last_columns_size
@resize_column col, value
else
# Reinitialize @last_columns_size
@last_column_size = {}
# Let's try to expand as much as we can
extra_size_table = @$('.json_table_container').width()-@$('.json_table').width()
if extra_size_table > 0 # The table doesn't take the full width
expandable_columns = []
for index in [0..@last_keys.length-1] # We skip the column record
real_size = 0
@$('.col-'+index).children().children().children().each((i, bloc) ->
$bloc = $(bloc)
if real_size<$bloc.width()
real_size = $bloc.width()
)
if real_size? and real_size is real_size and real_size > @default_size_column
expandable_columns.push
col: index
size: real_size+20 # 20 for padding
while expandable_columns.length > 0
expandable_columns.sort (a, b) ->
return a.size-b.size
if expandable_columns[0].size-@$('.col-'+expandable_columns[0].col).width() < extra_size_table/expandable_columns.length
extra_size_table = extra_size_table-(expandable_columns[0]['size']-@$('.col-'+expandable_columns[0].col).width())
@$('.col-'+expandable_columns[0]['col']).css 'max-width', expandable_columns[0]['size']
@$('.value-'+expandable_columns[0]['col']).css 'max-width', expandable_columns[0]['size']-20
expandable_columns.shift()
else
max_size = extra_size_table/expandable_columns.length
for column in expandable_columns
current_size = @$('.col-'+expandable_columns[0].col).width()
@$('.col-'+expandable_columns[0]['col']).css 'max-width', current_size+max_size
@$('.value-'+expandable_columns[0]['col']).css 'max-width', current_size+max_size-20
expandable_columns = []
return @
class RawView extends ResultView
className: 'results raw_view_container'
template: require('../handlebars/dataexplorer_result_raw.hbs')
init_after_dom_rendered: =>
@adjust_height()
adjust_height: =>
height = @$('.raw_view_textarea')[0].scrollHeight
if height > 0
@$('.raw_view_textarea').height(height)
render: =>
@$el.html @template JSON.stringify @current_batch()
@adjust_height()
return @
class ProfileView extends ResultView
className: 'results profile_view_container'
template:
require('../handlebars/dataexplorer_result_profile.hbs')
initialize: (args) =>
ZeroClipboard.setDefaults
moviePath: 'js/ZeroClipboard.swf'
forceHandCursor: true #TODO Find a fix for chromium(/linux?)
@clip = new ZeroClipboard()
super args
compute_total_duration: (profile) ->
profile.reduce(((total, task) ->
total + (task['duration(ms)'] or task['mean_duration(ms)'])) ,0)
compute_num_shard_accesses: (profile) ->
num_shard_accesses = 0
for task in profile
if task['description'] is 'Perform read on shard.'
num_shard_accesses += 1
if Object::toString.call(task['sub_tasks']) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task['sub_tasks']
if Object::toString.call(task['parallel_tasks']) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task['parallel_tasks']
# In parallel tasks, we get arrays of tasks instead of a super task
if Object::toString.call(task) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task
return num_shard_accesses
render: =>
if not @query_result.profile?
@$el.html @template {}
else
profile = @query_result.profile
@$el.html @template
profile:
clipboard_text: JSON.stringify profile, null, 2
tree: @json_to_tree profile
total_duration: util.prettify_duration @parent.container.driver_handler.total_duration
server_duration: util.prettify_duration @compute_total_duration profile
num_shard_accesses: @compute_num_shard_accesses profile
@clip.glue(@$('button.copy_profile'))
@delegateEvents()
@
class ResultViewWrapper extends Backbone.View
className: 'result_view'
template: require('../handlebars/dataexplorer_result_container.hbs')
option_template: require('../handlebars/dataexplorer-option_page.hbs')
error_template: require('../handlebars/dataexplorer-error.hbs')
cursor_timed_out_template: require('../handlebars/dataexplorer-cursor_timed_out.hbs')
primitive_key: '_-primitive value-_--' # We suppose that there is no key with such value in the database.
views:
tree: TreeView
table: TableView
profile: ProfileView
raw: RawView
events: ->
'click .link_to_profile_view': 'show_profile'
'click .link_to_tree_view': 'show_tree'
'click .link_to_table_view': 'show_table'
'click .link_to_raw_view': 'show_raw'
'click .activate_profiler': 'activate_profiler'
'click .more_results_link': 'show_next_batch'
'click .pause_feed': 'pause_feed'
'click .unpause_feed': 'unpause_feed'
initialize: (args) =>
@container = args.container
@view = args.view
@view_object = null
@scroll_handler = => @handle_scroll()
@floating_metadata = false
$(window).on('scroll', @scroll_handler)
@handle_scroll()
handle_scroll: =>
scroll = $(window).scrollTop()
pos = @$('.results_header').offset()?.top + 2
if not pos?
return
if @floating_metadata and pos > scroll
@floating_metadata = false
@$('.metadata').removeClass('floating_metadata')
if @container.state.pause_at?
@unpause_feed 'automatic'
if not @floating_metadata and pos < scroll
@floating_metadata = true
@$('.metadata').addClass('floating_metadata')
if not @container.state.pause_at?
@pause_feed 'automatic'
pause_feed: (event) =>
if event is 'automatic'
@auto_unpause = true
else
@auto_unpause = false
event?.preventDefault()
@view_object?.pause_feed()
@$('.metadata').addClass('feed_paused').removeClass('feed_unpaused')
unpause_feed: (event) =>
if event is 'automatic'
if not @auto_unpause
return
else
event.preventDefault()
@view_object?.unpause_feed()
@$('.metadata').removeClass('feed_paused').addClass('feed_unpaused')
show_tree: (event) =>
event.preventDefault()
@set_view 'tree'
show_profile: (event) =>
event.preventDefault()
@set_view 'profile'
show_table: (event) =>
event.preventDefault()
@set_view 'table'
show_raw: (event) =>
event.preventDefault()
@set_view 'raw'
set_view: (view) =>
@view = view
@container.state.view = view
@$(".link_to_#{@view}_view").parent().addClass 'active'
@$(".link_to_#{@view}_view").parent().siblings().removeClass 'active'
if @query_result?.ready
@new_view()
# TODO: The scrollbar sometime shows up when it is not needed
set_scrollbar: =>
if @view is 'table'
content_name = '.json_table'
content_container = '.table_view_container'
else if @view is 'tree'
content_name = '.json_tree'
content_container = '.tree_view_container'
else if @view is 'profile'
content_name = '.json_tree'
content_container = '.profile_view_container'
else if @view is 'raw'
@$('.wrapper_scrollbar').hide()
# There is no scrolbar with the raw view
return
# Set the floating scrollbar
width_value = @$(content_name).innerWidth() # Include padding
if width_value < @$(content_container).width()
# If there is no need for scrollbar, we hide the one on the top
@$('.wrapper_scrollbar').hide()
if @set_scrollbar_scroll_handler?
$(window).unbind 'scroll', @set_scrollbar_scroll_handler
else
# Else we set the fake_content to the same width as the table that contains data and links the two scrollbars
@$('.wrapper_scrollbar').show()
@$('.scrollbar_fake_content').width width_value
$(".wrapper_scrollbar").scroll ->
$(content_container).scrollLeft($(".wrapper_scrollbar").scrollLeft())
$(content_container).scroll ->
$(".wrapper_scrollbar").scrollLeft($(content_container).scrollLeft())
position_scrollbar = ->
if $(content_container).offset()?
# Sometimes we don't have to display the scrollbar (when the results are not shown because the query is too big)
if $(window).scrollTop()+$(window).height() < $(content_container).offset().top+20 # bottom of the window < beginning of $('.json_table_container') // 20 pixels is the approximate height of the scrollbar (so we don't show JUST the scrollbar)
that.$('.wrapper_scrollbar').hide()
# We show the scrollbar and stick it to the bottom of the window because there ismore content below
else if $(window).scrollTop()+$(window).height() < $(content_container).offset().top+$(content_container).height() # bottom of the window < end of $('.json_table_container')
that.$('.wrapper_scrollbar').show()
that.$('.wrapper_scrollbar').css 'overflow', 'auto'
that.$('.wrapper_scrollbar').css 'margin-bottom', '0px'
# And sometimes we "hide" it
else
# We can not hide .wrapper_scrollbar because it would break the binding between wrapper_scrollbar and content_container
that.$('.wrapper_scrollbar').css 'overflow', 'hidden'
that = @
position_scrollbar()
@set_scrollbar_scroll_handler = position_scrollbar
$(window).scroll @set_scrollbar_scroll_handler
$(window).resize ->
position_scrollbar()
activate_profiler: (event) =>
event.preventDefault()
if @container.options_view.state is 'hidden'
@container.toggle_options
cb: =>
setTimeout( =>
if @container.state.options.profiler is false
@container.options_view.$('.option_description[data-option="profiler"]').click()
@container.options_view.$('.profiler_enabled').show()
@container.options_view.$('.profiler_enabled').css 'visibility', 'visible'
, 100)
else
if @container.state.options.profiler is false
@container.options_view.$('.option_description[data-option="profiler"]').click()
@container.options_view.$('.profiler_enabled').hide()
@container.options_view.$('.profiler_enabled').css 'visibility', 'visible'
@container.options_view.$('.profiler_enabled').slideDown 'fast'
render_error: (query, err, js_error) =>
@view_object?.remove()
@view_object = null
@query_result?.discard()
@$el.html @error_template
query: query
error: err.toString().replace(/^(\s*)/, '')
js_error: js_error is true
return @
set_query_result: ({query_result}) =>
@query_result?.discard()
@query_result = query_result
if query_result.ready
@render()
@new_view()
else
@query_result.on 'ready', () =>
@render()
@new_view()
@query_result.on 'end', =>
@render()
render: (args) =>
if @query_result?.ready
@view_object?.$el.detach()
has_more_data = not @query_result.ended and @query_result.position + @container.state.options.query_limit <= @query_result.size()
batch_size = @view_object?.current_batch_size()
@$el.html @template
range_begin: @query_result.position + 1
range_end: batch_size and @query_result.position + batch_size
query_has_changed: args?.query_has_changed
show_more_data: has_more_data and not @container.state.cursor_timed_out
cursor_timed_out_template: (
@cursor_timed_out_template() if not @query_result.ended and @container.state.cursor_timed_out)
execution_time_pretty: util.prettify_duration @query_result.server_duration
no_results: @query_result.ended and @query_result.size() == 0
num_results: @query_result.size()
floating_metadata: @floating_metadata
feed: @feed_info()
@$('.execution_time').tooltip
for_dataexplorer: true
trigger: 'hover'
placement: 'bottom'
@$('.tab-content').html @view_object?.$el
@$(".link_to_#{@view}_view").parent().addClass 'active'
return @
update_feed_metadata: =>
info = @feed_info()
if not info?
return
$('.feed_upcoming').text(info.upcoming)
$('.feed_overflow').parent().toggleClass('hidden', not info.overflow)
feed_info: =>
if @query_result.is_feed
total = @container.state.pause_at ? @query_result.size()
ended: @query_result.ended
overflow: @container.state.options.query_limit < total
paused: @container.state.pause_at?
upcoming: @query_result.size() - total
new_view: () =>
@view_object?.remove()
@view_object = new @views[@view]
parent: @
query_result: @query_result
@$('.tab-content').html @view_object.render().$el
@init_after_dom_rendered()
@set_scrollbar()
init_after_dom_rendered: =>
@view_object?.init_after_dom_rendered?()
# Check if the cursor timed out. If yes, make sure that the user cannot fetch more results
cursor_timed_out: =>
@container.state.cursor_timed_out = true
if @container.state.query_result?.ended is true
@$('.more_results_paragraph').html @cursor_timed_out_template()
remove: =>
@view_object?.remove()
if @query_result?.is_feed
@query_result.force_end_gracefully()
if @set_scrollbar_scroll_handler?
$(window).unbind 'scroll', @set_scrollbar_scroll_handler
$(window).unbind 'resize'
$(window).off('scroll', @scroll_handler)
super()
handle_mouseup: (event) =>
@view_object?.handle_mouseup?(event)
handle_mousemove: (event) =>
@view_object?.handle_mousedown?(event)
show_next_batch: (event) =>
event.preventDefault()
$(window).scrollTop($('.results_container').offset().top)
@view_object?.show_next_batch()
class OptionsView extends Backbone.View
dataexplorer_options_template: require('../handlebars/dataexplorer-options.hbs')
className: 'options_view'
events:
'click li:not(.text-input)': 'toggle_option'
'change #query_limit': 'change_query_limit'
initialize: (args) =>
@container = args.container
@options = args.options
@state = 'hidden'
toggle_option: (event) =>
event.preventDefault()
new_target = @$(event.target).data('option')
@$('#'+new_target).prop 'checked', !@options[new_target]
if event.target.nodeName isnt 'INPUT' # Label we catch if for us
new_value = @$('#'+new_target).is(':checked')
@options[new_target] = new_value
if window.localStorage?
window.localStorage.options = JSON.stringify @options
if new_target is 'profiler' and new_value is false
@$('.profiler_enabled').slideUp 'fast'
change_query_limit: (event) =>
query_limit = parseInt(@$("#query_limit").val(), 10) or DEFAULTS.options.query_limit
@options['query_limit'] = Math.max(query_limit, 1)
if window.localStorage?
window.localStorage.options = JSON.stringify @options
@$('#query_limit').val(@options['query_limit']) # In case the input is reset to 40
render: (displayed) =>
@$el.html @dataexplorer_options_template @options
if displayed is true
@$el.show()
@delegateEvents()
return @
class HistoryView extends Backbone.View
dataexplorer_history_template: require('../handlebars/dataexplorer-history.hbs')
dataexplorer_query_li_template: require('../handlebars/dataexplorer-query_li.hbs')
className: 'history_container'
size_history_displayed: 300
state: 'hidden' # hidden, visible
index_displayed: 0
events:
'click .load_query': 'load_query'
'click .delete_query': 'delete_query'
start_resize: (event) =>
@start_y = event.pageY
@start_height = @container.$('.nano').height()
@mouse_down = true
$('body').toggleClass('resizing', true)
handle_mousemove: (event) =>
if @mouse_down is true
@height_history = Math.max 0, @start_height-@start_y+event.pageY
@container.$('.nano').height @height_history
handle_mouseup: (event) =>
if @mouse_down is true
@mouse_down = false
$('.nano').nanoScroller({preventPageScrolling: true})
$('body').toggleClass('resizing', false)
initialize: (args) =>
@container = args.container
@history = args.history
@height_history = 204
render: (displayed) =>
@$el.html @dataexplorer_history_template()
if displayed is true
@$el.show()
if @history.length is 0
@$('.history_list').append @dataexplorer_query_li_template
no_query: true
displayed_class: 'displayed'
else
for query, i in @history
@$('.history_list').append @dataexplorer_query_li_template
query: query.query
broken_query: query.broken_query
id: i
num: i+1
@delegateEvents()
return @
load_query: (event) =>
id = @$(event.target).data().id
# Set + save codemirror
@container.codemirror.setValue @history[parseInt(id)].query
@container.state.current_query = @history[parseInt(id)].query
@container.save_current_query()
delete_query: (event) =>
that = @
# Remove the query and overwrite localStorage.rethinkdb_history
id = parseInt(@$(event.target).data().id)
@history.splice(id, 1)
window.localStorage.rethinkdb_history = JSON.stringify @history
# Animate the deletion
is_at_bottom = @$('.history_list').height() is $('.nano > .content').scrollTop()+$('.nano').height()
@$('#query_history_'+id).slideUp 'fast', =>
that.$(this).remove()
that.render()
that.container.adjust_collapsible_panel_height
is_at_bottom: is_at_bottom
add_query: (args) =>
query = args.query
broken_query = args.broken_query
that = @
is_at_bottom = @$('.history_list').height() is $('.nano > .content').scrollTop()+$('.nano').height()
@$('.history_list').append @dataexplorer_query_li_template
query: query
broken_query: broken_query
id: @history.length-1
num: @history.length
if @$('.no_history').length > 0
@$('.no_history').slideUp 'fast', ->
$(@).remove()
if that.state is 'visible'
that.container.adjust_collapsible_panel_height
is_at_bottom: is_at_bottom
else if that.state is 'visible'
@container.adjust_collapsible_panel_height
delay_scroll: true
is_at_bottom: is_at_bottom
clear_history: (event) =>
that = @
event.preventDefault()
@container.clear_history()
@history = @container.state.history
@$('.query_history').slideUp 'fast', ->
$(@).remove()
if that.$('.no_history').length is 0
that.$('.history_list').append that.dataexplorer_query_li_template
no_query: true
displayed_class: 'hidden'
that.$('.no_history').slideDown 'fast'
that.container.adjust_collapsible_panel_height
size: 40
move_arrow: 'show'
is_at_bottom: 'true'
class DriverHandler
constructor: (options) ->
@container = options.container
@concurrent = 0
@total_duration = 0
_begin: =>
if @concurrent == 0
@container.toggle_executing true
@begin_time = new Date()
@concurrent++
_end: =>
if @concurrent > 0
@concurrent--
now = new Date()
@total_duration += now - @begin_time
@begin_time = now
if @concurrent == 0
@container.toggle_executing false
close_connection: =>
if @connection?.open is true
driver.close @connection
@connection = null
@_end()
run_with_new_connection: (query, {callback, connection_error, optargs}) =>
@close_connection()
@total_duration = 0
@concurrent = 0
driver.connect (error, connection) =>
if error?
connection_error error
connection.removeAllListeners 'error' # See issue 1347
connection.on 'error', (error) =>
connection_error error
@connection = connection
@_begin()
query.private_run connection, optargs, (error, result) =>
@_end()
callback error, result
cursor_next: (cursor, {error, row, end}) =>
if not @connection?
end()
@_begin()
cursor.next (err, row_) =>
@_end()
if err?
if err.message is 'No more rows in the cursor.'
end()
else
error err
else
row row_
remove: =>
@close_connection()
exports.QueryResult = QueryResult
exports.Container = Container
exports.ResultView = ResultView
exports.TreeView = TreeView
exports.TableView = TableView
exports.RawView = RawView
exports.ProfileView = ProfileView
exports.ResultViewWrapper = ResultViewWrapper
exports.OptionsView = OptionsView
exports.HistoryView = HistoryView
exports.DriverHandler = DriverHandler
exports.dataexplorer_state = dataexplorer_state
| 199664 | # Copyright 2010-2015 RethinkDB, all rights reserved.
app = require('./app.coffee')
system_db = app.system_db
driver = app.driver
util = require('./util.coffee')
r = require('rethinkdb')
DEFAULTS =
current_query: null
query_result: null
cursor_timed_out: true
view: 'tree'
history_state: 'hidden'
last_keys: []
last_columns_size: {}
options_state: 'hidden'
options:
suggestions: true
electric_punctuation: false
profiler: false
query_limit: 40
history: []
focus_on_codemirror: true
Object.freeze(DEFAULTS)
Object.freeze(DEFAULTS.options)
# state is initially a mutable version of defaults. It's modified later
dataexplorer_state = _.extend({}, DEFAULTS)
# This class represents the results of a query.
#
# If there is a profile, `profile` is set. After a 'ready' event,
# one of `error`, `value` or `cursor` is always set, `type`
# indicates which. `ended` indicates whether there are any more
# results to read.
#
# It triggers the following events:
# * ready: The first response has been received
# * add: Another row has been received from a cursor
# * error: An error has occurred
# * end: There are no more documents to fetch
# * discard: The results have been discarded
class QueryResult
_.extend @::, Backbone.Events
constructor: (options) ->
@has_profile = options.has_profile
@current_query = options.current_query
@raw_query = options.raw_query
@driver_handler = options.driver_handler
@ready = false
@position = 0
@server_duration = null
if options.events?
for own event, handler of options.events
@on event, handler
# Can be used as a callback to run
set: (error, result) =>
if error?
@set_error error
else if not @discard_results
if @has_profile
@profile = result.profile
@server_duration = result.profile.reduce(((total, prof) ->
total + (prof['duration(ms)'] or prof['mean_duration(ms)'])), 0)
value = result.value
else
@profile = null
@server_duration = result?.profile[0]['duration(ms)']
value = result.value
if value? and typeof value._next is 'function' and value not instanceof Array # if it's a cursor
@type = 'cursor'
@results = []
@results_offset = 0
@cursor = value
@is_feed = @cursor.toString().match(/\[object .*Feed\]/)
@missing = 0
@ended = false
@server_duration = null # ignore server time if batched response
else
@type = 'value'
@value = value
@ended = true
@ready = true
@trigger 'ready', @
# Discard the results
discard: =>
@trigger 'discard', @
@off()
@type = 'discarded'
@discard_results = true
delete @profile
delete @value
delete @results
delete @results_offset
@cursor?.close().catch?(() -> null)
delete @cursor
# Gets the next result from the cursor
fetch_next: =>
if not @ended
try
@driver_handler.cursor_next @cursor,
end: () =>
@ended = true
@trigger 'end', @
error: (error) =>
if not @ended
@set_error error
row: (row) =>
if @discard_results
return
@results.push row
@trigger 'add', @, row
catch error
@set_error error
set_error: (error) =>
@type = 'error'
@error = error
@trigger 'error', @, error
@discard_results = true
@ended = true
size: =>
switch @type
when 'value'
if @value instanceof Array
return @value.length
else
return 1
when 'cursor'
return @results.length + @results_offset
force_end_gracefully: =>
if @is_feed
@ended = true
@cursor?.close().catch(() -> null)
@trigger 'end', @
drop_before: (n) =>
if n > @results_offset
@results = @results[n - @results_offset ..]
@results_offset = n
slice: (from, to) =>
if from < 0
from = @results.length + from
else
from = from - @results_offset
from = Math.max 0, from
if to?
if to < 0
to = @results.length + to
else
to = to - @results_offset
to = Math.min @results.length, to
return @results[from .. to]
else
return @results[from ..]
at_beginning: =>
if @results_offset?
return @results_offset == 0
else
return true
class Container extends Backbone.View
id: 'dataexplorer'
template: require('../handlebars/dataexplorer_view.hbs')
input_query_template: require('../handlebars/dataexplorer_input_query.hbs')
description_template: require('../handlebars/dataexplorer-description.hbs')
template_suggestion_name: require('../handlebars/dataexplorer_suggestion_name_li.hbs')
description_with_example_template: require('../handlebars/dataexplorer-description_with_example.hbs')
alert_connection_fail_template: require('../handlebars/alert-connection_fail.hbs')
databases_suggestions_template: require('../handlebars/dataexplorer-databases_suggestions.hbs')
tables_suggestions_template: require('../handlebars/dataexplorer-tables_suggestions.hbs')
reason_dataexplorer_broken_template: require('../handlebars/dataexplorer-reason_broken.hbs')
query_error_template: require('../handlebars/dataexplorer-query_error.hbs')
# Constants
line_height: 13 # Define the height of a line (used for a line is too long)
size_history: 50
max_size_stack: 100 # If the stack of the query (including function, string, object etc. is greater than @max_size_stack, we stop parsing the query
max_size_query: 1000 # If the query is more than 1000 char, we don't show suggestion (codemirror doesn't highlight/parse if the query is more than 1000 characdd_ters too
delay_toggle_abort: 70 # If a query didn't return during this period (ms) we let people abort the query
events:
'mouseup .CodeMirror': 'handle_click'
'mousedown .suggestion_name_li': 'select_suggestion' # Keep mousedown to compete with blur on .input_query
'mouseover .suggestion_name_li' : 'mouseover_suggestion'
'mouseout .suggestion_name_li' : 'mouseout_suggestion'
'click .clear_query': 'clear_query'
'click .execute_query': 'execute_query'
'click .abort_query': 'abort_query'
'click .change_size': 'toggle_size'
'click #rerun_query': 'execute_query'
'click .close': 'close_alert'
'click .clear_queries_link': 'clear_history_view'
'click .close_queries_link': 'toggle_history'
'click .toggle_options_link': 'toggle_options'
'mousedown .nano_border_bottom': 'start_resize_history'
# Let people click on the description and select text
'mousedown .suggestion_description': 'mouse_down_description'
'click .suggestion_description': 'stop_propagation'
'mouseup .suggestion_description': 'mouse_up_description'
'mousedown .suggestion_full_container': 'mouse_down_description'
'click .suggestion_full_container': 'stop_propagation'
'mousedown .CodeMirror': 'mouse_down_description'
'click .CodeMirror': 'stop_propagation'
mouse_down_description: (event) =>
@keep_suggestions_on_blur = true
@stop_propagation event
stop_propagation: (event) =>
event.stopPropagation()
mouse_up_description: (event) =>
@keep_suggestions_on_blur = false
@stop_propagation event
start_resize_history: (event) =>
@history_view.start_resize event
clear_history_view: (event) =>
that = @
@clear_history() # Delete from localstorage
@history_view.clear_history event
# Method that make sure that just one button (history or option) is active
# We give this button an "active" class that make it looks like it's pressed.
toggle_pressed_buttons: =>
if @history_view.state is 'visible'
dataexplorer_state.history_state = 'visible'
@$('.clear_queries_link').fadeIn 'fast'
@$('.close_queries_link').addClass 'active'
else
dataexplorer_state.history_state = 'hidden'
@$('.clear_queries_link').fadeOut 'fast'
@$('.close_queries_link').removeClass 'active'
if @options_view.state is 'visible'
dataexplorer_state.options_state = 'visible'
@$('.toggle_options_link').addClass 'active'
else
dataexplorer_state.options_state = 'hidden'
@$('.toggle_options_link').removeClass 'active'
# Show/hide the history view
toggle_history: (args) =>
that = @
@deactivate_overflow()
if args.no_animation is true
# We just show the history
@history_view.state = 'visible'
@$('.content').html @history_view.render(true).$el
@move_arrow
type: 'history'
move_arrow: 'show'
@adjust_collapsible_panel_height
no_animation: true
is_at_bottom: true
else if @options_view.state is 'visible'
@options_view.state = 'hidden'
@move_arrow
type: 'history'
move_arrow: 'animate'
@options_view.$el.fadeOut 'fast', ->
that.$('.content').html that.history_view.render(false).$el
that.history_view.state = 'visible'
that.history_view.$el.fadeIn 'fast'
that.adjust_collapsible_panel_height
is_at_bottom: true
that.toggle_pressed_buttons() # Re-execute toggle_pressed_buttons because we delay the fadeIn
else if @history_view.state is 'hidden'
@history_view.state = 'visible'
@$('.content').html @history_view.render(true).$el
@history_view.delegateEvents()
@move_arrow
type: 'history'
move_arrow: 'show'
@adjust_collapsible_panel_height
is_at_bottom: true
else if @history_view.state is 'visible'
@history_view.state = 'hidden'
@hide_collapsible_panel 'history'
@toggle_pressed_buttons()
# Show/hide the options view
toggle_options: (args) =>
that = @
@deactivate_overflow()
if args?.no_animation is true
@options_view.state = 'visible'
@$('.content').html @options_view.render(true).$el
@options_view.delegateEvents()
@move_arrow
type: 'options'
move_arrow: 'show'
@adjust_collapsible_panel_height
no_animation: true
is_at_bottom: true
else if @history_view.state is 'visible'
@history_view.state = 'hidden'
@move_arrow
type: 'options'
move_arrow: 'animate'
@history_view.$el.fadeOut 'fast', ->
that.$('.content').html that.options_view.render(false).$el
that.options_view.state = 'visible'
that.options_view.$el.fadeIn 'fast'
that.adjust_collapsible_panel_height()
that.toggle_pressed_buttons()
that.$('.profiler_enabled').css 'visibility', 'hidden'
that.$('.profiler_enabled').hide()
else if @options_view.state is 'hidden'
@options_view.state = 'visible'
@$('.content').html @options_view.render(true).$el
@options_view.delegateEvents()
@move_arrow
type: 'options'
move_arrow: 'show'
@adjust_collapsible_panel_height
cb: args?.cb
else if @options_view.state is 'visible'
@options_view.state = 'hidden'
@hide_collapsible_panel 'options'
@toggle_pressed_buttons()
# Hide the collapsible_panel whether it contains the option or history view
hide_collapsible_panel: (type) =>
that = @
@deactivate_overflow()
@$('.nano').animate
height: 0
, 200
, ->
that.activate_overflow()
# We don't want to hide the view if the user changed the state of the view while it was being animated
if (type is 'history' and that.history_view.state is 'hidden') or (type is 'options' and that.options_view.state is 'hidden')
that.$('.nano_border').hide() # In case the user trigger hide/show really fast
that.$('.arrow_dataexplorer').hide() # In case the user trigger hide/show really fast
that.$(@).css 'visibility', 'hidden'
@$('.nano_border').slideUp 'fast'
@$('.arrow_dataexplorer').slideUp 'fast'
# Move the arrow that points to the active button (on top of the collapsible panel). In case the user switch from options to history (or the opposite), we need to animate it
move_arrow: (args) =>
# args =
# type: 'options'/'history'
# move_arrow: 'show'/'animate'
if args.type is 'options'
margin_right = 74
else if args.type is 'history'
margin_right = 154
if args.move_arrow is 'show'
@$('.arrow_dataexplorer').css 'margin-right', margin_right
@$('.arrow_dataexplorer').show()
else if args.move_arrow is 'animate'
@$('.arrow_dataexplorer').animate
'margin-right': margin_right
, 200
@$('.nano_border').show()
# Adjust the height of the container of the history/option view
# Arguments:
# size: size of the collapsible panel we want // If not specified, we are going to try to figure it out ourselves
# no_animation: boolean (do we need to animate things or just to show it)
# is_at_bottom: boolean (if we were at the bottom, we want to scroll down once we have added elements in)
# delay_scroll: boolean, true if we just added a query - It speficied if we adjust the height then scroll or do both at the same time
adjust_collapsible_panel_height: (args) =>
that = @
if args?.size?
size = args.size
else
if args?.extra?
size = Math.min @$('.content > div').height()+args.extra, @history_view.height_history
else
size = Math.min @$('.content > div').height(), @history_view.height_history
@deactivate_overflow()
duration = Math.max 150, size
duration = Math.min duration, 250
#@$('.nano').stop(true, true).animate
@$('.nano').css 'visibility', 'visible' # In case the user trigger hide/show really fast
if args?.no_animation is true
@$('.nano').height size
@$('.nano > .content').scrollTop @$('.nano > .content > div').height()
@$('.nano').css 'visibility', 'visible' # In case the user trigger hide/show really fast
@$('.arrow_dataexplorer').show() # In case the user trigger hide/show really fast
@$('.nano_border').show() # In case the user trigger hide/show really fast
if args?.no_animation is true
@$('.nano').nanoScroller({preventPageScrolling: true})
@activate_overflow()
else
@$('.nano').animate
height: size
, duration
, ->
that.$(@).css 'visibility', 'visible' # In case the user trigger hide/show really fast
that.$('.arrow_dataexplorer').show() # In case the user trigger hide/show really fast
that.$('.nano_border').show() # In case the user trigger hide/show really fast
that.$(@).nanoScroller({preventPageScrolling: true})
that.activate_overflow()
if args? and args.delay_scroll is true and args.is_at_bottom is true
that.$('.nano > .content').animate
scrollTop: that.$('.nano > .content > div').height()
, 200
if args?.cb?
args.cb()
if args? and args.delay_scroll isnt true and args.is_at_bottom is true
that.$('.nano > .content').animate
scrollTop: that.$('.nano > .content > div').height()
, 200
# We deactivate the scrollbar (if there isn't) while animating to have a smoother experience. We´ll put back the scrollbar once the animation is done.
deactivate_overflow: =>
if $(window).height() >= $(document).height()
$('body').css 'overflow', 'hidden'
activate_overflow: =>
$('body').css 'overflow', 'auto'
displaying_full_view: false # Boolean for the full view (true if full view)
# Method to close an alert/warning/arror
close_alert: (event) ->
event.preventDefault()
$(event.currentTarget).parent().slideUp('fast', -> $(this).remove())
# Build the suggestions
map_state: # Map function -> state
'': ''
descriptions: {}
suggestions: {} # Suggestions[state] = function for this state
types:
value: ['number', 'bool', 'string', 'array', 'object', 'time', 'binary', 'line', 'point', 'polygon']
any: ['number', 'bool', 'string', 'array', 'object', 'stream', 'selection', 'table', 'db', 'r', 'error', 'binary', 'line', 'point', 'polygon']
geometry: ['line', 'point', 'polygon']
sequence: ['table', 'selection', 'stream', 'array']
stream: ['table', 'selection']
grouped_stream: ['stream', 'array']
# Convert meta types (value, any or sequence) to an array of types or return an array composed of just the type
convert_type: (type) =>
if @types[type]?
return @types[type]
else
return [type]
# Flatten an array
expand_types: (ar) =>
result = []
if _.isArray(ar)
for element in ar
result.concat @convert_type element
else
result.concat @convert_type element
return result
# Once we are done moving the doc, we could generate a .js in the makefile file with the data so we don't have to do an ajax request+all this stuff
set_doc_description: (command, tag, suggestions) =>
if command['body']?
# The body of `bracket` uses `()` and not `bracket()`
# so we manually set the variables dont_need_parenthesis and full_tag
if tag is 'bracket'
dont_need_parenthesis = false
full_tag = tag+'('
else
dont_need_parenthesis = not (new RegExp(tag+'\\(')).test(command['body'])
if dont_need_parenthesis
full_tag = tag # Here full_tag is just the name of the tag
else
full_tag = tag+'(' # full tag is the name plus a parenthesis (we will match the parenthesis too)
@descriptions[full_tag] = (grouped_data) =>
name: tag
args: /.*(\(.*\))/.exec(command['body'])?[1]
description:
@description_with_example_template
description: command['description']
example: command['example']
grouped_data: grouped_data is true and full_tag isnt 'group(' and full_tag isnt 'ungroup('
parents = {}
returns = []
for pair in command.io ? []
parent_values = if (pair[0] == null) then '' else pair[0]
return_values = pair[1]
parent_values = @convert_type parent_values
return_values = @convert_type return_values
returns = returns.concat return_values
for parent_value in parent_values
parents[parent_value] = true
if full_tag isnt '('
for parent_value of parents
if not suggestions[parent_value]?
suggestions[parent_value] = []
suggestions[parent_value].push full_tag
@map_state[full_tag] = returns # We use full_tag because we need to differentiate between r. and r(
# All the commands we are going to ignore
ignored_commands:
'connect': true
'close': true
'reconnect': true
'use': true
'runp': true
'next': true
'collect': true
'run': true
'EventEmitter\'s methods': true
# Method called on the content of reql_docs.json
# Load the suggestions in @suggestions, @map_state, @descriptions
set_docs: (data) =>
for key of data
command = data[key]
tag = command['name']
if tag of @ignored_commands
continue
if tag is '() (bracket)' # The parentheses will be added later
# Add `(attr)`
tag = ''
@set_doc_description command, tag, @suggestions
# Add `bracket(sttr)`
tag = 'bracket'
else if tag is 'toJsonString, toJSON'
# Add the `toJsonString()` alias
tag = 'toJsonString'
@set_doc_description command, tag, @suggestions
# Also add `toJSON()`
tag = 'toJSON'
@set_doc_description command, tag, @suggestions
relations = data['types']
for state of @suggestions
@suggestions[state].sort()
if Container.prototype.focus_on_codemirror is true
# "@" refers to prototype -_-
# In case we give focus to codemirror then load the docs, we show the suggestion
app.main.router.current_view.handle_keypress()
# Save the query in the history
# The size of the history is infinite per session. But we will just save @size_history queries in localStorage
save_query: (args) =>
query = args.query
broken_query = args.broken_query
# Remove empty lines
query = query.replace(/^\s*$[\n\r]{1,}/gm, '')
query = query.replace(/\s*$/, '') # Remove the white spaces at the end of the query (like newline/space/tab)
if window.localStorage?
if dataexplorer_state.history.length is 0 or dataexplorer_state.history[dataexplorer_state.history.length-1].query isnt query and @regex.white.test(query) is false
dataexplorer_state.history.push
query: query
broken_query: broken_query
if dataexplorer_state.history.length>@size_history
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history.slice dataexplorer_state.history.length-@size_history
else
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history
@history_view.add_query
query: query
broken_query: broken_query
clear_history: =>
dataexplorer_state.history.length = 0
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history
# Save the current query (the one in codemirror) in local storage
save_current_query: =>
if window.localStorage?
window.localStorage.current_query = JSON.stringify @codemirror.getValue()
initialize: (args) =>
@TermBaseConstructor = r.expr(1).constructor.__super__.constructor.__super__.constructor
@state = args.state
@executing = false
# Load options from local storage
if window.localStorage?
try
@state.options = JSON.parse(window.localStorage.options)
# Ensure no keys are without a default value in the
# options object
_.defaults(@state.options, DEFAULTS.options)
catch err
window.localStorage.removeItem 'options'
# Whatever the case with default values, we need to sync
# up with the current application's idea of the options
window.localStorage.options = JSON.stringify(@state.options)
# Load the query that was written in code mirror (that may not have been executed before)
if typeof window.localStorage?.current_query is 'string'
try
dataexplorer_state.current_query = JSON.parse window.localStorage.current_query
catch err
window.localStorage.removeItem 'current_query'
if window.localStorage?.rethinkdb_history?
try
dataexplorer_state.history = JSON.parse window.localStorage.rethinkdb_history
catch err
window.localStorage.removeItem 'rethinkdb_history'
@query_has_changed = dataexplorer_state.query_result?.current_query isnt dataexplorer_state.current_query
# Index used to navigate through history with the keyboard
@history_displayed_id = 0 # 0 means we are showing the draft, n>0 means we are showing the nth query in the history
# We escape the last function because we are building a regex on top of it.
# Structure: [ [ pattern, replacement], [pattern, replacement], ... ]
@unsafe_to_safe_regexstr = [
[/\\/g, '\\\\'] # This one has to be first
[/\(/g, '\\(']
[/\)/g, '\\)']
[/\^/g, '\\^']
[/\$/g, '\\$']
[/\*/g, '\\*']
[/\+/g, '\\+']
[/\?/g, '\\?']
[/\./g, '\\.']
[/\|/g, '\\|']
[/\{/g, '\\{']
[/\}/g, '\\}']
[/\[/g, '\\[']
]
@results_view_wrapper = new ResultViewWrapper
container: @
view: dataexplorer_state.view
@options_view = new OptionsView
container: @
options: dataexplorer_state.options
@history_view = new HistoryView
container: @
history: dataexplorer_state.history
@driver_handler = new DriverHandler
container: @
# These events were caught here to avoid being bound and unbound every time
# The results changed. It should ideally be caught in the individual result views
# that actually need it.
$(window).mousemove @handle_mousemove
$(window).mouseup @handle_mouseup
$(window).mousedown @handle_mousedown
@keep_suggestions_on_blur = false
@databases_available = {}
@fetch_data()
fetch_data: =>
# We fetch all "proper" tables from `table_config`. In addition, we need
# to fetch the list of system tables separately.
query = r.db(system_db).table('table_config')
.pluck('db', 'name')
.group('db')
.ungroup()
.map((group) -> [group("group"), group("reduction")("name").orderBy( (x) -> x )])
.coerceTo "OBJECT"
.merge(r.object(system_db, r.db(system_db).tableList().coerceTo("ARRAY")))
@timer = driver.run query, 5000, (error, result) =>
if error?
# Nothing bad, we'll try again, let's just log the error
console.log "Error: Could not fetch databases and tables"
console.log error
else
@databases_available = result
handle_mousemove: (event) =>
@results_view_wrapper.handle_mousemove event
@history_view.handle_mousemove event
handle_mouseup: (event) =>
@results_view_wrapper.handle_mouseup event
@history_view.handle_mouseup event
handle_mousedown: (event) =>
# $(window) caught a mousedown event, so it wasn't caught by $('.suggestion_description')
# Let's hide the suggestion/description
@keep_suggestions_on_blur = false
@hide_suggestion_and_description()
render: =>
@$el.html @template()
@$('.input_query_full_container').html @input_query_template()
# Check if the browser supports the JavaScript driver
# We do not support internet explorer (even IE 10) and old browsers.
if navigator?.appName is 'Microsoft Internet Explorer'
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
is_internet_explorer: true
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
else if (not DataView?) or (not Uint8Array?) # The main two components that the javascript driver requires.
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
else if not r? # In case the javascript driver is not found (if build from source for example)
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
no_driver: true
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
# Let's bring back the data explorer to its old state (if there was)
if dataexplorer_state?.query_result?
@results_view_wrapper.set_query_result
query_result: dataexplorer_state.query_result
@$('.results_container').html @results_view_wrapper.render(query_has_changed: @query_has_changed).$el
# The query in code mirror is set in init_after_dom_rendered (because we can't set it now)
return @
# This method has to be called AFTER the el element has been inserted in the DOM tree, mostly for codemirror
init_after_dom_rendered: =>
@codemirror = CodeMirror.fromTextArea document.getElementById('input_query'),
mode:
name: 'javascript'
onKeyEvent: @handle_keypress
lineNumbers: true
lineWrapping: true
matchBrackets: true
tabSize: 2
@codemirror.on 'blur', @on_blur
@codemirror.on 'gutterClick', @handle_gutter_click
@codemirror.setSize '100%', 'auto'
if dataexplorer_state.current_query?
@codemirror.setValue dataexplorer_state.current_query
@codemirror.focus() # Give focus
# Track if the focus is on codemirror
# We use it to refresh the docs once the reql_docs.json is loaded
dataexplorer_state.focus_on_codemirror = true
@codemirror.setCursor @codemirror.lineCount(), 0
if @codemirror.getValue() is '' # We show suggestion for an empty query only
@handle_keypress()
@results_view_wrapper.init_after_dom_rendered()
@draft = @codemirror.getValue()
if dataexplorer_state.history_state is 'visible' # If the history was visible, we show it
@toggle_history
no_animation: true
if dataexplorer_state.options_state is 'visible' # If the history was visible, we show it
@toggle_options
no_animation: true
on_blur: =>
dataexplorer_state.focus_on_codemirror = false
# We hide the description only if the user isn't selecting text from a description.
if @keep_suggestions_on_blur is false
@hide_suggestion_and_description()
# We have to keep track of a lot of things because web-kit browsers handle the events keydown, keyup, blur etc... in a strange way.
current_suggestions: []
current_highlighted_suggestion: -1
current_conpleted_query: ''
query_first_part: ''
query_last_part: ''
mouse_type_event:
click: true
dblclick: true
mousedown: true
mouseup: true
mouseover: true
mouseout: true
mousemove: true
char_breakers:
'.': true
'}': true
')': true
',': true
';': true
']': true
handle_click: (event) =>
@handle_keypress null, event
# Pair ', ", {, [, (
# Return true if we want code mirror to ignore the key event
pair_char: (event, stack) =>
if event?.which?
# If there is a selection and the user hit a quote, we wrap the seleciton in quotes
if @codemirror.getSelection() isnt '' and event.type is 'keypress' # This is madness. If we look for keydown, shift+right arrow match a single quote...
char_to_insert = String.fromCharCode event.which
if char_to_insert? and char_to_insert is '"' or char_to_insert is "'"
@codemirror.replaceSelection(char_to_insert+@codemirror.getSelection()+char_to_insert)
event.preventDefault()
return true
if event.which is 8 # Backspace
if event.type isnt 'keydown'
return true
previous_char = @get_previous_char()
if previous_char is null
return true
# If the user remove the opening bracket and the next char is the closing bracket, we delete both
if previous_char of @matching_opening_bracket
next_char = @get_next_char()
if next_char is @matching_opening_bracket[previous_char]
num_not_closed_bracket = @count_not_closed_brackets previous_char
if num_not_closed_bracket <= 0
@remove_next()
return true
# If the user remove the first quote of an empty string, we remove both quotes
else if previous_char is '"' or previous_char is "'"
next_char = @get_next_char()
if next_char is previous_char and @get_previous_char(2) isnt '\\'
num_quote = @count_char char_to_insert
if num_quote%2 is 0
@remove_next()
return true
return true
if event.type isnt 'keypress' # We catch keypress because single and double quotes have not the same keyCode on keydown/keypres #thisIsMadness
return true
char_to_insert = String.fromCharCode event.which
if char_to_insert? # and event.which isnt 91 # 91 map to [ on OS X
if @codemirror.getSelection() isnt ''
if (char_to_insert of @matching_opening_bracket or char_to_insert of @matching_closing_bracket)
@codemirror.replaceSelection ''
else
return true
last_element_incomplete_type = @last_element_type_if_incomplete(stack)
if char_to_insert is '"' or char_to_insert is "'"
num_quote = @count_char char_to_insert
next_char = @get_next_char()
if next_char is char_to_insert # Next char is a single quote
if num_quote%2 is 0
if last_element_incomplete_type is 'string' or last_element_incomplete_type is 'object_key' # We are at the end of a string and the user just wrote a quote
@move_cursor 1
event.preventDefault()
return true
else
# We are at the begining of a string, so let's just add one quote
return true
else
# Let's add the closing/opening quote missing
return true
else
if num_quote%2 is 0 # Next char is not a single quote and the user has an even number of quotes.
# Let's keep a number of quote even, so we add one extra quote
last_key = @get_last_key(stack)
if last_element_incomplete_type is 'string'
return true
else if last_element_incomplete_type is 'object_key' and (last_key isnt '' and @create_safe_regex(char_to_insert).test(last_key) is true) # A key in an object can be seen as a string
return true
else
@insert_next char_to_insert
else # Else we'll just insert one quote
return true
else if last_element_incomplete_type isnt 'string'
next_char = @get_next_char()
if char_to_insert of @matching_opening_bracket
num_not_closed_bracket = @count_not_closed_brackets char_to_insert
if num_not_closed_bracket >= 0 # We insert a closing bracket only if it help having a balanced number of opened/closed brackets
@insert_next @matching_opening_bracket[char_to_insert]
return true
return true
else if char_to_insert of @matching_closing_bracket
opening_char = @matching_closing_bracket[char_to_insert]
num_not_closed_bracket = @count_not_closed_brackets opening_char
if next_char is char_to_insert
if num_not_closed_bracket <= 0 # g(f(...|) In this case we add a closing parenthesis. Same behavior as in Ace
@move_cursor 1
event.preventDefault()
return true
return false
get_next_char: =>
cursor_end = @codemirror.getCursor()
cursor_end.ch++
return @codemirror.getRange @codemirror.getCursor(), cursor_end
get_previous_char: (less_value) =>
cursor_start = @codemirror.getCursor()
cursor_end = @codemirror.getCursor()
if less_value?
cursor_start.ch -= less_value
cursor_end.ch -= (less_value-1)
else
cursor_start.ch--
if cursor_start.ch < 0
return null
return @codemirror.getRange cursor_start, cursor_end
# Insert str after the cursor in codemirror
insert_next: (str) =>
@codemirror.replaceRange str, @codemirror.getCursor()
@move_cursor -1
remove_next: =>
end_cursor = @codemirror.getCursor()
end_cursor.ch++
@codemirror.replaceRange '', @codemirror.getCursor(), end_cursor
# Move cursor of move_value
# A negative value move the cursor to the left
move_cursor: (move_value) =>
cursor = @codemirror.getCursor()
cursor.ch += move_value
if cursor.ch < 0
cursor.ch = 0
@codemirror.setCursor cursor
# Count how many time char_to_count appeared ignoring strings and comments
count_char: (char_to_count) =>
query = @codemirror.getValue()
is_parsing_string = false
to_skip = 0
result = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
if char is char_to_count
result++
else # if element.is_parsing_string is false
if char is char_to_count
result++
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
return result
matching_opening_bracket:
'(': ')'
'{': '}'
'[': ']'
matching_closing_bracket:
')': '('
'}': '{'
']': '['
# opening_char has to be in @matching_bracket
# Count how many time opening_char has been opened but not closed
# A result < 0 means that the closing char has been found more often than the opening one
count_not_closed_brackets: (opening_char) =>
query = @codemirror.getValue()
is_parsing_string = false
to_skip = 0
result = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
else # if element.is_parsing_string is false
if char is opening_char
result++
else if char is @matching_opening_bracket[opening_char]
result--
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
return result
# Handle events on codemirror
# Return true if we want code mirror to ignore the event
handle_keypress: (editor, event) =>
if @ignored_next_keyup is true
if event?.type is 'keyup' and event?.which isnt 9
@ignored_next_keyup = false
return true
dataexplorer_state.focus_on_codemirror = true
# Let's hide the tooltip if the user just clicked on the textarea. We'll only display later the suggestions if there are (no description)
if event?.type is 'mouseup'
@hide_suggestion_and_description()
# Save the last query (even incomplete)
dataexplorer_state.current_query = @codemirror.getValue()
@save_current_query()
# Look for special commands
if event?.which?
if event.type isnt 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32)
# Because on event.type == 'keydown' we are going to change the state (hidden or displayed) of @$('.suggestion_description') and @$('.suggestion_name_list'), we don't want to fire this event a second time
return true
if event.which is 27 or (event.type is 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32) and (@$('.suggestion_description').css('display') isnt 'none' or @$('.suggestion_name_list').css('display') isnt 'none'))
# We caugh ESC or (Ctrl/Cmd+space with suggestion/description being displayed)
event.preventDefault() # Keep focus on code mirror
@hide_suggestion_and_description()
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
query_after_cursor = @codemirror.getRange @codemirror.getCursor(), {line:@codemirror.lineCount()+1, ch: 0}
# Compute the structure of the query written by the user.
# We compute it earlier than before because @pair_char also listen on keydown and needs stack
stack = @extract_data_from_query
size_stack: 0
query: query_before_cursor
position: 0
if stack is null # Stack is null if the query was too big for us to parse
@ignore_tab_keyup = false
@hide_suggestion_and_description()
return false
@current_highlighted_suggestion = -1
@current_highlighted_extra_suggestion = -1
@$('.suggestion_name_list').empty()
# Valid step, let's save the data
@query_last_part = query_after_cursor
@current_suggestions = []
@current_element = ''
@current_extra_suggestion = ''
@written_suggestion = null
@cursor_for_auto_completion = @codemirror.getCursor()
@description = null
result =
status: null
# create_suggestion is going to fill to_complete and to_describe
#to_complete: undefined
#to_describe: undefined
# Create the suggestion/description
@create_suggestion
stack: stack
query: query_before_cursor
result: result
result.suggestions = @uniq result.suggestions
@grouped_data = @count_group_level(stack).count_group > 0
if result.suggestions?.length > 0
for suggestion, i in result.suggestions
if suggestion isnt 'ungroup(' or @grouped_data is true # We add the suggestion for `ungroup` only if we are in a group_stream/data (using the flag @grouped_data)
result.suggestions.sort() # We could eventually sort things earlier with a merge sort but for now that should be enough
@current_suggestions.push suggestion
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
else if result.description?
@description = result.description
return true
else if event.which is 13 and (event.shiftKey is false and event.ctrlKey is false and event.metaKey is false)
if event.type is 'keydown'
if @current_highlighted_suggestion > -1
event.preventDefault()
@handle_keypress()
return true
previous_char = @get_previous_char()
if previous_char of @matching_opening_bracket
next_char = @get_next_char()
if @matching_opening_bracket[previous_char] is next_char
cursor = @codemirror.getCursor()
@insert_next '\n'
@codemirror.indentLine cursor.line+1, 'smart'
@codemirror.setCursor cursor
return false
else if (event.which is 9 and event.ctrlKey is false) or (event.type is 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32) and (@$('.suggestion_description').css('display') is 'none' and @.$('.suggestion_name_list').css('display') is 'none'))
# If the user just hit tab, we are going to show the suggestions if they are hidden
# or if they suggestions are already shown, we are going to cycle through them.
#
# If the user just hit Ctrl/Cmd+space with suggestion/description being hidden we show the suggestions
# Note that the user cannot cycle through suggestions because we make sure in the IF condition that suggestion/description are hidden
# If the suggestions/description are visible, the event will be caught earlier with ESC
event.preventDefault()
if event.type isnt 'keydown'
return false
else
if @current_suggestions?.length > 0
if @$('.suggestion_name_list').css('display') is 'none'
@show_suggestion()
return true
else
# We can retrieve the content of codemirror only on keyup events. The users may write "r." then hit "d" then "tab" If the events are triggered this way
# keydown d - keydown tab - keyup d - keyup tab
# We want to only show the suggestions for r.d
if @written_suggestion is null
cached_query = @query_first_part+@current_element+@query_last_part
else
cached_query = @query_first_part+@written_suggestion+@query_last_part
if cached_query isnt @codemirror.getValue() # We fired a keydown tab before a keyup, so our suggestions are not up to date
@current_element = @codemirror.getValue().slice @query_first_part.length, @codemirror.getValue().length-@query_last_part.length
regex = @create_safe_regex @current_element
new_suggestions = []
new_highlighted_suggestion = -1
for suggestion, index in @current_suggestions
if index < @current_highlighted_suggestion
new_highlighted_suggestion = new_suggestions.length
if regex.test(suggestion) is true
new_suggestions.push suggestion
@current_suggestions = new_suggestions
@current_highlighted_suggestion = new_highlighted_suggestion
if @current_suggestions.length > 0
@$('.suggestion_name_list').empty()
for suggestion, i in @current_suggestions
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
@ignored_next_keyup = true
else
@hide_suggestion_and_description()
# Switch throught the suggestions
if event.shiftKey
@current_highlighted_suggestion--
if @current_highlighted_suggestion < -1
@current_highlighted_suggestion = @current_suggestions.length-1
else if @current_highlighted_suggestion < 0
@show_suggestion_without_moving()
@remove_highlight_suggestion()
@write_suggestion
suggestion_to_write: @current_element
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
return true
else
@current_highlighted_suggestion++
if @current_highlighted_suggestion >= @current_suggestions.length
@show_suggestion_without_moving()
@remove_highlight_suggestion()
@write_suggestion
suggestion_to_write: @current_element
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
@current_highlighted_suggestion = -1
return true
if @current_suggestions[@current_highlighted_suggestion]?
@show_suggestion_without_moving()
@highlight_suggestion @current_highlighted_suggestion # Highlight the current suggestion
@write_suggestion
suggestion_to_write: @current_suggestions[@current_highlighted_suggestion] # Auto complete with the highlighted suggestion
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
return true
else if @description?
if @$('.suggestion_description').css('display') is 'none'
# We show it once only because we don't want to move the cursor around
@show_description()
return true
if @extra_suggestions? and @extra_suggestions.length > 0 and @extra_suggestion.start_body is @extra_suggestion.start_body
# Trim suggestion
if @extra_suggestion?.body?[0]?.type is 'string'
if @extra_suggestion.body[0].complete is true
@extra_suggestions = []
else
# Remove quotes around the table/db name
current_name = @extra_suggestion.body[0].name.replace(/^\s*('|")/, '').replace(/('|")\s*$/, '')
regex = @create_safe_regex current_name
new_extra_suggestions = []
for suggestion in @extra_suggestions
if regex.test(suggestion) is true
new_extra_suggestions.push suggestion
@extra_suggestions = new_extra_suggestions
if @extra_suggestions.length > 0 # If there are still some valid suggestions
query = @codemirror.getValue()
# We did not parse what is after the cursor, so let's take a look
start_search = @extra_suggestion.start_body
if @extra_suggestion.body?[0]?.name.length?
start_search += @extra_suggestion.body[0].name.length
# Define @query_first_part and @query_last_part
# Note that ) is not a valid character for a db/table name
end_body = query.indexOf ')', start_search
@query_last_part = ''
if end_body isnt -1
@query_last_part = query.slice end_body
@query_first_part = query.slice 0, @extra_suggestion.start_body
lines = @query_first_part.split('\n')
if event.shiftKey is true
@current_highlighted_extra_suggestion--
else
@current_highlighted_extra_suggestion++
if @current_highlighted_extra_suggestion >= @extra_suggestions.length
@current_highlighted_extra_suggestion = -1
else if @current_highlighted_extra_suggestion < -1
@current_highlighted_extra_suggestion = @extra_suggestions.length-1
# Create the next suggestion
suggestion = ''
if @current_highlighted_extra_suggestion is -1
if @current_extra_suggestion?
if /^\s*'/.test(@current_extra_suggestion) is true
suggestion = @current_extra_suggestion+"'"
else if /^\s*"/.test(@current_extra_suggestion) is true
suggestion = @current_extra_suggestion+'"'
else
if dataexplorer_state.options.electric_punctuation is false
move_outside = true
if /^\s*'/.test(@current_extra_suggestion) is true
string_delimiter = "'"
else if /^\s*"/.test(@current_extra_suggestion) is true
string_delimiter = '"'
else
string_delimiter = "'"
move_outside = true
suggestion = string_delimiter+@extra_suggestions[@current_highlighted_extra_suggestion]+string_delimiter
@write_suggestion
move_outside: move_outside
suggestion_to_write: suggestion
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
# If the user hit enter and (Ctrl or Shift)
if event.which is 13 and (event.shiftKey or event.ctrlKey or event.metaKey)
@hide_suggestion_and_description()
event.preventDefault()
if event.type isnt 'keydown'
return true
@execute_query()
return true
# Ctrl/Cmd + V
else if (event.ctrlKey or event.metaKey) and event.which is 86 and event.type is 'keydown'
@last_action_is_paste = true
@num_released_keys = 0 # We want to know when the user release Ctrl AND V
if event.metaKey
@num_released_keys++ # Because on OS X, the keyup event is not fired when the metaKey is pressed (true for Firefox, Chrome, Safari at least...)
@hide_suggestion_and_description()
return true
# When the user release Ctrl/Cmd after a Ctrl/Cmd + V
else if event.type is 'keyup' and @last_action_is_paste is true and (event.which is 17 or event.which is 91)
@num_released_keys++
if @num_released_keys is 2
@last_action_is_paste = false
@hide_suggestion_and_description()
return true
# When the user release V after a Ctrl/Cmd + V
else if event.type is 'keyup' and @last_action_is_paste is true and event.which is 86
@num_released_keys++
if @num_released_keys is 2
@last_action_is_paste = false
@hide_suggestion_and_description()
return true
# Catching history navigation
else if event.type is 'keyup' and event.altKey and event.which is 38 # Key up
if @history_displayed_id < dataexplorer_state.history.length
@history_displayed_id++
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if event.type is 'keyup' and event.altKey and event.which is 40 # Key down
if @history_displayed_id > 1
@history_displayed_id--
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if @history_displayed_id is 1
@history_displayed_id--
@codemirror.setValue @draft
@codemirror.setCursor @codemirror.lineCount(), 0 # We hit the draft and put the cursor at the end
else if event.type is 'keyup' and event.altKey and event.which is 33 # Page up
@history_displayed_id = dataexplorer_state.history.length
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if event.type is 'keyup' and event.altKey and event.which is 34 # Page down
@history_displayed_id = @history.length
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
@codemirror.setCursor @codemirror.lineCount(), 0 # We hit the draft and put the cursor at the end
event.preventDefault()
return true
# If there is a hilighted suggestion, we want to catch enter
if @$('.suggestion_name_li_hl').length > 0
if event?.which is 13
event.preventDefault()
@handle_keypress()
return true
# We are scrolling in history
if @history_displayed_id isnt 0 and event?
# We catch ctrl, shift, alt and command
if event.ctrlKey or event.shiftKey or event.altKey or event.which is 16 or event.which is 17 or event.which is 18 or event.which is 20 or (event.which is 91 and event.type isnt 'keypress') or event.which is 92 or event.type of @mouse_type_event
return false
# We catch ctrl, shift, alt and command but don't look for active key (active key here refer to ctrl, shift, alt being pressed and hold)
if event? and (event.which is 16 or event.which is 17 or event.which is 18 or event.which is 20 or (event.which is 91 and event.type isnt 'keypress') or event.which is 92)
return false
# Avoid arrows+home+end+page down+pageup
# if event? and (event.which is 24 or event.which is ..)
# 0 is for firefox...
if not event? or (event.which isnt 37 and event.which isnt 38 and event.which isnt 39 and event.which isnt 40 and event.which isnt 33 and event.which isnt 34 and event.which isnt 35 and event.which isnt 36 and event.which isnt 0)
@history_displayed_id = 0
@draft = @codemirror.getValue()
# The expensive operations are coming. If the query is too long, we just don't parse the query
if @codemirror.getValue().length > @max_size_query
# Return true or false will break the event propagation
return undefined
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
query_after_cursor = @codemirror.getRange @codemirror.getCursor(), {line:@codemirror.lineCount()+1, ch: 0}
# Compute the structure of the query written by the user.
# We compute it earlier than before because @pair_char also listen on keydown and needs stack
stack = @extract_data_from_query
size_stack: 0
query: query_before_cursor
position: 0
if stack is null # Stack is null if the query was too big for us to parse
@ignore_tab_keyup = false
@hide_suggestion_and_description()
return false
if dataexplorer_state.options.electric_punctuation is true
@pair_char(event, stack) # Pair brackets/quotes
# We just look at key up so we don't fire the call 3 times
if event?.type? and event.type isnt 'keyup' and event.which isnt 9 and event.type isnt 'mouseup'
return false
if event?.which is 16 # We don't do anything with Shift.
return false
# Tab is an exception, we let it pass (tab bring back suggestions) - What we want is to catch keydown
if @ignore_tab_keyup is true and event?.which is 9
if event.type is 'keyup'
@ignore_tab_keyup = false
return true
@current_highlighted_suggestion = -1
@current_highlighted_extra_suggestion = -1
@$('.suggestion_name_list').empty()
# Valid step, let's save the data
@query_last_part = query_after_cursor
# If a selection is active, we just catch shift+enter
if @codemirror.getSelection() isnt ''
@hide_suggestion_and_description()
if event? and event.which is 13 and (event.shiftKey or event.ctrlKey or event.metaKey) # If the user hit enter and (Ctrl or Shift or Cmd)
@hide_suggestion_and_description()
if event.type isnt 'keydown'
return true
@execute_query()
return true # We do not replace the selection with a new line
# If the user select something and end somehwere with suggestion
if event?.type isnt 'mouseup'
return false
else
return true
@current_suggestions = []
@current_element = ''
@current_extra_suggestion = ''
@written_suggestion = null
@cursor_for_auto_completion = @codemirror.getCursor()
@description = null
result =
status: null
# create_suggestion is going to fill to_complete and to_describe
#to_complete: undefined
#to_describe: undefined
# If we are in the middle of a function (text after the cursor - that is not an element in @char_breakers or a comment), we just show a description, not a suggestion
result_non_white_char_after_cursor = @regex.get_first_non_white_char.exec(query_after_cursor)
if result_non_white_char_after_cursor isnt null and not(result_non_white_char_after_cursor[1]?[0] of @char_breakers or result_non_white_char_after_cursor[1]?.match(/^((\/\/)|(\/\*))/) isnt null)
result.status = 'break_and_look_for_description'
@hide_suggestion()
else
result_last_char_is_white = @regex.last_char_is_white.exec(query_before_cursor[query_before_cursor.length-1])
if result_last_char_is_white isnt null
result.status = 'break_and_look_for_description'
@hide_suggestion()
# Create the suggestion/description
@create_suggestion
stack: stack
query: query_before_cursor
result: result
result.suggestions = @uniq result.suggestions
@grouped_data = @count_group_level(stack).count_group > 0
if result.suggestions?.length > 0
show_suggestion = false
for suggestion, i in result.suggestions
if suggestion isnt 'ungroup(' or @grouped_data is true # We add the suggestion for `ungroup` only if we are in a group_stream/data (using the flag @grouped_data)
show_suggestion = true
@current_suggestions.push suggestion
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
if dataexplorer_state.options.suggestions is true and show_suggestion is true
@show_suggestion()
else
@hide_suggestion()
@hide_description()
else if result.description?
@hide_suggestion()
@description = result.description
if dataexplorer_state.options.suggestions is true and event?.type isnt 'mouseup'
@show_description()
else
@hide_description()
else
@hide_suggestion_and_description()
if event?.which is 9 # Catch tab
# If you're in a string, you add a TAB. If you're at the beginning of a newline with preceding whitespace, you add a TAB. If it's any other case do nothing.
if @last_element_type_if_incomplete(stack) isnt 'string' and @regex.white_or_empty.test(@codemirror.getLine(@codemirror.getCursor().line).slice(0, @codemirror.getCursor().ch)) isnt true
return true
else
return false
return true
# Similar to underscore's uniq but faster with a hashmap
uniq: (ar) ->
if not ar? or ar.length is 0
return ar
result = []
hash = {}
for element in ar
hash[element] = true
for key of hash
result.push key
result.sort()
return result
# Extract information from the current query
# Regex used
regex:
anonymous:/^(\s)*function\s*\(([a-zA-Z0-9,\s]*)\)(\s)*{/
loop:/^(\s)*(for|while)(\s)*\(([^\)]*)\)(\s)*{/
method: /^(\s)*([a-zA-Z0-9]*)\(/ # forEach( merge( filter(
row: /^(\s)*row\(/
method_var: /^(\s)*(\d*[a-zA-Z][a-zA-Z0-9]*)\./ # r. r.row. (r.count will be caught later)
return : /^(\s)*return(\s)*/
object: /^(\s)*{(\s)*/
array: /^(\s)*\[(\s)*/
white: /^(\s)+$/
white_or_empty: /^(\s)*$/
white_replace: /\s/g
white_start: /^(\s)+/
comma: /^(\s)*,(\s)*/
semicolon: /^(\s)*;(\s)*/
number: /^[0-9]+\.?[0-9]*/
inline_comment: /^(\s)*\/\/.*(\n|$)/
multiple_line_comment: /^(\s)*\/\*[^(\*\/)]*\*\//
get_first_non_white_char: /\s*(\S+)/
last_char_is_white: /.*(\s+)$/
stop_char: # Just for performance (we look for a stop_char in constant time - which is better than having 3 and conditions) and cleaner code
opening:
'(': ')'
'{': '}'
'[': ']'
closing:
')': '(' # Match the opening character
'}': '{'
']': '['
# Return the type of the last incomplete object or an empty string
last_element_type_if_incomplete: (stack) =>
if (not stack?) or stack.length is 0
return ''
element = stack[stack.length-1]
if element.body?
return @last_element_type_if_incomplete(element.body)
else
if element.complete is false
return element.type
else
return ''
# Get the last key if the last element is a key of an object
get_last_key: (stack) =>
if (not stack?) or stack.length is 0
return ''
element = stack[stack.length-1]
if element.body?
return @get_last_key(element.body)
else
if element.complete is false and element.key?
return element.key
else
return ''
# We build a stack of the query.
# Chained functions are in the same array, arguments/inner queries are in a nested array
# element.type in ['string', 'function', 'var', 'separator', 'anonymous_function', 'object', 'array_entry', 'object_key' 'array']
extract_data_from_query: (args) =>
size_stack = args.size_stack
query = args.query
context = if args.context? then util.deep_copy(args.context) else {}
position = args.position
stack = []
element =
type: null
context: context
complete: false
start = 0
is_parsing_string = false
to_skip = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
if element.type is 'string'
element.name = query.slice start, i+1
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+1
else # if element.is_parsing_string is false
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
if element.type is null
element.type = 'string'
start = i
continue
if element.type is null
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
start += result_inline_comment[0].length
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
start += result_multiple_line_comment[0].length
continue
if start is i
result_white = @regex.white_start.exec query.slice i
if result_white?
to_skip = result_white[0].length-1
start += result_white[0].length
continue
# Check for anonymous function
result_regex = @regex.anonymous.exec query.slice i
if result_regex isnt null
element.type = 'anonymous_function'
list_args = result_regex[2]?.split(',')
element.args = []
new_context = util.deep_copy context
for arg in list_args
arg = arg.replace(/(^\s*)|(\s*$)/gi,"") # Removing leading/trailing spaces
new_context[arg] = true
element.args.push arg
element.context = new_context
to_skip = result_regex[0].length
body_start = i+result_regex[0].length
stack_stop_char = ['{']
continue
# Check for a for loop
result_regex = @regex.loop.exec query.slice i
if result_regex isnt null
element.type = 'loop'
element.context = context
to_skip = result_regex[0].length
body_start = i+result_regex[0].length
stack_stop_char = ['{']
continue
# Check for return
result_regex = @regex.return.exec query.slice i
if result_regex isnt null
# I'm not sure we need to keep track of return, but let's keep it for now
element.type = 'return'
element.complete = true
to_skip = result_regex[0].length-1
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length
continue
# Check for object
result_regex = @regex.object.exec query.slice i
if result_regex isnt null
element.type = 'object'
element.next_key = null
element.body = [] # We need to keep tracker of the order of pairs
element.current_key_start = i+result_regex[0].length
to_skip = result_regex[0].length-1
stack_stop_char = ['{']
continue
# Check for array
result_regex = @regex.array.exec query.slice i
if result_regex isnt null
element.type = 'array'
element.next_key = null
element.body = []
entry_start = i+result_regex[0].length
to_skip = result_regex[0].length-1
stack_stop_char = ['[']
continue
if char is '.'
new_start = i+1
else
new_start = i
# Check for a standard method
result_regex = @regex.method.exec query.slice new_start
if result_regex isnt null
result_regex_row = @regex.row.exec query.slice new_start
if result_regex_row isnt null
position_opening_parenthesis = result_regex_row[0].indexOf('(')
element.type = 'function' # TODO replace with function
element.name = 'row'
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: 'function'
name: '('
position: position+3+1
context: context
complete: 'false'
stack_stop_char = ['(']
start += position_opening_parenthesis
to_skip = result_regex[0].length-1+new_start-i
continue
else
if stack[stack.length-1]?.type is 'function' or stack[stack.length-1]?.type is 'var' # We want the query to start with r. or arg.
element.type = 'function'
element.name = result_regex[0]
element.position = position+new_start
start += new_start-i
to_skip = result_regex[0].length-1+new_start-i
stack_stop_char = ['(']
continue
else
position_opening_parenthesis = result_regex[0].indexOf('(')
if position_opening_parenthesis isnt -1 and result_regex[0].slice(0, position_opening_parenthesis) of context
# Save the var
element.real_type = @types.value
element.type = 'var'
element.name = result_regex[0].slice(0, position_opening_parenthesis)
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: 'function'
name: '('
position: position+position_opening_parenthesis+1
context: context
complete: 'false'
stack_stop_char = ['(']
start = position_opening_parenthesis
to_skip = result_regex[0].length-1
continue
###
# This last condition is a special case for r(expr)
else if position_opening_parenthesis isnt -1 and result_regex[0].slice(0, position_opening_parenthesis) is 'r'
element.type = 'var'
element.name = 'r'
element.real_type = @types.value
element.position = position+new_start
start += new_start-i
to_skip = result_regex[0].length-1+new_start-i
stack_stop_char = ['(']
continue
###
# Check for method without parenthesis r., r.row., doc.
result_regex = @regex.method_var.exec query.slice new_start
if result_regex isnt null
if result_regex[0].slice(0, result_regex[0].length-1) of context
element.type = 'var'
element.real_type = @types.value
else
element.type = 'function'
element.position = position+new_start
element.name = result_regex[0].slice(0, result_regex[0].length-1).replace(/\s/, '')
element.complete = true
to_skip = element.name.length-1+new_start-i
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = new_start+to_skip+1
start -= new_start-i
continue
# Look for a comma
result_regex = @regex.comma.exec query.slice i
if result_regex isnt null
# element should have been pushed in stack. If not, the query is malformed
element.complete = true
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1+1
to_skip = result_regex[0].length-1
continue
# Look for a semi colon
result_regex = @regex.semicolon.exec query.slice i
if result_regex isnt null
# element should have been pushed in stack. If not, the query is malformed
element.complete = true
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1+1
to_skip = result_regex[0].length-1
continue
#else # if element.start isnt i
# We caught the white spaces, so there is nothing to do here
else
if char is ';'
# We just encountered a semi colon. We have an unknown element
# So We just got a random javascript statement, let's just ignore it
start = i+1
else # element.type isnt null
# Catch separator like for groupedMapReduce
result_regex = @regex.comma.exec(query.slice(i))
if result_regex isnt null and stack_stop_char.length < 1
# element should have been pushed in stack. If not, the query is malformed
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
position: position+i
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1
to_skip = result_regex[0].length-1
continue
# Catch for anonymous function
else if element.type is 'anonymous_function'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start, i
context: element.context
position: position+body_start
if element.body is null
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
#else the written query is broken here. The user forgot to close something?
#TODO Default behavior? Wait for Brackets/Ace to see how we handle errors
else if element.type is 'loop'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start, i
context: element.context
position: position+body_start
if element.body
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
# Catch for function
else if element.type is 'function'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice start+element.name.length, i
context: element.context
position: position+start+element.name.length
if element.body is null
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
# Catch for object
else if element.type is 'object'
# Since we are sure that we are not in a string, we can just look for colon and comma
# Still, we need to check the stack_stop_char since we can have { key: { inner: 'test, 'other_inner'}, other_key: 'other_value'}
keys_values = []
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
# We just reach a }, it's the end of the object
if element.next_key?
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start, i
context: element.context
position: position+element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
complete: false
body: body
element.body[element.body.length-1] = new_element
element.next_key = null # No more next_key
element.complete = true
# if not element.next_key?
# The next key is not defined, this is a broken query.
# TODO show error once brackets/ace will be used
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
continue
if not element.next_key?
if stack_stop_char.length is 1 and char is ':'
new_element =
type: 'object_key'
key: query.slice element.current_key_start, i
key_complete: true
if element.body.length is 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
else
element.body[element.body.length-1] = new_element
element.next_key = query.slice element.current_key_start, i
element.current_value_start = i+1
else
result_regex = @regex.comma.exec query.slice i
if stack_stop_char.length is 1 and result_regex isnt null #We reached the end of a value
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start, i
context: element.context
position: element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
body: body
element.body[element.body.length-1] = new_element
to_skip = result_regex[0].length-1
element.next_key = null
element.current_key_start = i+result_regex[0].length
# Catch for array
else if element.type is 'array'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
# We just reach a ], it's the end of the object
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start, i
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: true
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
continue
if stack_stop_char.length is 1 and char is ','
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start, i
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: true
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
entry_start = i+1
# We just reached the end, let's try to find the type of the incomplete element
if element.type isnt null
element.complete = false
if element.type is 'function'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice start+element.name.length
context: element.context
position: position+start+element.name.length
if element.body is null
return null
else if element.type is 'anonymous_function'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start
context: element.context
position: position+body_start
if element.body is null
return null
else if element.type is 'loop'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start
context: element.context
position: position+body_start
if element.body is null
return null
else if element.type is 'string'
element.name = query.slice start
else if element.type is 'object'
if not element.next_key? # Key not defined yet
new_element =
type: 'object_key'
key: query.slice element.current_key_start
key_complete: false
complete: false
element.body.push new_element # They key was not defined, so we add a new element
size_stack++
if size_stack > @max_size_stack
return null
element.next_key = query.slice element.current_key_start
else
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start
context: element.context
position: position+element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
complete: false
body: body
element.body[element.body.length-1] = new_element
element.next_key = null # No more next_key
else if element.type is 'array'
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: false
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
else if start isnt i
if query.slice(start) of element.context
element.name = query.slice start
element.type = 'var'
element.real_type = @types.value
element.complete = true
else if @regex.number.test(query.slice(start)) is true
element.type = 'number'
element.name = query.slice start
element.complete = true
else if query[start] is '.'
element.type = 'function'
element.position = position+start
element.name = query.slice start+1
element.complete = false
else
element.name = query.slice start
element.position = position+start
element.complete = false
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
return stack
# Count the number of `group` commands minus `ungroup` commands in the current level
# We count per level because we don't want to report a positive number of group for nested queries, e.g:
# r.table("foo").group("bar").map(function(doc) { doc.merge(
#
# We return an object with two fields
# - count_group: number of `group` commands minus the number of `ungroup` commands
# - parse_level: should we keep parsing the same level
count_group_level: (stack) =>
count_group = 0
if stack.length > 0
# Flag for whether or not we should keep looking for group/ungroup
# we want the warning to appear only at the same level
parse_level = true
element = stack[stack.length-1]
if element.body? and element.body.length > 0 and element.complete is false
parse_body = @count_group_level element.body
count_group += parse_body.count_group
parse_level = parse_body.parse_level
if element.body[0].type is 'return'
parse_level = false
if element.body[element.body.length-1].type is 'function'
parse_level = false
if parse_level is true
for i in [stack.length-1..0] by -1
if stack[i].type is 'function' and stack[i].name is 'ungroup('
count_group -= 1
else if stack[i].type is 'function' and stack[i].name is 'group('
count_group += 1
count_group: count_group
parse_level: parse_level
# Decide if we have to show a suggestion or a description
# Mainly use the stack created by extract_data_from_query
create_suggestion: (args) =>
stack = args.stack
query = args.query
result = args.result
# No stack, ie an empty query
if result.status is null and stack.length is 0
result.suggestions = []
result.status = 'done'
@query_first_part = ''
if @suggestions['']? # The docs may not have loaded
for suggestion in @suggestions['']
result.suggestions.push suggestion
for i in [stack.length-1..0] by -1
element = stack[i]
if element.body? and element.body.length > 0 and element.complete is false
@create_suggestion
stack: element.body
query: args?.query
result: args.result
if result.status is 'done'
continue
if result.status is null
# Top of the stack
if element.complete is true
if element.type is 'function'
if element.complete is true or element.name is ''
result.suggestions = null
result.status = 'look_for_description'
break
else
result.suggestions = null
result.description = element.name
#Define the current argument we have. It's the suggestion whose index is -1
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.status = 'done'
else if element.type is 'anonymous_function' or element.type is 'separator' or element.type is 'object' or element.type is 'object_key' or element.type is 'return' or 'element.type' is 'array'
# element.type === 'object' is impossible I think with the current implementation of extract_data_from_query
result.suggestions = null
result.status = 'look_for_description'
break # We want to look in the upper levels
#else type cannot be null (because not complete)
else # if element.complete is false
if element.type is 'function'
if element.body? # It means that element.body.length === 0
# We just opened a new function, so let's just show the description
result.suggestions = null
result.description = element.name # That means we are going to describe the function named element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.status = 'done'
break
else
# function not complete, need suggestion
result.suggestions = []
result.suggestions_regex = @create_safe_regex element.name # That means we are going to give all the suggestions that match element.name and that are in the good group (not yet defined)
result.description = null
@query_first_part = query.slice 0, element.position+1
@current_element = element.name
@cursor_for_auto_completion.ch -= element.name.length
@current_query
if i isnt 0
result.status = 'look_for_state'
else
result.state = ''
else if element.type is 'anonymous_function' or element.type is 'object_key' or element.type is 'string' or element.type is 'separator' or element.type is 'array'
result.suggestions = null
result.status = 'look_for_description'
break
#else if element.type is 'object' # Not possible
#else if element.type is 'var' # Not possible because we require a . or ( to asssess that it's a var
else if element.type is null
result.suggestions = []
result.status = 'look_for_description'
break
else if result.status is 'look_for_description'
if element.type is 'function'
result.description = element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.suggestions = null
result.status = 'done'
else
break
if result.status is 'break_and_look_for_description'
if element.type is 'function' and element.complete is false and element.name.indexOf('(') isnt -1
result.description = element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.suggestions = null
result.status = 'done'
else
if element.type isnt 'function'
break
else
result.status = 'look_for_description'
break
else if result.status is 'look_for_state'
if element.type is 'function' and element.complete is true
result.state = element.name
if @map_state[element.name]?
for state in @map_state[element.name]
if @suggestions[state]?
for suggestion in @suggestions[state]
if result.suggestions_regex.test(suggestion) is true
result.suggestions.push suggestion
#else # This is a non valid ReQL function.
# It may be a personalized function defined in the data explorer...
result.status = 'done'
else if element.type is 'var' and element.complete is true
result.state = element.real_type
for type in result.state
if @suggestions[type]?
for suggestion in @suggestions[type]
if result.suggestions_regex.test(suggestion) is true
result.suggestions.push suggestion
result.status = 'done'
#else # Is that possible? A function can only be preceded by a function (except for r)
# Create regex based on the user input. We make it safe
create_safe_regex: (str) =>
for char in @unsafe_to_safe_regexstr
str = str.replace char[0], char[1]
return new RegExp('^('+str+')', 'i')
# Show suggestion and determine where to put the box
show_suggestion: =>
@move_suggestion()
margin = (parseInt(@$('.CodeMirror-cursor').css('top').replace('px', ''))+@line_height)+'px'
@$('.suggestion_full_container').css 'margin-top', margin
@$('.arrow').css 'margin-top', margin
@$('.suggestion_name_list').show()
@$('.arrow').show()
# If want to show suggestion without moving the arrow
show_suggestion_without_moving: =>
@$('.arrow').show()
@$('.suggestion_name_list').show()
# Show description and determine where to put it
show_description: =>
if @descriptions[@description]? # Just for safety
margin = (parseInt(@$('.CodeMirror-cursor').css('top').replace('px', ''))+@line_height)+'px'
@$('.suggestion_full_container').css 'margin-top', margin
@$('.arrow').css 'margin-top', margin
@$('.suggestion_description').html @description_template @extend_description @description
@$('.suggestion_description').show()
@move_suggestion()
@show_or_hide_arrow()
else
@hide_description()
hide_suggestion: =>
@$('.suggestion_name_list').hide()
@show_or_hide_arrow()
hide_description: =>
@$('.suggestion_description').hide()
@show_or_hide_arrow()
hide_suggestion_and_description: =>
@hide_suggestion()
@hide_description()
# Show the arrow if suggestion or/and description is being displayed
show_or_hide_arrow: =>
if @$('.suggestion_name_list').css('display') is 'none' and @$('.suggestion_description').css('display') is 'none'
@$('.arrow').hide()
else
@$('.arrow').show()
# Move the suggestion. We have steps of 200 pixels and try not to overlaps button if we can. If we cannot, we just hide them all since their total width is less than 200 pixels
move_suggestion: =>
margin_left = parseInt(@$('.CodeMirror-cursor').css('left').replace('px', ''))+23
@$('.arrow').css 'margin-left', margin_left
if margin_left < 200
@$('.suggestion_full_container').css 'left', '0px'
else
max_margin = @$('.CodeMirror-scroll').width()-418
margin_left_bloc = Math.min max_margin, Math.floor(margin_left/200)*200
if margin_left > max_margin+418-150-23 # We are really at the end
@$('.suggestion_full_container').css 'left', (max_margin-34)+'px'
else if margin_left_bloc > max_margin-150-23
@$('.suggestion_full_container').css 'left', (max_margin-34-150)+'px'
else
@$('.suggestion_full_container').css 'left', (margin_left_bloc-100)+'px'
#Highlight suggestion. Method called when the user hit tab or mouseover
highlight_suggestion: (id) =>
@remove_highlight_suggestion()
@$('.suggestion_name_li').eq(id).addClass 'suggestion_name_li_hl'
@$('.suggestion_description').html @description_template @extend_description @current_suggestions[id]
@$('.suggestion_description').show()
remove_highlight_suggestion: =>
@$('.suggestion_name_li').removeClass 'suggestion_name_li_hl'
# Write the suggestion in the code mirror
write_suggestion: (args) =>
suggestion_to_write = args.suggestion_to_write
move_outside = args.move_outside is true # So default value is false
ch = @cursor_for_auto_completion.ch+suggestion_to_write.length
if dataexplorer_state.options.electric_punctuation is true
if suggestion_to_write[suggestion_to_write.length-1] is '(' and @count_not_closed_brackets('(') >= 0
@codemirror.setValue @query_first_part+suggestion_to_write+')'+@query_last_part
@written_suggestion = suggestion_to_write+')'
else
@codemirror.setValue @query_first_part+suggestion_to_write+@query_last_part
@written_suggestion = suggestion_to_write
if (move_outside is false) and (suggestion_to_write[suggestion_to_write.length-1] is '"' or suggestion_to_write[suggestion_to_write.length-1] is "'")
ch--
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
@codemirror.setCursor
line: @cursor_for_auto_completion.line
ch:ch
else
@codemirror.setValue @query_first_part+suggestion_to_write+@query_last_part
@written_suggestion = suggestion_to_write
if (move_outside is false) and (suggestion_to_write[suggestion_to_write.length-1] is '"' or suggestion_to_write[suggestion_to_write.length-1] is "'")
ch--
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
@codemirror.setCursor
line: @cursor_for_auto_completion.line
ch:ch
# Select the suggestion. Called by mousdown .suggestion_name_li
select_suggestion: (event) =>
suggestion_to_write = @$(event.target).html()
@write_suggestion
suggestion_to_write: suggestion_to_write
# Give back focus to code mirror
@hide_suggestion()
# Put back in the stack
setTimeout =>
@handle_keypress() # That's going to describe the function the user just selected
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
, 0 # Useful if the user used the mouse to select a suggestion
# Highlight a suggestion in case of a mouseover
mouseover_suggestion: (event) =>
@highlight_suggestion event.target.dataset.id
# Hide suggestion in case of a mouse out
mouseout_suggestion: (event) =>
@hide_description()
# Extend description for .db() and .table() with dbs/tables names
extend_description: (fn) =>
if fn is 'db(' or fn is 'dbDrop('
description = _.extend {}, @descriptions[fn]()
if _.keys(@databases_available).length is 0
data =
no_database: true
else
databases_available = _.keys @databases_available
data =
no_database: false
databases_available: databases_available
description.description = @databases_suggestions_template(data)+description.description
@extra_suggestions= databases_available # @extra_suggestions store the suggestions for arguments. So far they are just for db(), dbDrop(), table(), tableDrop()
else if fn is 'table(' or fn is 'tableDrop('
# Look for the argument of the previous db()
database_used = @extract_database_used()
description = _.extend {}, @descriptions[fn]()
if database_used.error is false
data =
tables_available: @databases_available[database_used.name]
no_table: @databases_available[database_used.name].length is 0
if database_used.name?
data.database_name = database_used.name
else
data =
error: database_used.error
description.description = @tables_suggestions_template(data) + description.description
@extra_suggestions = @databases_available[database_used.name]
else
description = @descriptions[fn] @grouped_data
@extra_suggestions= null
return description
# We could create a new stack with @extract_data_from_query, but that would be a more expensive for not that much
# We can not use the previous stack too since autocompletion doesn't validate the query until you hit enter (or another key than tab)
extract_database_used: =>
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
# We cannot have ".db(" in a db name
last_db_position = query_before_cursor.lastIndexOf('.db(')
if last_db_position is -1
found = false
if @databases_available['test']?
return {
db_found: true
error: false
name: 'test'
}
else
return {
db_found: false
error: true
}
else
arg = query_before_cursor.slice last_db_position+5 # +4 for .db(
char = query_before_cursor.slice last_db_position+4, last_db_position+5 # ' or " used for the argument of db()
end_arg_position = arg.indexOf char # Check for the next quote or apostrophe
if end_arg_position is -1
return {
db_found: false
error: true
}
db_name = arg.slice 0, end_arg_position
if @databases_available[db_name]?
return {
db_found: true
error: false
name: db_name
}
else
return {
db_found: false
error: true
}
abort_query: =>
@disable_toggle_executing = false
@toggle_executing false
dataexplorer_state.query_result?.force_end_gracefully()
@driver_handler.close_connection()
# Function that execute the queries in a synchronous way.
execute_query: =>
# We don't let people execute more than one query at a time on the same connection
# While we remove the button run, `execute_query` could still be called with Shift+Enter
if @executing is true
@abort_query
# Hide the option, if already hidden, nothing happens.
@$('.profiler_enabled').slideUp 'fast'
# The user just executed a query, so we reset cursor_timed_out to false
dataexplorer_state.cursor_timed_out = false
dataexplorer_state.query_has_changed = false
@raw_query = @codemirror.getSelection() or @codemirror.getValue()
@query = @clean_query @raw_query # Save it because we'll use it in @callback_multilples_queries
# Execute the query
try
dataexplorer_state.query_result?.discard()
# Separate queries
@non_rethinkdb_query = '' # Store the statements that don't return a rethinkdb query (like "var a = 1;")
@index = 0 # index of the query currently being executed
@raw_queries = @separate_queries @raw_query # We first split raw_queries
@queries = @separate_queries @query
if @queries.length is 0
error = @query_error_template
no_query: true
@results_view_wrapper.render_error(null, error, true)
else
@execute_portion()
catch err
# Missing brackets, so we display everything (we don't know if we properly splitted the query)
@results_view_wrapper.render_error(@query, err, true)
@save_query
query: @raw_query
broken_query: true
toggle_executing: (executing) =>
if executing == @executing
if executing and dataexplorer_state.query_result?.is_feed
@$('.loading_query_img').hide()
return
if @disable_toggle_executing
return
@executing = executing
if @timeout_toggle_abort?
clearTimeout @timeout_toggle_abort
if executing
@timeout_toggle_abort = setTimeout =>
@timeout_toggle_abort = null
if not dataexplorer_state.query_result?.is_feed
@$('.loading_query_img').show()
@$('.execute_query').hide()
@$('.abort_query').show()
, @delay_toggle_abort
else
@timeout_toggle_abort = setTimeout =>
@timeout_toggle_abort = null
@$('.loading_query_img').hide()
@$('.execute_query').show()
@$('.abort_query').hide()
, @delay_toggle_abort
# A portion is one query of the whole input.
execute_portion: =>
dataexplorer_state.query_result = null
while @queries[@index]?
full_query = @non_rethinkdb_query
full_query += @queries[@index]
try
rdb_query = @evaluate(full_query)
catch err
if @queries.length > 1
@results_view_wrapper.render_error(@raw_queries[@index], err, true)
else
@results_view_wrapper.render_error(null, err, true)
@save_query
query: @raw_query
broken_query: true
return false
@index++
if rdb_query instanceof @TermBaseConstructor
final_query = @index is @queries.length
@start_time = new Date()
if final_query
query_result = new QueryResult
has_profile: dataexplorer_state.options.profiler
current_query: @raw_query
raw_query: @raw_queries[@index]
driver_handler: @driver_handler
events:
error: (query_result, err) =>
@results_view_wrapper.render_error(@query, err)
ready: (query_result) =>
dataexplorer_state.pause_at = null
if query_result.is_feed
@toggle_executing true
@disable_toggle_executing = true
for event in ['end', 'discard', 'error']
query_result.on event, () =>
@disable_toggle_executing = false
@toggle_executing false
dataexplorer_state.query_result = query_result
@results_view_wrapper.set_query_result
query_result: dataexplorer_state.query_result
@disable_toggle_executing = false
@driver_handler.run_with_new_connection rdb_query,
optargs:
binaryFormat: "raw"
timeFormat: "raw"
profile: dataexplorer_state.options.profiler
connection_error: (error) =>
@save_query
query: @raw_query
broken_query: true
@error_on_connect error
callback: (error, result) =>
if final_query
@save_query
query: @raw_query
broken_query: false
query_result.set error, result
else if error
@save_query
query: @raw_query
broken_query: true
@results_view_wrapper.render_error(@query, err)
else
@execute_portion()
return true
else
@non_rethinkdb_query += @queries[@index-1]
if @index is @queries.length
error = @query_error_template
last_non_query: true
@results_view_wrapper.render_error(@raw_queries[@index-1], error, true)
@save_query
query: @raw_query
broken_query: true
# Evaluate the query
# We cannot force eval to a local scope, but "use strict" will declare variables in the scope at least
evaluate: (query) =>
"use strict"
return eval(query)
# In a string \n becomes \\n, outside a string we just remove \n, so
# r
# .expr('hello
# world')
# becomes
# r.expr('hello\nworld')
# We also remove comments from the query
clean_query: (query) ->
is_parsing_string = false
start = 0
result_query = ''
for char, i in query
if to_skip > 0
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\'
result_query += query.slice(start, i+1).replace(/\n/g, '\\n')
start = i+1
is_parsing_string = false
continue
else # if element.is_parsing_string is false
if char is '\'' or char is '"'
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
to_skip = result_inline_comment[0].length-1
start += result_inline_comment[0].length
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
to_skip = result_multiple_line_comment[0].length-1
start += result_multiple_line_comment[0].length
continue
if is_parsing_string
result_query += query.slice(start, i).replace(/\n/g, '\\\\n')
else
result_query += query.slice(start, i).replace(/\n/g, '')
return result_query
# Split input in queries. We use semi colon, pay attention to string, brackets and comments
separate_queries: (query) =>
queries = []
is_parsing_string = false
stack = []
start = 0
position =
char: 0
line: 1
for char, i in query
if char is '\n'
position.line++
position.char = 0
else
position.char++
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\'
is_parsing_string = false
continue
else # if element.is_parsing_string is false
if char is '\'' or char is '"'
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
if char of @stop_char.opening
stack.push char
else if char of @stop_char.closing
if stack[stack.length-1] isnt @stop_char.closing[char]
throw @query_error_template
syntax_error: true
bracket: char
line: position.line
position: position.char
else
stack.pop()
else if char is ';' and stack.length is 0
queries.push query.slice start, i+1
start = i+1
if start < query.length-1
last_query = query.slice start
if @regex.white.test(last_query) is false
queries.push last_query
return queries
# Clear the input
clear_query: =>
@codemirror.setValue ''
@codemirror.focus()
# Called if there is any on the connection
error_on_connect: (error) =>
if /^(Unexpected token)/.test(error.message)
# Unexpected token, the server couldn't parse the message
# The truth is we don't know which query failed (unexpected token), but it seems safe to suppose in 99% that the last one failed.
@results_view_wrapper.render_error(null, error)
# We save the query since the callback will never be called.
@save_query
query: @raw_query
broken_query: true
else
@results_view_wrapper.cursor_timed_out()
# We fail to connect, so we display a message except if we were already disconnected and we are not trying to manually reconnect
# So if the user fails to reconnect after a failure, the alert will still flash
@$('#user-alert-space').hide()
@$('#user-alert-space').html @alert_connection_fail_template({})
@$('#user-alert-space').slideDown 'fast'
handle_gutter_click: (editor, line) =>
start =
line: line
ch: 0
end =
line: line
ch: @codemirror.getLine(line).length
@codemirror.setSelection start, end
# Switch between full view and normal view
toggle_size: =>
if @displaying_full_view is true
@display_normal()
$(window).off 'resize', @display_full
@displaying_full_view = false
else
@display_full()
$(window).on 'resize', @display_full
@displaying_full_view = true
@results_view_wrapper.set_scrollbar()
display_normal: =>
$('#cluster').addClass 'container'
$('#cluster').removeClass 'cluster_with_margin'
@$('.wrapper_scrollbar').css 'width', '888px'
@$('.option_icon').removeClass 'fullscreen_exit'
@$('.option_icon').addClass 'fullscreen'
display_full: =>
$('#cluster').removeClass 'container'
$('#cluster').addClass 'cluster_with_margin'
@$('.wrapper_scrollbar').css 'width', ($(window).width()-92)+'px'
@$('.option_icon').removeClass 'fullscreen'
@$('.option_icon').addClass 'fullscreen_exit'
remove: =>
@results_view_wrapper.remove()
@history_view.remove()
@driver_handler.remove()
@display_normal()
$(window).off 'resize', @display_full
$(document).unbind 'mousemove', @handle_mousemove
$(document).unbind 'mouseup', @handle_mouseup
clearTimeout @timeout_driver_connect
driver.stop_timer @timer
# We do not destroy the cursor, because the user might come back and use it.
super()
# An abstract base class
class ResultView extends Backbone.View
tree_large_container_template: require('../handlebars/dataexplorer_large_result_json_tree_container.hbs')
tree_container_template: require('../handlebars/dataexplorer_result_json_tree_container.hbs')
events: ->
'click .jt_arrow': 'toggle_collapse'
'click .jta_arrow_h': 'expand_tree_in_table'
'mousedown': 'parent_pause_feed'
initialize: (args) =>
@_patched_already = false
@parent = args.parent
@query_result = args.query_result
@render()
@listenTo @query_result, 'end', =>
if not @query_result.is_feed
@render()
@fetch_batch_rows()
remove: =>
@removed_self = true
super()
max_datum_threshold: 1000
# Return whether there are too many datums
# If there are too many, we will disable syntax highlighting to avoid freezing the page
has_too_many_datums: (result) ->
if @has_too_many_datums_helper(result) > @max_datum_threshold
return true
return false
json_to_tree: (result) =>
# If the results are too large, we just display the raw indented JSON to avoid freezing the interface
if @has_too_many_datums(result)
return @tree_large_container_template
json_data: JSON.stringify(result, null, 4)
else
return @tree_container_template
tree: util.json_to_node(result)
# Return the number of datums if there are less than @max_datum_threshold
# Or return a number greater than @max_datum_threshold
has_too_many_datums_helper: (result) ->
if Object::toString.call(result) is '[object Object]'
count = 0
for key of result
count += @has_too_many_datums_helper result[key]
if count > @max_datum_threshold
return count
return count
else if Array.isArray(result)
count = 0
for element in result
count += @has_too_many_datums_helper element
if count > @max_datum_threshold
return count
return count
return 1
toggle_collapse: (event) =>
@$(event.target).nextAll('.jt_collapsible').toggleClass('jt_collapsed')
@$(event.target).nextAll('.jt_points').toggleClass('jt_points_collapsed')
@$(event.target).nextAll('.jt_b').toggleClass('jt_b_collapsed')
@$(event.target).toggleClass('jt_arrow_hidden')
@parent.set_scrollbar()
expand_tree_in_table: (event) =>
dom_element = @$(event.target).parent()
@$(event.target).remove()
data = dom_element.data('json_data')
result = @json_to_tree data
dom_element.html result
classname_to_change = dom_element.parent().attr('class').split(' ')[0]
$('.'+classname_to_change).css 'max-width', 'none'
classname_to_change = dom_element.parent().parent().attr('class')
$('.'+classname_to_change).css 'max-width', 'none'
dom_element.css 'max-width', 'none'
@parent.set_scrollbar()
parent_pause_feed: (event) =>
@parent.pause_feed()
pause_feed: =>
unless @parent.container.state.pause_at?
@parent.container.state.pause_at = @query_result.size()
unpause_feed: =>
if @parent.container.state.pause_at?
@parent.container.state.pause_at = null
@render()
current_batch: =>
switch @query_result.type
when 'value'
return @query_result.value
when 'cursor'
if @query_result.is_feed
pause_at = @parent.container.state.pause_at
if pause_at?
latest = @query_result.slice(Math.min(0, pause_at - @parent.container.state.options.query_limit), pause_at - 1)
else
latest = @query_result.slice(-@parent.container.state.options.query_limit)
latest.reverse()
return latest
else
return @query_result.slice(@query_result.position, @query_result.position + @parent.container.state.options.query_limit)
current_batch_size: =>
return @current_batch()?.length ? 0
setStackSize: =>
# In some versions of firefox, the effective recursion
# limit gets hit sometimes by the driver. Here we patch
# the driver's built in stackSize to 12 (normally it's
# 100). The driver will invoke callbacks with setImmediate
# vs directly invoking themif the stackSize limit is
# exceeded, which keeps the stack size manageable (but
# results in worse tracebacks).
if @_patched_already
return
iterableProto = @query_result.cursor?.__proto__?.__proto__?.constructor?.prototype
if iterableProto?.stackSize > 12
console.log "Patching stack limit on cursors to 12"
iterableProto.stackSize = 12
@_patched_already = true
# TODO: rate limit events to avoid freezing the browser when there are too many
fetch_batch_rows: =>
if @query_result.type is not 'cursor'
return
@setStackSize()
if @query_result.is_feed or @query_result.size() < @query_result.position + @parent.container.state.options.query_limit
@query_result.once 'add', (query_result, row) =>
if @removed_self
return
if @query_result.is_feed
if not @parent.container.state.pause_at?
if not @paused_at?
@query_result.drop_before(@query_result.size() - @parent.container.state.options.query_limit)
@add_row row
@parent.update_feed_metadata()
@fetch_batch_rows()
@query_result.fetch_next()
else
@parent.render()
@render()
show_next_batch: =>
@query_result.position += @parent.container.state.options.query_limit
@query_result.drop_before @parent.container.state.options.query_limit
@render()
@parent.render()
@fetch_batch_rows()
add_row: (row) =>
# TODO: Don't render the whole view on every change
@render()
class TreeView extends ResultView
className: 'results tree_view_container'
templates:
wrapper: require('../handlebars/dataexplorer_result_tree.hbs')
no_result: require('../handlebars/dataexplorer_result_empty.hbs')
render: =>
if @query_result.results?.length == 0
@$el.html @templates.wrapper tree: @templates.no_result
ended: @query_result.ended
at_beginning: @query_result.at_beginning()
return @
switch @query_result.type
when 'value'
@$el.html @templates.wrapper tree: @json_to_tree @query_result.value
when 'cursor'
@$el.html @templates.wrapper tree: []
tree_container = @$('.json_tree_container')
for row in @current_batch()
tree_container.append @json_to_tree row
return @
add_row: (row, noflash) =>
tree_container = @$('.json_tree_container')
node = $(@json_to_tree(row)).prependTo(tree_container)
if not noflash
node.addClass 'flash'
children = tree_container.children()
if children.length > @parent.container.state.options.query_limit
children.last().remove()
class TableView extends ResultView
className: 'results table_view_container'
templates:
wrapper: require('../handlebars/dataexplorer_result_table.hbs')
container: require('../handlebars/dataexplorer_result_json_table_container.hbs')
tr_attr: require('../handlebars/dataexplorer_result_json_table_tr_attr.hbs')
td_attr: require('../handlebars/dataexplorer_result_json_table_td_attr.hbs')
tr_value: require('../handlebars/dataexplorer_result_json_table_tr_value.hbs')
td_value: require('../handlebars/dataexplorer_result_json_table_td_value.hbs')
td_value_content: require('../handlebars/dataexplorer_result_json_table_td_value_content.hbs')
data_inline: require('../handlebars/dataexplorer_result_json_table_data_inline.hbs')
no_result: require('../handlebars/dataexplorer_result_empty.hbs')
default_size_column: 310 # max-width value of a cell of a table (as defined in the css file)
mouse_down: false
events: -> _.extend super(),
'mousedown .click_detector': 'handle_mousedown'
initialize: (args) =>
super args
@last_keys = @parent.container.state.last_keys # Arrays of the last keys displayed
@last_columns_size = @parent.container.state.last_columns_size # Size of the columns displayed. Undefined if a column has the default size
@listenTo @query_result, 'end', =>
if @current_batch_size() == 0
@render()
handle_mousedown: (event) =>
if event?.target?.className is 'click_detector'
@col_resizing = @$(event.target).parent().data('col')
@start_width = @$(event.target).parent().width()
@start_x = event.pageX
@mouse_down = true
$('body').toggleClass('resizing', true)
handle_mousemove: (event) =>
if @mouse_down
@parent.container.state.last_columns_size[@col_resizing] = Math.max 5, @start_width-@start_x+event.pageX # Save the personalized size
@resize_column @col_resizing, @parent.container.state.last_columns_size[@col_resizing] # Resize
resize_column: (col, size) =>
@$('.col-'+col).css 'max-width', size
@$('.value-'+col).css 'max-width', size-20
@$('.col-'+col).css 'width', size
@$('.value-'+col).css 'width', size-20
if size < 20
@$('.value-'+col).css 'padding-left', (size-5)+'px'
@$('.value-'+col).css 'visibility', 'hidden'
else
@$('.value-'+col).css 'padding-left', '15px'
@$('.value-'+col).css 'visibility', 'visible'
handle_mouseup: (event) =>
if @mouse_down is true
@mouse_down = false
$('body').toggleClass('resizing', false)
@parent.set_scrollbar()
###
keys =
primitive_value_count: <int>
object:
key_1: <keys>
key_2: <keys>
###
build_map_keys: (args) =>
keys_count = args.keys_count
result = args.result
if jQuery.isPlainObject(result)
if result.$reql_type$ is 'TIME'
keys_count.primitive_value_count++
else if result.$reql_type$ is 'BINARY'
keys_count.primitive_value_count++
else
for key, row of result
if not keys_count['object']?
keys_count['object'] = {} # That's define only if there are keys!
if not keys_count['object'][key]?
keys_count['object'][key] =
primitive_value_count: 0
@build_map_keys
keys_count: keys_count['object'][key]
result: row
else
keys_count.primitive_value_count++
# Compute occurrence of each key. The occurence can be a float since we compute the average occurence of all keys for an object
compute_occurrence: (keys_count) =>
if not keys_count['object']? # That means we are accessing only a primitive value
keys_count.occurrence = keys_count.primitive_value_count
else
count_key = if keys_count.primitive_value_count > 0 then 1 else 0
count_occurrence = keys_count.primitive_value_count
for key, row of keys_count['object']
count_key++
@compute_occurrence row
count_occurrence += row.occurrence
keys_count.occurrence = count_occurrence/count_key # count_key cannot be 0
# Sort the keys per level
order_keys: (keys) =>
copy_keys = []
if keys.object?
for key, value of keys.object
if jQuery.isPlainObject(value)
@order_keys value
copy_keys.push
key: key
value: value.occurrence
# If we could know if a key is a primary key, that would be awesome
copy_keys.sort (a, b) ->
if b.value-a.value
return b.value-a.value
else
if a.key > b.key
return 1
else # We cannot have two times the same key
return -1
keys.sorted_keys = _.map copy_keys, (d) -> return d.key
if keys.primitive_value_count > 0
keys.sorted_keys.unshift @primitive_key
# Flatten the object returns by build_map_keys().
# We get back an array of keys
get_all_attr: (args) =>
keys_count = args.keys_count
attr = args.attr
prefix = args.prefix
prefix_str = args.prefix_str
for key in keys_count.sorted_keys
if key is @primitive_key
new_prefix_str = prefix_str # prefix_str without the last dot
if new_prefix_str.length > 0
new_prefix_str = new_prefix_str.slice(0, -1)
attr.push
prefix: prefix
prefix_str: new_prefix_str
is_primitive: true
else
if keys_count['object'][key]['object']?
new_prefix = util.deep_copy(prefix)
new_prefix.push key
@get_all_attr
keys_count: keys_count.object[key]
attr: attr
prefix: new_prefix
prefix_str: (if prefix_str? then prefix_str else '')+key+'.'
else
attr.push
prefix: prefix
prefix_str: prefix_str
key: key
json_to_table_get_attr: (flatten_attr) =>
return @templates.tr_attr
attr: flatten_attr
json_to_table_get_values: (args) =>
result = args.result
flatten_attr = args.flatten_attr
document_list = []
for single_result, i in result
new_document =
cells: []
for attr_obj, col in flatten_attr
key = attr_obj.key
value = single_result
for prefix in attr_obj.prefix
value = value?[prefix]
if attr_obj.is_primitive isnt true
if value?
value = value[key]
else
value = undefined
new_document.cells.push @json_to_table_get_td_value value, col
index = if @query_result.is_feed then @query_result.size() - i else i + 1
@tag_record new_document, index
document_list.push new_document
return @templates.tr_value
document: document_list
json_to_table_get_td_value: (value, col) =>
data = @compute_data_for_type(value, col)
return @templates.td_value
col: col
cell_content: @templates.td_value_content data
compute_data_for_type: (value, col) =>
data =
value: value
class_value: 'value-'+col
value_type = typeof value
if value is null
data['value'] = 'null'
data['classname'] = 'jta_null'
else if value is undefined
data['value'] = 'undefined'
data['classname'] = 'jta_undefined'
else if value.constructor? and value.constructor is Array
if value.length is 0
data['value'] = '[ ]'
data['classname'] = 'empty array'
else
data['value'] = '[ ... ]'
data['data_to_expand'] = JSON.stringify(value)
else if Object::toString.call(value) is '[object Object]' and value.$reql_type$ is 'TIME'
data['value'] = util.date_to_string(value)
data['classname'] = 'jta_date'
else if Object::toString.call(value) is '[object Object]' and value.$reql_type$ is 'BINARY'
data['value'] = util.binary_to_string value
data['classname'] = 'jta_bin'
else if Object::toString.call(value) is '[object Object]'
data['value'] = '{ ... }'
data['is_object'] = true
else if value_type is 'number'
data['classname'] = 'jta_num'
else if value_type is 'string'
if /^(http|https):\/\/[^\s]+$/i.test(value)
data['classname'] = 'jta_url'
else if /^[a-z0-9]+@[a-z0-9]+.[a-z0-9]{2,4}/i.test(value) # We don't handle .museum extension and special characters
data['classname'] = 'jta_email'
else
data['classname'] = 'jta_string'
else if value_type is 'boolean'
data['classname'] = 'jta_bool'
data.value = if value is true then 'true' else 'false'
return data
# Helper for expanding a table when showing an object (creating new columns)
join_table: (data) =>
result = ''
for value, i in data
data_cell = @compute_data_for_type(value, 'float')
data_cell['is_inline'] = true
if i isnt data.length-1
data_cell['need_comma'] = true
result += @templates.data_inline data_cell
return result
# Build the table
# We order by the most frequent keys then by alphabetic order
json_to_table: (result) =>
# While an Array type is never returned by the driver, we still build an Array in the data explorer
# when a cursor is returned (since we just print @limit results)
if not result.constructor? or result.constructor isnt Array
result = [result]
keys_count =
primitive_value_count: 0
for result_entry in result
@build_map_keys
keys_count: keys_count
result: result_entry
@compute_occurrence keys_count
@order_keys keys_count
flatten_attr = []
@get_all_attr # fill attr[]
keys_count: keys_count
attr: flatten_attr
prefix: []
prefix_str: ''
for value, index in flatten_attr
value.col = index
@last_keys = flatten_attr.map (attr, i) ->
if attr.prefix_str isnt ''
return attr.prefix_str+attr.key
return attr.key
@parent.container.state.last_keys = @last_keys
return @templates.container
table_attr: @json_to_table_get_attr flatten_attr
table_data: @json_to_table_get_values
result: result
flatten_attr: flatten_attr
tag_record: (doc, i) =>
doc.record = @query_result.position + i
render: =>
previous_keys = @parent.container.state.last_keys # Save previous keys. @last_keys will be updated in @json_to_table
results = @current_batch()
if Object::toString.call(results) is '[object Array]'
if results.length is 0
@$el.html @templates.wrapper content: @templates.no_result
ended: @query_result.ended
at_beginning: @query_result.at_beginning()
else
@$el.html @templates.wrapper content: @json_to_table results
else
if results is undefined
@$el.html ''
else
@$el.html @templates.wrapper content: @json_to_table [results]
if @query_result.is_feed
# TODO: highlight all new rows, not just the latest one
first_row = @$('.jta_tr').eq(1).find('td:not(:first)')
first_row.css 'background-color': '#eeeeff'
first_row.animate 'background-color': '#fbfbfb'
# Check if the keys are the same
if @parent.container.state.last_keys.length isnt previous_keys.length
same_keys = false
else
same_keys = true
for keys, index in @parent.container.state.last_keys
if @parent.container.state.last_keys[index] isnt previous_keys[index]
same_keys = false
# TODO we should just check if previous_keys is included in last_keys
# If the keys are the same, we are going to resize the columns as they were before
if same_keys is true
for col, value of @parent.container.state.last_columns_size
@resize_column col, value
else
# Reinitialize @last_columns_size
@last_column_size = {}
# Let's try to expand as much as we can
extra_size_table = @$('.json_table_container').width()-@$('.json_table').width()
if extra_size_table > 0 # The table doesn't take the full width
expandable_columns = []
for index in [0..@last_keys.length-1] # We skip the column record
real_size = 0
@$('.col-'+index).children().children().children().each((i, bloc) ->
$bloc = $(bloc)
if real_size<$bloc.width()
real_size = $bloc.width()
)
if real_size? and real_size is real_size and real_size > @default_size_column
expandable_columns.push
col: index
size: real_size+20 # 20 for padding
while expandable_columns.length > 0
expandable_columns.sort (a, b) ->
return a.size-b.size
if expandable_columns[0].size-@$('.col-'+expandable_columns[0].col).width() < extra_size_table/expandable_columns.length
extra_size_table = extra_size_table-(expandable_columns[0]['size']-@$('.col-'+expandable_columns[0].col).width())
@$('.col-'+expandable_columns[0]['col']).css 'max-width', expandable_columns[0]['size']
@$('.value-'+expandable_columns[0]['col']).css 'max-width', expandable_columns[0]['size']-20
expandable_columns.shift()
else
max_size = extra_size_table/expandable_columns.length
for column in expandable_columns
current_size = @$('.col-'+expandable_columns[0].col).width()
@$('.col-'+expandable_columns[0]['col']).css 'max-width', current_size+max_size
@$('.value-'+expandable_columns[0]['col']).css 'max-width', current_size+max_size-20
expandable_columns = []
return @
class RawView extends ResultView
className: 'results raw_view_container'
template: require('../handlebars/dataexplorer_result_raw.hbs')
init_after_dom_rendered: =>
@adjust_height()
adjust_height: =>
height = @$('.raw_view_textarea')[0].scrollHeight
if height > 0
@$('.raw_view_textarea').height(height)
render: =>
@$el.html @template JSON.stringify @current_batch()
@adjust_height()
return @
class ProfileView extends ResultView
className: 'results profile_view_container'
template:
require('../handlebars/dataexplorer_result_profile.hbs')
initialize: (args) =>
ZeroClipboard.setDefaults
moviePath: 'js/ZeroClipboard.swf'
forceHandCursor: true #TODO Find a fix for chromium(/linux?)
@clip = new ZeroClipboard()
super args
compute_total_duration: (profile) ->
profile.reduce(((total, task) ->
total + (task['duration(ms)'] or task['mean_duration(ms)'])) ,0)
compute_num_shard_accesses: (profile) ->
num_shard_accesses = 0
for task in profile
if task['description'] is 'Perform read on shard.'
num_shard_accesses += 1
if Object::toString.call(task['sub_tasks']) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task['sub_tasks']
if Object::toString.call(task['parallel_tasks']) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task['parallel_tasks']
# In parallel tasks, we get arrays of tasks instead of a super task
if Object::toString.call(task) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task
return num_shard_accesses
render: =>
if not @query_result.profile?
@$el.html @template {}
else
profile = @query_result.profile
@$el.html @template
profile:
clipboard_text: JSON.stringify profile, null, 2
tree: @json_to_tree profile
total_duration: util.prettify_duration @parent.container.driver_handler.total_duration
server_duration: util.prettify_duration @compute_total_duration profile
num_shard_accesses: @compute_num_shard_accesses profile
@clip.glue(@$('button.copy_profile'))
@delegateEvents()
@
class ResultViewWrapper extends Backbone.View
className: 'result_view'
template: require('../handlebars/dataexplorer_result_container.hbs')
option_template: require('../handlebars/dataexplorer-option_page.hbs')
error_template: require('../handlebars/dataexplorer-error.hbs')
cursor_timed_out_template: require('../handlebars/dataexplorer-cursor_timed_out.hbs')
primitive_key: <KEY>' # We suppose that there is no key with such value in the database.
views:
tree: TreeView
table: TableView
profile: ProfileView
raw: RawView
events: ->
'click .link_to_profile_view': 'show_profile'
'click .link_to_tree_view': 'show_tree'
'click .link_to_table_view': 'show_table'
'click .link_to_raw_view': 'show_raw'
'click .activate_profiler': 'activate_profiler'
'click .more_results_link': 'show_next_batch'
'click .pause_feed': 'pause_feed'
'click .unpause_feed': 'unpause_feed'
initialize: (args) =>
@container = args.container
@view = args.view
@view_object = null
@scroll_handler = => @handle_scroll()
@floating_metadata = false
$(window).on('scroll', @scroll_handler)
@handle_scroll()
handle_scroll: =>
scroll = $(window).scrollTop()
pos = @$('.results_header').offset()?.top + 2
if not pos?
return
if @floating_metadata and pos > scroll
@floating_metadata = false
@$('.metadata').removeClass('floating_metadata')
if @container.state.pause_at?
@unpause_feed 'automatic'
if not @floating_metadata and pos < scroll
@floating_metadata = true
@$('.metadata').addClass('floating_metadata')
if not @container.state.pause_at?
@pause_feed 'automatic'
pause_feed: (event) =>
if event is 'automatic'
@auto_unpause = true
else
@auto_unpause = false
event?.preventDefault()
@view_object?.pause_feed()
@$('.metadata').addClass('feed_paused').removeClass('feed_unpaused')
unpause_feed: (event) =>
if event is 'automatic'
if not @auto_unpause
return
else
event.preventDefault()
@view_object?.unpause_feed()
@$('.metadata').removeClass('feed_paused').addClass('feed_unpaused')
show_tree: (event) =>
event.preventDefault()
@set_view 'tree'
show_profile: (event) =>
event.preventDefault()
@set_view 'profile'
show_table: (event) =>
event.preventDefault()
@set_view 'table'
show_raw: (event) =>
event.preventDefault()
@set_view 'raw'
set_view: (view) =>
@view = view
@container.state.view = view
@$(".link_to_#{@view}_view").parent().addClass 'active'
@$(".link_to_#{@view}_view").parent().siblings().removeClass 'active'
if @query_result?.ready
@new_view()
# TODO: The scrollbar sometime shows up when it is not needed
set_scrollbar: =>
if @view is 'table'
content_name = '.json_table'
content_container = '.table_view_container'
else if @view is 'tree'
content_name = '.json_tree'
content_container = '.tree_view_container'
else if @view is 'profile'
content_name = '.json_tree'
content_container = '.profile_view_container'
else if @view is 'raw'
@$('.wrapper_scrollbar').hide()
# There is no scrolbar with the raw view
return
# Set the floating scrollbar
width_value = @$(content_name).innerWidth() # Include padding
if width_value < @$(content_container).width()
# If there is no need for scrollbar, we hide the one on the top
@$('.wrapper_scrollbar').hide()
if @set_scrollbar_scroll_handler?
$(window).unbind 'scroll', @set_scrollbar_scroll_handler
else
# Else we set the fake_content to the same width as the table that contains data and links the two scrollbars
@$('.wrapper_scrollbar').show()
@$('.scrollbar_fake_content').width width_value
$(".wrapper_scrollbar").scroll ->
$(content_container).scrollLeft($(".wrapper_scrollbar").scrollLeft())
$(content_container).scroll ->
$(".wrapper_scrollbar").scrollLeft($(content_container).scrollLeft())
position_scrollbar = ->
if $(content_container).offset()?
# Sometimes we don't have to display the scrollbar (when the results are not shown because the query is too big)
if $(window).scrollTop()+$(window).height() < $(content_container).offset().top+20 # bottom of the window < beginning of $('.json_table_container') // 20 pixels is the approximate height of the scrollbar (so we don't show JUST the scrollbar)
that.$('.wrapper_scrollbar').hide()
# We show the scrollbar and stick it to the bottom of the window because there ismore content below
else if $(window).scrollTop()+$(window).height() < $(content_container).offset().top+$(content_container).height() # bottom of the window < end of $('.json_table_container')
that.$('.wrapper_scrollbar').show()
that.$('.wrapper_scrollbar').css 'overflow', 'auto'
that.$('.wrapper_scrollbar').css 'margin-bottom', '0px'
# And sometimes we "hide" it
else
# We can not hide .wrapper_scrollbar because it would break the binding between wrapper_scrollbar and content_container
that.$('.wrapper_scrollbar').css 'overflow', 'hidden'
that = @
position_scrollbar()
@set_scrollbar_scroll_handler = position_scrollbar
$(window).scroll @set_scrollbar_scroll_handler
$(window).resize ->
position_scrollbar()
activate_profiler: (event) =>
event.preventDefault()
if @container.options_view.state is 'hidden'
@container.toggle_options
cb: =>
setTimeout( =>
if @container.state.options.profiler is false
@container.options_view.$('.option_description[data-option="profiler"]').click()
@container.options_view.$('.profiler_enabled').show()
@container.options_view.$('.profiler_enabled').css 'visibility', 'visible'
, 100)
else
if @container.state.options.profiler is false
@container.options_view.$('.option_description[data-option="profiler"]').click()
@container.options_view.$('.profiler_enabled').hide()
@container.options_view.$('.profiler_enabled').css 'visibility', 'visible'
@container.options_view.$('.profiler_enabled').slideDown 'fast'
render_error: (query, err, js_error) =>
@view_object?.remove()
@view_object = null
@query_result?.discard()
@$el.html @error_template
query: query
error: err.toString().replace(/^(\s*)/, '')
js_error: js_error is true
return @
set_query_result: ({query_result}) =>
@query_result?.discard()
@query_result = query_result
if query_result.ready
@render()
@new_view()
else
@query_result.on 'ready', () =>
@render()
@new_view()
@query_result.on 'end', =>
@render()
render: (args) =>
if @query_result?.ready
@view_object?.$el.detach()
has_more_data = not @query_result.ended and @query_result.position + @container.state.options.query_limit <= @query_result.size()
batch_size = @view_object?.current_batch_size()
@$el.html @template
range_begin: @query_result.position + 1
range_end: batch_size and @query_result.position + batch_size
query_has_changed: args?.query_has_changed
show_more_data: has_more_data and not @container.state.cursor_timed_out
cursor_timed_out_template: (
@cursor_timed_out_template() if not @query_result.ended and @container.state.cursor_timed_out)
execution_time_pretty: util.prettify_duration @query_result.server_duration
no_results: @query_result.ended and @query_result.size() == 0
num_results: @query_result.size()
floating_metadata: @floating_metadata
feed: @feed_info()
@$('.execution_time').tooltip
for_dataexplorer: true
trigger: 'hover'
placement: 'bottom'
@$('.tab-content').html @view_object?.$el
@$(".link_to_#{@view}_view").parent().addClass 'active'
return @
update_feed_metadata: =>
info = @feed_info()
if not info?
return
$('.feed_upcoming').text(info.upcoming)
$('.feed_overflow').parent().toggleClass('hidden', not info.overflow)
feed_info: =>
if @query_result.is_feed
total = @container.state.pause_at ? @query_result.size()
ended: @query_result.ended
overflow: @container.state.options.query_limit < total
paused: @container.state.pause_at?
upcoming: @query_result.size() - total
new_view: () =>
@view_object?.remove()
@view_object = new @views[@view]
parent: @
query_result: @query_result
@$('.tab-content').html @view_object.render().$el
@init_after_dom_rendered()
@set_scrollbar()
init_after_dom_rendered: =>
@view_object?.init_after_dom_rendered?()
# Check if the cursor timed out. If yes, make sure that the user cannot fetch more results
cursor_timed_out: =>
@container.state.cursor_timed_out = true
if @container.state.query_result?.ended is true
@$('.more_results_paragraph').html @cursor_timed_out_template()
remove: =>
@view_object?.remove()
if @query_result?.is_feed
@query_result.force_end_gracefully()
if @set_scrollbar_scroll_handler?
$(window).unbind 'scroll', @set_scrollbar_scroll_handler
$(window).unbind 'resize'
$(window).off('scroll', @scroll_handler)
super()
handle_mouseup: (event) =>
@view_object?.handle_mouseup?(event)
handle_mousemove: (event) =>
@view_object?.handle_mousedown?(event)
show_next_batch: (event) =>
event.preventDefault()
$(window).scrollTop($('.results_container').offset().top)
@view_object?.show_next_batch()
class OptionsView extends Backbone.View
dataexplorer_options_template: require('../handlebars/dataexplorer-options.hbs')
className: 'options_view'
events:
'click li:not(.text-input)': 'toggle_option'
'change #query_limit': 'change_query_limit'
initialize: (args) =>
@container = args.container
@options = args.options
@state = 'hidden'
toggle_option: (event) =>
event.preventDefault()
new_target = @$(event.target).data('option')
@$('#'+new_target).prop 'checked', !@options[new_target]
if event.target.nodeName isnt 'INPUT' # Label we catch if for us
new_value = @$('#'+new_target).is(':checked')
@options[new_target] = new_value
if window.localStorage?
window.localStorage.options = JSON.stringify @options
if new_target is 'profiler' and new_value is false
@$('.profiler_enabled').slideUp 'fast'
change_query_limit: (event) =>
query_limit = parseInt(@$("#query_limit").val(), 10) or DEFAULTS.options.query_limit
@options['query_limit'] = Math.max(query_limit, 1)
if window.localStorage?
window.localStorage.options = JSON.stringify @options
@$('#query_limit').val(@options['query_limit']) # In case the input is reset to 40
render: (displayed) =>
@$el.html @dataexplorer_options_template @options
if displayed is true
@$el.show()
@delegateEvents()
return @
class HistoryView extends Backbone.View
dataexplorer_history_template: require('../handlebars/dataexplorer-history.hbs')
dataexplorer_query_li_template: require('../handlebars/dataexplorer-query_li.hbs')
className: 'history_container'
size_history_displayed: 300
state: 'hidden' # hidden, visible
index_displayed: 0
events:
'click .load_query': 'load_query'
'click .delete_query': 'delete_query'
start_resize: (event) =>
@start_y = event.pageY
@start_height = @container.$('.nano').height()
@mouse_down = true
$('body').toggleClass('resizing', true)
handle_mousemove: (event) =>
if @mouse_down is true
@height_history = Math.max 0, @start_height-@start_y+event.pageY
@container.$('.nano').height @height_history
handle_mouseup: (event) =>
if @mouse_down is true
@mouse_down = false
$('.nano').nanoScroller({preventPageScrolling: true})
$('body').toggleClass('resizing', false)
initialize: (args) =>
@container = args.container
@history = args.history
@height_history = 204
render: (displayed) =>
@$el.html @dataexplorer_history_template()
if displayed is true
@$el.show()
if @history.length is 0
@$('.history_list').append @dataexplorer_query_li_template
no_query: true
displayed_class: 'displayed'
else
for query, i in @history
@$('.history_list').append @dataexplorer_query_li_template
query: query.query
broken_query: query.broken_query
id: i
num: i+1
@delegateEvents()
return @
load_query: (event) =>
id = @$(event.target).data().id
# Set + save codemirror
@container.codemirror.setValue @history[parseInt(id)].query
@container.state.current_query = @history[parseInt(id)].query
@container.save_current_query()
delete_query: (event) =>
that = @
# Remove the query and overwrite localStorage.rethinkdb_history
id = parseInt(@$(event.target).data().id)
@history.splice(id, 1)
window.localStorage.rethinkdb_history = JSON.stringify @history
# Animate the deletion
is_at_bottom = @$('.history_list').height() is $('.nano > .content').scrollTop()+$('.nano').height()
@$('#query_history_'+id).slideUp 'fast', =>
that.$(this).remove()
that.render()
that.container.adjust_collapsible_panel_height
is_at_bottom: is_at_bottom
add_query: (args) =>
query = args.query
broken_query = args.broken_query
that = @
is_at_bottom = @$('.history_list').height() is $('.nano > .content').scrollTop()+$('.nano').height()
@$('.history_list').append @dataexplorer_query_li_template
query: query
broken_query: broken_query
id: @history.length-1
num: @history.length
if @$('.no_history').length > 0
@$('.no_history').slideUp 'fast', ->
$(@).remove()
if that.state is 'visible'
that.container.adjust_collapsible_panel_height
is_at_bottom: is_at_bottom
else if that.state is 'visible'
@container.adjust_collapsible_panel_height
delay_scroll: true
is_at_bottom: is_at_bottom
clear_history: (event) =>
that = @
event.preventDefault()
@container.clear_history()
@history = @container.state.history
@$('.query_history').slideUp 'fast', ->
$(@).remove()
if that.$('.no_history').length is 0
that.$('.history_list').append that.dataexplorer_query_li_template
no_query: true
displayed_class: 'hidden'
that.$('.no_history').slideDown 'fast'
that.container.adjust_collapsible_panel_height
size: 40
move_arrow: 'show'
is_at_bottom: 'true'
class DriverHandler
constructor: (options) ->
@container = options.container
@concurrent = 0
@total_duration = 0
_begin: =>
if @concurrent == 0
@container.toggle_executing true
@begin_time = new Date()
@concurrent++
_end: =>
if @concurrent > 0
@concurrent--
now = new Date()
@total_duration += now - @begin_time
@begin_time = now
if @concurrent == 0
@container.toggle_executing false
close_connection: =>
if @connection?.open is true
driver.close @connection
@connection = null
@_end()
run_with_new_connection: (query, {callback, connection_error, optargs}) =>
@close_connection()
@total_duration = 0
@concurrent = 0
driver.connect (error, connection) =>
if error?
connection_error error
connection.removeAllListeners 'error' # See issue 1347
connection.on 'error', (error) =>
connection_error error
@connection = connection
@_begin()
query.private_run connection, optargs, (error, result) =>
@_end()
callback error, result
cursor_next: (cursor, {error, row, end}) =>
if not @connection?
end()
@_begin()
cursor.next (err, row_) =>
@_end()
if err?
if err.message is 'No more rows in the cursor.'
end()
else
error err
else
row row_
remove: =>
@close_connection()
exports.QueryResult = QueryResult
exports.Container = Container
exports.ResultView = ResultView
exports.TreeView = TreeView
exports.TableView = TableView
exports.RawView = RawView
exports.ProfileView = ProfileView
exports.ResultViewWrapper = ResultViewWrapper
exports.OptionsView = OptionsView
exports.HistoryView = HistoryView
exports.DriverHandler = DriverHandler
exports.dataexplorer_state = dataexplorer_state
| true | # Copyright 2010-2015 RethinkDB, all rights reserved.
app = require('./app.coffee')
system_db = app.system_db
driver = app.driver
util = require('./util.coffee')
r = require('rethinkdb')
DEFAULTS =
current_query: null
query_result: null
cursor_timed_out: true
view: 'tree'
history_state: 'hidden'
last_keys: []
last_columns_size: {}
options_state: 'hidden'
options:
suggestions: true
electric_punctuation: false
profiler: false
query_limit: 40
history: []
focus_on_codemirror: true
Object.freeze(DEFAULTS)
Object.freeze(DEFAULTS.options)
# state is initially a mutable version of defaults. It's modified later
dataexplorer_state = _.extend({}, DEFAULTS)
# This class represents the results of a query.
#
# If there is a profile, `profile` is set. After a 'ready' event,
# one of `error`, `value` or `cursor` is always set, `type`
# indicates which. `ended` indicates whether there are any more
# results to read.
#
# It triggers the following events:
# * ready: The first response has been received
# * add: Another row has been received from a cursor
# * error: An error has occurred
# * end: There are no more documents to fetch
# * discard: The results have been discarded
class QueryResult
_.extend @::, Backbone.Events
constructor: (options) ->
@has_profile = options.has_profile
@current_query = options.current_query
@raw_query = options.raw_query
@driver_handler = options.driver_handler
@ready = false
@position = 0
@server_duration = null
if options.events?
for own event, handler of options.events
@on event, handler
# Can be used as a callback to run
set: (error, result) =>
if error?
@set_error error
else if not @discard_results
if @has_profile
@profile = result.profile
@server_duration = result.profile.reduce(((total, prof) ->
total + (prof['duration(ms)'] or prof['mean_duration(ms)'])), 0)
value = result.value
else
@profile = null
@server_duration = result?.profile[0]['duration(ms)']
value = result.value
if value? and typeof value._next is 'function' and value not instanceof Array # if it's a cursor
@type = 'cursor'
@results = []
@results_offset = 0
@cursor = value
@is_feed = @cursor.toString().match(/\[object .*Feed\]/)
@missing = 0
@ended = false
@server_duration = null # ignore server time if batched response
else
@type = 'value'
@value = value
@ended = true
@ready = true
@trigger 'ready', @
# Discard the results
discard: =>
@trigger 'discard', @
@off()
@type = 'discarded'
@discard_results = true
delete @profile
delete @value
delete @results
delete @results_offset
@cursor?.close().catch?(() -> null)
delete @cursor
# Gets the next result from the cursor
fetch_next: =>
if not @ended
try
@driver_handler.cursor_next @cursor,
end: () =>
@ended = true
@trigger 'end', @
error: (error) =>
if not @ended
@set_error error
row: (row) =>
if @discard_results
return
@results.push row
@trigger 'add', @, row
catch error
@set_error error
set_error: (error) =>
@type = 'error'
@error = error
@trigger 'error', @, error
@discard_results = true
@ended = true
size: =>
switch @type
when 'value'
if @value instanceof Array
return @value.length
else
return 1
when 'cursor'
return @results.length + @results_offset
force_end_gracefully: =>
if @is_feed
@ended = true
@cursor?.close().catch(() -> null)
@trigger 'end', @
drop_before: (n) =>
if n > @results_offset
@results = @results[n - @results_offset ..]
@results_offset = n
slice: (from, to) =>
if from < 0
from = @results.length + from
else
from = from - @results_offset
from = Math.max 0, from
if to?
if to < 0
to = @results.length + to
else
to = to - @results_offset
to = Math.min @results.length, to
return @results[from .. to]
else
return @results[from ..]
at_beginning: =>
if @results_offset?
return @results_offset == 0
else
return true
class Container extends Backbone.View
id: 'dataexplorer'
template: require('../handlebars/dataexplorer_view.hbs')
input_query_template: require('../handlebars/dataexplorer_input_query.hbs')
description_template: require('../handlebars/dataexplorer-description.hbs')
template_suggestion_name: require('../handlebars/dataexplorer_suggestion_name_li.hbs')
description_with_example_template: require('../handlebars/dataexplorer-description_with_example.hbs')
alert_connection_fail_template: require('../handlebars/alert-connection_fail.hbs')
databases_suggestions_template: require('../handlebars/dataexplorer-databases_suggestions.hbs')
tables_suggestions_template: require('../handlebars/dataexplorer-tables_suggestions.hbs')
reason_dataexplorer_broken_template: require('../handlebars/dataexplorer-reason_broken.hbs')
query_error_template: require('../handlebars/dataexplorer-query_error.hbs')
# Constants
line_height: 13 # Define the height of a line (used for a line is too long)
size_history: 50
max_size_stack: 100 # If the stack of the query (including function, string, object etc. is greater than @max_size_stack, we stop parsing the query
max_size_query: 1000 # If the query is more than 1000 char, we don't show suggestion (codemirror doesn't highlight/parse if the query is more than 1000 characdd_ters too
delay_toggle_abort: 70 # If a query didn't return during this period (ms) we let people abort the query
events:
'mouseup .CodeMirror': 'handle_click'
'mousedown .suggestion_name_li': 'select_suggestion' # Keep mousedown to compete with blur on .input_query
'mouseover .suggestion_name_li' : 'mouseover_suggestion'
'mouseout .suggestion_name_li' : 'mouseout_suggestion'
'click .clear_query': 'clear_query'
'click .execute_query': 'execute_query'
'click .abort_query': 'abort_query'
'click .change_size': 'toggle_size'
'click #rerun_query': 'execute_query'
'click .close': 'close_alert'
'click .clear_queries_link': 'clear_history_view'
'click .close_queries_link': 'toggle_history'
'click .toggle_options_link': 'toggle_options'
'mousedown .nano_border_bottom': 'start_resize_history'
# Let people click on the description and select text
'mousedown .suggestion_description': 'mouse_down_description'
'click .suggestion_description': 'stop_propagation'
'mouseup .suggestion_description': 'mouse_up_description'
'mousedown .suggestion_full_container': 'mouse_down_description'
'click .suggestion_full_container': 'stop_propagation'
'mousedown .CodeMirror': 'mouse_down_description'
'click .CodeMirror': 'stop_propagation'
mouse_down_description: (event) =>
@keep_suggestions_on_blur = true
@stop_propagation event
stop_propagation: (event) =>
event.stopPropagation()
mouse_up_description: (event) =>
@keep_suggestions_on_blur = false
@stop_propagation event
start_resize_history: (event) =>
@history_view.start_resize event
clear_history_view: (event) =>
that = @
@clear_history() # Delete from localstorage
@history_view.clear_history event
# Method that make sure that just one button (history or option) is active
# We give this button an "active" class that make it looks like it's pressed.
toggle_pressed_buttons: =>
if @history_view.state is 'visible'
dataexplorer_state.history_state = 'visible'
@$('.clear_queries_link').fadeIn 'fast'
@$('.close_queries_link').addClass 'active'
else
dataexplorer_state.history_state = 'hidden'
@$('.clear_queries_link').fadeOut 'fast'
@$('.close_queries_link').removeClass 'active'
if @options_view.state is 'visible'
dataexplorer_state.options_state = 'visible'
@$('.toggle_options_link').addClass 'active'
else
dataexplorer_state.options_state = 'hidden'
@$('.toggle_options_link').removeClass 'active'
# Show/hide the history view
toggle_history: (args) =>
that = @
@deactivate_overflow()
if args.no_animation is true
# We just show the history
@history_view.state = 'visible'
@$('.content').html @history_view.render(true).$el
@move_arrow
type: 'history'
move_arrow: 'show'
@adjust_collapsible_panel_height
no_animation: true
is_at_bottom: true
else if @options_view.state is 'visible'
@options_view.state = 'hidden'
@move_arrow
type: 'history'
move_arrow: 'animate'
@options_view.$el.fadeOut 'fast', ->
that.$('.content').html that.history_view.render(false).$el
that.history_view.state = 'visible'
that.history_view.$el.fadeIn 'fast'
that.adjust_collapsible_panel_height
is_at_bottom: true
that.toggle_pressed_buttons() # Re-execute toggle_pressed_buttons because we delay the fadeIn
else if @history_view.state is 'hidden'
@history_view.state = 'visible'
@$('.content').html @history_view.render(true).$el
@history_view.delegateEvents()
@move_arrow
type: 'history'
move_arrow: 'show'
@adjust_collapsible_panel_height
is_at_bottom: true
else if @history_view.state is 'visible'
@history_view.state = 'hidden'
@hide_collapsible_panel 'history'
@toggle_pressed_buttons()
# Show/hide the options view
toggle_options: (args) =>
that = @
@deactivate_overflow()
if args?.no_animation is true
@options_view.state = 'visible'
@$('.content').html @options_view.render(true).$el
@options_view.delegateEvents()
@move_arrow
type: 'options'
move_arrow: 'show'
@adjust_collapsible_panel_height
no_animation: true
is_at_bottom: true
else if @history_view.state is 'visible'
@history_view.state = 'hidden'
@move_arrow
type: 'options'
move_arrow: 'animate'
@history_view.$el.fadeOut 'fast', ->
that.$('.content').html that.options_view.render(false).$el
that.options_view.state = 'visible'
that.options_view.$el.fadeIn 'fast'
that.adjust_collapsible_panel_height()
that.toggle_pressed_buttons()
that.$('.profiler_enabled').css 'visibility', 'hidden'
that.$('.profiler_enabled').hide()
else if @options_view.state is 'hidden'
@options_view.state = 'visible'
@$('.content').html @options_view.render(true).$el
@options_view.delegateEvents()
@move_arrow
type: 'options'
move_arrow: 'show'
@adjust_collapsible_panel_height
cb: args?.cb
else if @options_view.state is 'visible'
@options_view.state = 'hidden'
@hide_collapsible_panel 'options'
@toggle_pressed_buttons()
# Hide the collapsible_panel whether it contains the option or history view
hide_collapsible_panel: (type) =>
that = @
@deactivate_overflow()
@$('.nano').animate
height: 0
, 200
, ->
that.activate_overflow()
# We don't want to hide the view if the user changed the state of the view while it was being animated
if (type is 'history' and that.history_view.state is 'hidden') or (type is 'options' and that.options_view.state is 'hidden')
that.$('.nano_border').hide() # In case the user trigger hide/show really fast
that.$('.arrow_dataexplorer').hide() # In case the user trigger hide/show really fast
that.$(@).css 'visibility', 'hidden'
@$('.nano_border').slideUp 'fast'
@$('.arrow_dataexplorer').slideUp 'fast'
# Move the arrow that points to the active button (on top of the collapsible panel). In case the user switch from options to history (or the opposite), we need to animate it
move_arrow: (args) =>
# args =
# type: 'options'/'history'
# move_arrow: 'show'/'animate'
if args.type is 'options'
margin_right = 74
else if args.type is 'history'
margin_right = 154
if args.move_arrow is 'show'
@$('.arrow_dataexplorer').css 'margin-right', margin_right
@$('.arrow_dataexplorer').show()
else if args.move_arrow is 'animate'
@$('.arrow_dataexplorer').animate
'margin-right': margin_right
, 200
@$('.nano_border').show()
# Adjust the height of the container of the history/option view
# Arguments:
# size: size of the collapsible panel we want // If not specified, we are going to try to figure it out ourselves
# no_animation: boolean (do we need to animate things or just to show it)
# is_at_bottom: boolean (if we were at the bottom, we want to scroll down once we have added elements in)
# delay_scroll: boolean, true if we just added a query - It speficied if we adjust the height then scroll or do both at the same time
adjust_collapsible_panel_height: (args) =>
that = @
if args?.size?
size = args.size
else
if args?.extra?
size = Math.min @$('.content > div').height()+args.extra, @history_view.height_history
else
size = Math.min @$('.content > div').height(), @history_view.height_history
@deactivate_overflow()
duration = Math.max 150, size
duration = Math.min duration, 250
#@$('.nano').stop(true, true).animate
@$('.nano').css 'visibility', 'visible' # In case the user trigger hide/show really fast
if args?.no_animation is true
@$('.nano').height size
@$('.nano > .content').scrollTop @$('.nano > .content > div').height()
@$('.nano').css 'visibility', 'visible' # In case the user trigger hide/show really fast
@$('.arrow_dataexplorer').show() # In case the user trigger hide/show really fast
@$('.nano_border').show() # In case the user trigger hide/show really fast
if args?.no_animation is true
@$('.nano').nanoScroller({preventPageScrolling: true})
@activate_overflow()
else
@$('.nano').animate
height: size
, duration
, ->
that.$(@).css 'visibility', 'visible' # In case the user trigger hide/show really fast
that.$('.arrow_dataexplorer').show() # In case the user trigger hide/show really fast
that.$('.nano_border').show() # In case the user trigger hide/show really fast
that.$(@).nanoScroller({preventPageScrolling: true})
that.activate_overflow()
if args? and args.delay_scroll is true and args.is_at_bottom is true
that.$('.nano > .content').animate
scrollTop: that.$('.nano > .content > div').height()
, 200
if args?.cb?
args.cb()
if args? and args.delay_scroll isnt true and args.is_at_bottom is true
that.$('.nano > .content').animate
scrollTop: that.$('.nano > .content > div').height()
, 200
# We deactivate the scrollbar (if there isn't) while animating to have a smoother experience. We´ll put back the scrollbar once the animation is done.
deactivate_overflow: =>
if $(window).height() >= $(document).height()
$('body').css 'overflow', 'hidden'
activate_overflow: =>
$('body').css 'overflow', 'auto'
displaying_full_view: false # Boolean for the full view (true if full view)
# Method to close an alert/warning/arror
close_alert: (event) ->
event.preventDefault()
$(event.currentTarget).parent().slideUp('fast', -> $(this).remove())
# Build the suggestions
map_state: # Map function -> state
'': ''
descriptions: {}
suggestions: {} # Suggestions[state] = function for this state
types:
value: ['number', 'bool', 'string', 'array', 'object', 'time', 'binary', 'line', 'point', 'polygon']
any: ['number', 'bool', 'string', 'array', 'object', 'stream', 'selection', 'table', 'db', 'r', 'error', 'binary', 'line', 'point', 'polygon']
geometry: ['line', 'point', 'polygon']
sequence: ['table', 'selection', 'stream', 'array']
stream: ['table', 'selection']
grouped_stream: ['stream', 'array']
# Convert meta types (value, any or sequence) to an array of types or return an array composed of just the type
convert_type: (type) =>
if @types[type]?
return @types[type]
else
return [type]
# Flatten an array
expand_types: (ar) =>
result = []
if _.isArray(ar)
for element in ar
result.concat @convert_type element
else
result.concat @convert_type element
return result
# Once we are done moving the doc, we could generate a .js in the makefile file with the data so we don't have to do an ajax request+all this stuff
set_doc_description: (command, tag, suggestions) =>
if command['body']?
# The body of `bracket` uses `()` and not `bracket()`
# so we manually set the variables dont_need_parenthesis and full_tag
if tag is 'bracket'
dont_need_parenthesis = false
full_tag = tag+'('
else
dont_need_parenthesis = not (new RegExp(tag+'\\(')).test(command['body'])
if dont_need_parenthesis
full_tag = tag # Here full_tag is just the name of the tag
else
full_tag = tag+'(' # full tag is the name plus a parenthesis (we will match the parenthesis too)
@descriptions[full_tag] = (grouped_data) =>
name: tag
args: /.*(\(.*\))/.exec(command['body'])?[1]
description:
@description_with_example_template
description: command['description']
example: command['example']
grouped_data: grouped_data is true and full_tag isnt 'group(' and full_tag isnt 'ungroup('
parents = {}
returns = []
for pair in command.io ? []
parent_values = if (pair[0] == null) then '' else pair[0]
return_values = pair[1]
parent_values = @convert_type parent_values
return_values = @convert_type return_values
returns = returns.concat return_values
for parent_value in parent_values
parents[parent_value] = true
if full_tag isnt '('
for parent_value of parents
if not suggestions[parent_value]?
suggestions[parent_value] = []
suggestions[parent_value].push full_tag
@map_state[full_tag] = returns # We use full_tag because we need to differentiate between r. and r(
# All the commands we are going to ignore
ignored_commands:
'connect': true
'close': true
'reconnect': true
'use': true
'runp': true
'next': true
'collect': true
'run': true
'EventEmitter\'s methods': true
# Method called on the content of reql_docs.json
# Load the suggestions in @suggestions, @map_state, @descriptions
set_docs: (data) =>
for key of data
command = data[key]
tag = command['name']
if tag of @ignored_commands
continue
if tag is '() (bracket)' # The parentheses will be added later
# Add `(attr)`
tag = ''
@set_doc_description command, tag, @suggestions
# Add `bracket(sttr)`
tag = 'bracket'
else if tag is 'toJsonString, toJSON'
# Add the `toJsonString()` alias
tag = 'toJsonString'
@set_doc_description command, tag, @suggestions
# Also add `toJSON()`
tag = 'toJSON'
@set_doc_description command, tag, @suggestions
relations = data['types']
for state of @suggestions
@suggestions[state].sort()
if Container.prototype.focus_on_codemirror is true
# "@" refers to prototype -_-
# In case we give focus to codemirror then load the docs, we show the suggestion
app.main.router.current_view.handle_keypress()
# Save the query in the history
# The size of the history is infinite per session. But we will just save @size_history queries in localStorage
save_query: (args) =>
query = args.query
broken_query = args.broken_query
# Remove empty lines
query = query.replace(/^\s*$[\n\r]{1,}/gm, '')
query = query.replace(/\s*$/, '') # Remove the white spaces at the end of the query (like newline/space/tab)
if window.localStorage?
if dataexplorer_state.history.length is 0 or dataexplorer_state.history[dataexplorer_state.history.length-1].query isnt query and @regex.white.test(query) is false
dataexplorer_state.history.push
query: query
broken_query: broken_query
if dataexplorer_state.history.length>@size_history
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history.slice dataexplorer_state.history.length-@size_history
else
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history
@history_view.add_query
query: query
broken_query: broken_query
clear_history: =>
dataexplorer_state.history.length = 0
window.localStorage.rethinkdb_history = JSON.stringify dataexplorer_state.history
# Save the current query (the one in codemirror) in local storage
save_current_query: =>
if window.localStorage?
window.localStorage.current_query = JSON.stringify @codemirror.getValue()
initialize: (args) =>
@TermBaseConstructor = r.expr(1).constructor.__super__.constructor.__super__.constructor
@state = args.state
@executing = false
# Load options from local storage
if window.localStorage?
try
@state.options = JSON.parse(window.localStorage.options)
# Ensure no keys are without a default value in the
# options object
_.defaults(@state.options, DEFAULTS.options)
catch err
window.localStorage.removeItem 'options'
# Whatever the case with default values, we need to sync
# up with the current application's idea of the options
window.localStorage.options = JSON.stringify(@state.options)
# Load the query that was written in code mirror (that may not have been executed before)
if typeof window.localStorage?.current_query is 'string'
try
dataexplorer_state.current_query = JSON.parse window.localStorage.current_query
catch err
window.localStorage.removeItem 'current_query'
if window.localStorage?.rethinkdb_history?
try
dataexplorer_state.history = JSON.parse window.localStorage.rethinkdb_history
catch err
window.localStorage.removeItem 'rethinkdb_history'
@query_has_changed = dataexplorer_state.query_result?.current_query isnt dataexplorer_state.current_query
# Index used to navigate through history with the keyboard
@history_displayed_id = 0 # 0 means we are showing the draft, n>0 means we are showing the nth query in the history
# We escape the last function because we are building a regex on top of it.
# Structure: [ [ pattern, replacement], [pattern, replacement], ... ]
@unsafe_to_safe_regexstr = [
[/\\/g, '\\\\'] # This one has to be first
[/\(/g, '\\(']
[/\)/g, '\\)']
[/\^/g, '\\^']
[/\$/g, '\\$']
[/\*/g, '\\*']
[/\+/g, '\\+']
[/\?/g, '\\?']
[/\./g, '\\.']
[/\|/g, '\\|']
[/\{/g, '\\{']
[/\}/g, '\\}']
[/\[/g, '\\[']
]
@results_view_wrapper = new ResultViewWrapper
container: @
view: dataexplorer_state.view
@options_view = new OptionsView
container: @
options: dataexplorer_state.options
@history_view = new HistoryView
container: @
history: dataexplorer_state.history
@driver_handler = new DriverHandler
container: @
# These events were caught here to avoid being bound and unbound every time
# The results changed. It should ideally be caught in the individual result views
# that actually need it.
$(window).mousemove @handle_mousemove
$(window).mouseup @handle_mouseup
$(window).mousedown @handle_mousedown
@keep_suggestions_on_blur = false
@databases_available = {}
@fetch_data()
fetch_data: =>
# We fetch all "proper" tables from `table_config`. In addition, we need
# to fetch the list of system tables separately.
query = r.db(system_db).table('table_config')
.pluck('db', 'name')
.group('db')
.ungroup()
.map((group) -> [group("group"), group("reduction")("name").orderBy( (x) -> x )])
.coerceTo "OBJECT"
.merge(r.object(system_db, r.db(system_db).tableList().coerceTo("ARRAY")))
@timer = driver.run query, 5000, (error, result) =>
if error?
# Nothing bad, we'll try again, let's just log the error
console.log "Error: Could not fetch databases and tables"
console.log error
else
@databases_available = result
handle_mousemove: (event) =>
@results_view_wrapper.handle_mousemove event
@history_view.handle_mousemove event
handle_mouseup: (event) =>
@results_view_wrapper.handle_mouseup event
@history_view.handle_mouseup event
handle_mousedown: (event) =>
# $(window) caught a mousedown event, so it wasn't caught by $('.suggestion_description')
# Let's hide the suggestion/description
@keep_suggestions_on_blur = false
@hide_suggestion_and_description()
render: =>
@$el.html @template()
@$('.input_query_full_container').html @input_query_template()
# Check if the browser supports the JavaScript driver
# We do not support internet explorer (even IE 10) and old browsers.
if navigator?.appName is 'Microsoft Internet Explorer'
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
is_internet_explorer: true
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
else if (not DataView?) or (not Uint8Array?) # The main two components that the javascript driver requires.
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
else if not r? # In case the javascript driver is not found (if build from source for example)
@$('.reason_dataexplorer_broken').html @reason_dataexplorer_broken_template
no_driver: true
@$('.reason_dataexplorer_broken').slideDown 'fast'
@$('.button_query').prop 'disabled', true
# Let's bring back the data explorer to its old state (if there was)
if dataexplorer_state?.query_result?
@results_view_wrapper.set_query_result
query_result: dataexplorer_state.query_result
@$('.results_container').html @results_view_wrapper.render(query_has_changed: @query_has_changed).$el
# The query in code mirror is set in init_after_dom_rendered (because we can't set it now)
return @
# This method has to be called AFTER the el element has been inserted in the DOM tree, mostly for codemirror
init_after_dom_rendered: =>
@codemirror = CodeMirror.fromTextArea document.getElementById('input_query'),
mode:
name: 'javascript'
onKeyEvent: @handle_keypress
lineNumbers: true
lineWrapping: true
matchBrackets: true
tabSize: 2
@codemirror.on 'blur', @on_blur
@codemirror.on 'gutterClick', @handle_gutter_click
@codemirror.setSize '100%', 'auto'
if dataexplorer_state.current_query?
@codemirror.setValue dataexplorer_state.current_query
@codemirror.focus() # Give focus
# Track if the focus is on codemirror
# We use it to refresh the docs once the reql_docs.json is loaded
dataexplorer_state.focus_on_codemirror = true
@codemirror.setCursor @codemirror.lineCount(), 0
if @codemirror.getValue() is '' # We show suggestion for an empty query only
@handle_keypress()
@results_view_wrapper.init_after_dom_rendered()
@draft = @codemirror.getValue()
if dataexplorer_state.history_state is 'visible' # If the history was visible, we show it
@toggle_history
no_animation: true
if dataexplorer_state.options_state is 'visible' # If the history was visible, we show it
@toggle_options
no_animation: true
on_blur: =>
dataexplorer_state.focus_on_codemirror = false
# We hide the description only if the user isn't selecting text from a description.
if @keep_suggestions_on_blur is false
@hide_suggestion_and_description()
# We have to keep track of a lot of things because web-kit browsers handle the events keydown, keyup, blur etc... in a strange way.
current_suggestions: []
current_highlighted_suggestion: -1
current_conpleted_query: ''
query_first_part: ''
query_last_part: ''
mouse_type_event:
click: true
dblclick: true
mousedown: true
mouseup: true
mouseover: true
mouseout: true
mousemove: true
char_breakers:
'.': true
'}': true
')': true
',': true
';': true
']': true
handle_click: (event) =>
@handle_keypress null, event
# Pair ', ", {, [, (
# Return true if we want code mirror to ignore the key event
pair_char: (event, stack) =>
if event?.which?
# If there is a selection and the user hit a quote, we wrap the seleciton in quotes
if @codemirror.getSelection() isnt '' and event.type is 'keypress' # This is madness. If we look for keydown, shift+right arrow match a single quote...
char_to_insert = String.fromCharCode event.which
if char_to_insert? and char_to_insert is '"' or char_to_insert is "'"
@codemirror.replaceSelection(char_to_insert+@codemirror.getSelection()+char_to_insert)
event.preventDefault()
return true
if event.which is 8 # Backspace
if event.type isnt 'keydown'
return true
previous_char = @get_previous_char()
if previous_char is null
return true
# If the user remove the opening bracket and the next char is the closing bracket, we delete both
if previous_char of @matching_opening_bracket
next_char = @get_next_char()
if next_char is @matching_opening_bracket[previous_char]
num_not_closed_bracket = @count_not_closed_brackets previous_char
if num_not_closed_bracket <= 0
@remove_next()
return true
# If the user remove the first quote of an empty string, we remove both quotes
else if previous_char is '"' or previous_char is "'"
next_char = @get_next_char()
if next_char is previous_char and @get_previous_char(2) isnt '\\'
num_quote = @count_char char_to_insert
if num_quote%2 is 0
@remove_next()
return true
return true
if event.type isnt 'keypress' # We catch keypress because single and double quotes have not the same keyCode on keydown/keypres #thisIsMadness
return true
char_to_insert = String.fromCharCode event.which
if char_to_insert? # and event.which isnt 91 # 91 map to [ on OS X
if @codemirror.getSelection() isnt ''
if (char_to_insert of @matching_opening_bracket or char_to_insert of @matching_closing_bracket)
@codemirror.replaceSelection ''
else
return true
last_element_incomplete_type = @last_element_type_if_incomplete(stack)
if char_to_insert is '"' or char_to_insert is "'"
num_quote = @count_char char_to_insert
next_char = @get_next_char()
if next_char is char_to_insert # Next char is a single quote
if num_quote%2 is 0
if last_element_incomplete_type is 'string' or last_element_incomplete_type is 'object_key' # We are at the end of a string and the user just wrote a quote
@move_cursor 1
event.preventDefault()
return true
else
# We are at the begining of a string, so let's just add one quote
return true
else
# Let's add the closing/opening quote missing
return true
else
if num_quote%2 is 0 # Next char is not a single quote and the user has an even number of quotes.
# Let's keep a number of quote even, so we add one extra quote
last_key = @get_last_key(stack)
if last_element_incomplete_type is 'string'
return true
else if last_element_incomplete_type is 'object_key' and (last_key isnt '' and @create_safe_regex(char_to_insert).test(last_key) is true) # A key in an object can be seen as a string
return true
else
@insert_next char_to_insert
else # Else we'll just insert one quote
return true
else if last_element_incomplete_type isnt 'string'
next_char = @get_next_char()
if char_to_insert of @matching_opening_bracket
num_not_closed_bracket = @count_not_closed_brackets char_to_insert
if num_not_closed_bracket >= 0 # We insert a closing bracket only if it help having a balanced number of opened/closed brackets
@insert_next @matching_opening_bracket[char_to_insert]
return true
return true
else if char_to_insert of @matching_closing_bracket
opening_char = @matching_closing_bracket[char_to_insert]
num_not_closed_bracket = @count_not_closed_brackets opening_char
if next_char is char_to_insert
if num_not_closed_bracket <= 0 # g(f(...|) In this case we add a closing parenthesis. Same behavior as in Ace
@move_cursor 1
event.preventDefault()
return true
return false
get_next_char: =>
cursor_end = @codemirror.getCursor()
cursor_end.ch++
return @codemirror.getRange @codemirror.getCursor(), cursor_end
get_previous_char: (less_value) =>
cursor_start = @codemirror.getCursor()
cursor_end = @codemirror.getCursor()
if less_value?
cursor_start.ch -= less_value
cursor_end.ch -= (less_value-1)
else
cursor_start.ch--
if cursor_start.ch < 0
return null
return @codemirror.getRange cursor_start, cursor_end
# Insert str after the cursor in codemirror
insert_next: (str) =>
@codemirror.replaceRange str, @codemirror.getCursor()
@move_cursor -1
remove_next: =>
end_cursor = @codemirror.getCursor()
end_cursor.ch++
@codemirror.replaceRange '', @codemirror.getCursor(), end_cursor
# Move cursor of move_value
# A negative value move the cursor to the left
move_cursor: (move_value) =>
cursor = @codemirror.getCursor()
cursor.ch += move_value
if cursor.ch < 0
cursor.ch = 0
@codemirror.setCursor cursor
# Count how many time char_to_count appeared ignoring strings and comments
count_char: (char_to_count) =>
query = @codemirror.getValue()
is_parsing_string = false
to_skip = 0
result = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
if char is char_to_count
result++
else # if element.is_parsing_string is false
if char is char_to_count
result++
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
return result
matching_opening_bracket:
'(': ')'
'{': '}'
'[': ']'
matching_closing_bracket:
')': '('
'}': '{'
']': '['
# opening_char has to be in @matching_bracket
# Count how many time opening_char has been opened but not closed
# A result < 0 means that the closing char has been found more often than the opening one
count_not_closed_brackets: (opening_char) =>
query = @codemirror.getValue()
is_parsing_string = false
to_skip = 0
result = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
else # if element.is_parsing_string is false
if char is opening_char
result++
else if char is @matching_opening_bracket[opening_char]
result--
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
return result
# Handle events on codemirror
# Return true if we want code mirror to ignore the event
handle_keypress: (editor, event) =>
if @ignored_next_keyup is true
if event?.type is 'keyup' and event?.which isnt 9
@ignored_next_keyup = false
return true
dataexplorer_state.focus_on_codemirror = true
# Let's hide the tooltip if the user just clicked on the textarea. We'll only display later the suggestions if there are (no description)
if event?.type is 'mouseup'
@hide_suggestion_and_description()
# Save the last query (even incomplete)
dataexplorer_state.current_query = @codemirror.getValue()
@save_current_query()
# Look for special commands
if event?.which?
if event.type isnt 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32)
# Because on event.type == 'keydown' we are going to change the state (hidden or displayed) of @$('.suggestion_description') and @$('.suggestion_name_list'), we don't want to fire this event a second time
return true
if event.which is 27 or (event.type is 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32) and (@$('.suggestion_description').css('display') isnt 'none' or @$('.suggestion_name_list').css('display') isnt 'none'))
# We caugh ESC or (Ctrl/Cmd+space with suggestion/description being displayed)
event.preventDefault() # Keep focus on code mirror
@hide_suggestion_and_description()
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
query_after_cursor = @codemirror.getRange @codemirror.getCursor(), {line:@codemirror.lineCount()+1, ch: 0}
# Compute the structure of the query written by the user.
# We compute it earlier than before because @pair_char also listen on keydown and needs stack
stack = @extract_data_from_query
size_stack: 0
query: query_before_cursor
position: 0
if stack is null # Stack is null if the query was too big for us to parse
@ignore_tab_keyup = false
@hide_suggestion_and_description()
return false
@current_highlighted_suggestion = -1
@current_highlighted_extra_suggestion = -1
@$('.suggestion_name_list').empty()
# Valid step, let's save the data
@query_last_part = query_after_cursor
@current_suggestions = []
@current_element = ''
@current_extra_suggestion = ''
@written_suggestion = null
@cursor_for_auto_completion = @codemirror.getCursor()
@description = null
result =
status: null
# create_suggestion is going to fill to_complete and to_describe
#to_complete: undefined
#to_describe: undefined
# Create the suggestion/description
@create_suggestion
stack: stack
query: query_before_cursor
result: result
result.suggestions = @uniq result.suggestions
@grouped_data = @count_group_level(stack).count_group > 0
if result.suggestions?.length > 0
for suggestion, i in result.suggestions
if suggestion isnt 'ungroup(' or @grouped_data is true # We add the suggestion for `ungroup` only if we are in a group_stream/data (using the flag @grouped_data)
result.suggestions.sort() # We could eventually sort things earlier with a merge sort but for now that should be enough
@current_suggestions.push suggestion
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
else if result.description?
@description = result.description
return true
else if event.which is 13 and (event.shiftKey is false and event.ctrlKey is false and event.metaKey is false)
if event.type is 'keydown'
if @current_highlighted_suggestion > -1
event.preventDefault()
@handle_keypress()
return true
previous_char = @get_previous_char()
if previous_char of @matching_opening_bracket
next_char = @get_next_char()
if @matching_opening_bracket[previous_char] is next_char
cursor = @codemirror.getCursor()
@insert_next '\n'
@codemirror.indentLine cursor.line+1, 'smart'
@codemirror.setCursor cursor
return false
else if (event.which is 9 and event.ctrlKey is false) or (event.type is 'keydown' and ((event.ctrlKey is true or event.metaKey is true) and event.which is 32) and (@$('.suggestion_description').css('display') is 'none' and @.$('.suggestion_name_list').css('display') is 'none'))
# If the user just hit tab, we are going to show the suggestions if they are hidden
# or if they suggestions are already shown, we are going to cycle through them.
#
# If the user just hit Ctrl/Cmd+space with suggestion/description being hidden we show the suggestions
# Note that the user cannot cycle through suggestions because we make sure in the IF condition that suggestion/description are hidden
# If the suggestions/description are visible, the event will be caught earlier with ESC
event.preventDefault()
if event.type isnt 'keydown'
return false
else
if @current_suggestions?.length > 0
if @$('.suggestion_name_list').css('display') is 'none'
@show_suggestion()
return true
else
# We can retrieve the content of codemirror only on keyup events. The users may write "r." then hit "d" then "tab" If the events are triggered this way
# keydown d - keydown tab - keyup d - keyup tab
# We want to only show the suggestions for r.d
if @written_suggestion is null
cached_query = @query_first_part+@current_element+@query_last_part
else
cached_query = @query_first_part+@written_suggestion+@query_last_part
if cached_query isnt @codemirror.getValue() # We fired a keydown tab before a keyup, so our suggestions are not up to date
@current_element = @codemirror.getValue().slice @query_first_part.length, @codemirror.getValue().length-@query_last_part.length
regex = @create_safe_regex @current_element
new_suggestions = []
new_highlighted_suggestion = -1
for suggestion, index in @current_suggestions
if index < @current_highlighted_suggestion
new_highlighted_suggestion = new_suggestions.length
if regex.test(suggestion) is true
new_suggestions.push suggestion
@current_suggestions = new_suggestions
@current_highlighted_suggestion = new_highlighted_suggestion
if @current_suggestions.length > 0
@$('.suggestion_name_list').empty()
for suggestion, i in @current_suggestions
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
@ignored_next_keyup = true
else
@hide_suggestion_and_description()
# Switch throught the suggestions
if event.shiftKey
@current_highlighted_suggestion--
if @current_highlighted_suggestion < -1
@current_highlighted_suggestion = @current_suggestions.length-1
else if @current_highlighted_suggestion < 0
@show_suggestion_without_moving()
@remove_highlight_suggestion()
@write_suggestion
suggestion_to_write: @current_element
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
return true
else
@current_highlighted_suggestion++
if @current_highlighted_suggestion >= @current_suggestions.length
@show_suggestion_without_moving()
@remove_highlight_suggestion()
@write_suggestion
suggestion_to_write: @current_element
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
@current_highlighted_suggestion = -1
return true
if @current_suggestions[@current_highlighted_suggestion]?
@show_suggestion_without_moving()
@highlight_suggestion @current_highlighted_suggestion # Highlight the current suggestion
@write_suggestion
suggestion_to_write: @current_suggestions[@current_highlighted_suggestion] # Auto complete with the highlighted suggestion
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
return true
else if @description?
if @$('.suggestion_description').css('display') is 'none'
# We show it once only because we don't want to move the cursor around
@show_description()
return true
if @extra_suggestions? and @extra_suggestions.length > 0 and @extra_suggestion.start_body is @extra_suggestion.start_body
# Trim suggestion
if @extra_suggestion?.body?[0]?.type is 'string'
if @extra_suggestion.body[0].complete is true
@extra_suggestions = []
else
# Remove quotes around the table/db name
current_name = @extra_suggestion.body[0].name.replace(/^\s*('|")/, '').replace(/('|")\s*$/, '')
regex = @create_safe_regex current_name
new_extra_suggestions = []
for suggestion in @extra_suggestions
if regex.test(suggestion) is true
new_extra_suggestions.push suggestion
@extra_suggestions = new_extra_suggestions
if @extra_suggestions.length > 0 # If there are still some valid suggestions
query = @codemirror.getValue()
# We did not parse what is after the cursor, so let's take a look
start_search = @extra_suggestion.start_body
if @extra_suggestion.body?[0]?.name.length?
start_search += @extra_suggestion.body[0].name.length
# Define @query_first_part and @query_last_part
# Note that ) is not a valid character for a db/table name
end_body = query.indexOf ')', start_search
@query_last_part = ''
if end_body isnt -1
@query_last_part = query.slice end_body
@query_first_part = query.slice 0, @extra_suggestion.start_body
lines = @query_first_part.split('\n')
if event.shiftKey is true
@current_highlighted_extra_suggestion--
else
@current_highlighted_extra_suggestion++
if @current_highlighted_extra_suggestion >= @extra_suggestions.length
@current_highlighted_extra_suggestion = -1
else if @current_highlighted_extra_suggestion < -1
@current_highlighted_extra_suggestion = @extra_suggestions.length-1
# Create the next suggestion
suggestion = ''
if @current_highlighted_extra_suggestion is -1
if @current_extra_suggestion?
if /^\s*'/.test(@current_extra_suggestion) is true
suggestion = @current_extra_suggestion+"'"
else if /^\s*"/.test(@current_extra_suggestion) is true
suggestion = @current_extra_suggestion+'"'
else
if dataexplorer_state.options.electric_punctuation is false
move_outside = true
if /^\s*'/.test(@current_extra_suggestion) is true
string_delimiter = "'"
else if /^\s*"/.test(@current_extra_suggestion) is true
string_delimiter = '"'
else
string_delimiter = "'"
move_outside = true
suggestion = string_delimiter+@extra_suggestions[@current_highlighted_extra_suggestion]+string_delimiter
@write_suggestion
move_outside: move_outside
suggestion_to_write: suggestion
@ignore_tab_keyup = true # If we are switching suggestion, we don't want to do anything else related to tab
# If the user hit enter and (Ctrl or Shift)
if event.which is 13 and (event.shiftKey or event.ctrlKey or event.metaKey)
@hide_suggestion_and_description()
event.preventDefault()
if event.type isnt 'keydown'
return true
@execute_query()
return true
# Ctrl/Cmd + V
else if (event.ctrlKey or event.metaKey) and event.which is 86 and event.type is 'keydown'
@last_action_is_paste = true
@num_released_keys = 0 # We want to know when the user release Ctrl AND V
if event.metaKey
@num_released_keys++ # Because on OS X, the keyup event is not fired when the metaKey is pressed (true for Firefox, Chrome, Safari at least...)
@hide_suggestion_and_description()
return true
# When the user release Ctrl/Cmd after a Ctrl/Cmd + V
else if event.type is 'keyup' and @last_action_is_paste is true and (event.which is 17 or event.which is 91)
@num_released_keys++
if @num_released_keys is 2
@last_action_is_paste = false
@hide_suggestion_and_description()
return true
# When the user release V after a Ctrl/Cmd + V
else if event.type is 'keyup' and @last_action_is_paste is true and event.which is 86
@num_released_keys++
if @num_released_keys is 2
@last_action_is_paste = false
@hide_suggestion_and_description()
return true
# Catching history navigation
else if event.type is 'keyup' and event.altKey and event.which is 38 # Key up
if @history_displayed_id < dataexplorer_state.history.length
@history_displayed_id++
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if event.type is 'keyup' and event.altKey and event.which is 40 # Key down
if @history_displayed_id > 1
@history_displayed_id--
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if @history_displayed_id is 1
@history_displayed_id--
@codemirror.setValue @draft
@codemirror.setCursor @codemirror.lineCount(), 0 # We hit the draft and put the cursor at the end
else if event.type is 'keyup' and event.altKey and event.which is 33 # Page up
@history_displayed_id = dataexplorer_state.history.length
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
event.preventDefault()
return true
else if event.type is 'keyup' and event.altKey and event.which is 34 # Page down
@history_displayed_id = @history.length
@codemirror.setValue dataexplorer_state.history[dataexplorer_state.history.length-@history_displayed_id].query
@codemirror.setCursor @codemirror.lineCount(), 0 # We hit the draft and put the cursor at the end
event.preventDefault()
return true
# If there is a hilighted suggestion, we want to catch enter
if @$('.suggestion_name_li_hl').length > 0
if event?.which is 13
event.preventDefault()
@handle_keypress()
return true
# We are scrolling in history
if @history_displayed_id isnt 0 and event?
# We catch ctrl, shift, alt and command
if event.ctrlKey or event.shiftKey or event.altKey or event.which is 16 or event.which is 17 or event.which is 18 or event.which is 20 or (event.which is 91 and event.type isnt 'keypress') or event.which is 92 or event.type of @mouse_type_event
return false
# We catch ctrl, shift, alt and command but don't look for active key (active key here refer to ctrl, shift, alt being pressed and hold)
if event? and (event.which is 16 or event.which is 17 or event.which is 18 or event.which is 20 or (event.which is 91 and event.type isnt 'keypress') or event.which is 92)
return false
# Avoid arrows+home+end+page down+pageup
# if event? and (event.which is 24 or event.which is ..)
# 0 is for firefox...
if not event? or (event.which isnt 37 and event.which isnt 38 and event.which isnt 39 and event.which isnt 40 and event.which isnt 33 and event.which isnt 34 and event.which isnt 35 and event.which isnt 36 and event.which isnt 0)
@history_displayed_id = 0
@draft = @codemirror.getValue()
# The expensive operations are coming. If the query is too long, we just don't parse the query
if @codemirror.getValue().length > @max_size_query
# Return true or false will break the event propagation
return undefined
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
query_after_cursor = @codemirror.getRange @codemirror.getCursor(), {line:@codemirror.lineCount()+1, ch: 0}
# Compute the structure of the query written by the user.
# We compute it earlier than before because @pair_char also listen on keydown and needs stack
stack = @extract_data_from_query
size_stack: 0
query: query_before_cursor
position: 0
if stack is null # Stack is null if the query was too big for us to parse
@ignore_tab_keyup = false
@hide_suggestion_and_description()
return false
if dataexplorer_state.options.electric_punctuation is true
@pair_char(event, stack) # Pair brackets/quotes
# We just look at key up so we don't fire the call 3 times
if event?.type? and event.type isnt 'keyup' and event.which isnt 9 and event.type isnt 'mouseup'
return false
if event?.which is 16 # We don't do anything with Shift.
return false
# Tab is an exception, we let it pass (tab bring back suggestions) - What we want is to catch keydown
if @ignore_tab_keyup is true and event?.which is 9
if event.type is 'keyup'
@ignore_tab_keyup = false
return true
@current_highlighted_suggestion = -1
@current_highlighted_extra_suggestion = -1
@$('.suggestion_name_list').empty()
# Valid step, let's save the data
@query_last_part = query_after_cursor
# If a selection is active, we just catch shift+enter
if @codemirror.getSelection() isnt ''
@hide_suggestion_and_description()
if event? and event.which is 13 and (event.shiftKey or event.ctrlKey or event.metaKey) # If the user hit enter and (Ctrl or Shift or Cmd)
@hide_suggestion_and_description()
if event.type isnt 'keydown'
return true
@execute_query()
return true # We do not replace the selection with a new line
# If the user select something and end somehwere with suggestion
if event?.type isnt 'mouseup'
return false
else
return true
@current_suggestions = []
@current_element = ''
@current_extra_suggestion = ''
@written_suggestion = null
@cursor_for_auto_completion = @codemirror.getCursor()
@description = null
result =
status: null
# create_suggestion is going to fill to_complete and to_describe
#to_complete: undefined
#to_describe: undefined
# If we are in the middle of a function (text after the cursor - that is not an element in @char_breakers or a comment), we just show a description, not a suggestion
result_non_white_char_after_cursor = @regex.get_first_non_white_char.exec(query_after_cursor)
if result_non_white_char_after_cursor isnt null and not(result_non_white_char_after_cursor[1]?[0] of @char_breakers or result_non_white_char_after_cursor[1]?.match(/^((\/\/)|(\/\*))/) isnt null)
result.status = 'break_and_look_for_description'
@hide_suggestion()
else
result_last_char_is_white = @regex.last_char_is_white.exec(query_before_cursor[query_before_cursor.length-1])
if result_last_char_is_white isnt null
result.status = 'break_and_look_for_description'
@hide_suggestion()
# Create the suggestion/description
@create_suggestion
stack: stack
query: query_before_cursor
result: result
result.suggestions = @uniq result.suggestions
@grouped_data = @count_group_level(stack).count_group > 0
if result.suggestions?.length > 0
show_suggestion = false
for suggestion, i in result.suggestions
if suggestion isnt 'ungroup(' or @grouped_data is true # We add the suggestion for `ungroup` only if we are in a group_stream/data (using the flag @grouped_data)
show_suggestion = true
@current_suggestions.push suggestion
@$('.suggestion_name_list').append @template_suggestion_name
id: i
suggestion: suggestion
if dataexplorer_state.options.suggestions is true and show_suggestion is true
@show_suggestion()
else
@hide_suggestion()
@hide_description()
else if result.description?
@hide_suggestion()
@description = result.description
if dataexplorer_state.options.suggestions is true and event?.type isnt 'mouseup'
@show_description()
else
@hide_description()
else
@hide_suggestion_and_description()
if event?.which is 9 # Catch tab
# If you're in a string, you add a TAB. If you're at the beginning of a newline with preceding whitespace, you add a TAB. If it's any other case do nothing.
if @last_element_type_if_incomplete(stack) isnt 'string' and @regex.white_or_empty.test(@codemirror.getLine(@codemirror.getCursor().line).slice(0, @codemirror.getCursor().ch)) isnt true
return true
else
return false
return true
# Similar to underscore's uniq but faster with a hashmap
uniq: (ar) ->
if not ar? or ar.length is 0
return ar
result = []
hash = {}
for element in ar
hash[element] = true
for key of hash
result.push key
result.sort()
return result
# Extract information from the current query
# Regex used
regex:
anonymous:/^(\s)*function\s*\(([a-zA-Z0-9,\s]*)\)(\s)*{/
loop:/^(\s)*(for|while)(\s)*\(([^\)]*)\)(\s)*{/
method: /^(\s)*([a-zA-Z0-9]*)\(/ # forEach( merge( filter(
row: /^(\s)*row\(/
method_var: /^(\s)*(\d*[a-zA-Z][a-zA-Z0-9]*)\./ # r. r.row. (r.count will be caught later)
return : /^(\s)*return(\s)*/
object: /^(\s)*{(\s)*/
array: /^(\s)*\[(\s)*/
white: /^(\s)+$/
white_or_empty: /^(\s)*$/
white_replace: /\s/g
white_start: /^(\s)+/
comma: /^(\s)*,(\s)*/
semicolon: /^(\s)*;(\s)*/
number: /^[0-9]+\.?[0-9]*/
inline_comment: /^(\s)*\/\/.*(\n|$)/
multiple_line_comment: /^(\s)*\/\*[^(\*\/)]*\*\//
get_first_non_white_char: /\s*(\S+)/
last_char_is_white: /.*(\s+)$/
stop_char: # Just for performance (we look for a stop_char in constant time - which is better than having 3 and conditions) and cleaner code
opening:
'(': ')'
'{': '}'
'[': ']'
closing:
')': '(' # Match the opening character
'}': '{'
']': '['
# Return the type of the last incomplete object or an empty string
last_element_type_if_incomplete: (stack) =>
if (not stack?) or stack.length is 0
return ''
element = stack[stack.length-1]
if element.body?
return @last_element_type_if_incomplete(element.body)
else
if element.complete is false
return element.type
else
return ''
# Get the last key if the last element is a key of an object
get_last_key: (stack) =>
if (not stack?) or stack.length is 0
return ''
element = stack[stack.length-1]
if element.body?
return @get_last_key(element.body)
else
if element.complete is false and element.key?
return element.key
else
return ''
# We build a stack of the query.
# Chained functions are in the same array, arguments/inner queries are in a nested array
# element.type in ['string', 'function', 'var', 'separator', 'anonymous_function', 'object', 'array_entry', 'object_key' 'array']
extract_data_from_query: (args) =>
size_stack = args.size_stack
query = args.query
context = if args.context? then util.deep_copy(args.context) else {}
position = args.position
stack = []
element =
type: null
context: context
complete: false
start = 0
is_parsing_string = false
to_skip = 0
for char, i in query
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\' # We were in a string. If we see string_delimiter and that the previous character isn't a backslash, we just reached the end of the string.
is_parsing_string = false # Else we just keep parsing the string
if element.type is 'string'
element.name = query.slice start, i+1
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+1
else # if element.is_parsing_string is false
if char is '\'' or char is '"' # So we get a string here
is_parsing_string = true
string_delimiter = char
if element.type is null
element.type = 'string'
start = i
continue
if element.type is null
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
start += result_inline_comment[0].length
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
start += result_multiple_line_comment[0].length
continue
if start is i
result_white = @regex.white_start.exec query.slice i
if result_white?
to_skip = result_white[0].length-1
start += result_white[0].length
continue
# Check for anonymous function
result_regex = @regex.anonymous.exec query.slice i
if result_regex isnt null
element.type = 'anonymous_function'
list_args = result_regex[2]?.split(',')
element.args = []
new_context = util.deep_copy context
for arg in list_args
arg = arg.replace(/(^\s*)|(\s*$)/gi,"") # Removing leading/trailing spaces
new_context[arg] = true
element.args.push arg
element.context = new_context
to_skip = result_regex[0].length
body_start = i+result_regex[0].length
stack_stop_char = ['{']
continue
# Check for a for loop
result_regex = @regex.loop.exec query.slice i
if result_regex isnt null
element.type = 'loop'
element.context = context
to_skip = result_regex[0].length
body_start = i+result_regex[0].length
stack_stop_char = ['{']
continue
# Check for return
result_regex = @regex.return.exec query.slice i
if result_regex isnt null
# I'm not sure we need to keep track of return, but let's keep it for now
element.type = 'return'
element.complete = true
to_skip = result_regex[0].length-1
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length
continue
# Check for object
result_regex = @regex.object.exec query.slice i
if result_regex isnt null
element.type = 'object'
element.next_key = null
element.body = [] # We need to keep tracker of the order of pairs
element.current_key_start = i+result_regex[0].length
to_skip = result_regex[0].length-1
stack_stop_char = ['{']
continue
# Check for array
result_regex = @regex.array.exec query.slice i
if result_regex isnt null
element.type = 'array'
element.next_key = null
element.body = []
entry_start = i+result_regex[0].length
to_skip = result_regex[0].length-1
stack_stop_char = ['[']
continue
if char is '.'
new_start = i+1
else
new_start = i
# Check for a standard method
result_regex = @regex.method.exec query.slice new_start
if result_regex isnt null
result_regex_row = @regex.row.exec query.slice new_start
if result_regex_row isnt null
position_opening_parenthesis = result_regex_row[0].indexOf('(')
element.type = 'function' # TODO replace with function
element.name = 'row'
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: 'function'
name: '('
position: position+3+1
context: context
complete: 'false'
stack_stop_char = ['(']
start += position_opening_parenthesis
to_skip = result_regex[0].length-1+new_start-i
continue
else
if stack[stack.length-1]?.type is 'function' or stack[stack.length-1]?.type is 'var' # We want the query to start with r. or arg.
element.type = 'function'
element.name = result_regex[0]
element.position = position+new_start
start += new_start-i
to_skip = result_regex[0].length-1+new_start-i
stack_stop_char = ['(']
continue
else
position_opening_parenthesis = result_regex[0].indexOf('(')
if position_opening_parenthesis isnt -1 and result_regex[0].slice(0, position_opening_parenthesis) of context
# Save the var
element.real_type = @types.value
element.type = 'var'
element.name = result_regex[0].slice(0, position_opening_parenthesis)
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: 'function'
name: '('
position: position+position_opening_parenthesis+1
context: context
complete: 'false'
stack_stop_char = ['(']
start = position_opening_parenthesis
to_skip = result_regex[0].length-1
continue
###
# This last condition is a special case for r(expr)
else if position_opening_parenthesis isnt -1 and result_regex[0].slice(0, position_opening_parenthesis) is 'r'
element.type = 'var'
element.name = 'r'
element.real_type = @types.value
element.position = position+new_start
start += new_start-i
to_skip = result_regex[0].length-1+new_start-i
stack_stop_char = ['(']
continue
###
# Check for method without parenthesis r., r.row., doc.
result_regex = @regex.method_var.exec query.slice new_start
if result_regex isnt null
if result_regex[0].slice(0, result_regex[0].length-1) of context
element.type = 'var'
element.real_type = @types.value
else
element.type = 'function'
element.position = position+new_start
element.name = result_regex[0].slice(0, result_regex[0].length-1).replace(/\s/, '')
element.complete = true
to_skip = element.name.length-1+new_start-i
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = new_start+to_skip+1
start -= new_start-i
continue
# Look for a comma
result_regex = @regex.comma.exec query.slice i
if result_regex isnt null
# element should have been pushed in stack. If not, the query is malformed
element.complete = true
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1+1
to_skip = result_regex[0].length-1
continue
# Look for a semi colon
result_regex = @regex.semicolon.exec query.slice i
if result_regex isnt null
# element should have been pushed in stack. If not, the query is malformed
element.complete = true
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1+1
to_skip = result_regex[0].length-1
continue
#else # if element.start isnt i
# We caught the white spaces, so there is nothing to do here
else
if char is ';'
# We just encountered a semi colon. We have an unknown element
# So We just got a random javascript statement, let's just ignore it
start = i+1
else # element.type isnt null
# Catch separator like for groupedMapReduce
result_regex = @regex.comma.exec(query.slice(i))
if result_regex isnt null and stack_stop_char.length < 1
# element should have been pushed in stack. If not, the query is malformed
stack.push
type: 'separator'
complete: true
name: query.slice i, result_regex[0].length
position: position+i
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
complete: false
start = i+result_regex[0].length-1
to_skip = result_regex[0].length-1
continue
# Catch for anonymous function
else if element.type is 'anonymous_function'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start, i
context: element.context
position: position+body_start
if element.body is null
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
#else the written query is broken here. The user forgot to close something?
#TODO Default behavior? Wait for Brackets/Ace to see how we handle errors
else if element.type is 'loop'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start, i
context: element.context
position: position+body_start
if element.body
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
# Catch for function
else if element.type is 'function'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice start+element.name.length, i
context: element.context
position: position+start+element.name.length
if element.body is null
return null
element.complete = true
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
# Catch for object
else if element.type is 'object'
# Since we are sure that we are not in a string, we can just look for colon and comma
# Still, we need to check the stack_stop_char since we can have { key: { inner: 'test, 'other_inner'}, other_key: 'other_value'}
keys_values = []
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
# We just reach a }, it's the end of the object
if element.next_key?
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start, i
context: element.context
position: position+element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
complete: false
body: body
element.body[element.body.length-1] = new_element
element.next_key = null # No more next_key
element.complete = true
# if not element.next_key?
# The next key is not defined, this is a broken query.
# TODO show error once brackets/ace will be used
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
element =
type: null
context: context
start = i+1
continue
if not element.next_key?
if stack_stop_char.length is 1 and char is ':'
new_element =
type: 'object_key'
key: query.slice element.current_key_start, i
key_complete: true
if element.body.length is 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
else
element.body[element.body.length-1] = new_element
element.next_key = query.slice element.current_key_start, i
element.current_value_start = i+1
else
result_regex = @regex.comma.exec query.slice i
if stack_stop_char.length is 1 and result_regex isnt null #We reached the end of a value
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start, i
context: element.context
position: element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
body: body
element.body[element.body.length-1] = new_element
to_skip = result_regex[0].length-1
element.next_key = null
element.current_key_start = i+result_regex[0].length
# Catch for array
else if element.type is 'array'
if char of @stop_char.opening
stack_stop_char.push char
else if char of @stop_char.closing
if stack_stop_char[stack_stop_char.length-1] is @stop_char.closing[char]
stack_stop_char.pop()
if stack_stop_char.length is 0
# We just reach a ], it's the end of the object
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start, i
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: true
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
continue
if stack_stop_char.length is 1 and char is ','
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start, i
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: true
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
entry_start = i+1
# We just reached the end, let's try to find the type of the incomplete element
if element.type isnt null
element.complete = false
if element.type is 'function'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice start+element.name.length
context: element.context
position: position+start+element.name.length
if element.body is null
return null
else if element.type is 'anonymous_function'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start
context: element.context
position: position+body_start
if element.body is null
return null
else if element.type is 'loop'
element.body = @extract_data_from_query
size_stack: size_stack
query: query.slice body_start
context: element.context
position: position+body_start
if element.body is null
return null
else if element.type is 'string'
element.name = query.slice start
else if element.type is 'object'
if not element.next_key? # Key not defined yet
new_element =
type: 'object_key'
key: query.slice element.current_key_start
key_complete: false
complete: false
element.body.push new_element # They key was not defined, so we add a new element
size_stack++
if size_stack > @max_size_stack
return null
element.next_key = query.slice element.current_key_start
else
body = @extract_data_from_query
size_stack: size_stack
query: query.slice element.current_value_start
context: element.context
position: position+element.current_value_start
if body is null
return null
new_element =
type: 'object_key'
key: element.next_key
key_complete: true
complete: false
body: body
element.body[element.body.length-1] = new_element
element.next_key = null # No more next_key
else if element.type is 'array'
body = @extract_data_from_query
size_stack: size_stack
query: query.slice entry_start
context: element.context
position: position+entry_start
if body is null
return null
new_element =
type: 'array_entry'
complete: false
body: body
if new_element.body.length > 0
element.body.push new_element
size_stack++
if size_stack > @max_size_stack
return null
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
else if start isnt i
if query.slice(start) of element.context
element.name = query.slice start
element.type = 'var'
element.real_type = @types.value
element.complete = true
else if @regex.number.test(query.slice(start)) is true
element.type = 'number'
element.name = query.slice start
element.complete = true
else if query[start] is '.'
element.type = 'function'
element.position = position+start
element.name = query.slice start+1
element.complete = false
else
element.name = query.slice start
element.position = position+start
element.complete = false
stack.push element
size_stack++
if size_stack > @max_size_stack
return null
return stack
# Count the number of `group` commands minus `ungroup` commands in the current level
# We count per level because we don't want to report a positive number of group for nested queries, e.g:
# r.table("foo").group("bar").map(function(doc) { doc.merge(
#
# We return an object with two fields
# - count_group: number of `group` commands minus the number of `ungroup` commands
# - parse_level: should we keep parsing the same level
count_group_level: (stack) =>
count_group = 0
if stack.length > 0
# Flag for whether or not we should keep looking for group/ungroup
# we want the warning to appear only at the same level
parse_level = true
element = stack[stack.length-1]
if element.body? and element.body.length > 0 and element.complete is false
parse_body = @count_group_level element.body
count_group += parse_body.count_group
parse_level = parse_body.parse_level
if element.body[0].type is 'return'
parse_level = false
if element.body[element.body.length-1].type is 'function'
parse_level = false
if parse_level is true
for i in [stack.length-1..0] by -1
if stack[i].type is 'function' and stack[i].name is 'ungroup('
count_group -= 1
else if stack[i].type is 'function' and stack[i].name is 'group('
count_group += 1
count_group: count_group
parse_level: parse_level
# Decide if we have to show a suggestion or a description
# Mainly use the stack created by extract_data_from_query
create_suggestion: (args) =>
stack = args.stack
query = args.query
result = args.result
# No stack, ie an empty query
if result.status is null and stack.length is 0
result.suggestions = []
result.status = 'done'
@query_first_part = ''
if @suggestions['']? # The docs may not have loaded
for suggestion in @suggestions['']
result.suggestions.push suggestion
for i in [stack.length-1..0] by -1
element = stack[i]
if element.body? and element.body.length > 0 and element.complete is false
@create_suggestion
stack: element.body
query: args?.query
result: args.result
if result.status is 'done'
continue
if result.status is null
# Top of the stack
if element.complete is true
if element.type is 'function'
if element.complete is true or element.name is ''
result.suggestions = null
result.status = 'look_for_description'
break
else
result.suggestions = null
result.description = element.name
#Define the current argument we have. It's the suggestion whose index is -1
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.status = 'done'
else if element.type is 'anonymous_function' or element.type is 'separator' or element.type is 'object' or element.type is 'object_key' or element.type is 'return' or 'element.type' is 'array'
# element.type === 'object' is impossible I think with the current implementation of extract_data_from_query
result.suggestions = null
result.status = 'look_for_description'
break # We want to look in the upper levels
#else type cannot be null (because not complete)
else # if element.complete is false
if element.type is 'function'
if element.body? # It means that element.body.length === 0
# We just opened a new function, so let's just show the description
result.suggestions = null
result.description = element.name # That means we are going to describe the function named element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.status = 'done'
break
else
# function not complete, need suggestion
result.suggestions = []
result.suggestions_regex = @create_safe_regex element.name # That means we are going to give all the suggestions that match element.name and that are in the good group (not yet defined)
result.description = null
@query_first_part = query.slice 0, element.position+1
@current_element = element.name
@cursor_for_auto_completion.ch -= element.name.length
@current_query
if i isnt 0
result.status = 'look_for_state'
else
result.state = ''
else if element.type is 'anonymous_function' or element.type is 'object_key' or element.type is 'string' or element.type is 'separator' or element.type is 'array'
result.suggestions = null
result.status = 'look_for_description'
break
#else if element.type is 'object' # Not possible
#else if element.type is 'var' # Not possible because we require a . or ( to asssess that it's a var
else if element.type is null
result.suggestions = []
result.status = 'look_for_description'
break
else if result.status is 'look_for_description'
if element.type is 'function'
result.description = element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.suggestions = null
result.status = 'done'
else
break
if result.status is 'break_and_look_for_description'
if element.type is 'function' and element.complete is false and element.name.indexOf('(') isnt -1
result.description = element.name
@extra_suggestion =
start_body: element.position + element.name.length
body: element.body
if element.body?[0]?.name?.length?
@cursor_for_auto_completion.ch -= element.body[0].name.length
@current_extra_suggestion = element.body[0].name
result.suggestions = null
result.status = 'done'
else
if element.type isnt 'function'
break
else
result.status = 'look_for_description'
break
else if result.status is 'look_for_state'
if element.type is 'function' and element.complete is true
result.state = element.name
if @map_state[element.name]?
for state in @map_state[element.name]
if @suggestions[state]?
for suggestion in @suggestions[state]
if result.suggestions_regex.test(suggestion) is true
result.suggestions.push suggestion
#else # This is a non valid ReQL function.
# It may be a personalized function defined in the data explorer...
result.status = 'done'
else if element.type is 'var' and element.complete is true
result.state = element.real_type
for type in result.state
if @suggestions[type]?
for suggestion in @suggestions[type]
if result.suggestions_regex.test(suggestion) is true
result.suggestions.push suggestion
result.status = 'done'
#else # Is that possible? A function can only be preceded by a function (except for r)
# Create regex based on the user input. We make it safe
create_safe_regex: (str) =>
for char in @unsafe_to_safe_regexstr
str = str.replace char[0], char[1]
return new RegExp('^('+str+')', 'i')
# Show suggestion and determine where to put the box
show_suggestion: =>
@move_suggestion()
margin = (parseInt(@$('.CodeMirror-cursor').css('top').replace('px', ''))+@line_height)+'px'
@$('.suggestion_full_container').css 'margin-top', margin
@$('.arrow').css 'margin-top', margin
@$('.suggestion_name_list').show()
@$('.arrow').show()
# If want to show suggestion without moving the arrow
show_suggestion_without_moving: =>
@$('.arrow').show()
@$('.suggestion_name_list').show()
# Show description and determine where to put it
show_description: =>
if @descriptions[@description]? # Just for safety
margin = (parseInt(@$('.CodeMirror-cursor').css('top').replace('px', ''))+@line_height)+'px'
@$('.suggestion_full_container').css 'margin-top', margin
@$('.arrow').css 'margin-top', margin
@$('.suggestion_description').html @description_template @extend_description @description
@$('.suggestion_description').show()
@move_suggestion()
@show_or_hide_arrow()
else
@hide_description()
hide_suggestion: =>
@$('.suggestion_name_list').hide()
@show_or_hide_arrow()
hide_description: =>
@$('.suggestion_description').hide()
@show_or_hide_arrow()
hide_suggestion_and_description: =>
@hide_suggestion()
@hide_description()
# Show the arrow if suggestion or/and description is being displayed
show_or_hide_arrow: =>
if @$('.suggestion_name_list').css('display') is 'none' and @$('.suggestion_description').css('display') is 'none'
@$('.arrow').hide()
else
@$('.arrow').show()
# Move the suggestion. We have steps of 200 pixels and try not to overlaps button if we can. If we cannot, we just hide them all since their total width is less than 200 pixels
move_suggestion: =>
margin_left = parseInt(@$('.CodeMirror-cursor').css('left').replace('px', ''))+23
@$('.arrow').css 'margin-left', margin_left
if margin_left < 200
@$('.suggestion_full_container').css 'left', '0px'
else
max_margin = @$('.CodeMirror-scroll').width()-418
margin_left_bloc = Math.min max_margin, Math.floor(margin_left/200)*200
if margin_left > max_margin+418-150-23 # We are really at the end
@$('.suggestion_full_container').css 'left', (max_margin-34)+'px'
else if margin_left_bloc > max_margin-150-23
@$('.suggestion_full_container').css 'left', (max_margin-34-150)+'px'
else
@$('.suggestion_full_container').css 'left', (margin_left_bloc-100)+'px'
#Highlight suggestion. Method called when the user hit tab or mouseover
highlight_suggestion: (id) =>
@remove_highlight_suggestion()
@$('.suggestion_name_li').eq(id).addClass 'suggestion_name_li_hl'
@$('.suggestion_description').html @description_template @extend_description @current_suggestions[id]
@$('.suggestion_description').show()
remove_highlight_suggestion: =>
@$('.suggestion_name_li').removeClass 'suggestion_name_li_hl'
# Write the suggestion in the code mirror
write_suggestion: (args) =>
suggestion_to_write = args.suggestion_to_write
move_outside = args.move_outside is true # So default value is false
ch = @cursor_for_auto_completion.ch+suggestion_to_write.length
if dataexplorer_state.options.electric_punctuation is true
if suggestion_to_write[suggestion_to_write.length-1] is '(' and @count_not_closed_brackets('(') >= 0
@codemirror.setValue @query_first_part+suggestion_to_write+')'+@query_last_part
@written_suggestion = suggestion_to_write+')'
else
@codemirror.setValue @query_first_part+suggestion_to_write+@query_last_part
@written_suggestion = suggestion_to_write
if (move_outside is false) and (suggestion_to_write[suggestion_to_write.length-1] is '"' or suggestion_to_write[suggestion_to_write.length-1] is "'")
ch--
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
@codemirror.setCursor
line: @cursor_for_auto_completion.line
ch:ch
else
@codemirror.setValue @query_first_part+suggestion_to_write+@query_last_part
@written_suggestion = suggestion_to_write
if (move_outside is false) and (suggestion_to_write[suggestion_to_write.length-1] is '"' or suggestion_to_write[suggestion_to_write.length-1] is "'")
ch--
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
@codemirror.setCursor
line: @cursor_for_auto_completion.line
ch:ch
# Select the suggestion. Called by mousdown .suggestion_name_li
select_suggestion: (event) =>
suggestion_to_write = @$(event.target).html()
@write_suggestion
suggestion_to_write: suggestion_to_write
# Give back focus to code mirror
@hide_suggestion()
# Put back in the stack
setTimeout =>
@handle_keypress() # That's going to describe the function the user just selected
@codemirror.focus() # Useful if the user used the mouse to select a suggestion
, 0 # Useful if the user used the mouse to select a suggestion
# Highlight a suggestion in case of a mouseover
mouseover_suggestion: (event) =>
@highlight_suggestion event.target.dataset.id
# Hide suggestion in case of a mouse out
mouseout_suggestion: (event) =>
@hide_description()
# Extend description for .db() and .table() with dbs/tables names
extend_description: (fn) =>
if fn is 'db(' or fn is 'dbDrop('
description = _.extend {}, @descriptions[fn]()
if _.keys(@databases_available).length is 0
data =
no_database: true
else
databases_available = _.keys @databases_available
data =
no_database: false
databases_available: databases_available
description.description = @databases_suggestions_template(data)+description.description
@extra_suggestions= databases_available # @extra_suggestions store the suggestions for arguments. So far they are just for db(), dbDrop(), table(), tableDrop()
else if fn is 'table(' or fn is 'tableDrop('
# Look for the argument of the previous db()
database_used = @extract_database_used()
description = _.extend {}, @descriptions[fn]()
if database_used.error is false
data =
tables_available: @databases_available[database_used.name]
no_table: @databases_available[database_used.name].length is 0
if database_used.name?
data.database_name = database_used.name
else
data =
error: database_used.error
description.description = @tables_suggestions_template(data) + description.description
@extra_suggestions = @databases_available[database_used.name]
else
description = @descriptions[fn] @grouped_data
@extra_suggestions= null
return description
# We could create a new stack with @extract_data_from_query, but that would be a more expensive for not that much
# We can not use the previous stack too since autocompletion doesn't validate the query until you hit enter (or another key than tab)
extract_database_used: =>
query_before_cursor = @codemirror.getRange {line: 0, ch: 0}, @codemirror.getCursor()
# We cannot have ".db(" in a db name
last_db_position = query_before_cursor.lastIndexOf('.db(')
if last_db_position is -1
found = false
if @databases_available['test']?
return {
db_found: true
error: false
name: 'test'
}
else
return {
db_found: false
error: true
}
else
arg = query_before_cursor.slice last_db_position+5 # +4 for .db(
char = query_before_cursor.slice last_db_position+4, last_db_position+5 # ' or " used for the argument of db()
end_arg_position = arg.indexOf char # Check for the next quote or apostrophe
if end_arg_position is -1
return {
db_found: false
error: true
}
db_name = arg.slice 0, end_arg_position
if @databases_available[db_name]?
return {
db_found: true
error: false
name: db_name
}
else
return {
db_found: false
error: true
}
abort_query: =>
@disable_toggle_executing = false
@toggle_executing false
dataexplorer_state.query_result?.force_end_gracefully()
@driver_handler.close_connection()
# Function that execute the queries in a synchronous way.
execute_query: =>
# We don't let people execute more than one query at a time on the same connection
# While we remove the button run, `execute_query` could still be called with Shift+Enter
if @executing is true
@abort_query
# Hide the option, if already hidden, nothing happens.
@$('.profiler_enabled').slideUp 'fast'
# The user just executed a query, so we reset cursor_timed_out to false
dataexplorer_state.cursor_timed_out = false
dataexplorer_state.query_has_changed = false
@raw_query = @codemirror.getSelection() or @codemirror.getValue()
@query = @clean_query @raw_query # Save it because we'll use it in @callback_multilples_queries
# Execute the query
try
dataexplorer_state.query_result?.discard()
# Separate queries
@non_rethinkdb_query = '' # Store the statements that don't return a rethinkdb query (like "var a = 1;")
@index = 0 # index of the query currently being executed
@raw_queries = @separate_queries @raw_query # We first split raw_queries
@queries = @separate_queries @query
if @queries.length is 0
error = @query_error_template
no_query: true
@results_view_wrapper.render_error(null, error, true)
else
@execute_portion()
catch err
# Missing brackets, so we display everything (we don't know if we properly splitted the query)
@results_view_wrapper.render_error(@query, err, true)
@save_query
query: @raw_query
broken_query: true
toggle_executing: (executing) =>
if executing == @executing
if executing and dataexplorer_state.query_result?.is_feed
@$('.loading_query_img').hide()
return
if @disable_toggle_executing
return
@executing = executing
if @timeout_toggle_abort?
clearTimeout @timeout_toggle_abort
if executing
@timeout_toggle_abort = setTimeout =>
@timeout_toggle_abort = null
if not dataexplorer_state.query_result?.is_feed
@$('.loading_query_img').show()
@$('.execute_query').hide()
@$('.abort_query').show()
, @delay_toggle_abort
else
@timeout_toggle_abort = setTimeout =>
@timeout_toggle_abort = null
@$('.loading_query_img').hide()
@$('.execute_query').show()
@$('.abort_query').hide()
, @delay_toggle_abort
# A portion is one query of the whole input.
execute_portion: =>
dataexplorer_state.query_result = null
while @queries[@index]?
full_query = @non_rethinkdb_query
full_query += @queries[@index]
try
rdb_query = @evaluate(full_query)
catch err
if @queries.length > 1
@results_view_wrapper.render_error(@raw_queries[@index], err, true)
else
@results_view_wrapper.render_error(null, err, true)
@save_query
query: @raw_query
broken_query: true
return false
@index++
if rdb_query instanceof @TermBaseConstructor
final_query = @index is @queries.length
@start_time = new Date()
if final_query
query_result = new QueryResult
has_profile: dataexplorer_state.options.profiler
current_query: @raw_query
raw_query: @raw_queries[@index]
driver_handler: @driver_handler
events:
error: (query_result, err) =>
@results_view_wrapper.render_error(@query, err)
ready: (query_result) =>
dataexplorer_state.pause_at = null
if query_result.is_feed
@toggle_executing true
@disable_toggle_executing = true
for event in ['end', 'discard', 'error']
query_result.on event, () =>
@disable_toggle_executing = false
@toggle_executing false
dataexplorer_state.query_result = query_result
@results_view_wrapper.set_query_result
query_result: dataexplorer_state.query_result
@disable_toggle_executing = false
@driver_handler.run_with_new_connection rdb_query,
optargs:
binaryFormat: "raw"
timeFormat: "raw"
profile: dataexplorer_state.options.profiler
connection_error: (error) =>
@save_query
query: @raw_query
broken_query: true
@error_on_connect error
callback: (error, result) =>
if final_query
@save_query
query: @raw_query
broken_query: false
query_result.set error, result
else if error
@save_query
query: @raw_query
broken_query: true
@results_view_wrapper.render_error(@query, err)
else
@execute_portion()
return true
else
@non_rethinkdb_query += @queries[@index-1]
if @index is @queries.length
error = @query_error_template
last_non_query: true
@results_view_wrapper.render_error(@raw_queries[@index-1], error, true)
@save_query
query: @raw_query
broken_query: true
# Evaluate the query
# We cannot force eval to a local scope, but "use strict" will declare variables in the scope at least
evaluate: (query) =>
"use strict"
return eval(query)
# In a string \n becomes \\n, outside a string we just remove \n, so
# r
# .expr('hello
# world')
# becomes
# r.expr('hello\nworld')
# We also remove comments from the query
clean_query: (query) ->
is_parsing_string = false
start = 0
result_query = ''
for char, i in query
if to_skip > 0
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\'
result_query += query.slice(start, i+1).replace(/\n/g, '\\n')
start = i+1
is_parsing_string = false
continue
else # if element.is_parsing_string is false
if char is '\'' or char is '"'
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
to_skip = result_inline_comment[0].length-1
start += result_inline_comment[0].length
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
result_query += query.slice(start, i).replace(/\n/g, '')
start = i
to_skip = result_multiple_line_comment[0].length-1
start += result_multiple_line_comment[0].length
continue
if is_parsing_string
result_query += query.slice(start, i).replace(/\n/g, '\\\\n')
else
result_query += query.slice(start, i).replace(/\n/g, '')
return result_query
# Split input in queries. We use semi colon, pay attention to string, brackets and comments
separate_queries: (query) =>
queries = []
is_parsing_string = false
stack = []
start = 0
position =
char: 0
line: 1
for char, i in query
if char is '\n'
position.line++
position.char = 0
else
position.char++
if to_skip > 0 # Because we cannot mess with the iterator in coffee-script
to_skip--
continue
if is_parsing_string is true
if char is string_delimiter and query[i-1]? and query[i-1] isnt '\\'
is_parsing_string = false
continue
else # if element.is_parsing_string is false
if char is '\'' or char is '"'
is_parsing_string = true
string_delimiter = char
continue
result_inline_comment = @regex.inline_comment.exec query.slice i
if result_inline_comment?
to_skip = result_inline_comment[0].length-1
continue
result_multiple_line_comment = @regex.multiple_line_comment.exec query.slice i
if result_multiple_line_comment?
to_skip = result_multiple_line_comment[0].length-1
continue
if char of @stop_char.opening
stack.push char
else if char of @stop_char.closing
if stack[stack.length-1] isnt @stop_char.closing[char]
throw @query_error_template
syntax_error: true
bracket: char
line: position.line
position: position.char
else
stack.pop()
else if char is ';' and stack.length is 0
queries.push query.slice start, i+1
start = i+1
if start < query.length-1
last_query = query.slice start
if @regex.white.test(last_query) is false
queries.push last_query
return queries
# Clear the input
clear_query: =>
@codemirror.setValue ''
@codemirror.focus()
# Called if there is any on the connection
error_on_connect: (error) =>
if /^(Unexpected token)/.test(error.message)
# Unexpected token, the server couldn't parse the message
# The truth is we don't know which query failed (unexpected token), but it seems safe to suppose in 99% that the last one failed.
@results_view_wrapper.render_error(null, error)
# We save the query since the callback will never be called.
@save_query
query: @raw_query
broken_query: true
else
@results_view_wrapper.cursor_timed_out()
# We fail to connect, so we display a message except if we were already disconnected and we are not trying to manually reconnect
# So if the user fails to reconnect after a failure, the alert will still flash
@$('#user-alert-space').hide()
@$('#user-alert-space').html @alert_connection_fail_template({})
@$('#user-alert-space').slideDown 'fast'
handle_gutter_click: (editor, line) =>
start =
line: line
ch: 0
end =
line: line
ch: @codemirror.getLine(line).length
@codemirror.setSelection start, end
# Switch between full view and normal view
toggle_size: =>
if @displaying_full_view is true
@display_normal()
$(window).off 'resize', @display_full
@displaying_full_view = false
else
@display_full()
$(window).on 'resize', @display_full
@displaying_full_view = true
@results_view_wrapper.set_scrollbar()
display_normal: =>
$('#cluster').addClass 'container'
$('#cluster').removeClass 'cluster_with_margin'
@$('.wrapper_scrollbar').css 'width', '888px'
@$('.option_icon').removeClass 'fullscreen_exit'
@$('.option_icon').addClass 'fullscreen'
display_full: =>
$('#cluster').removeClass 'container'
$('#cluster').addClass 'cluster_with_margin'
@$('.wrapper_scrollbar').css 'width', ($(window).width()-92)+'px'
@$('.option_icon').removeClass 'fullscreen'
@$('.option_icon').addClass 'fullscreen_exit'
remove: =>
@results_view_wrapper.remove()
@history_view.remove()
@driver_handler.remove()
@display_normal()
$(window).off 'resize', @display_full
$(document).unbind 'mousemove', @handle_mousemove
$(document).unbind 'mouseup', @handle_mouseup
clearTimeout @timeout_driver_connect
driver.stop_timer @timer
# We do not destroy the cursor, because the user might come back and use it.
super()
# An abstract base class
class ResultView extends Backbone.View
tree_large_container_template: require('../handlebars/dataexplorer_large_result_json_tree_container.hbs')
tree_container_template: require('../handlebars/dataexplorer_result_json_tree_container.hbs')
events: ->
'click .jt_arrow': 'toggle_collapse'
'click .jta_arrow_h': 'expand_tree_in_table'
'mousedown': 'parent_pause_feed'
initialize: (args) =>
@_patched_already = false
@parent = args.parent
@query_result = args.query_result
@render()
@listenTo @query_result, 'end', =>
if not @query_result.is_feed
@render()
@fetch_batch_rows()
remove: =>
@removed_self = true
super()
max_datum_threshold: 1000
# Return whether there are too many datums
# If there are too many, we will disable syntax highlighting to avoid freezing the page
has_too_many_datums: (result) ->
if @has_too_many_datums_helper(result) > @max_datum_threshold
return true
return false
json_to_tree: (result) =>
# If the results are too large, we just display the raw indented JSON to avoid freezing the interface
if @has_too_many_datums(result)
return @tree_large_container_template
json_data: JSON.stringify(result, null, 4)
else
return @tree_container_template
tree: util.json_to_node(result)
# Return the number of datums if there are less than @max_datum_threshold
# Or return a number greater than @max_datum_threshold
has_too_many_datums_helper: (result) ->
if Object::toString.call(result) is '[object Object]'
count = 0
for key of result
count += @has_too_many_datums_helper result[key]
if count > @max_datum_threshold
return count
return count
else if Array.isArray(result)
count = 0
for element in result
count += @has_too_many_datums_helper element
if count > @max_datum_threshold
return count
return count
return 1
toggle_collapse: (event) =>
@$(event.target).nextAll('.jt_collapsible').toggleClass('jt_collapsed')
@$(event.target).nextAll('.jt_points').toggleClass('jt_points_collapsed')
@$(event.target).nextAll('.jt_b').toggleClass('jt_b_collapsed')
@$(event.target).toggleClass('jt_arrow_hidden')
@parent.set_scrollbar()
expand_tree_in_table: (event) =>
dom_element = @$(event.target).parent()
@$(event.target).remove()
data = dom_element.data('json_data')
result = @json_to_tree data
dom_element.html result
classname_to_change = dom_element.parent().attr('class').split(' ')[0]
$('.'+classname_to_change).css 'max-width', 'none'
classname_to_change = dom_element.parent().parent().attr('class')
$('.'+classname_to_change).css 'max-width', 'none'
dom_element.css 'max-width', 'none'
@parent.set_scrollbar()
parent_pause_feed: (event) =>
@parent.pause_feed()
pause_feed: =>
unless @parent.container.state.pause_at?
@parent.container.state.pause_at = @query_result.size()
unpause_feed: =>
if @parent.container.state.pause_at?
@parent.container.state.pause_at = null
@render()
current_batch: =>
switch @query_result.type
when 'value'
return @query_result.value
when 'cursor'
if @query_result.is_feed
pause_at = @parent.container.state.pause_at
if pause_at?
latest = @query_result.slice(Math.min(0, pause_at - @parent.container.state.options.query_limit), pause_at - 1)
else
latest = @query_result.slice(-@parent.container.state.options.query_limit)
latest.reverse()
return latest
else
return @query_result.slice(@query_result.position, @query_result.position + @parent.container.state.options.query_limit)
current_batch_size: =>
return @current_batch()?.length ? 0
setStackSize: =>
# In some versions of firefox, the effective recursion
# limit gets hit sometimes by the driver. Here we patch
# the driver's built in stackSize to 12 (normally it's
# 100). The driver will invoke callbacks with setImmediate
# vs directly invoking themif the stackSize limit is
# exceeded, which keeps the stack size manageable (but
# results in worse tracebacks).
if @_patched_already
return
iterableProto = @query_result.cursor?.__proto__?.__proto__?.constructor?.prototype
if iterableProto?.stackSize > 12
console.log "Patching stack limit on cursors to 12"
iterableProto.stackSize = 12
@_patched_already = true
# TODO: rate limit events to avoid freezing the browser when there are too many
fetch_batch_rows: =>
if @query_result.type is not 'cursor'
return
@setStackSize()
if @query_result.is_feed or @query_result.size() < @query_result.position + @parent.container.state.options.query_limit
@query_result.once 'add', (query_result, row) =>
if @removed_self
return
if @query_result.is_feed
if not @parent.container.state.pause_at?
if not @paused_at?
@query_result.drop_before(@query_result.size() - @parent.container.state.options.query_limit)
@add_row row
@parent.update_feed_metadata()
@fetch_batch_rows()
@query_result.fetch_next()
else
@parent.render()
@render()
show_next_batch: =>
@query_result.position += @parent.container.state.options.query_limit
@query_result.drop_before @parent.container.state.options.query_limit
@render()
@parent.render()
@fetch_batch_rows()
add_row: (row) =>
# TODO: Don't render the whole view on every change
@render()
class TreeView extends ResultView
className: 'results tree_view_container'
templates:
wrapper: require('../handlebars/dataexplorer_result_tree.hbs')
no_result: require('../handlebars/dataexplorer_result_empty.hbs')
render: =>
if @query_result.results?.length == 0
@$el.html @templates.wrapper tree: @templates.no_result
ended: @query_result.ended
at_beginning: @query_result.at_beginning()
return @
switch @query_result.type
when 'value'
@$el.html @templates.wrapper tree: @json_to_tree @query_result.value
when 'cursor'
@$el.html @templates.wrapper tree: []
tree_container = @$('.json_tree_container')
for row in @current_batch()
tree_container.append @json_to_tree row
return @
add_row: (row, noflash) =>
tree_container = @$('.json_tree_container')
node = $(@json_to_tree(row)).prependTo(tree_container)
if not noflash
node.addClass 'flash'
children = tree_container.children()
if children.length > @parent.container.state.options.query_limit
children.last().remove()
class TableView extends ResultView
className: 'results table_view_container'
templates:
wrapper: require('../handlebars/dataexplorer_result_table.hbs')
container: require('../handlebars/dataexplorer_result_json_table_container.hbs')
tr_attr: require('../handlebars/dataexplorer_result_json_table_tr_attr.hbs')
td_attr: require('../handlebars/dataexplorer_result_json_table_td_attr.hbs')
tr_value: require('../handlebars/dataexplorer_result_json_table_tr_value.hbs')
td_value: require('../handlebars/dataexplorer_result_json_table_td_value.hbs')
td_value_content: require('../handlebars/dataexplorer_result_json_table_td_value_content.hbs')
data_inline: require('../handlebars/dataexplorer_result_json_table_data_inline.hbs')
no_result: require('../handlebars/dataexplorer_result_empty.hbs')
default_size_column: 310 # max-width value of a cell of a table (as defined in the css file)
mouse_down: false
events: -> _.extend super(),
'mousedown .click_detector': 'handle_mousedown'
initialize: (args) =>
super args
@last_keys = @parent.container.state.last_keys # Arrays of the last keys displayed
@last_columns_size = @parent.container.state.last_columns_size # Size of the columns displayed. Undefined if a column has the default size
@listenTo @query_result, 'end', =>
if @current_batch_size() == 0
@render()
handle_mousedown: (event) =>
if event?.target?.className is 'click_detector'
@col_resizing = @$(event.target).parent().data('col')
@start_width = @$(event.target).parent().width()
@start_x = event.pageX
@mouse_down = true
$('body').toggleClass('resizing', true)
handle_mousemove: (event) =>
if @mouse_down
@parent.container.state.last_columns_size[@col_resizing] = Math.max 5, @start_width-@start_x+event.pageX # Save the personalized size
@resize_column @col_resizing, @parent.container.state.last_columns_size[@col_resizing] # Resize
resize_column: (col, size) =>
@$('.col-'+col).css 'max-width', size
@$('.value-'+col).css 'max-width', size-20
@$('.col-'+col).css 'width', size
@$('.value-'+col).css 'width', size-20
if size < 20
@$('.value-'+col).css 'padding-left', (size-5)+'px'
@$('.value-'+col).css 'visibility', 'hidden'
else
@$('.value-'+col).css 'padding-left', '15px'
@$('.value-'+col).css 'visibility', 'visible'
handle_mouseup: (event) =>
if @mouse_down is true
@mouse_down = false
$('body').toggleClass('resizing', false)
@parent.set_scrollbar()
###
keys =
primitive_value_count: <int>
object:
key_1: <keys>
key_2: <keys>
###
build_map_keys: (args) =>
keys_count = args.keys_count
result = args.result
if jQuery.isPlainObject(result)
if result.$reql_type$ is 'TIME'
keys_count.primitive_value_count++
else if result.$reql_type$ is 'BINARY'
keys_count.primitive_value_count++
else
for key, row of result
if not keys_count['object']?
keys_count['object'] = {} # That's define only if there are keys!
if not keys_count['object'][key]?
keys_count['object'][key] =
primitive_value_count: 0
@build_map_keys
keys_count: keys_count['object'][key]
result: row
else
keys_count.primitive_value_count++
# Compute occurrence of each key. The occurence can be a float since we compute the average occurence of all keys for an object
compute_occurrence: (keys_count) =>
if not keys_count['object']? # That means we are accessing only a primitive value
keys_count.occurrence = keys_count.primitive_value_count
else
count_key = if keys_count.primitive_value_count > 0 then 1 else 0
count_occurrence = keys_count.primitive_value_count
for key, row of keys_count['object']
count_key++
@compute_occurrence row
count_occurrence += row.occurrence
keys_count.occurrence = count_occurrence/count_key # count_key cannot be 0
# Sort the keys per level
order_keys: (keys) =>
copy_keys = []
if keys.object?
for key, value of keys.object
if jQuery.isPlainObject(value)
@order_keys value
copy_keys.push
key: key
value: value.occurrence
# If we could know if a key is a primary key, that would be awesome
copy_keys.sort (a, b) ->
if b.value-a.value
return b.value-a.value
else
if a.key > b.key
return 1
else # We cannot have two times the same key
return -1
keys.sorted_keys = _.map copy_keys, (d) -> return d.key
if keys.primitive_value_count > 0
keys.sorted_keys.unshift @primitive_key
# Flatten the object returns by build_map_keys().
# We get back an array of keys
get_all_attr: (args) =>
keys_count = args.keys_count
attr = args.attr
prefix = args.prefix
prefix_str = args.prefix_str
for key in keys_count.sorted_keys
if key is @primitive_key
new_prefix_str = prefix_str # prefix_str without the last dot
if new_prefix_str.length > 0
new_prefix_str = new_prefix_str.slice(0, -1)
attr.push
prefix: prefix
prefix_str: new_prefix_str
is_primitive: true
else
if keys_count['object'][key]['object']?
new_prefix = util.deep_copy(prefix)
new_prefix.push key
@get_all_attr
keys_count: keys_count.object[key]
attr: attr
prefix: new_prefix
prefix_str: (if prefix_str? then prefix_str else '')+key+'.'
else
attr.push
prefix: prefix
prefix_str: prefix_str
key: key
json_to_table_get_attr: (flatten_attr) =>
return @templates.tr_attr
attr: flatten_attr
json_to_table_get_values: (args) =>
result = args.result
flatten_attr = args.flatten_attr
document_list = []
for single_result, i in result
new_document =
cells: []
for attr_obj, col in flatten_attr
key = attr_obj.key
value = single_result
for prefix in attr_obj.prefix
value = value?[prefix]
if attr_obj.is_primitive isnt true
if value?
value = value[key]
else
value = undefined
new_document.cells.push @json_to_table_get_td_value value, col
index = if @query_result.is_feed then @query_result.size() - i else i + 1
@tag_record new_document, index
document_list.push new_document
return @templates.tr_value
document: document_list
json_to_table_get_td_value: (value, col) =>
data = @compute_data_for_type(value, col)
return @templates.td_value
col: col
cell_content: @templates.td_value_content data
compute_data_for_type: (value, col) =>
data =
value: value
class_value: 'value-'+col
value_type = typeof value
if value is null
data['value'] = 'null'
data['classname'] = 'jta_null'
else if value is undefined
data['value'] = 'undefined'
data['classname'] = 'jta_undefined'
else if value.constructor? and value.constructor is Array
if value.length is 0
data['value'] = '[ ]'
data['classname'] = 'empty array'
else
data['value'] = '[ ... ]'
data['data_to_expand'] = JSON.stringify(value)
else if Object::toString.call(value) is '[object Object]' and value.$reql_type$ is 'TIME'
data['value'] = util.date_to_string(value)
data['classname'] = 'jta_date'
else if Object::toString.call(value) is '[object Object]' and value.$reql_type$ is 'BINARY'
data['value'] = util.binary_to_string value
data['classname'] = 'jta_bin'
else if Object::toString.call(value) is '[object Object]'
data['value'] = '{ ... }'
data['is_object'] = true
else if value_type is 'number'
data['classname'] = 'jta_num'
else if value_type is 'string'
if /^(http|https):\/\/[^\s]+$/i.test(value)
data['classname'] = 'jta_url'
else if /^[a-z0-9]+@[a-z0-9]+.[a-z0-9]{2,4}/i.test(value) # We don't handle .museum extension and special characters
data['classname'] = 'jta_email'
else
data['classname'] = 'jta_string'
else if value_type is 'boolean'
data['classname'] = 'jta_bool'
data.value = if value is true then 'true' else 'false'
return data
# Helper for expanding a table when showing an object (creating new columns)
join_table: (data) =>
result = ''
for value, i in data
data_cell = @compute_data_for_type(value, 'float')
data_cell['is_inline'] = true
if i isnt data.length-1
data_cell['need_comma'] = true
result += @templates.data_inline data_cell
return result
# Build the table
# We order by the most frequent keys then by alphabetic order
json_to_table: (result) =>
# While an Array type is never returned by the driver, we still build an Array in the data explorer
# when a cursor is returned (since we just print @limit results)
if not result.constructor? or result.constructor isnt Array
result = [result]
keys_count =
primitive_value_count: 0
for result_entry in result
@build_map_keys
keys_count: keys_count
result: result_entry
@compute_occurrence keys_count
@order_keys keys_count
flatten_attr = []
@get_all_attr # fill attr[]
keys_count: keys_count
attr: flatten_attr
prefix: []
prefix_str: ''
for value, index in flatten_attr
value.col = index
@last_keys = flatten_attr.map (attr, i) ->
if attr.prefix_str isnt ''
return attr.prefix_str+attr.key
return attr.key
@parent.container.state.last_keys = @last_keys
return @templates.container
table_attr: @json_to_table_get_attr flatten_attr
table_data: @json_to_table_get_values
result: result
flatten_attr: flatten_attr
tag_record: (doc, i) =>
doc.record = @query_result.position + i
render: =>
previous_keys = @parent.container.state.last_keys # Save previous keys. @last_keys will be updated in @json_to_table
results = @current_batch()
if Object::toString.call(results) is '[object Array]'
if results.length is 0
@$el.html @templates.wrapper content: @templates.no_result
ended: @query_result.ended
at_beginning: @query_result.at_beginning()
else
@$el.html @templates.wrapper content: @json_to_table results
else
if results is undefined
@$el.html ''
else
@$el.html @templates.wrapper content: @json_to_table [results]
if @query_result.is_feed
# TODO: highlight all new rows, not just the latest one
first_row = @$('.jta_tr').eq(1).find('td:not(:first)')
first_row.css 'background-color': '#eeeeff'
first_row.animate 'background-color': '#fbfbfb'
# Check if the keys are the same
if @parent.container.state.last_keys.length isnt previous_keys.length
same_keys = false
else
same_keys = true
for keys, index in @parent.container.state.last_keys
if @parent.container.state.last_keys[index] isnt previous_keys[index]
same_keys = false
# TODO we should just check if previous_keys is included in last_keys
# If the keys are the same, we are going to resize the columns as they were before
if same_keys is true
for col, value of @parent.container.state.last_columns_size
@resize_column col, value
else
# Reinitialize @last_columns_size
@last_column_size = {}
# Let's try to expand as much as we can
extra_size_table = @$('.json_table_container').width()-@$('.json_table').width()
if extra_size_table > 0 # The table doesn't take the full width
expandable_columns = []
for index in [0..@last_keys.length-1] # We skip the column record
real_size = 0
@$('.col-'+index).children().children().children().each((i, bloc) ->
$bloc = $(bloc)
if real_size<$bloc.width()
real_size = $bloc.width()
)
if real_size? and real_size is real_size and real_size > @default_size_column
expandable_columns.push
col: index
size: real_size+20 # 20 for padding
while expandable_columns.length > 0
expandable_columns.sort (a, b) ->
return a.size-b.size
if expandable_columns[0].size-@$('.col-'+expandable_columns[0].col).width() < extra_size_table/expandable_columns.length
extra_size_table = extra_size_table-(expandable_columns[0]['size']-@$('.col-'+expandable_columns[0].col).width())
@$('.col-'+expandable_columns[0]['col']).css 'max-width', expandable_columns[0]['size']
@$('.value-'+expandable_columns[0]['col']).css 'max-width', expandable_columns[0]['size']-20
expandable_columns.shift()
else
max_size = extra_size_table/expandable_columns.length
for column in expandable_columns
current_size = @$('.col-'+expandable_columns[0].col).width()
@$('.col-'+expandable_columns[0]['col']).css 'max-width', current_size+max_size
@$('.value-'+expandable_columns[0]['col']).css 'max-width', current_size+max_size-20
expandable_columns = []
return @
class RawView extends ResultView
className: 'results raw_view_container'
template: require('../handlebars/dataexplorer_result_raw.hbs')
init_after_dom_rendered: =>
@adjust_height()
adjust_height: =>
height = @$('.raw_view_textarea')[0].scrollHeight
if height > 0
@$('.raw_view_textarea').height(height)
render: =>
@$el.html @template JSON.stringify @current_batch()
@adjust_height()
return @
class ProfileView extends ResultView
className: 'results profile_view_container'
template:
require('../handlebars/dataexplorer_result_profile.hbs')
initialize: (args) =>
ZeroClipboard.setDefaults
moviePath: 'js/ZeroClipboard.swf'
forceHandCursor: true #TODO Find a fix for chromium(/linux?)
@clip = new ZeroClipboard()
super args
compute_total_duration: (profile) ->
profile.reduce(((total, task) ->
total + (task['duration(ms)'] or task['mean_duration(ms)'])) ,0)
compute_num_shard_accesses: (profile) ->
num_shard_accesses = 0
for task in profile
if task['description'] is 'Perform read on shard.'
num_shard_accesses += 1
if Object::toString.call(task['sub_tasks']) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task['sub_tasks']
if Object::toString.call(task['parallel_tasks']) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task['parallel_tasks']
# In parallel tasks, we get arrays of tasks instead of a super task
if Object::toString.call(task) is '[object Array]'
num_shard_accesses += @compute_num_shard_accesses task
return num_shard_accesses
render: =>
if not @query_result.profile?
@$el.html @template {}
else
profile = @query_result.profile
@$el.html @template
profile:
clipboard_text: JSON.stringify profile, null, 2
tree: @json_to_tree profile
total_duration: util.prettify_duration @parent.container.driver_handler.total_duration
server_duration: util.prettify_duration @compute_total_duration profile
num_shard_accesses: @compute_num_shard_accesses profile
@clip.glue(@$('button.copy_profile'))
@delegateEvents()
@
class ResultViewWrapper extends Backbone.View
className: 'result_view'
template: require('../handlebars/dataexplorer_result_container.hbs')
option_template: require('../handlebars/dataexplorer-option_page.hbs')
error_template: require('../handlebars/dataexplorer-error.hbs')
cursor_timed_out_template: require('../handlebars/dataexplorer-cursor_timed_out.hbs')
primitive_key: PI:KEY:<KEY>END_PI' # We suppose that there is no key with such value in the database.
views:
tree: TreeView
table: TableView
profile: ProfileView
raw: RawView
events: ->
'click .link_to_profile_view': 'show_profile'
'click .link_to_tree_view': 'show_tree'
'click .link_to_table_view': 'show_table'
'click .link_to_raw_view': 'show_raw'
'click .activate_profiler': 'activate_profiler'
'click .more_results_link': 'show_next_batch'
'click .pause_feed': 'pause_feed'
'click .unpause_feed': 'unpause_feed'
initialize: (args) =>
@container = args.container
@view = args.view
@view_object = null
@scroll_handler = => @handle_scroll()
@floating_metadata = false
$(window).on('scroll', @scroll_handler)
@handle_scroll()
handle_scroll: =>
scroll = $(window).scrollTop()
pos = @$('.results_header').offset()?.top + 2
if not pos?
return
if @floating_metadata and pos > scroll
@floating_metadata = false
@$('.metadata').removeClass('floating_metadata')
if @container.state.pause_at?
@unpause_feed 'automatic'
if not @floating_metadata and pos < scroll
@floating_metadata = true
@$('.metadata').addClass('floating_metadata')
if not @container.state.pause_at?
@pause_feed 'automatic'
pause_feed: (event) =>
if event is 'automatic'
@auto_unpause = true
else
@auto_unpause = false
event?.preventDefault()
@view_object?.pause_feed()
@$('.metadata').addClass('feed_paused').removeClass('feed_unpaused')
unpause_feed: (event) =>
if event is 'automatic'
if not @auto_unpause
return
else
event.preventDefault()
@view_object?.unpause_feed()
@$('.metadata').removeClass('feed_paused').addClass('feed_unpaused')
show_tree: (event) =>
event.preventDefault()
@set_view 'tree'
show_profile: (event) =>
event.preventDefault()
@set_view 'profile'
show_table: (event) =>
event.preventDefault()
@set_view 'table'
show_raw: (event) =>
event.preventDefault()
@set_view 'raw'
set_view: (view) =>
@view = view
@container.state.view = view
@$(".link_to_#{@view}_view").parent().addClass 'active'
@$(".link_to_#{@view}_view").parent().siblings().removeClass 'active'
if @query_result?.ready
@new_view()
# TODO: The scrollbar sometime shows up when it is not needed
set_scrollbar: =>
if @view is 'table'
content_name = '.json_table'
content_container = '.table_view_container'
else if @view is 'tree'
content_name = '.json_tree'
content_container = '.tree_view_container'
else if @view is 'profile'
content_name = '.json_tree'
content_container = '.profile_view_container'
else if @view is 'raw'
@$('.wrapper_scrollbar').hide()
# There is no scrolbar with the raw view
return
# Set the floating scrollbar
width_value = @$(content_name).innerWidth() # Include padding
if width_value < @$(content_container).width()
# If there is no need for scrollbar, we hide the one on the top
@$('.wrapper_scrollbar').hide()
if @set_scrollbar_scroll_handler?
$(window).unbind 'scroll', @set_scrollbar_scroll_handler
else
# Else we set the fake_content to the same width as the table that contains data and links the two scrollbars
@$('.wrapper_scrollbar').show()
@$('.scrollbar_fake_content').width width_value
$(".wrapper_scrollbar").scroll ->
$(content_container).scrollLeft($(".wrapper_scrollbar").scrollLeft())
$(content_container).scroll ->
$(".wrapper_scrollbar").scrollLeft($(content_container).scrollLeft())
position_scrollbar = ->
if $(content_container).offset()?
# Sometimes we don't have to display the scrollbar (when the results are not shown because the query is too big)
if $(window).scrollTop()+$(window).height() < $(content_container).offset().top+20 # bottom of the window < beginning of $('.json_table_container') // 20 pixels is the approximate height of the scrollbar (so we don't show JUST the scrollbar)
that.$('.wrapper_scrollbar').hide()
# We show the scrollbar and stick it to the bottom of the window because there ismore content below
else if $(window).scrollTop()+$(window).height() < $(content_container).offset().top+$(content_container).height() # bottom of the window < end of $('.json_table_container')
that.$('.wrapper_scrollbar').show()
that.$('.wrapper_scrollbar').css 'overflow', 'auto'
that.$('.wrapper_scrollbar').css 'margin-bottom', '0px'
# And sometimes we "hide" it
else
# We can not hide .wrapper_scrollbar because it would break the binding between wrapper_scrollbar and content_container
that.$('.wrapper_scrollbar').css 'overflow', 'hidden'
that = @
position_scrollbar()
@set_scrollbar_scroll_handler = position_scrollbar
$(window).scroll @set_scrollbar_scroll_handler
$(window).resize ->
position_scrollbar()
activate_profiler: (event) =>
event.preventDefault()
if @container.options_view.state is 'hidden'
@container.toggle_options
cb: =>
setTimeout( =>
if @container.state.options.profiler is false
@container.options_view.$('.option_description[data-option="profiler"]').click()
@container.options_view.$('.profiler_enabled').show()
@container.options_view.$('.profiler_enabled').css 'visibility', 'visible'
, 100)
else
if @container.state.options.profiler is false
@container.options_view.$('.option_description[data-option="profiler"]').click()
@container.options_view.$('.profiler_enabled').hide()
@container.options_view.$('.profiler_enabled').css 'visibility', 'visible'
@container.options_view.$('.profiler_enabled').slideDown 'fast'
render_error: (query, err, js_error) =>
@view_object?.remove()
@view_object = null
@query_result?.discard()
@$el.html @error_template
query: query
error: err.toString().replace(/^(\s*)/, '')
js_error: js_error is true
return @
set_query_result: ({query_result}) =>
@query_result?.discard()
@query_result = query_result
if query_result.ready
@render()
@new_view()
else
@query_result.on 'ready', () =>
@render()
@new_view()
@query_result.on 'end', =>
@render()
render: (args) =>
if @query_result?.ready
@view_object?.$el.detach()
has_more_data = not @query_result.ended and @query_result.position + @container.state.options.query_limit <= @query_result.size()
batch_size = @view_object?.current_batch_size()
@$el.html @template
range_begin: @query_result.position + 1
range_end: batch_size and @query_result.position + batch_size
query_has_changed: args?.query_has_changed
show_more_data: has_more_data and not @container.state.cursor_timed_out
cursor_timed_out_template: (
@cursor_timed_out_template() if not @query_result.ended and @container.state.cursor_timed_out)
execution_time_pretty: util.prettify_duration @query_result.server_duration
no_results: @query_result.ended and @query_result.size() == 0
num_results: @query_result.size()
floating_metadata: @floating_metadata
feed: @feed_info()
@$('.execution_time').tooltip
for_dataexplorer: true
trigger: 'hover'
placement: 'bottom'
@$('.tab-content').html @view_object?.$el
@$(".link_to_#{@view}_view").parent().addClass 'active'
return @
update_feed_metadata: =>
info = @feed_info()
if not info?
return
$('.feed_upcoming').text(info.upcoming)
$('.feed_overflow').parent().toggleClass('hidden', not info.overflow)
feed_info: =>
if @query_result.is_feed
total = @container.state.pause_at ? @query_result.size()
ended: @query_result.ended
overflow: @container.state.options.query_limit < total
paused: @container.state.pause_at?
upcoming: @query_result.size() - total
new_view: () =>
@view_object?.remove()
@view_object = new @views[@view]
parent: @
query_result: @query_result
@$('.tab-content').html @view_object.render().$el
@init_after_dom_rendered()
@set_scrollbar()
init_after_dom_rendered: =>
@view_object?.init_after_dom_rendered?()
# Check if the cursor timed out. If yes, make sure that the user cannot fetch more results
cursor_timed_out: =>
@container.state.cursor_timed_out = true
if @container.state.query_result?.ended is true
@$('.more_results_paragraph').html @cursor_timed_out_template()
remove: =>
@view_object?.remove()
if @query_result?.is_feed
@query_result.force_end_gracefully()
if @set_scrollbar_scroll_handler?
$(window).unbind 'scroll', @set_scrollbar_scroll_handler
$(window).unbind 'resize'
$(window).off('scroll', @scroll_handler)
super()
handle_mouseup: (event) =>
@view_object?.handle_mouseup?(event)
handle_mousemove: (event) =>
@view_object?.handle_mousedown?(event)
show_next_batch: (event) =>
event.preventDefault()
$(window).scrollTop($('.results_container').offset().top)
@view_object?.show_next_batch()
class OptionsView extends Backbone.View
dataexplorer_options_template: require('../handlebars/dataexplorer-options.hbs')
className: 'options_view'
events:
'click li:not(.text-input)': 'toggle_option'
'change #query_limit': 'change_query_limit'
initialize: (args) =>
@container = args.container
@options = args.options
@state = 'hidden'
toggle_option: (event) =>
event.preventDefault()
new_target = @$(event.target).data('option')
@$('#'+new_target).prop 'checked', !@options[new_target]
if event.target.nodeName isnt 'INPUT' # Label we catch if for us
new_value = @$('#'+new_target).is(':checked')
@options[new_target] = new_value
if window.localStorage?
window.localStorage.options = JSON.stringify @options
if new_target is 'profiler' and new_value is false
@$('.profiler_enabled').slideUp 'fast'
change_query_limit: (event) =>
query_limit = parseInt(@$("#query_limit").val(), 10) or DEFAULTS.options.query_limit
@options['query_limit'] = Math.max(query_limit, 1)
if window.localStorage?
window.localStorage.options = JSON.stringify @options
@$('#query_limit').val(@options['query_limit']) # In case the input is reset to 40
render: (displayed) =>
@$el.html @dataexplorer_options_template @options
if displayed is true
@$el.show()
@delegateEvents()
return @
class HistoryView extends Backbone.View
dataexplorer_history_template: require('../handlebars/dataexplorer-history.hbs')
dataexplorer_query_li_template: require('../handlebars/dataexplorer-query_li.hbs')
className: 'history_container'
size_history_displayed: 300
state: 'hidden' # hidden, visible
index_displayed: 0
events:
'click .load_query': 'load_query'
'click .delete_query': 'delete_query'
start_resize: (event) =>
@start_y = event.pageY
@start_height = @container.$('.nano').height()
@mouse_down = true
$('body').toggleClass('resizing', true)
handle_mousemove: (event) =>
if @mouse_down is true
@height_history = Math.max 0, @start_height-@start_y+event.pageY
@container.$('.nano').height @height_history
handle_mouseup: (event) =>
if @mouse_down is true
@mouse_down = false
$('.nano').nanoScroller({preventPageScrolling: true})
$('body').toggleClass('resizing', false)
initialize: (args) =>
@container = args.container
@history = args.history
@height_history = 204
render: (displayed) =>
@$el.html @dataexplorer_history_template()
if displayed is true
@$el.show()
if @history.length is 0
@$('.history_list').append @dataexplorer_query_li_template
no_query: true
displayed_class: 'displayed'
else
for query, i in @history
@$('.history_list').append @dataexplorer_query_li_template
query: query.query
broken_query: query.broken_query
id: i
num: i+1
@delegateEvents()
return @
load_query: (event) =>
id = @$(event.target).data().id
# Set + save codemirror
@container.codemirror.setValue @history[parseInt(id)].query
@container.state.current_query = @history[parseInt(id)].query
@container.save_current_query()
delete_query: (event) =>
that = @
# Remove the query and overwrite localStorage.rethinkdb_history
id = parseInt(@$(event.target).data().id)
@history.splice(id, 1)
window.localStorage.rethinkdb_history = JSON.stringify @history
# Animate the deletion
is_at_bottom = @$('.history_list').height() is $('.nano > .content').scrollTop()+$('.nano').height()
@$('#query_history_'+id).slideUp 'fast', =>
that.$(this).remove()
that.render()
that.container.adjust_collapsible_panel_height
is_at_bottom: is_at_bottom
add_query: (args) =>
query = args.query
broken_query = args.broken_query
that = @
is_at_bottom = @$('.history_list').height() is $('.nano > .content').scrollTop()+$('.nano').height()
@$('.history_list').append @dataexplorer_query_li_template
query: query
broken_query: broken_query
id: @history.length-1
num: @history.length
if @$('.no_history').length > 0
@$('.no_history').slideUp 'fast', ->
$(@).remove()
if that.state is 'visible'
that.container.adjust_collapsible_panel_height
is_at_bottom: is_at_bottom
else if that.state is 'visible'
@container.adjust_collapsible_panel_height
delay_scroll: true
is_at_bottom: is_at_bottom
clear_history: (event) =>
that = @
event.preventDefault()
@container.clear_history()
@history = @container.state.history
@$('.query_history').slideUp 'fast', ->
$(@).remove()
if that.$('.no_history').length is 0
that.$('.history_list').append that.dataexplorer_query_li_template
no_query: true
displayed_class: 'hidden'
that.$('.no_history').slideDown 'fast'
that.container.adjust_collapsible_panel_height
size: 40
move_arrow: 'show'
is_at_bottom: 'true'
class DriverHandler
constructor: (options) ->
@container = options.container
@concurrent = 0
@total_duration = 0
_begin: =>
if @concurrent == 0
@container.toggle_executing true
@begin_time = new Date()
@concurrent++
_end: =>
if @concurrent > 0
@concurrent--
now = new Date()
@total_duration += now - @begin_time
@begin_time = now
if @concurrent == 0
@container.toggle_executing false
close_connection: =>
if @connection?.open is true
driver.close @connection
@connection = null
@_end()
run_with_new_connection: (query, {callback, connection_error, optargs}) =>
@close_connection()
@total_duration = 0
@concurrent = 0
driver.connect (error, connection) =>
if error?
connection_error error
connection.removeAllListeners 'error' # See issue 1347
connection.on 'error', (error) =>
connection_error error
@connection = connection
@_begin()
query.private_run connection, optargs, (error, result) =>
@_end()
callback error, result
cursor_next: (cursor, {error, row, end}) =>
if not @connection?
end()
@_begin()
cursor.next (err, row_) =>
@_end()
if err?
if err.message is 'No more rows in the cursor.'
end()
else
error err
else
row row_
remove: =>
@close_connection()
exports.QueryResult = QueryResult
exports.Container = Container
exports.ResultView = ResultView
exports.TreeView = TreeView
exports.TableView = TableView
exports.RawView = RawView
exports.ProfileView = ProfileView
exports.ResultViewWrapper = ResultViewWrapper
exports.OptionsView = OptionsView
exports.HistoryView = HistoryView
exports.DriverHandler = DriverHandler
exports.dataexplorer_state = dataexplorer_state
|
[
{
"context": "match.pairId is pair._id\n\t\t\t<MatchColumn\n\t\t\t\tkey={pair._id}\n\t\t\t\tpair={pair}\n\t\t\t\tcolumnClass={columnClass}\n\t\t",
"end": 708,
"score": 0.992602527141571,
"start": 700,
"tag": "KEY",
"value": "pair._id"
}
] | src/js/columns.cjsx | BS-Harou/hockey-frontend | 0 | React = require 'react'
ReactDOM = require 'react-dom'
MatchColumn = require './match-column'
PureRenderMixin = require 'react-addons-pure-render-mixin'
AddPair = require './add-pair'
css = require '../css/columns.styl'
module.exports = React.createClass
mixins: [PureRenderMixin]
displayName: 'Columns'
openAddPair: ->
ReactDOM.render React.createElement(AddPair, app.store.getState()), app.modalPlaceholder
return
render: ->
columnClass = css['column']
columns = @props.pairs.items.map (pair, i) =>
pic1 = pair.team1Name?.toLowerCase()
pic2 = pair.team2Name?.toLowerCase()
matches = @props.matches.items.filter (match) -> match.pairId is pair._id
<MatchColumn
key={pair._id}
pair={pair}
columnClass={columnClass}
teams={@props.teams}
matches={matches}
pics={[pic1, pic2]}
/>
<div className={css['columns']}>
{columns}
<div className={css['add-column']} onClick={@openAddPair}>+</div>
</div>
| 172247 | React = require 'react'
ReactDOM = require 'react-dom'
MatchColumn = require './match-column'
PureRenderMixin = require 'react-addons-pure-render-mixin'
AddPair = require './add-pair'
css = require '../css/columns.styl'
module.exports = React.createClass
mixins: [PureRenderMixin]
displayName: 'Columns'
openAddPair: ->
ReactDOM.render React.createElement(AddPair, app.store.getState()), app.modalPlaceholder
return
render: ->
columnClass = css['column']
columns = @props.pairs.items.map (pair, i) =>
pic1 = pair.team1Name?.toLowerCase()
pic2 = pair.team2Name?.toLowerCase()
matches = @props.matches.items.filter (match) -> match.pairId is pair._id
<MatchColumn
key={<KEY>}
pair={pair}
columnClass={columnClass}
teams={@props.teams}
matches={matches}
pics={[pic1, pic2]}
/>
<div className={css['columns']}>
{columns}
<div className={css['add-column']} onClick={@openAddPair}>+</div>
</div>
| true | React = require 'react'
ReactDOM = require 'react-dom'
MatchColumn = require './match-column'
PureRenderMixin = require 'react-addons-pure-render-mixin'
AddPair = require './add-pair'
css = require '../css/columns.styl'
module.exports = React.createClass
mixins: [PureRenderMixin]
displayName: 'Columns'
openAddPair: ->
ReactDOM.render React.createElement(AddPair, app.store.getState()), app.modalPlaceholder
return
render: ->
columnClass = css['column']
columns = @props.pairs.items.map (pair, i) =>
pic1 = pair.team1Name?.toLowerCase()
pic2 = pair.team2Name?.toLowerCase()
matches = @props.matches.items.filter (match) -> match.pairId is pair._id
<MatchColumn
key={PI:KEY:<KEY>END_PI}
pair={pair}
columnClass={columnClass}
teams={@props.teams}
matches={matches}
pics={[pic1, pic2]}
/>
<div className={css['columns']}>
{columns}
<div className={css['add-column']} onClick={@openAddPair}>+</div>
</div>
|
[
{
"context": "Snapshot(@get(\"$el\"))\n\n obj = {\n name: name\n body: body\n htmlAttrs: htmlAttrs\n ",
"end": 7144,
"score": 0.5681754946708679,
"start": 7140,
"tag": "NAME",
"value": "name"
},
{
"context": "ps = ->\n key = if _this.get(\"event\") then \"Event\" else \"Command\"\n\n consoleObj = {}\n c",
"end": 9993,
"score": 0.653529703617096,
"start": 9987,
"tag": "KEY",
"value": "Event\""
},
{
"context": " key = if _this.get(\"event\") then \"Event\" else \"Command\"\n\n consoleObj = {}\n consoleObj[key] ",
"end": 10008,
"score": 0.47998446226119995,
"start": 10000,
"tag": "KEY",
"value": "Command\""
}
] | packages/driver/src/cypress/log.coffee | andreirogobete/cypress | 1 | _ = require("lodash")
$ = require("jquery")
clone = require("clone")
$Snapshots = require("../cy/snapshots")
$Events = require("./events")
$dom = require("../dom")
$utils = require("./utils")
## adds class methods for command, route, and agent logging
## including the intermediate $Log interface
CypressErrorRe = /(AssertionError|CypressError)/
groupsOrTableRe = /^(groups|table)$/
parentOrChildRe = /parent|child/
ERROR_PROPS = "message type name stack fileName lineNumber columnNumber host uncaught actual expected showDiff".split(" ")
SNAPSHOT_PROPS = "id snapshots $el url coords highlightAttr scrollBy viewportWidth viewportHeight".split(" ")
DISPLAY_PROPS = "id alias aliasType callCount displayName end err event functionName hookName instrument isStubbed message method name numElements numResponses referencesAlias renderProps state testId type url visible".split(" ")
BLACKLIST_PROPS = "snapshots".split(" ")
delay = null
counter = 0
{ HIGHLIGHT_ATTR } = $Snapshots
reduceMemory = (attrs) ->
## mutate attrs by nulling out
## object properties
_.each attrs, (value, key) ->
if _.isObject(value)
attrs[key] = null
toSerializedJSON = (attrs) ->
isDom = $dom.isDom
isWindow = $dom.isWindow
isDocument = $dom.isDocument
isElement = $dom.isElement
stringify = (value, key) ->
return null if key in BLACKLIST_PROPS
switch
when _.isArray(value)
_.map(value, stringify)
when isDom(value)
$dom.stringify(value, "short")
when _.isFunction(value) and groupsOrTableRe.test(key)
value()
when _.isFunction(value)
value.toString()
when _.isObject(value)
## clone to nuke circular references
## and blow away anything that throws
try
_.mapValues(clone(value), stringify)
catch err
null
else
value
_.mapValues(attrs, stringify)
getDisplayProps = (attrs) ->
_.pick(attrs, DISPLAY_PROPS)
getConsoleProps = (attrs) ->
attrs.consoleProps
getSnapshotProps = (attrs) ->
_.pick(attrs, SNAPSHOT_PROPS)
countLogsByTests = (tests = {}) ->
return 0 if _.isEmpty(tests)
_
.chain(tests)
.map (test, key) ->
[].concat(test.agents, test.routes, test.commands)
.flatten()
.compact()
.union([{id: 0}])
.map("id")
.max()
.value()
## TODO: fix this
setCounter = (num) ->
counter = num
setDelay = (val) ->
delay = val ? 4
defaults = (state, config, obj) ->
instrument = obj.instrument ? "command"
## dont set any defaults if this
## is an agent or route because we
## may not even be inside of a command
if instrument is "command"
current = state("current")
## we are logging a command instrument by default
_.defaults(obj, current?.pick("name", "type"))
## force duals to become either parents or childs
## normally this would be handled by the command itself
## but in cases where the command purposely does not log
## then it could still be logged during a failure, which
## is why we normalize its type value
if not parentOrChildRe.test(obj.type)
## does this command have a previously linked command
## by chainer id
obj.type = if current.hasPreviouslyLinkedCommand() then "child" else "parent"
_.defaults(obj, {
event: false
renderProps: -> {}
consoleProps: ->
## if we don't have a current command just bail
return {} if not current
ret = if $dom.isElement(current.get("subject"))
$dom.getElements(current.get("subject"))
else
current.get("subject")
return { Yielded: ret }
})
# if obj.isCurrent
## stringify the obj.message (if it exists) or current.get("args")
obj.message = $utils.stringify(obj.message ? current.get("args"))
## allow type to by a dynamic function
## so it can conditionally return either
## parent or child (useful in assertions)
if _.isFunction(obj.type)
obj.type = obj.type(current, state("subject"))
_.defaults(obj, {
id: (counter += 1)
state: "pending"
instrument: "command"
url: state("url")
hookName: state("hookName")
testId: state("runnable")?.id
viewportWidth: state("viewportWidth")
viewportHeight: state("viewportHeight")
referencesAlias: undefined
alias: undefined
aliasType: undefined
message: undefined
renderProps: -> {}
consoleProps: -> {}
})
Log = (state, config, obj) ->
obj = defaults(state, config, obj)
## private attributes of each log
attributes = {}
return {
get: (attr) ->
if attr then attributes[attr] else attributes
unset: (key) ->
@set(key, undefined)
invoke: (key) ->
invoke = =>
## ensure this is a callable function
## and set its default to empty object literal
fn = @get(key)
if _.isFunction(fn)
fn()
else
fn
invoke() ? {}
serializeError: ->
if err = @get("error")
_.reduce ERROR_PROPS, (memo, prop) ->
if _.has(err, prop) or err[prop]
memo[prop] = err[prop]
memo
, {}
else
null
toJSON: ->
_
.chain(attributes)
.omit("error")
.omitBy(_.isFunction)
.extend({
err: @serializeError()
consoleProps: @invoke("consoleProps")
renderProps: @invoke("renderProps")
})
.value()
set: (key, val) ->
if _.isString(key)
obj = {}
obj[key] = val
else
obj = key
if "url" of obj
## always stringify the url property
obj.url = (obj.url ? "").toString()
## convert onConsole to consoleProps
## for backwards compatibility
if oc = obj.onConsole
obj.consoleProps = oc
## if we have an alias automatically
## figure out what type of alias it is
if obj.alias
_.defaults obj, {aliasType: if obj.$el then "dom" else "primitive"}
## dont ever allow existing id's to be mutated
if attributes.id
delete obj.id
_.extend(attributes, obj)
## if we have an consoleProps function
## then re-wrap it
if obj and _.isFunction(obj.consoleProps)
@wrapConsoleProps()
if obj and obj.$el
@setElAttrs()
@fireChangeEvent()
return @
pick: (args...) ->
args.unshift(attributes)
_.pick.apply(_, args)
publicInterface: ->
{
get: _.bind(@get, @)
on: _.bind(@on, @)
off: _.bind(@off, @)
pick: _.bind(@pick, @)
attributes: attributes
}
snapshot: (name, options = {}) ->
## bail early and dont snapshot
## if we're in headless mode
## TODO: fix this
if not config("isInteractive")
return @
_.defaults options,
at: null
next: null
{body, htmlAttrs, headStyles, bodyStyles} = cy.createSnapshot(@get("$el"))
obj = {
name: name
body: body
htmlAttrs: htmlAttrs
headStyles: headStyles
bodyStyles: bodyStyles
}
snapshots = @get("snapshots") ? []
## insert at index 'at' or whatever is the next position
snapshots[options.at or snapshots.length] = obj
@set("snapshots", snapshots)
if next = options.next
fn = @snapshot
@snapshot = ->
## restore the fn
@snapshot = fn
## call orig fn with next as name
fn.call(@, next)
return @
error: (err) ->
@set({
ended: true
error: err
state: "failed"
})
return @
end: ->
## dont set back to passed
## if we've already ended
return if @get("ended")
@set({
ended: true
state: "passed"
})
return @
getError: (err) ->
## dont log stack traces on cypress errors
## or assertion errors
if CypressErrorRe.test(err.name)
err.toString()
else
err.stack
setElAttrs: ->
$el = @get("$el")
return if not $el
if _.isElement($el)
## wrap the element in jquery
## if its just a plain element
return @set("$el", $($el), {silent: true})
## if we've passed something like
## <window> or <document> here or
## a primitive then unset $el
if not $dom.isJquery($el)
return @unset("$el")
## make sure all $el elements are visible!
obj = {
highlightAttr: HIGHLIGHT_ATTR
numElements: $el.length
visible: $el.length is $el.filter(":visible").length
}
@set(obj, {silent: true})
merge: (log) ->
## merges another logs attributes into
## ours by also removing / adding any properties
## on the original
## 1. calculate which properties to unset
unsets = _.chain(attributes).keys().without(_.keys(log.get())...).value()
_.each unsets, (unset) =>
@unset(unset)
## 2. merge in any other properties
@set(log.get())
_shouldAutoEnd: ->
## must be autoEnd
## and not already ended
## and not an event
## and a command
@get("autoEnd") isnt false and
@get("ended") isnt true and
@get("event") is false and
@get("instrument") is "command"
finish: ->
## end our command since our subject
## has been resolved at this point
## unless its already been 'ended'
## or has been specifically told not to auto resolve
if @_shouldAutoEnd()
@snapshot().end()
wrapConsoleProps: ->
_this = @
consoleProps = attributes.consoleProps
## re-wrap consoleProps to set Command + Error defaults
attributes.consoleProps = ->
key = if _this.get("event") then "Event" else "Command"
consoleObj = {}
consoleObj[key] = _this.get("name")
## merge in the other properties from consoleProps
_.extend consoleObj, consoleProps.apply(@, arguments)
## TODO: right here we need to automatically
## merge in "Yielded + Element" if there is an $el
## and finally add error if one exists
if err = _this.get("error")
_.defaults(consoleObj, {
Error: _this.getError(err)
})
## add note if no snapshot exists on command instruments
if _this.get("instrument") is "command" and not _this.get("snapshots")
consoleObj.Snapshot = "The snapshot is missing. Displaying current state of the DOM."
else
delete consoleObj.Snapshot
return consoleObj
}
create = (Cypress, cy, state, config) ->
counter = 0
logs = {}
## give us the ability to change the delay for firing
## the change event, or default it to 4
delay ?= setDelay(config("logAttrsDelay"))
trigger = (log, event) ->
## bail if we never fired our initial log event
return if not log._hasInitiallyLogged
## bail if we've reset the logs due to a Cypress.abort
return if not logs[log.get("id")]
attrs = log.toJSON()
## only trigger this event if our last stored
## emitted attrs do not match the current toJSON
if not _.isEqual(log._emittedAttrs, attrs)
log._emittedAttrs = attrs
log.emit(event, attrs)
Cypress.action(event, attrs, log)
triggerLog = (log) ->
log._hasInitiallyLogged = true
trigger(log, "command:log:added")
addToLogs = (log) ->
id = log.get("id")
logs[id] = true
logFn = (obj = {}) ->
attributes = {}
log = Log(state, config, obj)
## add event emitter interface
$Events.extend(log)
triggerStateChanged = ->
trigger(log, "command:log:changed")
## only fire the log:state:changed event
## as fast as every 4ms
log.fireChangeEvent = _.debounce(triggerStateChanged, 4)
log.set(obj)
## if snapshot was passed
## in, go ahead and snapshot
log.snapshot() if log.get("snapshot")
## if end was passed in
## go ahead and end
log.end({silent: true}) if log.get("end")
if err = log.get("error")
log.error(err, {silent: true})
log.wrapConsoleProps()
onBeforeLog = state("onBeforeLog")
## dont trigger log if this function
## explicitly returns false
if _.isFunction(onBeforeLog)
return if onBeforeLog.call(cy, log) is false
## set the log on the command
state("current")?.log(log)
addToLogs(log)
triggerLog(log)
return log
logFn._logs = logs
return logFn
module.exports = {
reduceMemory
toSerializedJSON
getDisplayProps
getConsoleProps
getSnapshotProps
countLogsByTests
setCounter
create
}
| 113070 | _ = require("lodash")
$ = require("jquery")
clone = require("clone")
$Snapshots = require("../cy/snapshots")
$Events = require("./events")
$dom = require("../dom")
$utils = require("./utils")
## adds class methods for command, route, and agent logging
## including the intermediate $Log interface
CypressErrorRe = /(AssertionError|CypressError)/
groupsOrTableRe = /^(groups|table)$/
parentOrChildRe = /parent|child/
ERROR_PROPS = "message type name stack fileName lineNumber columnNumber host uncaught actual expected showDiff".split(" ")
SNAPSHOT_PROPS = "id snapshots $el url coords highlightAttr scrollBy viewportWidth viewportHeight".split(" ")
DISPLAY_PROPS = "id alias aliasType callCount displayName end err event functionName hookName instrument isStubbed message method name numElements numResponses referencesAlias renderProps state testId type url visible".split(" ")
BLACKLIST_PROPS = "snapshots".split(" ")
delay = null
counter = 0
{ HIGHLIGHT_ATTR } = $Snapshots
reduceMemory = (attrs) ->
## mutate attrs by nulling out
## object properties
_.each attrs, (value, key) ->
if _.isObject(value)
attrs[key] = null
toSerializedJSON = (attrs) ->
isDom = $dom.isDom
isWindow = $dom.isWindow
isDocument = $dom.isDocument
isElement = $dom.isElement
stringify = (value, key) ->
return null if key in BLACKLIST_PROPS
switch
when _.isArray(value)
_.map(value, stringify)
when isDom(value)
$dom.stringify(value, "short")
when _.isFunction(value) and groupsOrTableRe.test(key)
value()
when _.isFunction(value)
value.toString()
when _.isObject(value)
## clone to nuke circular references
## and blow away anything that throws
try
_.mapValues(clone(value), stringify)
catch err
null
else
value
_.mapValues(attrs, stringify)
getDisplayProps = (attrs) ->
_.pick(attrs, DISPLAY_PROPS)
getConsoleProps = (attrs) ->
attrs.consoleProps
getSnapshotProps = (attrs) ->
_.pick(attrs, SNAPSHOT_PROPS)
countLogsByTests = (tests = {}) ->
return 0 if _.isEmpty(tests)
_
.chain(tests)
.map (test, key) ->
[].concat(test.agents, test.routes, test.commands)
.flatten()
.compact()
.union([{id: 0}])
.map("id")
.max()
.value()
## TODO: fix this
setCounter = (num) ->
counter = num
setDelay = (val) ->
delay = val ? 4
defaults = (state, config, obj) ->
instrument = obj.instrument ? "command"
## dont set any defaults if this
## is an agent or route because we
## may not even be inside of a command
if instrument is "command"
current = state("current")
## we are logging a command instrument by default
_.defaults(obj, current?.pick("name", "type"))
## force duals to become either parents or childs
## normally this would be handled by the command itself
## but in cases where the command purposely does not log
## then it could still be logged during a failure, which
## is why we normalize its type value
if not parentOrChildRe.test(obj.type)
## does this command have a previously linked command
## by chainer id
obj.type = if current.hasPreviouslyLinkedCommand() then "child" else "parent"
_.defaults(obj, {
event: false
renderProps: -> {}
consoleProps: ->
## if we don't have a current command just bail
return {} if not current
ret = if $dom.isElement(current.get("subject"))
$dom.getElements(current.get("subject"))
else
current.get("subject")
return { Yielded: ret }
})
# if obj.isCurrent
## stringify the obj.message (if it exists) or current.get("args")
obj.message = $utils.stringify(obj.message ? current.get("args"))
## allow type to by a dynamic function
## so it can conditionally return either
## parent or child (useful in assertions)
if _.isFunction(obj.type)
obj.type = obj.type(current, state("subject"))
_.defaults(obj, {
id: (counter += 1)
state: "pending"
instrument: "command"
url: state("url")
hookName: state("hookName")
testId: state("runnable")?.id
viewportWidth: state("viewportWidth")
viewportHeight: state("viewportHeight")
referencesAlias: undefined
alias: undefined
aliasType: undefined
message: undefined
renderProps: -> {}
consoleProps: -> {}
})
Log = (state, config, obj) ->
obj = defaults(state, config, obj)
## private attributes of each log
attributes = {}
return {
get: (attr) ->
if attr then attributes[attr] else attributes
unset: (key) ->
@set(key, undefined)
invoke: (key) ->
invoke = =>
## ensure this is a callable function
## and set its default to empty object literal
fn = @get(key)
if _.isFunction(fn)
fn()
else
fn
invoke() ? {}
serializeError: ->
if err = @get("error")
_.reduce ERROR_PROPS, (memo, prop) ->
if _.has(err, prop) or err[prop]
memo[prop] = err[prop]
memo
, {}
else
null
toJSON: ->
_
.chain(attributes)
.omit("error")
.omitBy(_.isFunction)
.extend({
err: @serializeError()
consoleProps: @invoke("consoleProps")
renderProps: @invoke("renderProps")
})
.value()
set: (key, val) ->
if _.isString(key)
obj = {}
obj[key] = val
else
obj = key
if "url" of obj
## always stringify the url property
obj.url = (obj.url ? "").toString()
## convert onConsole to consoleProps
## for backwards compatibility
if oc = obj.onConsole
obj.consoleProps = oc
## if we have an alias automatically
## figure out what type of alias it is
if obj.alias
_.defaults obj, {aliasType: if obj.$el then "dom" else "primitive"}
## dont ever allow existing id's to be mutated
if attributes.id
delete obj.id
_.extend(attributes, obj)
## if we have an consoleProps function
## then re-wrap it
if obj and _.isFunction(obj.consoleProps)
@wrapConsoleProps()
if obj and obj.$el
@setElAttrs()
@fireChangeEvent()
return @
pick: (args...) ->
args.unshift(attributes)
_.pick.apply(_, args)
publicInterface: ->
{
get: _.bind(@get, @)
on: _.bind(@on, @)
off: _.bind(@off, @)
pick: _.bind(@pick, @)
attributes: attributes
}
snapshot: (name, options = {}) ->
## bail early and dont snapshot
## if we're in headless mode
## TODO: fix this
if not config("isInteractive")
return @
_.defaults options,
at: null
next: null
{body, htmlAttrs, headStyles, bodyStyles} = cy.createSnapshot(@get("$el"))
obj = {
name: <NAME>
body: body
htmlAttrs: htmlAttrs
headStyles: headStyles
bodyStyles: bodyStyles
}
snapshots = @get("snapshots") ? []
## insert at index 'at' or whatever is the next position
snapshots[options.at or snapshots.length] = obj
@set("snapshots", snapshots)
if next = options.next
fn = @snapshot
@snapshot = ->
## restore the fn
@snapshot = fn
## call orig fn with next as name
fn.call(@, next)
return @
error: (err) ->
@set({
ended: true
error: err
state: "failed"
})
return @
end: ->
## dont set back to passed
## if we've already ended
return if @get("ended")
@set({
ended: true
state: "passed"
})
return @
getError: (err) ->
## dont log stack traces on cypress errors
## or assertion errors
if CypressErrorRe.test(err.name)
err.toString()
else
err.stack
setElAttrs: ->
$el = @get("$el")
return if not $el
if _.isElement($el)
## wrap the element in jquery
## if its just a plain element
return @set("$el", $($el), {silent: true})
## if we've passed something like
## <window> or <document> here or
## a primitive then unset $el
if not $dom.isJquery($el)
return @unset("$el")
## make sure all $el elements are visible!
obj = {
highlightAttr: HIGHLIGHT_ATTR
numElements: $el.length
visible: $el.length is $el.filter(":visible").length
}
@set(obj, {silent: true})
merge: (log) ->
## merges another logs attributes into
## ours by also removing / adding any properties
## on the original
## 1. calculate which properties to unset
unsets = _.chain(attributes).keys().without(_.keys(log.get())...).value()
_.each unsets, (unset) =>
@unset(unset)
## 2. merge in any other properties
@set(log.get())
_shouldAutoEnd: ->
## must be autoEnd
## and not already ended
## and not an event
## and a command
@get("autoEnd") isnt false and
@get("ended") isnt true and
@get("event") is false and
@get("instrument") is "command"
finish: ->
## end our command since our subject
## has been resolved at this point
## unless its already been 'ended'
## or has been specifically told not to auto resolve
if @_shouldAutoEnd()
@snapshot().end()
wrapConsoleProps: ->
_this = @
consoleProps = attributes.consoleProps
## re-wrap consoleProps to set Command + Error defaults
attributes.consoleProps = ->
key = if _this.get("event") then "<KEY> else "<KEY>
consoleObj = {}
consoleObj[key] = _this.get("name")
## merge in the other properties from consoleProps
_.extend consoleObj, consoleProps.apply(@, arguments)
## TODO: right here we need to automatically
## merge in "Yielded + Element" if there is an $el
## and finally add error if one exists
if err = _this.get("error")
_.defaults(consoleObj, {
Error: _this.getError(err)
})
## add note if no snapshot exists on command instruments
if _this.get("instrument") is "command" and not _this.get("snapshots")
consoleObj.Snapshot = "The snapshot is missing. Displaying current state of the DOM."
else
delete consoleObj.Snapshot
return consoleObj
}
create = (Cypress, cy, state, config) ->
counter = 0
logs = {}
## give us the ability to change the delay for firing
## the change event, or default it to 4
delay ?= setDelay(config("logAttrsDelay"))
trigger = (log, event) ->
## bail if we never fired our initial log event
return if not log._hasInitiallyLogged
## bail if we've reset the logs due to a Cypress.abort
return if not logs[log.get("id")]
attrs = log.toJSON()
## only trigger this event if our last stored
## emitted attrs do not match the current toJSON
if not _.isEqual(log._emittedAttrs, attrs)
log._emittedAttrs = attrs
log.emit(event, attrs)
Cypress.action(event, attrs, log)
triggerLog = (log) ->
log._hasInitiallyLogged = true
trigger(log, "command:log:added")
addToLogs = (log) ->
id = log.get("id")
logs[id] = true
logFn = (obj = {}) ->
attributes = {}
log = Log(state, config, obj)
## add event emitter interface
$Events.extend(log)
triggerStateChanged = ->
trigger(log, "command:log:changed")
## only fire the log:state:changed event
## as fast as every 4ms
log.fireChangeEvent = _.debounce(triggerStateChanged, 4)
log.set(obj)
## if snapshot was passed
## in, go ahead and snapshot
log.snapshot() if log.get("snapshot")
## if end was passed in
## go ahead and end
log.end({silent: true}) if log.get("end")
if err = log.get("error")
log.error(err, {silent: true})
log.wrapConsoleProps()
onBeforeLog = state("onBeforeLog")
## dont trigger log if this function
## explicitly returns false
if _.isFunction(onBeforeLog)
return if onBeforeLog.call(cy, log) is false
## set the log on the command
state("current")?.log(log)
addToLogs(log)
triggerLog(log)
return log
logFn._logs = logs
return logFn
module.exports = {
reduceMemory
toSerializedJSON
getDisplayProps
getConsoleProps
getSnapshotProps
countLogsByTests
setCounter
create
}
| true | _ = require("lodash")
$ = require("jquery")
clone = require("clone")
$Snapshots = require("../cy/snapshots")
$Events = require("./events")
$dom = require("../dom")
$utils = require("./utils")
## adds class methods for command, route, and agent logging
## including the intermediate $Log interface
CypressErrorRe = /(AssertionError|CypressError)/
groupsOrTableRe = /^(groups|table)$/
parentOrChildRe = /parent|child/
ERROR_PROPS = "message type name stack fileName lineNumber columnNumber host uncaught actual expected showDiff".split(" ")
SNAPSHOT_PROPS = "id snapshots $el url coords highlightAttr scrollBy viewportWidth viewportHeight".split(" ")
DISPLAY_PROPS = "id alias aliasType callCount displayName end err event functionName hookName instrument isStubbed message method name numElements numResponses referencesAlias renderProps state testId type url visible".split(" ")
BLACKLIST_PROPS = "snapshots".split(" ")
delay = null
counter = 0
{ HIGHLIGHT_ATTR } = $Snapshots
reduceMemory = (attrs) ->
## mutate attrs by nulling out
## object properties
_.each attrs, (value, key) ->
if _.isObject(value)
attrs[key] = null
toSerializedJSON = (attrs) ->
isDom = $dom.isDom
isWindow = $dom.isWindow
isDocument = $dom.isDocument
isElement = $dom.isElement
stringify = (value, key) ->
return null if key in BLACKLIST_PROPS
switch
when _.isArray(value)
_.map(value, stringify)
when isDom(value)
$dom.stringify(value, "short")
when _.isFunction(value) and groupsOrTableRe.test(key)
value()
when _.isFunction(value)
value.toString()
when _.isObject(value)
## clone to nuke circular references
## and blow away anything that throws
try
_.mapValues(clone(value), stringify)
catch err
null
else
value
_.mapValues(attrs, stringify)
getDisplayProps = (attrs) ->
_.pick(attrs, DISPLAY_PROPS)
getConsoleProps = (attrs) ->
attrs.consoleProps
getSnapshotProps = (attrs) ->
_.pick(attrs, SNAPSHOT_PROPS)
countLogsByTests = (tests = {}) ->
return 0 if _.isEmpty(tests)
_
.chain(tests)
.map (test, key) ->
[].concat(test.agents, test.routes, test.commands)
.flatten()
.compact()
.union([{id: 0}])
.map("id")
.max()
.value()
## TODO: fix this
setCounter = (num) ->
counter = num
setDelay = (val) ->
delay = val ? 4
defaults = (state, config, obj) ->
instrument = obj.instrument ? "command"
## dont set any defaults if this
## is an agent or route because we
## may not even be inside of a command
if instrument is "command"
current = state("current")
## we are logging a command instrument by default
_.defaults(obj, current?.pick("name", "type"))
## force duals to become either parents or childs
## normally this would be handled by the command itself
## but in cases where the command purposely does not log
## then it could still be logged during a failure, which
## is why we normalize its type value
if not parentOrChildRe.test(obj.type)
## does this command have a previously linked command
## by chainer id
obj.type = if current.hasPreviouslyLinkedCommand() then "child" else "parent"
_.defaults(obj, {
event: false
renderProps: -> {}
consoleProps: ->
## if we don't have a current command just bail
return {} if not current
ret = if $dom.isElement(current.get("subject"))
$dom.getElements(current.get("subject"))
else
current.get("subject")
return { Yielded: ret }
})
# if obj.isCurrent
## stringify the obj.message (if it exists) or current.get("args")
obj.message = $utils.stringify(obj.message ? current.get("args"))
## allow type to by a dynamic function
## so it can conditionally return either
## parent or child (useful in assertions)
if _.isFunction(obj.type)
obj.type = obj.type(current, state("subject"))
_.defaults(obj, {
id: (counter += 1)
state: "pending"
instrument: "command"
url: state("url")
hookName: state("hookName")
testId: state("runnable")?.id
viewportWidth: state("viewportWidth")
viewportHeight: state("viewportHeight")
referencesAlias: undefined
alias: undefined
aliasType: undefined
message: undefined
renderProps: -> {}
consoleProps: -> {}
})
Log = (state, config, obj) ->
obj = defaults(state, config, obj)
## private attributes of each log
attributes = {}
return {
get: (attr) ->
if attr then attributes[attr] else attributes
unset: (key) ->
@set(key, undefined)
invoke: (key) ->
invoke = =>
## ensure this is a callable function
## and set its default to empty object literal
fn = @get(key)
if _.isFunction(fn)
fn()
else
fn
invoke() ? {}
serializeError: ->
if err = @get("error")
_.reduce ERROR_PROPS, (memo, prop) ->
if _.has(err, prop) or err[prop]
memo[prop] = err[prop]
memo
, {}
else
null
toJSON: ->
_
.chain(attributes)
.omit("error")
.omitBy(_.isFunction)
.extend({
err: @serializeError()
consoleProps: @invoke("consoleProps")
renderProps: @invoke("renderProps")
})
.value()
set: (key, val) ->
if _.isString(key)
obj = {}
obj[key] = val
else
obj = key
if "url" of obj
## always stringify the url property
obj.url = (obj.url ? "").toString()
## convert onConsole to consoleProps
## for backwards compatibility
if oc = obj.onConsole
obj.consoleProps = oc
## if we have an alias automatically
## figure out what type of alias it is
if obj.alias
_.defaults obj, {aliasType: if obj.$el then "dom" else "primitive"}
## dont ever allow existing id's to be mutated
if attributes.id
delete obj.id
_.extend(attributes, obj)
## if we have an consoleProps function
## then re-wrap it
if obj and _.isFunction(obj.consoleProps)
@wrapConsoleProps()
if obj and obj.$el
@setElAttrs()
@fireChangeEvent()
return @
pick: (args...) ->
args.unshift(attributes)
_.pick.apply(_, args)
publicInterface: ->
{
get: _.bind(@get, @)
on: _.bind(@on, @)
off: _.bind(@off, @)
pick: _.bind(@pick, @)
attributes: attributes
}
snapshot: (name, options = {}) ->
## bail early and dont snapshot
## if we're in headless mode
## TODO: fix this
if not config("isInteractive")
return @
_.defaults options,
at: null
next: null
{body, htmlAttrs, headStyles, bodyStyles} = cy.createSnapshot(@get("$el"))
obj = {
name: PI:NAME:<NAME>END_PI
body: body
htmlAttrs: htmlAttrs
headStyles: headStyles
bodyStyles: bodyStyles
}
snapshots = @get("snapshots") ? []
## insert at index 'at' or whatever is the next position
snapshots[options.at or snapshots.length] = obj
@set("snapshots", snapshots)
if next = options.next
fn = @snapshot
@snapshot = ->
## restore the fn
@snapshot = fn
## call orig fn with next as name
fn.call(@, next)
return @
error: (err) ->
@set({
ended: true
error: err
state: "failed"
})
return @
end: ->
## dont set back to passed
## if we've already ended
return if @get("ended")
@set({
ended: true
state: "passed"
})
return @
getError: (err) ->
## dont log stack traces on cypress errors
## or assertion errors
if CypressErrorRe.test(err.name)
err.toString()
else
err.stack
setElAttrs: ->
$el = @get("$el")
return if not $el
if _.isElement($el)
## wrap the element in jquery
## if its just a plain element
return @set("$el", $($el), {silent: true})
## if we've passed something like
## <window> or <document> here or
## a primitive then unset $el
if not $dom.isJquery($el)
return @unset("$el")
## make sure all $el elements are visible!
obj = {
highlightAttr: HIGHLIGHT_ATTR
numElements: $el.length
visible: $el.length is $el.filter(":visible").length
}
@set(obj, {silent: true})
merge: (log) ->
## merges another logs attributes into
## ours by also removing / adding any properties
## on the original
## 1. calculate which properties to unset
unsets = _.chain(attributes).keys().without(_.keys(log.get())...).value()
_.each unsets, (unset) =>
@unset(unset)
## 2. merge in any other properties
@set(log.get())
_shouldAutoEnd: ->
## must be autoEnd
## and not already ended
## and not an event
## and a command
@get("autoEnd") isnt false and
@get("ended") isnt true and
@get("event") is false and
@get("instrument") is "command"
finish: ->
## end our command since our subject
## has been resolved at this point
## unless its already been 'ended'
## or has been specifically told not to auto resolve
if @_shouldAutoEnd()
@snapshot().end()
wrapConsoleProps: ->
_this = @
consoleProps = attributes.consoleProps
## re-wrap consoleProps to set Command + Error defaults
attributes.consoleProps = ->
key = if _this.get("event") then "PI:KEY:<KEY>END_PI else "PI:KEY:<KEY>END_PI
consoleObj = {}
consoleObj[key] = _this.get("name")
## merge in the other properties from consoleProps
_.extend consoleObj, consoleProps.apply(@, arguments)
## TODO: right here we need to automatically
## merge in "Yielded + Element" if there is an $el
## and finally add error if one exists
if err = _this.get("error")
_.defaults(consoleObj, {
Error: _this.getError(err)
})
## add note if no snapshot exists on command instruments
if _this.get("instrument") is "command" and not _this.get("snapshots")
consoleObj.Snapshot = "The snapshot is missing. Displaying current state of the DOM."
else
delete consoleObj.Snapshot
return consoleObj
}
create = (Cypress, cy, state, config) ->
counter = 0
logs = {}
## give us the ability to change the delay for firing
## the change event, or default it to 4
delay ?= setDelay(config("logAttrsDelay"))
trigger = (log, event) ->
## bail if we never fired our initial log event
return if not log._hasInitiallyLogged
## bail if we've reset the logs due to a Cypress.abort
return if not logs[log.get("id")]
attrs = log.toJSON()
## only trigger this event if our last stored
## emitted attrs do not match the current toJSON
if not _.isEqual(log._emittedAttrs, attrs)
log._emittedAttrs = attrs
log.emit(event, attrs)
Cypress.action(event, attrs, log)
triggerLog = (log) ->
log._hasInitiallyLogged = true
trigger(log, "command:log:added")
addToLogs = (log) ->
id = log.get("id")
logs[id] = true
logFn = (obj = {}) ->
attributes = {}
log = Log(state, config, obj)
## add event emitter interface
$Events.extend(log)
triggerStateChanged = ->
trigger(log, "command:log:changed")
## only fire the log:state:changed event
## as fast as every 4ms
log.fireChangeEvent = _.debounce(triggerStateChanged, 4)
log.set(obj)
## if snapshot was passed
## in, go ahead and snapshot
log.snapshot() if log.get("snapshot")
## if end was passed in
## go ahead and end
log.end({silent: true}) if log.get("end")
if err = log.get("error")
log.error(err, {silent: true})
log.wrapConsoleProps()
onBeforeLog = state("onBeforeLog")
## dont trigger log if this function
## explicitly returns false
if _.isFunction(onBeforeLog)
return if onBeforeLog.call(cy, log) is false
## set the log on the command
state("current")?.log(log)
addToLogs(log)
triggerLog(log)
return log
logFn._logs = logs
return logFn
module.exports = {
reduceMemory
toSerializedJSON
getDisplayProps
getConsoleProps
getSnapshotProps
countLogsByTests
setCounter
create
}
|
[
{
"context": "refer to the FAQ: https://githubusercontent.com/bevry/docpad/wiki/FAQ\n\n templateData:\n\n # Specify s",
"end": 457,
"score": 0.7330897450447083,
"start": 454,
"tag": "USERNAME",
"value": "vry"
},
{
"context": "\n # The website author's name\n author: \"William Hearn\"\n\n # The website author's email\n email:",
"end": 1153,
"score": 0.9998944401741028,
"start": 1140,
"tag": "NAME",
"value": "William Hearn"
},
{
"context": "\n # The website author's email\n email: \"william.hearn@statcan.gc.ca\"\n\n # Styles\n styles: [\n \"/styles",
"end": 1232,
"score": 0.9999284744262695,
"start": 1205,
"tag": "EMAIL",
"value": "william.hearn@statcan.gc.ca"
},
{
"context": " url: 'https://codeload.githubusercontent.com/twbs/bootstrap/tar.gz/master'\n tarExtractClea",
"end": 4981,
"score": 0.9315614700317383,
"start": 4977,
"tag": "USERNAME",
"value": "twbs"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew/wet-boew-drupal/7.x-1.x/README.md'\n }\n ",
"end": 5320,
"score": 0.8056877851486206,
"start": 5312,
"tag": "USERNAME",
"value": "wet-boew"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-admin/7.x-1.x/README.md'\n }",
"end": 5528,
"score": 0.7115654945373535,
"start": 5528,
"tag": "USERNAME",
"value": ""
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-admin/7.x-1.x/README.md'\n }\n ",
"end": 5533,
"score": 0.6390417814254761,
"start": 5531,
"tag": "USERNAME",
"value": "ew"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-bean/7.x-1.x/README.md'\n }\n ",
"end": 5749,
"score": 0.8667020201683044,
"start": 5737,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-breadcrumbs/7.x-1.x/README.md'\n }\n ",
"end": 5974,
"score": 0.6146948933601379,
"start": 5966,
"tag": "USERNAME",
"value": "boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-core/7.x-1.x/README.md'\n }\n ",
"end": 6192,
"score": 0.9853514432907104,
"start": 6180,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-demo/7.x-1.x/README.md'\n }\n ",
"end": 6403,
"score": 0.8852416276931763,
"start": 6391,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-deployment/7.x-1.x/README.md'\n }\n ",
"end": 6626,
"score": 0.8702717423439026,
"start": 6614,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-images/7.x-1.x/README.md'\n }\n ",
"end": 6847,
"score": 0.8373184204101562,
"start": 6835,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-language/7.x-1.x/README.md'\n }\n ",
"end": 7068,
"score": 0.8979790806770325,
"start": 7056,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-layouts/7.x-1.x/README.md'\n }\n ",
"end": 7288,
"score": 0.8721727728843689,
"start": 7276,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-menu/7.x-1.x/README.md'\n }\n ",
"end": 7502,
"score": 0.8101677298545837,
"start": 7490,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-metatag/7.x-1.x/README.md'\n }\n ",
"end": 7719,
"score": 0.9533640742301941,
"start": 7707,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-migrate/7.x-1.x/README.md'\n }\n ",
"end": 7939,
"score": 0.9277020692825317,
"start": 7927,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-pages/7.x-1.x/README.md'\n }\n ",
"end": 8155,
"score": 0.9484108686447144,
"start": 8143,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-search/7.x-1.x/README.md'\n }\n ",
"end": 8371,
"score": 0.9192696809768677,
"start": 8359,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-theme/7.x-1.x/README.md'\n }\n ",
"end": 8586,
"score": 0.9354285597801208,
"start": 8574,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-users/7.x-1.x/README.md'\n }\n ",
"end": 8800,
"score": 0.9430532455444336,
"start": 8788,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wetboew/7.x-1.x/README.md'\n }",
"end": 9012,
"score": 0.9632732272148132,
"start": 9006,
"tag": "USERNAME",
"value": "wet-bo"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-widgets/7.x-1.x/README.md'\n }\n ",
"end": 9238,
"score": 0.8539284467697144,
"start": 9226,
"tag": "USERNAME",
"value": "wet-boew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wysiwyg/7.x-1.x/README.md'\n ",
"end": 9449,
"score": 0.5384222269058228,
"start": 9449,
"tag": "USERNAME",
"value": ""
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wysiwyg/7.x-1.x/README.md'\n }\n ",
"end": 9454,
"score": 0.5538708567619324,
"start": 9454,
"tag": "USERNAME",
"value": ""
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-ember/7.x-1.x/README.md'\n }",
"end": 9665,
"score": 0.705022931098938,
"start": 9665,
"tag": "USERNAME",
"value": ""
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-ember/7.x-1.x/README.md'\n }\n ",
"end": 9674,
"score": 0.6193987727165222,
"start": 9668,
"tag": "USERNAME",
"value": "ew-wem"
},
{
"context": " url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-shiny/7.x-1.x/README.md'\n }\n ]",
"end": 10102,
"score": 0.7418254017829895,
"start": 10090,
"tag": "USERNAME",
"value": "wet-boew-wem"
}
] | docpad.coffee | wet-boew-wem/website | 0 | # The DocPad Configuration File
# Require
fsUtil = require('fs')
marked = require 'docpad-plugin-marked/node_modules/marked'
pathUtil = require('path')
# It is simply a CoffeeScript Object which is parsed by CSON
docpadConfig = {
# =================================
# Template Data
# These are variables that will be accessible via our templates
# To access one of these within our templates, refer to the FAQ: https://githubusercontent.com/bevry/docpad/wiki/FAQ
templateData:
# Specify some site properties
site:
# The production url of our website
url: "http://docs.drupalwxt.org"
# Here are some old site urls that you would like to redirect from
oldUrls: []
# The default title of our website
title: "Drupal WxT Documentation"
# The website description (for SEO)
description: """
The Web Experience Toolkit Drupal Variant documentation website.
"""
# The website keywords (for SEO) separated by commas
keywords: """
documentation, drupal, wxt, enterprise, devops
"""
# The website author's name
author: "William Hearn"
# The website author's email
email: "william.hearn@statcan.gc.ca"
# Styles
styles: [
"/styles/twitter-bootstrap.css"
"/styles/style.css"
"/styles/monokai.css"
]
# Scripts
scripts: [
"//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"
"//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"
"/vendor/twitter-bootstrap/dist/js/bootstrap.min.js"
"/scripts/script.js"
]
services:
disqus: "drupalwxt"
# -----------------------------
# Helper Functions
# Get Gravatar URL
getGravatarUrl: (email,size) ->
hash = require('crypto').createHash('md5').update(email).digest('hex')
url = "http://www.gravatar.com/avatar/#{hash}.jpg"
if size then url += "?s=#{size}"
return url
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} | #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
# Get the prepared site/document description
getPreparedDescription: ->
# if we have a document description, then we should use that, otherwise use the site's description
@document.description or @site.description
# Get the prepared site/document keywords
getPreparedKeywords: ->
# Merge the document keywords with the site keywords
@site.keywords.concat(@document.keywords or []).join(', ')
# Read File
readFile: (relativePath) ->
path = @document.fullDirPath+'/'+relativePath
result = fsUtil.readFileSync(path)
if result instanceof Error
throw result
else
return result.toString()
# Code File
codeFile: (relativePath,language) ->
language ?= pathUtil.extname(relativePath).substr(1)
contents = @readFile(relativePath)
return """<pre><code class="#{language}">#{contents}</code></pre>"""
# MarkDown File
markdownFile: (relativePath,language) ->
language ?= pathUtil.extname(relativePath).substr(1)
contents = @readFile(relativePath)
marked.setOptions({
breaks: false
gfm: true
pedantic: false
sanitize: false
tables: true
highlight: null
})
return marked(contents)
# =================================
# Collections
# These are special collections that our website makes available to us
collections:
architecture: (database) ->
database.findAllLive({tags:$has:'architecture'}, [date:-1])
concepts: (database) ->
database.findAllLive({tags:$has:'concept'}, [date:-1])
features: (database) ->
database.findAllLive({tags:$has:'feature'}, [name:1])
modules: (database) ->
database.findAllLive({tags:$has:'module'}, [name:1])
pages: (database) ->
database.findAllLive({pageOrder: $exists: true}, [pageOrder:1,title:1])
performance: (database) ->
database.findAllLive({tags:$has:'performance'}, [name:1])
posts: (database) ->
database.findAllLive({tags:$has:'post'}, [date:-1])
profiles: (database) ->
database.findAllLive({tags:$has:'profile'}, [name:1])
themes: (database) ->
database.findAllLive({tags:$has:'theme'}, [name:1])
# =================================
# Plugins
plugins:
downloader:
downloads: [
{
name: 'Twitter Bootstrap'
path: 'src/files/vendor/twitter-bootstrap'
url: 'https://codeload.githubusercontent.com/twbs/bootstrap/tar.gz/master'
tarExtractClean: true
}
]
highlightjs:
aliases:
vcl: 'perl'
sh: 'bash'
downloader:
downloads: [
{
name: 'WetKit Readme'
path: 'src/documents/wxt/tmp/wetkit.html.md'
url: 'https://raw.githubusercontent.com/wet-boew/wet-boew-drupal/7.x-1.x/README.md'
}
{
name: 'WetKit Admin Readme'
path: 'src/documents/wxt/tmp/wetkit-admin.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-admin/7.x-1.x/README.md'
}
{
name: 'WetKit Bean Readme'
path: 'src/documents/wxt/tmp/wetkit-bean.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-bean/7.x-1.x/README.md'
}
{
name: 'WetKit Breadcrumbs Readme'
path: 'src/documents/wxt/tmp/wetkit-breadcrumbs.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-breadcrumbs/7.x-1.x/README.md'
}
{
name: 'WetKit Core Readme'
path: 'src/documents/wxt/tmp/wetkit-core.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-core/7.x-1.x/README.md'
}
{
name: 'WetKit Demo Readme'
path: 'src/documents/wxt/tmp/wetkit-demo.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-demo/7.x-1.x/README.md'
}
{
name: 'WetKit Deployment Readme'
path: 'src/documents/wxt/tmp/wetkit-deployment.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-deployment/7.x-1.x/README.md'
}
{
name: 'WetKit Images Readme'
path: 'src/documents/wxt/tmp/wetkit-images.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-images/7.x-1.x/README.md'
}
{
name: 'WetKit Language Readme'
path: 'src/documents/wxt/tmp/wetkit-language.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-language/7.x-1.x/README.md'
}
{
name: 'WetKit Layout Readme'
path: 'src/documents/wxt/tmp/wetkit-layouts.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-layouts/7.x-1.x/README.md'
}
{
name: 'WetKit Menu Readme'
path: 'src/documents/wxt/tmp/wetkit-menu.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-menu/7.x-1.x/README.md'
}
{
name: 'WetKit Metatag Readme'
path: 'src/documents/wxt/tmp/wetkit-metatag.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-metatag/7.x-1.x/README.md'
}
{
name: 'WetKit Migrate Readme'
path: 'src/documents/wxt/tmp/wetkit-migrate.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-migrate/7.x-1.x/README.md'
}
{
name: 'WetKit Pages Readme'
path: 'src/documents/wxt/tmp/wetkit-pages.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-pages/7.x-1.x/README.md'
}
{
name: 'WetKit Search Readme'
path: 'src/documents/wxt/tmp/wetkit-search.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-search/7.x-1.x/README.md'
}
{
name: 'WetKit Theme Readme'
path: 'src/documents/wxt/tmp/wetkit-theme.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-theme/7.x-1.x/README.md'
}
{
name: 'WetKit Users Readme'
path: 'src/documents/wxt/tmp/wetkit-users.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-users/7.x-1.x/README.md'
}
{
name: 'WetKit WETBOEW Readme'
path: 'src/documents/wxt/tmp/wetkit-wetboew.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wetboew/7.x-1.x/README.md'
}
{
name: 'WetKit Widgets Readme'
path: 'src/documents/wxt/tmp/wetkit-widgets.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-widgets/7.x-1.x/README.md'
}
{
name: 'WetKit WYSIWYG Readme'
path: 'src/documents/wxt/tmp/wetkit-wysiwyg.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wysiwyg/7.x-1.x/README.md'
}
{
name: 'WetKit Ember Readme'
path: 'src/documents/wxt/tmp/wetkit-ember.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-ember/7.x-1.x/README.md'
}
{
name: 'WetKit Omega Readme'
path: 'src/documents/wxt/tmp/wetkit-omega.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-omega/7.x-1.x/README.md'
}
{
name: 'WetKit Shiny Readme'
path: 'src/documents/wxt/tmp/wetkit-shiny.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-shiny/7.x-1.x/README.md'
}
]
# =================================
# DocPad Events
# Here we can define handlers for events that DocPad fires
# You can find a full listing of events on the DocPad Wiki
events:
# Server Extend
# Used to add our own custom routes to the server before the docpad routes are added
serverExtend: (opts) ->
# Extract the server from the options
{server} = opts
docpad = @docpad
# As we are now running in an event,
# ensure we are using the latest copy of the docpad configuraiton
# and fetch our urls from it
latestConfig = docpad.getConfig()
oldUrls = latestConfig.templateData.site.oldUrls or []
newUrl = latestConfig.templateData.site.url
# Redirect any requests accessing one of our sites oldUrls to the new site url
server.use (req,res,next) ->
if req.headers.host in oldUrls
res.redirect(newUrl+req.url, 301)
else
next()
}
# Export our DocPad Configuration
module.exports = docpadConfig
| 152374 | # The DocPad Configuration File
# Require
fsUtil = require('fs')
marked = require 'docpad-plugin-marked/node_modules/marked'
pathUtil = require('path')
# It is simply a CoffeeScript Object which is parsed by CSON
docpadConfig = {
# =================================
# Template Data
# These are variables that will be accessible via our templates
# To access one of these within our templates, refer to the FAQ: https://githubusercontent.com/bevry/docpad/wiki/FAQ
templateData:
# Specify some site properties
site:
# The production url of our website
url: "http://docs.drupalwxt.org"
# Here are some old site urls that you would like to redirect from
oldUrls: []
# The default title of our website
title: "Drupal WxT Documentation"
# The website description (for SEO)
description: """
The Web Experience Toolkit Drupal Variant documentation website.
"""
# The website keywords (for SEO) separated by commas
keywords: """
documentation, drupal, wxt, enterprise, devops
"""
# The website author's name
author: "<NAME>"
# The website author's email
email: "<EMAIL>"
# Styles
styles: [
"/styles/twitter-bootstrap.css"
"/styles/style.css"
"/styles/monokai.css"
]
# Scripts
scripts: [
"//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"
"//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"
"/vendor/twitter-bootstrap/dist/js/bootstrap.min.js"
"/scripts/script.js"
]
services:
disqus: "drupalwxt"
# -----------------------------
# Helper Functions
# Get Gravatar URL
getGravatarUrl: (email,size) ->
hash = require('crypto').createHash('md5').update(email).digest('hex')
url = "http://www.gravatar.com/avatar/#{hash}.jpg"
if size then url += "?s=#{size}"
return url
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} | #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
# Get the prepared site/document description
getPreparedDescription: ->
# if we have a document description, then we should use that, otherwise use the site's description
@document.description or @site.description
# Get the prepared site/document keywords
getPreparedKeywords: ->
# Merge the document keywords with the site keywords
@site.keywords.concat(@document.keywords or []).join(', ')
# Read File
readFile: (relativePath) ->
path = @document.fullDirPath+'/'+relativePath
result = fsUtil.readFileSync(path)
if result instanceof Error
throw result
else
return result.toString()
# Code File
codeFile: (relativePath,language) ->
language ?= pathUtil.extname(relativePath).substr(1)
contents = @readFile(relativePath)
return """<pre><code class="#{language}">#{contents}</code></pre>"""
# MarkDown File
markdownFile: (relativePath,language) ->
language ?= pathUtil.extname(relativePath).substr(1)
contents = @readFile(relativePath)
marked.setOptions({
breaks: false
gfm: true
pedantic: false
sanitize: false
tables: true
highlight: null
})
return marked(contents)
# =================================
# Collections
# These are special collections that our website makes available to us
collections:
architecture: (database) ->
database.findAllLive({tags:$has:'architecture'}, [date:-1])
concepts: (database) ->
database.findAllLive({tags:$has:'concept'}, [date:-1])
features: (database) ->
database.findAllLive({tags:$has:'feature'}, [name:1])
modules: (database) ->
database.findAllLive({tags:$has:'module'}, [name:1])
pages: (database) ->
database.findAllLive({pageOrder: $exists: true}, [pageOrder:1,title:1])
performance: (database) ->
database.findAllLive({tags:$has:'performance'}, [name:1])
posts: (database) ->
database.findAllLive({tags:$has:'post'}, [date:-1])
profiles: (database) ->
database.findAllLive({tags:$has:'profile'}, [name:1])
themes: (database) ->
database.findAllLive({tags:$has:'theme'}, [name:1])
# =================================
# Plugins
plugins:
downloader:
downloads: [
{
name: 'Twitter Bootstrap'
path: 'src/files/vendor/twitter-bootstrap'
url: 'https://codeload.githubusercontent.com/twbs/bootstrap/tar.gz/master'
tarExtractClean: true
}
]
highlightjs:
aliases:
vcl: 'perl'
sh: 'bash'
downloader:
downloads: [
{
name: 'WetKit Readme'
path: 'src/documents/wxt/tmp/wetkit.html.md'
url: 'https://raw.githubusercontent.com/wet-boew/wet-boew-drupal/7.x-1.x/README.md'
}
{
name: 'WetKit Admin Readme'
path: 'src/documents/wxt/tmp/wetkit-admin.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-admin/7.x-1.x/README.md'
}
{
name: 'WetKit Bean Readme'
path: 'src/documents/wxt/tmp/wetkit-bean.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-bean/7.x-1.x/README.md'
}
{
name: 'WetKit Breadcrumbs Readme'
path: 'src/documents/wxt/tmp/wetkit-breadcrumbs.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-breadcrumbs/7.x-1.x/README.md'
}
{
name: 'WetKit Core Readme'
path: 'src/documents/wxt/tmp/wetkit-core.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-core/7.x-1.x/README.md'
}
{
name: 'WetKit Demo Readme'
path: 'src/documents/wxt/tmp/wetkit-demo.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-demo/7.x-1.x/README.md'
}
{
name: 'WetKit Deployment Readme'
path: 'src/documents/wxt/tmp/wetkit-deployment.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-deployment/7.x-1.x/README.md'
}
{
name: 'WetKit Images Readme'
path: 'src/documents/wxt/tmp/wetkit-images.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-images/7.x-1.x/README.md'
}
{
name: 'WetKit Language Readme'
path: 'src/documents/wxt/tmp/wetkit-language.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-language/7.x-1.x/README.md'
}
{
name: 'WetKit Layout Readme'
path: 'src/documents/wxt/tmp/wetkit-layouts.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-layouts/7.x-1.x/README.md'
}
{
name: 'WetKit Menu Readme'
path: 'src/documents/wxt/tmp/wetkit-menu.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-menu/7.x-1.x/README.md'
}
{
name: 'WetKit Metatag Readme'
path: 'src/documents/wxt/tmp/wetkit-metatag.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-metatag/7.x-1.x/README.md'
}
{
name: 'WetKit Migrate Readme'
path: 'src/documents/wxt/tmp/wetkit-migrate.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-migrate/7.x-1.x/README.md'
}
{
name: 'WetKit Pages Readme'
path: 'src/documents/wxt/tmp/wetkit-pages.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-pages/7.x-1.x/README.md'
}
{
name: 'WetKit Search Readme'
path: 'src/documents/wxt/tmp/wetkit-search.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-search/7.x-1.x/README.md'
}
{
name: 'WetKit Theme Readme'
path: 'src/documents/wxt/tmp/wetkit-theme.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-theme/7.x-1.x/README.md'
}
{
name: 'WetKit Users Readme'
path: 'src/documents/wxt/tmp/wetkit-users.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-users/7.x-1.x/README.md'
}
{
name: 'WetKit WETBOEW Readme'
path: 'src/documents/wxt/tmp/wetkit-wetboew.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wetboew/7.x-1.x/README.md'
}
{
name: 'WetKit Widgets Readme'
path: 'src/documents/wxt/tmp/wetkit-widgets.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-widgets/7.x-1.x/README.md'
}
{
name: 'WetKit WYSIWYG Readme'
path: 'src/documents/wxt/tmp/wetkit-wysiwyg.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wysiwyg/7.x-1.x/README.md'
}
{
name: 'WetKit Ember Readme'
path: 'src/documents/wxt/tmp/wetkit-ember.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-ember/7.x-1.x/README.md'
}
{
name: 'WetKit Omega Readme'
path: 'src/documents/wxt/tmp/wetkit-omega.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-omega/7.x-1.x/README.md'
}
{
name: 'WetKit Shiny Readme'
path: 'src/documents/wxt/tmp/wetkit-shiny.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-shiny/7.x-1.x/README.md'
}
]
# =================================
# DocPad Events
# Here we can define handlers for events that DocPad fires
# You can find a full listing of events on the DocPad Wiki
events:
# Server Extend
# Used to add our own custom routes to the server before the docpad routes are added
serverExtend: (opts) ->
# Extract the server from the options
{server} = opts
docpad = @docpad
# As we are now running in an event,
# ensure we are using the latest copy of the docpad configuraiton
# and fetch our urls from it
latestConfig = docpad.getConfig()
oldUrls = latestConfig.templateData.site.oldUrls or []
newUrl = latestConfig.templateData.site.url
# Redirect any requests accessing one of our sites oldUrls to the new site url
server.use (req,res,next) ->
if req.headers.host in oldUrls
res.redirect(newUrl+req.url, 301)
else
next()
}
# Export our DocPad Configuration
module.exports = docpadConfig
| true | # The DocPad Configuration File
# Require
fsUtil = require('fs')
marked = require 'docpad-plugin-marked/node_modules/marked'
pathUtil = require('path')
# It is simply a CoffeeScript Object which is parsed by CSON
docpadConfig = {
# =================================
# Template Data
# These are variables that will be accessible via our templates
# To access one of these within our templates, refer to the FAQ: https://githubusercontent.com/bevry/docpad/wiki/FAQ
templateData:
# Specify some site properties
site:
# The production url of our website
url: "http://docs.drupalwxt.org"
# Here are some old site urls that you would like to redirect from
oldUrls: []
# The default title of our website
title: "Drupal WxT Documentation"
# The website description (for SEO)
description: """
The Web Experience Toolkit Drupal Variant documentation website.
"""
# The website keywords (for SEO) separated by commas
keywords: """
documentation, drupal, wxt, enterprise, devops
"""
# The website author's name
author: "PI:NAME:<NAME>END_PI"
# The website author's email
email: "PI:EMAIL:<EMAIL>END_PI"
# Styles
styles: [
"/styles/twitter-bootstrap.css"
"/styles/style.css"
"/styles/monokai.css"
]
# Scripts
scripts: [
"//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"
"//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"
"/vendor/twitter-bootstrap/dist/js/bootstrap.min.js"
"/scripts/script.js"
]
services:
disqus: "drupalwxt"
# -----------------------------
# Helper Functions
# Get Gravatar URL
getGravatarUrl: (email,size) ->
hash = require('crypto').createHash('md5').update(email).digest('hex')
url = "http://www.gravatar.com/avatar/#{hash}.jpg"
if size then url += "?s=#{size}"
return url
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} | #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
# Get the prepared site/document description
getPreparedDescription: ->
# if we have a document description, then we should use that, otherwise use the site's description
@document.description or @site.description
# Get the prepared site/document keywords
getPreparedKeywords: ->
# Merge the document keywords with the site keywords
@site.keywords.concat(@document.keywords or []).join(', ')
# Read File
readFile: (relativePath) ->
path = @document.fullDirPath+'/'+relativePath
result = fsUtil.readFileSync(path)
if result instanceof Error
throw result
else
return result.toString()
# Code File
codeFile: (relativePath,language) ->
language ?= pathUtil.extname(relativePath).substr(1)
contents = @readFile(relativePath)
return """<pre><code class="#{language}">#{contents}</code></pre>"""
# MarkDown File
markdownFile: (relativePath,language) ->
language ?= pathUtil.extname(relativePath).substr(1)
contents = @readFile(relativePath)
marked.setOptions({
breaks: false
gfm: true
pedantic: false
sanitize: false
tables: true
highlight: null
})
return marked(contents)
# =================================
# Collections
# These are special collections that our website makes available to us
collections:
architecture: (database) ->
database.findAllLive({tags:$has:'architecture'}, [date:-1])
concepts: (database) ->
database.findAllLive({tags:$has:'concept'}, [date:-1])
features: (database) ->
database.findAllLive({tags:$has:'feature'}, [name:1])
modules: (database) ->
database.findAllLive({tags:$has:'module'}, [name:1])
pages: (database) ->
database.findAllLive({pageOrder: $exists: true}, [pageOrder:1,title:1])
performance: (database) ->
database.findAllLive({tags:$has:'performance'}, [name:1])
posts: (database) ->
database.findAllLive({tags:$has:'post'}, [date:-1])
profiles: (database) ->
database.findAllLive({tags:$has:'profile'}, [name:1])
themes: (database) ->
database.findAllLive({tags:$has:'theme'}, [name:1])
# =================================
# Plugins
plugins:
downloader:
downloads: [
{
name: 'Twitter Bootstrap'
path: 'src/files/vendor/twitter-bootstrap'
url: 'https://codeload.githubusercontent.com/twbs/bootstrap/tar.gz/master'
tarExtractClean: true
}
]
highlightjs:
aliases:
vcl: 'perl'
sh: 'bash'
downloader:
downloads: [
{
name: 'WetKit Readme'
path: 'src/documents/wxt/tmp/wetkit.html.md'
url: 'https://raw.githubusercontent.com/wet-boew/wet-boew-drupal/7.x-1.x/README.md'
}
{
name: 'WetKit Admin Readme'
path: 'src/documents/wxt/tmp/wetkit-admin.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-admin/7.x-1.x/README.md'
}
{
name: 'WetKit Bean Readme'
path: 'src/documents/wxt/tmp/wetkit-bean.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-bean/7.x-1.x/README.md'
}
{
name: 'WetKit Breadcrumbs Readme'
path: 'src/documents/wxt/tmp/wetkit-breadcrumbs.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-breadcrumbs/7.x-1.x/README.md'
}
{
name: 'WetKit Core Readme'
path: 'src/documents/wxt/tmp/wetkit-core.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-core/7.x-1.x/README.md'
}
{
name: 'WetKit Demo Readme'
path: 'src/documents/wxt/tmp/wetkit-demo.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-demo/7.x-1.x/README.md'
}
{
name: 'WetKit Deployment Readme'
path: 'src/documents/wxt/tmp/wetkit-deployment.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-deployment/7.x-1.x/README.md'
}
{
name: 'WetKit Images Readme'
path: 'src/documents/wxt/tmp/wetkit-images.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-images/7.x-1.x/README.md'
}
{
name: 'WetKit Language Readme'
path: 'src/documents/wxt/tmp/wetkit-language.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-language/7.x-1.x/README.md'
}
{
name: 'WetKit Layout Readme'
path: 'src/documents/wxt/tmp/wetkit-layouts.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-layouts/7.x-1.x/README.md'
}
{
name: 'WetKit Menu Readme'
path: 'src/documents/wxt/tmp/wetkit-menu.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-menu/7.x-1.x/README.md'
}
{
name: 'WetKit Metatag Readme'
path: 'src/documents/wxt/tmp/wetkit-metatag.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-metatag/7.x-1.x/README.md'
}
{
name: 'WetKit Migrate Readme'
path: 'src/documents/wxt/tmp/wetkit-migrate.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-migrate/7.x-1.x/README.md'
}
{
name: 'WetKit Pages Readme'
path: 'src/documents/wxt/tmp/wetkit-pages.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-pages/7.x-1.x/README.md'
}
{
name: 'WetKit Search Readme'
path: 'src/documents/wxt/tmp/wetkit-search.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-search/7.x-1.x/README.md'
}
{
name: 'WetKit Theme Readme'
path: 'src/documents/wxt/tmp/wetkit-theme.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-theme/7.x-1.x/README.md'
}
{
name: 'WetKit Users Readme'
path: 'src/documents/wxt/tmp/wetkit-users.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-users/7.x-1.x/README.md'
}
{
name: 'WetKit WETBOEW Readme'
path: 'src/documents/wxt/tmp/wetkit-wetboew.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wetboew/7.x-1.x/README.md'
}
{
name: 'WetKit Widgets Readme'
path: 'src/documents/wxt/tmp/wetkit-widgets.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-widgets/7.x-1.x/README.md'
}
{
name: 'WetKit WYSIWYG Readme'
path: 'src/documents/wxt/tmp/wetkit-wysiwyg.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-wysiwyg/7.x-1.x/README.md'
}
{
name: 'WetKit Ember Readme'
path: 'src/documents/wxt/tmp/wetkit-ember.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-ember/7.x-1.x/README.md'
}
{
name: 'WetKit Omega Readme'
path: 'src/documents/wxt/tmp/wetkit-omega.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-omega/7.x-1.x/README.md'
}
{
name: 'WetKit Shiny Readme'
path: 'src/documents/wxt/tmp/wetkit-shiny.html.md'
url: 'https://raw.githubusercontent.com/wet-boew-wem/wetkit-shiny/7.x-1.x/README.md'
}
]
# =================================
# DocPad Events
# Here we can define handlers for events that DocPad fires
# You can find a full listing of events on the DocPad Wiki
events:
# Server Extend
# Used to add our own custom routes to the server before the docpad routes are added
serverExtend: (opts) ->
# Extract the server from the options
{server} = opts
docpad = @docpad
# As we are now running in an event,
# ensure we are using the latest copy of the docpad configuraiton
# and fetch our urls from it
latestConfig = docpad.getConfig()
oldUrls = latestConfig.templateData.site.oldUrls or []
newUrl = latestConfig.templateData.site.url
# Redirect any requests accessing one of our sites oldUrls to the new site url
server.use (req,res,next) ->
if req.headers.host in oldUrls
res.redirect(newUrl+req.url, 301)
else
next()
}
# Export our DocPad Configuration
module.exports = docpadConfig
|
[
{
"context": " \"prettyPrint()\",\n A href: \"https://github.com/jed/domo\",\n IMG\n class: \"github\"\n ",
"end": 2242,
"score": 0.9997243881225586,
"start": 2239,
"tag": "USERNAME",
"value": "jed"
},
{
"context": "f dōmo, just view \", (A href: \"https://github.com/jed/domo/blob/master/docs/index.coffee\", \"the source ",
"end": 4166,
"score": 0.9996806383132935,
"start": 4163,
"tag": "USERNAME",
"value": "jed"
},
{
"context": "also ships with a \", (A href: \"https://github.com/jed/domo/blob/master/lib/document.js\", \"window.docume",
"end": 12752,
"score": 0.9997284412384033,
"start": 12749,
"tag": "USERNAME",
"value": "jed"
},
{
"context": "\n )\n \"\"\"\n\n P SMALL \"Copyright © Jed Schmidt 2012\"\n\n SCRIPT src: \"docs/vendor/prettify.js\"\n",
"end": 17632,
"score": 0.9998615384101868,
"start": 17621,
"tag": "NAME",
"value": "Jed Schmidt"
}
] | docs/index.coffee | jed/domo | 29 | boxShadow = (values) ->
MozBoxShadow : values
WebkitBoxShadow : values
boxShadow : values
HTML lang: "en",
HEAD {},
TITLE "dōmo: Markup, style, and code in one language."
LINK
rel: "stylesheet"
type: "text/css"
href: "//fonts.googleapis.com/css?family=Titillium+Web:900&subset=latin-ext"
STYLE type: "text/css",
(STYLE.on ".#{key}", {color} for key, color of {
pln: "#000", str: "#080", kwd: "#008", com: "#800", typ: "#606"
lit: "#066", pun: "#660", opn: "#660", clo: "#660", tag: "#008"
atn: "#606", atv: "#080", dec: "#606", var: "#606", fun: "red"
})
STYLE type: "text/css",
STYLE.on ".prettyprint" , padding: "2px"
STYLE.on ".linenums" , marginTop: "0 auto 0"
STYLE.on (".L#{n}" for n in [0..8]) , listStyleType: "none"
STYLE.on (".L#{n}" for n in [1..9] by 2) , background: "#eee"
STYLE type: "text/css",
STYLE.on "body"
background: "#f6f6f6"
color: "#222"
fontFamily: "Helvetica, Arial, sans-serif"
fontSize: "18px"
lineHeight: "1.5"
margin: "0 0 2em"
padding: 0
STYLE.on ["h1", "h2", "h3", "h4", "p", "ul", "ol", "pre", ".narrow"],
width: "750px"
margin: "1em auto"
display: "block"
STYLE.on "h1"
margin: "30px auto -60px auto"
fontSize: "150px"
fontFamily: "Titillium Web"
STYLE.on "a"
color: "#596C86"
STYLE.on "a:visited"
color: "#582525"
STYLE.on ".sub"
background: "#fff"
margin: "1em 0 0"
padding: "1em 0"
boxShadow "1px 1px 6px #ccc"
STYLE.on ["pre", "code"],
fontSize: "0.9em"
fontFamily: "Monaco, Courier New, monospace"
STYLE.on ".github"
position: "absolute"
top: 0
right: 0
border: 0
STYLE.on ".why-domo"
STYLE.on "li"
marginTop: "15px"
STYLE.on "code.inline"
margin: "0 2px"
padding: "0px 5px"
border: "1px solid #eee"
backgroundColor: "#fff"
borderRadius: "3px"
BODY onload: "prettyPrint()",
A href: "https://github.com/jed/domo",
IMG
class: "github"
src: "//s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"
alt: "Fork me on GitHub"
H1 "dōmo"
H2 "Markup, style, and code in one language."
P {},
"dōmo lets you write ", (A href: "#html", "HTML markup"), " and ", (A href: "#css", "CSS styles"), " in JavaScript syntax, in the browser and ", (A href: "#server", "on the server"), ". "
"dōmo is a simpler, easier, and more reliable alternative to template engines and CSS pre-processors, and works well with all the tools you already use."
P {},
"You can download ", (A href: "http://domo-js.com/lib/domo.js", "dōmo for the browser"), " (under ", (B "#{Math.ceil(domo.stats.size / 100) / 10}kb"), " minizipped), or install ", (A href: "https://npmjs.org/package/domo", "dōmo for node.js"), "."
H3 "Example"
P {},
"Here's a simple, self-contained example using dōmo in the browser. "
"This code replaces the existing root HTML element with its own DOM tree, using a simple opacity function as a CSS mixin."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "html", """
<!doctype html>
<script src="domo.js"><\/script>
<script>
function opacity(pct) {
return {opacity: String(pct / 100), filter: "alpha(opacity=" + pct + ")"}
}
HTML({lang: "en"},
HEAD(
TITLE("Welcome to dōmo"),
STYLE({type: "text/css"},
STYLE.on("body", {textAlign: "center", fontSize: 50}),
STYLE.on("h1", opacity(50), {background: "#000", color: "#fff"})
)
),
BODY(H1("Welcome to dōmo"))
)
<\/script>
"""
P "If you'd like to see a larger, real-world use of dōmo, just view ", (A href: "https://github.com/jed/domo/blob/master/docs/index.coffee", "the source of this very page"), "."
A name: "why"
H3 "Why?"
P "We all know CSS. We all know HTML. We mostly agree that neither is powerful enough to build modern web apps, hence the explosion of ", (A href: "http://lesscss.org", "CSS pre-processors"), " and ", (A href: "http://haml.info", "templating engines"), "."
P "If we're building tools to improve browser technologies like CSS and HTML, let's build them using another browser technology: JavaScript. Instead of adding incompatible extensions to CSS and HTML, let's first port them to a general-purpose language and do the extending there, where at least our tools can interoperate."
P "dōmo replaces the syntax of CSS and HTML syntax with JavaScript, leaving the semantics the same. You don't have to learn ad-hoc, underpowered syntax for looping or arithmetic or functions in your styles or markup, you can just use what you already know in JavaScript."
P "This means you can decouple your architecture from arbitrary implementation details, and render your app wherever it makes the most sense: on the server, on the browser, or both."
A name: "html"
H3 "Using dōmo instead of HTML"
P "dōmo lets you write concise JavaScript views for dynamic content, without having to choose between the lesser evil of verbose DOM code and embedding/compiling/escaping overhead of string templates."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var withDomo = A({href: "http://domo-js.com"}, "Learn about dōmo")
var withoutDomo = document.createElement("a")
withoutDomo.setAttribute("href", "http://domo-js.com")
withoutDomo.appendChild(document.createTextNode("Learn about dōmo"))
alert(withDomo.outerHTML == withoutDomo.outerHTML)
"""
P "dōmo's API is simple: it provides one function for ", (A href: "https://developer.mozilla.org/en-US/docs/HTML/HTML5/HTML5_element_list", "every standard HTML5 element"), ":"
H4 "domo.", (EM "elementName"), "(", (EM "attributes"), ", ", (EM "childNodes..."), ")"
P "Each function returns a namesake DOM element, and be accessed by UPPERCASE or lowercase name as a member of the ", (CODE "domo"), " object. These functions can also be ", (A href: "#convenience", "exported to the global namespace"), " for convenience by calling ", (CODE "domo.global(true)"), ", which is done automatically in browsers and other non-commonJS environments."
P {},
"The ", (EM "attributes"), " argument is an optional object that maps attribute names to their values. For easier use with JavaScript object literals, all camelCased attribute names are lowercased and hyphenated, so that names like ", (CODE class: "inline", "httpEquiv"), " and ", (CODE class: "inline", "http-equiv"), " are identical."
P {},
"The ", (EM "childNodes"), " argument is an optional list of children to be appended to the element. Any child that is already a node (has a ", (CODE class: "inline", "nodeType"), " property) is appended as-is, or converted to a text node otherwise. This allows you to append nodes generated elsewhere, to facilitate DOM composition. "
"Additional arguments can also be specified, in which case they will be flattened into a single list of children."
P "Note that in addition to returning the generated element, the ", (CODE "HTML"), ", ", (CODE "HEAD"), ", and ", (CODE "BODY"), " functions will also replace the existing element in the current document."
P "dōmo provides functions for the following HTML5 DOM elements out of the box:"
DIV class: "sub",
CODE class: "narrow", "A ABBR ACRONYM ADDRESS AREA ARTICLE ASIDE AUDIO B BDI BDO BIG BLOCKQUOTE BODY BR BUTTON CANVAS CAPTION CITE CODE COL COLGROUP COMMAND DATALIST DD DEL DETAILS DFN DIV DL DT EM EMBED FIELDSET FIGCAPTION FIGURE FOOTER FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HEADER HGROUP HR HTML I IFRAME IMG INPUT INS KBD KEYGEN LABEL LEGEND LI LINK MAP MARK META METER NAV NOSCRIPT OBJECT OL OPTGROUP OPTION OUTPUT P PARAM PRE PROGRESS Q RP RT RUBY SAMP SCRIPT SECTION SELECT SMALL SOURCE SPAN SPLIT STRONG STYLE SUB SUMMARY SUP TABLE TBODY TD TEXTAREA TFOOT TH THEAD TIME TITLE TR TRACK TT UL VAR VIDEO WBR"
P "If you need to use non-standard or custom HTML elements outside those provided by dōmo, pass the ", (EM "nodeName"), " of the element as the first argument of the ", (CODE style: "inline", "domo.ELEMENT"), " function:"
H4 "domo.ELEMENT(", (EM "nodeName"), ", ", (EM "attributes"), ", ", (EM "childNodes..."), ")"
P "Or if you need DOM comments, just use ", (CODE "domo.COMMENT"), " with the specified node value:"
H4 "domo.COMMENT(", (EM "nodeValue"), ")"
P "But dōmo isn't just limited to markup..."
A name: "css"
H3 "Using dōmo instead of CSS"
P "dōmo also lets you write CSS rules in JavaScript just as you would in CSS, by specifying a selector and style block per rule."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var styleSheet =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"}),
STYLE.on("*", {margin: 0, padding: 0})
)
alert(styleSheet.innerHTML == "a{color:red;}\\n*{margin:0px;padding:0px;}\\n")
"""
P "dōmo exposes CSS generation through a single function, attached to ", (CODE "domo.STYLE"), ":"
H4 "domo.STYLE.on(", (EM "selector"), ", ", (EM "properties..."), ")"
P "This generates the text source for a CSS rule, any number of which can be included in a stylesheet."
P {},
"The ", (EM "selector"), " is a string, ", "and the ", (EM "properties"), " are an object mapping property names to their values. "
"As with DOM attributes, all camelCased attribute names are lowercased and hyphenated for easier use with JavaScript object literals."
"If multiple property objects are specified, they are rolled into a single object."
P {},
"The interesting thing about using JavaScript to render CSS is that you have the full power of the language to make your stylesheets dynamic. "
"This means you can use plain old JavaScript functions to achieve the same rich CSS variables, mixins, operations, and functions that something like ", (A href: "http://lesscss.org/", "LESS"), " would provide, without any new syntax or compilation overhead, like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var blue = "#3B5998"
var gray = "#3B3B3B"
var defaultRadius = 10
function roundedCorners(radius) {
return {
borderRadius : radius,
WebkitBorderRadius : radius,
MozBorderRadius : radius
}
}
var styleSheet =
STYLE({type: "text/css"},
STYLE.on("h2", {color: gray}, roundedCorners(defaultRadius)),
STYLE.on("h1", {color: blue}, roundedCorners(defaultRadius * 2))
)
"""
P "dōmo also lets you nest rule declarations within other rule declarations, to help keep your related style declarations together:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var nestedStyles =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"},
STYLE.on("img", {borderWidth: 0})
)
)
var normalStyles =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"}),
STYLE.on("a img", {borderWidth: 0})
)
alert(nestedStyles.innerHTML == normalStyles.innerHTML)
"""
P {},
"Generating your styles on the client means that you don't need to ship redundant vendor-prefixed properties: you know the exact vendor at runtime. "
"And since the source of a stylesheet with multiple rules is fully concatenated before the DOM node is even created, the overhead in generating styles on the client is minimal. "
"If this is still a performance concern, you can move the code to the server and use a ", (CODE "LINK"), "element just as with server-side CSS pre-processors. It's your choice."
A name: "server"
H3 "Using dōmo on the server"
P {},
"dōmo really shines when used to build DOM code on the client. "
"But since you'll likely need to render an HTML client to run dōmo in the first place, dōmo also ships with a ", (A href: "https://github.com/jed/domo/blob/master/lib/document.js", "window.document shim"), " that mocks just enough of the DOM API to render HTML. "
P {},
"Using dōmo on the server is the same as that for the client; just ", (CODE class: "inline", "require('domo')"), " create a DOM, and use the ", (CODE class: "inline", "outerHTML"), " property to serialize it into HTML. "
"dōmo also adds a top-level ", (CODE class: "inline", "DOCUMENT"), " function that creates a doctype'd HTML document, allowing you to render HTML from an HTTP server like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
require("domo").global() // pollution is opt-in on CommonJS environments
var http = require("http")
http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"})
res.end(
DOCUMENT(
HTML({lang: "en"},
BODY("You accessed ", req.url, " at ", new Date)
)
).outerHTML
)
}).listen(80)
"""
A name: "convenience"
H3 "Convenience versus cleanliness"
P {},
(CODE class: "inline", "domo.global(true)"), " can be called to export all of dōmo's functions to the global object, so that you can call them without using the ", (CODE class: "inline", "domo"), " namespace. "
"This allows dōmo to mimic an in-code DSL, and given that only uppercase key names are exported, usually won't conflict with existing code. "
"Note that this is auto-executed by default in the browser and other non-CommonJS environments, and opt-in otherwise."
P {},
"However, if you're not cool with polluting the global scope, you still have some options. "
"Stash a reference to the ", (CODE class: "inline", "domo"), " object by calling ", (CODE class: "inline", "domo.global(false)"), " immediately after the dōmo script is loaded, like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "html", """
<script src="domo.js"><\/script>
<script>window.domo = domo.global(false)<\/script>
"""
P "This does two things:"
OL {},
LI "It reverts the global object to its original state (much like jQuery's ", CODE(".noConflict()"), " method)."
LI "It returns the ", (CODE class: "inline", "domo"), " object, which you can then assign for subsequent use."
P "(Note that ", (CODE class: "inline", "domo.global(false)"), " and ", (CODE class: "inline", "domo.global(true)"), " are idempotent, and can be called multiple times to extend and unextend the global object.)"
P "Once you have a reference to the ", (CODE class: "inline", "domo"), " object, you have some options about how to access its functions:"
H4 "Access them directly as ", (CODE class: "inline", "domo"), " object members."
P "This is safe, but a little verbose:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
domo = domo.global(false)
domo.HTML(
domo.HEAD(domo.TITLE("Hello, world.")),
domo.BODY("Hello, world.")
)
"""
H4 "Assign them to local variables"
P {},
"Since all dōmo functions are already bound to the current document object, they don't need to be called as methods. "
"This is especially nice if you only use a few DOM element types, and your flavor of JavaScript supports destructuring, like ", (A href: "http://coffeescript.org/#destructuring", "CoffeeScript"), " or ", (A href: "http://wiki.ecmascript.org/doku.php?id=harmony:destructuring", "ES6"), "."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
{HTML, HEAD, TITLE, BODY} = domo.global(false)
HTML(
HEAD(TITLE("Hello, world.")),
BODY("Hello, world.")
)
"""
H4 "Access them using the oft-maligned ", (CODE class: "inline", "with"), " statement."
P {},
"Don't just cargo cult ", (A href: "http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/", "Crockford"), ", ", A(href: "http://www.youtube.com/watch?v=MFtijdklZDo", "use what JavaScript gives you"), ". "
"As long as you're not assigning members or declaring functions, ", (A {href: "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with"}, "the ", (CODE class: "inline", "with"), " statement"), " is a very elegant way of temporarily importing a namespace:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
domo = domo.global(false)
with (domo)
HTML(
HEAD(TITLE("Hello, world.")),
BODY("Hello, world.")
)
"""
P SMALL "Copyright © Jed Schmidt 2012"
SCRIPT src: "docs/vendor/prettify.js"
| 221876 | boxShadow = (values) ->
MozBoxShadow : values
WebkitBoxShadow : values
boxShadow : values
HTML lang: "en",
HEAD {},
TITLE "dōmo: Markup, style, and code in one language."
LINK
rel: "stylesheet"
type: "text/css"
href: "//fonts.googleapis.com/css?family=Titillium+Web:900&subset=latin-ext"
STYLE type: "text/css",
(STYLE.on ".#{key}", {color} for key, color of {
pln: "#000", str: "#080", kwd: "#008", com: "#800", typ: "#606"
lit: "#066", pun: "#660", opn: "#660", clo: "#660", tag: "#008"
atn: "#606", atv: "#080", dec: "#606", var: "#606", fun: "red"
})
STYLE type: "text/css",
STYLE.on ".prettyprint" , padding: "2px"
STYLE.on ".linenums" , marginTop: "0 auto 0"
STYLE.on (".L#{n}" for n in [0..8]) , listStyleType: "none"
STYLE.on (".L#{n}" for n in [1..9] by 2) , background: "#eee"
STYLE type: "text/css",
STYLE.on "body"
background: "#f6f6f6"
color: "#222"
fontFamily: "Helvetica, Arial, sans-serif"
fontSize: "18px"
lineHeight: "1.5"
margin: "0 0 2em"
padding: 0
STYLE.on ["h1", "h2", "h3", "h4", "p", "ul", "ol", "pre", ".narrow"],
width: "750px"
margin: "1em auto"
display: "block"
STYLE.on "h1"
margin: "30px auto -60px auto"
fontSize: "150px"
fontFamily: "Titillium Web"
STYLE.on "a"
color: "#596C86"
STYLE.on "a:visited"
color: "#582525"
STYLE.on ".sub"
background: "#fff"
margin: "1em 0 0"
padding: "1em 0"
boxShadow "1px 1px 6px #ccc"
STYLE.on ["pre", "code"],
fontSize: "0.9em"
fontFamily: "Monaco, Courier New, monospace"
STYLE.on ".github"
position: "absolute"
top: 0
right: 0
border: 0
STYLE.on ".why-domo"
STYLE.on "li"
marginTop: "15px"
STYLE.on "code.inline"
margin: "0 2px"
padding: "0px 5px"
border: "1px solid #eee"
backgroundColor: "#fff"
borderRadius: "3px"
BODY onload: "prettyPrint()",
A href: "https://github.com/jed/domo",
IMG
class: "github"
src: "//s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"
alt: "Fork me on GitHub"
H1 "dōmo"
H2 "Markup, style, and code in one language."
P {},
"dōmo lets you write ", (A href: "#html", "HTML markup"), " and ", (A href: "#css", "CSS styles"), " in JavaScript syntax, in the browser and ", (A href: "#server", "on the server"), ". "
"dōmo is a simpler, easier, and more reliable alternative to template engines and CSS pre-processors, and works well with all the tools you already use."
P {},
"You can download ", (A href: "http://domo-js.com/lib/domo.js", "dōmo for the browser"), " (under ", (B "#{Math.ceil(domo.stats.size / 100) / 10}kb"), " minizipped), or install ", (A href: "https://npmjs.org/package/domo", "dōmo for node.js"), "."
H3 "Example"
P {},
"Here's a simple, self-contained example using dōmo in the browser. "
"This code replaces the existing root HTML element with its own DOM tree, using a simple opacity function as a CSS mixin."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "html", """
<!doctype html>
<script src="domo.js"><\/script>
<script>
function opacity(pct) {
return {opacity: String(pct / 100), filter: "alpha(opacity=" + pct + ")"}
}
HTML({lang: "en"},
HEAD(
TITLE("Welcome to dōmo"),
STYLE({type: "text/css"},
STYLE.on("body", {textAlign: "center", fontSize: 50}),
STYLE.on("h1", opacity(50), {background: "#000", color: "#fff"})
)
),
BODY(H1("Welcome to dōmo"))
)
<\/script>
"""
P "If you'd like to see a larger, real-world use of dōmo, just view ", (A href: "https://github.com/jed/domo/blob/master/docs/index.coffee", "the source of this very page"), "."
A name: "why"
H3 "Why?"
P "We all know CSS. We all know HTML. We mostly agree that neither is powerful enough to build modern web apps, hence the explosion of ", (A href: "http://lesscss.org", "CSS pre-processors"), " and ", (A href: "http://haml.info", "templating engines"), "."
P "If we're building tools to improve browser technologies like CSS and HTML, let's build them using another browser technology: JavaScript. Instead of adding incompatible extensions to CSS and HTML, let's first port them to a general-purpose language and do the extending there, where at least our tools can interoperate."
P "dōmo replaces the syntax of CSS and HTML syntax with JavaScript, leaving the semantics the same. You don't have to learn ad-hoc, underpowered syntax for looping or arithmetic or functions in your styles or markup, you can just use what you already know in JavaScript."
P "This means you can decouple your architecture from arbitrary implementation details, and render your app wherever it makes the most sense: on the server, on the browser, or both."
A name: "html"
H3 "Using dōmo instead of HTML"
P "dōmo lets you write concise JavaScript views for dynamic content, without having to choose between the lesser evil of verbose DOM code and embedding/compiling/escaping overhead of string templates."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var withDomo = A({href: "http://domo-js.com"}, "Learn about dōmo")
var withoutDomo = document.createElement("a")
withoutDomo.setAttribute("href", "http://domo-js.com")
withoutDomo.appendChild(document.createTextNode("Learn about dōmo"))
alert(withDomo.outerHTML == withoutDomo.outerHTML)
"""
P "dōmo's API is simple: it provides one function for ", (A href: "https://developer.mozilla.org/en-US/docs/HTML/HTML5/HTML5_element_list", "every standard HTML5 element"), ":"
H4 "domo.", (EM "elementName"), "(", (EM "attributes"), ", ", (EM "childNodes..."), ")"
P "Each function returns a namesake DOM element, and be accessed by UPPERCASE or lowercase name as a member of the ", (CODE "domo"), " object. These functions can also be ", (A href: "#convenience", "exported to the global namespace"), " for convenience by calling ", (CODE "domo.global(true)"), ", which is done automatically in browsers and other non-commonJS environments."
P {},
"The ", (EM "attributes"), " argument is an optional object that maps attribute names to their values. For easier use with JavaScript object literals, all camelCased attribute names are lowercased and hyphenated, so that names like ", (CODE class: "inline", "httpEquiv"), " and ", (CODE class: "inline", "http-equiv"), " are identical."
P {},
"The ", (EM "childNodes"), " argument is an optional list of children to be appended to the element. Any child that is already a node (has a ", (CODE class: "inline", "nodeType"), " property) is appended as-is, or converted to a text node otherwise. This allows you to append nodes generated elsewhere, to facilitate DOM composition. "
"Additional arguments can also be specified, in which case they will be flattened into a single list of children."
P "Note that in addition to returning the generated element, the ", (CODE "HTML"), ", ", (CODE "HEAD"), ", and ", (CODE "BODY"), " functions will also replace the existing element in the current document."
P "dōmo provides functions for the following HTML5 DOM elements out of the box:"
DIV class: "sub",
CODE class: "narrow", "A ABBR ACRONYM ADDRESS AREA ARTICLE ASIDE AUDIO B BDI BDO BIG BLOCKQUOTE BODY BR BUTTON CANVAS CAPTION CITE CODE COL COLGROUP COMMAND DATALIST DD DEL DETAILS DFN DIV DL DT EM EMBED FIELDSET FIGCAPTION FIGURE FOOTER FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HEADER HGROUP HR HTML I IFRAME IMG INPUT INS KBD KEYGEN LABEL LEGEND LI LINK MAP MARK META METER NAV NOSCRIPT OBJECT OL OPTGROUP OPTION OUTPUT P PARAM PRE PROGRESS Q RP RT RUBY SAMP SCRIPT SECTION SELECT SMALL SOURCE SPAN SPLIT STRONG STYLE SUB SUMMARY SUP TABLE TBODY TD TEXTAREA TFOOT TH THEAD TIME TITLE TR TRACK TT UL VAR VIDEO WBR"
P "If you need to use non-standard or custom HTML elements outside those provided by dōmo, pass the ", (EM "nodeName"), " of the element as the first argument of the ", (CODE style: "inline", "domo.ELEMENT"), " function:"
H4 "domo.ELEMENT(", (EM "nodeName"), ", ", (EM "attributes"), ", ", (EM "childNodes..."), ")"
P "Or if you need DOM comments, just use ", (CODE "domo.COMMENT"), " with the specified node value:"
H4 "domo.COMMENT(", (EM "nodeValue"), ")"
P "But dōmo isn't just limited to markup..."
A name: "css"
H3 "Using dōmo instead of CSS"
P "dōmo also lets you write CSS rules in JavaScript just as you would in CSS, by specifying a selector and style block per rule."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var styleSheet =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"}),
STYLE.on("*", {margin: 0, padding: 0})
)
alert(styleSheet.innerHTML == "a{color:red;}\\n*{margin:0px;padding:0px;}\\n")
"""
P "dōmo exposes CSS generation through a single function, attached to ", (CODE "domo.STYLE"), ":"
H4 "domo.STYLE.on(", (EM "selector"), ", ", (EM "properties..."), ")"
P "This generates the text source for a CSS rule, any number of which can be included in a stylesheet."
P {},
"The ", (EM "selector"), " is a string, ", "and the ", (EM "properties"), " are an object mapping property names to their values. "
"As with DOM attributes, all camelCased attribute names are lowercased and hyphenated for easier use with JavaScript object literals."
"If multiple property objects are specified, they are rolled into a single object."
P {},
"The interesting thing about using JavaScript to render CSS is that you have the full power of the language to make your stylesheets dynamic. "
"This means you can use plain old JavaScript functions to achieve the same rich CSS variables, mixins, operations, and functions that something like ", (A href: "http://lesscss.org/", "LESS"), " would provide, without any new syntax or compilation overhead, like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var blue = "#3B5998"
var gray = "#3B3B3B"
var defaultRadius = 10
function roundedCorners(radius) {
return {
borderRadius : radius,
WebkitBorderRadius : radius,
MozBorderRadius : radius
}
}
var styleSheet =
STYLE({type: "text/css"},
STYLE.on("h2", {color: gray}, roundedCorners(defaultRadius)),
STYLE.on("h1", {color: blue}, roundedCorners(defaultRadius * 2))
)
"""
P "dōmo also lets you nest rule declarations within other rule declarations, to help keep your related style declarations together:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var nestedStyles =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"},
STYLE.on("img", {borderWidth: 0})
)
)
var normalStyles =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"}),
STYLE.on("a img", {borderWidth: 0})
)
alert(nestedStyles.innerHTML == normalStyles.innerHTML)
"""
P {},
"Generating your styles on the client means that you don't need to ship redundant vendor-prefixed properties: you know the exact vendor at runtime. "
"And since the source of a stylesheet with multiple rules is fully concatenated before the DOM node is even created, the overhead in generating styles on the client is minimal. "
"If this is still a performance concern, you can move the code to the server and use a ", (CODE "LINK"), "element just as with server-side CSS pre-processors. It's your choice."
A name: "server"
H3 "Using dōmo on the server"
P {},
"dōmo really shines when used to build DOM code on the client. "
"But since you'll likely need to render an HTML client to run dōmo in the first place, dōmo also ships with a ", (A href: "https://github.com/jed/domo/blob/master/lib/document.js", "window.document shim"), " that mocks just enough of the DOM API to render HTML. "
P {},
"Using dōmo on the server is the same as that for the client; just ", (CODE class: "inline", "require('domo')"), " create a DOM, and use the ", (CODE class: "inline", "outerHTML"), " property to serialize it into HTML. "
"dōmo also adds a top-level ", (CODE class: "inline", "DOCUMENT"), " function that creates a doctype'd HTML document, allowing you to render HTML from an HTTP server like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
require("domo").global() // pollution is opt-in on CommonJS environments
var http = require("http")
http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"})
res.end(
DOCUMENT(
HTML({lang: "en"},
BODY("You accessed ", req.url, " at ", new Date)
)
).outerHTML
)
}).listen(80)
"""
A name: "convenience"
H3 "Convenience versus cleanliness"
P {},
(CODE class: "inline", "domo.global(true)"), " can be called to export all of dōmo's functions to the global object, so that you can call them without using the ", (CODE class: "inline", "domo"), " namespace. "
"This allows dōmo to mimic an in-code DSL, and given that only uppercase key names are exported, usually won't conflict with existing code. "
"Note that this is auto-executed by default in the browser and other non-CommonJS environments, and opt-in otherwise."
P {},
"However, if you're not cool with polluting the global scope, you still have some options. "
"Stash a reference to the ", (CODE class: "inline", "domo"), " object by calling ", (CODE class: "inline", "domo.global(false)"), " immediately after the dōmo script is loaded, like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "html", """
<script src="domo.js"><\/script>
<script>window.domo = domo.global(false)<\/script>
"""
P "This does two things:"
OL {},
LI "It reverts the global object to its original state (much like jQuery's ", CODE(".noConflict()"), " method)."
LI "It returns the ", (CODE class: "inline", "domo"), " object, which you can then assign for subsequent use."
P "(Note that ", (CODE class: "inline", "domo.global(false)"), " and ", (CODE class: "inline", "domo.global(true)"), " are idempotent, and can be called multiple times to extend and unextend the global object.)"
P "Once you have a reference to the ", (CODE class: "inline", "domo"), " object, you have some options about how to access its functions:"
H4 "Access them directly as ", (CODE class: "inline", "domo"), " object members."
P "This is safe, but a little verbose:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
domo = domo.global(false)
domo.HTML(
domo.HEAD(domo.TITLE("Hello, world.")),
domo.BODY("Hello, world.")
)
"""
H4 "Assign them to local variables"
P {},
"Since all dōmo functions are already bound to the current document object, they don't need to be called as methods. "
"This is especially nice if you only use a few DOM element types, and your flavor of JavaScript supports destructuring, like ", (A href: "http://coffeescript.org/#destructuring", "CoffeeScript"), " or ", (A href: "http://wiki.ecmascript.org/doku.php?id=harmony:destructuring", "ES6"), "."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
{HTML, HEAD, TITLE, BODY} = domo.global(false)
HTML(
HEAD(TITLE("Hello, world.")),
BODY("Hello, world.")
)
"""
H4 "Access them using the oft-maligned ", (CODE class: "inline", "with"), " statement."
P {},
"Don't just cargo cult ", (A href: "http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/", "Crockford"), ", ", A(href: "http://www.youtube.com/watch?v=MFtijdklZDo", "use what JavaScript gives you"), ". "
"As long as you're not assigning members or declaring functions, ", (A {href: "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with"}, "the ", (CODE class: "inline", "with"), " statement"), " is a very elegant way of temporarily importing a namespace:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
domo = domo.global(false)
with (domo)
HTML(
HEAD(TITLE("Hello, world.")),
BODY("Hello, world.")
)
"""
P SMALL "Copyright © <NAME> 2012"
SCRIPT src: "docs/vendor/prettify.js"
| true | boxShadow = (values) ->
MozBoxShadow : values
WebkitBoxShadow : values
boxShadow : values
HTML lang: "en",
HEAD {},
TITLE "dōmo: Markup, style, and code in one language."
LINK
rel: "stylesheet"
type: "text/css"
href: "//fonts.googleapis.com/css?family=Titillium+Web:900&subset=latin-ext"
STYLE type: "text/css",
(STYLE.on ".#{key}", {color} for key, color of {
pln: "#000", str: "#080", kwd: "#008", com: "#800", typ: "#606"
lit: "#066", pun: "#660", opn: "#660", clo: "#660", tag: "#008"
atn: "#606", atv: "#080", dec: "#606", var: "#606", fun: "red"
})
STYLE type: "text/css",
STYLE.on ".prettyprint" , padding: "2px"
STYLE.on ".linenums" , marginTop: "0 auto 0"
STYLE.on (".L#{n}" for n in [0..8]) , listStyleType: "none"
STYLE.on (".L#{n}" for n in [1..9] by 2) , background: "#eee"
STYLE type: "text/css",
STYLE.on "body"
background: "#f6f6f6"
color: "#222"
fontFamily: "Helvetica, Arial, sans-serif"
fontSize: "18px"
lineHeight: "1.5"
margin: "0 0 2em"
padding: 0
STYLE.on ["h1", "h2", "h3", "h4", "p", "ul", "ol", "pre", ".narrow"],
width: "750px"
margin: "1em auto"
display: "block"
STYLE.on "h1"
margin: "30px auto -60px auto"
fontSize: "150px"
fontFamily: "Titillium Web"
STYLE.on "a"
color: "#596C86"
STYLE.on "a:visited"
color: "#582525"
STYLE.on ".sub"
background: "#fff"
margin: "1em 0 0"
padding: "1em 0"
boxShadow "1px 1px 6px #ccc"
STYLE.on ["pre", "code"],
fontSize: "0.9em"
fontFamily: "Monaco, Courier New, monospace"
STYLE.on ".github"
position: "absolute"
top: 0
right: 0
border: 0
STYLE.on ".why-domo"
STYLE.on "li"
marginTop: "15px"
STYLE.on "code.inline"
margin: "0 2px"
padding: "0px 5px"
border: "1px solid #eee"
backgroundColor: "#fff"
borderRadius: "3px"
BODY onload: "prettyPrint()",
A href: "https://github.com/jed/domo",
IMG
class: "github"
src: "//s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"
alt: "Fork me on GitHub"
H1 "dōmo"
H2 "Markup, style, and code in one language."
P {},
"dōmo lets you write ", (A href: "#html", "HTML markup"), " and ", (A href: "#css", "CSS styles"), " in JavaScript syntax, in the browser and ", (A href: "#server", "on the server"), ". "
"dōmo is a simpler, easier, and more reliable alternative to template engines and CSS pre-processors, and works well with all the tools you already use."
P {},
"You can download ", (A href: "http://domo-js.com/lib/domo.js", "dōmo for the browser"), " (under ", (B "#{Math.ceil(domo.stats.size / 100) / 10}kb"), " minizipped), or install ", (A href: "https://npmjs.org/package/domo", "dōmo for node.js"), "."
H3 "Example"
P {},
"Here's a simple, self-contained example using dōmo in the browser. "
"This code replaces the existing root HTML element with its own DOM tree, using a simple opacity function as a CSS mixin."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "html", """
<!doctype html>
<script src="domo.js"><\/script>
<script>
function opacity(pct) {
return {opacity: String(pct / 100), filter: "alpha(opacity=" + pct + ")"}
}
HTML({lang: "en"},
HEAD(
TITLE("Welcome to dōmo"),
STYLE({type: "text/css"},
STYLE.on("body", {textAlign: "center", fontSize: 50}),
STYLE.on("h1", opacity(50), {background: "#000", color: "#fff"})
)
),
BODY(H1("Welcome to dōmo"))
)
<\/script>
"""
P "If you'd like to see a larger, real-world use of dōmo, just view ", (A href: "https://github.com/jed/domo/blob/master/docs/index.coffee", "the source of this very page"), "."
A name: "why"
H3 "Why?"
P "We all know CSS. We all know HTML. We mostly agree that neither is powerful enough to build modern web apps, hence the explosion of ", (A href: "http://lesscss.org", "CSS pre-processors"), " and ", (A href: "http://haml.info", "templating engines"), "."
P "If we're building tools to improve browser technologies like CSS and HTML, let's build them using another browser technology: JavaScript. Instead of adding incompatible extensions to CSS and HTML, let's first port them to a general-purpose language and do the extending there, where at least our tools can interoperate."
P "dōmo replaces the syntax of CSS and HTML syntax with JavaScript, leaving the semantics the same. You don't have to learn ad-hoc, underpowered syntax for looping or arithmetic or functions in your styles or markup, you can just use what you already know in JavaScript."
P "This means you can decouple your architecture from arbitrary implementation details, and render your app wherever it makes the most sense: on the server, on the browser, or both."
A name: "html"
H3 "Using dōmo instead of HTML"
P "dōmo lets you write concise JavaScript views for dynamic content, without having to choose between the lesser evil of verbose DOM code and embedding/compiling/escaping overhead of string templates."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var withDomo = A({href: "http://domo-js.com"}, "Learn about dōmo")
var withoutDomo = document.createElement("a")
withoutDomo.setAttribute("href", "http://domo-js.com")
withoutDomo.appendChild(document.createTextNode("Learn about dōmo"))
alert(withDomo.outerHTML == withoutDomo.outerHTML)
"""
P "dōmo's API is simple: it provides one function for ", (A href: "https://developer.mozilla.org/en-US/docs/HTML/HTML5/HTML5_element_list", "every standard HTML5 element"), ":"
H4 "domo.", (EM "elementName"), "(", (EM "attributes"), ", ", (EM "childNodes..."), ")"
P "Each function returns a namesake DOM element, and be accessed by UPPERCASE or lowercase name as a member of the ", (CODE "domo"), " object. These functions can also be ", (A href: "#convenience", "exported to the global namespace"), " for convenience by calling ", (CODE "domo.global(true)"), ", which is done automatically in browsers and other non-commonJS environments."
P {},
"The ", (EM "attributes"), " argument is an optional object that maps attribute names to their values. For easier use with JavaScript object literals, all camelCased attribute names are lowercased and hyphenated, so that names like ", (CODE class: "inline", "httpEquiv"), " and ", (CODE class: "inline", "http-equiv"), " are identical."
P {},
"The ", (EM "childNodes"), " argument is an optional list of children to be appended to the element. Any child that is already a node (has a ", (CODE class: "inline", "nodeType"), " property) is appended as-is, or converted to a text node otherwise. This allows you to append nodes generated elsewhere, to facilitate DOM composition. "
"Additional arguments can also be specified, in which case they will be flattened into a single list of children."
P "Note that in addition to returning the generated element, the ", (CODE "HTML"), ", ", (CODE "HEAD"), ", and ", (CODE "BODY"), " functions will also replace the existing element in the current document."
P "dōmo provides functions for the following HTML5 DOM elements out of the box:"
DIV class: "sub",
CODE class: "narrow", "A ABBR ACRONYM ADDRESS AREA ARTICLE ASIDE AUDIO B BDI BDO BIG BLOCKQUOTE BODY BR BUTTON CANVAS CAPTION CITE CODE COL COLGROUP COMMAND DATALIST DD DEL DETAILS DFN DIV DL DT EM EMBED FIELDSET FIGCAPTION FIGURE FOOTER FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HEADER HGROUP HR HTML I IFRAME IMG INPUT INS KBD KEYGEN LABEL LEGEND LI LINK MAP MARK META METER NAV NOSCRIPT OBJECT OL OPTGROUP OPTION OUTPUT P PARAM PRE PROGRESS Q RP RT RUBY SAMP SCRIPT SECTION SELECT SMALL SOURCE SPAN SPLIT STRONG STYLE SUB SUMMARY SUP TABLE TBODY TD TEXTAREA TFOOT TH THEAD TIME TITLE TR TRACK TT UL VAR VIDEO WBR"
P "If you need to use non-standard or custom HTML elements outside those provided by dōmo, pass the ", (EM "nodeName"), " of the element as the first argument of the ", (CODE style: "inline", "domo.ELEMENT"), " function:"
H4 "domo.ELEMENT(", (EM "nodeName"), ", ", (EM "attributes"), ", ", (EM "childNodes..."), ")"
P "Or if you need DOM comments, just use ", (CODE "domo.COMMENT"), " with the specified node value:"
H4 "domo.COMMENT(", (EM "nodeValue"), ")"
P "But dōmo isn't just limited to markup..."
A name: "css"
H3 "Using dōmo instead of CSS"
P "dōmo also lets you write CSS rules in JavaScript just as you would in CSS, by specifying a selector and style block per rule."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var styleSheet =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"}),
STYLE.on("*", {margin: 0, padding: 0})
)
alert(styleSheet.innerHTML == "a{color:red;}\\n*{margin:0px;padding:0px;}\\n")
"""
P "dōmo exposes CSS generation through a single function, attached to ", (CODE "domo.STYLE"), ":"
H4 "domo.STYLE.on(", (EM "selector"), ", ", (EM "properties..."), ")"
P "This generates the text source for a CSS rule, any number of which can be included in a stylesheet."
P {},
"The ", (EM "selector"), " is a string, ", "and the ", (EM "properties"), " are an object mapping property names to their values. "
"As with DOM attributes, all camelCased attribute names are lowercased and hyphenated for easier use with JavaScript object literals."
"If multiple property objects are specified, they are rolled into a single object."
P {},
"The interesting thing about using JavaScript to render CSS is that you have the full power of the language to make your stylesheets dynamic. "
"This means you can use plain old JavaScript functions to achieve the same rich CSS variables, mixins, operations, and functions that something like ", (A href: "http://lesscss.org/", "LESS"), " would provide, without any new syntax or compilation overhead, like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var blue = "#3B5998"
var gray = "#3B3B3B"
var defaultRadius = 10
function roundedCorners(radius) {
return {
borderRadius : radius,
WebkitBorderRadius : radius,
MozBorderRadius : radius
}
}
var styleSheet =
STYLE({type: "text/css"},
STYLE.on("h2", {color: gray}, roundedCorners(defaultRadius)),
STYLE.on("h1", {color: blue}, roundedCorners(defaultRadius * 2))
)
"""
P "dōmo also lets you nest rule declarations within other rule declarations, to help keep your related style declarations together:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
var nestedStyles =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"},
STYLE.on("img", {borderWidth: 0})
)
)
var normalStyles =
STYLE({type: "text/css"},
STYLE.on("a", {color: "red"}),
STYLE.on("a img", {borderWidth: 0})
)
alert(nestedStyles.innerHTML == normalStyles.innerHTML)
"""
P {},
"Generating your styles on the client means that you don't need to ship redundant vendor-prefixed properties: you know the exact vendor at runtime. "
"And since the source of a stylesheet with multiple rules is fully concatenated before the DOM node is even created, the overhead in generating styles on the client is minimal. "
"If this is still a performance concern, you can move the code to the server and use a ", (CODE "LINK"), "element just as with server-side CSS pre-processors. It's your choice."
A name: "server"
H3 "Using dōmo on the server"
P {},
"dōmo really shines when used to build DOM code on the client. "
"But since you'll likely need to render an HTML client to run dōmo in the first place, dōmo also ships with a ", (A href: "https://github.com/jed/domo/blob/master/lib/document.js", "window.document shim"), " that mocks just enough of the DOM API to render HTML. "
P {},
"Using dōmo on the server is the same as that for the client; just ", (CODE class: "inline", "require('domo')"), " create a DOM, and use the ", (CODE class: "inline", "outerHTML"), " property to serialize it into HTML. "
"dōmo also adds a top-level ", (CODE class: "inline", "DOCUMENT"), " function that creates a doctype'd HTML document, allowing you to render HTML from an HTTP server like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "js", """
require("domo").global() // pollution is opt-in on CommonJS environments
var http = require("http")
http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"})
res.end(
DOCUMENT(
HTML({lang: "en"},
BODY("You accessed ", req.url, " at ", new Date)
)
).outerHTML
)
}).listen(80)
"""
A name: "convenience"
H3 "Convenience versus cleanliness"
P {},
(CODE class: "inline", "domo.global(true)"), " can be called to export all of dōmo's functions to the global object, so that you can call them without using the ", (CODE class: "inline", "domo"), " namespace. "
"This allows dōmo to mimic an in-code DSL, and given that only uppercase key names are exported, usually won't conflict with existing code. "
"Note that this is auto-executed by default in the browser and other non-CommonJS environments, and opt-in otherwise."
P {},
"However, if you're not cool with polluting the global scope, you still have some options. "
"Stash a reference to the ", (CODE class: "inline", "domo"), " object by calling ", (CODE class: "inline", "domo.global(false)"), " immediately after the dōmo script is loaded, like this:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "html", """
<script src="domo.js"><\/script>
<script>window.domo = domo.global(false)<\/script>
"""
P "This does two things:"
OL {},
LI "It reverts the global object to its original state (much like jQuery's ", CODE(".noConflict()"), " method)."
LI "It returns the ", (CODE class: "inline", "domo"), " object, which you can then assign for subsequent use."
P "(Note that ", (CODE class: "inline", "domo.global(false)"), " and ", (CODE class: "inline", "domo.global(true)"), " are idempotent, and can be called multiple times to extend and unextend the global object.)"
P "Once you have a reference to the ", (CODE class: "inline", "domo"), " object, you have some options about how to access its functions:"
H4 "Access them directly as ", (CODE class: "inline", "domo"), " object members."
P "This is safe, but a little verbose:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
domo = domo.global(false)
domo.HTML(
domo.HEAD(domo.TITLE("Hello, world.")),
domo.BODY("Hello, world.")
)
"""
H4 "Assign them to local variables"
P {},
"Since all dōmo functions are already bound to the current document object, they don't need to be called as methods. "
"This is especially nice if you only use a few DOM element types, and your flavor of JavaScript supports destructuring, like ", (A href: "http://coffeescript.org/#destructuring", "CoffeeScript"), " or ", (A href: "http://wiki.ecmascript.org/doku.php?id=harmony:destructuring", "ES6"), "."
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
{HTML, HEAD, TITLE, BODY} = domo.global(false)
HTML(
HEAD(TITLE("Hello, world.")),
BODY("Hello, world.")
)
"""
H4 "Access them using the oft-maligned ", (CODE class: "inline", "with"), " statement."
P {},
"Don't just cargo cult ", (A href: "http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/", "Crockford"), ", ", A(href: "http://www.youtube.com/watch?v=MFtijdklZDo", "use what JavaScript gives you"), ". "
"As long as you're not assigning members or declaring functions, ", (A {href: "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with"}, "the ", (CODE class: "inline", "with"), " statement"), " is a very elegant way of temporarily importing a namespace:"
DIV class: "sub",
PRE class: "prettyprint",
CODE class: "javascript", """
domo = domo.global(false)
with (domo)
HTML(
HEAD(TITLE("Hello, world.")),
BODY("Hello, world.")
)
"""
P SMALL "Copyright © PI:NAME:<NAME>END_PI 2012"
SCRIPT src: "docs/vendor/prettify.js"
|
[
{
"context": "ting\"\n \"room\"\n ]\n author:\n name: \"James Halliday\"\n email: \"mail@substack.net\"\n url: \"htt",
"end": 1303,
"score": 0.9998043179512024,
"start": 1289,
"tag": "NAME",
"value": "James Halliday"
},
{
"context": "uthor:\n name: \"James Halliday\"\n email: \"mail@substack.net\"\n url: \"http://substack.net\"\n\n license: \"",
"end": 1336,
"score": 0.9999261498451233,
"start": 1319,
"tag": "EMAIL",
"value": "mail@substack.net"
}
] | deps/npm/node_modules/init-package-json/node_modules/promzard/test/basic.coffee | lxe/io.coffee | 0 | tap = require("tap")
pz = require("../promzard.js")
spawn = require("child_process").spawn
tap.test "run the example", (t) ->
respond = ->
console.error "respond", output
if output.match(/description: $/)
c.stdin.write "testing description\n"
return
if output.match(/entry point: \(index\.js\) $/)
c.stdin.write "test-entry.js\n"
return
if output.match(/keywords: $/)
c.stdin.write "fugazi function waiting room\n"
# "read" module is weird on node >= 0.10 when not a TTY
# requires explicit ending for reasons.
# could dig in, but really just wanna make tests pass, whatever.
c.stdin.end()
return
example = require.resolve("../example/index.js")
node = process.execPath
expect =
name: "example"
version: "0.0.0"
description: "testing description"
main: "test-entry.js"
directories:
example: "example"
test: "test"
dependencies: {}
devDependencies:
tap: "~0.2.5"
scripts:
test: "tap test/*.js"
repository:
type: "git"
url: "git://github.com/substack/example.git"
homepage: "https://github.com/substack/example"
keywords: [
"fugazi"
"function"
"waiting"
"room"
]
author:
name: "James Halliday"
email: "mail@substack.net"
url: "http://substack.net"
license: "MIT"
engine:
node: ">=0.6"
console.error "%s %s", node, example
c = spawn(node, [example],
customFds: [
-1
-1
-1
]
)
output = ""
c.stdout.on "data", (d) ->
output += d
respond()
return
actual = ""
c.stderr.on "data", (d) ->
actual += d
return
c.on "exit", ->
console.error "exit event"
return
c.on "close", ->
console.error "actual", actual
actual = JSON.parse(actual)
t.deepEqual actual, expect
t.end()
return
return
| 77183 | tap = require("tap")
pz = require("../promzard.js")
spawn = require("child_process").spawn
tap.test "run the example", (t) ->
respond = ->
console.error "respond", output
if output.match(/description: $/)
c.stdin.write "testing description\n"
return
if output.match(/entry point: \(index\.js\) $/)
c.stdin.write "test-entry.js\n"
return
if output.match(/keywords: $/)
c.stdin.write "fugazi function waiting room\n"
# "read" module is weird on node >= 0.10 when not a TTY
# requires explicit ending for reasons.
# could dig in, but really just wanna make tests pass, whatever.
c.stdin.end()
return
example = require.resolve("../example/index.js")
node = process.execPath
expect =
name: "example"
version: "0.0.0"
description: "testing description"
main: "test-entry.js"
directories:
example: "example"
test: "test"
dependencies: {}
devDependencies:
tap: "~0.2.5"
scripts:
test: "tap test/*.js"
repository:
type: "git"
url: "git://github.com/substack/example.git"
homepage: "https://github.com/substack/example"
keywords: [
"fugazi"
"function"
"waiting"
"room"
]
author:
name: "<NAME>"
email: "<EMAIL>"
url: "http://substack.net"
license: "MIT"
engine:
node: ">=0.6"
console.error "%s %s", node, example
c = spawn(node, [example],
customFds: [
-1
-1
-1
]
)
output = ""
c.stdout.on "data", (d) ->
output += d
respond()
return
actual = ""
c.stderr.on "data", (d) ->
actual += d
return
c.on "exit", ->
console.error "exit event"
return
c.on "close", ->
console.error "actual", actual
actual = JSON.parse(actual)
t.deepEqual actual, expect
t.end()
return
return
| true | tap = require("tap")
pz = require("../promzard.js")
spawn = require("child_process").spawn
tap.test "run the example", (t) ->
respond = ->
console.error "respond", output
if output.match(/description: $/)
c.stdin.write "testing description\n"
return
if output.match(/entry point: \(index\.js\) $/)
c.stdin.write "test-entry.js\n"
return
if output.match(/keywords: $/)
c.stdin.write "fugazi function waiting room\n"
# "read" module is weird on node >= 0.10 when not a TTY
# requires explicit ending for reasons.
# could dig in, but really just wanna make tests pass, whatever.
c.stdin.end()
return
example = require.resolve("../example/index.js")
node = process.execPath
expect =
name: "example"
version: "0.0.0"
description: "testing description"
main: "test-entry.js"
directories:
example: "example"
test: "test"
dependencies: {}
devDependencies:
tap: "~0.2.5"
scripts:
test: "tap test/*.js"
repository:
type: "git"
url: "git://github.com/substack/example.git"
homepage: "https://github.com/substack/example"
keywords: [
"fugazi"
"function"
"waiting"
"room"
]
author:
name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
url: "http://substack.net"
license: "MIT"
engine:
node: ">=0.6"
console.error "%s %s", node, example
c = spawn(node, [example],
customFds: [
-1
-1
-1
]
)
output = ""
c.stdout.on "data", (d) ->
output += d
respond()
return
actual = ""
c.stderr.on "data", (d) ->
actual += d
return
c.on "exit", ->
console.error "exit event"
return
c.on "close", ->
console.error "actual", actual
actual = JSON.parse(actual)
t.deepEqual actual, expect
t.end()
return
return
|
[
{
"context": "\n inputOptions :\n name : 'username'\n forceCase : 'lowercase'\n plac",
"end": 312,
"score": 0.9962128400802612,
"start": 304,
"tag": "USERNAME",
"value": "username"
},
{
"context": "pe : 'password'\n placeholder : 'Password'\n testPath : 'login-form-password'\n ",
"end": 824,
"score": 0.9433766603469849,
"start": 816,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "fcode.hide()\n\n pistachio: ->\n '''\n <div>{{> @username}}</div>\n <div>{{> @password}}</div>\n <div>{",
"end": 1782,
"score": 0.5699071288108826,
"start": 1773,
"tag": "USERNAME",
"value": "@username"
}
] | client/landing/site.landing/coffee/login/loginform.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
LoginViewInlineForm = require './loginviewinlineform'
LoginInputView = require './logininputview'
module.exports = class LoginInlineForm extends LoginViewInlineForm
constructor: ->
super
@username = new LoginInputView
inputOptions :
name : 'username'
forceCase : 'lowercase'
placeholder : 'Username or Email'
testPath : 'login-form-username'
attributes :
testpath : 'login-form-username'
validate :
rules :
required : yes
messages :
required : 'Please enter a username.'
@password = new LoginInputView
inputOptions :
name : 'password'
type : 'password'
placeholder : 'Password'
testPath : 'login-form-password'
attributes :
testpath : 'login-form-password'
validate :
rules :
required : yes
messages :
required : 'Please enter your password.'
@tfcode = new LoginInputView
inputOptions :
name : 'tfcode'
placeholder : 'Two-Factor Authentication Code'
testPath : 'login-form-tfcode'
attributes :
testpath : 'login-form-tfcode'
@tfcode.hide()
@button = new kd.ButtonView
title : 'SIGN IN'
style : 'solid medium green'
attributes :
testpath : 'login-button'
type : 'submit'
loader : yes
activate: ->
@username.setFocus()
resetDecoration: ->
@username.resetDecoration()
@password.resetDecoration()
@tfcode.hide()
pistachio: ->
'''
<div>{{> @username}}</div>
<div>{{> @password}}</div>
<div>{{> @tfcode}}</div>
<div>{{> @button}}</div>
'''
| 125198 | kd = require 'kd'
LoginViewInlineForm = require './loginviewinlineform'
LoginInputView = require './logininputview'
module.exports = class LoginInlineForm extends LoginViewInlineForm
constructor: ->
super
@username = new LoginInputView
inputOptions :
name : 'username'
forceCase : 'lowercase'
placeholder : 'Username or Email'
testPath : 'login-form-username'
attributes :
testpath : 'login-form-username'
validate :
rules :
required : yes
messages :
required : 'Please enter a username.'
@password = new LoginInputView
inputOptions :
name : 'password'
type : 'password'
placeholder : '<PASSWORD>'
testPath : 'login-form-password'
attributes :
testpath : 'login-form-password'
validate :
rules :
required : yes
messages :
required : 'Please enter your password.'
@tfcode = new LoginInputView
inputOptions :
name : 'tfcode'
placeholder : 'Two-Factor Authentication Code'
testPath : 'login-form-tfcode'
attributes :
testpath : 'login-form-tfcode'
@tfcode.hide()
@button = new kd.ButtonView
title : 'SIGN IN'
style : 'solid medium green'
attributes :
testpath : 'login-button'
type : 'submit'
loader : yes
activate: ->
@username.setFocus()
resetDecoration: ->
@username.resetDecoration()
@password.resetDecoration()
@tfcode.hide()
pistachio: ->
'''
<div>{{> @username}}</div>
<div>{{> @password}}</div>
<div>{{> @tfcode}}</div>
<div>{{> @button}}</div>
'''
| true | kd = require 'kd'
LoginViewInlineForm = require './loginviewinlineform'
LoginInputView = require './logininputview'
module.exports = class LoginInlineForm extends LoginViewInlineForm
constructor: ->
super
@username = new LoginInputView
inputOptions :
name : 'username'
forceCase : 'lowercase'
placeholder : 'Username or Email'
testPath : 'login-form-username'
attributes :
testpath : 'login-form-username'
validate :
rules :
required : yes
messages :
required : 'Please enter a username.'
@password = new LoginInputView
inputOptions :
name : 'password'
type : 'password'
placeholder : 'PI:PASSWORD:<PASSWORD>END_PI'
testPath : 'login-form-password'
attributes :
testpath : 'login-form-password'
validate :
rules :
required : yes
messages :
required : 'Please enter your password.'
@tfcode = new LoginInputView
inputOptions :
name : 'tfcode'
placeholder : 'Two-Factor Authentication Code'
testPath : 'login-form-tfcode'
attributes :
testpath : 'login-form-tfcode'
@tfcode.hide()
@button = new kd.ButtonView
title : 'SIGN IN'
style : 'solid medium green'
attributes :
testpath : 'login-button'
type : 'submit'
loader : yes
activate: ->
@username.setFocus()
resetDecoration: ->
@username.resetDecoration()
@password.resetDecoration()
@tfcode.hide()
pistachio: ->
'''
<div>{{> @username}}</div>
<div>{{> @password}}</div>
<div>{{> @tfcode}}</div>
<div>{{> @button}}</div>
'''
|
[
{
"context": "us is 'proceeding'\n loginData=account : @username , password : @password , rememberme : \"on\"\n ",
"end": 6075,
"score": 0.9950306415557861,
"start": 6066,
"tag": "USERNAME",
"value": "@username"
},
{
"context": " loginData=account : @username , password : @password , rememberme : \"on\"\n @client.login \"#",
"end": 6098,
"score": 0.9987275004386902,
"start": 6089,
"tag": "PASSWORD",
"value": "@password"
}
] | node_modules/mew/lib/otherweb.coffee | homepagea/mewbot | 0 | jsonrpc = require './jsonrpc.coffee'
{EventEmitter} = require 'events'
Fs = require 'fs'
http = require 'http'
mime = require 'mime'
class TimelineEvent extends EventEmitter
constructor : (@otherweb)->
@callTimeline()
callTimeline : ->
headers = Cookie : @otherweb.client.getCookies()
options = headers : headers
ievent =@otherweb.client.restful.post("#{@otherweb.rootURL}/gateway/api/timeline.jsp",options)
ievent.on "complete",(data,response)=>
@otherweb.client.handleResponseCookie response
@callTimeline()
try
rdata = JSON.parse(data)
if rdata.error
@emit "error",rdata.error
else
@emit "data",rdata
catch ex
@emit "error",ex
return ievent
class OTHERWebInstance
constructor : (@userAgent,@rootURL,@username,@password)->
@data = {}
@requestQueue=[]
@client = new jsonrpc("#{@rootURL}/gateway/api/jsonrpc.jsp")
@keepaliveTimeout=null
if @username and @password
@loginStatus = "incomplete"
else
@loginStatus = "complete"
autoBridge : (callback)=>
@client.jsonrpc "rpc.getBridge",[],(r,e)=>
if e
callback(e)
else
for key of r
@compileObject key,r[key]
callback(null,r)
compileObject : (name,functions)->
callinstance = @[name]={}
for functionName in functions
do (functionName)=>
functionNameKey = functionName
if functionName.indexOf("!") is 0
functionNameKey = functionName.substr(1)
callinstance[functionNameKey] = (params,callback)=>
if typeof params isnt 'function'
if Array.isArray params
@makeRequest "#{name}.#{functionName}",params,callback
else
@makeRequest "#{name}.#{functionName}",[params],callback
else
@makeRequest "#{name}.#{functionName}",[],params
download : (url,path,callback)->
request = http.get url,(response)=>
if response.statusCode is 200
fstream = Fs.createWriteStream(path)
response.pipe(fstream)
if @maxTimeout
request.setTimeout @maxTimeout,=>
request.abort()
callback("request timeout")
fstream.on "error",=>
Fs.unlink(path)
fstream.close (fcerr)=>
if fcerr
callback(fcerr)
else
callback(err)
fstream.on "finish",=>
fstream.close(callback)
else
request.abort()
callback("request error : #{response.statusCode}")
request.on "error",(err)=>
callback(err)
benchRequest : (path,params,benchcallback)->
startDate = new Date()
@makeRequest path,params,(r,e)->
endDate = new Date()
if benchcallback
benchcallback r,e,startDate,endDate
keepalive : (interval)->
if @keepaliveTimeout
clearTimeout(@keepaliveTimeout)
if interval
keepaliveCallback = =>
headers = Cookie : @client.getCookies()
options = headers : headers
@client.restful.post("#{@rootURL}/gateway/api/ping.jsp",options).on "complete",(data,response)=>
@client.handleResponseCookie response
@keepaliveTimeout = setTimeout keepaliveCallback,interval
@keepaliveTimeout = setTimeout keepaliveCallback,interval
makeRequest : (path,params,callback)->
if @loginStatus is 'incomplete' or @loginStatus is 'proceeding'
if @loginStatus is 'incomplete'
@loginStatus = 'proceeding'
@requestQueue = []
@requestQueue.push {
path : path ,
params : params ,
callback : callback
}
@login (error)=>
if error
callback(null,error)
else
for request in @requestQueue
@makeRequest request.path,request.params,request.callback
else
if path.indexOf("!") > 0
file = params.shift()
if file
@client.jsonrpcFile file,mime.lookup(file),path.replace("!",""),params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
else
@client.jsonrpc path.replace("!",""),params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
else
@client.jsonrpc path,params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
timeline : ->
if @loginStatus is 'complete'
return new TimelineEvent @
else
throw new Error ("not login")
login : (callback)->
if @loginStatus is 'incomplete' or @loginStatus is 'proceeding'
loginData=account : @username , password : @password , rememberme : "on"
@client.login "#{@rootURL}/gateway/api/ajax_login.jsp",loginData, (data)=>
if data
login_result = JSON.parse(data)
if login_result.result is 'SUCCESS'
@loginStatus = "complete"
try
if callback
callback(null,login_result)
catch ex
if callback
callback(ex)
else if login_result.result is 'ERROR'
@loginStatus = "incomplete"
if callback
callback("login_error")
else
if callback
callback("login_error")
else
if callback
callback()
module.exports = OTHERWebInstance | 95922 | jsonrpc = require './jsonrpc.coffee'
{EventEmitter} = require 'events'
Fs = require 'fs'
http = require 'http'
mime = require 'mime'
class TimelineEvent extends EventEmitter
constructor : (@otherweb)->
@callTimeline()
callTimeline : ->
headers = Cookie : @otherweb.client.getCookies()
options = headers : headers
ievent =@otherweb.client.restful.post("#{@otherweb.rootURL}/gateway/api/timeline.jsp",options)
ievent.on "complete",(data,response)=>
@otherweb.client.handleResponseCookie response
@callTimeline()
try
rdata = JSON.parse(data)
if rdata.error
@emit "error",rdata.error
else
@emit "data",rdata
catch ex
@emit "error",ex
return ievent
class OTHERWebInstance
constructor : (@userAgent,@rootURL,@username,@password)->
@data = {}
@requestQueue=[]
@client = new jsonrpc("#{@rootURL}/gateway/api/jsonrpc.jsp")
@keepaliveTimeout=null
if @username and @password
@loginStatus = "incomplete"
else
@loginStatus = "complete"
autoBridge : (callback)=>
@client.jsonrpc "rpc.getBridge",[],(r,e)=>
if e
callback(e)
else
for key of r
@compileObject key,r[key]
callback(null,r)
compileObject : (name,functions)->
callinstance = @[name]={}
for functionName in functions
do (functionName)=>
functionNameKey = functionName
if functionName.indexOf("!") is 0
functionNameKey = functionName.substr(1)
callinstance[functionNameKey] = (params,callback)=>
if typeof params isnt 'function'
if Array.isArray params
@makeRequest "#{name}.#{functionName}",params,callback
else
@makeRequest "#{name}.#{functionName}",[params],callback
else
@makeRequest "#{name}.#{functionName}",[],params
download : (url,path,callback)->
request = http.get url,(response)=>
if response.statusCode is 200
fstream = Fs.createWriteStream(path)
response.pipe(fstream)
if @maxTimeout
request.setTimeout @maxTimeout,=>
request.abort()
callback("request timeout")
fstream.on "error",=>
Fs.unlink(path)
fstream.close (fcerr)=>
if fcerr
callback(fcerr)
else
callback(err)
fstream.on "finish",=>
fstream.close(callback)
else
request.abort()
callback("request error : #{response.statusCode}")
request.on "error",(err)=>
callback(err)
benchRequest : (path,params,benchcallback)->
startDate = new Date()
@makeRequest path,params,(r,e)->
endDate = new Date()
if benchcallback
benchcallback r,e,startDate,endDate
keepalive : (interval)->
if @keepaliveTimeout
clearTimeout(@keepaliveTimeout)
if interval
keepaliveCallback = =>
headers = Cookie : @client.getCookies()
options = headers : headers
@client.restful.post("#{@rootURL}/gateway/api/ping.jsp",options).on "complete",(data,response)=>
@client.handleResponseCookie response
@keepaliveTimeout = setTimeout keepaliveCallback,interval
@keepaliveTimeout = setTimeout keepaliveCallback,interval
makeRequest : (path,params,callback)->
if @loginStatus is 'incomplete' or @loginStatus is 'proceeding'
if @loginStatus is 'incomplete'
@loginStatus = 'proceeding'
@requestQueue = []
@requestQueue.push {
path : path ,
params : params ,
callback : callback
}
@login (error)=>
if error
callback(null,error)
else
for request in @requestQueue
@makeRequest request.path,request.params,request.callback
else
if path.indexOf("!") > 0
file = params.shift()
if file
@client.jsonrpcFile file,mime.lookup(file),path.replace("!",""),params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
else
@client.jsonrpc path.replace("!",""),params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
else
@client.jsonrpc path,params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
timeline : ->
if @loginStatus is 'complete'
return new TimelineEvent @
else
throw new Error ("not login")
login : (callback)->
if @loginStatus is 'incomplete' or @loginStatus is 'proceeding'
loginData=account : @username , password : <PASSWORD> , rememberme : "on"
@client.login "#{@rootURL}/gateway/api/ajax_login.jsp",loginData, (data)=>
if data
login_result = JSON.parse(data)
if login_result.result is 'SUCCESS'
@loginStatus = "complete"
try
if callback
callback(null,login_result)
catch ex
if callback
callback(ex)
else if login_result.result is 'ERROR'
@loginStatus = "incomplete"
if callback
callback("login_error")
else
if callback
callback("login_error")
else
if callback
callback()
module.exports = OTHERWebInstance | true | jsonrpc = require './jsonrpc.coffee'
{EventEmitter} = require 'events'
Fs = require 'fs'
http = require 'http'
mime = require 'mime'
class TimelineEvent extends EventEmitter
constructor : (@otherweb)->
@callTimeline()
callTimeline : ->
headers = Cookie : @otherweb.client.getCookies()
options = headers : headers
ievent =@otherweb.client.restful.post("#{@otherweb.rootURL}/gateway/api/timeline.jsp",options)
ievent.on "complete",(data,response)=>
@otherweb.client.handleResponseCookie response
@callTimeline()
try
rdata = JSON.parse(data)
if rdata.error
@emit "error",rdata.error
else
@emit "data",rdata
catch ex
@emit "error",ex
return ievent
class OTHERWebInstance
constructor : (@userAgent,@rootURL,@username,@password)->
@data = {}
@requestQueue=[]
@client = new jsonrpc("#{@rootURL}/gateway/api/jsonrpc.jsp")
@keepaliveTimeout=null
if @username and @password
@loginStatus = "incomplete"
else
@loginStatus = "complete"
autoBridge : (callback)=>
@client.jsonrpc "rpc.getBridge",[],(r,e)=>
if e
callback(e)
else
for key of r
@compileObject key,r[key]
callback(null,r)
compileObject : (name,functions)->
callinstance = @[name]={}
for functionName in functions
do (functionName)=>
functionNameKey = functionName
if functionName.indexOf("!") is 0
functionNameKey = functionName.substr(1)
callinstance[functionNameKey] = (params,callback)=>
if typeof params isnt 'function'
if Array.isArray params
@makeRequest "#{name}.#{functionName}",params,callback
else
@makeRequest "#{name}.#{functionName}",[params],callback
else
@makeRequest "#{name}.#{functionName}",[],params
download : (url,path,callback)->
request = http.get url,(response)=>
if response.statusCode is 200
fstream = Fs.createWriteStream(path)
response.pipe(fstream)
if @maxTimeout
request.setTimeout @maxTimeout,=>
request.abort()
callback("request timeout")
fstream.on "error",=>
Fs.unlink(path)
fstream.close (fcerr)=>
if fcerr
callback(fcerr)
else
callback(err)
fstream.on "finish",=>
fstream.close(callback)
else
request.abort()
callback("request error : #{response.statusCode}")
request.on "error",(err)=>
callback(err)
benchRequest : (path,params,benchcallback)->
startDate = new Date()
@makeRequest path,params,(r,e)->
endDate = new Date()
if benchcallback
benchcallback r,e,startDate,endDate
keepalive : (interval)->
if @keepaliveTimeout
clearTimeout(@keepaliveTimeout)
if interval
keepaliveCallback = =>
headers = Cookie : @client.getCookies()
options = headers : headers
@client.restful.post("#{@rootURL}/gateway/api/ping.jsp",options).on "complete",(data,response)=>
@client.handleResponseCookie response
@keepaliveTimeout = setTimeout keepaliveCallback,interval
@keepaliveTimeout = setTimeout keepaliveCallback,interval
makeRequest : (path,params,callback)->
if @loginStatus is 'incomplete' or @loginStatus is 'proceeding'
if @loginStatus is 'incomplete'
@loginStatus = 'proceeding'
@requestQueue = []
@requestQueue.push {
path : path ,
params : params ,
callback : callback
}
@login (error)=>
if error
callback(null,error)
else
for request in @requestQueue
@makeRequest request.path,request.params,request.callback
else
if path.indexOf("!") > 0
file = params.shift()
if file
@client.jsonrpcFile file,mime.lookup(file),path.replace("!",""),params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
else
@client.jsonrpc path.replace("!",""),params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
else
@client.jsonrpc path,params,(r,e)=>
if e and e.code is 592
@loginStatus = "incomplete"
@makeRequest path,params,callback
else
if callback
callback(r,e)
timeline : ->
if @loginStatus is 'complete'
return new TimelineEvent @
else
throw new Error ("not login")
login : (callback)->
if @loginStatus is 'incomplete' or @loginStatus is 'proceeding'
loginData=account : @username , password : PI:PASSWORD:<PASSWORD>END_PI , rememberme : "on"
@client.login "#{@rootURL}/gateway/api/ajax_login.jsp",loginData, (data)=>
if data
login_result = JSON.parse(data)
if login_result.result is 'SUCCESS'
@loginStatus = "complete"
try
if callback
callback(null,login_result)
catch ex
if callback
callback(ex)
else if login_result.result is 'ERROR'
@loginStatus = "incomplete"
if callback
callback("login_error")
else
if callback
callback("login_error")
else
if callback
callback()
module.exports = OTHERWebInstance |
[
{
"context": "#\n# Copyright (c) 2019 Alexander Sporn. All rights reserved.\n# Copyright (c) 2020 Philip",
"end": 38,
"score": 0.9998718500137329,
"start": 23,
"tag": "NAME",
"value": "Alexander Sporn"
},
{
"context": "r Sporn. All rights reserved.\n# Copyright (c) 2020 Philipp Leser-Wolf\n#\n\nEnocean = require './Enocean'\n\nAccessory = und",
"end": 100,
"score": 0.9998540878295898,
"start": 82,
"tag": "NAME",
"value": "Philipp Leser-Wolf"
}
] | index.coffee | zonefuenf/homebridge-enocean | 2 | #
# Copyright (c) 2019 Alexander Sporn. All rights reserved.
# Copyright (c) 2020 Philipp Leser-Wolf
#
Enocean = require './Enocean'
Accessory = undefined
Service = undefined
Characteristic = undefined
UUIDGen = undefined
module.exports = (homebridge) ->
Accessory = homebridge.platformAccessory
Service = homebridge.hap.Service
Characteristic = homebridge.hap.Characteristic
UUIDGen = homebridge.hap.uuid
homebridge.registerPlatform 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', EnoceanPlatform, true
return
EnoceanPlatform = (@log, @config, @api) ->
if !@config?
@log "No configuration found!"
return
if !@config.port?
@log "Property port in configuration has to be set!"
return
@accessories = {}
@staleAccessories = []
@enocean = new Enocean(port: @config.port)
@enocean.on 'pressed', (sender, button) =>
@setSwitchEventValue(sender, button, Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, @config.logPresses ? false)
@api.on 'didFinishLaunching', =>
if @staleAccessories.length > 0
@log "Removing accessories not present in configuration"
@api.unregisterPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', @staleAccessories
for accessory in @config.accessories
@addAccessory(accessory)
return
return
EnoceanPlatform::setSwitchEventValue = (sender, button, value, logOn) ->
accessory = @accessories[sender]
unless accessory?
if @config.logUnconfigured ? true
@log 'Unconfigured sender', sender
return
for service in accessory.services
if service.UUID == Service.StatelessProgrammableSwitch.UUID and service.subtype == button
characteristic = service.getCharacteristic(Characteristic.ProgrammableSwitchEvent)
characteristic.setValue(value)
if logOn
@log accessory.displayName+':', 'Button', button, 'pressed'
return
@log 'Could not find button', button
return
EnoceanPlatform::configureAccessory = (accessory) ->
@log 'Configure accessory:', accessory.displayName
accessory.reachable = true
accessory.on 'identify', (paired, callback) =>
@log accessory.displayName, 'identified'
callback()
return
serial = accessory.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.SerialNumber).value
unless serial?
@api.unregisterPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', [ accessory ]
return
# Remove accessory from cache if it was removed from configuration by user
if !@config.accessories.find (c) -> c.id == serial
@log 'Schedule accessory for removal:', accessory.displayName
@staleAccessories.push accessory
return
@accessories[serial] = accessory
return
EnoceanPlatform::createProgrammableSwitch = (name, model, serial) ->
uuid = UUIDGen.generate(serial)
accessory = new Accessory(name, uuid)
accessory.on 'identify', (paired, callback) =>
@log accessory.displayName, 'identified'
callback()
return
info = accessory.getService(Service.AccessoryInformation)
info.updateCharacteristic(Characteristic.Manufacturer, "EnOcean")
.updateCharacteristic(Characteristic.Model, model)
.updateCharacteristic(Characteristic.SerialNumber, serial)
.updateCharacteristic(Characteristic.FirmwareRevision, '1.0')
label = new Service.ServiceLabel(accessory.displayName)
label.getCharacteristic(Characteristic.ServiceLabelNamespace).updateValue(Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS)
accessory.addService(label)
buttonAI = @createProgrammableSwitchButton(accessory.displayName, 1, 'AI')
buttonA0 = @createProgrammableSwitchButton(accessory.displayName, 2, 'A0')
buttonBI = @createProgrammableSwitchButton(accessory.displayName, 3, 'BI')
buttonB0 = @createProgrammableSwitchButton(accessory.displayName, 4, 'B0')
accessory.addService(buttonAI)
accessory.addService(buttonA0)
accessory.addService(buttonBI)
accessory.addService(buttonB0)
return accessory
EnoceanPlatform::createProgrammableSwitchButton = (accesoryName, buttonIndex, button) ->
button = new Service.StatelessProgrammableSwitch(accesoryName + ' ' + button, button)
singleButton =
minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS
maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS
button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(singleButton)
button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(buttonIndex)
return button
EnoceanPlatform::addAccessory = (config) ->
if @accessories[config.id]?
return
@log 'Add new accessory:', config.name
accessory = @createProgrammableSwitch(config.name, config.eep, config.id)
@accessories[config.id] = accessory
@api.registerPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', [ accessory ]
return
| 128965 | #
# Copyright (c) 2019 <NAME>. All rights reserved.
# Copyright (c) 2020 <NAME>
#
Enocean = require './Enocean'
Accessory = undefined
Service = undefined
Characteristic = undefined
UUIDGen = undefined
module.exports = (homebridge) ->
Accessory = homebridge.platformAccessory
Service = homebridge.hap.Service
Characteristic = homebridge.hap.Characteristic
UUIDGen = homebridge.hap.uuid
homebridge.registerPlatform 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', EnoceanPlatform, true
return
EnoceanPlatform = (@log, @config, @api) ->
if !@config?
@log "No configuration found!"
return
if !@config.port?
@log "Property port in configuration has to be set!"
return
@accessories = {}
@staleAccessories = []
@enocean = new Enocean(port: @config.port)
@enocean.on 'pressed', (sender, button) =>
@setSwitchEventValue(sender, button, Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, @config.logPresses ? false)
@api.on 'didFinishLaunching', =>
if @staleAccessories.length > 0
@log "Removing accessories not present in configuration"
@api.unregisterPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', @staleAccessories
for accessory in @config.accessories
@addAccessory(accessory)
return
return
EnoceanPlatform::setSwitchEventValue = (sender, button, value, logOn) ->
accessory = @accessories[sender]
unless accessory?
if @config.logUnconfigured ? true
@log 'Unconfigured sender', sender
return
for service in accessory.services
if service.UUID == Service.StatelessProgrammableSwitch.UUID and service.subtype == button
characteristic = service.getCharacteristic(Characteristic.ProgrammableSwitchEvent)
characteristic.setValue(value)
if logOn
@log accessory.displayName+':', 'Button', button, 'pressed'
return
@log 'Could not find button', button
return
EnoceanPlatform::configureAccessory = (accessory) ->
@log 'Configure accessory:', accessory.displayName
accessory.reachable = true
accessory.on 'identify', (paired, callback) =>
@log accessory.displayName, 'identified'
callback()
return
serial = accessory.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.SerialNumber).value
unless serial?
@api.unregisterPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', [ accessory ]
return
# Remove accessory from cache if it was removed from configuration by user
if !@config.accessories.find (c) -> c.id == serial
@log 'Schedule accessory for removal:', accessory.displayName
@staleAccessories.push accessory
return
@accessories[serial] = accessory
return
EnoceanPlatform::createProgrammableSwitch = (name, model, serial) ->
uuid = UUIDGen.generate(serial)
accessory = new Accessory(name, uuid)
accessory.on 'identify', (paired, callback) =>
@log accessory.displayName, 'identified'
callback()
return
info = accessory.getService(Service.AccessoryInformation)
info.updateCharacteristic(Characteristic.Manufacturer, "EnOcean")
.updateCharacteristic(Characteristic.Model, model)
.updateCharacteristic(Characteristic.SerialNumber, serial)
.updateCharacteristic(Characteristic.FirmwareRevision, '1.0')
label = new Service.ServiceLabel(accessory.displayName)
label.getCharacteristic(Characteristic.ServiceLabelNamespace).updateValue(Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS)
accessory.addService(label)
buttonAI = @createProgrammableSwitchButton(accessory.displayName, 1, 'AI')
buttonA0 = @createProgrammableSwitchButton(accessory.displayName, 2, 'A0')
buttonBI = @createProgrammableSwitchButton(accessory.displayName, 3, 'BI')
buttonB0 = @createProgrammableSwitchButton(accessory.displayName, 4, 'B0')
accessory.addService(buttonAI)
accessory.addService(buttonA0)
accessory.addService(buttonBI)
accessory.addService(buttonB0)
return accessory
EnoceanPlatform::createProgrammableSwitchButton = (accesoryName, buttonIndex, button) ->
button = new Service.StatelessProgrammableSwitch(accesoryName + ' ' + button, button)
singleButton =
minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS
maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS
button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(singleButton)
button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(buttonIndex)
return button
EnoceanPlatform::addAccessory = (config) ->
if @accessories[config.id]?
return
@log 'Add new accessory:', config.name
accessory = @createProgrammableSwitch(config.name, config.eep, config.id)
@accessories[config.id] = accessory
@api.registerPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', [ accessory ]
return
| true | #
# Copyright (c) 2019 PI:NAME:<NAME>END_PI. All rights reserved.
# Copyright (c) 2020 PI:NAME:<NAME>END_PI
#
Enocean = require './Enocean'
Accessory = undefined
Service = undefined
Characteristic = undefined
UUIDGen = undefined
module.exports = (homebridge) ->
Accessory = homebridge.platformAccessory
Service = homebridge.hap.Service
Characteristic = homebridge.hap.Characteristic
UUIDGen = homebridge.hap.uuid
homebridge.registerPlatform 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', EnoceanPlatform, true
return
EnoceanPlatform = (@log, @config, @api) ->
if !@config?
@log "No configuration found!"
return
if !@config.port?
@log "Property port in configuration has to be set!"
return
@accessories = {}
@staleAccessories = []
@enocean = new Enocean(port: @config.port)
@enocean.on 'pressed', (sender, button) =>
@setSwitchEventValue(sender, button, Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, @config.logPresses ? false)
@api.on 'didFinishLaunching', =>
if @staleAccessories.length > 0
@log "Removing accessories not present in configuration"
@api.unregisterPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', @staleAccessories
for accessory in @config.accessories
@addAccessory(accessory)
return
return
EnoceanPlatform::setSwitchEventValue = (sender, button, value, logOn) ->
accessory = @accessories[sender]
unless accessory?
if @config.logUnconfigured ? true
@log 'Unconfigured sender', sender
return
for service in accessory.services
if service.UUID == Service.StatelessProgrammableSwitch.UUID and service.subtype == button
characteristic = service.getCharacteristic(Characteristic.ProgrammableSwitchEvent)
characteristic.setValue(value)
if logOn
@log accessory.displayName+':', 'Button', button, 'pressed'
return
@log 'Could not find button', button
return
EnoceanPlatform::configureAccessory = (accessory) ->
@log 'Configure accessory:', accessory.displayName
accessory.reachable = true
accessory.on 'identify', (paired, callback) =>
@log accessory.displayName, 'identified'
callback()
return
serial = accessory.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.SerialNumber).value
unless serial?
@api.unregisterPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', [ accessory ]
return
# Remove accessory from cache if it was removed from configuration by user
if !@config.accessories.find (c) -> c.id == serial
@log 'Schedule accessory for removal:', accessory.displayName
@staleAccessories.push accessory
return
@accessories[serial] = accessory
return
EnoceanPlatform::createProgrammableSwitch = (name, model, serial) ->
uuid = UUIDGen.generate(serial)
accessory = new Accessory(name, uuid)
accessory.on 'identify', (paired, callback) =>
@log accessory.displayName, 'identified'
callback()
return
info = accessory.getService(Service.AccessoryInformation)
info.updateCharacteristic(Characteristic.Manufacturer, "EnOcean")
.updateCharacteristic(Characteristic.Model, model)
.updateCharacteristic(Characteristic.SerialNumber, serial)
.updateCharacteristic(Characteristic.FirmwareRevision, '1.0')
label = new Service.ServiceLabel(accessory.displayName)
label.getCharacteristic(Characteristic.ServiceLabelNamespace).updateValue(Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS)
accessory.addService(label)
buttonAI = @createProgrammableSwitchButton(accessory.displayName, 1, 'AI')
buttonA0 = @createProgrammableSwitchButton(accessory.displayName, 2, 'A0')
buttonBI = @createProgrammableSwitchButton(accessory.displayName, 3, 'BI')
buttonB0 = @createProgrammableSwitchButton(accessory.displayName, 4, 'B0')
accessory.addService(buttonAI)
accessory.addService(buttonA0)
accessory.addService(buttonBI)
accessory.addService(buttonB0)
return accessory
EnoceanPlatform::createProgrammableSwitchButton = (accesoryName, buttonIndex, button) ->
button = new Service.StatelessProgrammableSwitch(accesoryName + ' ' + button, button)
singleButton =
minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS
maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS
button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(singleButton)
button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(buttonIndex)
return button
EnoceanPlatform::addAccessory = (config) ->
if @accessories[config.id]?
return
@log 'Add new accessory:', config.name
accessory = @createProgrammableSwitch(config.name, config.eep, config.id)
@accessories[config.id] = accessory
@api.registerPlatformAccessories 'homebridge-enocean-zonefuenf', 'enocean-zonefuenf', [ accessory ]
return
|
[
{
"context": "key: 'open-block'\n\npatterns: [\n\n # Matches open block.\n #\n # Ex",
"end": 16,
"score": 0.9953886866569519,
"start": 6,
"tag": "KEY",
"value": "open-block"
}
] | grammars/repositories/blocks/open-grammar.cson | andrewcarver/atom-language-asciidoc | 45 | key: 'open-block'
patterns: [
# Matches open block.
#
# Examples
#
# --
# An open block can be an anonymous container
# --
#
name: 'markup.block.open.asciidoc'
begin: '^(-{2})$'
beginCaptures:
1: name: 'constant.other.symbol.asciidoc'
patterns: [
include: '$self'
]
end: '^(\\1)$'
endCaptures:
1: name: 'constant.other.symbol.asciidoc'
]
| 95775 | key: '<KEY>'
patterns: [
# Matches open block.
#
# Examples
#
# --
# An open block can be an anonymous container
# --
#
name: 'markup.block.open.asciidoc'
begin: '^(-{2})$'
beginCaptures:
1: name: 'constant.other.symbol.asciidoc'
patterns: [
include: '$self'
]
end: '^(\\1)$'
endCaptures:
1: name: 'constant.other.symbol.asciidoc'
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
# Matches open block.
#
# Examples
#
# --
# An open block can be an anonymous container
# --
#
name: 'markup.block.open.asciidoc'
begin: '^(-{2})$'
beginCaptures:
1: name: 'constant.other.symbol.asciidoc'
patterns: [
include: '$self'
]
end: '^(\\1)$'
endCaptures:
1: name: 'constant.other.symbol.asciidoc'
]
|
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o",
"end": 67,
"score": 0.8476415872573853,
"start": 62,
"tag": "NAME",
"value": "Hatio"
}
] | src/spec/SpecHandleLayer.coffee | heartyoh/infopik | 0 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (
dou
kin
) ->
"use strict"
createView = (attributes) ->
view = new kin.Layer(attributes)
view.handles = {}
view
onchangeoffset = (e) ->
view = this.listener
view.offset {x: e.x, y: e.y}
view.batchDraw()
ondragmove = (e) ->
view = this.listener
id = e.targetNode.getAttr('id')
handle = view.handles[id]
if handle
handle.setAbsolutePosition(e.targetNode.getAbsolutePosition())
view.batchDraw()
ondragend = (e) ->
view = this.listener
id = e.targetNode.getAttr('id')
handle = view.handles[id]
if handle
handle.setAbsolutePosition(e.targetNode.getAbsolutePosition())
view.draw()
onchangeselection = (after, before, added, removed, e) ->
controller = this
model = e.listener
view = controller.getAttachedViews(model)[0]
for node in removed
id = node.getAttr('id')
handle = view.handles[id]
handle_comp = controller.getAttachedModel(handle)
model.remove(handle_comp)
delete view.handles[id]
for node in added
id = node.getAttr('id')
pos = node.getAbsolutePosition()
handle_comp = this.createComponent
type: 'handle-rect'
attrs: {}
model.add(handle_comp)
handle_view = controller.getAttachedViews(handle_comp)[0]
# handle_view.setAbsolutePosition(pos)
handle_view.setTarget(node)
view.handles[id] = handle_view
view.batchDraw()
model_event_map =
'(root)' :
'(root)' :
'change-selections' : onchangeselection
view_event_map =
'?offset_monitor_target' :
'change-offset' : onchangeoffset
dragmove : ondragmove
dragend : ondragend
{
type: 'handle-layer'
name: 'handle-layer'
containable: true
container_type: 'layer'
description: 'Handle Layer Specification'
defaults:
draggable: false
model_event_map: model_event_map
view_event_map: view_event_map
view_factory_fn: createView
toolbox_image: 'images/toolbox_handle_layer.png'
}
| 132819 | # ==========================================
# Copyright 2014 <NAME>, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (
dou
kin
) ->
"use strict"
createView = (attributes) ->
view = new kin.Layer(attributes)
view.handles = {}
view
onchangeoffset = (e) ->
view = this.listener
view.offset {x: e.x, y: e.y}
view.batchDraw()
ondragmove = (e) ->
view = this.listener
id = e.targetNode.getAttr('id')
handle = view.handles[id]
if handle
handle.setAbsolutePosition(e.targetNode.getAbsolutePosition())
view.batchDraw()
ondragend = (e) ->
view = this.listener
id = e.targetNode.getAttr('id')
handle = view.handles[id]
if handle
handle.setAbsolutePosition(e.targetNode.getAbsolutePosition())
view.draw()
onchangeselection = (after, before, added, removed, e) ->
controller = this
model = e.listener
view = controller.getAttachedViews(model)[0]
for node in removed
id = node.getAttr('id')
handle = view.handles[id]
handle_comp = controller.getAttachedModel(handle)
model.remove(handle_comp)
delete view.handles[id]
for node in added
id = node.getAttr('id')
pos = node.getAbsolutePosition()
handle_comp = this.createComponent
type: 'handle-rect'
attrs: {}
model.add(handle_comp)
handle_view = controller.getAttachedViews(handle_comp)[0]
# handle_view.setAbsolutePosition(pos)
handle_view.setTarget(node)
view.handles[id] = handle_view
view.batchDraw()
model_event_map =
'(root)' :
'(root)' :
'change-selections' : onchangeselection
view_event_map =
'?offset_monitor_target' :
'change-offset' : onchangeoffset
dragmove : ondragmove
dragend : ondragend
{
type: 'handle-layer'
name: 'handle-layer'
containable: true
container_type: 'layer'
description: 'Handle Layer Specification'
defaults:
draggable: false
model_event_map: model_event_map
view_event_map: view_event_map
view_factory_fn: createView
toolbox_image: 'images/toolbox_handle_layer.png'
}
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PI, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (
dou
kin
) ->
"use strict"
createView = (attributes) ->
view = new kin.Layer(attributes)
view.handles = {}
view
onchangeoffset = (e) ->
view = this.listener
view.offset {x: e.x, y: e.y}
view.batchDraw()
ondragmove = (e) ->
view = this.listener
id = e.targetNode.getAttr('id')
handle = view.handles[id]
if handle
handle.setAbsolutePosition(e.targetNode.getAbsolutePosition())
view.batchDraw()
ondragend = (e) ->
view = this.listener
id = e.targetNode.getAttr('id')
handle = view.handles[id]
if handle
handle.setAbsolutePosition(e.targetNode.getAbsolutePosition())
view.draw()
onchangeselection = (after, before, added, removed, e) ->
controller = this
model = e.listener
view = controller.getAttachedViews(model)[0]
for node in removed
id = node.getAttr('id')
handle = view.handles[id]
handle_comp = controller.getAttachedModel(handle)
model.remove(handle_comp)
delete view.handles[id]
for node in added
id = node.getAttr('id')
pos = node.getAbsolutePosition()
handle_comp = this.createComponent
type: 'handle-rect'
attrs: {}
model.add(handle_comp)
handle_view = controller.getAttachedViews(handle_comp)[0]
# handle_view.setAbsolutePosition(pos)
handle_view.setTarget(node)
view.handles[id] = handle_view
view.batchDraw()
model_event_map =
'(root)' :
'(root)' :
'change-selections' : onchangeselection
view_event_map =
'?offset_monitor_target' :
'change-offset' : onchangeoffset
dragmove : ondragmove
dragend : ondragend
{
type: 'handle-layer'
name: 'handle-layer'
containable: true
container_type: 'layer'
description: 'Handle Layer Specification'
defaults:
draggable: false
model_event_map: model_event_map
view_event_map: view_event_map
view_factory_fn: createView
toolbox_image: 'images/toolbox_handle_layer.png'
}
|
[
{
"context": ", ($provide) ->\n products = [{ id: 123, name: \"foo\" }, { id: 234, name: \"bar\" }]\n\n class Products",
"end": 153,
"score": 0.7543646693229675,
"start": 150,
"tag": "NAME",
"value": "foo"
}
] | client/test/unit/routes_spec.coffee | lucassus/angular-coffee-seed | 2 | describe "Application routes", ->
# stub `Products` service
beforeEach module "myApp.resources", ($provide) ->
products = [{ id: 123, name: "foo" }, { id: 234, name: "bar" }]
class Products
@query: sinon.stub().returns $promise: then: (callback) -> callback(products)
@get: sinon.stub().returns $promise: then: (callback) -> callback(products[0])
$provide.value "Products", Products
return
beforeEach module "myApp"
navigateTo = (to, params = {}) ->
# for some reason `$route` has to be injected here
beforeEach inject ($rootScope, $state) ->
$rootScope.$apply -> $state.go(to, params)
describe "route `/products`", ->
navigateTo "products.list"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/products/list.html")
.and.to.have.controller("products.IndexCtrl as index")
.and.to.resolve("products")
it "queries for the products", inject (Products) ->
expect(Products.query).to.be.called
it "loads the products", inject ($state) ->
products = $state.$current.locals.resolve.$$values.products
expect(products).to.have.length 2
expect(products).to.satisfy (collection) -> _.findWhere(collection, id: 123)
expect(products).to.satisfy (collection) -> _.findWhere(collection, id: 234)
describe "route `/products/create`", ->
navigateTo "products.create"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/products/form.html")
.and.to.have.controller("products.FormCtrl as form")
.and.to.resolve("product")
it "resolves with a new product instance", inject ($state, Products) ->
product = $state.$current.locals.resolve.$$values.product
expect(product).to.be.instanceOf(Products)
expect(product.id).to.be.undefined
describe "route `/products/:id`", ->
itIsRecognized = ->
it "is recognized", inject ($state) ->
expect($state.$current.parent)
.to.have.templateUrl("templates/products/show.html")
.and.to.have.controller("products.ShowCtrl as show")
.and.to.resolve("product")
itQueriesForAProduct = ->
it "queries for a product", inject ($state, Products) ->
expect(Products.get).to.be.calledWith(id: "123")
itLoadsAProduct = ->
it "loads a product", inject ($state) ->
product = $state.$current.locals.resolve.$$values.product
expect(product.id).to.equal 123
expect(product.name).to.equal "foo"
describe "`info` tab", ->
navigateTo "products.show.info", id: 123
itIsRecognized()
itQueriesForAProduct()
itLoadsAProduct()
describe "`details` tab", ->
navigateTo "products.show.details", id: 123
itIsRecognized()
itQueriesForAProduct()
itLoadsAProduct()
describe "route `/other`", ->
navigateTo "other"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/other.html")
.and.to.have.controller("OtherCtrl as other")
describe "route `/tasks`", ->
navigateTo "tasks"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/tasks.html")
.and.to.have.controller("TasksCtrl as tasks")
| 38590 | describe "Application routes", ->
# stub `Products` service
beforeEach module "myApp.resources", ($provide) ->
products = [{ id: 123, name: "<NAME>" }, { id: 234, name: "bar" }]
class Products
@query: sinon.stub().returns $promise: then: (callback) -> callback(products)
@get: sinon.stub().returns $promise: then: (callback) -> callback(products[0])
$provide.value "Products", Products
return
beforeEach module "myApp"
navigateTo = (to, params = {}) ->
# for some reason `$route` has to be injected here
beforeEach inject ($rootScope, $state) ->
$rootScope.$apply -> $state.go(to, params)
describe "route `/products`", ->
navigateTo "products.list"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/products/list.html")
.and.to.have.controller("products.IndexCtrl as index")
.and.to.resolve("products")
it "queries for the products", inject (Products) ->
expect(Products.query).to.be.called
it "loads the products", inject ($state) ->
products = $state.$current.locals.resolve.$$values.products
expect(products).to.have.length 2
expect(products).to.satisfy (collection) -> _.findWhere(collection, id: 123)
expect(products).to.satisfy (collection) -> _.findWhere(collection, id: 234)
describe "route `/products/create`", ->
navigateTo "products.create"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/products/form.html")
.and.to.have.controller("products.FormCtrl as form")
.and.to.resolve("product")
it "resolves with a new product instance", inject ($state, Products) ->
product = $state.$current.locals.resolve.$$values.product
expect(product).to.be.instanceOf(Products)
expect(product.id).to.be.undefined
describe "route `/products/:id`", ->
itIsRecognized = ->
it "is recognized", inject ($state) ->
expect($state.$current.parent)
.to.have.templateUrl("templates/products/show.html")
.and.to.have.controller("products.ShowCtrl as show")
.and.to.resolve("product")
itQueriesForAProduct = ->
it "queries for a product", inject ($state, Products) ->
expect(Products.get).to.be.calledWith(id: "123")
itLoadsAProduct = ->
it "loads a product", inject ($state) ->
product = $state.$current.locals.resolve.$$values.product
expect(product.id).to.equal 123
expect(product.name).to.equal "foo"
describe "`info` tab", ->
navigateTo "products.show.info", id: 123
itIsRecognized()
itQueriesForAProduct()
itLoadsAProduct()
describe "`details` tab", ->
navigateTo "products.show.details", id: 123
itIsRecognized()
itQueriesForAProduct()
itLoadsAProduct()
describe "route `/other`", ->
navigateTo "other"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/other.html")
.and.to.have.controller("OtherCtrl as other")
describe "route `/tasks`", ->
navigateTo "tasks"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/tasks.html")
.and.to.have.controller("TasksCtrl as tasks")
| true | describe "Application routes", ->
# stub `Products` service
beforeEach module "myApp.resources", ($provide) ->
products = [{ id: 123, name: "PI:NAME:<NAME>END_PI" }, { id: 234, name: "bar" }]
class Products
@query: sinon.stub().returns $promise: then: (callback) -> callback(products)
@get: sinon.stub().returns $promise: then: (callback) -> callback(products[0])
$provide.value "Products", Products
return
beforeEach module "myApp"
navigateTo = (to, params = {}) ->
# for some reason `$route` has to be injected here
beforeEach inject ($rootScope, $state) ->
$rootScope.$apply -> $state.go(to, params)
describe "route `/products`", ->
navigateTo "products.list"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/products/list.html")
.and.to.have.controller("products.IndexCtrl as index")
.and.to.resolve("products")
it "queries for the products", inject (Products) ->
expect(Products.query).to.be.called
it "loads the products", inject ($state) ->
products = $state.$current.locals.resolve.$$values.products
expect(products).to.have.length 2
expect(products).to.satisfy (collection) -> _.findWhere(collection, id: 123)
expect(products).to.satisfy (collection) -> _.findWhere(collection, id: 234)
describe "route `/products/create`", ->
navigateTo "products.create"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/products/form.html")
.and.to.have.controller("products.FormCtrl as form")
.and.to.resolve("product")
it "resolves with a new product instance", inject ($state, Products) ->
product = $state.$current.locals.resolve.$$values.product
expect(product).to.be.instanceOf(Products)
expect(product.id).to.be.undefined
describe "route `/products/:id`", ->
itIsRecognized = ->
it "is recognized", inject ($state) ->
expect($state.$current.parent)
.to.have.templateUrl("templates/products/show.html")
.and.to.have.controller("products.ShowCtrl as show")
.and.to.resolve("product")
itQueriesForAProduct = ->
it "queries for a product", inject ($state, Products) ->
expect(Products.get).to.be.calledWith(id: "123")
itLoadsAProduct = ->
it "loads a product", inject ($state) ->
product = $state.$current.locals.resolve.$$values.product
expect(product.id).to.equal 123
expect(product.name).to.equal "foo"
describe "`info` tab", ->
navigateTo "products.show.info", id: 123
itIsRecognized()
itQueriesForAProduct()
itLoadsAProduct()
describe "`details` tab", ->
navigateTo "products.show.details", id: 123
itIsRecognized()
itQueriesForAProduct()
itLoadsAProduct()
describe "route `/other`", ->
navigateTo "other"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/other.html")
.and.to.have.controller("OtherCtrl as other")
describe "route `/tasks`", ->
navigateTo "tasks"
it "is recognized", inject ($state) ->
expect($state.current)
.to.have.templateUrl("templates/tasks.html")
.and.to.have.controller("TasksCtrl as tasks")
|
[
{
"context": "# @fileoverview Tests for no-empty rule.\n# @author Nicholas C. Zakas\n###\n\n'use strict'\n\n#-----------------------------",
"end": 73,
"score": 0.999796450138092,
"start": 56,
"tag": "NAME",
"value": "Nicholas C. Zakas"
}
] | src/tests/rules/no-empty.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-empty rule.
# @author Nicholas C. Zakas
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-empty'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-empty', rule,
valid: [
'''
if foo
bar()
'''
'''
while foo
bar()
'''
'''
try
foo()
catch ex
foo()
'''
'''
switch foo
when 'foo'
break
'''
'do ->'
'foo = ->'
'''
if foo
;
### empty ###
'''
'''
while foo
### empty ###
;
'''
'''
for x in y
### empty ###
;
'''
'''
try
foo()
catch ex
### empty ###
'''
'''
try
foo()
catch ex
# empty
'''
'''
try
foo()
finally
# empty
'''
'''
try
foo()
finally
# test
'''
'''
try
foo()
finally
# hi i am off no use
'''
'''
try
foo()
catch ex
### test111 ###
'''
'''
if foo
bar()
else
# nothing in me
'''
'''
if foo
bar()
else
### ###
'''
'''
if foo
bar()
else
#
'''
,
code: '''
try
foo()
catch ex
'''
options: [allowEmptyCatch: yes]
,
code: '''
try
foo()
catch ex
finally
bar()
'''
options: [allowEmptyCatch: yes]
]
invalid: [
code: '''
try
catch ex
throw ex
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
throw ex
finally
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
if foo
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
while foo
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
for x in y
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
catch ex
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
finally
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
catch ex
finally
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
,
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
finally
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
,
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
]
| 19899 | ###*
# @fileoverview Tests for no-empty rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-empty'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-empty', rule,
valid: [
'''
if foo
bar()
'''
'''
while foo
bar()
'''
'''
try
foo()
catch ex
foo()
'''
'''
switch foo
when 'foo'
break
'''
'do ->'
'foo = ->'
'''
if foo
;
### empty ###
'''
'''
while foo
### empty ###
;
'''
'''
for x in y
### empty ###
;
'''
'''
try
foo()
catch ex
### empty ###
'''
'''
try
foo()
catch ex
# empty
'''
'''
try
foo()
finally
# empty
'''
'''
try
foo()
finally
# test
'''
'''
try
foo()
finally
# hi i am off no use
'''
'''
try
foo()
catch ex
### test111 ###
'''
'''
if foo
bar()
else
# nothing in me
'''
'''
if foo
bar()
else
### ###
'''
'''
if foo
bar()
else
#
'''
,
code: '''
try
foo()
catch ex
'''
options: [allowEmptyCatch: yes]
,
code: '''
try
foo()
catch ex
finally
bar()
'''
options: [allowEmptyCatch: yes]
]
invalid: [
code: '''
try
catch ex
throw ex
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
throw ex
finally
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
if foo
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
while foo
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
for x in y
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
catch ex
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
finally
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
catch ex
finally
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
,
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
finally
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
,
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
]
| true | ###*
# @fileoverview Tests for no-empty rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-empty'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-empty', rule,
valid: [
'''
if foo
bar()
'''
'''
while foo
bar()
'''
'''
try
foo()
catch ex
foo()
'''
'''
switch foo
when 'foo'
break
'''
'do ->'
'foo = ->'
'''
if foo
;
### empty ###
'''
'''
while foo
### empty ###
;
'''
'''
for x in y
### empty ###
;
'''
'''
try
foo()
catch ex
### empty ###
'''
'''
try
foo()
catch ex
# empty
'''
'''
try
foo()
finally
# empty
'''
'''
try
foo()
finally
# test
'''
'''
try
foo()
finally
# hi i am off no use
'''
'''
try
foo()
catch ex
### test111 ###
'''
'''
if foo
bar()
else
# nothing in me
'''
'''
if foo
bar()
else
### ###
'''
'''
if foo
bar()
else
#
'''
,
code: '''
try
foo()
catch ex
'''
options: [allowEmptyCatch: yes]
,
code: '''
try
foo()
catch ex
finally
bar()
'''
options: [allowEmptyCatch: yes]
]
invalid: [
code: '''
try
catch ex
throw ex
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
throw ex
finally
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
if foo
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
while foo
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
for x in y
;
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
catch ex
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
finally
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
catch ex
finally
'''
options: [allowEmptyCatch: yes]
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
,
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
,
code: '''
try
foo()
catch ex
finally
'''
errors: [
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
,
messageId: 'unexpected', data: {type: 'block'}, type: 'BlockStatement'
]
]
|
[
{
"context": "\n done(e)\n\n metadata = {title: 'hi', link: [{href: window.location.href}]}\n p",
"end": 9418,
"score": 0.7834463119506836,
"start": 9416,
"tag": "NAME",
"value": "hi"
},
{
"context": "urns(Promise.resolve({\n metadata: {title: 'hello'}\n uri: 'http://example.com/'\n }))\n\n ",
"end": 12825,
"score": 0.7883303761482239,
"start": 12820,
"tag": "NAME",
"value": "hello"
},
{
"context": "urns(Promise.resolve({\n metadata: {title: 'hello'}\n uri: 'http://example.com/'\n }))\n\n ",
"end": 13265,
"score": 0.8616915345191956,
"start": 13260,
"tag": "NAME",
"value": "hello"
}
] | src/annotator/test/guest-test.coffee | jccr/client | 1 | adder = require('../adder')
Observable = require('../util/observable').Observable
Plugin = require('../plugin')
Delegator = require('../delegator')
$ = require('jquery')
Delegator['@noCallThru'] = true
Guest = require('../guest')
rangeUtil = null
selections = null
raf = sinon.stub().yields()
raf['@noCallThru'] = true
scrollIntoView = sinon.stub()
scrollIntoView['@noCallThru'] = true
class FakeAdder
instance: null
constructor: ->
FakeAdder::instance = this
this.hide = sinon.stub()
this.showAt = sinon.stub()
this.target = sinon.stub()
class FakePlugin extends Plugin
instance: null
events:
'customEvent': 'customEventHandler'
constructor: ->
FakePlugin::instance = this
super
pluginInit: sinon.stub()
customEventHandler: sinon.stub()
# A little helper which returns a promise that resolves after a timeout
timeoutPromise = (millis = 0) ->
new Promise((resolve) -> setTimeout(resolve, millis))
describe 'Guest', ->
sandbox = sinon.sandbox.create()
CrossFrame = null
fakeCrossFrame = null
highlighter = null
guestConfig = null
htmlAnchoring = null
createGuest = (config={}) ->
config = Object.assign({}, guestConfig, config)
element = document.createElement('div')
guest = new Guest(element, config)
return guest
beforeEach ->
sinon.stub(console, 'warn')
FakeAdder::instance = null
rangeUtil = {
isSelectionBackwards: sinon.stub()
selectionFocusRect: sinon.stub()
}
selections = null
guestConfig = {pluginClasses: {}}
highlighter = {
highlightRange: sinon.stub()
removeHighlights: sinon.stub()
}
htmlAnchoring = {
anchor: sinon.stub()
}
Guest.$imports.$mock({
'./adder': {Adder: FakeAdder},
'./anchoring/html': htmlAnchoring,
'./highlighter': highlighter,
'./range-util': rangeUtil,
'./selections': (document) ->
new Observable((obs) ->
selections = obs
return () ->
)
'./delegator': Delegator,
'raf': raf,
'scroll-into-view': scrollIntoView,
})
fakeCrossFrame = {
onConnect: sinon.stub()
on: sinon.stub()
call: sinon.stub()
sync: sinon.stub()
destroy: sinon.stub()
}
CrossFrame = sandbox.stub().returns(fakeCrossFrame)
guestConfig.pluginClasses['CrossFrame'] = CrossFrame
afterEach ->
sandbox.restore()
console.warn.restore()
Guest.$imports.$restore()
describe 'plugins', ->
fakePlugin = null
guest = null
beforeEach ->
FakePlugin::instance = null
guestConfig.pluginClasses['FakePlugin'] = FakePlugin
guest = createGuest(FakePlugin: {})
fakePlugin = FakePlugin::instance
it 'load and "pluginInit" gets called', ->
assert.calledOnce(fakePlugin.pluginInit)
it 'hold reference to instance', ->
assert.equal(fakePlugin.annotator, guest)
it 'subscribe to events', ->
guest.publish('customEvent', ['1', '2'])
assert.calledWith(fakePlugin.customEventHandler, '1', '2')
it 'destroy when instance is destroyed', ->
sandbox.spy(fakePlugin, 'destroy')
guest.destroy()
assert.called(fakePlugin.destroy)
describe 'cross frame', ->
it 'provides an event bus for the annotation sync module', ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
assert.isFunction(options.on)
assert.isFunction(options.emit)
it 'publishes the "panelReady" event when a connection is established', ->
handler = sandbox.stub()
guest = createGuest()
guest.subscribe('panelReady', handler)
fakeCrossFrame.onConnect.yield()
assert.called(handler)
describe 'event subscription', ->
options = null
guest = null
beforeEach ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
it 'proxies the event into the annotator event system', ->
fooHandler = sandbox.stub()
barHandler = sandbox.stub()
options.on('foo', fooHandler)
options.on('bar', barHandler)
guest.publish('foo', ['1', '2'])
guest.publish('bar', ['1', '2'])
assert.calledWith(fooHandler, '1', '2')
assert.calledWith(barHandler, '1', '2')
describe 'event publication', ->
options = null
guest = null
beforeEach ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
it 'detaches annotations on "annotationDeleted"', ->
ann = {id: 1, $tag: 'tag1'}
sandbox.stub(guest, 'detach')
options.emit('annotationDeleted', ann)
assert.calledOnce(guest.detach)
assert.calledWith(guest.detach, ann)
it 'anchors annotations on "annotationsLoaded"', ->
ann1 = {id: 1, $tag: 'tag1'}
ann2 = {id: 2, $tag: 'tag2'}
sandbox.stub(guest, 'anchor')
options.emit('annotationsLoaded', [ann1, ann2])
assert.calledTwice(guest.anchor)
assert.calledWith(guest.anchor, ann1)
assert.calledWith(guest.anchor, ann2)
it 'proxies all other events into the annotator event system', ->
fooHandler = sandbox.stub()
barHandler = sandbox.stub()
guest.subscribe('foo', fooHandler)
guest.subscribe('bar', barHandler)
options.emit('foo', '1', '2')
options.emit('bar', '1', '2')
assert.calledWith(fooHandler, '1', '2')
assert.calledWith(barHandler, '1', '2')
describe 'annotation UI events', ->
emitGuestEvent = (event, args...) ->
fn(args...) for [evt, fn] in fakeCrossFrame.on.args when event == evt
describe 'on "focusAnnotations" event', ->
it 'focuses any annotations with a matching tag', ->
highlight0 = $('<span></span>')
highlight1 = $('<span></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight0.toArray()}
{annotation: {$tag: 'tag2'}, highlights: highlight1.toArray()}
]
emitGuestEvent('focusAnnotations', ['tag1'])
assert.isTrue(highlight0.hasClass('annotator-hl-focused'))
it 'unfocuses any annotations without a matching tag', ->
highlight0 = $('<span class="annotator-hl-focused"></span>')
highlight1 = $('<span class="annotator-hl-focused"></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight0.toArray()}
{annotation: {$tag: 'tag2'}, highlights: highlight1.toArray()}
]
emitGuestEvent('focusAnnotations', 'ctx', ['tag1'])
assert.isFalse(highlight1.hasClass('annotator-hl-focused'))
describe 'on "scrollToAnnotation" event', ->
beforeEach ->
scrollIntoView.reset()
it 'scrolls to the anchor with the matching tag', ->
highlight = $('<span></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray()}
]
emitGuestEvent('scrollToAnnotation', 'tag1')
assert.called(scrollIntoView)
assert.calledWith(scrollIntoView, highlight[0])
context 'when dispatching the "scrolltorange" event', ->
it 'emits with the range', ->
highlight = $('<span></span>')
guest = createGuest()
fakeRange = sinon.stub()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray(), range: fakeRange}
]
return new Promise (resolve) ->
guest.element.on 'scrolltorange', (event) ->
assert.equal(event.detail, fakeRange)
resolve()
emitGuestEvent('scrollToAnnotation', 'tag1')
it 'allows the default scroll behaviour to be prevented', ->
highlight = $('<span></span>')
guest = createGuest()
fakeRange = sinon.stub()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray(), range: fakeRange}
]
guest.element.on 'scrolltorange', (event) -> event.preventDefault()
emitGuestEvent('scrollToAnnotation', 'tag1')
assert.notCalled(scrollIntoView)
describe 'on "getDocumentInfo" event', ->
guest = null
beforeEach ->
document.title = 'hi'
guest = createGuest()
guest.plugins.PDF =
uri: sandbox.stub().returns(window.location.href)
getMetadata: sandbox.stub()
afterEach ->
sandbox.restore()
it 'calls the callback with the href and pdf metadata', (done) ->
assertComplete = (err, payload) ->
try
assert.equal(payload.uri, document.location.href)
assert.equal(payload.metadata, metadata)
done()
catch e
done(e)
metadata = {title: 'hi'}
promise = Promise.resolve(metadata)
guest.plugins.PDF.getMetadata.returns(promise)
emitGuestEvent('getDocumentInfo', assertComplete)
it 'calls the callback with the href and basic metadata if pdf fails', (done) ->
assertComplete = (err, payload) ->
try
assert.equal(payload.uri, window.location.href)
assert.deepEqual(payload.metadata, metadata)
done()
catch e
done(e)
metadata = {title: 'hi', link: [{href: window.location.href}]}
promise = Promise.reject(new Error('Not a PDF document'))
guest.plugins.PDF.getMetadata.returns(promise)
emitGuestEvent('getDocumentInfo', assertComplete)
describe 'document events', ->
guest = null
beforeEach ->
guest = createGuest()
it 'emits "hideSidebar" on cross frame when the user taps or clicks in the page', ->
methods =
'click': 'onElementClick'
'touchstart': 'onElementTouchStart'
for event in ['click', 'touchstart']
sandbox.spy(guest, methods[event])
guest.element.trigger(event)
assert.called(guest[methods[event]])
assert.calledWith(guest.plugins.CrossFrame.call, 'hideSidebar')
describe 'when the selection changes', ->
it 'shows the adder if the selection contains text', ->
guest = createGuest()
rangeUtil.selectionFocusRect.returns({left: 0, top: 0, width: 5, height: 5})
FakeAdder::instance.target.returns({
left: 0, top: 0, arrowDirection: adder.ARROW_POINTING_UP
})
selections.next({})
assert.called FakeAdder::instance.showAt
it 'hides the adder if the selection does not contain text', ->
guest = createGuest()
rangeUtil.selectionFocusRect.returns(null)
selections.next({})
assert.called FakeAdder::instance.hide
assert.notCalled FakeAdder::instance.showAt
it 'hides the adder if the selection is empty', ->
guest = createGuest()
selections.next(null)
assert.called FakeAdder::instance.hide
describe '#getDocumentInfo()', ->
guest = null
beforeEach ->
guest = createGuest()
guest.plugins.PDF =
uri: -> 'urn:x-pdf:001122'
getMetadata: sandbox.stub()
it 'preserves the components of the URI other than the fragment', ->
guest.plugins.PDF = null
guest.plugins.Document =
uri: -> 'http://foobar.com/things?id=42'
metadata: {}
return guest.getDocumentInfo().then ({uri}) ->
assert.equal uri, 'http://foobar.com/things?id=42'
it 'removes the fragment identifier from URIs', () ->
guest.plugins.PDF.uri = -> 'urn:x-pdf:aabbcc#'
return guest.getDocumentInfo().then ({uri}) ->
assert.equal uri, 'urn:x-pdf:aabbcc'
describe '#createAnnotation()', ->
it 'adds metadata to the annotation object', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'hello'}
uri: 'http://example.com/'
}))
annotation = {}
guest.createAnnotation(annotation)
timeoutPromise()
.then ->
assert.equal(annotation.uri, 'http://example.com/')
assert.deepEqual(annotation.document, {title: 'hello'})
it 'treats an argument as the annotation object', ->
guest = createGuest()
annotation = {foo: 'bar'}
annotation = guest.createAnnotation(annotation)
assert.equal(annotation.foo, 'bar')
it 'triggers a beforeAnnotationCreated event', (done) ->
guest = createGuest()
guest.subscribe('beforeAnnotationCreated', -> done())
guest.createAnnotation()
describe '#createComment()', ->
it 'adds metadata to the annotation object', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'hello'}
uri: 'http://example.com/'
}))
annotation = guest.createComment()
timeoutPromise()
.then ->
assert.equal(annotation.uri, 'http://example.com/')
assert.deepEqual(annotation.document, {title: 'hello'})
it 'adds a single target with a source property', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'hello'}
uri: 'http://example.com/'
}))
annotation = guest.createComment()
timeoutPromise()
.then ->
assert.deepEqual(annotation.target, [{source: 'http://example.com/'}])
it 'triggers a beforeAnnotationCreated event', (done) ->
guest = createGuest()
guest.subscribe('beforeAnnotationCreated', -> done())
guest.createComment()
describe '#anchor()', ->
el = null
range = null
beforeEach ->
el = document.createElement('span')
txt = document.createTextNode('hello')
el.appendChild(txt)
document.body.appendChild(el)
range = document.createRange()
range.selectNode(el)
afterEach ->
document.body.removeChild(el)
it "doesn't mark an annotation lacking targets as an orphan", ->
guest = createGuest()
annotation = target: []
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation with a selectorless target as an orphan", ->
guest = createGuest()
annotation = {target: [{source: 'wibble'}]}
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation with only selectorless targets as an orphan", ->
guest = createGuest()
annotation = {target: [{source: 'foo'}, {source: 'bar'}]}
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation in which the target anchors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]},
]
}
htmlAnchoring.anchor.returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation in which at least one target anchors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]},
]
}
htmlAnchoring.anchor
.onFirstCall().returns(Promise.reject())
.onSecondCall().returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "marks an annotation in which the target fails to anchor as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
]
}
htmlAnchoring.anchor.returns(Promise.reject())
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "marks an annotation in which all (suitable) targets fail to anchor as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
{selector: [{type: 'TextQuoteSelector', exact: 'neitherami'}]},
]
}
htmlAnchoring.anchor.returns(Promise.reject())
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "marks an annotation where the target has no TextQuoteSelectors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextPositionSelector', start: 0, end: 5}]},
]
}
# This shouldn't be called, but if it is, we successfully anchor so that
# this test is guaranteed to fail.
htmlAnchoring.anchor.returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "does not attempt to anchor targets which have no TextQuoteSelector", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextPositionSelector', start: 0, end: 5}]},
]
}
guest.anchor(annotation).then ->
assert.notCalled(htmlAnchoring.anchor)
it 'updates the cross frame and bucket bar plugins', () ->
guest = createGuest()
guest.plugins.CrossFrame =
sync: sinon.stub()
guest.plugins.BucketBar =
update: sinon.stub()
annotation = {}
return guest.anchor(annotation).then ->
assert.called(guest.plugins.BucketBar.update)
assert.called(guest.plugins.CrossFrame.sync)
it 'returns a promise of the anchors for the annotation', () ->
guest = createGuest()
highlights = [document.createElement('span')]
htmlAnchoring.anchor.returns(Promise.resolve(range))
highlighter.highlightRange.returns(highlights)
target = {selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}
return guest.anchor({target: [target]}).then (anchors) ->
assert.equal(anchors.length, 1)
it 'adds the anchor to the "anchors" instance property"', () ->
guest = createGuest()
highlights = [document.createElement('span')]
htmlAnchoring.anchor.returns(Promise.resolve(range))
highlighter.highlightRange.returns(highlights)
target = {selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}
annotation = {target: [target]}
return guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 1)
assert.strictEqual(guest.anchors[0].annotation, annotation)
assert.strictEqual(guest.anchors[0].target, target)
assert.strictEqual(guest.anchors[0].range, range)
assert.strictEqual(guest.anchors[0].highlights, highlights)
it 'destroys targets that have been removed from the annotation', () ->
annotation = {}
target = {}
highlights = []
guest = createGuest()
guest.anchors = [{annotation, target, highlights}]
removeHighlights = highlighter.removeHighlights
return guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 0)
assert.calledOnce(removeHighlights)
assert.calledWith(removeHighlights, highlights)
it 'does not reanchor targets that are already anchored', () ->
guest = createGuest()
annotation = target: [{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}]
htmlAnchoring.anchor.returns(Promise.resolve(range))
return guest.anchor(annotation).then ->
guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 1)
assert.calledOnce(htmlAnchoring.anchor)
describe '#detach()', ->
it 'removes the anchors from the "anchors" instance variable', ->
guest = createGuest()
annotation = {}
guest.anchors.push({annotation})
guest.detach(annotation)
assert.equal(guest.anchors.length, 0)
it 'updates the bucket bar plugin', ->
guest = createGuest()
guest.plugins.BucketBar = update: sinon.stub()
annotation = {}
guest.anchors.push({annotation})
guest.detach(annotation)
assert.calledOnce(guest.plugins.BucketBar.update)
it 'publishes the "annotationDeleted" event', ->
guest = createGuest()
annotation = {}
publish = sandbox.stub(guest, 'publish')
guest.deleteAnnotation(annotation)
assert.calledOnce(publish)
assert.calledWith(publish, 'annotationDeleted', [annotation])
it 'removes any highlights associated with the annotation', ->
guest = createGuest()
annotation = {}
highlights = [document.createElement('span')]
removeHighlights = highlighter.removeHighlights
guest.anchors.push({annotation, highlights})
guest.deleteAnnotation(annotation)
assert.calledOnce(removeHighlights)
assert.calledWith(removeHighlights, highlights)
| 25240 | adder = require('../adder')
Observable = require('../util/observable').Observable
Plugin = require('../plugin')
Delegator = require('../delegator')
$ = require('jquery')
Delegator['@noCallThru'] = true
Guest = require('../guest')
rangeUtil = null
selections = null
raf = sinon.stub().yields()
raf['@noCallThru'] = true
scrollIntoView = sinon.stub()
scrollIntoView['@noCallThru'] = true
class FakeAdder
instance: null
constructor: ->
FakeAdder::instance = this
this.hide = sinon.stub()
this.showAt = sinon.stub()
this.target = sinon.stub()
class FakePlugin extends Plugin
instance: null
events:
'customEvent': 'customEventHandler'
constructor: ->
FakePlugin::instance = this
super
pluginInit: sinon.stub()
customEventHandler: sinon.stub()
# A little helper which returns a promise that resolves after a timeout
timeoutPromise = (millis = 0) ->
new Promise((resolve) -> setTimeout(resolve, millis))
describe 'Guest', ->
sandbox = sinon.sandbox.create()
CrossFrame = null
fakeCrossFrame = null
highlighter = null
guestConfig = null
htmlAnchoring = null
createGuest = (config={}) ->
config = Object.assign({}, guestConfig, config)
element = document.createElement('div')
guest = new Guest(element, config)
return guest
beforeEach ->
sinon.stub(console, 'warn')
FakeAdder::instance = null
rangeUtil = {
isSelectionBackwards: sinon.stub()
selectionFocusRect: sinon.stub()
}
selections = null
guestConfig = {pluginClasses: {}}
highlighter = {
highlightRange: sinon.stub()
removeHighlights: sinon.stub()
}
htmlAnchoring = {
anchor: sinon.stub()
}
Guest.$imports.$mock({
'./adder': {Adder: FakeAdder},
'./anchoring/html': htmlAnchoring,
'./highlighter': highlighter,
'./range-util': rangeUtil,
'./selections': (document) ->
new Observable((obs) ->
selections = obs
return () ->
)
'./delegator': Delegator,
'raf': raf,
'scroll-into-view': scrollIntoView,
})
fakeCrossFrame = {
onConnect: sinon.stub()
on: sinon.stub()
call: sinon.stub()
sync: sinon.stub()
destroy: sinon.stub()
}
CrossFrame = sandbox.stub().returns(fakeCrossFrame)
guestConfig.pluginClasses['CrossFrame'] = CrossFrame
afterEach ->
sandbox.restore()
console.warn.restore()
Guest.$imports.$restore()
describe 'plugins', ->
fakePlugin = null
guest = null
beforeEach ->
FakePlugin::instance = null
guestConfig.pluginClasses['FakePlugin'] = FakePlugin
guest = createGuest(FakePlugin: {})
fakePlugin = FakePlugin::instance
it 'load and "pluginInit" gets called', ->
assert.calledOnce(fakePlugin.pluginInit)
it 'hold reference to instance', ->
assert.equal(fakePlugin.annotator, guest)
it 'subscribe to events', ->
guest.publish('customEvent', ['1', '2'])
assert.calledWith(fakePlugin.customEventHandler, '1', '2')
it 'destroy when instance is destroyed', ->
sandbox.spy(fakePlugin, 'destroy')
guest.destroy()
assert.called(fakePlugin.destroy)
describe 'cross frame', ->
it 'provides an event bus for the annotation sync module', ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
assert.isFunction(options.on)
assert.isFunction(options.emit)
it 'publishes the "panelReady" event when a connection is established', ->
handler = sandbox.stub()
guest = createGuest()
guest.subscribe('panelReady', handler)
fakeCrossFrame.onConnect.yield()
assert.called(handler)
describe 'event subscription', ->
options = null
guest = null
beforeEach ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
it 'proxies the event into the annotator event system', ->
fooHandler = sandbox.stub()
barHandler = sandbox.stub()
options.on('foo', fooHandler)
options.on('bar', barHandler)
guest.publish('foo', ['1', '2'])
guest.publish('bar', ['1', '2'])
assert.calledWith(fooHandler, '1', '2')
assert.calledWith(barHandler, '1', '2')
describe 'event publication', ->
options = null
guest = null
beforeEach ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
it 'detaches annotations on "annotationDeleted"', ->
ann = {id: 1, $tag: 'tag1'}
sandbox.stub(guest, 'detach')
options.emit('annotationDeleted', ann)
assert.calledOnce(guest.detach)
assert.calledWith(guest.detach, ann)
it 'anchors annotations on "annotationsLoaded"', ->
ann1 = {id: 1, $tag: 'tag1'}
ann2 = {id: 2, $tag: 'tag2'}
sandbox.stub(guest, 'anchor')
options.emit('annotationsLoaded', [ann1, ann2])
assert.calledTwice(guest.anchor)
assert.calledWith(guest.anchor, ann1)
assert.calledWith(guest.anchor, ann2)
it 'proxies all other events into the annotator event system', ->
fooHandler = sandbox.stub()
barHandler = sandbox.stub()
guest.subscribe('foo', fooHandler)
guest.subscribe('bar', barHandler)
options.emit('foo', '1', '2')
options.emit('bar', '1', '2')
assert.calledWith(fooHandler, '1', '2')
assert.calledWith(barHandler, '1', '2')
describe 'annotation UI events', ->
emitGuestEvent = (event, args...) ->
fn(args...) for [evt, fn] in fakeCrossFrame.on.args when event == evt
describe 'on "focusAnnotations" event', ->
it 'focuses any annotations with a matching tag', ->
highlight0 = $('<span></span>')
highlight1 = $('<span></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight0.toArray()}
{annotation: {$tag: 'tag2'}, highlights: highlight1.toArray()}
]
emitGuestEvent('focusAnnotations', ['tag1'])
assert.isTrue(highlight0.hasClass('annotator-hl-focused'))
it 'unfocuses any annotations without a matching tag', ->
highlight0 = $('<span class="annotator-hl-focused"></span>')
highlight1 = $('<span class="annotator-hl-focused"></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight0.toArray()}
{annotation: {$tag: 'tag2'}, highlights: highlight1.toArray()}
]
emitGuestEvent('focusAnnotations', 'ctx', ['tag1'])
assert.isFalse(highlight1.hasClass('annotator-hl-focused'))
describe 'on "scrollToAnnotation" event', ->
beforeEach ->
scrollIntoView.reset()
it 'scrolls to the anchor with the matching tag', ->
highlight = $('<span></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray()}
]
emitGuestEvent('scrollToAnnotation', 'tag1')
assert.called(scrollIntoView)
assert.calledWith(scrollIntoView, highlight[0])
context 'when dispatching the "scrolltorange" event', ->
it 'emits with the range', ->
highlight = $('<span></span>')
guest = createGuest()
fakeRange = sinon.stub()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray(), range: fakeRange}
]
return new Promise (resolve) ->
guest.element.on 'scrolltorange', (event) ->
assert.equal(event.detail, fakeRange)
resolve()
emitGuestEvent('scrollToAnnotation', 'tag1')
it 'allows the default scroll behaviour to be prevented', ->
highlight = $('<span></span>')
guest = createGuest()
fakeRange = sinon.stub()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray(), range: fakeRange}
]
guest.element.on 'scrolltorange', (event) -> event.preventDefault()
emitGuestEvent('scrollToAnnotation', 'tag1')
assert.notCalled(scrollIntoView)
describe 'on "getDocumentInfo" event', ->
guest = null
beforeEach ->
document.title = 'hi'
guest = createGuest()
guest.plugins.PDF =
uri: sandbox.stub().returns(window.location.href)
getMetadata: sandbox.stub()
afterEach ->
sandbox.restore()
it 'calls the callback with the href and pdf metadata', (done) ->
assertComplete = (err, payload) ->
try
assert.equal(payload.uri, document.location.href)
assert.equal(payload.metadata, metadata)
done()
catch e
done(e)
metadata = {title: 'hi'}
promise = Promise.resolve(metadata)
guest.plugins.PDF.getMetadata.returns(promise)
emitGuestEvent('getDocumentInfo', assertComplete)
it 'calls the callback with the href and basic metadata if pdf fails', (done) ->
assertComplete = (err, payload) ->
try
assert.equal(payload.uri, window.location.href)
assert.deepEqual(payload.metadata, metadata)
done()
catch e
done(e)
metadata = {title: '<NAME>', link: [{href: window.location.href}]}
promise = Promise.reject(new Error('Not a PDF document'))
guest.plugins.PDF.getMetadata.returns(promise)
emitGuestEvent('getDocumentInfo', assertComplete)
describe 'document events', ->
guest = null
beforeEach ->
guest = createGuest()
it 'emits "hideSidebar" on cross frame when the user taps or clicks in the page', ->
methods =
'click': 'onElementClick'
'touchstart': 'onElementTouchStart'
for event in ['click', 'touchstart']
sandbox.spy(guest, methods[event])
guest.element.trigger(event)
assert.called(guest[methods[event]])
assert.calledWith(guest.plugins.CrossFrame.call, 'hideSidebar')
describe 'when the selection changes', ->
it 'shows the adder if the selection contains text', ->
guest = createGuest()
rangeUtil.selectionFocusRect.returns({left: 0, top: 0, width: 5, height: 5})
FakeAdder::instance.target.returns({
left: 0, top: 0, arrowDirection: adder.ARROW_POINTING_UP
})
selections.next({})
assert.called FakeAdder::instance.showAt
it 'hides the adder if the selection does not contain text', ->
guest = createGuest()
rangeUtil.selectionFocusRect.returns(null)
selections.next({})
assert.called FakeAdder::instance.hide
assert.notCalled FakeAdder::instance.showAt
it 'hides the adder if the selection is empty', ->
guest = createGuest()
selections.next(null)
assert.called FakeAdder::instance.hide
describe '#getDocumentInfo()', ->
guest = null
beforeEach ->
guest = createGuest()
guest.plugins.PDF =
uri: -> 'urn:x-pdf:001122'
getMetadata: sandbox.stub()
it 'preserves the components of the URI other than the fragment', ->
guest.plugins.PDF = null
guest.plugins.Document =
uri: -> 'http://foobar.com/things?id=42'
metadata: {}
return guest.getDocumentInfo().then ({uri}) ->
assert.equal uri, 'http://foobar.com/things?id=42'
it 'removes the fragment identifier from URIs', () ->
guest.plugins.PDF.uri = -> 'urn:x-pdf:aabbcc#'
return guest.getDocumentInfo().then ({uri}) ->
assert.equal uri, 'urn:x-pdf:aabbcc'
describe '#createAnnotation()', ->
it 'adds metadata to the annotation object', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'hello'}
uri: 'http://example.com/'
}))
annotation = {}
guest.createAnnotation(annotation)
timeoutPromise()
.then ->
assert.equal(annotation.uri, 'http://example.com/')
assert.deepEqual(annotation.document, {title: 'hello'})
it 'treats an argument as the annotation object', ->
guest = createGuest()
annotation = {foo: 'bar'}
annotation = guest.createAnnotation(annotation)
assert.equal(annotation.foo, 'bar')
it 'triggers a beforeAnnotationCreated event', (done) ->
guest = createGuest()
guest.subscribe('beforeAnnotationCreated', -> done())
guest.createAnnotation()
describe '#createComment()', ->
it 'adds metadata to the annotation object', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: '<NAME>'}
uri: 'http://example.com/'
}))
annotation = guest.createComment()
timeoutPromise()
.then ->
assert.equal(annotation.uri, 'http://example.com/')
assert.deepEqual(annotation.document, {title: 'hello'})
it 'adds a single target with a source property', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: '<NAME>'}
uri: 'http://example.com/'
}))
annotation = guest.createComment()
timeoutPromise()
.then ->
assert.deepEqual(annotation.target, [{source: 'http://example.com/'}])
it 'triggers a beforeAnnotationCreated event', (done) ->
guest = createGuest()
guest.subscribe('beforeAnnotationCreated', -> done())
guest.createComment()
describe '#anchor()', ->
el = null
range = null
beforeEach ->
el = document.createElement('span')
txt = document.createTextNode('hello')
el.appendChild(txt)
document.body.appendChild(el)
range = document.createRange()
range.selectNode(el)
afterEach ->
document.body.removeChild(el)
it "doesn't mark an annotation lacking targets as an orphan", ->
guest = createGuest()
annotation = target: []
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation with a selectorless target as an orphan", ->
guest = createGuest()
annotation = {target: [{source: 'wibble'}]}
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation with only selectorless targets as an orphan", ->
guest = createGuest()
annotation = {target: [{source: 'foo'}, {source: 'bar'}]}
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation in which the target anchors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]},
]
}
htmlAnchoring.anchor.returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation in which at least one target anchors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]},
]
}
htmlAnchoring.anchor
.onFirstCall().returns(Promise.reject())
.onSecondCall().returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "marks an annotation in which the target fails to anchor as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
]
}
htmlAnchoring.anchor.returns(Promise.reject())
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "marks an annotation in which all (suitable) targets fail to anchor as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
{selector: [{type: 'TextQuoteSelector', exact: 'neitherami'}]},
]
}
htmlAnchoring.anchor.returns(Promise.reject())
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "marks an annotation where the target has no TextQuoteSelectors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextPositionSelector', start: 0, end: 5}]},
]
}
# This shouldn't be called, but if it is, we successfully anchor so that
# this test is guaranteed to fail.
htmlAnchoring.anchor.returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "does not attempt to anchor targets which have no TextQuoteSelector", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextPositionSelector', start: 0, end: 5}]},
]
}
guest.anchor(annotation).then ->
assert.notCalled(htmlAnchoring.anchor)
it 'updates the cross frame and bucket bar plugins', () ->
guest = createGuest()
guest.plugins.CrossFrame =
sync: sinon.stub()
guest.plugins.BucketBar =
update: sinon.stub()
annotation = {}
return guest.anchor(annotation).then ->
assert.called(guest.plugins.BucketBar.update)
assert.called(guest.plugins.CrossFrame.sync)
it 'returns a promise of the anchors for the annotation', () ->
guest = createGuest()
highlights = [document.createElement('span')]
htmlAnchoring.anchor.returns(Promise.resolve(range))
highlighter.highlightRange.returns(highlights)
target = {selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}
return guest.anchor({target: [target]}).then (anchors) ->
assert.equal(anchors.length, 1)
it 'adds the anchor to the "anchors" instance property"', () ->
guest = createGuest()
highlights = [document.createElement('span')]
htmlAnchoring.anchor.returns(Promise.resolve(range))
highlighter.highlightRange.returns(highlights)
target = {selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}
annotation = {target: [target]}
return guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 1)
assert.strictEqual(guest.anchors[0].annotation, annotation)
assert.strictEqual(guest.anchors[0].target, target)
assert.strictEqual(guest.anchors[0].range, range)
assert.strictEqual(guest.anchors[0].highlights, highlights)
it 'destroys targets that have been removed from the annotation', () ->
annotation = {}
target = {}
highlights = []
guest = createGuest()
guest.anchors = [{annotation, target, highlights}]
removeHighlights = highlighter.removeHighlights
return guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 0)
assert.calledOnce(removeHighlights)
assert.calledWith(removeHighlights, highlights)
it 'does not reanchor targets that are already anchored', () ->
guest = createGuest()
annotation = target: [{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}]
htmlAnchoring.anchor.returns(Promise.resolve(range))
return guest.anchor(annotation).then ->
guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 1)
assert.calledOnce(htmlAnchoring.anchor)
describe '#detach()', ->
it 'removes the anchors from the "anchors" instance variable', ->
guest = createGuest()
annotation = {}
guest.anchors.push({annotation})
guest.detach(annotation)
assert.equal(guest.anchors.length, 0)
it 'updates the bucket bar plugin', ->
guest = createGuest()
guest.plugins.BucketBar = update: sinon.stub()
annotation = {}
guest.anchors.push({annotation})
guest.detach(annotation)
assert.calledOnce(guest.plugins.BucketBar.update)
it 'publishes the "annotationDeleted" event', ->
guest = createGuest()
annotation = {}
publish = sandbox.stub(guest, 'publish')
guest.deleteAnnotation(annotation)
assert.calledOnce(publish)
assert.calledWith(publish, 'annotationDeleted', [annotation])
it 'removes any highlights associated with the annotation', ->
guest = createGuest()
annotation = {}
highlights = [document.createElement('span')]
removeHighlights = highlighter.removeHighlights
guest.anchors.push({annotation, highlights})
guest.deleteAnnotation(annotation)
assert.calledOnce(removeHighlights)
assert.calledWith(removeHighlights, highlights)
| true | adder = require('../adder')
Observable = require('../util/observable').Observable
Plugin = require('../plugin')
Delegator = require('../delegator')
$ = require('jquery')
Delegator['@noCallThru'] = true
Guest = require('../guest')
rangeUtil = null
selections = null
raf = sinon.stub().yields()
raf['@noCallThru'] = true
scrollIntoView = sinon.stub()
scrollIntoView['@noCallThru'] = true
class FakeAdder
instance: null
constructor: ->
FakeAdder::instance = this
this.hide = sinon.stub()
this.showAt = sinon.stub()
this.target = sinon.stub()
class FakePlugin extends Plugin
instance: null
events:
'customEvent': 'customEventHandler'
constructor: ->
FakePlugin::instance = this
super
pluginInit: sinon.stub()
customEventHandler: sinon.stub()
# A little helper which returns a promise that resolves after a timeout
timeoutPromise = (millis = 0) ->
new Promise((resolve) -> setTimeout(resolve, millis))
describe 'Guest', ->
sandbox = sinon.sandbox.create()
CrossFrame = null
fakeCrossFrame = null
highlighter = null
guestConfig = null
htmlAnchoring = null
createGuest = (config={}) ->
config = Object.assign({}, guestConfig, config)
element = document.createElement('div')
guest = new Guest(element, config)
return guest
beforeEach ->
sinon.stub(console, 'warn')
FakeAdder::instance = null
rangeUtil = {
isSelectionBackwards: sinon.stub()
selectionFocusRect: sinon.stub()
}
selections = null
guestConfig = {pluginClasses: {}}
highlighter = {
highlightRange: sinon.stub()
removeHighlights: sinon.stub()
}
htmlAnchoring = {
anchor: sinon.stub()
}
Guest.$imports.$mock({
'./adder': {Adder: FakeAdder},
'./anchoring/html': htmlAnchoring,
'./highlighter': highlighter,
'./range-util': rangeUtil,
'./selections': (document) ->
new Observable((obs) ->
selections = obs
return () ->
)
'./delegator': Delegator,
'raf': raf,
'scroll-into-view': scrollIntoView,
})
fakeCrossFrame = {
onConnect: sinon.stub()
on: sinon.stub()
call: sinon.stub()
sync: sinon.stub()
destroy: sinon.stub()
}
CrossFrame = sandbox.stub().returns(fakeCrossFrame)
guestConfig.pluginClasses['CrossFrame'] = CrossFrame
afterEach ->
sandbox.restore()
console.warn.restore()
Guest.$imports.$restore()
describe 'plugins', ->
fakePlugin = null
guest = null
beforeEach ->
FakePlugin::instance = null
guestConfig.pluginClasses['FakePlugin'] = FakePlugin
guest = createGuest(FakePlugin: {})
fakePlugin = FakePlugin::instance
it 'load and "pluginInit" gets called', ->
assert.calledOnce(fakePlugin.pluginInit)
it 'hold reference to instance', ->
assert.equal(fakePlugin.annotator, guest)
it 'subscribe to events', ->
guest.publish('customEvent', ['1', '2'])
assert.calledWith(fakePlugin.customEventHandler, '1', '2')
it 'destroy when instance is destroyed', ->
sandbox.spy(fakePlugin, 'destroy')
guest.destroy()
assert.called(fakePlugin.destroy)
describe 'cross frame', ->
it 'provides an event bus for the annotation sync module', ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
assert.isFunction(options.on)
assert.isFunction(options.emit)
it 'publishes the "panelReady" event when a connection is established', ->
handler = sandbox.stub()
guest = createGuest()
guest.subscribe('panelReady', handler)
fakeCrossFrame.onConnect.yield()
assert.called(handler)
describe 'event subscription', ->
options = null
guest = null
beforeEach ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
it 'proxies the event into the annotator event system', ->
fooHandler = sandbox.stub()
barHandler = sandbox.stub()
options.on('foo', fooHandler)
options.on('bar', barHandler)
guest.publish('foo', ['1', '2'])
guest.publish('bar', ['1', '2'])
assert.calledWith(fooHandler, '1', '2')
assert.calledWith(barHandler, '1', '2')
describe 'event publication', ->
options = null
guest = null
beforeEach ->
guest = createGuest()
options = CrossFrame.lastCall.args[1]
it 'detaches annotations on "annotationDeleted"', ->
ann = {id: 1, $tag: 'tag1'}
sandbox.stub(guest, 'detach')
options.emit('annotationDeleted', ann)
assert.calledOnce(guest.detach)
assert.calledWith(guest.detach, ann)
it 'anchors annotations on "annotationsLoaded"', ->
ann1 = {id: 1, $tag: 'tag1'}
ann2 = {id: 2, $tag: 'tag2'}
sandbox.stub(guest, 'anchor')
options.emit('annotationsLoaded', [ann1, ann2])
assert.calledTwice(guest.anchor)
assert.calledWith(guest.anchor, ann1)
assert.calledWith(guest.anchor, ann2)
it 'proxies all other events into the annotator event system', ->
fooHandler = sandbox.stub()
barHandler = sandbox.stub()
guest.subscribe('foo', fooHandler)
guest.subscribe('bar', barHandler)
options.emit('foo', '1', '2')
options.emit('bar', '1', '2')
assert.calledWith(fooHandler, '1', '2')
assert.calledWith(barHandler, '1', '2')
describe 'annotation UI events', ->
emitGuestEvent = (event, args...) ->
fn(args...) for [evt, fn] in fakeCrossFrame.on.args when event == evt
describe 'on "focusAnnotations" event', ->
it 'focuses any annotations with a matching tag', ->
highlight0 = $('<span></span>')
highlight1 = $('<span></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight0.toArray()}
{annotation: {$tag: 'tag2'}, highlights: highlight1.toArray()}
]
emitGuestEvent('focusAnnotations', ['tag1'])
assert.isTrue(highlight0.hasClass('annotator-hl-focused'))
it 'unfocuses any annotations without a matching tag', ->
highlight0 = $('<span class="annotator-hl-focused"></span>')
highlight1 = $('<span class="annotator-hl-focused"></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight0.toArray()}
{annotation: {$tag: 'tag2'}, highlights: highlight1.toArray()}
]
emitGuestEvent('focusAnnotations', 'ctx', ['tag1'])
assert.isFalse(highlight1.hasClass('annotator-hl-focused'))
describe 'on "scrollToAnnotation" event', ->
beforeEach ->
scrollIntoView.reset()
it 'scrolls to the anchor with the matching tag', ->
highlight = $('<span></span>')
guest = createGuest()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray()}
]
emitGuestEvent('scrollToAnnotation', 'tag1')
assert.called(scrollIntoView)
assert.calledWith(scrollIntoView, highlight[0])
context 'when dispatching the "scrolltorange" event', ->
it 'emits with the range', ->
highlight = $('<span></span>')
guest = createGuest()
fakeRange = sinon.stub()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray(), range: fakeRange}
]
return new Promise (resolve) ->
guest.element.on 'scrolltorange', (event) ->
assert.equal(event.detail, fakeRange)
resolve()
emitGuestEvent('scrollToAnnotation', 'tag1')
it 'allows the default scroll behaviour to be prevented', ->
highlight = $('<span></span>')
guest = createGuest()
fakeRange = sinon.stub()
guest.anchors = [
{annotation: {$tag: 'tag1'}, highlights: highlight.toArray(), range: fakeRange}
]
guest.element.on 'scrolltorange', (event) -> event.preventDefault()
emitGuestEvent('scrollToAnnotation', 'tag1')
assert.notCalled(scrollIntoView)
describe 'on "getDocumentInfo" event', ->
guest = null
beforeEach ->
document.title = 'hi'
guest = createGuest()
guest.plugins.PDF =
uri: sandbox.stub().returns(window.location.href)
getMetadata: sandbox.stub()
afterEach ->
sandbox.restore()
it 'calls the callback with the href and pdf metadata', (done) ->
assertComplete = (err, payload) ->
try
assert.equal(payload.uri, document.location.href)
assert.equal(payload.metadata, metadata)
done()
catch e
done(e)
metadata = {title: 'hi'}
promise = Promise.resolve(metadata)
guest.plugins.PDF.getMetadata.returns(promise)
emitGuestEvent('getDocumentInfo', assertComplete)
it 'calls the callback with the href and basic metadata if pdf fails', (done) ->
assertComplete = (err, payload) ->
try
assert.equal(payload.uri, window.location.href)
assert.deepEqual(payload.metadata, metadata)
done()
catch e
done(e)
metadata = {title: 'PI:NAME:<NAME>END_PI', link: [{href: window.location.href}]}
promise = Promise.reject(new Error('Not a PDF document'))
guest.plugins.PDF.getMetadata.returns(promise)
emitGuestEvent('getDocumentInfo', assertComplete)
describe 'document events', ->
guest = null
beforeEach ->
guest = createGuest()
it 'emits "hideSidebar" on cross frame when the user taps or clicks in the page', ->
methods =
'click': 'onElementClick'
'touchstart': 'onElementTouchStart'
for event in ['click', 'touchstart']
sandbox.spy(guest, methods[event])
guest.element.trigger(event)
assert.called(guest[methods[event]])
assert.calledWith(guest.plugins.CrossFrame.call, 'hideSidebar')
describe 'when the selection changes', ->
it 'shows the adder if the selection contains text', ->
guest = createGuest()
rangeUtil.selectionFocusRect.returns({left: 0, top: 0, width: 5, height: 5})
FakeAdder::instance.target.returns({
left: 0, top: 0, arrowDirection: adder.ARROW_POINTING_UP
})
selections.next({})
assert.called FakeAdder::instance.showAt
it 'hides the adder if the selection does not contain text', ->
guest = createGuest()
rangeUtil.selectionFocusRect.returns(null)
selections.next({})
assert.called FakeAdder::instance.hide
assert.notCalled FakeAdder::instance.showAt
it 'hides the adder if the selection is empty', ->
guest = createGuest()
selections.next(null)
assert.called FakeAdder::instance.hide
describe '#getDocumentInfo()', ->
guest = null
beforeEach ->
guest = createGuest()
guest.plugins.PDF =
uri: -> 'urn:x-pdf:001122'
getMetadata: sandbox.stub()
it 'preserves the components of the URI other than the fragment', ->
guest.plugins.PDF = null
guest.plugins.Document =
uri: -> 'http://foobar.com/things?id=42'
metadata: {}
return guest.getDocumentInfo().then ({uri}) ->
assert.equal uri, 'http://foobar.com/things?id=42'
it 'removes the fragment identifier from URIs', () ->
guest.plugins.PDF.uri = -> 'urn:x-pdf:aabbcc#'
return guest.getDocumentInfo().then ({uri}) ->
assert.equal uri, 'urn:x-pdf:aabbcc'
describe '#createAnnotation()', ->
it 'adds metadata to the annotation object', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'hello'}
uri: 'http://example.com/'
}))
annotation = {}
guest.createAnnotation(annotation)
timeoutPromise()
.then ->
assert.equal(annotation.uri, 'http://example.com/')
assert.deepEqual(annotation.document, {title: 'hello'})
it 'treats an argument as the annotation object', ->
guest = createGuest()
annotation = {foo: 'bar'}
annotation = guest.createAnnotation(annotation)
assert.equal(annotation.foo, 'bar')
it 'triggers a beforeAnnotationCreated event', (done) ->
guest = createGuest()
guest.subscribe('beforeAnnotationCreated', -> done())
guest.createAnnotation()
describe '#createComment()', ->
it 'adds metadata to the annotation object', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'PI:NAME:<NAME>END_PI'}
uri: 'http://example.com/'
}))
annotation = guest.createComment()
timeoutPromise()
.then ->
assert.equal(annotation.uri, 'http://example.com/')
assert.deepEqual(annotation.document, {title: 'hello'})
it 'adds a single target with a source property', ->
guest = createGuest()
sinon.stub(guest, 'getDocumentInfo').returns(Promise.resolve({
metadata: {title: 'PI:NAME:<NAME>END_PI'}
uri: 'http://example.com/'
}))
annotation = guest.createComment()
timeoutPromise()
.then ->
assert.deepEqual(annotation.target, [{source: 'http://example.com/'}])
it 'triggers a beforeAnnotationCreated event', (done) ->
guest = createGuest()
guest.subscribe('beforeAnnotationCreated', -> done())
guest.createComment()
describe '#anchor()', ->
el = null
range = null
beforeEach ->
el = document.createElement('span')
txt = document.createTextNode('hello')
el.appendChild(txt)
document.body.appendChild(el)
range = document.createRange()
range.selectNode(el)
afterEach ->
document.body.removeChild(el)
it "doesn't mark an annotation lacking targets as an orphan", ->
guest = createGuest()
annotation = target: []
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation with a selectorless target as an orphan", ->
guest = createGuest()
annotation = {target: [{source: 'wibble'}]}
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation with only selectorless targets as an orphan", ->
guest = createGuest()
annotation = {target: [{source: 'foo'}, {source: 'bar'}]}
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation in which the target anchors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]},
]
}
htmlAnchoring.anchor.returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "doesn't mark an annotation in which at least one target anchors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]},
]
}
htmlAnchoring.anchor
.onFirstCall().returns(Promise.reject())
.onSecondCall().returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isFalse(annotation.$orphan)
it "marks an annotation in which the target fails to anchor as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
]
}
htmlAnchoring.anchor.returns(Promise.reject())
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "marks an annotation in which all (suitable) targets fail to anchor as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextQuoteSelector', exact: 'notinhere'}]},
{selector: [{type: 'TextQuoteSelector', exact: 'neitherami'}]},
]
}
htmlAnchoring.anchor.returns(Promise.reject())
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "marks an annotation where the target has no TextQuoteSelectors as an orphan", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextPositionSelector', start: 0, end: 5}]},
]
}
# This shouldn't be called, but if it is, we successfully anchor so that
# this test is guaranteed to fail.
htmlAnchoring.anchor.returns(Promise.resolve(range))
guest.anchor(annotation).then ->
assert.isTrue(annotation.$orphan)
it "does not attempt to anchor targets which have no TextQuoteSelector", ->
guest = createGuest()
annotation = {
target: [
{selector: [{type: 'TextPositionSelector', start: 0, end: 5}]},
]
}
guest.anchor(annotation).then ->
assert.notCalled(htmlAnchoring.anchor)
it 'updates the cross frame and bucket bar plugins', () ->
guest = createGuest()
guest.plugins.CrossFrame =
sync: sinon.stub()
guest.plugins.BucketBar =
update: sinon.stub()
annotation = {}
return guest.anchor(annotation).then ->
assert.called(guest.plugins.BucketBar.update)
assert.called(guest.plugins.CrossFrame.sync)
it 'returns a promise of the anchors for the annotation', () ->
guest = createGuest()
highlights = [document.createElement('span')]
htmlAnchoring.anchor.returns(Promise.resolve(range))
highlighter.highlightRange.returns(highlights)
target = {selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}
return guest.anchor({target: [target]}).then (anchors) ->
assert.equal(anchors.length, 1)
it 'adds the anchor to the "anchors" instance property"', () ->
guest = createGuest()
highlights = [document.createElement('span')]
htmlAnchoring.anchor.returns(Promise.resolve(range))
highlighter.highlightRange.returns(highlights)
target = {selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}
annotation = {target: [target]}
return guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 1)
assert.strictEqual(guest.anchors[0].annotation, annotation)
assert.strictEqual(guest.anchors[0].target, target)
assert.strictEqual(guest.anchors[0].range, range)
assert.strictEqual(guest.anchors[0].highlights, highlights)
it 'destroys targets that have been removed from the annotation', () ->
annotation = {}
target = {}
highlights = []
guest = createGuest()
guest.anchors = [{annotation, target, highlights}]
removeHighlights = highlighter.removeHighlights
return guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 0)
assert.calledOnce(removeHighlights)
assert.calledWith(removeHighlights, highlights)
it 'does not reanchor targets that are already anchored', () ->
guest = createGuest()
annotation = target: [{selector: [{type: 'TextQuoteSelector', exact: 'hello'}]}]
htmlAnchoring.anchor.returns(Promise.resolve(range))
return guest.anchor(annotation).then ->
guest.anchor(annotation).then ->
assert.equal(guest.anchors.length, 1)
assert.calledOnce(htmlAnchoring.anchor)
describe '#detach()', ->
it 'removes the anchors from the "anchors" instance variable', ->
guest = createGuest()
annotation = {}
guest.anchors.push({annotation})
guest.detach(annotation)
assert.equal(guest.anchors.length, 0)
it 'updates the bucket bar plugin', ->
guest = createGuest()
guest.plugins.BucketBar = update: sinon.stub()
annotation = {}
guest.anchors.push({annotation})
guest.detach(annotation)
assert.calledOnce(guest.plugins.BucketBar.update)
it 'publishes the "annotationDeleted" event', ->
guest = createGuest()
annotation = {}
publish = sandbox.stub(guest, 'publish')
guest.deleteAnnotation(annotation)
assert.calledOnce(publish)
assert.calledWith(publish, 'annotationDeleted', [annotation])
it 'removes any highlights associated with the annotation', ->
guest = createGuest()
annotation = {}
highlights = [document.createElement('span')]
removeHighlights = highlighter.removeHighlights
guest.anchors.push({annotation, highlights})
guest.deleteAnnotation(annotation)
assert.calledOnce(removeHighlights)
assert.calledWith(removeHighlights, highlights)
|
[
{
"context": "16) ->\n\t[num, alpb, alps] = [\"0123456789\", \"ABCDEFGHIJKLMNOPQRSTUVWXTZ\", \"abcdefghiklmnopqrstuvwxyz\"]\n",
"end": 137,
"score": 0.5614303946495056,
"start": 135,
"tag": "KEY",
"value": "GH"
},
{
"context": "um, alpb, alps] = [\"0123456789\", \"ABCDEFGHIJKLMNOPQRSTUVWXTZ\", \"abcdefghiklmnopqrstuvwxyz\"]\n\t[chars, ",
"end": 146,
"score": 0.5462439060211182,
"start": 145,
"tag": "KEY",
"value": "Q"
},
{
"context": "alpb, alps] = [\"0123456789\", \"ABCDEFGHIJKLMNOPQRSTUVWXTZ\", \"abcdefghiklmnopqrstuvwxyz\"]\n\t[chars, key] ",
"end": 155,
"score": 0.5708308219909668,
"start": 149,
"tag": "KEY",
"value": "UVWXTZ"
},
{
"context": "23456789\", \"ABCDEFGHIJKLMNOPQRSTUVWXTZ\", \"abcdefghiklmnopqrstuvwxyz\"]\n\t[chars, key] = [(alpb + num + alps).split",
"end": 184,
"score": 0.8295844793319702,
"start": 167,
"tag": "KEY",
"value": "iklmnopqrstuvwxyz"
}
] | 02convert/node_modules/generate-key/lib/generate.coffee | seiche/Autoh264 | 4 | rn = (max) ->
return Math.floor (Math.random() * max)
exports.generateKey = (len = 16) ->
[num, alpb, alps] = ["0123456789", "ABCDEFGHIJKLMNOPQRSTUVWXTZ", "abcdefghiklmnopqrstuvwxyz"]
[chars, key] = [(alpb + num + alps).split(''),""]
key += chars[rn(chars.length)] for i in [1..len]
return key | 178070 | rn = (max) ->
return Math.floor (Math.random() * max)
exports.generateKey = (len = 16) ->
[num, alpb, alps] = ["0123456789", "ABCDEF<KEY>IJKLMNOP<KEY>RST<KEY>", "abcdefgh<KEY>"]
[chars, key] = [(alpb + num + alps).split(''),""]
key += chars[rn(chars.length)] for i in [1..len]
return key | true | rn = (max) ->
return Math.floor (Math.random() * max)
exports.generateKey = (len = 16) ->
[num, alpb, alps] = ["0123456789", "ABCDEFPI:KEY:<KEY>END_PIIJKLMNOPPI:KEY:<KEY>END_PIRSTPI:KEY:<KEY>END_PI", "abcdefghPI:KEY:<KEY>END_PI"]
[chars, key] = [(alpb + num + alps).split(''),""]
key += chars[rn(chars.length)] for i in [1..len]
return key |
[
{
"context": "de: 'usrdel'\n onlyimgdel: fileOnly\n pwd: QR.persona.getPassword()\n form[post.ID] = 'delete'\n\n link = @\n ",
"end": 1311,
"score": 0.9988619089126587,
"start": 1289,
"tag": "PASSWORD",
"value": "QR.persona.getPassword"
}
] | src/Menu/DeleteLink.coffee | ihavenoface/4chan-x | 4 | DeleteLink =
init: ->
return if !Conf['Menu'] or !Conf['Delete Link']
div = $.el 'div',
className: 'delete-link'
textContent: 'Delete'
postEl = $.el 'a',
className: 'delete-post'
href: 'javascript:;'
fileEl = $.el 'a',
className: 'delete-file'
href: 'javascript:;'
postEntry =
el: postEl
open: ->
postEl.textContent = 'Post'
$.on postEl, 'click', DeleteLink.delete
true
fileEntry =
el: fileEl
open: ({file}) ->
return false if !file or file.isDead
fileEl.textContent = 'File'
$.on fileEl, 'click', DeleteLink.delete
true
Menu.menu.addEntry
el: div
order: 40
open: (post) ->
return false if post.isDead
DeleteLink.post = post
node = div.firstChild
node.textContent = 'Delete'
DeleteLink.cooldown.start post, node
true
subEntries: [postEntry, fileEntry]
delete: ->
{post} = DeleteLink
return if DeleteLink.cooldown.counting is post
$.off @, 'click', DeleteLink.delete
fileOnly = $.hasClass @, 'delete-file'
@textContent = "Deleting #{if fileOnly then 'file' else 'post'}..."
form =
mode: 'usrdel'
onlyimgdel: fileOnly
pwd: QR.persona.getPassword()
form[post.ID] = 'delete'
link = @
$.ajax $.id('delform').action.replace("/#{g.BOARD}/", "/#{post.board}/"),
responseType: 'document'
withCredentials: true
onload: -> DeleteLink.load link, post, fileOnly, @response
onerror: -> DeleteLink.error link
,
form: $.formData form
load: (link, post, fileOnly, resDoc) ->
if resDoc.title is '4chan - Banned' # Ban/warn check
s = 'Banned!'
else if msg = resDoc.getElementById 'errmsg' # error!
s = msg.textContent
$.on link, 'click', DeleteLink.delete
else
if resDoc.title is 'Updating index...'
# We're 100% sure.
(post.origin or post).kill fileOnly
s = 'Deleted'
link.textContent = s
error: (link) ->
link.textContent = 'Connection error, please retry.'
$.on link, 'click', DeleteLink.delete
cooldown:
start: (post, node) ->
unless QR.db?.get {boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID}
# Only start counting on our posts.
delete DeleteLink.cooldown.counting
return
DeleteLink.cooldown.counting = post
length = 60
seconds = Math.ceil (length * $.SECOND - (Date.now() - post.info.date)) / $.SECOND
DeleteLink.cooldown.count post, seconds, length, node
count: (post, seconds, length, node) ->
return if DeleteLink.cooldown.counting isnt post
unless 0 <= seconds <= length
if DeleteLink.cooldown.counting is post
node.textContent = 'Delete'
delete DeleteLink.cooldown.counting
return
setTimeout DeleteLink.cooldown.count, 1000, post, seconds - 1, length, node
node.textContent = "Delete (#{seconds})"
| 127962 | DeleteLink =
init: ->
return if !Conf['Menu'] or !Conf['Delete Link']
div = $.el 'div',
className: 'delete-link'
textContent: 'Delete'
postEl = $.el 'a',
className: 'delete-post'
href: 'javascript:;'
fileEl = $.el 'a',
className: 'delete-file'
href: 'javascript:;'
postEntry =
el: postEl
open: ->
postEl.textContent = 'Post'
$.on postEl, 'click', DeleteLink.delete
true
fileEntry =
el: fileEl
open: ({file}) ->
return false if !file or file.isDead
fileEl.textContent = 'File'
$.on fileEl, 'click', DeleteLink.delete
true
Menu.menu.addEntry
el: div
order: 40
open: (post) ->
return false if post.isDead
DeleteLink.post = post
node = div.firstChild
node.textContent = 'Delete'
DeleteLink.cooldown.start post, node
true
subEntries: [postEntry, fileEntry]
delete: ->
{post} = DeleteLink
return if DeleteLink.cooldown.counting is post
$.off @, 'click', DeleteLink.delete
fileOnly = $.hasClass @, 'delete-file'
@textContent = "Deleting #{if fileOnly then 'file' else 'post'}..."
form =
mode: 'usrdel'
onlyimgdel: fileOnly
pwd: <PASSWORD>()
form[post.ID] = 'delete'
link = @
$.ajax $.id('delform').action.replace("/#{g.BOARD}/", "/#{post.board}/"),
responseType: 'document'
withCredentials: true
onload: -> DeleteLink.load link, post, fileOnly, @response
onerror: -> DeleteLink.error link
,
form: $.formData form
load: (link, post, fileOnly, resDoc) ->
if resDoc.title is '4chan - Banned' # Ban/warn check
s = 'Banned!'
else if msg = resDoc.getElementById 'errmsg' # error!
s = msg.textContent
$.on link, 'click', DeleteLink.delete
else
if resDoc.title is 'Updating index...'
# We're 100% sure.
(post.origin or post).kill fileOnly
s = 'Deleted'
link.textContent = s
error: (link) ->
link.textContent = 'Connection error, please retry.'
$.on link, 'click', DeleteLink.delete
cooldown:
start: (post, node) ->
unless QR.db?.get {boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID}
# Only start counting on our posts.
delete DeleteLink.cooldown.counting
return
DeleteLink.cooldown.counting = post
length = 60
seconds = Math.ceil (length * $.SECOND - (Date.now() - post.info.date)) / $.SECOND
DeleteLink.cooldown.count post, seconds, length, node
count: (post, seconds, length, node) ->
return if DeleteLink.cooldown.counting isnt post
unless 0 <= seconds <= length
if DeleteLink.cooldown.counting is post
node.textContent = 'Delete'
delete DeleteLink.cooldown.counting
return
setTimeout DeleteLink.cooldown.count, 1000, post, seconds - 1, length, node
node.textContent = "Delete (#{seconds})"
| true | DeleteLink =
init: ->
return if !Conf['Menu'] or !Conf['Delete Link']
div = $.el 'div',
className: 'delete-link'
textContent: 'Delete'
postEl = $.el 'a',
className: 'delete-post'
href: 'javascript:;'
fileEl = $.el 'a',
className: 'delete-file'
href: 'javascript:;'
postEntry =
el: postEl
open: ->
postEl.textContent = 'Post'
$.on postEl, 'click', DeleteLink.delete
true
fileEntry =
el: fileEl
open: ({file}) ->
return false if !file or file.isDead
fileEl.textContent = 'File'
$.on fileEl, 'click', DeleteLink.delete
true
Menu.menu.addEntry
el: div
order: 40
open: (post) ->
return false if post.isDead
DeleteLink.post = post
node = div.firstChild
node.textContent = 'Delete'
DeleteLink.cooldown.start post, node
true
subEntries: [postEntry, fileEntry]
delete: ->
{post} = DeleteLink
return if DeleteLink.cooldown.counting is post
$.off @, 'click', DeleteLink.delete
fileOnly = $.hasClass @, 'delete-file'
@textContent = "Deleting #{if fileOnly then 'file' else 'post'}..."
form =
mode: 'usrdel'
onlyimgdel: fileOnly
pwd: PI:PASSWORD:<PASSWORD>END_PI()
form[post.ID] = 'delete'
link = @
$.ajax $.id('delform').action.replace("/#{g.BOARD}/", "/#{post.board}/"),
responseType: 'document'
withCredentials: true
onload: -> DeleteLink.load link, post, fileOnly, @response
onerror: -> DeleteLink.error link
,
form: $.formData form
load: (link, post, fileOnly, resDoc) ->
if resDoc.title is '4chan - Banned' # Ban/warn check
s = 'Banned!'
else if msg = resDoc.getElementById 'errmsg' # error!
s = msg.textContent
$.on link, 'click', DeleteLink.delete
else
if resDoc.title is 'Updating index...'
# We're 100% sure.
(post.origin or post).kill fileOnly
s = 'Deleted'
link.textContent = s
error: (link) ->
link.textContent = 'Connection error, please retry.'
$.on link, 'click', DeleteLink.delete
cooldown:
start: (post, node) ->
unless QR.db?.get {boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID}
# Only start counting on our posts.
delete DeleteLink.cooldown.counting
return
DeleteLink.cooldown.counting = post
length = 60
seconds = Math.ceil (length * $.SECOND - (Date.now() - post.info.date)) / $.SECOND
DeleteLink.cooldown.count post, seconds, length, node
count: (post, seconds, length, node) ->
return if DeleteLink.cooldown.counting isnt post
unless 0 <= seconds <= length
if DeleteLink.cooldown.counting is post
node.textContent = 'Delete'
delete DeleteLink.cooldown.counting
return
setTimeout DeleteLink.cooldown.count, 1000, post, seconds - 1, length, node
node.textContent = "Delete (#{seconds})"
|
[
{
"context": "ceiswithyou.com\"\n EventCollectorToken : \"DarthVaderRules\"\n @message =\n somekey : \"has a va",
"end": 1733,
"score": 0.9943345785140991,
"start": 1718,
"tag": "PASSWORD",
"value": "DarthVaderRules"
}
] | test/index-spec.coffee | octoblu/meshblu-splunk-event-collector | 0 | {Plugin} = require '../index'
{EventEmitter} = require 'events'
nock = require 'nock'
request = require 'request'
describe 'EventCollectorPlugin', ->
it 'should exist', ->
expect(Plugin).to.exist
describe '->onMessage', ->
describe 'when given an invalid SplunkEventUrl in the options', ->
beforeEach ->
@sut = new Plugin
@messageSpy = sinon.spy()
@message =
skynet : "Is Genisys"
@errorMessage =
topic : "error"
error : "SplunkEventUrl is undefined or invalid"
@sut.on('message', @messageSpy)
@sut.setOptions({})
@sut.onMessage(@message)
it 'should send an error message saying the SplunkEventUrl is invalid', ->
expect(@messageSpy).to.have.been.calledWith(@errorMessage)
describe 'when the event collector token is not set', ->
beforeEach ->
@sut = new Plugin
@messageSpy = sinon.spy()
@message =
skynet : "It's whatever"
@errorMessage =
topic : "error"
error : "EventCollectorToken is undefined or invalid"
@sut.on('message', @messageSpy)
@sut.setOptions({})
@sut.onMessage(@message)
it 'should send an error message saying the EventCollectorToken is invalid', ->
expect(@messageSpy).to.have.been.calledWith(@errorMessage)
xdescribe 'when there is a valid URL and Token in the config options', ->
beforeEach ->
@dependencies =
request : request
@dependencies.request.post = sinon.spy()
@sut = new Plugin @dependencies
@options =
SplunkEventUrl : "https://theforceiswithyou.com"
EventCollectorToken : "DarthVaderRules"
@message =
somekey : "has a value"
@sut.setOptions(@options)
@sut.onMessage(@message)
it 'Should post the message to the SplunkEventUrl endpoint', ->
expect(@dependencies.request.post).to.have.been.calledWith(@options.SplunkEventUrl,
{
headers :
Authorization : "Splunk #{@options.EventCollectorToken}"
json : true
body :
event : @message
})
| 118878 | {Plugin} = require '../index'
{EventEmitter} = require 'events'
nock = require 'nock'
request = require 'request'
describe 'EventCollectorPlugin', ->
it 'should exist', ->
expect(Plugin).to.exist
describe '->onMessage', ->
describe 'when given an invalid SplunkEventUrl in the options', ->
beforeEach ->
@sut = new Plugin
@messageSpy = sinon.spy()
@message =
skynet : "Is Genisys"
@errorMessage =
topic : "error"
error : "SplunkEventUrl is undefined or invalid"
@sut.on('message', @messageSpy)
@sut.setOptions({})
@sut.onMessage(@message)
it 'should send an error message saying the SplunkEventUrl is invalid', ->
expect(@messageSpy).to.have.been.calledWith(@errorMessage)
describe 'when the event collector token is not set', ->
beforeEach ->
@sut = new Plugin
@messageSpy = sinon.spy()
@message =
skynet : "It's whatever"
@errorMessage =
topic : "error"
error : "EventCollectorToken is undefined or invalid"
@sut.on('message', @messageSpy)
@sut.setOptions({})
@sut.onMessage(@message)
it 'should send an error message saying the EventCollectorToken is invalid', ->
expect(@messageSpy).to.have.been.calledWith(@errorMessage)
xdescribe 'when there is a valid URL and Token in the config options', ->
beforeEach ->
@dependencies =
request : request
@dependencies.request.post = sinon.spy()
@sut = new Plugin @dependencies
@options =
SplunkEventUrl : "https://theforceiswithyou.com"
EventCollectorToken : "<PASSWORD>"
@message =
somekey : "has a value"
@sut.setOptions(@options)
@sut.onMessage(@message)
it 'Should post the message to the SplunkEventUrl endpoint', ->
expect(@dependencies.request.post).to.have.been.calledWith(@options.SplunkEventUrl,
{
headers :
Authorization : "Splunk #{@options.EventCollectorToken}"
json : true
body :
event : @message
})
| true | {Plugin} = require '../index'
{EventEmitter} = require 'events'
nock = require 'nock'
request = require 'request'
describe 'EventCollectorPlugin', ->
it 'should exist', ->
expect(Plugin).to.exist
describe '->onMessage', ->
describe 'when given an invalid SplunkEventUrl in the options', ->
beforeEach ->
@sut = new Plugin
@messageSpy = sinon.spy()
@message =
skynet : "Is Genisys"
@errorMessage =
topic : "error"
error : "SplunkEventUrl is undefined or invalid"
@sut.on('message', @messageSpy)
@sut.setOptions({})
@sut.onMessage(@message)
it 'should send an error message saying the SplunkEventUrl is invalid', ->
expect(@messageSpy).to.have.been.calledWith(@errorMessage)
describe 'when the event collector token is not set', ->
beforeEach ->
@sut = new Plugin
@messageSpy = sinon.spy()
@message =
skynet : "It's whatever"
@errorMessage =
topic : "error"
error : "EventCollectorToken is undefined or invalid"
@sut.on('message', @messageSpy)
@sut.setOptions({})
@sut.onMessage(@message)
it 'should send an error message saying the EventCollectorToken is invalid', ->
expect(@messageSpy).to.have.been.calledWith(@errorMessage)
xdescribe 'when there is a valid URL and Token in the config options', ->
beforeEach ->
@dependencies =
request : request
@dependencies.request.post = sinon.spy()
@sut = new Plugin @dependencies
@options =
SplunkEventUrl : "https://theforceiswithyou.com"
EventCollectorToken : "PI:PASSWORD:<PASSWORD>END_PI"
@message =
somekey : "has a value"
@sut.setOptions(@options)
@sut.onMessage(@message)
it 'Should post the message to the SplunkEventUrl endpoint', ->
expect(@dependencies.request.post).to.have.been.calledWith(@options.SplunkEventUrl,
{
headers :
Authorization : "Splunk #{@options.EventCollectorToken}"
json : true
body :
event : @message
})
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991704821586609,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-fs-append-file-sync.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")
join = require("path").join
fs = require("fs")
currentFileData = "ABCD"
num = 220
data = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、" + "广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。" + "南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。" + "前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年," + "南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年," + "历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度," + "它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"
# test that empty file will be created and have content added
filename = join(common.tmpDir, "append-sync.txt")
common.error "appending to " + filename
fs.appendFileSync filename, data
fileData = fs.readFileSync(filename)
console.error "filedata is a " + typeof fileData
assert.equal Buffer.byteLength(data), fileData.length
# test that appends data to a non empty file
filename2 = join(common.tmpDir, "append-sync2.txt")
fs.writeFileSync filename2, currentFileData
common.error "appending to " + filename2
fs.appendFileSync filename2, data
fileData2 = fs.readFileSync(filename2)
assert.equal Buffer.byteLength(data) + currentFileData.length, fileData2.length
# test that appendFileSync accepts buffers
filename3 = join(common.tmpDir, "append-sync3.txt")
fs.writeFileSync filename3, currentFileData
common.error "appending to " + filename3
buf = new Buffer(data, "utf8")
fs.appendFileSync filename3, buf
fileData3 = fs.readFileSync(filename3)
assert.equal buf.length + currentFileData.length, fileData3.length
# test that appendFile accepts numbers.
filename4 = join(common.tmpDir, "append-sync4.txt")
fs.writeFileSync filename4, currentFileData,
mode: m
common.error "appending to " + filename4
m = 0600
fs.appendFileSync filename4, num,
mode: m
# windows permissions aren't unix
if process.platform isnt "win32"
st = fs.statSync(filename4)
assert.equal st.mode & 0700, m
fileData4 = fs.readFileSync(filename4)
assert.equal Buffer.byteLength("" + num) + currentFileData.length, fileData4.length
#exit logic for cleanup
process.on "exit", ->
common.error "done"
fs.unlinkSync filename
fs.unlinkSync filename2
fs.unlinkSync filename3
fs.unlinkSync filename4
return
| 41072 | # 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")
join = require("path").join
fs = require("fs")
currentFileData = "ABCD"
num = 220
data = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、" + "广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。" + "南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。" + "前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年," + "南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年," + "历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度," + "它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"
# test that empty file will be created and have content added
filename = join(common.tmpDir, "append-sync.txt")
common.error "appending to " + filename
fs.appendFileSync filename, data
fileData = fs.readFileSync(filename)
console.error "filedata is a " + typeof fileData
assert.equal Buffer.byteLength(data), fileData.length
# test that appends data to a non empty file
filename2 = join(common.tmpDir, "append-sync2.txt")
fs.writeFileSync filename2, currentFileData
common.error "appending to " + filename2
fs.appendFileSync filename2, data
fileData2 = fs.readFileSync(filename2)
assert.equal Buffer.byteLength(data) + currentFileData.length, fileData2.length
# test that appendFileSync accepts buffers
filename3 = join(common.tmpDir, "append-sync3.txt")
fs.writeFileSync filename3, currentFileData
common.error "appending to " + filename3
buf = new Buffer(data, "utf8")
fs.appendFileSync filename3, buf
fileData3 = fs.readFileSync(filename3)
assert.equal buf.length + currentFileData.length, fileData3.length
# test that appendFile accepts numbers.
filename4 = join(common.tmpDir, "append-sync4.txt")
fs.writeFileSync filename4, currentFileData,
mode: m
common.error "appending to " + filename4
m = 0600
fs.appendFileSync filename4, num,
mode: m
# windows permissions aren't unix
if process.platform isnt "win32"
st = fs.statSync(filename4)
assert.equal st.mode & 0700, m
fileData4 = fs.readFileSync(filename4)
assert.equal Buffer.byteLength("" + num) + currentFileData.length, fileData4.length
#exit logic for cleanup
process.on "exit", ->
common.error "done"
fs.unlinkSync filename
fs.unlinkSync filename2
fs.unlinkSync filename3
fs.unlinkSync filename4
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")
join = require("path").join
fs = require("fs")
currentFileData = "ABCD"
num = 220
data = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、" + "广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。" + "南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。" + "前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年," + "南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年," + "历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度," + "它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"
# test that empty file will be created and have content added
filename = join(common.tmpDir, "append-sync.txt")
common.error "appending to " + filename
fs.appendFileSync filename, data
fileData = fs.readFileSync(filename)
console.error "filedata is a " + typeof fileData
assert.equal Buffer.byteLength(data), fileData.length
# test that appends data to a non empty file
filename2 = join(common.tmpDir, "append-sync2.txt")
fs.writeFileSync filename2, currentFileData
common.error "appending to " + filename2
fs.appendFileSync filename2, data
fileData2 = fs.readFileSync(filename2)
assert.equal Buffer.byteLength(data) + currentFileData.length, fileData2.length
# test that appendFileSync accepts buffers
filename3 = join(common.tmpDir, "append-sync3.txt")
fs.writeFileSync filename3, currentFileData
common.error "appending to " + filename3
buf = new Buffer(data, "utf8")
fs.appendFileSync filename3, buf
fileData3 = fs.readFileSync(filename3)
assert.equal buf.length + currentFileData.length, fileData3.length
# test that appendFile accepts numbers.
filename4 = join(common.tmpDir, "append-sync4.txt")
fs.writeFileSync filename4, currentFileData,
mode: m
common.error "appending to " + filename4
m = 0600
fs.appendFileSync filename4, num,
mode: m
# windows permissions aren't unix
if process.platform isnt "win32"
st = fs.statSync(filename4)
assert.equal st.mode & 0700, m
fileData4 = fs.readFileSync(filename4)
assert.equal Buffer.byteLength("" + num) + currentFileData.length, fileData4.length
#exit logic for cleanup
process.on "exit", ->
common.error "done"
fs.unlinkSync filename
fs.unlinkSync filename2
fs.unlinkSync filename3
fs.unlinkSync filename4
return
|
[
{
"context": "@binaryStar = \"\"\"\n ",
"end": 11,
"score": 0.9157455563545227,
"start": 0,
"tag": "USERNAME",
"value": "@binaryStar"
},
{
"context": "ll 2013 as of Feb-27-2013 at 08:00 AM\n \nADVISOR: Naps,Thomas L UGLS J34006222\n \nSTUDENT ACA",
"end": 862,
"score": 0.9054405093193054,
"start": 858,
"tag": "NAME",
"value": "Naps"
},
{
"context": "3 as of Feb-27-2013 at 08:00 AM\n \nADVISOR: Naps,Thomas L UGLS J34006222\n \nSTUDENT ACADEMIC PR",
"end": 871,
"score": 0.9992485046386719,
"start": 863,
"tag": "NAME",
"value": "Thomas L"
}
] | binarystar.coffee | seiyria/star-report-reader | 0 | @binaryStar = """
New Window | Help | Customize Page
STAR On-Line
Return to Request STAR On-Line
Binary Guy
PREPARED: 02/06/13 - 10:27
Guy,Binary
PROGRAM CODE: 222234006 CATALOG YEAR: 2011
CAMPUS ID : xxxxxxx
BACHELOR OF SCIENCE DEGREE - COLLEGE OF LETTERS AND SCIENCE
COMPUTER SC & SOFTWARE ENGINEERING (COMPUTER INFO SYS) MAJOR
=================================================================
UNIVERSITY OF WISCONSIN OSHKOSH STUDENT ACADEMIC REPORT (STAR)
REPORT NO.
You can register on Titan Web for
Fall 2013 as of Feb-27-2013 at 08:00 AM
ADVISOR: Naps,Thomas L UGLS J34006222
STUDENT ACADEMIC PROGRAM
PROGRAM : UGLS 2011
PLAN : J34006222 Comp Sci(CIS)-BS 2011
TRANSFER INST : Northeast Wisconsin Technical 4585 JC
UW-OSHKOSH PLACEMENT AT TIME OF ADMISSION
ENGLISH : Gen Ed English Comp or English 110
MATH : Deficient-Math 103
ACADEMIC STANDING : GOOD
COMMENTS :
OFFICIAL GRADE EARNED
GPA CREDS POINTS GPA CREDS
TRANSFER INST 0.00
UWO OFFICIAL 46.00 155.00 3.370 46.00
=================================================================
------> AT LEAST ONE REQUIREMENT HAS NOT BEEN SATISFIED <------
=================================================================
COMBINED GPA (IPLIST)
UWO AND TRANSFER COURSE COMBINED GPA
(Amnesty courses excluded)
46.00 CRS EARNED
46.00 ATTEMPTED HOURS 155.00 POINTS 3.369 GPA
IN-PROG 17.00 CREDITS
=======================================================
IN-PROGRESS COURSES
1232 34-251 3.00 .00 IP Architecture & Assembly Lang
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 38-214 3.00 .00 IP American Lit II (HU)
1232 67-171 4.00 .00 IP Calculus I (MA)
1232 73-102 3.00 .00 IP Theory Music Gen Student (HU)
* =======================================================
ADJUSTMENTS TO THE COURSE REGISTRATIONS LISTED ABOVE OR
COURSES NOT COMPLETED SUCCESSFULLY WILL CHANGE THE
STATUS OF THIS REPORT. COURSES CURRENTLY BEING
REPEATED WILL NOT BE LISTED WITH THE IN-PROGRESS COURSE
BUT WILL BE LISTED IN THE REQUIREMENT TO WHICH THEY
APPLY.
=======================================================
BRING YOUR STAR WITH YOU WHEN MEETING WITH YOUR ADVISOR
=================================================================
NO GENERAL EDUCATION COMPOSITION (GCOMP) 2011-99
MINIMUM 2.00 GPA REQUIRED IN ALL APPLICABLE COURSES
TWO COURSES (6 CREDITS) REQUIRED
EARNED 3.330 GPA
+ 1) COMPLETE A WRITING-BASED COMPOSITION COURSE:
1122 88-188 3.00 B+ 9.99 Wrtng-Bsd Inq Sem (WBIS) (EN)
- 2) COMPLETE A SECOND COMPOSITION COURSE:
(MINIMUM OF 45 CREDITS REQUIRED TO ENROLL)
SELECT FROM: 38-203 38-302 38-307 38-309 38-310
38-316 38-317 38-318 38-321 38-389
=================================================================
OK MATHEMATICS REQUIREMENT FOR THE L&S (GMATH2BS)
BACHELOR OF SCIENCE DEGREE
+ 1) YOU MUST COMPLETE REMEDIAL MATH COURSE 103
AND EARN A GRADE OF C OR BETTER.
1121 67-103 3.00 B+ 9.99 Intermediate Algebra
+ 2) LEVEL I COMPLETED
**NOTE: APPROPRIATE LEVEL I COURSE OPTIONS ARE BASED
ON THE STUDENT'S TEST SCORE AND THE REQUIREMENTS
FOR YOUR MAJOR. SEE AN ADVISOR FOR CORRECT SEQUENCE**
1122 67-104 3.00 C 6.00 College Algebra
+ 3) LEVEL II MATH
4.000 GPA
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 67-171 4.00 .00 IP Calculus I (MA)
+ 4) LEVEL I MATH EXEMPTED/COMPLETED WITH LEVEL II
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 67-171 4.00 .00 IP Calculus I (MA)
=================================================================
OK GENERAL EDUCATION PHYSICAL EDUCATION (GPED)
ONE COURSE (TWO CREDITS) REQUIRED (2011-99)
1121 79-105 2.00 A 8.00 Active Lifestyle (PE)
=================================================================
OK GENERAL EDUCATION NON-WESTERN CULTURE (GNWST)
ONE COURSE (THREE CREDITS) REQUIRED
1122 84-101 3.00 B+ 9.99 Intro to Cmpartv Pltcs(SS)(NW
=================================================================
OK COMMUNICATION REQUIREMENT FOR THE L&S (GSPCH2BSA)
BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES
1231 96-111 3.00 A- 11.01 Fund Spch Comm (GE)
=================================================================
OK HUMANITIES REQUIREMENT FOR THE L&S (GHUM2BS)
BACHELOR OF SCIENCE DEGREE
EARNED 7.00 CREDITS 4 SUB-REQS
IN-PROGRESS 6.00 CREDITS
1232 38-214 3.00 .00 IP American Lit II (HU)
1232 73-102 3.00 .00 IP Theory Music Gen Student (HU)
1122 76-110 3.00 B 9.00 H: Intro Philosophy (HU)
1122 41-110 4.00 A- 14.68 Intro French I (HU)
=================================================================
COMPLETION OF THE B.S. LAB SCIENCE AREA REQUIRES FOUR (4) COURSES
AS DESCRIBED BELOW IN AREAS 1-3. SELECT FROM LAB SCIENCES IN
BIOLOGY, CHEMISTRY, GEOGRAPHY, GEOLOGY, PHYSICS/ASTRONOMY (NEW1)
------------ AREA #1 ------------------------------------------
TWO LABORATORY SCIENCE COURSES FROM THE SAME DEPARTMENT, ONE OF
WHICH REQUIRES THE SECOND AS A PREREQUISITE.
------------ AREA #2 ------------------------------------------
ONE NATURAL SCIENCE LABORATORY COURSE FROM A DIFFERENT DEPARTMENT
THAN THE DEPARTMENT SELECTED IN AREA #1
------------ AREA #3 ------------------------------------------
ONE COURSE THAT MATCHES ONE OF THE OPTIONS BELOW:
A) A COURSE FROM THE SAME DEPARTMENT AS THE ONE SELECTED FOR
AREA #2 AND WHICH HAS THAT COURSE AS A PREREQUISITE
B) A LAB SCIENCE COURSE FROM A 3RD DEPARTMENT
C) A COURSE FROM THOSE LISTED UNDER THE B.S. MATH REQUIREMENT
=================================================================
NO TWO PAIRS (ONE PAIR FROM EACH OF TWO DEPARTMENTS) (NEW3)
- 1) GEOLOGY DEPARTMENTAL APPROVED PAIRINGS
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
=================================================================
COMPLETE TWO COURSES FROM THE SAME NATURAL
SCIENCE DEPARTMENT. (THE FIRST COURSE MUST
BE THE PREREQUISITE OF THE SECOND COURSE)
NOTE: PLEASE SEE THE LIST OF APPROVED PAIRS
LOCATED IN THE PREVIOUS REQUIREMENT.
---------------------------------------------
NO OR ONE PAIR PLUS 2 OTHER DEPARTMENTS OPTION (NEW2)
- 1) BIOLOGY DEPARTMENT APPROVED PAIRINGS
SELECT 26-105 PLUS ONE OF THE FOLLOWING:
- OR) SELECT 26-108 PLUS ONE OF THE FOLLOWING:
- OR) CHEMISTRY DEPARTMENTAL APPROVED PAIRINGS
- OR) GEOGRAPHY DEPARTMENTAL APPROVED PAIR
- OR) GEOLOGY DEPARTMENTAL APPROVED PAIRINGS
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
- OR) PHYSICS/ASTRONOMY APPROVED PAIRINGS
- 2) CHEMISTRY
- 3) -----------------------------------------------
COMPLETE A LAB SCIENCE COURSE FROM EACH OF TWO
SCIENCE DEPARTMENTS OTHER THAN THE DEPARTMENT
SELECTED FOR THE REQUIRED LAB PAIR.
......THE COURSES USED TO SATISFY THE PAIR ABOVE
WILL ALSO PRINT IN THE APPROPRIATE AREA
BELOW, BUT WILL NOT SATISFY THE DEPARTMENTAL
REQUIREMENT (A TOTAL OF THREE DEPARTMENTS
REQUIRED -- INCLUDING THE PAIR)
BIOLOGY
- 4) GEOGRAPHY
+ 5) GEOLOGY
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
+ 6) PHYSICS/ASTRONOMY
1121 80-101 4.00 A 16.00 Workshop Physical Science (NS
- 7) ANTHROPOLOGY
+ 8) YOU MAY TAKE A SECOND MATH/STATS/COMPUTER SC.
AREA (AS DESCRIBED IN THE MATH REQUIREMENT
FOR YOUR THIRD DEPARTMENT REQUIREMENT.
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 67-171 4.00 .00 IP Calculus I (MA)
=================================================================
OK SOCIAL SCIENCE REQUIREMENT FOR THE L&S (GSOSC2BSA)
BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES
EARNED 12.00 CREDITS
+R 1) YOU MUST COMPLETE A MINIMUM OF THREE CREDITS
OF HISTORY
3.00 CRS EARNED
1121 57-101 3.00 A- 11.01 Early Civilization (SS)
+ 3) ANTHROPOLOGY (ANY COURSE EXCEPT 21-202)
3.00 CRS EARNED
1231 21-123 3.00 A- 11.01 American Ethnography (ES) (SS
+ 10) POLITICAL SCIENCE/PUBLIC ADMIN (ANY COURSE)
3.00 CRS EARNED
1122 84-101 3.00 B+ 9.99 Intro to Cmpartv Pltcs(SS)(NW
+ 11) PSYCHOLOGY (ANY COURSE EXCEPT PSYCH 203, 303, 305, 310,
341,367,371,380,383,384,391,411,455,481,498 & 499)
3.00 CRS EARNED
1121 86-104 3.00 B 9.00 H: General Psychology (SS)
=================================================================
OK GENERAL EDUCATION ETHNIC STUDIES (GETHNIC)
ONE COURSE (THREE CREDITS) REQUIRED
(IF SELECTED, 74-215 MUST BE COMPLETED FOR 3 CREDITS)
1231 21-123 3.00 A- 11.01 American Ethnography (ES) (SS
=================================================================
OPTIONAL GENERAL EDUCATION COURSES (NOT REQUIRED, BUT MAY
BE APPLIED TOWARD 42 CREDIT MINIMUM IN GENERAL EDUCATION)
(GOPT) (SEE E-BULLETIN OR E-TIMETABLE FOR LIST)
=================================================================
OK GENERAL EDUCATION SUMMARY (GENEDSUM)
A MINIMUM OF 42 CREDITS IN GENERAL EDUCATION IS REQUIRED.
PLEASE REFER TO THE E-BULLETIN OR E-TIMETABLE FOR THE
APPROVED GENERAL EDUCATION LIST.
EARNED 35.00 CREDITS
35.00 ATTEMPTED HOURS 123.01 POINTS 3.514 GPA
IN-PROGRESS 10.00 CREDITS
=================================================================
NO COMPUTER SCIENCE MAJOR (COMPUTER INFO SYSTEMS)
59 CREDITS AND A 2.00 MIN G.P.A. REQUIRED (J34006/09-9999)
EARNED 3.00 CREDITS 4.000 GPA
IN-PROGRESS 11.00 CREDITS
--> NEEDS: 45.00 CREDITS 4 SUB-REQS 2.000 GPA
- 1) COMPLETE THE FOLLOWING CORE COURSES:
3.00 CRS EARNED 4.000 GPA
IN-PROG 7.00 CREDITS
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 34-251 3.00 .00 IP Architecture & Assembly Lang
1232 34-262 4.00 .00 IP OO Design & Programming II
NEEDS: 5 COURSES
SELECT FROM: 34-271 34-331 34-399 OR 34-490 67-212
82-311
- 2) COMPLETE THE FOLLOWING COURSES IN ADDITION
TO THE COMPUTER SCIENCE CORE COURSES:
.00 CRS EARNED
IN-PROG 4.00 CREDITS
1232 67-171 4.00 .00 IP Calculus I (MA)
NEEDS: 5 COURSES
SELECT FROM: 34-341 34-346 34-350 34-361 67-201 OR
67-301 OR 36-210
- 3) COMPLETE A MINIMUM OF NINE CREDITS FROM THE
FOLLOWING LIST A ELECTIVE COURSES:
NEEDS: 9.00 CREDITS
SELECT FROM: 34-300 34-310 34-321 34-342 34-371
34-381 34-391 34-421 34-431 34-480
- 4) SELECT A MINIMUM OF 6 CREDITS FROM THE
FOLLOWING LIST B ELECTIVE COURSES:
NEEDS: 6.00 CREDITS
SELECT FROM: 28-260 28-314 28-315 28-319 28-355
28-410
+ 5) A MINIMUM GRADE POINT AVERAGE OF 2.00 IN ALL COURSES
NUMBERED 300 OR ABOVE (EXCEPT 34-399, 34-446, 34-456,
34-474, AND 34-490) IS REQUIRED.
NEEDS: 2.000 GPA
-> NOT FROM: 34-334 34-335 34-399 34-446 34-456
34-474 34-490
SELECT FROM: 34-300 TO 34-499
=================================================================
ELECTIVE CREDITS WHICH APPLY TO THE UNDERGRADUATE DEGREE
(ELECTIVE)
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
1122 67-104 3.00 C 6.00 College Algebra
1231 67-106 2.00 C 4.00 Trigonometry
1121 80-101 4.00 A 16.00 Workshop Physical Science (NS
=================================================================
CHECK LIMITS FOR MUSIC, DRAMA, PHY-ED PARTICIPATION
AND PROFESSIONAL COURSES (PRESUM2)
1) ONLY 4 CREDITS OF MUSIC PARTICIPATION COURSES
MAY BE APPLIED TO DEGREE CREDIT FOR NON-MUSIC MAJORS
OR MINORS.
2) ONLY 4 CREDITS OF DRAMA OR THEATRE PARTICIPATION
COURSES MAY APPLY TO DEGREE CREDITS
3) ONLY 4 CREDITS OF PHYSICAL EDUCATION ACTIVITY
COURSES MAY APPLY TO THE DEGREE CREDITS IN THIS AREA.
(ANY CREDITS OVER 4 WILL BE COUNTED AS PREPROFESSIONAL)
1121 79-105 2.00 A 8.00 Active Lifestyle (PE)
4) A MAXIMUM OF 24 PREPROFESSIONAL CREDITS MAY COUNT
TOWARD THE 120 REQUIRED TO GRADUATE.
=================================================================
NO GENERAL BACCALAUREATE DEGREE REQUIREMENTS (SUMMARY)
- 1) EARN A MINIMUM OF 120 DEGREE CREDITS
43.00 CRS EARNED
IN-PROG 17.00 CREDITS
NEEDS: 60.00 CREDITS
+ 3) EARN A MINIMUM 2.00 GPA IN UWO CREDITS ATTEMPTED
46.00 ATTEMPTED HOURS 155.00 POINTS 3.369 GPA
+ 4) EARN A MINIMUM 2.00 GPA IN ALL COURSES APPLICABLE TO
THE UNIVERSITY'S GENERAL EDUCATION ENGLISH COMPOSITION
REQUIREMENT
3.330 GPA
+ 5) EARN AT LEAST 30 SEMESTER CREDITS AT UW OSHKOSH
( 46.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
+ 6) EARN AT LEAST 48 CREDITS FROM A 4 YEAR INSTITUTION
( 46.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
- 7) EARN AT LEAST 35 CREDITS AT THE UPPER LEVEL (300/400)
WITH A MINIMUM 2.00 GPA
NEEDS: 35.00 CREDITS
+ 8) 15 OF THE LAST 30 CREDITS MUST BE TAKEN AT UWO.
( 15.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
=================================================================
CREDITS NOT APPLICABLE TO THE UNDERGRADUATE DEGREE
(REMEDIAL & GRADUATE COURSES)
- REMEDIAL COURSES NOT APPLIED TO UNDERGRAD DEGREE
1121 67-103 3.00 B+ 9.99 Intermediate Algebra
=================================================================
**** LEGEND ****
NO = REQUIREMENT NOT COMPLETE >D = DUPLICATE COURSE - CREDIT
OK = REQUIREMENT COMPLETE & GPA EFFECT REMOVED ON
- = SUBREQUIREMENT NOT COMPLETE COURSE EXCEEDING LIMIT
+ = SUBREQUIREMENT COMPLETE >X = REPEATED COURSE - CREDIT
* = SUBREQUIREMENT IS OPTIONAL & GPA EFFECT REMOVED ON
(R)= REQUIRED COURSE ORIGINAL COURSE
+R = REQUIRED SUBREQUIREMENT >S = COURSE CREDIT SPLIT
COMPLETED BETWEEN REQUIREMENTS
-R = REQUIRED SUBREQUIREMENT >R = REPEATABLE COURSE - CREDIT
NOT COMPLETED MAY BE EARNED MORE THAN
CS = COURSE SUBSTITUTION ONCE
WC = WAIVED COURSE WH = WAIVED CREDIT HOUR
<> = CONTINUED REQUIREMENT >C = DUPLICAT CROSS-LINKED COUR
S = SATISFACTORY GRADE IN RETRO., MILITARY, DEPT., TEST OUT CR.
******
PLEASE NOTE: THE FOUR NUMBERS BEFORE A COURSE INDICATE THE TERM
IN WHICH THE COURSE WAS TAKEN. THE FIRST THREE NUMBERS INDICATE
THE ACADEMIC YEAR (078 IS USED FOR THE 2007-08 ACADEMIC YEAR).
THE LAST NUMBER INDICATES THE TERM (1 = FALL, 2 = SPRING,
4 = SUMMER). FOR EXAMPLE, 0782 IS THE SPRING TERM OF 2007-08.
****************************************************************
******
THIS NOTICE OF ACADEMIC PROGRESS HAS BEEN PREPARED TO ASSIST YOU
DURING YOUR COLLEGE EXPERIENCE. ALTHOUGH EFFORTS HAVE BEEN MADE
TO ASSESS THE ACCURACY OF THIS REPORT, YOU ARE RESPONSIBLE FOR
MAKING SURE THAT ALL REQUIREMENTS HAVE BEEN COMPLETED. THE
REGISTRAR'S OFFICE WILL ULTIMATELY AUTHORIZE THE AWARDING OF
YOUR DEGREE; THEREFORE, IF YOU HAVE ANY QUESTIONS ABOUT THE
ACCURACY OF THIS PROGRESS REPORT, PLEASE SEE AN ACADEMIC ADVISOR
IN DEMPSEY 130.
*******
****************************************************************
=================================================================
THIS AUDIT ASSUMES SUCCESSFUL COMPLETION OF ALL IN-PROGRESS
COURSES; ANY IN-PROGRESS COURSES NOT COMPLETED SUCCESSFULLY
MAY CHANGE THIS AUDIT'S EVALUATION.
-----------------------------------------------------------------
**** CONFIDENTIAL - STUDENT/ADVISOR USE ONLY ****
**** FEDERAL LAW PROHIBITS TRANSMITTAL TO A THIRD PARTY ****
-----------------------------------------------------------------
DEPARTMENT CONVERSION TABLE
HONORS 00 HEALTH 55
SERVICE COURSES IN EDUC 11 HEALTH EDUCATION 55
EDUCATIONAL FOUNDATIONS 12 CHINESE 56
ELEMENTARY EDUCATION 13 HISTORY 57
SECONDARY EDUCATION 14 INTERNATIONAL STUDIES 59
READING EDUCATION 15 JOURNALISM 61
SPECIAL EDUCATION 16 KINESIOLOGY 77
EDUCATIONAL LEADERSHIP 17 MATHEMATICS 67
HUMAN SERVICES 18 MEDICAL TECHNOLOGY 68
ANTHROPOLOGY 21 MILITARY SCIENCE 70
ART 22 NURSING COLLABORATIVE 71
AFRICAN AMERICAN STUDIES 23 MUSIC 73
BIOLOGY 26 NURSING 74
BUSINESS 28 PHILOSOPHY 76
COUNSELOR EDUCATION 29 PHYSICAL EDUCATION 79
PROFESSIONAL COUNSELING 29 PHYSICAL SCIENCE 80
LIBERAL STUDIES 31 PUBLIC ADMINISTRATION 81
CHEMISTRY 32 PHYSICS/ASTRONOMY 82
COMPUTER SCIENCE 34 POLITICAL SCIENCE 84
CRIMINAL JUSTICE 35 PRACTICAL ARTS 85
ECONOMICS 36 PSYCHOLOGY 86
ENVIRONMENTAL STUDIES 37 RELIGIOUS STUDIES 87
ENGLISH 38 WRITING-BASED INQ SEM 88
FRENCH 41 PROBLEM-BASED INQ SEM 89
GERMAN 43 SOCIAL JUSTICE 91
JAPANESE 44 SOCIOLOGY 92
RUSSIAN 48 SOCIAL WORK 93
SPANISH 49 INTERDISCIPLINARY STDS 94
GEOGRAPHY 50 COMMUNICATION 96
GEOLOGY 51 THEATRE 97
ARAPAHO 53 WOMEN'S STUDIES 98
SHOSHONE 54 URBAN PLANNING 99
-----------------------------------------------------------------
=================================================================
********************* END OF ANALYSIS *********************
Return to Academics
"""; | 122860 | @binaryStar = """
New Window | Help | Customize Page
STAR On-Line
Return to Request STAR On-Line
Binary Guy
PREPARED: 02/06/13 - 10:27
Guy,Binary
PROGRAM CODE: 222234006 CATALOG YEAR: 2011
CAMPUS ID : xxxxxxx
BACHELOR OF SCIENCE DEGREE - COLLEGE OF LETTERS AND SCIENCE
COMPUTER SC & SOFTWARE ENGINEERING (COMPUTER INFO SYS) MAJOR
=================================================================
UNIVERSITY OF WISCONSIN OSHKOSH STUDENT ACADEMIC REPORT (STAR)
REPORT NO.
You can register on Titan Web for
Fall 2013 as of Feb-27-2013 at 08:00 AM
ADVISOR: <NAME>,<NAME> UGLS J34006222
STUDENT ACADEMIC PROGRAM
PROGRAM : UGLS 2011
PLAN : J34006222 Comp Sci(CIS)-BS 2011
TRANSFER INST : Northeast Wisconsin Technical 4585 JC
UW-OSHKOSH PLACEMENT AT TIME OF ADMISSION
ENGLISH : Gen Ed English Comp or English 110
MATH : Deficient-Math 103
ACADEMIC STANDING : GOOD
COMMENTS :
OFFICIAL GRADE EARNED
GPA CREDS POINTS GPA CREDS
TRANSFER INST 0.00
UWO OFFICIAL 46.00 155.00 3.370 46.00
=================================================================
------> AT LEAST ONE REQUIREMENT HAS NOT BEEN SATISFIED <------
=================================================================
COMBINED GPA (IPLIST)
UWO AND TRANSFER COURSE COMBINED GPA
(Amnesty courses excluded)
46.00 CRS EARNED
46.00 ATTEMPTED HOURS 155.00 POINTS 3.369 GPA
IN-PROG 17.00 CREDITS
=======================================================
IN-PROGRESS COURSES
1232 34-251 3.00 .00 IP Architecture & Assembly Lang
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 38-214 3.00 .00 IP American Lit II (HU)
1232 67-171 4.00 .00 IP Calculus I (MA)
1232 73-102 3.00 .00 IP Theory Music Gen Student (HU)
* =======================================================
ADJUSTMENTS TO THE COURSE REGISTRATIONS LISTED ABOVE OR
COURSES NOT COMPLETED SUCCESSFULLY WILL CHANGE THE
STATUS OF THIS REPORT. COURSES CURRENTLY BEING
REPEATED WILL NOT BE LISTED WITH THE IN-PROGRESS COURSE
BUT WILL BE LISTED IN THE REQUIREMENT TO WHICH THEY
APPLY.
=======================================================
BRING YOUR STAR WITH YOU WHEN MEETING WITH YOUR ADVISOR
=================================================================
NO GENERAL EDUCATION COMPOSITION (GCOMP) 2011-99
MINIMUM 2.00 GPA REQUIRED IN ALL APPLICABLE COURSES
TWO COURSES (6 CREDITS) REQUIRED
EARNED 3.330 GPA
+ 1) COMPLETE A WRITING-BASED COMPOSITION COURSE:
1122 88-188 3.00 B+ 9.99 Wrtng-Bsd Inq Sem (WBIS) (EN)
- 2) COMPLETE A SECOND COMPOSITION COURSE:
(MINIMUM OF 45 CREDITS REQUIRED TO ENROLL)
SELECT FROM: 38-203 38-302 38-307 38-309 38-310
38-316 38-317 38-318 38-321 38-389
=================================================================
OK MATHEMATICS REQUIREMENT FOR THE L&S (GMATH2BS)
BACHELOR OF SCIENCE DEGREE
+ 1) YOU MUST COMPLETE REMEDIAL MATH COURSE 103
AND EARN A GRADE OF C OR BETTER.
1121 67-103 3.00 B+ 9.99 Intermediate Algebra
+ 2) LEVEL I COMPLETED
**NOTE: APPROPRIATE LEVEL I COURSE OPTIONS ARE BASED
ON THE STUDENT'S TEST SCORE AND THE REQUIREMENTS
FOR YOUR MAJOR. SEE AN ADVISOR FOR CORRECT SEQUENCE**
1122 67-104 3.00 C 6.00 College Algebra
+ 3) LEVEL II MATH
4.000 GPA
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 67-171 4.00 .00 IP Calculus I (MA)
+ 4) LEVEL I MATH EXEMPTED/COMPLETED WITH LEVEL II
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 67-171 4.00 .00 IP Calculus I (MA)
=================================================================
OK GENERAL EDUCATION PHYSICAL EDUCATION (GPED)
ONE COURSE (TWO CREDITS) REQUIRED (2011-99)
1121 79-105 2.00 A 8.00 Active Lifestyle (PE)
=================================================================
OK GENERAL EDUCATION NON-WESTERN CULTURE (GNWST)
ONE COURSE (THREE CREDITS) REQUIRED
1122 84-101 3.00 B+ 9.99 Intro to Cmpartv Pltcs(SS)(NW
=================================================================
OK COMMUNICATION REQUIREMENT FOR THE L&S (GSPCH2BSA)
BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES
1231 96-111 3.00 A- 11.01 Fund Spch Comm (GE)
=================================================================
OK HUMANITIES REQUIREMENT FOR THE L&S (GHUM2BS)
BACHELOR OF SCIENCE DEGREE
EARNED 7.00 CREDITS 4 SUB-REQS
IN-PROGRESS 6.00 CREDITS
1232 38-214 3.00 .00 IP American Lit II (HU)
1232 73-102 3.00 .00 IP Theory Music Gen Student (HU)
1122 76-110 3.00 B 9.00 H: Intro Philosophy (HU)
1122 41-110 4.00 A- 14.68 Intro French I (HU)
=================================================================
COMPLETION OF THE B.S. LAB SCIENCE AREA REQUIRES FOUR (4) COURSES
AS DESCRIBED BELOW IN AREAS 1-3. SELECT FROM LAB SCIENCES IN
BIOLOGY, CHEMISTRY, GEOGRAPHY, GEOLOGY, PHYSICS/ASTRONOMY (NEW1)
------------ AREA #1 ------------------------------------------
TWO LABORATORY SCIENCE COURSES FROM THE SAME DEPARTMENT, ONE OF
WHICH REQUIRES THE SECOND AS A PREREQUISITE.
------------ AREA #2 ------------------------------------------
ONE NATURAL SCIENCE LABORATORY COURSE FROM A DIFFERENT DEPARTMENT
THAN THE DEPARTMENT SELECTED IN AREA #1
------------ AREA #3 ------------------------------------------
ONE COURSE THAT MATCHES ONE OF THE OPTIONS BELOW:
A) A COURSE FROM THE SAME DEPARTMENT AS THE ONE SELECTED FOR
AREA #2 AND WHICH HAS THAT COURSE AS A PREREQUISITE
B) A LAB SCIENCE COURSE FROM A 3RD DEPARTMENT
C) A COURSE FROM THOSE LISTED UNDER THE B.S. MATH REQUIREMENT
=================================================================
NO TWO PAIRS (ONE PAIR FROM EACH OF TWO DEPARTMENTS) (NEW3)
- 1) GEOLOGY DEPARTMENTAL APPROVED PAIRINGS
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
=================================================================
COMPLETE TWO COURSES FROM THE SAME NATURAL
SCIENCE DEPARTMENT. (THE FIRST COURSE MUST
BE THE PREREQUISITE OF THE SECOND COURSE)
NOTE: PLEASE SEE THE LIST OF APPROVED PAIRS
LOCATED IN THE PREVIOUS REQUIREMENT.
---------------------------------------------
NO OR ONE PAIR PLUS 2 OTHER DEPARTMENTS OPTION (NEW2)
- 1) BIOLOGY DEPARTMENT APPROVED PAIRINGS
SELECT 26-105 PLUS ONE OF THE FOLLOWING:
- OR) SELECT 26-108 PLUS ONE OF THE FOLLOWING:
- OR) CHEMISTRY DEPARTMENTAL APPROVED PAIRINGS
- OR) GEOGRAPHY DEPARTMENTAL APPROVED PAIR
- OR) GEOLOGY DEPARTMENTAL APPROVED PAIRINGS
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
- OR) PHYSICS/ASTRONOMY APPROVED PAIRINGS
- 2) CHEMISTRY
- 3) -----------------------------------------------
COMPLETE A LAB SCIENCE COURSE FROM EACH OF TWO
SCIENCE DEPARTMENTS OTHER THAN THE DEPARTMENT
SELECTED FOR THE REQUIRED LAB PAIR.
......THE COURSES USED TO SATISFY THE PAIR ABOVE
WILL ALSO PRINT IN THE APPROPRIATE AREA
BELOW, BUT WILL NOT SATISFY THE DEPARTMENTAL
REQUIREMENT (A TOTAL OF THREE DEPARTMENTS
REQUIRED -- INCLUDING THE PAIR)
BIOLOGY
- 4) GEOGRAPHY
+ 5) GEOLOGY
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
+ 6) PHYSICS/ASTRONOMY
1121 80-101 4.00 A 16.00 Workshop Physical Science (NS
- 7) ANTHROPOLOGY
+ 8) YOU MAY TAKE A SECOND MATH/STATS/COMPUTER SC.
AREA (AS DESCRIBED IN THE MATH REQUIREMENT
FOR YOUR THIRD DEPARTMENT REQUIREMENT.
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 67-171 4.00 .00 IP Calculus I (MA)
=================================================================
OK SOCIAL SCIENCE REQUIREMENT FOR THE L&S (GSOSC2BSA)
BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES
EARNED 12.00 CREDITS
+R 1) YOU MUST COMPLETE A MINIMUM OF THREE CREDITS
OF HISTORY
3.00 CRS EARNED
1121 57-101 3.00 A- 11.01 Early Civilization (SS)
+ 3) ANTHROPOLOGY (ANY COURSE EXCEPT 21-202)
3.00 CRS EARNED
1231 21-123 3.00 A- 11.01 American Ethnography (ES) (SS
+ 10) POLITICAL SCIENCE/PUBLIC ADMIN (ANY COURSE)
3.00 CRS EARNED
1122 84-101 3.00 B+ 9.99 Intro to Cmpartv Pltcs(SS)(NW
+ 11) PSYCHOLOGY (ANY COURSE EXCEPT PSYCH 203, 303, 305, 310,
341,367,371,380,383,384,391,411,455,481,498 & 499)
3.00 CRS EARNED
1121 86-104 3.00 B 9.00 H: General Psychology (SS)
=================================================================
OK GENERAL EDUCATION ETHNIC STUDIES (GETHNIC)
ONE COURSE (THREE CREDITS) REQUIRED
(IF SELECTED, 74-215 MUST BE COMPLETED FOR 3 CREDITS)
1231 21-123 3.00 A- 11.01 American Ethnography (ES) (SS
=================================================================
OPTIONAL GENERAL EDUCATION COURSES (NOT REQUIRED, BUT MAY
BE APPLIED TOWARD 42 CREDIT MINIMUM IN GENERAL EDUCATION)
(GOPT) (SEE E-BULLETIN OR E-TIMETABLE FOR LIST)
=================================================================
OK GENERAL EDUCATION SUMMARY (GENEDSUM)
A MINIMUM OF 42 CREDITS IN GENERAL EDUCATION IS REQUIRED.
PLEASE REFER TO THE E-BULLETIN OR E-TIMETABLE FOR THE
APPROVED GENERAL EDUCATION LIST.
EARNED 35.00 CREDITS
35.00 ATTEMPTED HOURS 123.01 POINTS 3.514 GPA
IN-PROGRESS 10.00 CREDITS
=================================================================
NO COMPUTER SCIENCE MAJOR (COMPUTER INFO SYSTEMS)
59 CREDITS AND A 2.00 MIN G.P.A. REQUIRED (J34006/09-9999)
EARNED 3.00 CREDITS 4.000 GPA
IN-PROGRESS 11.00 CREDITS
--> NEEDS: 45.00 CREDITS 4 SUB-REQS 2.000 GPA
- 1) COMPLETE THE FOLLOWING CORE COURSES:
3.00 CRS EARNED 4.000 GPA
IN-PROG 7.00 CREDITS
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 34-251 3.00 .00 IP Architecture & Assembly Lang
1232 34-262 4.00 .00 IP OO Design & Programming II
NEEDS: 5 COURSES
SELECT FROM: 34-271 34-331 34-399 OR 34-490 67-212
82-311
- 2) COMPLETE THE FOLLOWING COURSES IN ADDITION
TO THE COMPUTER SCIENCE CORE COURSES:
.00 CRS EARNED
IN-PROG 4.00 CREDITS
1232 67-171 4.00 .00 IP Calculus I (MA)
NEEDS: 5 COURSES
SELECT FROM: 34-341 34-346 34-350 34-361 67-201 OR
67-301 OR 36-210
- 3) COMPLETE A MINIMUM OF NINE CREDITS FROM THE
FOLLOWING LIST A ELECTIVE COURSES:
NEEDS: 9.00 CREDITS
SELECT FROM: 34-300 34-310 34-321 34-342 34-371
34-381 34-391 34-421 34-431 34-480
- 4) SELECT A MINIMUM OF 6 CREDITS FROM THE
FOLLOWING LIST B ELECTIVE COURSES:
NEEDS: 6.00 CREDITS
SELECT FROM: 28-260 28-314 28-315 28-319 28-355
28-410
+ 5) A MINIMUM GRADE POINT AVERAGE OF 2.00 IN ALL COURSES
NUMBERED 300 OR ABOVE (EXCEPT 34-399, 34-446, 34-456,
34-474, AND 34-490) IS REQUIRED.
NEEDS: 2.000 GPA
-> NOT FROM: 34-334 34-335 34-399 34-446 34-456
34-474 34-490
SELECT FROM: 34-300 TO 34-499
=================================================================
ELECTIVE CREDITS WHICH APPLY TO THE UNDERGRADUATE DEGREE
(ELECTIVE)
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
1122 67-104 3.00 C 6.00 College Algebra
1231 67-106 2.00 C 4.00 Trigonometry
1121 80-101 4.00 A 16.00 Workshop Physical Science (NS
=================================================================
CHECK LIMITS FOR MUSIC, DRAMA, PHY-ED PARTICIPATION
AND PROFESSIONAL COURSES (PRESUM2)
1) ONLY 4 CREDITS OF MUSIC PARTICIPATION COURSES
MAY BE APPLIED TO DEGREE CREDIT FOR NON-MUSIC MAJORS
OR MINORS.
2) ONLY 4 CREDITS OF DRAMA OR THEATRE PARTICIPATION
COURSES MAY APPLY TO DEGREE CREDITS
3) ONLY 4 CREDITS OF PHYSICAL EDUCATION ACTIVITY
COURSES MAY APPLY TO THE DEGREE CREDITS IN THIS AREA.
(ANY CREDITS OVER 4 WILL BE COUNTED AS PREPROFESSIONAL)
1121 79-105 2.00 A 8.00 Active Lifestyle (PE)
4) A MAXIMUM OF 24 PREPROFESSIONAL CREDITS MAY COUNT
TOWARD THE 120 REQUIRED TO GRADUATE.
=================================================================
NO GENERAL BACCALAUREATE DEGREE REQUIREMENTS (SUMMARY)
- 1) EARN A MINIMUM OF 120 DEGREE CREDITS
43.00 CRS EARNED
IN-PROG 17.00 CREDITS
NEEDS: 60.00 CREDITS
+ 3) EARN A MINIMUM 2.00 GPA IN UWO CREDITS ATTEMPTED
46.00 ATTEMPTED HOURS 155.00 POINTS 3.369 GPA
+ 4) EARN A MINIMUM 2.00 GPA IN ALL COURSES APPLICABLE TO
THE UNIVERSITY'S GENERAL EDUCATION ENGLISH COMPOSITION
REQUIREMENT
3.330 GPA
+ 5) EARN AT LEAST 30 SEMESTER CREDITS AT UW OSHKOSH
( 46.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
+ 6) EARN AT LEAST 48 CREDITS FROM A 4 YEAR INSTITUTION
( 46.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
- 7) EARN AT LEAST 35 CREDITS AT THE UPPER LEVEL (300/400)
WITH A MINIMUM 2.00 GPA
NEEDS: 35.00 CREDITS
+ 8) 15 OF THE LAST 30 CREDITS MUST BE TAKEN AT UWO.
( 15.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
=================================================================
CREDITS NOT APPLICABLE TO THE UNDERGRADUATE DEGREE
(REMEDIAL & GRADUATE COURSES)
- REMEDIAL COURSES NOT APPLIED TO UNDERGRAD DEGREE
1121 67-103 3.00 B+ 9.99 Intermediate Algebra
=================================================================
**** LEGEND ****
NO = REQUIREMENT NOT COMPLETE >D = DUPLICATE COURSE - CREDIT
OK = REQUIREMENT COMPLETE & GPA EFFECT REMOVED ON
- = SUBREQUIREMENT NOT COMPLETE COURSE EXCEEDING LIMIT
+ = SUBREQUIREMENT COMPLETE >X = REPEATED COURSE - CREDIT
* = SUBREQUIREMENT IS OPTIONAL & GPA EFFECT REMOVED ON
(R)= REQUIRED COURSE ORIGINAL COURSE
+R = REQUIRED SUBREQUIREMENT >S = COURSE CREDIT SPLIT
COMPLETED BETWEEN REQUIREMENTS
-R = REQUIRED SUBREQUIREMENT >R = REPEATABLE COURSE - CREDIT
NOT COMPLETED MAY BE EARNED MORE THAN
CS = COURSE SUBSTITUTION ONCE
WC = WAIVED COURSE WH = WAIVED CREDIT HOUR
<> = CONTINUED REQUIREMENT >C = DUPLICAT CROSS-LINKED COUR
S = SATISFACTORY GRADE IN RETRO., MILITARY, DEPT., TEST OUT CR.
******
PLEASE NOTE: THE FOUR NUMBERS BEFORE A COURSE INDICATE THE TERM
IN WHICH THE COURSE WAS TAKEN. THE FIRST THREE NUMBERS INDICATE
THE ACADEMIC YEAR (078 IS USED FOR THE 2007-08 ACADEMIC YEAR).
THE LAST NUMBER INDICATES THE TERM (1 = FALL, 2 = SPRING,
4 = SUMMER). FOR EXAMPLE, 0782 IS THE SPRING TERM OF 2007-08.
****************************************************************
******
THIS NOTICE OF ACADEMIC PROGRESS HAS BEEN PREPARED TO ASSIST YOU
DURING YOUR COLLEGE EXPERIENCE. ALTHOUGH EFFORTS HAVE BEEN MADE
TO ASSESS THE ACCURACY OF THIS REPORT, YOU ARE RESPONSIBLE FOR
MAKING SURE THAT ALL REQUIREMENTS HAVE BEEN COMPLETED. THE
REGISTRAR'S OFFICE WILL ULTIMATELY AUTHORIZE THE AWARDING OF
YOUR DEGREE; THEREFORE, IF YOU HAVE ANY QUESTIONS ABOUT THE
ACCURACY OF THIS PROGRESS REPORT, PLEASE SEE AN ACADEMIC ADVISOR
IN DEMPSEY 130.
*******
****************************************************************
=================================================================
THIS AUDIT ASSUMES SUCCESSFUL COMPLETION OF ALL IN-PROGRESS
COURSES; ANY IN-PROGRESS COURSES NOT COMPLETED SUCCESSFULLY
MAY CHANGE THIS AUDIT'S EVALUATION.
-----------------------------------------------------------------
**** CONFIDENTIAL - STUDENT/ADVISOR USE ONLY ****
**** FEDERAL LAW PROHIBITS TRANSMITTAL TO A THIRD PARTY ****
-----------------------------------------------------------------
DEPARTMENT CONVERSION TABLE
HONORS 00 HEALTH 55
SERVICE COURSES IN EDUC 11 HEALTH EDUCATION 55
EDUCATIONAL FOUNDATIONS 12 CHINESE 56
ELEMENTARY EDUCATION 13 HISTORY 57
SECONDARY EDUCATION 14 INTERNATIONAL STUDIES 59
READING EDUCATION 15 JOURNALISM 61
SPECIAL EDUCATION 16 KINESIOLOGY 77
EDUCATIONAL LEADERSHIP 17 MATHEMATICS 67
HUMAN SERVICES 18 MEDICAL TECHNOLOGY 68
ANTHROPOLOGY 21 MILITARY SCIENCE 70
ART 22 NURSING COLLABORATIVE 71
AFRICAN AMERICAN STUDIES 23 MUSIC 73
BIOLOGY 26 NURSING 74
BUSINESS 28 PHILOSOPHY 76
COUNSELOR EDUCATION 29 PHYSICAL EDUCATION 79
PROFESSIONAL COUNSELING 29 PHYSICAL SCIENCE 80
LIBERAL STUDIES 31 PUBLIC ADMINISTRATION 81
CHEMISTRY 32 PHYSICS/ASTRONOMY 82
COMPUTER SCIENCE 34 POLITICAL SCIENCE 84
CRIMINAL JUSTICE 35 PRACTICAL ARTS 85
ECONOMICS 36 PSYCHOLOGY 86
ENVIRONMENTAL STUDIES 37 RELIGIOUS STUDIES 87
ENGLISH 38 WRITING-BASED INQ SEM 88
FRENCH 41 PROBLEM-BASED INQ SEM 89
GERMAN 43 SOCIAL JUSTICE 91
JAPANESE 44 SOCIOLOGY 92
RUSSIAN 48 SOCIAL WORK 93
SPANISH 49 INTERDISCIPLINARY STDS 94
GEOGRAPHY 50 COMMUNICATION 96
GEOLOGY 51 THEATRE 97
ARAPAHO 53 WOMEN'S STUDIES 98
SHOSHONE 54 URBAN PLANNING 99
-----------------------------------------------------------------
=================================================================
********************* END OF ANALYSIS *********************
Return to Academics
"""; | true | @binaryStar = """
New Window | Help | Customize Page
STAR On-Line
Return to Request STAR On-Line
Binary Guy
PREPARED: 02/06/13 - 10:27
Guy,Binary
PROGRAM CODE: 222234006 CATALOG YEAR: 2011
CAMPUS ID : xxxxxxx
BACHELOR OF SCIENCE DEGREE - COLLEGE OF LETTERS AND SCIENCE
COMPUTER SC & SOFTWARE ENGINEERING (COMPUTER INFO SYS) MAJOR
=================================================================
UNIVERSITY OF WISCONSIN OSHKOSH STUDENT ACADEMIC REPORT (STAR)
REPORT NO.
You can register on Titan Web for
Fall 2013 as of Feb-27-2013 at 08:00 AM
ADVISOR: PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI UGLS J34006222
STUDENT ACADEMIC PROGRAM
PROGRAM : UGLS 2011
PLAN : J34006222 Comp Sci(CIS)-BS 2011
TRANSFER INST : Northeast Wisconsin Technical 4585 JC
UW-OSHKOSH PLACEMENT AT TIME OF ADMISSION
ENGLISH : Gen Ed English Comp or English 110
MATH : Deficient-Math 103
ACADEMIC STANDING : GOOD
COMMENTS :
OFFICIAL GRADE EARNED
GPA CREDS POINTS GPA CREDS
TRANSFER INST 0.00
UWO OFFICIAL 46.00 155.00 3.370 46.00
=================================================================
------> AT LEAST ONE REQUIREMENT HAS NOT BEEN SATISFIED <------
=================================================================
COMBINED GPA (IPLIST)
UWO AND TRANSFER COURSE COMBINED GPA
(Amnesty courses excluded)
46.00 CRS EARNED
46.00 ATTEMPTED HOURS 155.00 POINTS 3.369 GPA
IN-PROG 17.00 CREDITS
=======================================================
IN-PROGRESS COURSES
1232 34-251 3.00 .00 IP Architecture & Assembly Lang
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 38-214 3.00 .00 IP American Lit II (HU)
1232 67-171 4.00 .00 IP Calculus I (MA)
1232 73-102 3.00 .00 IP Theory Music Gen Student (HU)
* =======================================================
ADJUSTMENTS TO THE COURSE REGISTRATIONS LISTED ABOVE OR
COURSES NOT COMPLETED SUCCESSFULLY WILL CHANGE THE
STATUS OF THIS REPORT. COURSES CURRENTLY BEING
REPEATED WILL NOT BE LISTED WITH THE IN-PROGRESS COURSE
BUT WILL BE LISTED IN THE REQUIREMENT TO WHICH THEY
APPLY.
=======================================================
BRING YOUR STAR WITH YOU WHEN MEETING WITH YOUR ADVISOR
=================================================================
NO GENERAL EDUCATION COMPOSITION (GCOMP) 2011-99
MINIMUM 2.00 GPA REQUIRED IN ALL APPLICABLE COURSES
TWO COURSES (6 CREDITS) REQUIRED
EARNED 3.330 GPA
+ 1) COMPLETE A WRITING-BASED COMPOSITION COURSE:
1122 88-188 3.00 B+ 9.99 Wrtng-Bsd Inq Sem (WBIS) (EN)
- 2) COMPLETE A SECOND COMPOSITION COURSE:
(MINIMUM OF 45 CREDITS REQUIRED TO ENROLL)
SELECT FROM: 38-203 38-302 38-307 38-309 38-310
38-316 38-317 38-318 38-321 38-389
=================================================================
OK MATHEMATICS REQUIREMENT FOR THE L&S (GMATH2BS)
BACHELOR OF SCIENCE DEGREE
+ 1) YOU MUST COMPLETE REMEDIAL MATH COURSE 103
AND EARN A GRADE OF C OR BETTER.
1121 67-103 3.00 B+ 9.99 Intermediate Algebra
+ 2) LEVEL I COMPLETED
**NOTE: APPROPRIATE LEVEL I COURSE OPTIONS ARE BASED
ON THE STUDENT'S TEST SCORE AND THE REQUIREMENTS
FOR YOUR MAJOR. SEE AN ADVISOR FOR CORRECT SEQUENCE**
1122 67-104 3.00 C 6.00 College Algebra
+ 3) LEVEL II MATH
4.000 GPA
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 67-171 4.00 .00 IP Calculus I (MA)
+ 4) LEVEL I MATH EXEMPTED/COMPLETED WITH LEVEL II
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 67-171 4.00 .00 IP Calculus I (MA)
=================================================================
OK GENERAL EDUCATION PHYSICAL EDUCATION (GPED)
ONE COURSE (TWO CREDITS) REQUIRED (2011-99)
1121 79-105 2.00 A 8.00 Active Lifestyle (PE)
=================================================================
OK GENERAL EDUCATION NON-WESTERN CULTURE (GNWST)
ONE COURSE (THREE CREDITS) REQUIRED
1122 84-101 3.00 B+ 9.99 Intro to Cmpartv Pltcs(SS)(NW
=================================================================
OK COMMUNICATION REQUIREMENT FOR THE L&S (GSPCH2BSA)
BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES
1231 96-111 3.00 A- 11.01 Fund Spch Comm (GE)
=================================================================
OK HUMANITIES REQUIREMENT FOR THE L&S (GHUM2BS)
BACHELOR OF SCIENCE DEGREE
EARNED 7.00 CREDITS 4 SUB-REQS
IN-PROGRESS 6.00 CREDITS
1232 38-214 3.00 .00 IP American Lit II (HU)
1232 73-102 3.00 .00 IP Theory Music Gen Student (HU)
1122 76-110 3.00 B 9.00 H: Intro Philosophy (HU)
1122 41-110 4.00 A- 14.68 Intro French I (HU)
=================================================================
COMPLETION OF THE B.S. LAB SCIENCE AREA REQUIRES FOUR (4) COURSES
AS DESCRIBED BELOW IN AREAS 1-3. SELECT FROM LAB SCIENCES IN
BIOLOGY, CHEMISTRY, GEOGRAPHY, GEOLOGY, PHYSICS/ASTRONOMY (NEW1)
------------ AREA #1 ------------------------------------------
TWO LABORATORY SCIENCE COURSES FROM THE SAME DEPARTMENT, ONE OF
WHICH REQUIRES THE SECOND AS A PREREQUISITE.
------------ AREA #2 ------------------------------------------
ONE NATURAL SCIENCE LABORATORY COURSE FROM A DIFFERENT DEPARTMENT
THAN THE DEPARTMENT SELECTED IN AREA #1
------------ AREA #3 ------------------------------------------
ONE COURSE THAT MATCHES ONE OF THE OPTIONS BELOW:
A) A COURSE FROM THE SAME DEPARTMENT AS THE ONE SELECTED FOR
AREA #2 AND WHICH HAS THAT COURSE AS A PREREQUISITE
B) A LAB SCIENCE COURSE FROM A 3RD DEPARTMENT
C) A COURSE FROM THOSE LISTED UNDER THE B.S. MATH REQUIREMENT
=================================================================
NO TWO PAIRS (ONE PAIR FROM EACH OF TWO DEPARTMENTS) (NEW3)
- 1) GEOLOGY DEPARTMENTAL APPROVED PAIRINGS
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
=================================================================
COMPLETE TWO COURSES FROM THE SAME NATURAL
SCIENCE DEPARTMENT. (THE FIRST COURSE MUST
BE THE PREREQUISITE OF THE SECOND COURSE)
NOTE: PLEASE SEE THE LIST OF APPROVED PAIRS
LOCATED IN THE PREVIOUS REQUIREMENT.
---------------------------------------------
NO OR ONE PAIR PLUS 2 OTHER DEPARTMENTS OPTION (NEW2)
- 1) BIOLOGY DEPARTMENT APPROVED PAIRINGS
SELECT 26-105 PLUS ONE OF THE FOLLOWING:
- OR) SELECT 26-108 PLUS ONE OF THE FOLLOWING:
- OR) CHEMISTRY DEPARTMENTAL APPROVED PAIRINGS
- OR) GEOGRAPHY DEPARTMENTAL APPROVED PAIR
- OR) GEOLOGY DEPARTMENTAL APPROVED PAIRINGS
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
- OR) PHYSICS/ASTRONOMY APPROVED PAIRINGS
- 2) CHEMISTRY
- 3) -----------------------------------------------
COMPLETE A LAB SCIENCE COURSE FROM EACH OF TWO
SCIENCE DEPARTMENTS OTHER THAN THE DEPARTMENT
SELECTED FOR THE REQUIRED LAB PAIR.
......THE COURSES USED TO SATISFY THE PAIR ABOVE
WILL ALSO PRINT IN THE APPROPRIATE AREA
BELOW, BUT WILL NOT SATISFY THE DEPARTMENTAL
REQUIREMENT (A TOTAL OF THREE DEPARTMENTS
REQUIRED -- INCLUDING THE PAIR)
BIOLOGY
- 4) GEOGRAPHY
+ 5) GEOLOGY
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
+ 6) PHYSICS/ASTRONOMY
1121 80-101 4.00 A 16.00 Workshop Physical Science (NS
- 7) ANTHROPOLOGY
+ 8) YOU MAY TAKE A SECOND MATH/STATS/COMPUTER SC.
AREA (AS DESCRIBED IN THE MATH REQUIREMENT
FOR YOUR THIRD DEPARTMENT REQUIREMENT.
1232 34-262 4.00 .00 IP OO Design & Programming II
1232 67-171 4.00 .00 IP Calculus I (MA)
=================================================================
OK SOCIAL SCIENCE REQUIREMENT FOR THE L&S (GSOSC2BSA)
BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES
EARNED 12.00 CREDITS
+R 1) YOU MUST COMPLETE A MINIMUM OF THREE CREDITS
OF HISTORY
3.00 CRS EARNED
1121 57-101 3.00 A- 11.01 Early Civilization (SS)
+ 3) ANTHROPOLOGY (ANY COURSE EXCEPT 21-202)
3.00 CRS EARNED
1231 21-123 3.00 A- 11.01 American Ethnography (ES) (SS
+ 10) POLITICAL SCIENCE/PUBLIC ADMIN (ANY COURSE)
3.00 CRS EARNED
1122 84-101 3.00 B+ 9.99 Intro to Cmpartv Pltcs(SS)(NW
+ 11) PSYCHOLOGY (ANY COURSE EXCEPT PSYCH 203, 303, 305, 310,
341,367,371,380,383,384,391,411,455,481,498 & 499)
3.00 CRS EARNED
1121 86-104 3.00 B 9.00 H: General Psychology (SS)
=================================================================
OK GENERAL EDUCATION ETHNIC STUDIES (GETHNIC)
ONE COURSE (THREE CREDITS) REQUIRED
(IF SELECTED, 74-215 MUST BE COMPLETED FOR 3 CREDITS)
1231 21-123 3.00 A- 11.01 American Ethnography (ES) (SS
=================================================================
OPTIONAL GENERAL EDUCATION COURSES (NOT REQUIRED, BUT MAY
BE APPLIED TOWARD 42 CREDIT MINIMUM IN GENERAL EDUCATION)
(GOPT) (SEE E-BULLETIN OR E-TIMETABLE FOR LIST)
=================================================================
OK GENERAL EDUCATION SUMMARY (GENEDSUM)
A MINIMUM OF 42 CREDITS IN GENERAL EDUCATION IS REQUIRED.
PLEASE REFER TO THE E-BULLETIN OR E-TIMETABLE FOR THE
APPROVED GENERAL EDUCATION LIST.
EARNED 35.00 CREDITS
35.00 ATTEMPTED HOURS 123.01 POINTS 3.514 GPA
IN-PROGRESS 10.00 CREDITS
=================================================================
NO COMPUTER SCIENCE MAJOR (COMPUTER INFO SYSTEMS)
59 CREDITS AND A 2.00 MIN G.P.A. REQUIRED (J34006/09-9999)
EARNED 3.00 CREDITS 4.000 GPA
IN-PROGRESS 11.00 CREDITS
--> NEEDS: 45.00 CREDITS 4 SUB-REQS 2.000 GPA
- 1) COMPLETE THE FOLLOWING CORE COURSES:
3.00 CRS EARNED 4.000 GPA
IN-PROG 7.00 CREDITS
1231 34-221 3.00 A 12.00 OO Design & Programming I
1232 34-251 3.00 .00 IP Architecture & Assembly Lang
1232 34-262 4.00 .00 IP OO Design & Programming II
NEEDS: 5 COURSES
SELECT FROM: 34-271 34-331 34-399 OR 34-490 67-212
82-311
- 2) COMPLETE THE FOLLOWING COURSES IN ADDITION
TO THE COMPUTER SCIENCE CORE COURSES:
.00 CRS EARNED
IN-PROG 4.00 CREDITS
1232 67-171 4.00 .00 IP Calculus I (MA)
NEEDS: 5 COURSES
SELECT FROM: 34-341 34-346 34-350 34-361 67-201 OR
67-301 OR 36-210
- 3) COMPLETE A MINIMUM OF NINE CREDITS FROM THE
FOLLOWING LIST A ELECTIVE COURSES:
NEEDS: 9.00 CREDITS
SELECT FROM: 34-300 34-310 34-321 34-342 34-371
34-381 34-391 34-421 34-431 34-480
- 4) SELECT A MINIMUM OF 6 CREDITS FROM THE
FOLLOWING LIST B ELECTIVE COURSES:
NEEDS: 6.00 CREDITS
SELECT FROM: 28-260 28-314 28-315 28-319 28-355
28-410
+ 5) A MINIMUM GRADE POINT AVERAGE OF 2.00 IN ALL COURSES
NUMBERED 300 OR ABOVE (EXCEPT 34-399, 34-446, 34-456,
34-474, AND 34-490) IS REQUIRED.
NEEDS: 2.000 GPA
-> NOT FROM: 34-334 34-335 34-399 34-446 34-456
34-474 34-490
SELECT FROM: 34-300 TO 34-499
=================================================================
ELECTIVE CREDITS WHICH APPLY TO THE UNDERGRADUATE DEGREE
(ELECTIVE)
1231 51-102 4.00 B+ 13.32 Physical Geology (NS)
1122 67-104 3.00 C 6.00 College Algebra
1231 67-106 2.00 C 4.00 Trigonometry
1121 80-101 4.00 A 16.00 Workshop Physical Science (NS
=================================================================
CHECK LIMITS FOR MUSIC, DRAMA, PHY-ED PARTICIPATION
AND PROFESSIONAL COURSES (PRESUM2)
1) ONLY 4 CREDITS OF MUSIC PARTICIPATION COURSES
MAY BE APPLIED TO DEGREE CREDIT FOR NON-MUSIC MAJORS
OR MINORS.
2) ONLY 4 CREDITS OF DRAMA OR THEATRE PARTICIPATION
COURSES MAY APPLY TO DEGREE CREDITS
3) ONLY 4 CREDITS OF PHYSICAL EDUCATION ACTIVITY
COURSES MAY APPLY TO THE DEGREE CREDITS IN THIS AREA.
(ANY CREDITS OVER 4 WILL BE COUNTED AS PREPROFESSIONAL)
1121 79-105 2.00 A 8.00 Active Lifestyle (PE)
4) A MAXIMUM OF 24 PREPROFESSIONAL CREDITS MAY COUNT
TOWARD THE 120 REQUIRED TO GRADUATE.
=================================================================
NO GENERAL BACCALAUREATE DEGREE REQUIREMENTS (SUMMARY)
- 1) EARN A MINIMUM OF 120 DEGREE CREDITS
43.00 CRS EARNED
IN-PROG 17.00 CREDITS
NEEDS: 60.00 CREDITS
+ 3) EARN A MINIMUM 2.00 GPA IN UWO CREDITS ATTEMPTED
46.00 ATTEMPTED HOURS 155.00 POINTS 3.369 GPA
+ 4) EARN A MINIMUM 2.00 GPA IN ALL COURSES APPLICABLE TO
THE UNIVERSITY'S GENERAL EDUCATION ENGLISH COMPOSITION
REQUIREMENT
3.330 GPA
+ 5) EARN AT LEAST 30 SEMESTER CREDITS AT UW OSHKOSH
( 46.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
+ 6) EARN AT LEAST 48 CREDITS FROM A 4 YEAR INSTITUTION
( 46.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
- 7) EARN AT LEAST 35 CREDITS AT THE UPPER LEVEL (300/400)
WITH A MINIMUM 2.00 GPA
NEEDS: 35.00 CREDITS
+ 8) 15 OF THE LAST 30 CREDITS MUST BE TAKEN AT UWO.
( 15.00 CREDITS TAKEN)
IN-PROG 17.00 CREDITS
=================================================================
CREDITS NOT APPLICABLE TO THE UNDERGRADUATE DEGREE
(REMEDIAL & GRADUATE COURSES)
- REMEDIAL COURSES NOT APPLIED TO UNDERGRAD DEGREE
1121 67-103 3.00 B+ 9.99 Intermediate Algebra
=================================================================
**** LEGEND ****
NO = REQUIREMENT NOT COMPLETE >D = DUPLICATE COURSE - CREDIT
OK = REQUIREMENT COMPLETE & GPA EFFECT REMOVED ON
- = SUBREQUIREMENT NOT COMPLETE COURSE EXCEEDING LIMIT
+ = SUBREQUIREMENT COMPLETE >X = REPEATED COURSE - CREDIT
* = SUBREQUIREMENT IS OPTIONAL & GPA EFFECT REMOVED ON
(R)= REQUIRED COURSE ORIGINAL COURSE
+R = REQUIRED SUBREQUIREMENT >S = COURSE CREDIT SPLIT
COMPLETED BETWEEN REQUIREMENTS
-R = REQUIRED SUBREQUIREMENT >R = REPEATABLE COURSE - CREDIT
NOT COMPLETED MAY BE EARNED MORE THAN
CS = COURSE SUBSTITUTION ONCE
WC = WAIVED COURSE WH = WAIVED CREDIT HOUR
<> = CONTINUED REQUIREMENT >C = DUPLICAT CROSS-LINKED COUR
S = SATISFACTORY GRADE IN RETRO., MILITARY, DEPT., TEST OUT CR.
******
PLEASE NOTE: THE FOUR NUMBERS BEFORE A COURSE INDICATE THE TERM
IN WHICH THE COURSE WAS TAKEN. THE FIRST THREE NUMBERS INDICATE
THE ACADEMIC YEAR (078 IS USED FOR THE 2007-08 ACADEMIC YEAR).
THE LAST NUMBER INDICATES THE TERM (1 = FALL, 2 = SPRING,
4 = SUMMER). FOR EXAMPLE, 0782 IS THE SPRING TERM OF 2007-08.
****************************************************************
******
THIS NOTICE OF ACADEMIC PROGRESS HAS BEEN PREPARED TO ASSIST YOU
DURING YOUR COLLEGE EXPERIENCE. ALTHOUGH EFFORTS HAVE BEEN MADE
TO ASSESS THE ACCURACY OF THIS REPORT, YOU ARE RESPONSIBLE FOR
MAKING SURE THAT ALL REQUIREMENTS HAVE BEEN COMPLETED. THE
REGISTRAR'S OFFICE WILL ULTIMATELY AUTHORIZE THE AWARDING OF
YOUR DEGREE; THEREFORE, IF YOU HAVE ANY QUESTIONS ABOUT THE
ACCURACY OF THIS PROGRESS REPORT, PLEASE SEE AN ACADEMIC ADVISOR
IN DEMPSEY 130.
*******
****************************************************************
=================================================================
THIS AUDIT ASSUMES SUCCESSFUL COMPLETION OF ALL IN-PROGRESS
COURSES; ANY IN-PROGRESS COURSES NOT COMPLETED SUCCESSFULLY
MAY CHANGE THIS AUDIT'S EVALUATION.
-----------------------------------------------------------------
**** CONFIDENTIAL - STUDENT/ADVISOR USE ONLY ****
**** FEDERAL LAW PROHIBITS TRANSMITTAL TO A THIRD PARTY ****
-----------------------------------------------------------------
DEPARTMENT CONVERSION TABLE
HONORS 00 HEALTH 55
SERVICE COURSES IN EDUC 11 HEALTH EDUCATION 55
EDUCATIONAL FOUNDATIONS 12 CHINESE 56
ELEMENTARY EDUCATION 13 HISTORY 57
SECONDARY EDUCATION 14 INTERNATIONAL STUDIES 59
READING EDUCATION 15 JOURNALISM 61
SPECIAL EDUCATION 16 KINESIOLOGY 77
EDUCATIONAL LEADERSHIP 17 MATHEMATICS 67
HUMAN SERVICES 18 MEDICAL TECHNOLOGY 68
ANTHROPOLOGY 21 MILITARY SCIENCE 70
ART 22 NURSING COLLABORATIVE 71
AFRICAN AMERICAN STUDIES 23 MUSIC 73
BIOLOGY 26 NURSING 74
BUSINESS 28 PHILOSOPHY 76
COUNSELOR EDUCATION 29 PHYSICAL EDUCATION 79
PROFESSIONAL COUNSELING 29 PHYSICAL SCIENCE 80
LIBERAL STUDIES 31 PUBLIC ADMINISTRATION 81
CHEMISTRY 32 PHYSICS/ASTRONOMY 82
COMPUTER SCIENCE 34 POLITICAL SCIENCE 84
CRIMINAL JUSTICE 35 PRACTICAL ARTS 85
ECONOMICS 36 PSYCHOLOGY 86
ENVIRONMENTAL STUDIES 37 RELIGIOUS STUDIES 87
ENGLISH 38 WRITING-BASED INQ SEM 88
FRENCH 41 PROBLEM-BASED INQ SEM 89
GERMAN 43 SOCIAL JUSTICE 91
JAPANESE 44 SOCIOLOGY 92
RUSSIAN 48 SOCIAL WORK 93
SPANISH 49 INTERDISCIPLINARY STDS 94
GEOGRAPHY 50 COMMUNICATION 96
GEOLOGY 51 THEATRE 97
ARAPAHO 53 WOMEN'S STUDIES 98
SHOSHONE 54 URBAN PLANNING 99
-----------------------------------------------------------------
=================================================================
********************* END OF ANALYSIS *********************
Return to Academics
"""; |
[
{
"context": "lue of exchange.responseHeaders\n if key in ['Content-Type', 'Connection', 'Date', 'Via', 'Server', 'Content",
"end": 639,
"score": 0.704582691192627,
"start": 627,
"tag": "KEY",
"value": "Content-Type"
},
{
"context": "', 'Server', 'Content-Length']\n if key == 'Content-Type'\n is_json = value.search(/(json)/i) > -1",
"end": 730,
"score": 0.9232831001281738,
"start": 718,
"tag": "KEY",
"value": "Content-Type"
}
] | APIBlueprintGenerator.coffee | jdve/Paw-APIBlueprintGenerator | 0 | # in API v0.2.0 and below (Paw 2.2.2 and below), require had no return value
((root) ->
if root.bundle?.minApiVersion('0.2.0')
root.Mustache = require("./mustache")
else
require("mustache.js")
)(this)
APIBlueprintGenerator = ->
# Generate a response dictionary for the mustache context from a paw HTTPExchange
#
# @param [HTTPExchange] exchange The paw HTTP exchange for the response
#
# @return [Object] The template context object
#
@response = (exchange) ->
if !exchange
return null
headers = []
is_json = false
for key, value of exchange.responseHeaders
if key in ['Content-Type', 'Connection', 'Date', 'Via', 'Server', 'Content-Length']
if key == 'Content-Type'
is_json = value.search(/(json)/i) > -1
continue
headers.push({ key: key, value: value })
has_headers = (headers.length > 0)
body = exchange.responseBody
has_body = body.length > 0
if has_body
if is_json
body = JSON.stringify(JSON.parse(body), null, 4)
body_indentation = ' '
if has_headers
body_indentation += ' '
body = body.replace(/^/gm, body_indentation)
return {
statusCode: exchange.responseStatusCode,
contentType: exchange.responseHeaders['Content-Type'],
"headers?": has_headers,
headers: headers
"body?": has_headers && has_body,
body: body,
}
# Generate a request dictionary for the mustache context from a paw Request
#
# @param [Request] exchange The paw HTTP request
#
# @return [Object] The template context object
#
@request = (paw_request) ->
headers = []
is_json = false
for key, value of paw_request.headers
if key in ['Content-Type']
is_json = (value.search(/(json)/i) > -1)
continue
headers.push({ key: key, value: value })
has_headers = (headers.length > 0)
body = paw_request.body
has_body = body.length > 0
if has_body
if is_json
body = JSON.stringify(JSON.parse(body), null, 4)
body_indentation = ' '
if has_headers
body_indentation += ' '
body = body.replace(/^/gm, body_indentation)
description = paw_request.description
has_description = description && description.length > 0
if has_headers || has_body || paw_request.headers['Content-Type']
return {
"headers?": has_headers,
headers: headers,
contentType: paw_request.headers['Content-Type'],
"body?": has_headers && has_body,
body: body,
"description?": has_description,
description: description,
}
# Get a path from a URL
#
# @param [String] url The given URL
#
# @return [String] The path from the URL
@path = (url) ->
path = url.replace(/^https?:\/\/[^\/]+/i, '')
if !path
path = '/'
path
@generate = (context) ->
paw_request = context.getCurrentRequest()
url = paw_request.url
template = readFile("apiblueprint.mustache")
Mustache.render(template,
method: paw_request.method,
path: @path(url),
request: @request(paw_request),
response: @response(paw_request.getLastExchange()),
)
return
APIBlueprintGenerator.identifier = "io.apiary.PawExtensions.APIBlueprintGenerator"
APIBlueprintGenerator.title = "API Blueprint Generator"
APIBlueprintGenerator.fileExtension = "md"
registerCodeGenerator APIBlueprintGenerator
| 52505 | # in API v0.2.0 and below (Paw 2.2.2 and below), require had no return value
((root) ->
if root.bundle?.minApiVersion('0.2.0')
root.Mustache = require("./mustache")
else
require("mustache.js")
)(this)
APIBlueprintGenerator = ->
# Generate a response dictionary for the mustache context from a paw HTTPExchange
#
# @param [HTTPExchange] exchange The paw HTTP exchange for the response
#
# @return [Object] The template context object
#
@response = (exchange) ->
if !exchange
return null
headers = []
is_json = false
for key, value of exchange.responseHeaders
if key in ['<KEY>', 'Connection', 'Date', 'Via', 'Server', 'Content-Length']
if key == '<KEY>'
is_json = value.search(/(json)/i) > -1
continue
headers.push({ key: key, value: value })
has_headers = (headers.length > 0)
body = exchange.responseBody
has_body = body.length > 0
if has_body
if is_json
body = JSON.stringify(JSON.parse(body), null, 4)
body_indentation = ' '
if has_headers
body_indentation += ' '
body = body.replace(/^/gm, body_indentation)
return {
statusCode: exchange.responseStatusCode,
contentType: exchange.responseHeaders['Content-Type'],
"headers?": has_headers,
headers: headers
"body?": has_headers && has_body,
body: body,
}
# Generate a request dictionary for the mustache context from a paw Request
#
# @param [Request] exchange The paw HTTP request
#
# @return [Object] The template context object
#
@request = (paw_request) ->
headers = []
is_json = false
for key, value of paw_request.headers
if key in ['Content-Type']
is_json = (value.search(/(json)/i) > -1)
continue
headers.push({ key: key, value: value })
has_headers = (headers.length > 0)
body = paw_request.body
has_body = body.length > 0
if has_body
if is_json
body = JSON.stringify(JSON.parse(body), null, 4)
body_indentation = ' '
if has_headers
body_indentation += ' '
body = body.replace(/^/gm, body_indentation)
description = paw_request.description
has_description = description && description.length > 0
if has_headers || has_body || paw_request.headers['Content-Type']
return {
"headers?": has_headers,
headers: headers,
contentType: paw_request.headers['Content-Type'],
"body?": has_headers && has_body,
body: body,
"description?": has_description,
description: description,
}
# Get a path from a URL
#
# @param [String] url The given URL
#
# @return [String] The path from the URL
@path = (url) ->
path = url.replace(/^https?:\/\/[^\/]+/i, '')
if !path
path = '/'
path
@generate = (context) ->
paw_request = context.getCurrentRequest()
url = paw_request.url
template = readFile("apiblueprint.mustache")
Mustache.render(template,
method: paw_request.method,
path: @path(url),
request: @request(paw_request),
response: @response(paw_request.getLastExchange()),
)
return
APIBlueprintGenerator.identifier = "io.apiary.PawExtensions.APIBlueprintGenerator"
APIBlueprintGenerator.title = "API Blueprint Generator"
APIBlueprintGenerator.fileExtension = "md"
registerCodeGenerator APIBlueprintGenerator
| true | # in API v0.2.0 and below (Paw 2.2.2 and below), require had no return value
((root) ->
if root.bundle?.minApiVersion('0.2.0')
root.Mustache = require("./mustache")
else
require("mustache.js")
)(this)
APIBlueprintGenerator = ->
# Generate a response dictionary for the mustache context from a paw HTTPExchange
#
# @param [HTTPExchange] exchange The paw HTTP exchange for the response
#
# @return [Object] The template context object
#
@response = (exchange) ->
if !exchange
return null
headers = []
is_json = false
for key, value of exchange.responseHeaders
if key in ['PI:KEY:<KEY>END_PI', 'Connection', 'Date', 'Via', 'Server', 'Content-Length']
if key == 'PI:KEY:<KEY>END_PI'
is_json = value.search(/(json)/i) > -1
continue
headers.push({ key: key, value: value })
has_headers = (headers.length > 0)
body = exchange.responseBody
has_body = body.length > 0
if has_body
if is_json
body = JSON.stringify(JSON.parse(body), null, 4)
body_indentation = ' '
if has_headers
body_indentation += ' '
body = body.replace(/^/gm, body_indentation)
return {
statusCode: exchange.responseStatusCode,
contentType: exchange.responseHeaders['Content-Type'],
"headers?": has_headers,
headers: headers
"body?": has_headers && has_body,
body: body,
}
# Generate a request dictionary for the mustache context from a paw Request
#
# @param [Request] exchange The paw HTTP request
#
# @return [Object] The template context object
#
@request = (paw_request) ->
headers = []
is_json = false
for key, value of paw_request.headers
if key in ['Content-Type']
is_json = (value.search(/(json)/i) > -1)
continue
headers.push({ key: key, value: value })
has_headers = (headers.length > 0)
body = paw_request.body
has_body = body.length > 0
if has_body
if is_json
body = JSON.stringify(JSON.parse(body), null, 4)
body_indentation = ' '
if has_headers
body_indentation += ' '
body = body.replace(/^/gm, body_indentation)
description = paw_request.description
has_description = description && description.length > 0
if has_headers || has_body || paw_request.headers['Content-Type']
return {
"headers?": has_headers,
headers: headers,
contentType: paw_request.headers['Content-Type'],
"body?": has_headers && has_body,
body: body,
"description?": has_description,
description: description,
}
# Get a path from a URL
#
# @param [String] url The given URL
#
# @return [String] The path from the URL
@path = (url) ->
path = url.replace(/^https?:\/\/[^\/]+/i, '')
if !path
path = '/'
path
@generate = (context) ->
paw_request = context.getCurrentRequest()
url = paw_request.url
template = readFile("apiblueprint.mustache")
Mustache.render(template,
method: paw_request.method,
path: @path(url),
request: @request(paw_request),
response: @response(paw_request.getLastExchange()),
)
return
APIBlueprintGenerator.identifier = "io.apiary.PawExtensions.APIBlueprintGenerator"
APIBlueprintGenerator.title = "API Blueprint Generator"
APIBlueprintGenerator.fileExtension = "md"
registerCodeGenerator APIBlueprintGenerator
|
[
{
"context": "roxy'\nutils = require '../lib/utils'\n\nusername = 'mikerobe@me.com'\npassword = 'test'\ncookiesPath = path.join(__file",
"end": 249,
"score": 0.9999130964279175,
"start": 234,
"tag": "EMAIL",
"value": "mikerobe@me.com"
},
{
"context": "/utils'\n\nusername = 'mikerobe@me.com'\npassword = 'test'\ncookiesPath = path.join(__filename, '../cookies.",
"end": 267,
"score": 0.9992570281028748,
"start": 263,
"tag": "PASSWORD",
"value": "test"
},
{
"context": "add a tag if it does not exist', ->\n name = 'foo bar'\n assert.equal(utils.addTag(name, 'today'), ",
"end": 14967,
"score": 0.6363178491592407,
"start": 14960,
"tag": "NAME",
"value": "foo bar"
}
] | test/index.coffee | mvgrimes/workflowy | 1 | assert = require 'assert'
fs = require 'fs'
Q = require 'q'
path = require 'path'
Workflowy = require '../'
FileCookieStore = require 'tough-cookie-filestore'
proxy = require '../lib/proxy'
utils = require '../lib/utils'
username = 'mikerobe@me.com'
password = 'test'
cookiesPath = path.join(__filename, '../cookies.json')
initialList = """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
fc = null
workflowy = null
workflowyMatchesOutline = (inst, outline) ->
[outline, inst] = [inst, workflowy] if arguments.length <2
inst.find().then (nodes) ->
# find the root nodes in the flat list
nodes = nodes.filter (node) -> node.parentId is 'None'
assert.equal(utils.treeToOutline(nodes),outline)
addChildrenTest = (workflowy) ->
workflowy.addChildren [{name: 'first'}, {name: 'second'}]
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'second')
workflowy.addChildren [{name: 'underFirst1'}, {name: 'underFirst2'}], nodes[0]
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'underFirst1')
assert.equal(nodes[2].nm, 'underFirst2')
assert.equal(nodes[3].nm, 'second')
assert.equal(nodes[1].parentId, nodes[0].id)
assert.equal(nodes[2].parentId, nodes[0].id)
workflowy.addChildren [{name: 'between underFirst1 and underFirst2 a'}, {name: 'between underFirst1 and underFirst2 b'}], nodes[0], 1
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'underFirst1')
assert.equal(nodes[2].nm, 'between underFirst1 and underFirst2 a')
assert.equal(nodes[3].nm, 'between underFirst1 and underFirst2 b')
assert.equal(nodes[4].nm, 'underFirst2')
assert.equal(nodes[5].nm, 'second')
assert.equal(nodes[0].parentId, 'None')
assert.equal(nodes[1].parentId, nodes[0].id)
assert.equal(nodes[2].parentId, nodes[0].id)
assert.equal(nodes[3].parentId, nodes[0].id)
assert.equal(nodes[4].parentId, nodes[0].id)
assert.equal(nodes[5].parentId, 'None')
.then ->
root = "foo #{Date.now()}"
rootNode = null
workflowy.addChildren name: root
.then -> workflowy.find()
.then (nodes) ->
rootNode = nodes[0]
assert.equal(nodes[0].nm,root)
workflowy.addChildren [{name: '1'},{name: '3'},{name:'5'}], nodes[0]
.then -> workflowy.find( (node) -> node.id is rootNode.id )
.then (nodes) -> rootNode = nodes[0]
.then -> workflowy.asText(rootNode)
.then (text) ->
assert.equal text, """
- #{root}
- 1
- 3
- 5
"""
workflowy.addChildren [{name: '2'},{name: '4'}], rootNode, [1,2]
.then -> workflowy.find( (node) -> node.id is rootNode.id )
.then (nodes) -> rootNode = nodes[0]
.then -> workflowy.asText(rootNode)
.then (text) ->
assert.equal text, """
- #{root}
- 1
- 2
- 3
- 4
- 5
"""
# add at the botom of the doc with a high priority
.then ->
names = [1..10].map (num) -> ''+num
workflowy.addChildren names.map (name) -> {name}
.then -> workflowy.find()
.then (nodes) ->
# first 10 nodes should have the given names
for name,i in names
assert.equal(nodes[i].nm, names[i])
# now add a node with a crazy priority
workflowy.addChildren({name: 'at the bottom'},null, 1e6)
.then -> workflowy.find()
.then (nodes) ->
# first 10 nodes should still have the given names
for name,i in names
assert.equal(nodes[i].nm, names[i])
# last node is known
assert.equal(nodes[nodes.length-1].nm, 'at the bottom')
shareIdTests = (useQuarantine) ->
rootName = "Book list"
throw new Error "env var WORKFLOWY_SHAREID is required to test quarantine and share id" unless shareId = process.env.WORKFLOWY_SHAREID
fcSub = new FileCookieStore('cookies.json')
workflowySub = null
beforeEach ->
# clean up all the nodes under the book list
workflowy = new Workflowy username, password, jar: fc
if useQuarantine
workflowySub = workflowy.quarantine shareId
workflowy.find(rootName)
.then (nodes) ->
assert.equal nodes.length, 1
if (children = nodes[0].ch)?.length
workflowy.delete(children)
.then ->
unless useQuarantine
workflowySub = new Workflowy username, password, jar: fcSub, shareId: shareId
else
unless useQuarantine
workflowySub = new Workflowy username, password, jar: fcSub, shareId: shareId
describe '#find', ->
it 'should return only nodes under the given Id', ->
workflowySub.refresh()
workflowyMatchesOutline workflowySub, ""
describe '#addChildren shareId', ->
it 'should add children under the expected root node', ->
newRootNode = "top level child #{Date.now()}"
newShareNode = "share #{Date.now()}"
Q.all([
workflowy.addChildren name: newRootNode
workflowySub.addChildren name: newShareNode
]).then ->
workflowyMatchesOutline workflowySub, "- #{newShareNode}"
.then ->
workflowy.find().then (nodes) ->
assert.equal nodes[0].nm, newRootNode
describe.skip 'Workflowy over the wire', ->
username = process.env.WORKFLOWY_USERNAME
password = process.env.WORKFLOWY_PASSWORD
beforeEach ->
(console.error "Workflowy username and password must be provided through environmental variables."; process.exit 1) unless username and password
Q.ninvoke fs, 'unlink', cookiesPath
.then Q, Q
.then ->
fc = new FileCookieStore('cookies.json')
describe.skip '#constructor', ->
it 'with empty cookies, should make 3 initial requests (meta, login, meta) then 1 with cookies present', ->
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
workflowy.nodes.then ->
assert.equal(workflowy._requests,3)
workflowy = new Workflowy username, password, jar: fc
workflowy.nodes.then ->
assert.equal(workflowy._requests, 1)
describe.skip '#update', ->
it 'should reflect an empty tree after deleting all top level nodes', ->
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
workflowy.nodes.then ->
workflowy.find().then (nodes) ->
workflowy.delete(nodes).then ->
workflowy.nodes.then (nodes) ->
assert.equal(nodes.length, 0)
assert(workflowy._requests, 7)
describe '#addChildren', ->
it 'should add child nodes where expected in the tree', ->
this.timeout(60000)
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
addChildrenTest workflowy
# describe.skip 'with a shareId in constructor', ->
# shareIdTests false
# describe.skip '#quarantine', ->
# shareIdTests true
describe 'Workflowy with proxy', ->
beforeEach ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate initialList
describe '#find', ->
it 'should reflect an initialized tree with empty search', ->
workflowy.find().then (nodes) -> assert.equal(nodes.length, 10)
it 'should find nodes that match a string', ->
workflowy.find('another').then (nodes) ->
assert.equal(nodes.length, 2)
assert.equal(nodes[0].nm, 'and another')
assert.equal(nodes[1].nm, 'or another')
it 'should find nodes that are complete', ->
workflowy.find(null, true).then (nodes) ->
assert.equal(nodes.length, 3)
assert.equal(nodes[0].nm, 'baz')
assert.equal(nodes[1].nm, 'boo')
assert.equal(nodes[2].nm, 'top complete')
it 'should find nodes that are not complete', ->
workflowy.find(null, false).then (nodes) ->
assert.equal(nodes.length, 7)
assert.equal(nodes[0].nm, 'foo')
assert.equal(nodes[1].nm, '<b>bold</b> #today')
assert.equal(nodes[2].nm, 'and another')
assert.equal(nodes[3].nm, 'or another')
assert.equal(nodes[4].nm, 'a final entry')
assert.equal(nodes[5].nm, 'bar')
assert.equal(nodes[6].nm, 'not complete')
describe '#update', ->
it 'should allow passing an object mapping node id to new name', ->
id = null
workflowy.find('and another').then (nodes) ->
id = nodes[0].id
map = {}; map[id] = "a new name"
workflowy.update(nodes[0], map).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- a new name
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
describe '#complete', ->
it 'should mark as complete the passed nodes', ->
workflowy.find('another').then (nodes) ->
workflowy.complete(nodes).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- [COMPLETE] and another
- [COMPLETE] or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
it 'should mark as not complete the passed nodes', ->
workflowy.find('top', true).then (nodes) ->
workflowy.complete(nodes, false).then ->
workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- top complete
- not complete
"""
describe '#bold', ->
it 'should make nodes not previously bold, bold', ->
workflowy.find('top').then (nodes) ->
workflowy.bold(nodes).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] <b>top complete</b>
- not complete
"""
describe '#delete', ->
it 'should only delete the selected nodes, including children', ->
workflowy.find('#today').then (nodes) ->
workflowy.delete(nodes)
.then -> workflowyMatchesOutline """
- foo
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
describe '#asText', ->
it 'should return the same outline given', ->
workflowy.asText().then (text) ->
assert.equal text, initialList
it 'should make expected modifications', ->
workflowy.find('',true)
.then (nodes) -> workflowy.delete(nodes)
.then -> workflowy.asText()
.then (text) -> assert.equal text, """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
"""
it 'should return the same outline when there are notes', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate newText = '''
- parent
| parent note
| parent line 2
- child
| child note 1
| child note 2
| child 3
- grandchild 1
- grandchild 2
'''
workflowyWithNote.asText().then (text) ->
assert.equal text, newText
describe '#populate', ->
it 'should handle the description field (notes)', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- top item
| here's a note associated with the item
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 1
node = nodes[0]
assert.equal !!node.cp, false
assert.equal node.nm, 'top item'
assert.equal node.no, '''here's a note associated with the item'''
it 'should handle multi-line notes and lines with spaces', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- top item
| here's a note associated with the item
| here's a second line on the same note
| a third line that's indented
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 1
node = nodes[0]
assert.equal !!node.cp, false
assert.equal node.nm, 'top item'
assert.equal node.no, '''here's a note associated with the item\nhere's a second line on the same note\n a third line that's indented'''
it 'should handle notes on child nodes', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- parent
| parent note
| parent line 2
- child
| child note 1
| child note 2
| child 3
- grandchild 1
- grandchild 2
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 4
parent = nodes[0]
child = nodes[1]
grandchild1 = nodes[2]
grandchild2 = nodes[3]
assert.equal child.parentId, parent.id
assert.equal grandchild1.parentId, child.id
assert.equal grandchild2.parentId, child.id
assert.equal parent.ch.length, 1
assert.equal parent.ch[0], child
assert.equal child.ch.length, 2
assert.equal child.ch[0], grandchild1
assert.equal child.ch[1], grandchild2
assert.equal parent.nm, 'parent'
assert.equal child.nm, 'child'
assert.equal grandchild1.nm, 'grandchild 1'
assert.equal grandchild2.nm, 'grandchild 2'
assert.equal parent.no, 'parent note\nparent line 2'
assert.equal child.no, 'child note 1\n child note 2\nchild 3'
assert.equal !!grandchild1.no, false
assert.equal !!grandchild2.no, false
describe '#addChildren', ->
it 'should add child nodes where expected in the tree', ->
addChildrenTest workflowy
describe 'Workflowy utils', ->
describe '#addTag', ->
it 'should add a tag if it does not exist', ->
name = 'foo bar'
assert.equal(utils.addTag(name, 'today'), name + ' #today')
name = 'foo bar #todays'
assert.equal(utils.addTag(name, 'today'), name + ' #today')
it 'should not add a tag if it does exist', ->
name = '#today foo bar'
assert.equal(utils.addTag(name, 'today'), name)
name = 'foo bar #today'
assert.equal(utils.addTag(name, 'today'), name)
it 'should insert the tag within bold', ->
name = '<b>foo bar</b>'
assert.equal(utils.addTag(name, 'today'), '<b>foo bar #today</b>')
describe '#removeTag', ->
it 'should remove a tag if it exists', ->
name = 'foo #today bar'
assert.equal(utils.removeTag(name, 'today'), 'foo bar')
it 'should do nothing if the tag does not exist', ->
name = 'foo #todays bar'
assert.equal(utils.removeTag(name, 'today'), name)
it 'should remove spacing before and after as appropriate', ->
name = 'foo #today bar'
assert.equal(utils.removeTag(name, 'today'), 'foo bar')
name = '#today bar'
assert.equal(utils.removeTag(name, 'today'), 'bar')
name = 'bar #today'
assert.equal(utils.removeTag(name, 'today'), 'bar')
name = '#today #week this was for this week'
assert.equal(utils.removeTag(name, 'today'), '#week this was for this week')
it 'should remove tags with metadata, stopping at the end of the data', ->
name = '#today #weekly/1/2 this was for this week'
assert.equal(utils.removeTag(name, 'weekly'), '#today this was for this week')
name = '#today #thursday/1p. this was for this week'
assert.equal(utils.removeTag(name, 'thursday'), '#today. this was for this week')
name = '#today #thursday/1p/2.5h. this was for this week'
assert.equal(utils.removeTag(name, 'thursday'), '#today. this was for this week')
name = 'hello world #today #thursday/1p/2.5h'
assert.equal(utils.removeTag(name, 'thursday'), 'hello world #today')
name = 'hello world #today #thursday/1p/2.5h.'
assert.equal(utils.removeTag(name, 'thursday'), 'hello world #today.')
describe '#addContext', ->
it 'should add a context if it does not exist', ->
name = 'foo bar'
assert.equal(utils.addContext(name, 'home'), name + ' @home')
name = 'foo bar @homes'
assert.equal(utils.addContext(name, 'home'), name + ' @home')
it 'should not add a context if it does exist', ->
name = '@home foo bar'
assert.equal(utils.addContext(name, 'home'), name)
name = 'foo bar @home'
assert.equal(utils.addContext(name, 'home'), name)
it 'should insert the context within bold', ->
name = '<b>foo bar</b>'
assert.equal(utils.addContext(name, 'home'), '<b>foo bar @home</b>')
describe '#removeContext', ->
it 'should remove a context if it exists', ->
name = 'foo @home bar'
assert.equal(utils.removeContext(name, 'home'), 'foo bar')
it 'should do nothing if the context does not exist', ->
name = 'foo @homes bar'
assert.equal(utils.removeContext(name, 'home'), name)
it 'should remove spacing before and after as appropriate', ->
name = 'foo @home bar'
assert.equal(utils.removeContext(name, 'home'), 'foo bar')
name = '@home bar'
assert.equal(utils.removeContext(name, 'home'), 'bar')
name = 'bar @home'
assert.equal(utils.removeContext(name, 'home'), 'bar')
name = '@home #week this was for this week'
assert.equal(utils.removeContext(name, 'home'), '#week this was for this week')
it 'should remove context with metadata', ->
name = '@home #week this was for this week @rating/1.5'
assert.equal(utils.removeContext(name, 'rating'), '@home #week this was for this week')
name = '@home #week this was for this week @rating/1.5 and more'
assert.equal(utils.removeContext(name, 'rating'), '@home #week this was for this week and more')
describe '#getContexts', ->
it 'should return an array of all the contexts', ->
arr = utils.getContexts "foo @bar @baz hello @world: yay @mundo"
assert.equal(arr.length, 3)
assert('bar' in arr)
assert('baz' in arr)
assert('mundo' in arr)
describe '#inheritContexts', ->
it 'should inherit all the (regular) contexts from ancestors', ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate """
- hello @bar
- another @baz:
- and a final hello
"""
workflowy.find().then (nodes) ->
assert.equal utils.inheritContexts(nodes[2].nm, nodes[2]), "and a final hello @bar"
describe '#getBubbledContexts', ->
it 'should return an array of all the bubbled contexts', ->
arr = utils.getBubbledContexts "foo @bar @baz hello @world: yay @mundo"
assert.equal(arr.length, 1)
assert('world' in arr)
describe '#bubbleUpContexts', ->
it 'should bubble not present contexts and remove unnecessary bubbles', ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate """
- hello @bar @bazoo:
- another @baz:
- and a final hello @baz @hello
"""
workflowy.find().then (nodes) ->
assert.equal utils.bubbleUpContexts(nodes[0].nm, nodes[0]), "hello @bar @baz: @hello:"
| 41268 | assert = require 'assert'
fs = require 'fs'
Q = require 'q'
path = require 'path'
Workflowy = require '../'
FileCookieStore = require 'tough-cookie-filestore'
proxy = require '../lib/proxy'
utils = require '../lib/utils'
username = '<EMAIL>'
password = '<PASSWORD>'
cookiesPath = path.join(__filename, '../cookies.json')
initialList = """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
fc = null
workflowy = null
workflowyMatchesOutline = (inst, outline) ->
[outline, inst] = [inst, workflowy] if arguments.length <2
inst.find().then (nodes) ->
# find the root nodes in the flat list
nodes = nodes.filter (node) -> node.parentId is 'None'
assert.equal(utils.treeToOutline(nodes),outline)
addChildrenTest = (workflowy) ->
workflowy.addChildren [{name: 'first'}, {name: 'second'}]
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'second')
workflowy.addChildren [{name: 'underFirst1'}, {name: 'underFirst2'}], nodes[0]
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'underFirst1')
assert.equal(nodes[2].nm, 'underFirst2')
assert.equal(nodes[3].nm, 'second')
assert.equal(nodes[1].parentId, nodes[0].id)
assert.equal(nodes[2].parentId, nodes[0].id)
workflowy.addChildren [{name: 'between underFirst1 and underFirst2 a'}, {name: 'between underFirst1 and underFirst2 b'}], nodes[0], 1
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'underFirst1')
assert.equal(nodes[2].nm, 'between underFirst1 and underFirst2 a')
assert.equal(nodes[3].nm, 'between underFirst1 and underFirst2 b')
assert.equal(nodes[4].nm, 'underFirst2')
assert.equal(nodes[5].nm, 'second')
assert.equal(nodes[0].parentId, 'None')
assert.equal(nodes[1].parentId, nodes[0].id)
assert.equal(nodes[2].parentId, nodes[0].id)
assert.equal(nodes[3].parentId, nodes[0].id)
assert.equal(nodes[4].parentId, nodes[0].id)
assert.equal(nodes[5].parentId, 'None')
.then ->
root = "foo #{Date.now()}"
rootNode = null
workflowy.addChildren name: root
.then -> workflowy.find()
.then (nodes) ->
rootNode = nodes[0]
assert.equal(nodes[0].nm,root)
workflowy.addChildren [{name: '1'},{name: '3'},{name:'5'}], nodes[0]
.then -> workflowy.find( (node) -> node.id is rootNode.id )
.then (nodes) -> rootNode = nodes[0]
.then -> workflowy.asText(rootNode)
.then (text) ->
assert.equal text, """
- #{root}
- 1
- 3
- 5
"""
workflowy.addChildren [{name: '2'},{name: '4'}], rootNode, [1,2]
.then -> workflowy.find( (node) -> node.id is rootNode.id )
.then (nodes) -> rootNode = nodes[0]
.then -> workflowy.asText(rootNode)
.then (text) ->
assert.equal text, """
- #{root}
- 1
- 2
- 3
- 4
- 5
"""
# add at the botom of the doc with a high priority
.then ->
names = [1..10].map (num) -> ''+num
workflowy.addChildren names.map (name) -> {name}
.then -> workflowy.find()
.then (nodes) ->
# first 10 nodes should have the given names
for name,i in names
assert.equal(nodes[i].nm, names[i])
# now add a node with a crazy priority
workflowy.addChildren({name: 'at the bottom'},null, 1e6)
.then -> workflowy.find()
.then (nodes) ->
# first 10 nodes should still have the given names
for name,i in names
assert.equal(nodes[i].nm, names[i])
# last node is known
assert.equal(nodes[nodes.length-1].nm, 'at the bottom')
shareIdTests = (useQuarantine) ->
rootName = "Book list"
throw new Error "env var WORKFLOWY_SHAREID is required to test quarantine and share id" unless shareId = process.env.WORKFLOWY_SHAREID
fcSub = new FileCookieStore('cookies.json')
workflowySub = null
beforeEach ->
# clean up all the nodes under the book list
workflowy = new Workflowy username, password, jar: fc
if useQuarantine
workflowySub = workflowy.quarantine shareId
workflowy.find(rootName)
.then (nodes) ->
assert.equal nodes.length, 1
if (children = nodes[0].ch)?.length
workflowy.delete(children)
.then ->
unless useQuarantine
workflowySub = new Workflowy username, password, jar: fcSub, shareId: shareId
else
unless useQuarantine
workflowySub = new Workflowy username, password, jar: fcSub, shareId: shareId
describe '#find', ->
it 'should return only nodes under the given Id', ->
workflowySub.refresh()
workflowyMatchesOutline workflowySub, ""
describe '#addChildren shareId', ->
it 'should add children under the expected root node', ->
newRootNode = "top level child #{Date.now()}"
newShareNode = "share #{Date.now()}"
Q.all([
workflowy.addChildren name: newRootNode
workflowySub.addChildren name: newShareNode
]).then ->
workflowyMatchesOutline workflowySub, "- #{newShareNode}"
.then ->
workflowy.find().then (nodes) ->
assert.equal nodes[0].nm, newRootNode
describe.skip 'Workflowy over the wire', ->
username = process.env.WORKFLOWY_USERNAME
password = process.env.WORKFLOWY_PASSWORD
beforeEach ->
(console.error "Workflowy username and password must be provided through environmental variables."; process.exit 1) unless username and password
Q.ninvoke fs, 'unlink', cookiesPath
.then Q, Q
.then ->
fc = new FileCookieStore('cookies.json')
describe.skip '#constructor', ->
it 'with empty cookies, should make 3 initial requests (meta, login, meta) then 1 with cookies present', ->
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
workflowy.nodes.then ->
assert.equal(workflowy._requests,3)
workflowy = new Workflowy username, password, jar: fc
workflowy.nodes.then ->
assert.equal(workflowy._requests, 1)
describe.skip '#update', ->
it 'should reflect an empty tree after deleting all top level nodes', ->
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
workflowy.nodes.then ->
workflowy.find().then (nodes) ->
workflowy.delete(nodes).then ->
workflowy.nodes.then (nodes) ->
assert.equal(nodes.length, 0)
assert(workflowy._requests, 7)
describe '#addChildren', ->
it 'should add child nodes where expected in the tree', ->
this.timeout(60000)
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
addChildrenTest workflowy
# describe.skip 'with a shareId in constructor', ->
# shareIdTests false
# describe.skip '#quarantine', ->
# shareIdTests true
describe 'Workflowy with proxy', ->
beforeEach ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate initialList
describe '#find', ->
it 'should reflect an initialized tree with empty search', ->
workflowy.find().then (nodes) -> assert.equal(nodes.length, 10)
it 'should find nodes that match a string', ->
workflowy.find('another').then (nodes) ->
assert.equal(nodes.length, 2)
assert.equal(nodes[0].nm, 'and another')
assert.equal(nodes[1].nm, 'or another')
it 'should find nodes that are complete', ->
workflowy.find(null, true).then (nodes) ->
assert.equal(nodes.length, 3)
assert.equal(nodes[0].nm, 'baz')
assert.equal(nodes[1].nm, 'boo')
assert.equal(nodes[2].nm, 'top complete')
it 'should find nodes that are not complete', ->
workflowy.find(null, false).then (nodes) ->
assert.equal(nodes.length, 7)
assert.equal(nodes[0].nm, 'foo')
assert.equal(nodes[1].nm, '<b>bold</b> #today')
assert.equal(nodes[2].nm, 'and another')
assert.equal(nodes[3].nm, 'or another')
assert.equal(nodes[4].nm, 'a final entry')
assert.equal(nodes[5].nm, 'bar')
assert.equal(nodes[6].nm, 'not complete')
describe '#update', ->
it 'should allow passing an object mapping node id to new name', ->
id = null
workflowy.find('and another').then (nodes) ->
id = nodes[0].id
map = {}; map[id] = "a new name"
workflowy.update(nodes[0], map).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- a new name
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
describe '#complete', ->
it 'should mark as complete the passed nodes', ->
workflowy.find('another').then (nodes) ->
workflowy.complete(nodes).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- [COMPLETE] and another
- [COMPLETE] or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
it 'should mark as not complete the passed nodes', ->
workflowy.find('top', true).then (nodes) ->
workflowy.complete(nodes, false).then ->
workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- top complete
- not complete
"""
describe '#bold', ->
it 'should make nodes not previously bold, bold', ->
workflowy.find('top').then (nodes) ->
workflowy.bold(nodes).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] <b>top complete</b>
- not complete
"""
describe '#delete', ->
it 'should only delete the selected nodes, including children', ->
workflowy.find('#today').then (nodes) ->
workflowy.delete(nodes)
.then -> workflowyMatchesOutline """
- foo
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
describe '#asText', ->
it 'should return the same outline given', ->
workflowy.asText().then (text) ->
assert.equal text, initialList
it 'should make expected modifications', ->
workflowy.find('',true)
.then (nodes) -> workflowy.delete(nodes)
.then -> workflowy.asText()
.then (text) -> assert.equal text, """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
"""
it 'should return the same outline when there are notes', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate newText = '''
- parent
| parent note
| parent line 2
- child
| child note 1
| child note 2
| child 3
- grandchild 1
- grandchild 2
'''
workflowyWithNote.asText().then (text) ->
assert.equal text, newText
describe '#populate', ->
it 'should handle the description field (notes)', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- top item
| here's a note associated with the item
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 1
node = nodes[0]
assert.equal !!node.cp, false
assert.equal node.nm, 'top item'
assert.equal node.no, '''here's a note associated with the item'''
it 'should handle multi-line notes and lines with spaces', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- top item
| here's a note associated with the item
| here's a second line on the same note
| a third line that's indented
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 1
node = nodes[0]
assert.equal !!node.cp, false
assert.equal node.nm, 'top item'
assert.equal node.no, '''here's a note associated with the item\nhere's a second line on the same note\n a third line that's indented'''
it 'should handle notes on child nodes', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- parent
| parent note
| parent line 2
- child
| child note 1
| child note 2
| child 3
- grandchild 1
- grandchild 2
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 4
parent = nodes[0]
child = nodes[1]
grandchild1 = nodes[2]
grandchild2 = nodes[3]
assert.equal child.parentId, parent.id
assert.equal grandchild1.parentId, child.id
assert.equal grandchild2.parentId, child.id
assert.equal parent.ch.length, 1
assert.equal parent.ch[0], child
assert.equal child.ch.length, 2
assert.equal child.ch[0], grandchild1
assert.equal child.ch[1], grandchild2
assert.equal parent.nm, 'parent'
assert.equal child.nm, 'child'
assert.equal grandchild1.nm, 'grandchild 1'
assert.equal grandchild2.nm, 'grandchild 2'
assert.equal parent.no, 'parent note\nparent line 2'
assert.equal child.no, 'child note 1\n child note 2\nchild 3'
assert.equal !!grandchild1.no, false
assert.equal !!grandchild2.no, false
describe '#addChildren', ->
it 'should add child nodes where expected in the tree', ->
addChildrenTest workflowy
describe 'Workflowy utils', ->
describe '#addTag', ->
it 'should add a tag if it does not exist', ->
name = '<NAME>'
assert.equal(utils.addTag(name, 'today'), name + ' #today')
name = 'foo bar #todays'
assert.equal(utils.addTag(name, 'today'), name + ' #today')
it 'should not add a tag if it does exist', ->
name = '#today foo bar'
assert.equal(utils.addTag(name, 'today'), name)
name = 'foo bar #today'
assert.equal(utils.addTag(name, 'today'), name)
it 'should insert the tag within bold', ->
name = '<b>foo bar</b>'
assert.equal(utils.addTag(name, 'today'), '<b>foo bar #today</b>')
describe '#removeTag', ->
it 'should remove a tag if it exists', ->
name = 'foo #today bar'
assert.equal(utils.removeTag(name, 'today'), 'foo bar')
it 'should do nothing if the tag does not exist', ->
name = 'foo #todays bar'
assert.equal(utils.removeTag(name, 'today'), name)
it 'should remove spacing before and after as appropriate', ->
name = 'foo #today bar'
assert.equal(utils.removeTag(name, 'today'), 'foo bar')
name = '#today bar'
assert.equal(utils.removeTag(name, 'today'), 'bar')
name = 'bar #today'
assert.equal(utils.removeTag(name, 'today'), 'bar')
name = '#today #week this was for this week'
assert.equal(utils.removeTag(name, 'today'), '#week this was for this week')
it 'should remove tags with metadata, stopping at the end of the data', ->
name = '#today #weekly/1/2 this was for this week'
assert.equal(utils.removeTag(name, 'weekly'), '#today this was for this week')
name = '#today #thursday/1p. this was for this week'
assert.equal(utils.removeTag(name, 'thursday'), '#today. this was for this week')
name = '#today #thursday/1p/2.5h. this was for this week'
assert.equal(utils.removeTag(name, 'thursday'), '#today. this was for this week')
name = 'hello world #today #thursday/1p/2.5h'
assert.equal(utils.removeTag(name, 'thursday'), 'hello world #today')
name = 'hello world #today #thursday/1p/2.5h.'
assert.equal(utils.removeTag(name, 'thursday'), 'hello world #today.')
describe '#addContext', ->
it 'should add a context if it does not exist', ->
name = 'foo bar'
assert.equal(utils.addContext(name, 'home'), name + ' @home')
name = 'foo bar @homes'
assert.equal(utils.addContext(name, 'home'), name + ' @home')
it 'should not add a context if it does exist', ->
name = '@home foo bar'
assert.equal(utils.addContext(name, 'home'), name)
name = 'foo bar @home'
assert.equal(utils.addContext(name, 'home'), name)
it 'should insert the context within bold', ->
name = '<b>foo bar</b>'
assert.equal(utils.addContext(name, 'home'), '<b>foo bar @home</b>')
describe '#removeContext', ->
it 'should remove a context if it exists', ->
name = 'foo @home bar'
assert.equal(utils.removeContext(name, 'home'), 'foo bar')
it 'should do nothing if the context does not exist', ->
name = 'foo @homes bar'
assert.equal(utils.removeContext(name, 'home'), name)
it 'should remove spacing before and after as appropriate', ->
name = 'foo @home bar'
assert.equal(utils.removeContext(name, 'home'), 'foo bar')
name = '@home bar'
assert.equal(utils.removeContext(name, 'home'), 'bar')
name = 'bar @home'
assert.equal(utils.removeContext(name, 'home'), 'bar')
name = '@home #week this was for this week'
assert.equal(utils.removeContext(name, 'home'), '#week this was for this week')
it 'should remove context with metadata', ->
name = '@home #week this was for this week @rating/1.5'
assert.equal(utils.removeContext(name, 'rating'), '@home #week this was for this week')
name = '@home #week this was for this week @rating/1.5 and more'
assert.equal(utils.removeContext(name, 'rating'), '@home #week this was for this week and more')
describe '#getContexts', ->
it 'should return an array of all the contexts', ->
arr = utils.getContexts "foo @bar @baz hello @world: yay @mundo"
assert.equal(arr.length, 3)
assert('bar' in arr)
assert('baz' in arr)
assert('mundo' in arr)
describe '#inheritContexts', ->
it 'should inherit all the (regular) contexts from ancestors', ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate """
- hello @bar
- another @baz:
- and a final hello
"""
workflowy.find().then (nodes) ->
assert.equal utils.inheritContexts(nodes[2].nm, nodes[2]), "and a final hello @bar"
describe '#getBubbledContexts', ->
it 'should return an array of all the bubbled contexts', ->
arr = utils.getBubbledContexts "foo @bar @baz hello @world: yay @mundo"
assert.equal(arr.length, 1)
assert('world' in arr)
describe '#bubbleUpContexts', ->
it 'should bubble not present contexts and remove unnecessary bubbles', ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate """
- hello @bar @bazoo:
- another @baz:
- and a final hello @baz @hello
"""
workflowy.find().then (nodes) ->
assert.equal utils.bubbleUpContexts(nodes[0].nm, nodes[0]), "hello @bar @baz: @hello:"
| true | assert = require 'assert'
fs = require 'fs'
Q = require 'q'
path = require 'path'
Workflowy = require '../'
FileCookieStore = require 'tough-cookie-filestore'
proxy = require '../lib/proxy'
utils = require '../lib/utils'
username = 'PI:EMAIL:<EMAIL>END_PI'
password = 'PI:PASSWORD:<PASSWORD>END_PI'
cookiesPath = path.join(__filename, '../cookies.json')
initialList = """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
fc = null
workflowy = null
workflowyMatchesOutline = (inst, outline) ->
[outline, inst] = [inst, workflowy] if arguments.length <2
inst.find().then (nodes) ->
# find the root nodes in the flat list
nodes = nodes.filter (node) -> node.parentId is 'None'
assert.equal(utils.treeToOutline(nodes),outline)
addChildrenTest = (workflowy) ->
workflowy.addChildren [{name: 'first'}, {name: 'second'}]
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'second')
workflowy.addChildren [{name: 'underFirst1'}, {name: 'underFirst2'}], nodes[0]
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'underFirst1')
assert.equal(nodes[2].nm, 'underFirst2')
assert.equal(nodes[3].nm, 'second')
assert.equal(nodes[1].parentId, nodes[0].id)
assert.equal(nodes[2].parentId, nodes[0].id)
workflowy.addChildren [{name: 'between underFirst1 and underFirst2 a'}, {name: 'between underFirst1 and underFirst2 b'}], nodes[0], 1
.then ->
workflowy.find().then (nodes) ->
assert.equal(nodes[0].nm, 'first')
assert.equal(nodes[1].nm, 'underFirst1')
assert.equal(nodes[2].nm, 'between underFirst1 and underFirst2 a')
assert.equal(nodes[3].nm, 'between underFirst1 and underFirst2 b')
assert.equal(nodes[4].nm, 'underFirst2')
assert.equal(nodes[5].nm, 'second')
assert.equal(nodes[0].parentId, 'None')
assert.equal(nodes[1].parentId, nodes[0].id)
assert.equal(nodes[2].parentId, nodes[0].id)
assert.equal(nodes[3].parentId, nodes[0].id)
assert.equal(nodes[4].parentId, nodes[0].id)
assert.equal(nodes[5].parentId, 'None')
.then ->
root = "foo #{Date.now()}"
rootNode = null
workflowy.addChildren name: root
.then -> workflowy.find()
.then (nodes) ->
rootNode = nodes[0]
assert.equal(nodes[0].nm,root)
workflowy.addChildren [{name: '1'},{name: '3'},{name:'5'}], nodes[0]
.then -> workflowy.find( (node) -> node.id is rootNode.id )
.then (nodes) -> rootNode = nodes[0]
.then -> workflowy.asText(rootNode)
.then (text) ->
assert.equal text, """
- #{root}
- 1
- 3
- 5
"""
workflowy.addChildren [{name: '2'},{name: '4'}], rootNode, [1,2]
.then -> workflowy.find( (node) -> node.id is rootNode.id )
.then (nodes) -> rootNode = nodes[0]
.then -> workflowy.asText(rootNode)
.then (text) ->
assert.equal text, """
- #{root}
- 1
- 2
- 3
- 4
- 5
"""
# add at the botom of the doc with a high priority
.then ->
names = [1..10].map (num) -> ''+num
workflowy.addChildren names.map (name) -> {name}
.then -> workflowy.find()
.then (nodes) ->
# first 10 nodes should have the given names
for name,i in names
assert.equal(nodes[i].nm, names[i])
# now add a node with a crazy priority
workflowy.addChildren({name: 'at the bottom'},null, 1e6)
.then -> workflowy.find()
.then (nodes) ->
# first 10 nodes should still have the given names
for name,i in names
assert.equal(nodes[i].nm, names[i])
# last node is known
assert.equal(nodes[nodes.length-1].nm, 'at the bottom')
shareIdTests = (useQuarantine) ->
rootName = "Book list"
throw new Error "env var WORKFLOWY_SHAREID is required to test quarantine and share id" unless shareId = process.env.WORKFLOWY_SHAREID
fcSub = new FileCookieStore('cookies.json')
workflowySub = null
beforeEach ->
# clean up all the nodes under the book list
workflowy = new Workflowy username, password, jar: fc
if useQuarantine
workflowySub = workflowy.quarantine shareId
workflowy.find(rootName)
.then (nodes) ->
assert.equal nodes.length, 1
if (children = nodes[0].ch)?.length
workflowy.delete(children)
.then ->
unless useQuarantine
workflowySub = new Workflowy username, password, jar: fcSub, shareId: shareId
else
unless useQuarantine
workflowySub = new Workflowy username, password, jar: fcSub, shareId: shareId
describe '#find', ->
it 'should return only nodes under the given Id', ->
workflowySub.refresh()
workflowyMatchesOutline workflowySub, ""
describe '#addChildren shareId', ->
it 'should add children under the expected root node', ->
newRootNode = "top level child #{Date.now()}"
newShareNode = "share #{Date.now()}"
Q.all([
workflowy.addChildren name: newRootNode
workflowySub.addChildren name: newShareNode
]).then ->
workflowyMatchesOutline workflowySub, "- #{newShareNode}"
.then ->
workflowy.find().then (nodes) ->
assert.equal nodes[0].nm, newRootNode
describe.skip 'Workflowy over the wire', ->
username = process.env.WORKFLOWY_USERNAME
password = process.env.WORKFLOWY_PASSWORD
beforeEach ->
(console.error "Workflowy username and password must be provided through environmental variables."; process.exit 1) unless username and password
Q.ninvoke fs, 'unlink', cookiesPath
.then Q, Q
.then ->
fc = new FileCookieStore('cookies.json')
describe.skip '#constructor', ->
it 'with empty cookies, should make 3 initial requests (meta, login, meta) then 1 with cookies present', ->
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
workflowy.nodes.then ->
assert.equal(workflowy._requests,3)
workflowy = new Workflowy username, password, jar: fc
workflowy.nodes.then ->
assert.equal(workflowy._requests, 1)
describe.skip '#update', ->
it 'should reflect an empty tree after deleting all top level nodes', ->
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
workflowy.nodes.then ->
workflowy.find().then (nodes) ->
workflowy.delete(nodes).then ->
workflowy.nodes.then (nodes) ->
assert.equal(nodes.length, 0)
assert(workflowy._requests, 7)
describe '#addChildren', ->
it 'should add child nodes where expected in the tree', ->
this.timeout(60000)
workflowy = new Workflowy username, password, jar: fc
workflowy.refresh()
addChildrenTest workflowy
# describe.skip 'with a shareId in constructor', ->
# shareIdTests false
# describe.skip '#quarantine', ->
# shareIdTests true
describe 'Workflowy with proxy', ->
beforeEach ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate initialList
describe '#find', ->
it 'should reflect an initialized tree with empty search', ->
workflowy.find().then (nodes) -> assert.equal(nodes.length, 10)
it 'should find nodes that match a string', ->
workflowy.find('another').then (nodes) ->
assert.equal(nodes.length, 2)
assert.equal(nodes[0].nm, 'and another')
assert.equal(nodes[1].nm, 'or another')
it 'should find nodes that are complete', ->
workflowy.find(null, true).then (nodes) ->
assert.equal(nodes.length, 3)
assert.equal(nodes[0].nm, 'baz')
assert.equal(nodes[1].nm, 'boo')
assert.equal(nodes[2].nm, 'top complete')
it 'should find nodes that are not complete', ->
workflowy.find(null, false).then (nodes) ->
assert.equal(nodes.length, 7)
assert.equal(nodes[0].nm, 'foo')
assert.equal(nodes[1].nm, '<b>bold</b> #today')
assert.equal(nodes[2].nm, 'and another')
assert.equal(nodes[3].nm, 'or another')
assert.equal(nodes[4].nm, 'a final entry')
assert.equal(nodes[5].nm, 'bar')
assert.equal(nodes[6].nm, 'not complete')
describe '#update', ->
it 'should allow passing an object mapping node id to new name', ->
id = null
workflowy.find('and another').then (nodes) ->
id = nodes[0].id
map = {}; map[id] = "a new name"
workflowy.update(nodes[0], map).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- a new name
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
describe '#complete', ->
it 'should mark as complete the passed nodes', ->
workflowy.find('another').then (nodes) ->
workflowy.complete(nodes).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- [COMPLETE] and another
- [COMPLETE] or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
it 'should mark as not complete the passed nodes', ->
workflowy.find('top', true).then (nodes) ->
workflowy.complete(nodes, false).then ->
workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- top complete
- not complete
"""
describe '#bold', ->
it 'should make nodes not previously bold, bold', ->
workflowy.find('top').then (nodes) ->
workflowy.bold(nodes).then -> workflowyMatchesOutline """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] <b>top complete</b>
- not complete
"""
describe '#delete', ->
it 'should only delete the selected nodes, including children', ->
workflowy.find('#today').then (nodes) ->
workflowy.delete(nodes)
.then -> workflowyMatchesOutline """
- foo
- bar
- [COMPLETE] baz
- [COMPLETE] boo
- [COMPLETE] top complete
- not complete
"""
describe '#asText', ->
it 'should return the same outline given', ->
workflowy.asText().then (text) ->
assert.equal text, initialList
it 'should make expected modifications', ->
workflowy.find('',true)
.then (nodes) -> workflowy.delete(nodes)
.then -> workflowy.asText()
.then (text) -> assert.equal text, """
- foo
- <b>bold</b> #today
- and another
- or another
- a final entry
- bar
"""
it 'should return the same outline when there are notes', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate newText = '''
- parent
| parent note
| parent line 2
- child
| child note 1
| child note 2
| child 3
- grandchild 1
- grandchild 2
'''
workflowyWithNote.asText().then (text) ->
assert.equal text, newText
describe '#populate', ->
it 'should handle the description field (notes)', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- top item
| here's a note associated with the item
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 1
node = nodes[0]
assert.equal !!node.cp, false
assert.equal node.nm, 'top item'
assert.equal node.no, '''here's a note associated with the item'''
it 'should handle multi-line notes and lines with spaces', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- top item
| here's a note associated with the item
| here's a second line on the same note
| a third line that's indented
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 1
node = nodes[0]
assert.equal !!node.cp, false
assert.equal node.nm, 'top item'
assert.equal node.no, '''here's a note associated with the item\nhere's a second line on the same note\n a third line that's indented'''
it 'should handle notes on child nodes', ->
workflowyWithNote = proxy new Workflowy username, password
workflowyWithNote.request.populate '''
- parent
| parent note
| parent line 2
- child
| child note 1
| child note 2
| child 3
- grandchild 1
- grandchild 2
'''
workflowyWithNote.find()
.then (nodes) ->
assert.equal nodes.length, 4
parent = nodes[0]
child = nodes[1]
grandchild1 = nodes[2]
grandchild2 = nodes[3]
assert.equal child.parentId, parent.id
assert.equal grandchild1.parentId, child.id
assert.equal grandchild2.parentId, child.id
assert.equal parent.ch.length, 1
assert.equal parent.ch[0], child
assert.equal child.ch.length, 2
assert.equal child.ch[0], grandchild1
assert.equal child.ch[1], grandchild2
assert.equal parent.nm, 'parent'
assert.equal child.nm, 'child'
assert.equal grandchild1.nm, 'grandchild 1'
assert.equal grandchild2.nm, 'grandchild 2'
assert.equal parent.no, 'parent note\nparent line 2'
assert.equal child.no, 'child note 1\n child note 2\nchild 3'
assert.equal !!grandchild1.no, false
assert.equal !!grandchild2.no, false
describe '#addChildren', ->
it 'should add child nodes where expected in the tree', ->
addChildrenTest workflowy
describe 'Workflowy utils', ->
describe '#addTag', ->
it 'should add a tag if it does not exist', ->
name = 'PI:NAME:<NAME>END_PI'
assert.equal(utils.addTag(name, 'today'), name + ' #today')
name = 'foo bar #todays'
assert.equal(utils.addTag(name, 'today'), name + ' #today')
it 'should not add a tag if it does exist', ->
name = '#today foo bar'
assert.equal(utils.addTag(name, 'today'), name)
name = 'foo bar #today'
assert.equal(utils.addTag(name, 'today'), name)
it 'should insert the tag within bold', ->
name = '<b>foo bar</b>'
assert.equal(utils.addTag(name, 'today'), '<b>foo bar #today</b>')
describe '#removeTag', ->
it 'should remove a tag if it exists', ->
name = 'foo #today bar'
assert.equal(utils.removeTag(name, 'today'), 'foo bar')
it 'should do nothing if the tag does not exist', ->
name = 'foo #todays bar'
assert.equal(utils.removeTag(name, 'today'), name)
it 'should remove spacing before and after as appropriate', ->
name = 'foo #today bar'
assert.equal(utils.removeTag(name, 'today'), 'foo bar')
name = '#today bar'
assert.equal(utils.removeTag(name, 'today'), 'bar')
name = 'bar #today'
assert.equal(utils.removeTag(name, 'today'), 'bar')
name = '#today #week this was for this week'
assert.equal(utils.removeTag(name, 'today'), '#week this was for this week')
it 'should remove tags with metadata, stopping at the end of the data', ->
name = '#today #weekly/1/2 this was for this week'
assert.equal(utils.removeTag(name, 'weekly'), '#today this was for this week')
name = '#today #thursday/1p. this was for this week'
assert.equal(utils.removeTag(name, 'thursday'), '#today. this was for this week')
name = '#today #thursday/1p/2.5h. this was for this week'
assert.equal(utils.removeTag(name, 'thursday'), '#today. this was for this week')
name = 'hello world #today #thursday/1p/2.5h'
assert.equal(utils.removeTag(name, 'thursday'), 'hello world #today')
name = 'hello world #today #thursday/1p/2.5h.'
assert.equal(utils.removeTag(name, 'thursday'), 'hello world #today.')
describe '#addContext', ->
it 'should add a context if it does not exist', ->
name = 'foo bar'
assert.equal(utils.addContext(name, 'home'), name + ' @home')
name = 'foo bar @homes'
assert.equal(utils.addContext(name, 'home'), name + ' @home')
it 'should not add a context if it does exist', ->
name = '@home foo bar'
assert.equal(utils.addContext(name, 'home'), name)
name = 'foo bar @home'
assert.equal(utils.addContext(name, 'home'), name)
it 'should insert the context within bold', ->
name = '<b>foo bar</b>'
assert.equal(utils.addContext(name, 'home'), '<b>foo bar @home</b>')
describe '#removeContext', ->
it 'should remove a context if it exists', ->
name = 'foo @home bar'
assert.equal(utils.removeContext(name, 'home'), 'foo bar')
it 'should do nothing if the context does not exist', ->
name = 'foo @homes bar'
assert.equal(utils.removeContext(name, 'home'), name)
it 'should remove spacing before and after as appropriate', ->
name = 'foo @home bar'
assert.equal(utils.removeContext(name, 'home'), 'foo bar')
name = '@home bar'
assert.equal(utils.removeContext(name, 'home'), 'bar')
name = 'bar @home'
assert.equal(utils.removeContext(name, 'home'), 'bar')
name = '@home #week this was for this week'
assert.equal(utils.removeContext(name, 'home'), '#week this was for this week')
it 'should remove context with metadata', ->
name = '@home #week this was for this week @rating/1.5'
assert.equal(utils.removeContext(name, 'rating'), '@home #week this was for this week')
name = '@home #week this was for this week @rating/1.5 and more'
assert.equal(utils.removeContext(name, 'rating'), '@home #week this was for this week and more')
describe '#getContexts', ->
it 'should return an array of all the contexts', ->
arr = utils.getContexts "foo @bar @baz hello @world: yay @mundo"
assert.equal(arr.length, 3)
assert('bar' in arr)
assert('baz' in arr)
assert('mundo' in arr)
describe '#inheritContexts', ->
it 'should inherit all the (regular) contexts from ancestors', ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate """
- hello @bar
- another @baz:
- and a final hello
"""
workflowy.find().then (nodes) ->
assert.equal utils.inheritContexts(nodes[2].nm, nodes[2]), "and a final hello @bar"
describe '#getBubbledContexts', ->
it 'should return an array of all the bubbled contexts', ->
arr = utils.getBubbledContexts "foo @bar @baz hello @world: yay @mundo"
assert.equal(arr.length, 1)
assert('world' in arr)
describe '#bubbleUpContexts', ->
it 'should bubble not present contexts and remove unnecessary bubbles', ->
workflowy = proxy new Workflowy username, password
workflowy.request.populate """
- hello @bar @bazoo:
- another @baz:
- and a final hello @baz @hello
"""
workflowy.find().then (nodes) ->
assert.equal utils.bubbleUpContexts(nodes[0].nm, nodes[0]), "hello @bar @baz: @hello:"
|
[
{
"context": "\\___\\___|\n#\n\n# A hand-re-written implementation of Ben Weaver's ReParse, a parser\n# combinator, which in turn w",
"end": 322,
"score": 0.9981521964073181,
"start": 312,
"tag": "NAME",
"value": "Ben Weaver"
},
{
"context": "ARSEC. In many cases, this code is almost exactly Ben's; in some,\n# I've lifted further ideas and comme",
"end": 464,
"score": 0.7046055197715759,
"start": 461,
"tag": "NAME",
"value": "Ben"
}
] | src/reparse.coffee | elfsternberg/reparse-coffeescript | 1 | #; -*- mode: coffee -*-
# ___ ___ ___ __ __
# | _ \___| _ \__ _ _ _ ___ ___ / __|___ / _|/ _|___ ___
# | / -_) _/ _` | '_(_-</ -_) | (__/ _ \ _| _/ -_) -_)
# |_|_\___|_| \__,_|_| /__/\___| \___\___/_| |_| \___\___|
#
# A hand-re-written implementation of Ben Weaver's ReParse, a parser
# combinator, which in turn was heavily influenced by Haskell's
# PARSEC. In many cases, this code is almost exactly Ben's; in some,
# I've lifted further ideas and commentary from the JSParsec project.
exports.ReParse = class ReParse
# Extend from ReParse and set to true if you don't care about
# whitespace.
ignorews: false
# Where the parse phase begins. The correct way to override this
# is to create a child method:
# parse: ->
# super
# @start(@your_top_level_production)
parse: (input) =>
@input = input
# Returns true when this parser has exhausted its input.
eof: =>
@input is ""
# Indicate failure, optionally resetting the input to a previous
# state. This is not an exceptional condition (in choice and
# maybes, for example).
fail: (input) =>
@input = input if input isnt `undefined`
throw @fail
# Execute a production, which could be a function or a RegExp.
produce: (method) =>
val = if ((method instanceof RegExp) or (typeof method == 'string'))
@m(method)
else
method.call(@)
@skipWS() if @ignorews
val
# Begin parsing using the given production, return the result.
# All input must be consumed.
start: (method) =>
val = undefined
@ignorews and @skipWS()
try
val = @produce method
return val if @eof()
catch err
throw err if err isnt @fail
throw new Error("Could not parse '" + @input + "'.")
# The core: Match a regular expression against the input,
# returning the first captured group. If no group is captured,
# return the matched string. This can result in surprises, if you
# don't wrap your groups exactly right, which is common in ()?
# regexps. Note that this is where the input consumption happens:
# upon a match, the input is reduced to whatever did not match.
#
# Note that as the tree of productions is followed, backups of
# existing input are kept and restored when a possible parse
# fails. If your source is very large, this can become
# problematic in both time and space.
#
# Note that the `return fail()` call eventually leads to a throw.
m: (pattern, putback = false) =>
if typeof pattern == 'string'
if @input.substr(0, pattern.length) == pattern
@input = @input.substr(pattern.length)
return pattern
return @fail()
probe = @input.match pattern
return @fail() unless probe
@input = @input.substr (if probe[1]? and putback then probe[1].length else probe[0].length)
if probe[1] is `undefined` then probe[0] else probe[1]
match: => @m.apply this, arguments
# Attempts to apply the method and produce a value. If it fails,
# restores the input to the previous state.
maybe: (method) =>
input = @input
try
return @produce method
catch err
throw err if err isnt @fail
@fail input
# Try to run the production `method`. If the production fails,
# don't fail, just return the otherwise.
option: (method, otherwise) =>
try
return @maybe method
catch err
throw err if err isnt @fail
return otherwise
# Given three parsers, return the value produced by `body`. This
# is equivalent to seq(left, body, right)[0]. I'm not sure why
# Weaver created an alternative syntax, then. Wishing JSParsec
# wasn't so damned unreadable.
between: (left, right, body) =>
input = @input
val = undefined
try
@produce left
val = @produce body
@produce right
return val
catch err
throw err if err isnt @fail
@fail input
# Returns the first production among arguments for which the
# production does not fail.
choice: =>
input = @input
for arg in arguments
try
return @produce arg
catch err
throw err if err isnt @fail
@fail input
# Match every production in a sequence, returning a list of the
# values produced. Sometimes Coffeescript's parser surprises me,
# as in this case where the try-return pairing confused it, and it
# needed help isolating the element.
#
# I have yet to find a case where where Weaver's unshift of the
# beginning of the input string to the front of the return value
# makes sense. It's not a feature of Parsec's sequence primitive,
# for example.
#
# It could be useful if one needed the raw of a seq: for example,
# when processing XML entities for correctness, not value. But in
# the short term, the productions can be as preservative as
# Weaver's technique, and for my needs that's my story, and I'm
# sticking to it.
seq: =>
input = @input
try
return (for arg in arguments
@produce(arg))
catch err
throw err if err isnt @fail
@fail input
# Applies the production `method` `min` or more times. Returns
# the parser object as a chainable convenience if it does not
# fail. Will fail if it skips less than `min` times.
skip: (method, min = null) =>
found = 0
input = @input
until @eof()
try
@maybe method
found++
catch err
throw err if err isnt @fail
break
if min and (found < min) then @fail input else @
# Applies the production `method` one or more times.
skip1: (method) => @skip(method, 1)
# Skip whitespace. Returns the parser object for chainable
# convenience. Note that this is the baseline whitespace: this
# will not skip carriage returns or linefeeds.
skipWS: =>
@m(/^\s*/)
@
# Returns an array of `min` values produced by `method`.
many: (method, min = null) =>
input = @input
result = []
until @eof()
try
result.push @maybe method
catch err
throw err if err isnt @fail
break
if min and (result.length < min) then @fail input else result
# Returns an array of at least one values produced by `method`.
# Fails if zero values are produced.
many1: (method) => @many method, 1
# Return the array of values produced by `method` with `sep`
# between each value. The series may be terminated by a `sep`.
sepBy: (method, sep, min = 0) =>
orig = @input
input = undefined
result = []
try
result.push @produce method
until @eof()
try
input = @input
@produce sep
result.push @produce method
catch err
throw err if err isnt @fail
@fail input
catch err
throw err if err isnt @fail
if min and (result.length < min) then @fail orig else result
sepBy1: (method, sep) => @sepBy method, sep, 1
# parses `min` or more productions of `method` (zero by default),
# which must be terminated with the `end` production. RESOLVE:
# There is no alternative production being given to `@option` in
# Weaver's code. I've changed this to @produce for the time
# being, which seems to be in line with the JSParsec
# implementation.
endBy: (method, end, min = 0) =>
val = @many method, min
@produce end
val
# Parses 1 or more productions of method, which must be terminated
# with the end production
endBy1: (method, end) =>
@endBy method, end, 1
# Returns an array of `min` or more values produced by `method`,
# separated by `sep`, and optionally terminated by `sep`.
# Defaults to zero productions.
sepEndBy: (method, sep, min = 0) =>
val = @sepBy method, sep, min
@option sep
val
# Returns an array of `min` or more values produced by `method`,
# separated by `sep`, and optionally terminated by `sep`.
# Defaults to zero productions. Must return at least one
# production; fails if there are zero productions.
sepEndBy1: (method, sep) => @sepEndBy method, sep, 1
# Process `min` occurrences of `method`, separated by `op`. Return
# a value obtained by the repeated application of the return of
# `op` to the return of `method`. If there are less that `min`
# occurrences of `method`, `otherwise` is returned. Used, for
# example, to process a collection of mathematical productions of
# the same precedence. This is analogous to the reduce() function
# of python, ruby, and ECMA5.
chainl: (method, op, otherwise = null, min = null) =>
found = 0
result = otherwise
orig = @input
input = undefined
try
result = @maybe(method)
found++
until @eof()
try
input = @input
result = @produce(op)(result, @produce(method))
found++
catch err
throw err if err isnt @fail
@fail input
catch err
throw err if err isnt @fail
if min and (found < min) then @fail input else result
# Like `chainl`, but must produce at least one production. Fails
# if there are zero productions.
chainl1: (method, op) => @chainl method, op, null, 1
| 28723 | #; -*- mode: coffee -*-
# ___ ___ ___ __ __
# | _ \___| _ \__ _ _ _ ___ ___ / __|___ / _|/ _|___ ___
# | / -_) _/ _` | '_(_-</ -_) | (__/ _ \ _| _/ -_) -_)
# |_|_\___|_| \__,_|_| /__/\___| \___\___/_| |_| \___\___|
#
# A hand-re-written implementation of <NAME>'s ReParse, a parser
# combinator, which in turn was heavily influenced by Haskell's
# PARSEC. In many cases, this code is almost exactly <NAME>'s; in some,
# I've lifted further ideas and commentary from the JSParsec project.
exports.ReParse = class ReParse
# Extend from ReParse and set to true if you don't care about
# whitespace.
ignorews: false
# Where the parse phase begins. The correct way to override this
# is to create a child method:
# parse: ->
# super
# @start(@your_top_level_production)
parse: (input) =>
@input = input
# Returns true when this parser has exhausted its input.
eof: =>
@input is ""
# Indicate failure, optionally resetting the input to a previous
# state. This is not an exceptional condition (in choice and
# maybes, for example).
fail: (input) =>
@input = input if input isnt `undefined`
throw @fail
# Execute a production, which could be a function or a RegExp.
produce: (method) =>
val = if ((method instanceof RegExp) or (typeof method == 'string'))
@m(method)
else
method.call(@)
@skipWS() if @ignorews
val
# Begin parsing using the given production, return the result.
# All input must be consumed.
start: (method) =>
val = undefined
@ignorews and @skipWS()
try
val = @produce method
return val if @eof()
catch err
throw err if err isnt @fail
throw new Error("Could not parse '" + @input + "'.")
# The core: Match a regular expression against the input,
# returning the first captured group. If no group is captured,
# return the matched string. This can result in surprises, if you
# don't wrap your groups exactly right, which is common in ()?
# regexps. Note that this is where the input consumption happens:
# upon a match, the input is reduced to whatever did not match.
#
# Note that as the tree of productions is followed, backups of
# existing input are kept and restored when a possible parse
# fails. If your source is very large, this can become
# problematic in both time and space.
#
# Note that the `return fail()` call eventually leads to a throw.
m: (pattern, putback = false) =>
if typeof pattern == 'string'
if @input.substr(0, pattern.length) == pattern
@input = @input.substr(pattern.length)
return pattern
return @fail()
probe = @input.match pattern
return @fail() unless probe
@input = @input.substr (if probe[1]? and putback then probe[1].length else probe[0].length)
if probe[1] is `undefined` then probe[0] else probe[1]
match: => @m.apply this, arguments
# Attempts to apply the method and produce a value. If it fails,
# restores the input to the previous state.
maybe: (method) =>
input = @input
try
return @produce method
catch err
throw err if err isnt @fail
@fail input
# Try to run the production `method`. If the production fails,
# don't fail, just return the otherwise.
option: (method, otherwise) =>
try
return @maybe method
catch err
throw err if err isnt @fail
return otherwise
# Given three parsers, return the value produced by `body`. This
# is equivalent to seq(left, body, right)[0]. I'm not sure why
# Weaver created an alternative syntax, then. Wishing JSParsec
# wasn't so damned unreadable.
between: (left, right, body) =>
input = @input
val = undefined
try
@produce left
val = @produce body
@produce right
return val
catch err
throw err if err isnt @fail
@fail input
# Returns the first production among arguments for which the
# production does not fail.
choice: =>
input = @input
for arg in arguments
try
return @produce arg
catch err
throw err if err isnt @fail
@fail input
# Match every production in a sequence, returning a list of the
# values produced. Sometimes Coffeescript's parser surprises me,
# as in this case where the try-return pairing confused it, and it
# needed help isolating the element.
#
# I have yet to find a case where where Weaver's unshift of the
# beginning of the input string to the front of the return value
# makes sense. It's not a feature of Parsec's sequence primitive,
# for example.
#
# It could be useful if one needed the raw of a seq: for example,
# when processing XML entities for correctness, not value. But in
# the short term, the productions can be as preservative as
# Weaver's technique, and for my needs that's my story, and I'm
# sticking to it.
seq: =>
input = @input
try
return (for arg in arguments
@produce(arg))
catch err
throw err if err isnt @fail
@fail input
# Applies the production `method` `min` or more times. Returns
# the parser object as a chainable convenience if it does not
# fail. Will fail if it skips less than `min` times.
skip: (method, min = null) =>
found = 0
input = @input
until @eof()
try
@maybe method
found++
catch err
throw err if err isnt @fail
break
if min and (found < min) then @fail input else @
# Applies the production `method` one or more times.
skip1: (method) => @skip(method, 1)
# Skip whitespace. Returns the parser object for chainable
# convenience. Note that this is the baseline whitespace: this
# will not skip carriage returns or linefeeds.
skipWS: =>
@m(/^\s*/)
@
# Returns an array of `min` values produced by `method`.
many: (method, min = null) =>
input = @input
result = []
until @eof()
try
result.push @maybe method
catch err
throw err if err isnt @fail
break
if min and (result.length < min) then @fail input else result
# Returns an array of at least one values produced by `method`.
# Fails if zero values are produced.
many1: (method) => @many method, 1
# Return the array of values produced by `method` with `sep`
# between each value. The series may be terminated by a `sep`.
sepBy: (method, sep, min = 0) =>
orig = @input
input = undefined
result = []
try
result.push @produce method
until @eof()
try
input = @input
@produce sep
result.push @produce method
catch err
throw err if err isnt @fail
@fail input
catch err
throw err if err isnt @fail
if min and (result.length < min) then @fail orig else result
sepBy1: (method, sep) => @sepBy method, sep, 1
# parses `min` or more productions of `method` (zero by default),
# which must be terminated with the `end` production. RESOLVE:
# There is no alternative production being given to `@option` in
# Weaver's code. I've changed this to @produce for the time
# being, which seems to be in line with the JSParsec
# implementation.
endBy: (method, end, min = 0) =>
val = @many method, min
@produce end
val
# Parses 1 or more productions of method, which must be terminated
# with the end production
endBy1: (method, end) =>
@endBy method, end, 1
# Returns an array of `min` or more values produced by `method`,
# separated by `sep`, and optionally terminated by `sep`.
# Defaults to zero productions.
sepEndBy: (method, sep, min = 0) =>
val = @sepBy method, sep, min
@option sep
val
# Returns an array of `min` or more values produced by `method`,
# separated by `sep`, and optionally terminated by `sep`.
# Defaults to zero productions. Must return at least one
# production; fails if there are zero productions.
sepEndBy1: (method, sep) => @sepEndBy method, sep, 1
# Process `min` occurrences of `method`, separated by `op`. Return
# a value obtained by the repeated application of the return of
# `op` to the return of `method`. If there are less that `min`
# occurrences of `method`, `otherwise` is returned. Used, for
# example, to process a collection of mathematical productions of
# the same precedence. This is analogous to the reduce() function
# of python, ruby, and ECMA5.
chainl: (method, op, otherwise = null, min = null) =>
found = 0
result = otherwise
orig = @input
input = undefined
try
result = @maybe(method)
found++
until @eof()
try
input = @input
result = @produce(op)(result, @produce(method))
found++
catch err
throw err if err isnt @fail
@fail input
catch err
throw err if err isnt @fail
if min and (found < min) then @fail input else result
# Like `chainl`, but must produce at least one production. Fails
# if there are zero productions.
chainl1: (method, op) => @chainl method, op, null, 1
| true | #; -*- mode: coffee -*-
# ___ ___ ___ __ __
# | _ \___| _ \__ _ _ _ ___ ___ / __|___ / _|/ _|___ ___
# | / -_) _/ _` | '_(_-</ -_) | (__/ _ \ _| _/ -_) -_)
# |_|_\___|_| \__,_|_| /__/\___| \___\___/_| |_| \___\___|
#
# A hand-re-written implementation of PI:NAME:<NAME>END_PI's ReParse, a parser
# combinator, which in turn was heavily influenced by Haskell's
# PARSEC. In many cases, this code is almost exactly PI:NAME:<NAME>END_PI's; in some,
# I've lifted further ideas and commentary from the JSParsec project.
exports.ReParse = class ReParse
# Extend from ReParse and set to true if you don't care about
# whitespace.
ignorews: false
# Where the parse phase begins. The correct way to override this
# is to create a child method:
# parse: ->
# super
# @start(@your_top_level_production)
parse: (input) =>
@input = input
# Returns true when this parser has exhausted its input.
eof: =>
@input is ""
# Indicate failure, optionally resetting the input to a previous
# state. This is not an exceptional condition (in choice and
# maybes, for example).
fail: (input) =>
@input = input if input isnt `undefined`
throw @fail
# Execute a production, which could be a function or a RegExp.
produce: (method) =>
val = if ((method instanceof RegExp) or (typeof method == 'string'))
@m(method)
else
method.call(@)
@skipWS() if @ignorews
val
# Begin parsing using the given production, return the result.
# All input must be consumed.
start: (method) =>
val = undefined
@ignorews and @skipWS()
try
val = @produce method
return val if @eof()
catch err
throw err if err isnt @fail
throw new Error("Could not parse '" + @input + "'.")
# The core: Match a regular expression against the input,
# returning the first captured group. If no group is captured,
# return the matched string. This can result in surprises, if you
# don't wrap your groups exactly right, which is common in ()?
# regexps. Note that this is where the input consumption happens:
# upon a match, the input is reduced to whatever did not match.
#
# Note that as the tree of productions is followed, backups of
# existing input are kept and restored when a possible parse
# fails. If your source is very large, this can become
# problematic in both time and space.
#
# Note that the `return fail()` call eventually leads to a throw.
m: (pattern, putback = false) =>
if typeof pattern == 'string'
if @input.substr(0, pattern.length) == pattern
@input = @input.substr(pattern.length)
return pattern
return @fail()
probe = @input.match pattern
return @fail() unless probe
@input = @input.substr (if probe[1]? and putback then probe[1].length else probe[0].length)
if probe[1] is `undefined` then probe[0] else probe[1]
match: => @m.apply this, arguments
# Attempts to apply the method and produce a value. If it fails,
# restores the input to the previous state.
maybe: (method) =>
input = @input
try
return @produce method
catch err
throw err if err isnt @fail
@fail input
# Try to run the production `method`. If the production fails,
# don't fail, just return the otherwise.
option: (method, otherwise) =>
try
return @maybe method
catch err
throw err if err isnt @fail
return otherwise
# Given three parsers, return the value produced by `body`. This
# is equivalent to seq(left, body, right)[0]. I'm not sure why
# Weaver created an alternative syntax, then. Wishing JSParsec
# wasn't so damned unreadable.
between: (left, right, body) =>
input = @input
val = undefined
try
@produce left
val = @produce body
@produce right
return val
catch err
throw err if err isnt @fail
@fail input
# Returns the first production among arguments for which the
# production does not fail.
choice: =>
input = @input
for arg in arguments
try
return @produce arg
catch err
throw err if err isnt @fail
@fail input
# Match every production in a sequence, returning a list of the
# values produced. Sometimes Coffeescript's parser surprises me,
# as in this case where the try-return pairing confused it, and it
# needed help isolating the element.
#
# I have yet to find a case where where Weaver's unshift of the
# beginning of the input string to the front of the return value
# makes sense. It's not a feature of Parsec's sequence primitive,
# for example.
#
# It could be useful if one needed the raw of a seq: for example,
# when processing XML entities for correctness, not value. But in
# the short term, the productions can be as preservative as
# Weaver's technique, and for my needs that's my story, and I'm
# sticking to it.
seq: =>
input = @input
try
return (for arg in arguments
@produce(arg))
catch err
throw err if err isnt @fail
@fail input
# Applies the production `method` `min` or more times. Returns
# the parser object as a chainable convenience if it does not
# fail. Will fail if it skips less than `min` times.
skip: (method, min = null) =>
found = 0
input = @input
until @eof()
try
@maybe method
found++
catch err
throw err if err isnt @fail
break
if min and (found < min) then @fail input else @
# Applies the production `method` one or more times.
skip1: (method) => @skip(method, 1)
# Skip whitespace. Returns the parser object for chainable
# convenience. Note that this is the baseline whitespace: this
# will not skip carriage returns or linefeeds.
skipWS: =>
@m(/^\s*/)
@
# Returns an array of `min` values produced by `method`.
many: (method, min = null) =>
input = @input
result = []
until @eof()
try
result.push @maybe method
catch err
throw err if err isnt @fail
break
if min and (result.length < min) then @fail input else result
# Returns an array of at least one values produced by `method`.
# Fails if zero values are produced.
many1: (method) => @many method, 1
# Return the array of values produced by `method` with `sep`
# between each value. The series may be terminated by a `sep`.
sepBy: (method, sep, min = 0) =>
orig = @input
input = undefined
result = []
try
result.push @produce method
until @eof()
try
input = @input
@produce sep
result.push @produce method
catch err
throw err if err isnt @fail
@fail input
catch err
throw err if err isnt @fail
if min and (result.length < min) then @fail orig else result
sepBy1: (method, sep) => @sepBy method, sep, 1
# parses `min` or more productions of `method` (zero by default),
# which must be terminated with the `end` production. RESOLVE:
# There is no alternative production being given to `@option` in
# Weaver's code. I've changed this to @produce for the time
# being, which seems to be in line with the JSParsec
# implementation.
endBy: (method, end, min = 0) =>
val = @many method, min
@produce end
val
# Parses 1 or more productions of method, which must be terminated
# with the end production
endBy1: (method, end) =>
@endBy method, end, 1
# Returns an array of `min` or more values produced by `method`,
# separated by `sep`, and optionally terminated by `sep`.
# Defaults to zero productions.
sepEndBy: (method, sep, min = 0) =>
val = @sepBy method, sep, min
@option sep
val
# Returns an array of `min` or more values produced by `method`,
# separated by `sep`, and optionally terminated by `sep`.
# Defaults to zero productions. Must return at least one
# production; fails if there are zero productions.
sepEndBy1: (method, sep) => @sepEndBy method, sep, 1
# Process `min` occurrences of `method`, separated by `op`. Return
# a value obtained by the repeated application of the return of
# `op` to the return of `method`. If there are less that `min`
# occurrences of `method`, `otherwise` is returned. Used, for
# example, to process a collection of mathematical productions of
# the same precedence. This is analogous to the reduce() function
# of python, ruby, and ECMA5.
chainl: (method, op, otherwise = null, min = null) =>
found = 0
result = otherwise
orig = @input
input = undefined
try
result = @maybe(method)
found++
until @eof()
try
input = @input
result = @produce(op)(result, @produce(method))
found++
catch err
throw err if err isnt @fail
@fail input
catch err
throw err if err isnt @fail
if min and (found < min) then @fail input else result
# Like `chainl`, but must produce at least one production. Fails
# if there are zero productions.
chainl1: (method, op) => @chainl method, op, null, 1
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.6547344923019409,
"start": 29,
"tag": "NAME",
"value": "Neo Technology"
}
] | community/server/src/main/coffeescript/neo4j/webadmin/utils/ItemUrlResolver.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 [], () ->
class ItemUrlResolver
constructor : (server) ->
@server = server
getNodeUrl : (id) =>
@server.url + "/db/data/node/" + id
getRelationshipUrl : (id) =>
@server.url + "/db/data/relationship/" + id
getNodeIndexHitsUrl: (index,key,value) =>
@server.url + "/db/data/index" + index + "/" + ( encodeURIComponent key ) + "/" + ( encodeURIComponent value )
extractNodeId : (url) =>
@extractLastUrlSegment(url)
extractRelationshipId : (url) =>
@extractLastUrlSegment(url)
extractLastUrlSegment : (url) =>
if url.substr(-1) is "/"
url = url.substr(0, url.length - 1)
url.substr(url.lastIndexOf("/") + 1)
| 20791 | ###
Copyright (c) 2002-2013 "<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 [], () ->
class ItemUrlResolver
constructor : (server) ->
@server = server
getNodeUrl : (id) =>
@server.url + "/db/data/node/" + id
getRelationshipUrl : (id) =>
@server.url + "/db/data/relationship/" + id
getNodeIndexHitsUrl: (index,key,value) =>
@server.url + "/db/data/index" + index + "/" + ( encodeURIComponent key ) + "/" + ( encodeURIComponent value )
extractNodeId : (url) =>
@extractLastUrlSegment(url)
extractRelationshipId : (url) =>
@extractLastUrlSegment(url)
extractLastUrlSegment : (url) =>
if url.substr(-1) is "/"
url = url.substr(0, url.length - 1)
url.substr(url.lastIndexOf("/") + 1)
| true | ###
Copyright (c) 2002-2013 "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 [], () ->
class ItemUrlResolver
constructor : (server) ->
@server = server
getNodeUrl : (id) =>
@server.url + "/db/data/node/" + id
getRelationshipUrl : (id) =>
@server.url + "/db/data/relationship/" + id
getNodeIndexHitsUrl: (index,key,value) =>
@server.url + "/db/data/index" + index + "/" + ( encodeURIComponent key ) + "/" + ( encodeURIComponent value )
extractNodeId : (url) =>
@extractLastUrlSegment(url)
extractRelationshipId : (url) =>
@extractLastUrlSegment(url)
extractLastUrlSegment : (url) =>
if url.substr(-1) is "/"
url = url.substr(0, url.length - 1)
url.substr(url.lastIndexOf("/") + 1)
|
[
{
"context": "###\n * Based on github.com/visionmedia/page.js\n * Licensed under the MIT license\n * Copy",
"end": 38,
"score": 0.9992603063583374,
"start": 27,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "* Licensed under the MIT license\n * Copyright 2012 TJ Holowaychuk <tj@vision-media.ca>\n###\n\nrunning = false\ncurrent",
"end": 113,
"score": 0.9998539090156555,
"start": 99,
"tag": "NAME",
"value": "TJ Holowaychuk"
},
{
"context": "the MIT license\n * Copyright 2012 TJ Holowaychuk <tj@vision-media.ca>\n###\n\nrunning = false\ncurrentState = null\ncallbac",
"end": 133,
"score": 0.9999273419380188,
"start": 115,
"tag": "EMAIL",
"value": "tj@vision-media.ca"
}
] | public/javascripts/lib/page.coffee | w3cub/docshub-node | 3 | ###
* Based on github.com/visionmedia/page.js
* Licensed under the MIT license
* Copyright 2012 TJ Holowaychuk <tj@vision-media.ca>
###
running = false
currentState = null
callbacks = []
@page = (value, fn) ->
if typeof value is 'function'
page '*', value
else if typeof fn is 'function'
route = new Route(value)
callbacks.push route.middleware(fn)
else if typeof value is 'string'
page.show(value, fn)
else
page.start(value)
return
page.start = (options = {}) ->
unless running
running = true
addEventListener 'popstate', onpopstate
addEventListener 'click', onclick
page.replace currentPath(), null, null, true
return
page.stop = ->
if running
running = false
removeEventListener 'click', onclick
removeEventListener 'popstate', onpopstate
return
page.show = (path, state) ->
return if path is currentState?.path
context = new Context(path, state)
previousState = currentState
currentState = context.state
if res = page.dispatch(context)
currentState = previousState
location.assign(res)
else
context.pushState()
updateCanonicalLink()
track()
context
page.replace = (path, state, skipDispatch, init) ->
context = new Context(path, state or currentState)
context.init = init
currentState = context.state
result = page.dispatch(context) unless skipDispatch
if result
context = new Context(result)
context.init = init
currentState = context.state
page.dispatch(context)
context.replaceState()
updateCanonicalLink()
track() unless skipDispatch
context
page.dispatch = (context) ->
i = 0
next = ->
res = fn(context, next) if fn = callbacks[i++]
return res
return next()
page.canGoBack = ->
not Context.isIntialState(currentState)
page.canGoForward = ->
not Context.isLastState(currentState)
currentPath = ->
location.pathname + location.search + location.hash
class Context
@initialPath: currentPath()
@sessionId: Date.now()
@stateId: 0
@isIntialState: (state) ->
state.id == 0
@isLastState: (state) ->
state.id == @stateId - 1
@isInitialPopState: (state) ->
state.path is @initialPath and @stateId is 1
@isSameSession: (state) ->
state.sessionId is @sessionId
constructor: (@path = '/', @state = {}) ->
@pathname = @path.replace /(?:\?([^#]*))?(?:#(.*))?$/, (_, query, hash) =>
@query = query
@hash = hash
''
@state.id ?= @constructor.stateId++
@state.sessionId ?= @constructor.sessionId
@state.path = @path
pushState: ->
location.href = @path
# history.pushState @state, '', @path
return
replaceState: ->
try history.replaceState @state, '', @path # NS_ERROR_FAILURE in Firefox
return
class Route
constructor: (@path, options = {}) ->
@keys = []
@regexp = pathtoRegexp @path, @keys
middleware: (fn) ->
(context, next) =>
if @match context.pathname, params = []
context.params = params
return fn(context, next)
else
return next()
match: (path, params) ->
return unless matchData = @regexp.exec(path)
for value, i in matchData[1..]
value = decodeURIComponent value if typeof value is 'string'
if key = @keys[i]
params[key.name] = value
else
params.push value
true
pathtoRegexp = (path, keys) ->
return path if path instanceof RegExp
path = "(#{path.join '|'})" if path instanceof Array
path = path
.replace /\/\(/g, '(?:/'
.replace /(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, (_, slash = '', format = '', key, capture, optional) ->
keys.push name: key, optional: !!optional
str = if optional then '' else slash
str += '(?:'
str += slash if optional
str += format
str += capture or if format then '([^/.]+?)' else '([^/]+?)'
str += ')'
str += optional if optional
str
.replace /([\/.])/g, '\\$1'
.replace /\*/g, '(.*)'
new RegExp "^#{path}$"
onpopstate = (event) ->
return if not event.state or Context.isInitialPopState(event.state)
if Context.isSameSession(event.state)
page.replace(event.state.path, event.state)
else
location.reload()
return
onclick = (event) ->
try
return if event.which isnt 1 or event.metaKey or event.ctrlKey or event.shiftKey or event.defaultPrevented
catch
return
link = $.eventTarget(event)
link = link.parentNode while link and link.tagName isnt 'A'
if link and not link.target and isSameOrigin(link.href)
# event.preventDefault()
path = link.pathname + link.search + link.hash
path = path.replace /^\/\/+/, '/' # IE11 bug
page.show(path)
return
isSameOrigin = (url) ->
url.indexOf("#{location.protocol}//#{location.hostname}") is 0
updateCanonicalLink = ->
@canonicalLink ||= document.head.querySelector('link[rel="canonical"]')
@canonicalLink.setAttribute('href', "http://#{location.host}#{location.pathname}")
trackers = []
page.track = (fn) ->
trackers.push(fn)
return
track = ->
tracker.call() for tracker in trackers
return
| 126429 | ###
* Based on github.com/visionmedia/page.js
* Licensed under the MIT license
* Copyright 2012 <NAME> <<EMAIL>>
###
running = false
currentState = null
callbacks = []
@page = (value, fn) ->
if typeof value is 'function'
page '*', value
else if typeof fn is 'function'
route = new Route(value)
callbacks.push route.middleware(fn)
else if typeof value is 'string'
page.show(value, fn)
else
page.start(value)
return
page.start = (options = {}) ->
unless running
running = true
addEventListener 'popstate', onpopstate
addEventListener 'click', onclick
page.replace currentPath(), null, null, true
return
page.stop = ->
if running
running = false
removeEventListener 'click', onclick
removeEventListener 'popstate', onpopstate
return
page.show = (path, state) ->
return if path is currentState?.path
context = new Context(path, state)
previousState = currentState
currentState = context.state
if res = page.dispatch(context)
currentState = previousState
location.assign(res)
else
context.pushState()
updateCanonicalLink()
track()
context
page.replace = (path, state, skipDispatch, init) ->
context = new Context(path, state or currentState)
context.init = init
currentState = context.state
result = page.dispatch(context) unless skipDispatch
if result
context = new Context(result)
context.init = init
currentState = context.state
page.dispatch(context)
context.replaceState()
updateCanonicalLink()
track() unless skipDispatch
context
page.dispatch = (context) ->
i = 0
next = ->
res = fn(context, next) if fn = callbacks[i++]
return res
return next()
page.canGoBack = ->
not Context.isIntialState(currentState)
page.canGoForward = ->
not Context.isLastState(currentState)
currentPath = ->
location.pathname + location.search + location.hash
class Context
@initialPath: currentPath()
@sessionId: Date.now()
@stateId: 0
@isIntialState: (state) ->
state.id == 0
@isLastState: (state) ->
state.id == @stateId - 1
@isInitialPopState: (state) ->
state.path is @initialPath and @stateId is 1
@isSameSession: (state) ->
state.sessionId is @sessionId
constructor: (@path = '/', @state = {}) ->
@pathname = @path.replace /(?:\?([^#]*))?(?:#(.*))?$/, (_, query, hash) =>
@query = query
@hash = hash
''
@state.id ?= @constructor.stateId++
@state.sessionId ?= @constructor.sessionId
@state.path = @path
pushState: ->
location.href = @path
# history.pushState @state, '', @path
return
replaceState: ->
try history.replaceState @state, '', @path # NS_ERROR_FAILURE in Firefox
return
class Route
constructor: (@path, options = {}) ->
@keys = []
@regexp = pathtoRegexp @path, @keys
middleware: (fn) ->
(context, next) =>
if @match context.pathname, params = []
context.params = params
return fn(context, next)
else
return next()
match: (path, params) ->
return unless matchData = @regexp.exec(path)
for value, i in matchData[1..]
value = decodeURIComponent value if typeof value is 'string'
if key = @keys[i]
params[key.name] = value
else
params.push value
true
pathtoRegexp = (path, keys) ->
return path if path instanceof RegExp
path = "(#{path.join '|'})" if path instanceof Array
path = path
.replace /\/\(/g, '(?:/'
.replace /(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, (_, slash = '', format = '', key, capture, optional) ->
keys.push name: key, optional: !!optional
str = if optional then '' else slash
str += '(?:'
str += slash if optional
str += format
str += capture or if format then '([^/.]+?)' else '([^/]+?)'
str += ')'
str += optional if optional
str
.replace /([\/.])/g, '\\$1'
.replace /\*/g, '(.*)'
new RegExp "^#{path}$"
onpopstate = (event) ->
return if not event.state or Context.isInitialPopState(event.state)
if Context.isSameSession(event.state)
page.replace(event.state.path, event.state)
else
location.reload()
return
onclick = (event) ->
try
return if event.which isnt 1 or event.metaKey or event.ctrlKey or event.shiftKey or event.defaultPrevented
catch
return
link = $.eventTarget(event)
link = link.parentNode while link and link.tagName isnt 'A'
if link and not link.target and isSameOrigin(link.href)
# event.preventDefault()
path = link.pathname + link.search + link.hash
path = path.replace /^\/\/+/, '/' # IE11 bug
page.show(path)
return
isSameOrigin = (url) ->
url.indexOf("#{location.protocol}//#{location.hostname}") is 0
updateCanonicalLink = ->
@canonicalLink ||= document.head.querySelector('link[rel="canonical"]')
@canonicalLink.setAttribute('href', "http://#{location.host}#{location.pathname}")
trackers = []
page.track = (fn) ->
trackers.push(fn)
return
track = ->
tracker.call() for tracker in trackers
return
| true | ###
* Based on github.com/visionmedia/page.js
* Licensed under the MIT license
* Copyright 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
running = false
currentState = null
callbacks = []
@page = (value, fn) ->
if typeof value is 'function'
page '*', value
else if typeof fn is 'function'
route = new Route(value)
callbacks.push route.middleware(fn)
else if typeof value is 'string'
page.show(value, fn)
else
page.start(value)
return
page.start = (options = {}) ->
unless running
running = true
addEventListener 'popstate', onpopstate
addEventListener 'click', onclick
page.replace currentPath(), null, null, true
return
page.stop = ->
if running
running = false
removeEventListener 'click', onclick
removeEventListener 'popstate', onpopstate
return
page.show = (path, state) ->
return if path is currentState?.path
context = new Context(path, state)
previousState = currentState
currentState = context.state
if res = page.dispatch(context)
currentState = previousState
location.assign(res)
else
context.pushState()
updateCanonicalLink()
track()
context
page.replace = (path, state, skipDispatch, init) ->
context = new Context(path, state or currentState)
context.init = init
currentState = context.state
result = page.dispatch(context) unless skipDispatch
if result
context = new Context(result)
context.init = init
currentState = context.state
page.dispatch(context)
context.replaceState()
updateCanonicalLink()
track() unless skipDispatch
context
page.dispatch = (context) ->
i = 0
next = ->
res = fn(context, next) if fn = callbacks[i++]
return res
return next()
page.canGoBack = ->
not Context.isIntialState(currentState)
page.canGoForward = ->
not Context.isLastState(currentState)
currentPath = ->
location.pathname + location.search + location.hash
class Context
@initialPath: currentPath()
@sessionId: Date.now()
@stateId: 0
@isIntialState: (state) ->
state.id == 0
@isLastState: (state) ->
state.id == @stateId - 1
@isInitialPopState: (state) ->
state.path is @initialPath and @stateId is 1
@isSameSession: (state) ->
state.sessionId is @sessionId
constructor: (@path = '/', @state = {}) ->
@pathname = @path.replace /(?:\?([^#]*))?(?:#(.*))?$/, (_, query, hash) =>
@query = query
@hash = hash
''
@state.id ?= @constructor.stateId++
@state.sessionId ?= @constructor.sessionId
@state.path = @path
pushState: ->
location.href = @path
# history.pushState @state, '', @path
return
replaceState: ->
try history.replaceState @state, '', @path # NS_ERROR_FAILURE in Firefox
return
class Route
constructor: (@path, options = {}) ->
@keys = []
@regexp = pathtoRegexp @path, @keys
middleware: (fn) ->
(context, next) =>
if @match context.pathname, params = []
context.params = params
return fn(context, next)
else
return next()
match: (path, params) ->
return unless matchData = @regexp.exec(path)
for value, i in matchData[1..]
value = decodeURIComponent value if typeof value is 'string'
if key = @keys[i]
params[key.name] = value
else
params.push value
true
pathtoRegexp = (path, keys) ->
return path if path instanceof RegExp
path = "(#{path.join '|'})" if path instanceof Array
path = path
.replace /\/\(/g, '(?:/'
.replace /(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, (_, slash = '', format = '', key, capture, optional) ->
keys.push name: key, optional: !!optional
str = if optional then '' else slash
str += '(?:'
str += slash if optional
str += format
str += capture or if format then '([^/.]+?)' else '([^/]+?)'
str += ')'
str += optional if optional
str
.replace /([\/.])/g, '\\$1'
.replace /\*/g, '(.*)'
new RegExp "^#{path}$"
onpopstate = (event) ->
return if not event.state or Context.isInitialPopState(event.state)
if Context.isSameSession(event.state)
page.replace(event.state.path, event.state)
else
location.reload()
return
onclick = (event) ->
try
return if event.which isnt 1 or event.metaKey or event.ctrlKey or event.shiftKey or event.defaultPrevented
catch
return
link = $.eventTarget(event)
link = link.parentNode while link and link.tagName isnt 'A'
if link and not link.target and isSameOrigin(link.href)
# event.preventDefault()
path = link.pathname + link.search + link.hash
path = path.replace /^\/\/+/, '/' # IE11 bug
page.show(path)
return
isSameOrigin = (url) ->
url.indexOf("#{location.protocol}//#{location.hostname}") is 0
updateCanonicalLink = ->
@canonicalLink ||= document.head.querySelector('link[rel="canonical"]')
@canonicalLink.setAttribute('href', "http://#{location.host}#{location.pathname}")
trackers = []
page.track = (fn) ->
trackers.push(fn)
return
track = ->
tracker.call() for tracker in trackers
return
|
[
{
"context": " email = null\n# id\n login = null\n# password\n# rep\n# salt\n# updated_at\n# verified\n\n constructor:",
"end": 93,
"score": 0.8455392122268677,
"start": 90,
"tag": "PASSWORD",
"value": "rep"
},
{
"context": " = null\n# id\n login = null\n# password\n# rep\n# salt\n# updated_at\n# verified\n\n constructor: (_login",
"end": 101,
"score": 0.6914263367652893,
"start": 97,
"tag": "PASSWORD",
"value": "salt"
}
] | app/assets/javascripts/model/user.coffee | migueldiab/llevame | 0 | class @User
# created_at
dob = null
email = null
# id
login = null
# password
# rep
# salt
# updated_at
# verified
constructor: (_login) ->
console.log "Creating user #{_login}"
login = _login
getLogin: ->
login
setLogin: (val) ->
login = val | 23575 | class @User
# created_at
dob = null
email = null
# id
login = null
# password
# <PASSWORD>
# <PASSWORD>
# updated_at
# verified
constructor: (_login) ->
console.log "Creating user #{_login}"
login = _login
getLogin: ->
login
setLogin: (val) ->
login = val | true | class @User
# created_at
dob = null
email = null
# id
login = null
# password
# PI:PASSWORD:<PASSWORD>END_PI
# PI:PASSWORD:<PASSWORD>END_PI
# updated_at
# verified
constructor: (_login) ->
console.log "Creating user #{_login}"
login = _login
getLogin: ->
login
setLogin: (val) ->
login = val |
[
{
"context": "wUlwT6tHrC0PmYda73KzAzQ0eSoFbIi6WV'\n PARSE_KEY: 'slNZDFWnonWXkam1XjTRhSqE0fwdJo111cEjZ2lm'\n PARSE_CLASS: 'WiFi'\n initParse: -> Parse.init",
"end": 1180,
"score": 0.9997774958610535,
"start": 1140,
"tag": "KEY",
"value": "slNZDFWnonWXkam1XjTRhSqE0fwdJo111cEjZ2lm"
}
] | main.coffee | arcestia/net-test-tool | 0 | 'use strict'
spinner = require 'elegant-spinner'
{Parse} = require 'parse/node'
{exec} = require 'child_process'
logger = require 'log-update'
async = require 'async'
chalk = require 'chalk'
meow = require 'meow'
os = require 'os'
Net = require './NetCore'
prefix = switch os.platform()
when 'darwin' then 'mac'
when 'linux' then null
when 'win32' then null
else null
if prefix is null
console.log chalk.red [
''
' Your operating system is currently not supported. PRs welcome at https://goo.gl/clvSD4'
''
].join '\n'
process.exit 1
Ssid = require "./#{prefix}/Ssid"
try
Ssid2 = require "./#{prefix}/SsidFallback"
Geo = require "./#{prefix}/Geo"
try Geo2 = require "./#{prefix}/GeoFallback"
catch ignore
try Geo2 = require './GeoFallbackCore'
tap = (o, fn) -> fn(o); o
merge = (xs...) ->
if xs?.length > 0
tap {}, (m) -> m[k] = v for k, v of x for x in xs
cli = meow
help: [
'Usage'
' $ net-test'
''
'Options'
' --no-parse Skip uploading results to parse'
''
]
class Test
PARSE_ID: '5mhCAqwUlwT6tHrC0PmYda73KzAzQ0eSoFbIi6WV'
PARSE_KEY: 'slNZDFWnonWXkam1XjTRhSqE0fwdJo111cEjZ2lm'
PARSE_CLASS: 'WiFi'
initParse: -> Parse.initialize @PARSE_ID, @PARSE_KEY
constructor: ->
@startTime = +new Date
@initParse()
@ssid = new Ssid Ssid2
@geo = new Geo Geo2
@net = new Net()
@intervalId = setInterval @render, 50
async.parallel
net: @net.exec
geo: @geo.exec
ssid: @ssid.exec
, @results
processForParse: (obj) ->
geoPoint = new Parse.GeoPoint
latitude: obj.lat
longitude: obj.lng
ssid: obj.ssid
download: obj.download
upload: obj.upload
ping: obj.ping
open: obj.open
channel: obj.channel
location: geoPoint
locationUrl: obj.url
ts: obj.ts
runtime: obj.runtime
uploadResults: (obj) ->
@parseFrame = spinner()
parseIntervalId = setInterval @renderParse, 50
WiFi = Parse.Object.extend 'WiFi'
wiFi = new WiFi()
wiFi.save @processForParse(obj),
success: (response) =>
clearInterval parseIntervalId
@renderParse response.id
error: (something, err) =>
console.log 'error', something, err
clearInterval parseIntervalId
results: (err, res) =>
clearInterval @intervalId
@render()
if err
console.error chalk.red [
''
' Some of the required tests have failed. Try again later or quickly reinstall your system.'
''
].join '\n'
return
final = merge res.net, res.geo, res.ssid
final.ts = Date()
final.runTime = +new Date - @startTime
console.log "\nResults: #{JSON.stringify(final, null, ' ')}\n"
unless cli.flags.parse is false
console.log "\n\n\n\n"
@uploadResults final
render: =>
logger [
''
' SSID: ' + @ssid.getStatus()
' location: ' + @geo.getStatus()
' speed: ' + @net.getStatus()
].join '\n'
renderParse: (id=null) =>
status = if id isnt null
chalk.green('done') + chalk.gray " (id: #{id})"
else
chalk.magenta @parseFrame()
logger chalk.bold('Uploading results to Parse: ') + status + '\n'
new Test()
| 62469 | 'use strict'
spinner = require 'elegant-spinner'
{Parse} = require 'parse/node'
{exec} = require 'child_process'
logger = require 'log-update'
async = require 'async'
chalk = require 'chalk'
meow = require 'meow'
os = require 'os'
Net = require './NetCore'
prefix = switch os.platform()
when 'darwin' then 'mac'
when 'linux' then null
when 'win32' then null
else null
if prefix is null
console.log chalk.red [
''
' Your operating system is currently not supported. PRs welcome at https://goo.gl/clvSD4'
''
].join '\n'
process.exit 1
Ssid = require "./#{prefix}/Ssid"
try
Ssid2 = require "./#{prefix}/SsidFallback"
Geo = require "./#{prefix}/Geo"
try Geo2 = require "./#{prefix}/GeoFallback"
catch ignore
try Geo2 = require './GeoFallbackCore'
tap = (o, fn) -> fn(o); o
merge = (xs...) ->
if xs?.length > 0
tap {}, (m) -> m[k] = v for k, v of x for x in xs
cli = meow
help: [
'Usage'
' $ net-test'
''
'Options'
' --no-parse Skip uploading results to parse'
''
]
class Test
PARSE_ID: '5mhCAqwUlwT6tHrC0PmYda73KzAzQ0eSoFbIi6WV'
PARSE_KEY: '<KEY>'
PARSE_CLASS: 'WiFi'
initParse: -> Parse.initialize @PARSE_ID, @PARSE_KEY
constructor: ->
@startTime = +new Date
@initParse()
@ssid = new Ssid Ssid2
@geo = new Geo Geo2
@net = new Net()
@intervalId = setInterval @render, 50
async.parallel
net: @net.exec
geo: @geo.exec
ssid: @ssid.exec
, @results
processForParse: (obj) ->
geoPoint = new Parse.GeoPoint
latitude: obj.lat
longitude: obj.lng
ssid: obj.ssid
download: obj.download
upload: obj.upload
ping: obj.ping
open: obj.open
channel: obj.channel
location: geoPoint
locationUrl: obj.url
ts: obj.ts
runtime: obj.runtime
uploadResults: (obj) ->
@parseFrame = spinner()
parseIntervalId = setInterval @renderParse, 50
WiFi = Parse.Object.extend 'WiFi'
wiFi = new WiFi()
wiFi.save @processForParse(obj),
success: (response) =>
clearInterval parseIntervalId
@renderParse response.id
error: (something, err) =>
console.log 'error', something, err
clearInterval parseIntervalId
results: (err, res) =>
clearInterval @intervalId
@render()
if err
console.error chalk.red [
''
' Some of the required tests have failed. Try again later or quickly reinstall your system.'
''
].join '\n'
return
final = merge res.net, res.geo, res.ssid
final.ts = Date()
final.runTime = +new Date - @startTime
console.log "\nResults: #{JSON.stringify(final, null, ' ')}\n"
unless cli.flags.parse is false
console.log "\n\n\n\n"
@uploadResults final
render: =>
logger [
''
' SSID: ' + @ssid.getStatus()
' location: ' + @geo.getStatus()
' speed: ' + @net.getStatus()
].join '\n'
renderParse: (id=null) =>
status = if id isnt null
chalk.green('done') + chalk.gray " (id: #{id})"
else
chalk.magenta @parseFrame()
logger chalk.bold('Uploading results to Parse: ') + status + '\n'
new Test()
| true | 'use strict'
spinner = require 'elegant-spinner'
{Parse} = require 'parse/node'
{exec} = require 'child_process'
logger = require 'log-update'
async = require 'async'
chalk = require 'chalk'
meow = require 'meow'
os = require 'os'
Net = require './NetCore'
prefix = switch os.platform()
when 'darwin' then 'mac'
when 'linux' then null
when 'win32' then null
else null
if prefix is null
console.log chalk.red [
''
' Your operating system is currently not supported. PRs welcome at https://goo.gl/clvSD4'
''
].join '\n'
process.exit 1
Ssid = require "./#{prefix}/Ssid"
try
Ssid2 = require "./#{prefix}/SsidFallback"
Geo = require "./#{prefix}/Geo"
try Geo2 = require "./#{prefix}/GeoFallback"
catch ignore
try Geo2 = require './GeoFallbackCore'
tap = (o, fn) -> fn(o); o
merge = (xs...) ->
if xs?.length > 0
tap {}, (m) -> m[k] = v for k, v of x for x in xs
cli = meow
help: [
'Usage'
' $ net-test'
''
'Options'
' --no-parse Skip uploading results to parse'
''
]
class Test
PARSE_ID: '5mhCAqwUlwT6tHrC0PmYda73KzAzQ0eSoFbIi6WV'
PARSE_KEY: 'PI:KEY:<KEY>END_PI'
PARSE_CLASS: 'WiFi'
initParse: -> Parse.initialize @PARSE_ID, @PARSE_KEY
constructor: ->
@startTime = +new Date
@initParse()
@ssid = new Ssid Ssid2
@geo = new Geo Geo2
@net = new Net()
@intervalId = setInterval @render, 50
async.parallel
net: @net.exec
geo: @geo.exec
ssid: @ssid.exec
, @results
processForParse: (obj) ->
geoPoint = new Parse.GeoPoint
latitude: obj.lat
longitude: obj.lng
ssid: obj.ssid
download: obj.download
upload: obj.upload
ping: obj.ping
open: obj.open
channel: obj.channel
location: geoPoint
locationUrl: obj.url
ts: obj.ts
runtime: obj.runtime
uploadResults: (obj) ->
@parseFrame = spinner()
parseIntervalId = setInterval @renderParse, 50
WiFi = Parse.Object.extend 'WiFi'
wiFi = new WiFi()
wiFi.save @processForParse(obj),
success: (response) =>
clearInterval parseIntervalId
@renderParse response.id
error: (something, err) =>
console.log 'error', something, err
clearInterval parseIntervalId
results: (err, res) =>
clearInterval @intervalId
@render()
if err
console.error chalk.red [
''
' Some of the required tests have failed. Try again later or quickly reinstall your system.'
''
].join '\n'
return
final = merge res.net, res.geo, res.ssid
final.ts = Date()
final.runTime = +new Date - @startTime
console.log "\nResults: #{JSON.stringify(final, null, ' ')}\n"
unless cli.flags.parse is false
console.log "\n\n\n\n"
@uploadResults final
render: =>
logger [
''
' SSID: ' + @ssid.getStatus()
' location: ' + @geo.getStatus()
' speed: ' + @net.getStatus()
].join '\n'
renderParse: (id=null) =>
status = if id isnt null
chalk.green('done') + chalk.gray " (id: #{id})"
else
chalk.magenta @parseFrame()
logger chalk.bold('Uploading results to Parse: ') + status + '\n'
new Test()
|
[
{
"context": "enMatches [\n# \tcommand: 'foo'\n# \twhen:\n# \t\tname: 'john'\n# ,\n# \tcommand: 'bar'\n# \twhen:\n# \t\tname: 'jane'\n",
"end": 1025,
"score": 0.9998459815979004,
"start": 1021,
"tag": "NAME",
"value": "john"
},
{
"context": " 'john'\n# ,\n# \tcommand: 'bar'\n# \twhen:\n# \t\tname: 'jane'\n# ],\n# \tname: 'john'\n###\nexports.filterWhenMatch",
"end": 1073,
"score": 0.9606499671936035,
"start": 1069,
"tag": "NAME",
"value": "jane"
},
{
"context": "d: 'bar'\n# \twhen:\n# \t\tname: 'jane'\n# ],\n# \tname: 'john'\n###\nexports.filterWhenMatches = (operations, opt",
"end": 1094,
"score": 0.99985271692276,
"start": 1090,
"tag": "NAME",
"value": "john"
}
] | lib/utils.coffee | resin-io/resin-devices-operations | 2 | ###
Copyright 2016 Resin.io
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.
###
os = require('os')
_ = require('lodash')
###*
# @summary Filter operations based on when properties
# @function
# @protected
#
# @description
# This function discards the operations that don't match given certain options.
#
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {Object[]} filtered operations
#
# @example
# operations = utils.filterWhenMatches [
# command: 'foo'
# when:
# name: 'john'
# ,
# command: 'bar'
# when:
# name: 'jane'
# ],
# name: 'john'
###
exports.filterWhenMatches = (operations, options = {}) ->
return _.filter operations, (operation) ->
return _.isMatch(options, operation.when)
###*
# @summary Get missing options from operations `when` properties
# @function
# @protected
#
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {String[]} missing options
#
# @example
# missingOptions = utils.getMissingOptions [
# command: 'foo'
# when:
# foo: 1
# ],
# bar: 2
#
# console.log(missingOptions)
# > [ 'foo' ]
###
exports.getMissingOptions = (operations, options = {}) ->
usedOptions = _.flatten(
_.map(
_.map(operations, 'when'),
_.keys
)
)
return _.uniq(_.difference(usedOptions, _.keys(options)))
###*
# @summary Get operating system
# @function
# @protected
#
# @returns {String} operating system
#
# @example
# os = utils.getOperatingSystem()
###
exports.getOperatingSystem = ->
platform = os.platform()
switch platform
when 'darwin' then 'osx'
else platform
| 85289 | ###
Copyright 2016 Resin.io
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.
###
os = require('os')
_ = require('lodash')
###*
# @summary Filter operations based on when properties
# @function
# @protected
#
# @description
# This function discards the operations that don't match given certain options.
#
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {Object[]} filtered operations
#
# @example
# operations = utils.filterWhenMatches [
# command: 'foo'
# when:
# name: '<NAME>'
# ,
# command: 'bar'
# when:
# name: '<NAME>'
# ],
# name: '<NAME>'
###
exports.filterWhenMatches = (operations, options = {}) ->
return _.filter operations, (operation) ->
return _.isMatch(options, operation.when)
###*
# @summary Get missing options from operations `when` properties
# @function
# @protected
#
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {String[]} missing options
#
# @example
# missingOptions = utils.getMissingOptions [
# command: 'foo'
# when:
# foo: 1
# ],
# bar: 2
#
# console.log(missingOptions)
# > [ 'foo' ]
###
exports.getMissingOptions = (operations, options = {}) ->
usedOptions = _.flatten(
_.map(
_.map(operations, 'when'),
_.keys
)
)
return _.uniq(_.difference(usedOptions, _.keys(options)))
###*
# @summary Get operating system
# @function
# @protected
#
# @returns {String} operating system
#
# @example
# os = utils.getOperatingSystem()
###
exports.getOperatingSystem = ->
platform = os.platform()
switch platform
when 'darwin' then 'osx'
else platform
| true | ###
Copyright 2016 Resin.io
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.
###
os = require('os')
_ = require('lodash')
###*
# @summary Filter operations based on when properties
# @function
# @protected
#
# @description
# This function discards the operations that don't match given certain options.
#
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {Object[]} filtered operations
#
# @example
# operations = utils.filterWhenMatches [
# command: 'foo'
# when:
# name: 'PI:NAME:<NAME>END_PI'
# ,
# command: 'bar'
# when:
# name: 'PI:NAME:<NAME>END_PI'
# ],
# name: 'PI:NAME:<NAME>END_PI'
###
exports.filterWhenMatches = (operations, options = {}) ->
return _.filter operations, (operation) ->
return _.isMatch(options, operation.when)
###*
# @summary Get missing options from operations `when` properties
# @function
# @protected
#
# @param {Object[]} operations - array of operations
# @param {Object} options - configuration options
#
# @returns {String[]} missing options
#
# @example
# missingOptions = utils.getMissingOptions [
# command: 'foo'
# when:
# foo: 1
# ],
# bar: 2
#
# console.log(missingOptions)
# > [ 'foo' ]
###
exports.getMissingOptions = (operations, options = {}) ->
usedOptions = _.flatten(
_.map(
_.map(operations, 'when'),
_.keys
)
)
return _.uniq(_.difference(usedOptions, _.keys(options)))
###*
# @summary Get operating system
# @function
# @protected
#
# @returns {String} operating system
#
# @example
# os = utils.getOperatingSystem()
###
exports.getOperatingSystem = ->
platform = os.platform()
switch platform
when 'darwin' then 'osx'
else platform
|
[
{
"context": "#version up\n config.setPasswordHash 2,\"md5\"\n user2=config.create \"id2\"\n ",
"end": 982,
"score": 0.9980154633522034,
"start": 979,
"tag": "PASSWORD",
"value": "md5"
},
{
"context": " \"hogehoge\"\n\n user.setData {},\"passwordv2\"\n\n assert.strictEqual user.salt,\"hogeh",
"end": 1701,
"score": 0.9990140795707703,
"start": 1691,
"tag": "PASSWORD",
"value": "passwordv2"
},
{
"context": "d\"\n\n assert.strictEqual user.password,\"saltpassword\"\n\n it 'partial upgrading',->\n c",
"end": 2075,
"score": 0.9992443919181824,
"start": 2063,
"tag": "PASSWORD",
"value": "saltpassword"
},
{
"context": "o\"\n\n assert.strictEqual user.password,\"saltfoo\"\n\n # set without changing password\n ",
"end": 2377,
"score": 0.9995317459106445,
"start": 2370,
"tag": "PASSWORD",
"value": "saltfoo"
},
{
"context": "3}\n\n assert.strictEqual user.password,\"saltfoo\"\n\n config.setPasswordHash 2,(salt,pass",
"end": 2511,
"score": 0.999518871307373,
"start": 2504,
"tag": "PASSWORD",
"value": "saltfoo"
},
{
"context": " \n assert.strictEqual user.password,\"saltbarbar\"\n\n describe 'user data',->\n config=null",
"end": 3296,
"score": 0.9995105266571045,
"start": 3286,
"tag": "PASSWORD",
"value": "saltbarbar"
},
{
"context": " piyo: '吉野家'\n user.setData data,\"password\"\n\n assert.deepEqual user.getData(),{\n ",
"end": 3640,
"score": 0.9660353064537048,
"start": 3632,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " foo: \"bar\"\n user.setData data, \"password\"\n\n assert data == user.getData()\n ",
"end": 3979,
"score": 0.9355893731117249,
"start": 3971,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " foo: \"bar\"\n user.setData data, \"password\"\n\n assert not Object.isFrozen user.get",
"end": 4192,
"score": 0.7522216439247131,
"start": 4184,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " piyo: '吉野家'\n user.setData data, \"password\"\n\n assert data != user.getData()\n ",
"end": 4513,
"score": 0.9522299766540527,
"start": 4505,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "nticate',->\n config.setPasswordHash 1,\"sha256\"\n user=config.create()\n use",
"end": 5840,
"score": 0.9972143173217773,
"start": 5834,
"tag": "PASSWORD",
"value": "sha256"
},
{
"context": "ltpassword\" | sha256sum\n password:\"13601bda4ea78e55a07b98866d2be6be0744e3866f13c00c811cab608a28f322\"\n }\n\n assert user.auth \"pas",
"end": 6104,
"score": 0.9994562864303589,
"start": 6040,
"tag": "PASSWORD",
"value": "13601bda4ea78e55a07b98866d2be6be0744e3866f13c00c811cab608a28f322"
}
] | test/user-object.coffee | uhyo/my-user | 0 | assert=require 'assert'
my_user=require '../dist/index'
describe 'User object',->
describe 'authenticate & versioning',->
config=null
beforeEach ->
config=my_user.init()
it 'user id',->
user=config.create "id"
assert.strictEqual user.id,"id"
it 'default user version',->
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.version,0
it 'default authenticats',->
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.auth("foobar"),false,"wrong password"
assert.strictEqual user.auth("password"),true,"correct password"
it 'user versioning',->
config.setSalt 1,16
user=config.create "id"
user.setData {},"foo"
assert.strictEqual user.version,1
#version up
config.setPasswordHash 2,"md5"
user2=config.create "id2"
user2.setData {},"bar"
assert.strictEqual user2.version,2
#version up
user.setData {},"baz"
assert.strictEqual user.version,2
#version down
user2.setData {},"foo",1
assert.strictEqual user2.version,1
it 'user-defined salt',->
config.setSalt 1,->
# static salt
"foobar"
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.salt,"foobar"
config.setSalt 2,->
# version up
"hogehoge"
user.setData {},"passwordv2"
assert.strictEqual user.salt,"hogehoge"
it 'user-defined passwordhash',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.password,"saltpassword"
it 'partial upgrading',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"foo"
assert.strictEqual user.password,"saltfoo"
# set without changing password
user.setData {foo:3}
assert.strictEqual user.password,"saltfoo"
config.setPasswordHash 2,(salt,password)->
salt+password+password
# still version 1
assert.strictEqual user.version,1
# can't upgrade without changing password
assert.throws ->
user.setData {bar:5}
it 'partial upgrading 2',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"foo"
config.setPasswordHash 2,(salt,password)->
salt+password+password
# upgrade user
user.setData {foo:3},"bar"
assert.strictEqual user.password,"saltbarbar"
describe 'user data',->
config=null
beforeEach ->
config=my_user.init()
it 'save & store data',->
user=config.create "id"
data=
foo: "bar"
baz:
a: -500
piyo: '吉野家'
user.setData data,"password"
assert.deepEqual user.getData(),{
foo: "bar"
baz:
a: -500
piyo: '吉野家'
}
it 'data is not copied by default', ->
user=config.create "id"
data=
foo: "bar"
user.setData data, "password"
assert data == user.getData()
it 'data is not frozen by default', ->
user=config.create "id"
data=
foo: "bar"
user.setData data, "password"
assert not Object.isFrozen user.getData()
it 'data deepcopy option', ->
config = my_user.init {deepcopy: true}
user=config.create "id"
data=
foo: "bar"
baz:
piyo: '吉野家'
user.setData data, "password"
assert data != user.getData()
assert data.baz != user.getData().bax
it 'data is frozen',->
config = my_user.init {freeze:true}
user=config.create "id"
user.setData {},"password"
assert Object.isFrozen user.getData()
it 'clones data',->
config = my_user.init {deepcopy:true}
user=config.create "id"
data=
foo: "bar"
baz: -500
user.setData data,"password"
# modify
data.quux="a"
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
}
user.setData data
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
quux: "a"
}
it 'loads data',->
user=config.create()
user.loadRawData {
id:"id"
data:
foo: "bar"
baz: -500
}
assert.deepEqual user.id,"id"
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
}
it 'load raw & authenticate',->
config.setPasswordHash 1,"sha256"
user=config.create()
user.loadRawData {
version: 1
salt:"salt"
# echo -n "saltpassword" | sha256sum
password:"13601bda4ea78e55a07b98866d2be6be0744e3866f13c00c811cab608a28f322"
}
assert user.auth "password"
it 'write data',->
user=config.create()
user.setData {
foo: "bar"
baz: 10
}
user.writeData {
hoge: "piyo"
}
assert.deepEqual user.getData(),{
foo: "bar"
baz: 10
hoge: "piyo"
}
it 'write data doesn\'t change user version',->
config.setSalt 1,->"salt1"
config.setSalt 2,->"salt2"
user=config.create()
user.setData {
foo: "bar"
},"password",1
assert.strictEqual user.version,1
user.writeData {
foo: "baz"
}
assert.deepEqual user.getData(),{
foo: "baz"
}
assert.strictEqual user.version,1
| 40976 | assert=require 'assert'
my_user=require '../dist/index'
describe 'User object',->
describe 'authenticate & versioning',->
config=null
beforeEach ->
config=my_user.init()
it 'user id',->
user=config.create "id"
assert.strictEqual user.id,"id"
it 'default user version',->
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.version,0
it 'default authenticats',->
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.auth("foobar"),false,"wrong password"
assert.strictEqual user.auth("password"),true,"correct password"
it 'user versioning',->
config.setSalt 1,16
user=config.create "id"
user.setData {},"foo"
assert.strictEqual user.version,1
#version up
config.setPasswordHash 2,"<PASSWORD>"
user2=config.create "id2"
user2.setData {},"bar"
assert.strictEqual user2.version,2
#version up
user.setData {},"baz"
assert.strictEqual user.version,2
#version down
user2.setData {},"foo",1
assert.strictEqual user2.version,1
it 'user-defined salt',->
config.setSalt 1,->
# static salt
"foobar"
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.salt,"foobar"
config.setSalt 2,->
# version up
"hogehoge"
user.setData {},"<PASSWORD>"
assert.strictEqual user.salt,"hogehoge"
it 'user-defined passwordhash',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.password,"<PASSWORD>"
it 'partial upgrading',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"foo"
assert.strictEqual user.password,"<PASSWORD>"
# set without changing password
user.setData {foo:3}
assert.strictEqual user.password,"<PASSWORD>"
config.setPasswordHash 2,(salt,password)->
salt+password+password
# still version 1
assert.strictEqual user.version,1
# can't upgrade without changing password
assert.throws ->
user.setData {bar:5}
it 'partial upgrading 2',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"foo"
config.setPasswordHash 2,(salt,password)->
salt+password+password
# upgrade user
user.setData {foo:3},"bar"
assert.strictEqual user.password,"<PASSWORD>"
describe 'user data',->
config=null
beforeEach ->
config=my_user.init()
it 'save & store data',->
user=config.create "id"
data=
foo: "bar"
baz:
a: -500
piyo: '吉野家'
user.setData data,"<PASSWORD>"
assert.deepEqual user.getData(),{
foo: "bar"
baz:
a: -500
piyo: '吉野家'
}
it 'data is not copied by default', ->
user=config.create "id"
data=
foo: "bar"
user.setData data, "<PASSWORD>"
assert data == user.getData()
it 'data is not frozen by default', ->
user=config.create "id"
data=
foo: "bar"
user.setData data, "<PASSWORD>"
assert not Object.isFrozen user.getData()
it 'data deepcopy option', ->
config = my_user.init {deepcopy: true}
user=config.create "id"
data=
foo: "bar"
baz:
piyo: '吉野家'
user.setData data, "<PASSWORD>"
assert data != user.getData()
assert data.baz != user.getData().bax
it 'data is frozen',->
config = my_user.init {freeze:true}
user=config.create "id"
user.setData {},"password"
assert Object.isFrozen user.getData()
it 'clones data',->
config = my_user.init {deepcopy:true}
user=config.create "id"
data=
foo: "bar"
baz: -500
user.setData data,"password"
# modify
data.quux="a"
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
}
user.setData data
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
quux: "a"
}
it 'loads data',->
user=config.create()
user.loadRawData {
id:"id"
data:
foo: "bar"
baz: -500
}
assert.deepEqual user.id,"id"
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
}
it 'load raw & authenticate',->
config.setPasswordHash 1,"<PASSWORD>"
user=config.create()
user.loadRawData {
version: 1
salt:"salt"
# echo -n "saltpassword" | sha256sum
password:"<PASSWORD>"
}
assert user.auth "password"
it 'write data',->
user=config.create()
user.setData {
foo: "bar"
baz: 10
}
user.writeData {
hoge: "piyo"
}
assert.deepEqual user.getData(),{
foo: "bar"
baz: 10
hoge: "piyo"
}
it 'write data doesn\'t change user version',->
config.setSalt 1,->"salt1"
config.setSalt 2,->"salt2"
user=config.create()
user.setData {
foo: "bar"
},"password",1
assert.strictEqual user.version,1
user.writeData {
foo: "baz"
}
assert.deepEqual user.getData(),{
foo: "baz"
}
assert.strictEqual user.version,1
| true | assert=require 'assert'
my_user=require '../dist/index'
describe 'User object',->
describe 'authenticate & versioning',->
config=null
beforeEach ->
config=my_user.init()
it 'user id',->
user=config.create "id"
assert.strictEqual user.id,"id"
it 'default user version',->
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.version,0
it 'default authenticats',->
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.auth("foobar"),false,"wrong password"
assert.strictEqual user.auth("password"),true,"correct password"
it 'user versioning',->
config.setSalt 1,16
user=config.create "id"
user.setData {},"foo"
assert.strictEqual user.version,1
#version up
config.setPasswordHash 2,"PI:PASSWORD:<PASSWORD>END_PI"
user2=config.create "id2"
user2.setData {},"bar"
assert.strictEqual user2.version,2
#version up
user.setData {},"baz"
assert.strictEqual user.version,2
#version down
user2.setData {},"foo",1
assert.strictEqual user2.version,1
it 'user-defined salt',->
config.setSalt 1,->
# static salt
"foobar"
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.salt,"foobar"
config.setSalt 2,->
# version up
"hogehoge"
user.setData {},"PI:PASSWORD:<PASSWORD>END_PI"
assert.strictEqual user.salt,"hogehoge"
it 'user-defined passwordhash',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"password"
assert.strictEqual user.password,"PI:PASSWORD:<PASSWORD>END_PI"
it 'partial upgrading',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"foo"
assert.strictEqual user.password,"PI:PASSWORD:<PASSWORD>END_PI"
# set without changing password
user.setData {foo:3}
assert.strictEqual user.password,"PI:PASSWORD:<PASSWORD>END_PI"
config.setPasswordHash 2,(salt,password)->
salt+password+password
# still version 1
assert.strictEqual user.version,1
# can't upgrade without changing password
assert.throws ->
user.setData {bar:5}
it 'partial upgrading 2',->
config.setSalt 1,->
"salt"
config.setPasswordHash 1,(salt,password)->
salt+password
user=config.create "id"
user.setData {},"foo"
config.setPasswordHash 2,(salt,password)->
salt+password+password
# upgrade user
user.setData {foo:3},"bar"
assert.strictEqual user.password,"PI:PASSWORD:<PASSWORD>END_PI"
describe 'user data',->
config=null
beforeEach ->
config=my_user.init()
it 'save & store data',->
user=config.create "id"
data=
foo: "bar"
baz:
a: -500
piyo: '吉野家'
user.setData data,"PI:PASSWORD:<PASSWORD>END_PI"
assert.deepEqual user.getData(),{
foo: "bar"
baz:
a: -500
piyo: '吉野家'
}
it 'data is not copied by default', ->
user=config.create "id"
data=
foo: "bar"
user.setData data, "PI:PASSWORD:<PASSWORD>END_PI"
assert data == user.getData()
it 'data is not frozen by default', ->
user=config.create "id"
data=
foo: "bar"
user.setData data, "PI:PASSWORD:<PASSWORD>END_PI"
assert not Object.isFrozen user.getData()
it 'data deepcopy option', ->
config = my_user.init {deepcopy: true}
user=config.create "id"
data=
foo: "bar"
baz:
piyo: '吉野家'
user.setData data, "PI:PASSWORD:<PASSWORD>END_PI"
assert data != user.getData()
assert data.baz != user.getData().bax
it 'data is frozen',->
config = my_user.init {freeze:true}
user=config.create "id"
user.setData {},"password"
assert Object.isFrozen user.getData()
it 'clones data',->
config = my_user.init {deepcopy:true}
user=config.create "id"
data=
foo: "bar"
baz: -500
user.setData data,"password"
# modify
data.quux="a"
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
}
user.setData data
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
quux: "a"
}
it 'loads data',->
user=config.create()
user.loadRawData {
id:"id"
data:
foo: "bar"
baz: -500
}
assert.deepEqual user.id,"id"
assert.deepEqual user.getData(),{
foo: "bar"
baz: -500
}
it 'load raw & authenticate',->
config.setPasswordHash 1,"PI:PASSWORD:<PASSWORD>END_PI"
user=config.create()
user.loadRawData {
version: 1
salt:"salt"
# echo -n "saltpassword" | sha256sum
password:"PI:PASSWORD:<PASSWORD>END_PI"
}
assert user.auth "password"
it 'write data',->
user=config.create()
user.setData {
foo: "bar"
baz: 10
}
user.writeData {
hoge: "piyo"
}
assert.deepEqual user.getData(),{
foo: "bar"
baz: 10
hoge: "piyo"
}
it 'write data doesn\'t change user version',->
config.setSalt 1,->"salt1"
config.setSalt 2,->"salt2"
user=config.create()
user.setData {
foo: "bar"
},"password",1
assert.strictEqual user.version,1
user.writeData {
foo: "baz"
}
assert.deepEqual user.getData(),{
foo: "baz"
}
assert.strictEqual user.version,1
|
[
{
"context": "ernates.length > 1\n sayKey = require('./sayCounter').get()\n output.push \"#{indent}switch(pick",
"end": 6278,
"score": 0.5215761661529541,
"start": 6271,
"tag": "KEY",
"value": "Counter"
}
] | packages/litexa/src/parser/say.coffee | cheruvian/litexa | 34 | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
lib = module.exports.lib = {}
lib[k] = v for k, v of require('./sayVariableParts.coffee')
lib[k] = v for k, v of require('./sayTagParts.coffee')
lib[k] = v for k, v of require('./sayJavascriptParts.coffee')
lib[k] = v for k, v of require('./sayFlowControlParts.coffee')
{ parseFragment } = require('./parser.coffee')
{ ParserError } = require('./errors.coffee').lib
{ AssetName } = require('./assets.coffee').lib
{
replaceNewlineCharacters,
isEmptyContentString,
isFirstOrLastItemOfArray,
dedupeNonNewlineConsecutiveWhitespaces,
cleanTrailingSpaces,
cleanLeadingSpaces
} = require('./utils.coffee').lib
class lib.StringPart
constructor: (text) ->
# Whitespace and line break rules:
# line breaks are converted to whitespaces
# empty (or whitespace-only) lines are considered a line break
# consecutive whitespaces are condensed to a single whitespace
splitLines = text.split('\n')
lines = splitLines.map((str, idx) ->
return '\n' if isEmptyContentString(str) and !isFirstOrLastItemOfArray(idx, splitLines)
return str.trim() unless isFirstOrLastItemOfArray(idx, splitLines)
return dedupeNonNewlineConsecutiveWhitespaces(str)
)
@tagClosePos = null
if lines.length > 1
@tagClosePos = lines[0].length + 1
if lines[0] == '\n'
@tagClosePos += 1
@text = lines.join(' ')
transformations = [
cleanTrailingSpaces,
cleanLeadingSpaces,
dedupeNonNewlineConsecutiveWhitespaces
]
transformations.forEach((transformation) =>
@text = transformation(@text)
)
visit: (depth, fn) -> fn(depth, @)
isStringPart: true
toString: -> @text
toUtterance: -> [ @text.toLowerCase() ]
toLambda: (options) ->
# escape quotes
str = @text.replace(/"/g, '\"')
# escape line breaks
str = replaceNewlineCharacters(str, '\\n')
return '"' + str + '"'
express: (context) ->
return @text
toRegex: ->
str = @text
# escape regex control characters
str = str.replace( /\?/g, '\\?' )
str = str.replace( /\./g, '\\.' )
# mirror the line break handling for the lambda
str = replaceNewlineCharacters(str, '\\n')
"(#{str})"
toTestRegex: -> @toRegex()
toTestScore: -> return 10
toLocalization: ->
return @toString()
class lib.AssetNamePart
constructor: (@assetName) ->
isAssetNamePart: true
toString: -> return "<#{@assetName}>"
toUtterance: -> throw new ParserError @assetName.location, "can't use an asset name part in an utterance"
toLambda: (options) -> return @assetName.toSSML(options.language)
express: (context) -> return @toString()
toRegex: ->
return "(#{@toSSML()})"
toTestRegex: -> @toRegex()
toTestScore: -> return 10
partsToExpression = (parts, options) ->
unless parts?.length > 0
return "''"
result = []
tagContext = []
closeTags = ->
if tagContext.length == 0
return ''
closed = []
for tag in tagContext by -1
closed.push "</#{tag}>"
tagContext = []
'"' + closed.join('') + '"'
result = for p in parts
if p.open
tagContext.push p.tag
code = p.toLambda options
if p.tagClosePos?
closed = closeTags()
if closed
before = code[0...p.tagClosePos] + '"'
after = '"' + code[p.tagClosePos..]
code = [before, closed, after].join '+'
if p.needsEscaping
"escapeSpeech( #{code} )"
else
code
closed = closeTags()
if closed
result.push closed
result.join(' + ')
class lib.Say
constructor: (parts, skill) ->
@alternates = {
default: [ parts ]
}
@checkForTranslations(skill)
isSay: true
checkForTranslations: (skill) ->
# Check if the localization map exists and has an entry for this string.
localizationEntry = skill?.projectInfo?.localization?.speech?[@toString()]
if localizationEntry?
for language, translation of localizationEntry
# ignore the translation if it's empty
continue unless translation
# ignore the translation if it isn't for one of the skill languages (could just be comments)
continue unless Object.keys(skill.languages).includes(language)
alternates = translation.split('|') # alternates delineation character is '|'
for i in [0..alternates.length - 1]
# parse the translation to identify the string parts
fragment = """say "#{alternates[i]}" """
parsedTranslation = null
try
parsedTranslation = parseFragment(fragment, language)
catch err
throw new Error("Failed to parse the following fragment translated for #{language}:\n#{fragment}\n#{err}")
if i == 0
# first (and potentially only) alternate
@alternates[language] = parsedTranslation.alternates.default
else
# split by '|' returned more than one string -> this is an 'or' alternate
@alternates[language].push(parsedTranslation.alternates.default[0])
pushAlternate: (location, parts, skill, language = 'default') ->
@alternates[language].push parts
# re-check localization since alternates are combined into single key as follows:
# "speech|alternate one|alternate two"
@checkForTranslations(skill)
toString: (language = 'default') ->
switch @alternates[language].length
when 0 then return ''
when 1
return (p.toString() for p in @alternates[language][0]).join('')
else
return (a.join('').toString() for a in @alternates[language]).join('|')
toExpression: (options, language = 'default') ->
partsToExpression @alternates[language][0], options
toLambda: (output, indent, options) ->
speechTargets = ["say"]
if @isReprompt
speechTargets = [ "reprompt" ]
else if @isAlsoReprompt
speechTargets = speechTargets.concat "reprompt"
writeAlternates = (indent, alternates) ->
if alternates.length > 1
sayKey = require('./sayCounter').get()
output.push "#{indent}switch(pickSayString(context, #{sayKey}, #{alternates.length})) {"
for alt, idx in alternates
if idx == alternates.length - 1
output.push "#{indent} default:"
else
output.push "#{indent} case #{idx}:"
writeLine indent + " ", alt
output.push "#{indent} break;"
output.push "#{indent}}"
else
writeLine indent, alternates[0]
writeLine = (indent, parts) ->
line = partsToExpression(parts, options)
for target in speechTargets
if line and line != '""'
output.push "#{indent}context.#{target}.push( (#{line}).trim().replace(/ +/g,' ') );"
# Add language-specific output speech to the Lambda, if translations exist.
alternates = @alternates[options.language] ? @alternates.default
writeAlternates(indent, alternates)
express: (context) ->
# given the info in the context, fully resolve the parts
if @alternates[context.language]?
(p.express(context) for p in @alternates[context.language][0]).join("")
else
(p.express(context) for p in @alternates.default[0]).join("")
matchFragment: (language, line, testLine) ->
for parts in @alternates.default
unless parts.regex?
regexText = ( p.toTestRegex() for p in parts ).join('')
# prefixed with any number of spaces to eat formatting
# adjustments with fragments are combined in the skill
parts.regex = new RegExp("\\s*" + regexText, '')
match = parts.regex.exec(line)
continue unless match?
continue unless match[0].length > 0
result =
offset: match.index
reduced: line.replace parts.regex, ''
part: @
removed: match[0]
slots: {}
dbs: {}
for read, idx in match[1..]
part = parts[idx]
if part?.isSlot
result.slots[part.name] = read
if part?.isDB
result.dbs[part.name] = read
return result
return null
toLocalization: (localization) ->
collectParts = (parts) ->
locParts = []
for p in parts when p.toLocalization?
fragment = p.toLocalization(localization)
locParts.push fragment if fragment?
locParts.join ''
switch @alternates.default.length
when 0 then return
when 1
speech = collectParts(@alternates.default[0])
unless localization.speech[speech]?
localization.speech[speech] = {}
else
speeches = ( collectParts(a) for a in @alternates.default )
speeches = speeches.join('|')
unless localization.speech[speeches]?
localization.speech[speeches] = {}
| 80392 | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
lib = module.exports.lib = {}
lib[k] = v for k, v of require('./sayVariableParts.coffee')
lib[k] = v for k, v of require('./sayTagParts.coffee')
lib[k] = v for k, v of require('./sayJavascriptParts.coffee')
lib[k] = v for k, v of require('./sayFlowControlParts.coffee')
{ parseFragment } = require('./parser.coffee')
{ ParserError } = require('./errors.coffee').lib
{ AssetName } = require('./assets.coffee').lib
{
replaceNewlineCharacters,
isEmptyContentString,
isFirstOrLastItemOfArray,
dedupeNonNewlineConsecutiveWhitespaces,
cleanTrailingSpaces,
cleanLeadingSpaces
} = require('./utils.coffee').lib
class lib.StringPart
constructor: (text) ->
# Whitespace and line break rules:
# line breaks are converted to whitespaces
# empty (or whitespace-only) lines are considered a line break
# consecutive whitespaces are condensed to a single whitespace
splitLines = text.split('\n')
lines = splitLines.map((str, idx) ->
return '\n' if isEmptyContentString(str) and !isFirstOrLastItemOfArray(idx, splitLines)
return str.trim() unless isFirstOrLastItemOfArray(idx, splitLines)
return dedupeNonNewlineConsecutiveWhitespaces(str)
)
@tagClosePos = null
if lines.length > 1
@tagClosePos = lines[0].length + 1
if lines[0] == '\n'
@tagClosePos += 1
@text = lines.join(' ')
transformations = [
cleanTrailingSpaces,
cleanLeadingSpaces,
dedupeNonNewlineConsecutiveWhitespaces
]
transformations.forEach((transformation) =>
@text = transformation(@text)
)
visit: (depth, fn) -> fn(depth, @)
isStringPart: true
toString: -> @text
toUtterance: -> [ @text.toLowerCase() ]
toLambda: (options) ->
# escape quotes
str = @text.replace(/"/g, '\"')
# escape line breaks
str = replaceNewlineCharacters(str, '\\n')
return '"' + str + '"'
express: (context) ->
return @text
toRegex: ->
str = @text
# escape regex control characters
str = str.replace( /\?/g, '\\?' )
str = str.replace( /\./g, '\\.' )
# mirror the line break handling for the lambda
str = replaceNewlineCharacters(str, '\\n')
"(#{str})"
toTestRegex: -> @toRegex()
toTestScore: -> return 10
toLocalization: ->
return @toString()
class lib.AssetNamePart
constructor: (@assetName) ->
isAssetNamePart: true
toString: -> return "<#{@assetName}>"
toUtterance: -> throw new ParserError @assetName.location, "can't use an asset name part in an utterance"
toLambda: (options) -> return @assetName.toSSML(options.language)
express: (context) -> return @toString()
toRegex: ->
return "(#{@toSSML()})"
toTestRegex: -> @toRegex()
toTestScore: -> return 10
partsToExpression = (parts, options) ->
unless parts?.length > 0
return "''"
result = []
tagContext = []
closeTags = ->
if tagContext.length == 0
return ''
closed = []
for tag in tagContext by -1
closed.push "</#{tag}>"
tagContext = []
'"' + closed.join('') + '"'
result = for p in parts
if p.open
tagContext.push p.tag
code = p.toLambda options
if p.tagClosePos?
closed = closeTags()
if closed
before = code[0...p.tagClosePos] + '"'
after = '"' + code[p.tagClosePos..]
code = [before, closed, after].join '+'
if p.needsEscaping
"escapeSpeech( #{code} )"
else
code
closed = closeTags()
if closed
result.push closed
result.join(' + ')
class lib.Say
constructor: (parts, skill) ->
@alternates = {
default: [ parts ]
}
@checkForTranslations(skill)
isSay: true
checkForTranslations: (skill) ->
# Check if the localization map exists and has an entry for this string.
localizationEntry = skill?.projectInfo?.localization?.speech?[@toString()]
if localizationEntry?
for language, translation of localizationEntry
# ignore the translation if it's empty
continue unless translation
# ignore the translation if it isn't for one of the skill languages (could just be comments)
continue unless Object.keys(skill.languages).includes(language)
alternates = translation.split('|') # alternates delineation character is '|'
for i in [0..alternates.length - 1]
# parse the translation to identify the string parts
fragment = """say "#{alternates[i]}" """
parsedTranslation = null
try
parsedTranslation = parseFragment(fragment, language)
catch err
throw new Error("Failed to parse the following fragment translated for #{language}:\n#{fragment}\n#{err}")
if i == 0
# first (and potentially only) alternate
@alternates[language] = parsedTranslation.alternates.default
else
# split by '|' returned more than one string -> this is an 'or' alternate
@alternates[language].push(parsedTranslation.alternates.default[0])
pushAlternate: (location, parts, skill, language = 'default') ->
@alternates[language].push parts
# re-check localization since alternates are combined into single key as follows:
# "speech|alternate one|alternate two"
@checkForTranslations(skill)
toString: (language = 'default') ->
switch @alternates[language].length
when 0 then return ''
when 1
return (p.toString() for p in @alternates[language][0]).join('')
else
return (a.join('').toString() for a in @alternates[language]).join('|')
toExpression: (options, language = 'default') ->
partsToExpression @alternates[language][0], options
toLambda: (output, indent, options) ->
speechTargets = ["say"]
if @isReprompt
speechTargets = [ "reprompt" ]
else if @isAlsoReprompt
speechTargets = speechTargets.concat "reprompt"
writeAlternates = (indent, alternates) ->
if alternates.length > 1
sayKey = require('./say<KEY>').get()
output.push "#{indent}switch(pickSayString(context, #{sayKey}, #{alternates.length})) {"
for alt, idx in alternates
if idx == alternates.length - 1
output.push "#{indent} default:"
else
output.push "#{indent} case #{idx}:"
writeLine indent + " ", alt
output.push "#{indent} break;"
output.push "#{indent}}"
else
writeLine indent, alternates[0]
writeLine = (indent, parts) ->
line = partsToExpression(parts, options)
for target in speechTargets
if line and line != '""'
output.push "#{indent}context.#{target}.push( (#{line}).trim().replace(/ +/g,' ') );"
# Add language-specific output speech to the Lambda, if translations exist.
alternates = @alternates[options.language] ? @alternates.default
writeAlternates(indent, alternates)
express: (context) ->
# given the info in the context, fully resolve the parts
if @alternates[context.language]?
(p.express(context) for p in @alternates[context.language][0]).join("")
else
(p.express(context) for p in @alternates.default[0]).join("")
matchFragment: (language, line, testLine) ->
for parts in @alternates.default
unless parts.regex?
regexText = ( p.toTestRegex() for p in parts ).join('')
# prefixed with any number of spaces to eat formatting
# adjustments with fragments are combined in the skill
parts.regex = new RegExp("\\s*" + regexText, '')
match = parts.regex.exec(line)
continue unless match?
continue unless match[0].length > 0
result =
offset: match.index
reduced: line.replace parts.regex, ''
part: @
removed: match[0]
slots: {}
dbs: {}
for read, idx in match[1..]
part = parts[idx]
if part?.isSlot
result.slots[part.name] = read
if part?.isDB
result.dbs[part.name] = read
return result
return null
toLocalization: (localization) ->
collectParts = (parts) ->
locParts = []
for p in parts when p.toLocalization?
fragment = p.toLocalization(localization)
locParts.push fragment if fragment?
locParts.join ''
switch @alternates.default.length
when 0 then return
when 1
speech = collectParts(@alternates.default[0])
unless localization.speech[speech]?
localization.speech[speech] = {}
else
speeches = ( collectParts(a) for a in @alternates.default )
speeches = speeches.join('|')
unless localization.speech[speeches]?
localization.speech[speeches] = {}
| true | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
lib = module.exports.lib = {}
lib[k] = v for k, v of require('./sayVariableParts.coffee')
lib[k] = v for k, v of require('./sayTagParts.coffee')
lib[k] = v for k, v of require('./sayJavascriptParts.coffee')
lib[k] = v for k, v of require('./sayFlowControlParts.coffee')
{ parseFragment } = require('./parser.coffee')
{ ParserError } = require('./errors.coffee').lib
{ AssetName } = require('./assets.coffee').lib
{
replaceNewlineCharacters,
isEmptyContentString,
isFirstOrLastItemOfArray,
dedupeNonNewlineConsecutiveWhitespaces,
cleanTrailingSpaces,
cleanLeadingSpaces
} = require('./utils.coffee').lib
class lib.StringPart
constructor: (text) ->
# Whitespace and line break rules:
# line breaks are converted to whitespaces
# empty (or whitespace-only) lines are considered a line break
# consecutive whitespaces are condensed to a single whitespace
splitLines = text.split('\n')
lines = splitLines.map((str, idx) ->
return '\n' if isEmptyContentString(str) and !isFirstOrLastItemOfArray(idx, splitLines)
return str.trim() unless isFirstOrLastItemOfArray(idx, splitLines)
return dedupeNonNewlineConsecutiveWhitespaces(str)
)
@tagClosePos = null
if lines.length > 1
@tagClosePos = lines[0].length + 1
if lines[0] == '\n'
@tagClosePos += 1
@text = lines.join(' ')
transformations = [
cleanTrailingSpaces,
cleanLeadingSpaces,
dedupeNonNewlineConsecutiveWhitespaces
]
transformations.forEach((transformation) =>
@text = transformation(@text)
)
visit: (depth, fn) -> fn(depth, @)
isStringPart: true
toString: -> @text
toUtterance: -> [ @text.toLowerCase() ]
toLambda: (options) ->
# escape quotes
str = @text.replace(/"/g, '\"')
# escape line breaks
str = replaceNewlineCharacters(str, '\\n')
return '"' + str + '"'
express: (context) ->
return @text
toRegex: ->
str = @text
# escape regex control characters
str = str.replace( /\?/g, '\\?' )
str = str.replace( /\./g, '\\.' )
# mirror the line break handling for the lambda
str = replaceNewlineCharacters(str, '\\n')
"(#{str})"
toTestRegex: -> @toRegex()
toTestScore: -> return 10
toLocalization: ->
return @toString()
class lib.AssetNamePart
constructor: (@assetName) ->
isAssetNamePart: true
toString: -> return "<#{@assetName}>"
toUtterance: -> throw new ParserError @assetName.location, "can't use an asset name part in an utterance"
toLambda: (options) -> return @assetName.toSSML(options.language)
express: (context) -> return @toString()
toRegex: ->
return "(#{@toSSML()})"
toTestRegex: -> @toRegex()
toTestScore: -> return 10
partsToExpression = (parts, options) ->
unless parts?.length > 0
return "''"
result = []
tagContext = []
closeTags = ->
if tagContext.length == 0
return ''
closed = []
for tag in tagContext by -1
closed.push "</#{tag}>"
tagContext = []
'"' + closed.join('') + '"'
result = for p in parts
if p.open
tagContext.push p.tag
code = p.toLambda options
if p.tagClosePos?
closed = closeTags()
if closed
before = code[0...p.tagClosePos] + '"'
after = '"' + code[p.tagClosePos..]
code = [before, closed, after].join '+'
if p.needsEscaping
"escapeSpeech( #{code} )"
else
code
closed = closeTags()
if closed
result.push closed
result.join(' + ')
class lib.Say
constructor: (parts, skill) ->
@alternates = {
default: [ parts ]
}
@checkForTranslations(skill)
isSay: true
checkForTranslations: (skill) ->
# Check if the localization map exists and has an entry for this string.
localizationEntry = skill?.projectInfo?.localization?.speech?[@toString()]
if localizationEntry?
for language, translation of localizationEntry
# ignore the translation if it's empty
continue unless translation
# ignore the translation if it isn't for one of the skill languages (could just be comments)
continue unless Object.keys(skill.languages).includes(language)
alternates = translation.split('|') # alternates delineation character is '|'
for i in [0..alternates.length - 1]
# parse the translation to identify the string parts
fragment = """say "#{alternates[i]}" """
parsedTranslation = null
try
parsedTranslation = parseFragment(fragment, language)
catch err
throw new Error("Failed to parse the following fragment translated for #{language}:\n#{fragment}\n#{err}")
if i == 0
# first (and potentially only) alternate
@alternates[language] = parsedTranslation.alternates.default
else
# split by '|' returned more than one string -> this is an 'or' alternate
@alternates[language].push(parsedTranslation.alternates.default[0])
pushAlternate: (location, parts, skill, language = 'default') ->
@alternates[language].push parts
# re-check localization since alternates are combined into single key as follows:
# "speech|alternate one|alternate two"
@checkForTranslations(skill)
toString: (language = 'default') ->
switch @alternates[language].length
when 0 then return ''
when 1
return (p.toString() for p in @alternates[language][0]).join('')
else
return (a.join('').toString() for a in @alternates[language]).join('|')
toExpression: (options, language = 'default') ->
partsToExpression @alternates[language][0], options
toLambda: (output, indent, options) ->
speechTargets = ["say"]
if @isReprompt
speechTargets = [ "reprompt" ]
else if @isAlsoReprompt
speechTargets = speechTargets.concat "reprompt"
writeAlternates = (indent, alternates) ->
if alternates.length > 1
sayKey = require('./sayPI:KEY:<KEY>END_PI').get()
output.push "#{indent}switch(pickSayString(context, #{sayKey}, #{alternates.length})) {"
for alt, idx in alternates
if idx == alternates.length - 1
output.push "#{indent} default:"
else
output.push "#{indent} case #{idx}:"
writeLine indent + " ", alt
output.push "#{indent} break;"
output.push "#{indent}}"
else
writeLine indent, alternates[0]
writeLine = (indent, parts) ->
line = partsToExpression(parts, options)
for target in speechTargets
if line and line != '""'
output.push "#{indent}context.#{target}.push( (#{line}).trim().replace(/ +/g,' ') );"
# Add language-specific output speech to the Lambda, if translations exist.
alternates = @alternates[options.language] ? @alternates.default
writeAlternates(indent, alternates)
express: (context) ->
# given the info in the context, fully resolve the parts
if @alternates[context.language]?
(p.express(context) for p in @alternates[context.language][0]).join("")
else
(p.express(context) for p in @alternates.default[0]).join("")
matchFragment: (language, line, testLine) ->
for parts in @alternates.default
unless parts.regex?
regexText = ( p.toTestRegex() for p in parts ).join('')
# prefixed with any number of spaces to eat formatting
# adjustments with fragments are combined in the skill
parts.regex = new RegExp("\\s*" + regexText, '')
match = parts.regex.exec(line)
continue unless match?
continue unless match[0].length > 0
result =
offset: match.index
reduced: line.replace parts.regex, ''
part: @
removed: match[0]
slots: {}
dbs: {}
for read, idx in match[1..]
part = parts[idx]
if part?.isSlot
result.slots[part.name] = read
if part?.isDB
result.dbs[part.name] = read
return result
return null
toLocalization: (localization) ->
collectParts = (parts) ->
locParts = []
for p in parts when p.toLocalization?
fragment = p.toLocalization(localization)
locParts.push fragment if fragment?
locParts.join ''
switch @alternates.default.length
when 0 then return
when 1
speech = collectParts(@alternates.default[0])
unless localization.speech[speech]?
localization.speech[speech] = {}
else
speeches = ( collectParts(a) for a in @alternates.default )
speeches = speeches.join('|')
unless localization.speech[speeches]?
localization.speech[speeches] = {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.