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": "'foo', \"Data foo in key\"\n\n el.data('key', {fizz: 1, buzz: 2})\n assert.deepEqual el.data('key'), {fizz:", "end": 697, "score": 0.9527223110198975, "start": 681, "tag": "KEY", "value": "fizz: 1, buzz: 2" }, { "context": "z: 2})\n assert.deepEqual...
test/data.spec.coffee
ryejs/rye
50
suite 'Data', -> test 'storage data', -> e = {} assert.equal data.get(e, 'key'), undefined, "No initial data" data.set(e, 'key', 'foo') assert.equal data.get(e, 'key'), 'foo', "Data foo in key" data.set(e, 'key', 'bar') assert.equal data.get(e, 'key'), 'bar', "Data changed to bar in key" assert.deepEqual data.get(e), {key: 'bar'}, "Get all data" test 'Element storage data', -> el = $(document.createElement('div')) assert.equal el.data('key'), undefined, "No initial data" el.data('key', 'foo') assert.equal el.data('key'), 'foo', "Data foo in key" el.data('key', {fizz: 1, buzz: 2}) assert.deepEqual el.data('key'), {fizz: 1, buzz: 2}, "Data changed to object in key" test 'List storage data', -> el = $([ document.createElement('div') document.createElement('div') ]) assert.deepEqual el.data('key'), [undefined, undefined], "No initial data" el.data('key', 'foo') assert.deepEqual el.data('key'), ['foo', 'foo'], "Data foo in key" el.data('key', 'bar') assert.deepEqual el.data('key'), ['bar', 'bar'], "Data changed to bar in key"
109213
suite 'Data', -> test 'storage data', -> e = {} assert.equal data.get(e, 'key'), undefined, "No initial data" data.set(e, 'key', 'foo') assert.equal data.get(e, 'key'), 'foo', "Data foo in key" data.set(e, 'key', 'bar') assert.equal data.get(e, 'key'), 'bar', "Data changed to bar in key" assert.deepEqual data.get(e), {key: 'bar'}, "Get all data" test 'Element storage data', -> el = $(document.createElement('div')) assert.equal el.data('key'), undefined, "No initial data" el.data('key', 'foo') assert.equal el.data('key'), 'foo', "Data foo in key" el.data('key', {<KEY>}) assert.deepEqual el.data('key'), {f<KEY>: 1, buzz: 2}, "Data changed to object in key" test 'List storage data', -> el = $([ document.createElement('div') document.createElement('div') ]) assert.deepEqual el.data('key'), [undefined, undefined], "No initial data" el.data('key', 'foo') assert.deepEqual el.data('key'), ['foo', 'foo'], "Data foo in key" el.data('key', 'bar') assert.deepEqual el.data('key'), ['bar', 'bar'], "Data changed to bar in key"
true
suite 'Data', -> test 'storage data', -> e = {} assert.equal data.get(e, 'key'), undefined, "No initial data" data.set(e, 'key', 'foo') assert.equal data.get(e, 'key'), 'foo', "Data foo in key" data.set(e, 'key', 'bar') assert.equal data.get(e, 'key'), 'bar', "Data changed to bar in key" assert.deepEqual data.get(e), {key: 'bar'}, "Get all data" test 'Element storage data', -> el = $(document.createElement('div')) assert.equal el.data('key'), undefined, "No initial data" el.data('key', 'foo') assert.equal el.data('key'), 'foo', "Data foo in key" el.data('key', {PI:KEY:<KEY>END_PI}) assert.deepEqual el.data('key'), {fPI:KEY:<KEY>END_PI: 1, buzz: 2}, "Data changed to object in key" test 'List storage data', -> el = $([ document.createElement('div') document.createElement('div') ]) assert.deepEqual el.data('key'), [undefined, undefined], "No initial data" el.data('key', 'foo') assert.deepEqual el.data('key'), ['foo', 'foo'], "Data foo in key" el.data('key', 'bar') assert.deepEqual el.data('key'), ['bar', 'bar'], "Data changed to bar in key"
[ { "context": "pts = extendOpts(opts, @metric.labelNames)\n\t\tkey = optsKey(opts)\n\t\t@instances.set(key, { time: new Date(), o", "end": 2160, "score": 0.9466886520385742, "start": 2153, "tag": "KEY", "value": "optsKey" }, { "context": "endOpts(opts, @metric.labelNames)\n\t\tkey = o...
prom_wrapper.coffee
j-licht/metrics-module
0
prom = require('prom-client') registry = require('prom-client').register metrics = new Map() optsKey = (opts) -> keys = Object.keys(opts) return '' if keys.length == 0 keys = keys.sort() hash = ''; for key in keys hash += "," if hash.length hash += "#{key}:#{opts[key]}" return hash extendOpts = (opts, labelNames) -> for label in labelNames opts[label] ||= '' return opts optsAsArgs = (opts, labelNames) -> args = [] for label in labelNames args.push(opts[label] || '') return args PromWrapper = ttlInMinutes: 0 registry: registry metric: (type, name) -> metrics.get(name) || new MetricWrapper(type, name) collectDefaultMetrics: prom.collectDefaultMetrics class MetricWrapper constructor: (type, name) -> metrics.set(name, this) @name = name @instances = new Map() @lastAccess = new Date() @metric = switch type when "counter" new prom.Counter({ name: name, help: name, labelNames: ['app','host','status','method', 'path'] }) when "summary" new prom.Summary({ name: name, help: name, maxAgeSeconds: 600, ageBuckets: 10, labelNames: ['app', 'host', 'path', 'status_code', 'method', 'collection', 'query'] }) when "gauge" new prom.Gauge({ name: name, help: name, labelNames: ['app','host', 'status'] }) inc: (opts, value) -> @_execMethod 'inc', opts, value observe: (opts, value) -> @_execMethod 'observe', opts, value set: (opts, value) -> @_execMethod 'set', opts, value sweep: () -> thresh = new Date(Date.now() - 1000 * 60 * PromWrapper.ttlInMinutes) @instances.forEach (instance, key) => if thresh > instance.time if process.env['DEBUG_METRICS'] console.log("Sweeping stale metric instance", @name, opts: instance.opts, key) @metric.remove(optsAsArgs(instance.opts, @metric.labelNames)...) if thresh > @lastAccess if process.env['DEBUG_METRICS'] console.log("Sweeping stale metric", @name, thresh, @lastAccess) metrics.delete(@name) registry.removeSingleMetric(@name) _execMethod: (method, opts, value) -> opts = extendOpts(opts, @metric.labelNames) key = optsKey(opts) @instances.set(key, { time: new Date(), opts }) unless key == '' @lastAccess = new Date() @metric[method](opts, value) unless PromWrapper.sweepRegistered if process.env['DEBUG_METRICS'] console.log("Registering sweep method") PromWrapper.sweepRegistered = true setInterval( () -> if PromWrapper.ttlInMinutes if process.env['DEBUG_METRICS'] console.log("Sweeping metrics") metrics.forEach (metric, key) => metric.sweep() 60000) module.exports = PromWrapper
35116
prom = require('prom-client') registry = require('prom-client').register metrics = new Map() optsKey = (opts) -> keys = Object.keys(opts) return '' if keys.length == 0 keys = keys.sort() hash = ''; for key in keys hash += "," if hash.length hash += "#{key}:#{opts[key]}" return hash extendOpts = (opts, labelNames) -> for label in labelNames opts[label] ||= '' return opts optsAsArgs = (opts, labelNames) -> args = [] for label in labelNames args.push(opts[label] || '') return args PromWrapper = ttlInMinutes: 0 registry: registry metric: (type, name) -> metrics.get(name) || new MetricWrapper(type, name) collectDefaultMetrics: prom.collectDefaultMetrics class MetricWrapper constructor: (type, name) -> metrics.set(name, this) @name = name @instances = new Map() @lastAccess = new Date() @metric = switch type when "counter" new prom.Counter({ name: name, help: name, labelNames: ['app','host','status','method', 'path'] }) when "summary" new prom.Summary({ name: name, help: name, maxAgeSeconds: 600, ageBuckets: 10, labelNames: ['app', 'host', 'path', 'status_code', 'method', 'collection', 'query'] }) when "gauge" new prom.Gauge({ name: name, help: name, labelNames: ['app','host', 'status'] }) inc: (opts, value) -> @_execMethod 'inc', opts, value observe: (opts, value) -> @_execMethod 'observe', opts, value set: (opts, value) -> @_execMethod 'set', opts, value sweep: () -> thresh = new Date(Date.now() - 1000 * 60 * PromWrapper.ttlInMinutes) @instances.forEach (instance, key) => if thresh > instance.time if process.env['DEBUG_METRICS'] console.log("Sweeping stale metric instance", @name, opts: instance.opts, key) @metric.remove(optsAsArgs(instance.opts, @metric.labelNames)...) if thresh > @lastAccess if process.env['DEBUG_METRICS'] console.log("Sweeping stale metric", @name, thresh, @lastAccess) metrics.delete(@name) registry.removeSingleMetric(@name) _execMethod: (method, opts, value) -> opts = extendOpts(opts, @metric.labelNames) key = <KEY>(<KEY>) @instances.set(key, { time: new Date(), opts }) unless key == '' @lastAccess = new Date() @metric[method](opts, value) unless PromWrapper.sweepRegistered if process.env['DEBUG_METRICS'] console.log("Registering sweep method") PromWrapper.sweepRegistered = true setInterval( () -> if PromWrapper.ttlInMinutes if process.env['DEBUG_METRICS'] console.log("Sweeping metrics") metrics.forEach (metric, key) => metric.sweep() 60000) module.exports = PromWrapper
true
prom = require('prom-client') registry = require('prom-client').register metrics = new Map() optsKey = (opts) -> keys = Object.keys(opts) return '' if keys.length == 0 keys = keys.sort() hash = ''; for key in keys hash += "," if hash.length hash += "#{key}:#{opts[key]}" return hash extendOpts = (opts, labelNames) -> for label in labelNames opts[label] ||= '' return opts optsAsArgs = (opts, labelNames) -> args = [] for label in labelNames args.push(opts[label] || '') return args PromWrapper = ttlInMinutes: 0 registry: registry metric: (type, name) -> metrics.get(name) || new MetricWrapper(type, name) collectDefaultMetrics: prom.collectDefaultMetrics class MetricWrapper constructor: (type, name) -> metrics.set(name, this) @name = name @instances = new Map() @lastAccess = new Date() @metric = switch type when "counter" new prom.Counter({ name: name, help: name, labelNames: ['app','host','status','method', 'path'] }) when "summary" new prom.Summary({ name: name, help: name, maxAgeSeconds: 600, ageBuckets: 10, labelNames: ['app', 'host', 'path', 'status_code', 'method', 'collection', 'query'] }) when "gauge" new prom.Gauge({ name: name, help: name, labelNames: ['app','host', 'status'] }) inc: (opts, value) -> @_execMethod 'inc', opts, value observe: (opts, value) -> @_execMethod 'observe', opts, value set: (opts, value) -> @_execMethod 'set', opts, value sweep: () -> thresh = new Date(Date.now() - 1000 * 60 * PromWrapper.ttlInMinutes) @instances.forEach (instance, key) => if thresh > instance.time if process.env['DEBUG_METRICS'] console.log("Sweeping stale metric instance", @name, opts: instance.opts, key) @metric.remove(optsAsArgs(instance.opts, @metric.labelNames)...) if thresh > @lastAccess if process.env['DEBUG_METRICS'] console.log("Sweeping stale metric", @name, thresh, @lastAccess) metrics.delete(@name) registry.removeSingleMetric(@name) _execMethod: (method, opts, value) -> opts = extendOpts(opts, @metric.labelNames) key = PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI) @instances.set(key, { time: new Date(), opts }) unless key == '' @lastAccess = new Date() @metric[method](opts, value) unless PromWrapper.sweepRegistered if process.env['DEBUG_METRICS'] console.log("Registering sweep method") PromWrapper.sweepRegistered = true setInterval( () -> if PromWrapper.ttlInMinutes if process.env['DEBUG_METRICS'] console.log("Sweeping metrics") metrics.forEach (metric, key) => metric.sweep() 60000) module.exports = PromWrapper
[ { "context": "###\n* @author Andrew D.Laptev <a.d.laptev@gmail.com>\n###\n\n###global describe, b", "end": 29, "score": 0.9998876452445984, "start": 14, "tag": "NAME", "value": "Andrew D.Laptev" }, { "context": "###\n* @author Andrew D.Laptev <a.d.laptev@gmail.com>\n###\n\n###global ...
test/test.getObject.coffee
agsh/boobst
16
### * @author Andrew D.Laptev <a.d.laptev@gmail.com> ### ###global describe, beforeEach, afterEach, it### assert = require 'assert' boobst = require '../boobst' BoobstSocket = boobst.BoobstSocket GLOBAL = '^testObject'; describe 'getObject', () -> this.timeout 1000 bs = new BoobstSocket(require './test.config') #bs.on('debug', console.log); # uncomment for debug messages beforeEach (done) -> bs.connect (err) -> throw err if err done() afterEach (done) -> bs.kill GLOBAL, (err) -> bs.disconnect () -> done() describe '#getObject', () -> object = { "array": ["a", "ab", "abc"] "object": "a": "a" "b": 2 "boolean": true "number": 42 } subscript = ['a', 'b'] it 'should return saved object', (done) -> bs.set GLOBAL, [], object, (err) -> assert.equal err, null bs.get GLOBAL, [], (err, data) -> assert.equal err, null assert.deepEqual JSON.parse(data), object done() it 'should return saved object with subscripts', (done) -> bs.set GLOBAL, subscript, object, (err) -> assert.equal err, null bs.get GLOBAL, subscript, (err, data) -> assert.equal err, null assert.deepEqual JSON.parse(data), object done()
206478
### * @author <NAME> <<EMAIL>> ### ###global describe, beforeEach, afterEach, it### assert = require 'assert' boobst = require '../boobst' BoobstSocket = boobst.BoobstSocket GLOBAL = '^testObject'; describe 'getObject', () -> this.timeout 1000 bs = new BoobstSocket(require './test.config') #bs.on('debug', console.log); # uncomment for debug messages beforeEach (done) -> bs.connect (err) -> throw err if err done() afterEach (done) -> bs.kill GLOBAL, (err) -> bs.disconnect () -> done() describe '#getObject', () -> object = { "array": ["a", "ab", "abc"] "object": "a": "a" "b": 2 "boolean": true "number": 42 } subscript = ['a', 'b'] it 'should return saved object', (done) -> bs.set GLOBAL, [], object, (err) -> assert.equal err, null bs.get GLOBAL, [], (err, data) -> assert.equal err, null assert.deepEqual JSON.parse(data), object done() it 'should return saved object with subscripts', (done) -> bs.set GLOBAL, subscript, object, (err) -> assert.equal err, null bs.get GLOBAL, subscript, (err, data) -> assert.equal err, null assert.deepEqual JSON.parse(data), object done()
true
### * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### ###global describe, beforeEach, afterEach, it### assert = require 'assert' boobst = require '../boobst' BoobstSocket = boobst.BoobstSocket GLOBAL = '^testObject'; describe 'getObject', () -> this.timeout 1000 bs = new BoobstSocket(require './test.config') #bs.on('debug', console.log); # uncomment for debug messages beforeEach (done) -> bs.connect (err) -> throw err if err done() afterEach (done) -> bs.kill GLOBAL, (err) -> bs.disconnect () -> done() describe '#getObject', () -> object = { "array": ["a", "ab", "abc"] "object": "a": "a" "b": 2 "boolean": true "number": 42 } subscript = ['a', 'b'] it 'should return saved object', (done) -> bs.set GLOBAL, [], object, (err) -> assert.equal err, null bs.get GLOBAL, [], (err, data) -> assert.equal err, null assert.deepEqual JSON.parse(data), object done() it 'should return saved object with subscripts', (done) -> bs.set GLOBAL, subscript, object, (err) -> assert.equal err, null bs.get GLOBAL, subscript, (err, data) -> assert.equal err, null assert.deepEqual JSON.parse(data), object done()
[ { "context": "@ds.ApiHero.createCollection 'People', (d = name:'Jimmy', \"age\":20), (e, col)=>\n col.insert d, =>\n ", "end": 1821, "score": 0.9995180368423462, "start": 1816, "tag": "NAME", "value": "Jimmy" } ]
test/server/node_modules/loopback-connector-apihero-mongodb/test/mongodb.coffee
vancarney/apihero-module-socket.io
0
{_} = require 'lodash' {should,expect} = require './_init' Customer = null describe 'mongodb connector', -> before => should() @ds = getDataSource() it 'should connect', (done)=> @ds.connector.connect done it 'should have the API Hero Mixin Defined', => expect( @ds.ApiHero ).to.exist it 'should create a Collections', (done)=> @ds.ApiHero.createCollection 'RenameMe', done it 'should get a Collections', (done)=> @ds.ApiHero.getCollection 'RenameMe', (e,col)=> col.s.name.should.eq 'RenameMe' done.apply @, arguments it 'should obtain a list of Collections', (done)=> expect( @ds.ApiHero.listCollections ).to.exist @ds.ApiHero.listCollections.should.be.a 'function' @ds.ApiHero.listCollections (e,names)=> throw e if e? names.length.should.eq 2 expect( names.indexOf 'RenameMe' ).to.be.above -1 done.apply @, arguments it 'should filter the list of Collections', (done)=> @ds.ApiHero.listCollections (e,names)=> filtered = _.compact _.map names, (v)=> if v.match new RegExp "^(#{@ds.ApiHero.exclude.join '|'})$" then null else v expect( filtered.indexOf 'system.indexes').to.eq -1 done() it 'should rename a collection', (done)=> @ds.ApiHero.renameCollection 'RenameMe', 'DeleteMe', => @ds.ApiHero.getCollection 'DeleteMe', (e, col)=> expect( col ).to.exist done.apply @, arguments it 'should drop a collection', (done)=> @ds.ApiHero.dropCollection 'DeleteMe', => @ds.ApiHero.listCollections (e,names)=> throw e if e? expect( names.indexOf 'DeleteMe' ).to.eq -1 done() it 'should create a Collection with Data', (done)=> @ds.ApiHero.createCollection 'People', (d = name:'Jimmy', "age":20), (e, col)=> col.insert d, => done.apply @, arguments it 'should have the discoverCollections Method Defined', (done)=> expect( @ds.ApiHero.discoverCollections ).to.exist @ds.ApiHero.discoverCollections.should.be.a 'function' @ds.ApiHero.discoverCollections (e,trees)=> @trees = trees done.apply @, arguments it 'should recognize name as a String', => expect(@trees.name).to.exist @trees.name.should.eq 'String' it 'should recognize age as a Number', => expect(@trees.age).to.exist @trees.age.should.eq 'Number' after (done)=> @ds.ApiHero.dropCollection 'People', done
142996
{_} = require 'lodash' {should,expect} = require './_init' Customer = null describe 'mongodb connector', -> before => should() @ds = getDataSource() it 'should connect', (done)=> @ds.connector.connect done it 'should have the API Hero Mixin Defined', => expect( @ds.ApiHero ).to.exist it 'should create a Collections', (done)=> @ds.ApiHero.createCollection 'RenameMe', done it 'should get a Collections', (done)=> @ds.ApiHero.getCollection 'RenameMe', (e,col)=> col.s.name.should.eq 'RenameMe' done.apply @, arguments it 'should obtain a list of Collections', (done)=> expect( @ds.ApiHero.listCollections ).to.exist @ds.ApiHero.listCollections.should.be.a 'function' @ds.ApiHero.listCollections (e,names)=> throw e if e? names.length.should.eq 2 expect( names.indexOf 'RenameMe' ).to.be.above -1 done.apply @, arguments it 'should filter the list of Collections', (done)=> @ds.ApiHero.listCollections (e,names)=> filtered = _.compact _.map names, (v)=> if v.match new RegExp "^(#{@ds.ApiHero.exclude.join '|'})$" then null else v expect( filtered.indexOf 'system.indexes').to.eq -1 done() it 'should rename a collection', (done)=> @ds.ApiHero.renameCollection 'RenameMe', 'DeleteMe', => @ds.ApiHero.getCollection 'DeleteMe', (e, col)=> expect( col ).to.exist done.apply @, arguments it 'should drop a collection', (done)=> @ds.ApiHero.dropCollection 'DeleteMe', => @ds.ApiHero.listCollections (e,names)=> throw e if e? expect( names.indexOf 'DeleteMe' ).to.eq -1 done() it 'should create a Collection with Data', (done)=> @ds.ApiHero.createCollection 'People', (d = name:'<NAME>', "age":20), (e, col)=> col.insert d, => done.apply @, arguments it 'should have the discoverCollections Method Defined', (done)=> expect( @ds.ApiHero.discoverCollections ).to.exist @ds.ApiHero.discoverCollections.should.be.a 'function' @ds.ApiHero.discoverCollections (e,trees)=> @trees = trees done.apply @, arguments it 'should recognize name as a String', => expect(@trees.name).to.exist @trees.name.should.eq 'String' it 'should recognize age as a Number', => expect(@trees.age).to.exist @trees.age.should.eq 'Number' after (done)=> @ds.ApiHero.dropCollection 'People', done
true
{_} = require 'lodash' {should,expect} = require './_init' Customer = null describe 'mongodb connector', -> before => should() @ds = getDataSource() it 'should connect', (done)=> @ds.connector.connect done it 'should have the API Hero Mixin Defined', => expect( @ds.ApiHero ).to.exist it 'should create a Collections', (done)=> @ds.ApiHero.createCollection 'RenameMe', done it 'should get a Collections', (done)=> @ds.ApiHero.getCollection 'RenameMe', (e,col)=> col.s.name.should.eq 'RenameMe' done.apply @, arguments it 'should obtain a list of Collections', (done)=> expect( @ds.ApiHero.listCollections ).to.exist @ds.ApiHero.listCollections.should.be.a 'function' @ds.ApiHero.listCollections (e,names)=> throw e if e? names.length.should.eq 2 expect( names.indexOf 'RenameMe' ).to.be.above -1 done.apply @, arguments it 'should filter the list of Collections', (done)=> @ds.ApiHero.listCollections (e,names)=> filtered = _.compact _.map names, (v)=> if v.match new RegExp "^(#{@ds.ApiHero.exclude.join '|'})$" then null else v expect( filtered.indexOf 'system.indexes').to.eq -1 done() it 'should rename a collection', (done)=> @ds.ApiHero.renameCollection 'RenameMe', 'DeleteMe', => @ds.ApiHero.getCollection 'DeleteMe', (e, col)=> expect( col ).to.exist done.apply @, arguments it 'should drop a collection', (done)=> @ds.ApiHero.dropCollection 'DeleteMe', => @ds.ApiHero.listCollections (e,names)=> throw e if e? expect( names.indexOf 'DeleteMe' ).to.eq -1 done() it 'should create a Collection with Data', (done)=> @ds.ApiHero.createCollection 'People', (d = name:'PI:NAME:<NAME>END_PI', "age":20), (e, col)=> col.insert d, => done.apply @, arguments it 'should have the discoverCollections Method Defined', (done)=> expect( @ds.ApiHero.discoverCollections ).to.exist @ds.ApiHero.discoverCollections.should.be.a 'function' @ds.ApiHero.discoverCollections (e,trees)=> @trees = trees done.apply @, arguments it 'should recognize name as a String', => expect(@trees.name).to.exist @trees.name.should.eq 'String' it 'should recognize age as a Number', => expect(@trees.age).to.exist @trees.age.should.eq 'Number' after (done)=> @ds.ApiHero.dropCollection 'People', done
[ { "context": "null\ndeliverStub = null\n\nbefore () ->\n apiKey = \"71ab53572c7b45316fb894d446f2e11d\"\n Bugsnag.register apiKey, notifyReleaseStages: ", "end": 237, "score": 0.9997579455375671, "start": 205, "tag": "KEY", "value": "71ab53572c7b45316fb894d446f2e11d" } ]
test/error.coffee
wennergr2/bugsnag-node
0
path = require("path") should = require("chai").should() sinon = require("sinon") Bugsnag = require "../" BugsnagError = require "../lib/error" apiKey = null deliverStub = null before () -> apiKey = "71ab53572c7b45316fb894d446f2e11d" Bugsnag.register apiKey, notifyReleaseStages: ["production", "development"] beforeEach -> Bugsnag.configure notifyReleaseStages: ["production", "development"] describe "Error", -> it "should have one error", -> error = new Error("error") errors = BugsnagError.buildErrors(error) errors.length.should.equal 1 it "should support oath errors", -> error = new Error("error") error.oauthError = new Error("oauth error") errors = BugsnagError.buildErrors(error) errors.length.should.equal 2
135620
path = require("path") should = require("chai").should() sinon = require("sinon") Bugsnag = require "../" BugsnagError = require "../lib/error" apiKey = null deliverStub = null before () -> apiKey = "<KEY>" Bugsnag.register apiKey, notifyReleaseStages: ["production", "development"] beforeEach -> Bugsnag.configure notifyReleaseStages: ["production", "development"] describe "Error", -> it "should have one error", -> error = new Error("error") errors = BugsnagError.buildErrors(error) errors.length.should.equal 1 it "should support oath errors", -> error = new Error("error") error.oauthError = new Error("oauth error") errors = BugsnagError.buildErrors(error) errors.length.should.equal 2
true
path = require("path") should = require("chai").should() sinon = require("sinon") Bugsnag = require "../" BugsnagError = require "../lib/error" apiKey = null deliverStub = null before () -> apiKey = "PI:KEY:<KEY>END_PI" Bugsnag.register apiKey, notifyReleaseStages: ["production", "development"] beforeEach -> Bugsnag.configure notifyReleaseStages: ["production", "development"] describe "Error", -> it "should have one error", -> error = new Error("error") errors = BugsnagError.buildErrors(error) errors.length.should.equal 1 it "should support oath errors", -> error = new Error("error") error.oauthError = new Error("oauth error") errors = BugsnagError.buildErrors(error) errors.length.should.equal 2
[ { "context": "issions.allowRead and @userId)\n\n# \t\t\t\t\tif key is 'cfs.files.filerecord'\n# \t\t\t\t\t\tcreateQuery.query['metadata.space'] = sp", "end": 10025, "score": 0.9969121217727661, "start": 10005, "tag": "KEY", "value": "cfs.files.filerecord" }, { "context": "\treadable_...
creator/packages/steedos-odata/server/odata.coffee
yicone/steedos-platform
42
Meteor.startup -> MeteorODataRouter = require('@steedos/core').MeteorODataRouter; ODataRouter = require('@steedos/core').ODataRouter express = require('express'); app = express(); app.use('/api/odata/v4', MeteorODataRouter); MeteorODataAPIV4Router = require('@steedos/core').MeteorODataAPIV4Router; if MeteorODataAPIV4Router app.use('/api/v4', MeteorODataAPIV4Router) WebApp.connectHandlers.use(app); _.each Creator.steedosSchema.getDataSources(), (datasource, name)-> if(name != 'default') otherApp = express(); otherApp.use("/api/odata/#{name}", ODataRouter); WebApp.connectHandlers.use(otherApp); # odataV4Mongodb = require 'odata-v4-mongodb' # querystring = require 'querystring' # handleError = (e)-> # console.error e.stack # body = {} # error = {} # error['message'] = e.message # statusCode = 500 # if e.error and _.isNumber(e.error) # statusCode = e.error # error['code'] = statusCode # error['error'] = statusCode # error['details'] = e.details # error['reason'] = e.reason # body['error'] = error # return { # statusCode: statusCode # body:body # } # visitorParser = (visitor)-> # parsedOpt = {} # if visitor.projection # parsedOpt.fields = visitor.projection # if visitor.hasOwnProperty('limit') # parsedOpt.limit = visitor.limit # if visitor.hasOwnProperty('skip') # parsedOpt.skip = visitor.skip # if visitor.sort # parsedOpt.sort = visitor.sort # parsedOpt # dealWithExpand = (createQuery, entities, key, spaceId)-> # if _.isEmpty createQuery.includes # return # obj = Creator.getObject(key, spaceId) # _.each createQuery.includes, (include)-> # # console.log 'include: ', include # navigationProperty = include.navigationProperty # # console.log 'navigationProperty: ', navigationProperty # field = obj.fields[navigationProperty] # if field and (field.type is 'lookup' or field.type is 'master_detail') # if _.isFunction(field.reference_to) # field.reference_to = field.reference_to() # if field.reference_to # queryOptions = visitorParser(include) # if _.isString field.reference_to # referenceToCollection = Creator.getCollection(field.reference_to, spaceId) # _ro_NAME_FIELD_KEY = Creator.getObject(field.reference_to, spaceId)?.NAME_FIELD_KEY # _.each entities, (entity, idx)-> # if entity[navigationProperty] # if field.multiple # originalData = _.clone(entity[navigationProperty]) # multiQuery = _.extend {_id: {$in: entity[navigationProperty]}}, include.query # entities[idx][navigationProperty] = referenceToCollection.find(multiQuery, queryOptions).fetch() # if !entities[idx][navigationProperty].length # entities[idx][navigationProperty] = originalData # #排序 # entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], originalData) # entities[idx][navigationProperty] = _.map entities[idx][navigationProperty], (o)-> # o['reference_to.o'] = referenceToCollection._name # o['reference_to._o'] = field.reference_to # o['_NAME_FIELD_VALUE'] = o[_ro_NAME_FIELD_KEY] # return o # else # singleQuery = _.extend {_id: entity[navigationProperty]}, include.query # # 特殊处理在相关表中没有找到数据的情况,返回原数据 # entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) || entities[idx][navigationProperty] # if entities[idx][navigationProperty] # entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name # entities[idx][navigationProperty]['reference_to._o'] = field.reference_to # entities[idx][navigationProperty]['_NAME_FIELD_VALUE'] = entities[idx][navigationProperty][_ro_NAME_FIELD_KEY] # if _.isArray field.reference_to # _.each entities, (entity, idx)-> # if entity[navigationProperty]?.ids # _o = entity[navigationProperty].o # _ro_NAME_FIELD_KEY = Creator.getObject(_o, spaceId)?.NAME_FIELD_KEY # if queryOptions?.fields && _ro_NAME_FIELD_KEY # queryOptions.fields[_ro_NAME_FIELD_KEY] = 1 # referenceToCollection = Creator.getCollection(entity[navigationProperty].o, spaceId) # if referenceToCollection # if field.multiple # _ids = _.clone(entity[navigationProperty].ids) # multiQuery = _.extend {_id: {$in: entity[navigationProperty].ids}}, include.query # entities[idx][navigationProperty] = _.map referenceToCollection.find(multiQuery, queryOptions).fetch(), (o)-> # o['reference_to.o'] = referenceToCollection._name # o['reference_to._o'] = _o # o['_NAME_FIELD_VALUE'] = o[_ro_NAME_FIELD_KEY] # return o # #排序 # entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], _ids) # else # singleQuery = _.extend {_id: entity[navigationProperty].ids[0]}, include.query # entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) # if entities[idx][navigationProperty] # entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name # entities[idx][navigationProperty]['reference_to._o'] = _o # entities[idx][navigationProperty]['_NAME_FIELD_VALUE'] = entities[idx][navigationProperty][_ro_NAME_FIELD_KEY] # else # # TODO # return # setOdataProperty=(entities,space,key)-> # entities_OdataProperties = [] # _.each entities, (entity, idx)-> # entity_OdataProperties = {} # id = entities[idx]["_id"] # entity_OdataProperties['@odata.id'] = SteedosOData.getODataNextLinkPath(space,key)+ '(\'' + "#{id}" + '\')' # entity_OdataProperties['@odata.etag'] = "W/\"08D589720BBB3DB1\"" # entity_OdataProperties['@odata.editLink'] = entity_OdataProperties['@odata.id'] # _.extend entity_OdataProperties,entity # entities_OdataProperties.push entity_OdataProperties # return entities_OdataProperties # setErrorMessage = (statusCode,collection,key,action)-> # body = {} # error = {} # innererror = {} # if statusCode == 404 # if collection # if action == 'post' # innererror['message'] = t("creator_odata_post_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_post_fail" # else # innererror['message'] = t("creator_odata_record_query_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_record_query_fail" # else # innererror['message'] = t("creator_odata_collection_query_fail")+ key # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_collection_query_fail" # if statusCode == 401 # innererror['message'] = t("creator_odata_authentication_required") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 401 # error['message'] = "creator_odata_authentication_required" # if statusCode == 403 # switch action # when 'get' then innererror['message'] = t("creator_odata_user_access_fail") # when 'post' then innererror['message'] = t("creator_odata_user_create_fail") # when 'put' then innererror['message'] = t("creator_odata_user_update_fail") # when 'delete' then innererror['message'] = t("creator_odata_user_remove_fail") # innererror['message'] = t("creator_odata_user_access_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 403 # error['message'] = "creator_odata_user_access_fail" # error['innererror'] = innererror # body['error'] = error # return body # removeInvalidMethod = (queryParams)-> # if queryParams.$filter && queryParams.$filter.indexOf('tolower(') > -1 # removeMethod = ($1)-> # return $1.replace('tolower(', '').replace(')', '') # queryParams.$filter = queryParams.$filter.replace(/tolower\(([^\)]+)\)/g, removeMethod) # isSameCompany = (spaceId, userId, companyId, query)-> # su = Creator.getCollection("space_users").findOne({ space: spaceId, user: userId }, { fields: { company_id: 1, company_ids: 1 } }) # if !companyId && query # companyId = su.company_id # query.company_id = { $in: su.company_ids } # return su.company_ids.includes(companyId) # # 不返回已假删除的数据 # excludeDeleted = (query)-> # query.is_deleted = { $ne: true } # # 修改、删除时,如果 doc.space = "global",报错 # checkGlobalRecord = (collection, id, object)-> # if object.enable_space_global && collection.find({ _id: id, space: 'global'}).count() # throw new Meteor.Error(400, "不能修改或者删除标准对象") # SteedosOdataAPI.addRoute(':object_name', {authRequired: true, spaceRequired: false}, { # get: ()-> # try # key = @urlParams.object_name # spaceId = @urlParams.spaceId # object = Creator.getObject(key, spaceId) # if not object?.enable_api # return { # statusCode: 401 # body:setErrorMessage(401) # } # collection = Creator.getCollection(key, spaceId) # if not collection # return { # statusCode: 404 # body:setErrorMessage(404,collection,key) # } # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if permissions.viewAllRecords or (permissions.viewCompanyRecords && isSameCompany(spaceId, @userId, createQuery.query.company_id, createQuery.query)) or (permissions.allowRead and @userId) # if key is 'cfs.files.filerecord' # createQuery.query['metadata.space'] = spaceId # else if key is 'spaces' # if spaceId isnt 'guest' # createQuery.query._id = spaceId # else # if spaceId isnt 'guest' and key != "users" and createQuery.query.space isnt 'global' # createQuery.query.space = spaceId # if Creator.isCommonSpace(spaceId) # if Creator.isSpaceAdmin(spaceId, @userId) # if key is 'spaces' # delete createQuery.query._id # else # delete createQuery.query.space # else # user_spaces = Creator.getCollection("space_users").find({user: @userId}, {fields: {space: 1}}).fetch() # if key is 'spaces' # # space 对所有用户记录为只读 # delete createQuery.query._id # # createQuery.query._id = {$in: _.pluck(user_spaces, 'space')} # else # createQuery.query.space = {$in: _.pluck(user_spaces, 'space')} # if not createQuery.sort or !_.size(createQuery.sort) # createQuery.sort = { modified: -1 } # is_enterprise = Steedos.isLegalVersion(spaceId,"workflow.enterprise") # is_professional = Steedos.isLegalVersion(spaceId,"workflow.professional") # is_standard = Steedos.isLegalVersion(spaceId,"workflow.standard") # if createQuery.limit # limit = createQuery.limit # if is_enterprise and limit>100000 # createQuery.limit = 100000 # else if is_professional and limit>10000 and !is_enterprise # createQuery.limit = 10000 # else if is_standard and limit>1000 and !is_professional and !is_enterprise # createQuery.limit = 1000 # else # if is_enterprise # createQuery.limit = 100000 # else if is_professional and !is_enterprise # createQuery.limit = 10000 # else if is_standard and !is_enterprise and !is_professional # createQuery.limit = 1000 # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # #if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, spaceId, @userId) # fields = Creator.getObject(key, spaceId).fields # _.each readable_fields, (field)-> # if field.indexOf('$') < 0 # #if fields[field]?.multiple!= true # createQuery.projection[field] = 1 # if not permissions.viewAllRecords && !permissions.viewCompanyRecords # if object.enable_share # # 满足共享规则中的记录也要搜索出来 # delete createQuery.query.owner # shares = [] # orgs = Steedos.getUserOrganizations(spaceId, @userId, true) # shares.push {"owner": @userId} # shares.push { "sharing.u": @userId } # shares.push { "sharing.o": { $in: orgs } } # createQuery.query["$or"] = shares # else # createQuery.query.owner = @userId # entities = [] # excludeDeleted(createQuery.query) # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # scannedCount = collection.find(createQuery.query,{fields:{_id: 1}}).count() # if entities # dealWithExpand(createQuery, entities, key, spaceId) # #scannedCount = entities.length # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) # # body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(spaceId,key)+"?%24skip="+ 10 # body['@odata.count'] = scannedCount # entities_OdataProperties = setOdataProperty(entities,spaceId, key) # body['value'] = entities_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,"get") # } # catch e # return handleError e # post: ()-> # try # key = @urlParams.object_name # spaceId = @urlParams.spaceId # if not Creator.getObject(key, spaceId)?.enable_api # return { # statusCode: 401 # body:setErrorMessage(401) # } # collection = Creator.getCollection(key, spaceId) # if not collection # return { # statusCode: 404 # body:setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = spaceId # if spaceId is 'guest' # delete @bodyParams.space # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # entities = [] # if entity # body = {} # headers = {} # entities.push entity # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # body['value'] = entity_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'post') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'post') # } # catch e # return handleError e # }) # SteedosOdataAPI.addRoute(':object_name/recent', {authRequired: true, spaceRequired: false}, { # get:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return { # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # recent_view_collection = Creator.Collections["object_recent_viewed"] # recent_view_selector = {"record.o":key,created_by:@userId} # recent_view_options = {} # recent_view_options.sort = {created: -1} # recent_view_options.fields = {record:1} # recent_view_records = recent_view_collection.find(recent_view_selector,recent_view_options).fetch() # recent_view_records_ids = _.pluck(recent_view_records,'record') # recent_view_records_ids = recent_view_records_ids.getProperty("ids") # recent_view_records_ids = _.flatten(recent_view_records_ids) # recent_view_records_ids = _.uniq(recent_view_records_ids) # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # if key is 'cfs.files.filerecord' # createQuery.query['metadata.space'] = @urlParams.spaceId # else # createQuery.query.space = @urlParams.spaceId # if not createQuery.limit # createQuery.limit = 100 # if createQuery.limit and recent_view_records_ids.length>createQuery.limit # recent_view_records_ids = _.first(recent_view_records_ids,createQuery.limit) # createQuery.query._id = {$in:recent_view_records_ids} # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # # if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId) # fields = Creator.getObject(key, @urlParams.spaceId).fields # _.each readable_fields, (field)-> # if field.indexOf('$') < 0 # #if fields[field]?.multiple!= true # createQuery.projection[field] = 1 # excludeDeleted(createQuery.query) # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # entities_index = [] # entities_ids = _.pluck(entities,'_id') # sort_entities = [] # if not createQuery.sort or !_.size(createQuery.sort) # _.each recent_view_records_ids ,(recent_view_records_id)-> # index = _.indexOf(entities_ids,recent_view_records_id) # if index>-1 # sort_entities.push entities[index] # else # sort_entities = entities # if sort_entities # dealWithExpand(createQuery, sort_entities, key, @urlParams.spaceId) # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) # # body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(@urlParams.spaceId,key)+"?%24skip="+ 10 # body['@odata.count'] = sort_entities.length # entities_OdataProperties = setOdataProperty(sort_entities,@urlParams.spaceId, key) # body['value'] = entities_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'get') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # catch e # return handleError e # }) # SteedosOdataAPI.addRoute(':object_name/:_id', {authRequired: true, spaceRequired: false}, { # post: ()-> # try # key = @urlParams.object_name # if not Creator.getObject(key, @urlParams.spaceId)?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = @urlParams.spaceId # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # entities = [] # if entity # body = {} # headers = {} # entities.push entity # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key) # body['value'] = entity_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'post') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'post') # } # catch e # return handleError e # get:()-> # key = @urlParams.object_name # if key.indexOf("(") > -1 # body = {} # headers = {} # collectionInfo = key # fieldName = @urlParams._id.split('_expand')[0] # collectionInfoSplit = collectionInfo.split('(') # collectionName = collectionInfoSplit[0] # id = collectionInfoSplit[1].split('\'')[1] # collection = Creator.getCollection(collectionName, @urlParams.spaceId) # fieldsOptions = {} # fieldsOptions[fieldName] = 1 # entity = collection.findOne({_id: id}, {fields: fieldsOptions}) # fieldValue = null # if entity # fieldValue = entity[fieldName] # obj = Creator.getObject(collectionName, @urlParams.spaceId) # field = obj.fields[fieldName] # if field and fieldValue and (field.type is 'lookup' or field.type is 'master_detail') # lookupCollection = Creator.getCollection(field.reference_to, @urlParams.spaceId) # queryOptions = {fields: {}} # readable_fields = Creator.getFields(field.reference_to, @urlParams.spaceId, @userId) # _.each readable_fields, (f)-> # if f.indexOf('$') < 0 # queryOptions.fields[f] = 1 # if field.multiple # values = [] # lookupCollection.find({_id: {$in: fieldValue}}, queryOptions).forEach (obj)-> # _.each obj, (v, k)-> # if _.isArray(v) || (_.isObject(v) && !_.isDate(v)) # obj[k] = JSON.stringify(v) # values.push(obj) # body['value'] = values # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}" # else # body = lookupCollection.findOne({_id: fieldValue}, queryOptions) || {} # _.each body, (v, k)-> # if _.isArray(v) || (_.isObject(v) && !_.isDate(v)) # body[k] = JSON.stringify(v) # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{field.reference_to}/$entity" # else # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}" # body['value'] = fieldValue # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # try # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return { # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # unreadable_fields = permissions.unreadable_fields || [] # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # createQuery.query._id = @urlParams._id # if key is 'cfs.files.filerecord' # createQuery.query['metadata.space'] = @urlParams.spaceId # else if key != 'spaces' # createQuery.query.space = @urlParams.spaceId # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # # if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId) # fields = object.fields # _.each readable_fields, (field) -> # if field.indexOf('$') < 0 # createQuery.projection[field] = 1 # entity = collection.findOne(createQuery.query,visitorParser(createQuery)) # entities = [] # if entity # isAllowed = entity.owner == @userId or permissions.viewAllRecords or (permissions.viewCompanyRecords && isSameCompany(@urlParams.spaceId, @userId, entity.company_id)) # if object.enable_share and !isAllowed # shares = [] # orgs = Steedos.getUserOrganizations(@urlParams.spaceId, @userId, true) # shares.push { "sharing.u": @userId } # shares.push { "sharing.o": { $in: orgs } } # isAllowed = collection.findOne({ _id: @urlParams._id, "$or": shares }, { fields: { _id: 1 } }) # if isAllowed # body = {} # headers = {} # entities.push entity # dealWithExpand(createQuery, entities, key, @urlParams.spaceId) # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key) # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'get') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # catch e # return handleError e # put:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # spaceId = @urlParams.spaceId # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if key == "users" # record_owner = @urlParams._id # else # record_owner = collection.findOne({ _id: @urlParams._id }, { fields: { owner: 1 } })?.owner # companyId = collection.findOne({ _id: @urlParams._id }, { fields: { company_id: 1 } })?.company_id # isAllowed = permissions.modifyAllRecords or (permissions.allowEdit and record_owner == @userId ) or (permissions.modifyCompanyRecords && isSameCompany(spaceId, @userId, companyId)) # if isAllowed # checkGlobalRecord(collection, @urlParams._id, object) # selector = {_id: @urlParams._id, space: spaceId} # if spaceId is 'guest' or spaceId is 'common' or key == "users" # delete selector.space # fields_editable = true # _.keys(@bodyParams.$set).forEach (key)-> # if _.indexOf(permissions.uneditable_fields, key) > -1 # fields_editable = false # if fields_editable # if key is 'spaces' # delete selector.space # entityIsUpdated = collection.update selector, @bodyParams # if entityIsUpdated # #statusCode: 201 # # entity = collection.findOne @urlParams._id # # entities = [] # # body = {} # headers = {} # body = {} # # entities.push entity # # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'put') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'put') # } # catch e # return handleError e # delete:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # spaceId = @urlParams.spaceId # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # recordData = collection.findOne({_id: @urlParams._id}, { fields: { owner: 1, company_id: 1 } }) # record_owner = recordData?.owner # companyId = recordData?.company_id # isAllowed = (permissions.modifyAllRecords and permissions.allowDelete) or (permissions.modifyCompanyRecords and permissions.allowDelete and isSameCompany(spaceId, @userId, companyId)) or (permissions.allowDelete and record_owner==@userId ) # if isAllowed # checkGlobalRecord(collection, @urlParams._id, object) # selector = {_id: @urlParams._id, space: spaceId} # if spaceId is 'guest' # delete selector.space # if object?.enable_trash # entityIsUpdated = collection.update(selector, { # $set: { # is_deleted: true, # deleted: new Date(), # deleted_by: @userId # } # }) # if entityIsUpdated # headers = {} # body = {} # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # if collection.remove selector # headers = {} # body = {} # # entities.push entity # # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return { # statusCode: 403 # body: setErrorMessage(403,collection,key) # } # catch e # return handleError e # }) # # _id可传all # SteedosOdataAPI.addRoute(':object_name/:_id/:methodName', {authRequired: true, spaceRequired: false}, { # post: ()-> # try # key = @urlParams.object_name # if not Creator.getObject(key, @urlParams.spaceId)?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # methodName = @urlParams.methodName # methods = Creator.Objects[key]?.methods || {} # if methods.hasOwnProperty(methodName) # thisObj = { # object_name: key # record_id: @urlParams._id # space_id: @urlParams.spaceId # user_id: @userId # permissions: permissions # } # return methods[methodName].apply(thisObj, [@bodyParams]) || {} # else # return { # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return { # statusCode: 403 # body: setErrorMessage(403,collection,key) # } # catch e # return handleError e # }) # #TODO remove # _.each [], (value, key, list)-> #Creator.Collections # if not Creator.getObject(key)?.enable_api # return # if SteedosOdataAPI # SteedosOdataAPI.addCollection Creator.getCollection(key), # excludedEndpoints: [] # routeOptions: # authRequired: true # spaceRequired: false # endpoints: # getAll: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.viewAllRecords or (permissions.allowRead and @userId) # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # if key is 'cfs.files.filerecord' # createQuery.query['metadata.space'] = @urlParams.spaceId # else # createQuery.query.space = @urlParams.spaceId # if not permissions.viewAllRecords # createQuery.query.owner = @userId # entities = [] # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # scannedCount = collection.find(createQuery.query).count() # if entities # dealWithExpand(createQuery, entities, key, @urlParams.spaceId) # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) # body['@odata.count'] = scannedCount # body['value'] = entities # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # statusCode: 404 # body: {status: 'fail', message: 'Unable to retrieve items from collection'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # post: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = @spaceId # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # if entity # statusCode: 201 # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'No item added'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # get: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowRead # selector = {_id: @urlParams.id, space: @spaceId} # entity = collection.findOne selector # if entity # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # put: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowEdit # selector = {_id: @urlParams.id, space: @spaceId} # entityIsUpdated = collection.update selector, $set: @bodyParams # if entityIsUpdated # entity = collection.findOne @urlParams.id # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # delete: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowDelete # selector = {_id: @urlParams.id, space: @spaceId} # if collection.remove selector # {status: 'success', message: 'Item removed'} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'}
72683
Meteor.startup -> MeteorODataRouter = require('@steedos/core').MeteorODataRouter; ODataRouter = require('@steedos/core').ODataRouter express = require('express'); app = express(); app.use('/api/odata/v4', MeteorODataRouter); MeteorODataAPIV4Router = require('@steedos/core').MeteorODataAPIV4Router; if MeteorODataAPIV4Router app.use('/api/v4', MeteorODataAPIV4Router) WebApp.connectHandlers.use(app); _.each Creator.steedosSchema.getDataSources(), (datasource, name)-> if(name != 'default') otherApp = express(); otherApp.use("/api/odata/#{name}", ODataRouter); WebApp.connectHandlers.use(otherApp); # odataV4Mongodb = require 'odata-v4-mongodb' # querystring = require 'querystring' # handleError = (e)-> # console.error e.stack # body = {} # error = {} # error['message'] = e.message # statusCode = 500 # if e.error and _.isNumber(e.error) # statusCode = e.error # error['code'] = statusCode # error['error'] = statusCode # error['details'] = e.details # error['reason'] = e.reason # body['error'] = error # return { # statusCode: statusCode # body:body # } # visitorParser = (visitor)-> # parsedOpt = {} # if visitor.projection # parsedOpt.fields = visitor.projection # if visitor.hasOwnProperty('limit') # parsedOpt.limit = visitor.limit # if visitor.hasOwnProperty('skip') # parsedOpt.skip = visitor.skip # if visitor.sort # parsedOpt.sort = visitor.sort # parsedOpt # dealWithExpand = (createQuery, entities, key, spaceId)-> # if _.isEmpty createQuery.includes # return # obj = Creator.getObject(key, spaceId) # _.each createQuery.includes, (include)-> # # console.log 'include: ', include # navigationProperty = include.navigationProperty # # console.log 'navigationProperty: ', navigationProperty # field = obj.fields[navigationProperty] # if field and (field.type is 'lookup' or field.type is 'master_detail') # if _.isFunction(field.reference_to) # field.reference_to = field.reference_to() # if field.reference_to # queryOptions = visitorParser(include) # if _.isString field.reference_to # referenceToCollection = Creator.getCollection(field.reference_to, spaceId) # _ro_NAME_FIELD_KEY = Creator.getObject(field.reference_to, spaceId)?.NAME_FIELD_KEY # _.each entities, (entity, idx)-> # if entity[navigationProperty] # if field.multiple # originalData = _.clone(entity[navigationProperty]) # multiQuery = _.extend {_id: {$in: entity[navigationProperty]}}, include.query # entities[idx][navigationProperty] = referenceToCollection.find(multiQuery, queryOptions).fetch() # if !entities[idx][navigationProperty].length # entities[idx][navigationProperty] = originalData # #排序 # entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], originalData) # entities[idx][navigationProperty] = _.map entities[idx][navigationProperty], (o)-> # o['reference_to.o'] = referenceToCollection._name # o['reference_to._o'] = field.reference_to # o['_NAME_FIELD_VALUE'] = o[_ro_NAME_FIELD_KEY] # return o # else # singleQuery = _.extend {_id: entity[navigationProperty]}, include.query # # 特殊处理在相关表中没有找到数据的情况,返回原数据 # entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) || entities[idx][navigationProperty] # if entities[idx][navigationProperty] # entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name # entities[idx][navigationProperty]['reference_to._o'] = field.reference_to # entities[idx][navigationProperty]['_NAME_FIELD_VALUE'] = entities[idx][navigationProperty][_ro_NAME_FIELD_KEY] # if _.isArray field.reference_to # _.each entities, (entity, idx)-> # if entity[navigationProperty]?.ids # _o = entity[navigationProperty].o # _ro_NAME_FIELD_KEY = Creator.getObject(_o, spaceId)?.NAME_FIELD_KEY # if queryOptions?.fields && _ro_NAME_FIELD_KEY # queryOptions.fields[_ro_NAME_FIELD_KEY] = 1 # referenceToCollection = Creator.getCollection(entity[navigationProperty].o, spaceId) # if referenceToCollection # if field.multiple # _ids = _.clone(entity[navigationProperty].ids) # multiQuery = _.extend {_id: {$in: entity[navigationProperty].ids}}, include.query # entities[idx][navigationProperty] = _.map referenceToCollection.find(multiQuery, queryOptions).fetch(), (o)-> # o['reference_to.o'] = referenceToCollection._name # o['reference_to._o'] = _o # o['_NAME_FIELD_VALUE'] = o[_ro_NAME_FIELD_KEY] # return o # #排序 # entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], _ids) # else # singleQuery = _.extend {_id: entity[navigationProperty].ids[0]}, include.query # entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) # if entities[idx][navigationProperty] # entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name # entities[idx][navigationProperty]['reference_to._o'] = _o # entities[idx][navigationProperty]['_NAME_FIELD_VALUE'] = entities[idx][navigationProperty][_ro_NAME_FIELD_KEY] # else # # TODO # return # setOdataProperty=(entities,space,key)-> # entities_OdataProperties = [] # _.each entities, (entity, idx)-> # entity_OdataProperties = {} # id = entities[idx]["_id"] # entity_OdataProperties['@odata.id'] = SteedosOData.getODataNextLinkPath(space,key)+ '(\'' + "#{id}" + '\')' # entity_OdataProperties['@odata.etag'] = "W/\"08D589720BBB3DB1\"" # entity_OdataProperties['@odata.editLink'] = entity_OdataProperties['@odata.id'] # _.extend entity_OdataProperties,entity # entities_OdataProperties.push entity_OdataProperties # return entities_OdataProperties # setErrorMessage = (statusCode,collection,key,action)-> # body = {} # error = {} # innererror = {} # if statusCode == 404 # if collection # if action == 'post' # innererror['message'] = t("creator_odata_post_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_post_fail" # else # innererror['message'] = t("creator_odata_record_query_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_record_query_fail" # else # innererror['message'] = t("creator_odata_collection_query_fail")+ key # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_collection_query_fail" # if statusCode == 401 # innererror['message'] = t("creator_odata_authentication_required") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 401 # error['message'] = "creator_odata_authentication_required" # if statusCode == 403 # switch action # when 'get' then innererror['message'] = t("creator_odata_user_access_fail") # when 'post' then innererror['message'] = t("creator_odata_user_create_fail") # when 'put' then innererror['message'] = t("creator_odata_user_update_fail") # when 'delete' then innererror['message'] = t("creator_odata_user_remove_fail") # innererror['message'] = t("creator_odata_user_access_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 403 # error['message'] = "creator_odata_user_access_fail" # error['innererror'] = innererror # body['error'] = error # return body # removeInvalidMethod = (queryParams)-> # if queryParams.$filter && queryParams.$filter.indexOf('tolower(') > -1 # removeMethod = ($1)-> # return $1.replace('tolower(', '').replace(')', '') # queryParams.$filter = queryParams.$filter.replace(/tolower\(([^\)]+)\)/g, removeMethod) # isSameCompany = (spaceId, userId, companyId, query)-> # su = Creator.getCollection("space_users").findOne({ space: spaceId, user: userId }, { fields: { company_id: 1, company_ids: 1 } }) # if !companyId && query # companyId = su.company_id # query.company_id = { $in: su.company_ids } # return su.company_ids.includes(companyId) # # 不返回已假删除的数据 # excludeDeleted = (query)-> # query.is_deleted = { $ne: true } # # 修改、删除时,如果 doc.space = "global",报错 # checkGlobalRecord = (collection, id, object)-> # if object.enable_space_global && collection.find({ _id: id, space: 'global'}).count() # throw new Meteor.Error(400, "不能修改或者删除标准对象") # SteedosOdataAPI.addRoute(':object_name', {authRequired: true, spaceRequired: false}, { # get: ()-> # try # key = @urlParams.object_name # spaceId = @urlParams.spaceId # object = Creator.getObject(key, spaceId) # if not object?.enable_api # return { # statusCode: 401 # body:setErrorMessage(401) # } # collection = Creator.getCollection(key, spaceId) # if not collection # return { # statusCode: 404 # body:setErrorMessage(404,collection,key) # } # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if permissions.viewAllRecords or (permissions.viewCompanyRecords && isSameCompany(spaceId, @userId, createQuery.query.company_id, createQuery.query)) or (permissions.allowRead and @userId) # if key is '<KEY>' # createQuery.query['metadata.space'] = spaceId # else if key is 'spaces' # if spaceId isnt 'guest' # createQuery.query._id = spaceId # else # if spaceId isnt 'guest' and key != "users" and createQuery.query.space isnt 'global' # createQuery.query.space = spaceId # if Creator.isCommonSpace(spaceId) # if Creator.isSpaceAdmin(spaceId, @userId) # if key is 'spaces' # delete createQuery.query._id # else # delete createQuery.query.space # else # user_spaces = Creator.getCollection("space_users").find({user: @userId}, {fields: {space: 1}}).fetch() # if key is 'spaces' # # space 对所有用户记录为只读 # delete createQuery.query._id # # createQuery.query._id = {$in: _.pluck(user_spaces, 'space')} # else # createQuery.query.space = {$in: _.pluck(user_spaces, 'space')} # if not createQuery.sort or !_.size(createQuery.sort) # createQuery.sort = { modified: -1 } # is_enterprise = Steedos.isLegalVersion(spaceId,"workflow.enterprise") # is_professional = Steedos.isLegalVersion(spaceId,"workflow.professional") # is_standard = Steedos.isLegalVersion(spaceId,"workflow.standard") # if createQuery.limit # limit = createQuery.limit # if is_enterprise and limit>100000 # createQuery.limit = 100000 # else if is_professional and limit>10000 and !is_enterprise # createQuery.limit = 10000 # else if is_standard and limit>1000 and !is_professional and !is_enterprise # createQuery.limit = 1000 # else # if is_enterprise # createQuery.limit = 100000 # else if is_professional and !is_enterprise # createQuery.limit = 10000 # else if is_standard and !is_enterprise and !is_professional # createQuery.limit = 1000 # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # #if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, spaceId, @userId) # fields = Creator.getObject(key, spaceId).fields # _.each readable_fields, (field)-> # if field.indexOf('$') < 0 # #if fields[field]?.multiple!= true # createQuery.projection[field] = 1 # if not permissions.viewAllRecords && !permissions.viewCompanyRecords # if object.enable_share # # 满足共享规则中的记录也要搜索出来 # delete createQuery.query.owner # shares = [] # orgs = Steedos.getUserOrganizations(spaceId, @userId, true) # shares.push {"owner": @userId} # shares.push { "sharing.u": @userId } # shares.push { "sharing.o": { $in: orgs } } # createQuery.query["$or"] = shares # else # createQuery.query.owner = @userId # entities = [] # excludeDeleted(createQuery.query) # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # scannedCount = collection.find(createQuery.query,{fields:{_id: 1}}).count() # if entities # dealWithExpand(createQuery, entities, key, spaceId) # #scannedCount = entities.length # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) # # body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(spaceId,key)+"?%24skip="+ 10 # body['@odata.count'] = scannedCount # entities_OdataProperties = setOdataProperty(entities,spaceId, key) # body['value'] = entities_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,"get") # } # catch e # return handleError e # post: ()-> # try # key = @urlParams.object_name # spaceId = @urlParams.spaceId # if not Creator.getObject(key, spaceId)?.enable_api # return { # statusCode: 401 # body:setErrorMessage(401) # } # collection = Creator.getCollection(key, spaceId) # if not collection # return { # statusCode: 404 # body:setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = spaceId # if spaceId is 'guest' # delete @bodyParams.space # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # entities = [] # if entity # body = {} # headers = {} # entities.push entity # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # body['value'] = entity_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'post') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'post') # } # catch e # return handleError e # }) # SteedosOdataAPI.addRoute(':object_name/recent', {authRequired: true, spaceRequired: false}, { # get:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return { # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # recent_view_collection = Creator.Collections["object_recent_viewed"] # recent_view_selector = {"record.o":key,created_by:@userId} # recent_view_options = {} # recent_view_options.sort = {created: -1} # recent_view_options.fields = {record:1} # recent_view_records = recent_view_collection.find(recent_view_selector,recent_view_options).fetch() # recent_view_records_ids = _.pluck(recent_view_records,'record') # recent_view_records_ids = recent_view_records_ids.getProperty("ids") # recent_view_records_ids = _.flatten(recent_view_records_ids) # recent_view_records_ids = _.uniq(recent_view_records_ids) # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # if key is '<KEY>' # createQuery.query['metadata.space'] = @urlParams.spaceId # else # createQuery.query.space = @urlParams.spaceId # if not createQuery.limit # createQuery.limit = 100 # if createQuery.limit and recent_view_records_ids.length>createQuery.limit # recent_view_records_ids = _.first(recent_view_records_ids,createQuery.limit) # createQuery.query._id = {$in:recent_view_records_ids} # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # # if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId) # fields = Creator.getObject(key, @urlParams.spaceId).fields # _.each readable_fields, (field)-> # if field.indexOf('$') < 0 # #if fields[field]?.multiple!= true # createQuery.projection[field] = 1 # excludeDeleted(createQuery.query) # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # entities_index = [] # entities_ids = _.pluck(entities,'_id') # sort_entities = [] # if not createQuery.sort or !_.size(createQuery.sort) # _.each recent_view_records_ids ,(recent_view_records_id)-> # index = _.indexOf(entities_ids,recent_view_records_id) # if index>-1 # sort_entities.push entities[index] # else # sort_entities = entities # if sort_entities # dealWithExpand(createQuery, sort_entities, key, @urlParams.spaceId) # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) # # body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(@urlParams.spaceId,key)+"?%24skip="+ 10 # body['@odata.count'] = sort_entities.length # entities_OdataProperties = setOdataProperty(sort_entities,@urlParams.spaceId, key) # body['value'] = entities_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'get') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # catch e # return handleError e # }) # SteedosOdataAPI.addRoute(':object_name/:_id', {authRequired: true, spaceRequired: false}, { # post: ()-> # try # key = @urlParams.object_name # if not Creator.getObject(key, @urlParams.spaceId)?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = @urlParams.spaceId # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # entities = [] # if entity # body = {} # headers = {} # entities.push entity # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key) # body['value'] = entity_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'post') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'post') # } # catch e # return handleError e # get:()-> # key = @urlParams.object_name # if key.indexOf("(") > -1 # body = {} # headers = {} # collectionInfo = key # fieldName = @urlParams._id.split('_expand')[0] # collectionInfoSplit = collectionInfo.split('(') # collectionName = collectionInfoSplit[0] # id = collectionInfoSplit[1].split('\'')[1] # collection = Creator.getCollection(collectionName, @urlParams.spaceId) # fieldsOptions = {} # fieldsOptions[fieldName] = 1 # entity = collection.findOne({_id: id}, {fields: fieldsOptions}) # fieldValue = null # if entity # fieldValue = entity[fieldName] # obj = Creator.getObject(collectionName, @urlParams.spaceId) # field = obj.fields[fieldName] # if field and fieldValue and (field.type is 'lookup' or field.type is 'master_detail') # lookupCollection = Creator.getCollection(field.reference_to, @urlParams.spaceId) # queryOptions = {fields: {}} # readable_fields = Creator.getFields(field.reference_to, @urlParams.spaceId, @userId) # _.each readable_fields, (f)-> # if f.indexOf('$') < 0 # queryOptions.fields[f] = 1 # if field.multiple # values = [] # lookupCollection.find({_id: {$in: fieldValue}}, queryOptions).forEach (obj)-> # _.each obj, (v, k)-> # if _.isArray(v) || (_.isObject(v) && !_.isDate(v)) # obj[k] = JSON.stringify(v) # values.push(obj) # body['value'] = values # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}" # else # body = lookupCollection.findOne({_id: fieldValue}, queryOptions) || {} # _.each body, (v, k)-> # if _.isArray(v) || (_.isObject(v) && !_.isDate(v)) # body[k] = JSON.stringify(v) # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{field.reference_to}/$entity" # else # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}" # body['value'] = fieldValue # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # try # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return { # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # unreadable_fields = permissions.unreadable_fields || [] # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # createQuery.query._id = @urlParams._id # if key is '<KEY>' # createQuery.query['metadata.space'] = @urlParams.spaceId # else if key != '<KEY>' # createQuery.query.space = @urlParams.spaceId # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # # if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId) # fields = object.fields # _.each readable_fields, (field) -> # if field.indexOf('$') < 0 # createQuery.projection[field] = 1 # entity = collection.findOne(createQuery.query,visitorParser(createQuery)) # entities = [] # if entity # isAllowed = entity.owner == @userId or permissions.viewAllRecords or (permissions.viewCompanyRecords && isSameCompany(@urlParams.spaceId, @userId, entity.company_id)) # if object.enable_share and !isAllowed # shares = [] # orgs = Steedos.getUserOrganizations(@urlParams.spaceId, @userId, true) # shares.push { "sharing.u": @userId } # shares.push { "sharing.o": { $in: orgs } } # isAllowed = collection.findOne({ _id: @urlParams._id, "$or": shares }, { fields: { _id: 1 } }) # if isAllowed # body = {} # headers = {} # entities.push entity # dealWithExpand(createQuery, entities, key, @urlParams.spaceId) # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key) # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'get') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # catch e # return handleError e # put:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # spaceId = @urlParams.spaceId # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if key == "users" # record_owner = @urlParams._id # else # record_owner = collection.findOne({ _id: @urlParams._id }, { fields: { owner: 1 } })?.owner # companyId = collection.findOne({ _id: @urlParams._id }, { fields: { company_id: 1 } })?.company_id # isAllowed = permissions.modifyAllRecords or (permissions.allowEdit and record_owner == @userId ) or (permissions.modifyCompanyRecords && isSameCompany(spaceId, @userId, companyId)) # if isAllowed # checkGlobalRecord(collection, @urlParams._id, object) # selector = {_id: @urlParams._id, space: spaceId} # if spaceId is 'guest' or spaceId is 'common' or key == "users" # delete selector.space # fields_editable = true # _.keys(@bodyParams.$set).forEach (key)-> # if _.indexOf(permissions.uneditable_fields, key) > -1 # fields_editable = false # if fields_editable # if key is 'spaces' # delete selector.space # entityIsUpdated = collection.update selector, @bodyParams # if entityIsUpdated # #statusCode: 201 # # entity = collection.findOne @urlParams._id # # entities = [] # # body = {} # headers = {} # body = {} # # entities.push entity # # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'put') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'put') # } # catch e # return handleError e # delete:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # spaceId = @urlParams.spaceId # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # recordData = collection.findOne({_id: @urlParams._id}, { fields: { owner: 1, company_id: 1 } }) # record_owner = recordData?.owner # companyId = recordData?.company_id # isAllowed = (permissions.modifyAllRecords and permissions.allowDelete) or (permissions.modifyCompanyRecords and permissions.allowDelete and isSameCompany(spaceId, @userId, companyId)) or (permissions.allowDelete and record_owner==@userId ) # if isAllowed # checkGlobalRecord(collection, @urlParams._id, object) # selector = {_id: @urlParams._id, space: spaceId} # if spaceId is 'guest' # delete selector.space # if object?.enable_trash # entityIsUpdated = collection.update(selector, { # $set: { # is_deleted: true, # deleted: new Date(), # deleted_by: @userId # } # }) # if entityIsUpdated # headers = {} # body = {} # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # if collection.remove selector # headers = {} # body = {} # # entities.push entity # # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return { # statusCode: 403 # body: setErrorMessage(403,collection,key) # } # catch e # return handleError e # }) # # _id可传all # SteedosOdataAPI.addRoute(':object_name/:_id/:methodName', {authRequired: true, spaceRequired: false}, { # post: ()-> # try # key = @urlParams.object_name # if not Creator.getObject(key, @urlParams.spaceId)?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # methodName = @urlParams.methodName # methods = Creator.Objects[key]?.methods || {} # if methods.hasOwnProperty(methodName) # thisObj = { # object_name: key # record_id: @urlParams._id # space_id: @urlParams.spaceId # user_id: @userId # permissions: permissions # } # return methods[methodName].apply(thisObj, [@bodyParams]) || {} # else # return { # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return { # statusCode: 403 # body: setErrorMessage(403,collection,key) # } # catch e # return handleError e # }) # #TODO remove # _.each [], (value, key, list)-> #Creator.Collections # if not Creator.getObject(key)?.enable_api # return # if SteedosOdataAPI # SteedosOdataAPI.addCollection Creator.getCollection(key), # excludedEndpoints: [] # routeOptions: # authRequired: true # spaceRequired: false # endpoints: # getAll: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.viewAllRecords or (permissions.allowRead and @userId) # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # if key is '<KEY>' # createQuery.query['metadata.space'] = @urlParams.spaceId # else # createQuery.query.space = @urlParams.spaceId # if not permissions.viewAllRecords # createQuery.query.owner = @userId # entities = [] # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # scannedCount = collection.find(createQuery.query).count() # if entities # dealWithExpand(createQuery, entities, key, @urlParams.spaceId) # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) # body['@odata.count'] = scannedCount # body['value'] = entities # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # statusCode: 404 # body: {status: 'fail', message: 'Unable to retrieve items from collection'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # post: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = @spaceId # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # if entity # statusCode: 201 # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'No item added'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # get: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowRead # selector = {_id: @urlParams.id, space: @spaceId} # entity = collection.findOne selector # if entity # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # put: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowEdit # selector = {_id: @urlParams.id, space: @spaceId} # entityIsUpdated = collection.update selector, $set: @bodyParams # if entityIsUpdated # entity = collection.findOne @urlParams.id # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # delete: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowDelete # selector = {_id: @urlParams.id, space: @spaceId} # if collection.remove selector # {status: 'success', message: 'Item removed'} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'}
true
Meteor.startup -> MeteorODataRouter = require('@steedos/core').MeteorODataRouter; ODataRouter = require('@steedos/core').ODataRouter express = require('express'); app = express(); app.use('/api/odata/v4', MeteorODataRouter); MeteorODataAPIV4Router = require('@steedos/core').MeteorODataAPIV4Router; if MeteorODataAPIV4Router app.use('/api/v4', MeteorODataAPIV4Router) WebApp.connectHandlers.use(app); _.each Creator.steedosSchema.getDataSources(), (datasource, name)-> if(name != 'default') otherApp = express(); otherApp.use("/api/odata/#{name}", ODataRouter); WebApp.connectHandlers.use(otherApp); # odataV4Mongodb = require 'odata-v4-mongodb' # querystring = require 'querystring' # handleError = (e)-> # console.error e.stack # body = {} # error = {} # error['message'] = e.message # statusCode = 500 # if e.error and _.isNumber(e.error) # statusCode = e.error # error['code'] = statusCode # error['error'] = statusCode # error['details'] = e.details # error['reason'] = e.reason # body['error'] = error # return { # statusCode: statusCode # body:body # } # visitorParser = (visitor)-> # parsedOpt = {} # if visitor.projection # parsedOpt.fields = visitor.projection # if visitor.hasOwnProperty('limit') # parsedOpt.limit = visitor.limit # if visitor.hasOwnProperty('skip') # parsedOpt.skip = visitor.skip # if visitor.sort # parsedOpt.sort = visitor.sort # parsedOpt # dealWithExpand = (createQuery, entities, key, spaceId)-> # if _.isEmpty createQuery.includes # return # obj = Creator.getObject(key, spaceId) # _.each createQuery.includes, (include)-> # # console.log 'include: ', include # navigationProperty = include.navigationProperty # # console.log 'navigationProperty: ', navigationProperty # field = obj.fields[navigationProperty] # if field and (field.type is 'lookup' or field.type is 'master_detail') # if _.isFunction(field.reference_to) # field.reference_to = field.reference_to() # if field.reference_to # queryOptions = visitorParser(include) # if _.isString field.reference_to # referenceToCollection = Creator.getCollection(field.reference_to, spaceId) # _ro_NAME_FIELD_KEY = Creator.getObject(field.reference_to, spaceId)?.NAME_FIELD_KEY # _.each entities, (entity, idx)-> # if entity[navigationProperty] # if field.multiple # originalData = _.clone(entity[navigationProperty]) # multiQuery = _.extend {_id: {$in: entity[navigationProperty]}}, include.query # entities[idx][navigationProperty] = referenceToCollection.find(multiQuery, queryOptions).fetch() # if !entities[idx][navigationProperty].length # entities[idx][navigationProperty] = originalData # #排序 # entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], originalData) # entities[idx][navigationProperty] = _.map entities[idx][navigationProperty], (o)-> # o['reference_to.o'] = referenceToCollection._name # o['reference_to._o'] = field.reference_to # o['_NAME_FIELD_VALUE'] = o[_ro_NAME_FIELD_KEY] # return o # else # singleQuery = _.extend {_id: entity[navigationProperty]}, include.query # # 特殊处理在相关表中没有找到数据的情况,返回原数据 # entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) || entities[idx][navigationProperty] # if entities[idx][navigationProperty] # entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name # entities[idx][navigationProperty]['reference_to._o'] = field.reference_to # entities[idx][navigationProperty]['_NAME_FIELD_VALUE'] = entities[idx][navigationProperty][_ro_NAME_FIELD_KEY] # if _.isArray field.reference_to # _.each entities, (entity, idx)-> # if entity[navigationProperty]?.ids # _o = entity[navigationProperty].o # _ro_NAME_FIELD_KEY = Creator.getObject(_o, spaceId)?.NAME_FIELD_KEY # if queryOptions?.fields && _ro_NAME_FIELD_KEY # queryOptions.fields[_ro_NAME_FIELD_KEY] = 1 # referenceToCollection = Creator.getCollection(entity[navigationProperty].o, spaceId) # if referenceToCollection # if field.multiple # _ids = _.clone(entity[navigationProperty].ids) # multiQuery = _.extend {_id: {$in: entity[navigationProperty].ids}}, include.query # entities[idx][navigationProperty] = _.map referenceToCollection.find(multiQuery, queryOptions).fetch(), (o)-> # o['reference_to.o'] = referenceToCollection._name # o['reference_to._o'] = _o # o['_NAME_FIELD_VALUE'] = o[_ro_NAME_FIELD_KEY] # return o # #排序 # entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], _ids) # else # singleQuery = _.extend {_id: entity[navigationProperty].ids[0]}, include.query # entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) # if entities[idx][navigationProperty] # entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name # entities[idx][navigationProperty]['reference_to._o'] = _o # entities[idx][navigationProperty]['_NAME_FIELD_VALUE'] = entities[idx][navigationProperty][_ro_NAME_FIELD_KEY] # else # # TODO # return # setOdataProperty=(entities,space,key)-> # entities_OdataProperties = [] # _.each entities, (entity, idx)-> # entity_OdataProperties = {} # id = entities[idx]["_id"] # entity_OdataProperties['@odata.id'] = SteedosOData.getODataNextLinkPath(space,key)+ '(\'' + "#{id}" + '\')' # entity_OdataProperties['@odata.etag'] = "W/\"08D589720BBB3DB1\"" # entity_OdataProperties['@odata.editLink'] = entity_OdataProperties['@odata.id'] # _.extend entity_OdataProperties,entity # entities_OdataProperties.push entity_OdataProperties # return entities_OdataProperties # setErrorMessage = (statusCode,collection,key,action)-> # body = {} # error = {} # innererror = {} # if statusCode == 404 # if collection # if action == 'post' # innererror['message'] = t("creator_odata_post_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_post_fail" # else # innererror['message'] = t("creator_odata_record_query_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_record_query_fail" # else # innererror['message'] = t("creator_odata_collection_query_fail")+ key # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 404 # error['message'] = "creator_odata_collection_query_fail" # if statusCode == 401 # innererror['message'] = t("creator_odata_authentication_required") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 401 # error['message'] = "creator_odata_authentication_required" # if statusCode == 403 # switch action # when 'get' then innererror['message'] = t("creator_odata_user_access_fail") # when 'post' then innererror['message'] = t("creator_odata_user_create_fail") # when 'put' then innererror['message'] = t("creator_odata_user_update_fail") # when 'delete' then innererror['message'] = t("creator_odata_user_remove_fail") # innererror['message'] = t("creator_odata_user_access_fail") # innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException' # error['code'] = 403 # error['message'] = "creator_odata_user_access_fail" # error['innererror'] = innererror # body['error'] = error # return body # removeInvalidMethod = (queryParams)-> # if queryParams.$filter && queryParams.$filter.indexOf('tolower(') > -1 # removeMethod = ($1)-> # return $1.replace('tolower(', '').replace(')', '') # queryParams.$filter = queryParams.$filter.replace(/tolower\(([^\)]+)\)/g, removeMethod) # isSameCompany = (spaceId, userId, companyId, query)-> # su = Creator.getCollection("space_users").findOne({ space: spaceId, user: userId }, { fields: { company_id: 1, company_ids: 1 } }) # if !companyId && query # companyId = su.company_id # query.company_id = { $in: su.company_ids } # return su.company_ids.includes(companyId) # # 不返回已假删除的数据 # excludeDeleted = (query)-> # query.is_deleted = { $ne: true } # # 修改、删除时,如果 doc.space = "global",报错 # checkGlobalRecord = (collection, id, object)-> # if object.enable_space_global && collection.find({ _id: id, space: 'global'}).count() # throw new Meteor.Error(400, "不能修改或者删除标准对象") # SteedosOdataAPI.addRoute(':object_name', {authRequired: true, spaceRequired: false}, { # get: ()-> # try # key = @urlParams.object_name # spaceId = @urlParams.spaceId # object = Creator.getObject(key, spaceId) # if not object?.enable_api # return { # statusCode: 401 # body:setErrorMessage(401) # } # collection = Creator.getCollection(key, spaceId) # if not collection # return { # statusCode: 404 # body:setErrorMessage(404,collection,key) # } # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if permissions.viewAllRecords or (permissions.viewCompanyRecords && isSameCompany(spaceId, @userId, createQuery.query.company_id, createQuery.query)) or (permissions.allowRead and @userId) # if key is 'PI:KEY:<KEY>END_PI' # createQuery.query['metadata.space'] = spaceId # else if key is 'spaces' # if spaceId isnt 'guest' # createQuery.query._id = spaceId # else # if spaceId isnt 'guest' and key != "users" and createQuery.query.space isnt 'global' # createQuery.query.space = spaceId # if Creator.isCommonSpace(spaceId) # if Creator.isSpaceAdmin(spaceId, @userId) # if key is 'spaces' # delete createQuery.query._id # else # delete createQuery.query.space # else # user_spaces = Creator.getCollection("space_users").find({user: @userId}, {fields: {space: 1}}).fetch() # if key is 'spaces' # # space 对所有用户记录为只读 # delete createQuery.query._id # # createQuery.query._id = {$in: _.pluck(user_spaces, 'space')} # else # createQuery.query.space = {$in: _.pluck(user_spaces, 'space')} # if not createQuery.sort or !_.size(createQuery.sort) # createQuery.sort = { modified: -1 } # is_enterprise = Steedos.isLegalVersion(spaceId,"workflow.enterprise") # is_professional = Steedos.isLegalVersion(spaceId,"workflow.professional") # is_standard = Steedos.isLegalVersion(spaceId,"workflow.standard") # if createQuery.limit # limit = createQuery.limit # if is_enterprise and limit>100000 # createQuery.limit = 100000 # else if is_professional and limit>10000 and !is_enterprise # createQuery.limit = 10000 # else if is_standard and limit>1000 and !is_professional and !is_enterprise # createQuery.limit = 1000 # else # if is_enterprise # createQuery.limit = 100000 # else if is_professional and !is_enterprise # createQuery.limit = 10000 # else if is_standard and !is_enterprise and !is_professional # createQuery.limit = 1000 # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # #if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, spaceId, @userId) # fields = Creator.getObject(key, spaceId).fields # _.each readable_fields, (field)-> # if field.indexOf('$') < 0 # #if fields[field]?.multiple!= true # createQuery.projection[field] = 1 # if not permissions.viewAllRecords && !permissions.viewCompanyRecords # if object.enable_share # # 满足共享规则中的记录也要搜索出来 # delete createQuery.query.owner # shares = [] # orgs = Steedos.getUserOrganizations(spaceId, @userId, true) # shares.push {"owner": @userId} # shares.push { "sharing.u": @userId } # shares.push { "sharing.o": { $in: orgs } } # createQuery.query["$or"] = shares # else # createQuery.query.owner = @userId # entities = [] # excludeDeleted(createQuery.query) # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # scannedCount = collection.find(createQuery.query,{fields:{_id: 1}}).count() # if entities # dealWithExpand(createQuery, entities, key, spaceId) # #scannedCount = entities.length # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) # # body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(spaceId,key)+"?%24skip="+ 10 # body['@odata.count'] = scannedCount # entities_OdataProperties = setOdataProperty(entities,spaceId, key) # body['value'] = entities_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,"get") # } # catch e # return handleError e # post: ()-> # try # key = @urlParams.object_name # spaceId = @urlParams.spaceId # if not Creator.getObject(key, spaceId)?.enable_api # return { # statusCode: 401 # body:setErrorMessage(401) # } # collection = Creator.getCollection(key, spaceId) # if not collection # return { # statusCode: 404 # body:setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = spaceId # if spaceId is 'guest' # delete @bodyParams.space # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # entities = [] # if entity # body = {} # headers = {} # entities.push entity # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # body['value'] = entity_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'post') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'post') # } # catch e # return handleError e # }) # SteedosOdataAPI.addRoute(':object_name/recent', {authRequired: true, spaceRequired: false}, { # get:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return { # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # recent_view_collection = Creator.Collections["object_recent_viewed"] # recent_view_selector = {"record.o":key,created_by:@userId} # recent_view_options = {} # recent_view_options.sort = {created: -1} # recent_view_options.fields = {record:1} # recent_view_records = recent_view_collection.find(recent_view_selector,recent_view_options).fetch() # recent_view_records_ids = _.pluck(recent_view_records,'record') # recent_view_records_ids = recent_view_records_ids.getProperty("ids") # recent_view_records_ids = _.flatten(recent_view_records_ids) # recent_view_records_ids = _.uniq(recent_view_records_ids) # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # if key is 'PI:KEY:<KEY>END_PI' # createQuery.query['metadata.space'] = @urlParams.spaceId # else # createQuery.query.space = @urlParams.spaceId # if not createQuery.limit # createQuery.limit = 100 # if createQuery.limit and recent_view_records_ids.length>createQuery.limit # recent_view_records_ids = _.first(recent_view_records_ids,createQuery.limit) # createQuery.query._id = {$in:recent_view_records_ids} # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # # if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId) # fields = Creator.getObject(key, @urlParams.spaceId).fields # _.each readable_fields, (field)-> # if field.indexOf('$') < 0 # #if fields[field]?.multiple!= true # createQuery.projection[field] = 1 # excludeDeleted(createQuery.query) # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # entities_index = [] # entities_ids = _.pluck(entities,'_id') # sort_entities = [] # if not createQuery.sort or !_.size(createQuery.sort) # _.each recent_view_records_ids ,(recent_view_records_id)-> # index = _.indexOf(entities_ids,recent_view_records_id) # if index>-1 # sort_entities.push entities[index] # else # sort_entities = entities # if sort_entities # dealWithExpand(createQuery, sort_entities, key, @urlParams.spaceId) # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) # # body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(@urlParams.spaceId,key)+"?%24skip="+ 10 # body['@odata.count'] = sort_entities.length # entities_OdataProperties = setOdataProperty(sort_entities,@urlParams.spaceId, key) # body['value'] = entities_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'get') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # catch e # return handleError e # }) # SteedosOdataAPI.addRoute(':object_name/:_id', {authRequired: true, spaceRequired: false}, { # post: ()-> # try # key = @urlParams.object_name # if not Creator.getObject(key, @urlParams.spaceId)?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = @urlParams.spaceId # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # entities = [] # if entity # body = {} # headers = {} # entities.push entity # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key) # body['value'] = entity_OdataProperties # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'post') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'post') # } # catch e # return handleError e # get:()-> # key = @urlParams.object_name # if key.indexOf("(") > -1 # body = {} # headers = {} # collectionInfo = key # fieldName = @urlParams._id.split('_expand')[0] # collectionInfoSplit = collectionInfo.split('(') # collectionName = collectionInfoSplit[0] # id = collectionInfoSplit[1].split('\'')[1] # collection = Creator.getCollection(collectionName, @urlParams.spaceId) # fieldsOptions = {} # fieldsOptions[fieldName] = 1 # entity = collection.findOne({_id: id}, {fields: fieldsOptions}) # fieldValue = null # if entity # fieldValue = entity[fieldName] # obj = Creator.getObject(collectionName, @urlParams.spaceId) # field = obj.fields[fieldName] # if field and fieldValue and (field.type is 'lookup' or field.type is 'master_detail') # lookupCollection = Creator.getCollection(field.reference_to, @urlParams.spaceId) # queryOptions = {fields: {}} # readable_fields = Creator.getFields(field.reference_to, @urlParams.spaceId, @userId) # _.each readable_fields, (f)-> # if f.indexOf('$') < 0 # queryOptions.fields[f] = 1 # if field.multiple # values = [] # lookupCollection.find({_id: {$in: fieldValue}}, queryOptions).forEach (obj)-> # _.each obj, (v, k)-> # if _.isArray(v) || (_.isObject(v) && !_.isDate(v)) # obj[k] = JSON.stringify(v) # values.push(obj) # body['value'] = values # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}" # else # body = lookupCollection.findOne({_id: fieldValue}, queryOptions) || {} # _.each body, (v, k)-> # if _.isArray(v) || (_.isObject(v) && !_.isDate(v)) # body[k] = JSON.stringify(v) # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{field.reference_to}/$entity" # else # body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}" # body['value'] = fieldValue # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # try # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return { # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # unreadable_fields = permissions.unreadable_fields || [] # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # createQuery.query._id = @urlParams._id # if key is 'PI:KEY:<KEY>END_PI' # createQuery.query['metadata.space'] = @urlParams.spaceId # else if key != 'PI:KEY:<KEY>END_PI' # createQuery.query.space = @urlParams.spaceId # unreadable_fields = permissions.unreadable_fields || [] # if createQuery.projection # projection = {} # _.keys(createQuery.projection).forEach (key)-> # if _.indexOf(unreadable_fields, key) < 0 # # if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple) # projection[key] = 1 # createQuery.projection = projection # if not createQuery.projection or !_.size(createQuery.projection) # readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId) # fields = object.fields # _.each readable_fields, (field) -> # if field.indexOf('$') < 0 # createQuery.projection[field] = 1 # entity = collection.findOne(createQuery.query,visitorParser(createQuery)) # entities = [] # if entity # isAllowed = entity.owner == @userId or permissions.viewAllRecords or (permissions.viewCompanyRecords && isSameCompany(@urlParams.spaceId, @userId, entity.company_id)) # if object.enable_share and !isAllowed # shares = [] # orgs = Steedos.getUserOrganizations(@urlParams.spaceId, @userId, true) # shares.push { "sharing.u": @userId } # shares.push { "sharing.o": { $in: orgs } } # isAllowed = collection.findOne({ _id: @urlParams._id, "$or": shares }, { fields: { _id: 1 } }) # if isAllowed # body = {} # headers = {} # entities.push entity # dealWithExpand(createQuery, entities, key, @urlParams.spaceId) # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity' # entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key) # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key,'get') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'get') # } # catch e # return handleError e # put:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # spaceId = @urlParams.spaceId # permissions = Creator.getObjectPermissions(spaceId, @userId, key) # if key == "users" # record_owner = @urlParams._id # else # record_owner = collection.findOne({ _id: @urlParams._id }, { fields: { owner: 1 } })?.owner # companyId = collection.findOne({ _id: @urlParams._id }, { fields: { company_id: 1 } })?.company_id # isAllowed = permissions.modifyAllRecords or (permissions.allowEdit and record_owner == @userId ) or (permissions.modifyCompanyRecords && isSameCompany(spaceId, @userId, companyId)) # if isAllowed # checkGlobalRecord(collection, @urlParams._id, object) # selector = {_id: @urlParams._id, space: spaceId} # if spaceId is 'guest' or spaceId is 'common' or key == "users" # delete selector.space # fields_editable = true # _.keys(@bodyParams.$set).forEach (key)-> # if _.indexOf(permissions.uneditable_fields, key) > -1 # fields_editable = false # if fields_editable # if key is 'spaces' # delete selector.space # entityIsUpdated = collection.update selector, @bodyParams # if entityIsUpdated # #statusCode: 201 # # entity = collection.findOne @urlParams._id # # entities = [] # # body = {} # headers = {} # body = {} # # entities.push entity # # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'put') # } # else # return{ # statusCode: 403 # body: setErrorMessage(403,collection,key,'put') # } # catch e # return handleError e # delete:()-> # try # key = @urlParams.object_name # object = Creator.getObject(key, @urlParams.spaceId) # if not object?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # spaceId = @urlParams.spaceId # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # recordData = collection.findOne({_id: @urlParams._id}, { fields: { owner: 1, company_id: 1 } }) # record_owner = recordData?.owner # companyId = recordData?.company_id # isAllowed = (permissions.modifyAllRecords and permissions.allowDelete) or (permissions.modifyCompanyRecords and permissions.allowDelete and isSameCompany(spaceId, @userId, companyId)) or (permissions.allowDelete and record_owner==@userId ) # if isAllowed # checkGlobalRecord(collection, @urlParams._id, object) # selector = {_id: @urlParams._id, space: spaceId} # if spaceId is 'guest' # delete selector.space # if object?.enable_trash # entityIsUpdated = collection.update(selector, { # $set: { # is_deleted: true, # deleted: new Date(), # deleted_by: @userId # } # }) # if entityIsUpdated # headers = {} # body = {} # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # if collection.remove selector # headers = {} # body = {} # # entities.push entity # # body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity' # # entity_OdataProperties = setOdataProperty(entities,spaceId, key) # # _.extend body,entity_OdataProperties[0] # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {headers: headers,body:body} # else # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return { # statusCode: 403 # body: setErrorMessage(403,collection,key) # } # catch e # return handleError e # }) # # _id可传all # SteedosOdataAPI.addRoute(':object_name/:_id/:methodName', {authRequired: true, spaceRequired: false}, { # post: ()-> # try # key = @urlParams.object_name # if not Creator.getObject(key, @urlParams.spaceId)?.enable_api # return{ # statusCode: 401 # body: setErrorMessage(401) # } # collection = Creator.getCollection(key, @urlParams.spaceId) # if not collection # return{ # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.allowRead # methodName = @urlParams.methodName # methods = Creator.Objects[key]?.methods || {} # if methods.hasOwnProperty(methodName) # thisObj = { # object_name: key # record_id: @urlParams._id # space_id: @urlParams.spaceId # user_id: @userId # permissions: permissions # } # return methods[methodName].apply(thisObj, [@bodyParams]) || {} # else # return { # statusCode: 404 # body: setErrorMessage(404,collection,key) # } # else # return { # statusCode: 403 # body: setErrorMessage(403,collection,key) # } # catch e # return handleError e # }) # #TODO remove # _.each [], (value, key, list)-> #Creator.Collections # if not Creator.getObject(key)?.enable_api # return # if SteedosOdataAPI # SteedosOdataAPI.addCollection Creator.getCollection(key), # excludedEndpoints: [] # routeOptions: # authRequired: true # spaceRequired: false # endpoints: # getAll: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key) # if permissions.viewAllRecords or (permissions.allowRead and @userId) # removeInvalidMethod(@queryParams) # qs = decodeURIComponent(querystring.stringify(@queryParams)) # createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery() # if key is 'PI:KEY:<KEY>END_PI' # createQuery.query['metadata.space'] = @urlParams.spaceId # else # createQuery.query.space = @urlParams.spaceId # if not permissions.viewAllRecords # createQuery.query.owner = @userId # entities = [] # if @queryParams.$top isnt '0' # entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch() # scannedCount = collection.find(createQuery.query).count() # if entities # dealWithExpand(createQuery, entities, key, @urlParams.spaceId) # body = {} # headers = {} # body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) # body['@odata.count'] = scannedCount # body['value'] = entities # headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8' # headers['OData-Version'] = SteedosOData.VERSION # {body: body, headers: headers} # else # statusCode: 404 # body: {status: 'fail', message: 'Unable to retrieve items from collection'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # post: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowCreate # @bodyParams.space = @spaceId # entityId = collection.insert @bodyParams # entity = collection.findOne entityId # if entity # statusCode: 201 # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'No item added'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # get: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowRead # selector = {_id: @urlParams.id, space: @spaceId} # entity = collection.findOne selector # if entity # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # put: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowEdit # selector = {_id: @urlParams.id, space: @spaceId} # entityIsUpdated = collection.update selector, $set: @bodyParams # if entityIsUpdated # entity = collection.findOne @urlParams.id # {status: 'success', value: entity} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'} # delete: # action: -> # collection = Creator.getCollection(key) # if not collection # statusCode: 404 # body: {status: 'fail', message: 'Collection not found'} # permissions = Creator.getObjectPermissions(@spaceId, @userId, key) # if permissions.allowDelete # selector = {_id: @urlParams.id, space: @spaceId} # if collection.remove selector # {status: 'success', message: 'Item removed'} # else # statusCode: 404 # body: {status: 'fail', message: 'Item not found'} # else # statusCode: 400 # body: {status: 'fail', message: 'Action not permitted'}
[ { "context": " Info : http://bit.ly/LsODY8\n\t* Copyright (c) 2013 Stephen Braitsch\n*\n###\n\nexpress = require('express')\nhttp = requir", "end": 108, "score": 0.999860942363739, "start": 92, "tag": "NAME", "value": "Stephen Braitsch" } ]
app.coffee
VirsixInc/serverSide
0
###* * Node.js Login Boilerplate * More Info : http://bit.ly/LsODY8 * Copyright (c) 2013 Stephen Braitsch * ### express = require('express') http = require('http') bodyParser = require('body-parser') multer = require('multer') app = express() app.configure -> app.set 'port', 8000 app.set 'views', __dirname + '/app/views' app.set 'view engine', 'jade' app.set 'view options',{layout:false} app.locals.pretty = true app.use bodyParser.urlencoded({extended:true}) app.use express.cookieParser() app.use express.session(secret: 'super-duper-secret-secret') app.use express.methodOverride() app.use express.multipart() app.use express.static(__dirname + '/dist/') return app.configure 'development', -> app.use express.errorHandler() return require('./app/router') app http.createServer(app).listen app.get('port'), -> console.log 'Express server listening on port ' + app.get('port') return
160001
###* * Node.js Login Boilerplate * More Info : http://bit.ly/LsODY8 * Copyright (c) 2013 <NAME> * ### express = require('express') http = require('http') bodyParser = require('body-parser') multer = require('multer') app = express() app.configure -> app.set 'port', 8000 app.set 'views', __dirname + '/app/views' app.set 'view engine', 'jade' app.set 'view options',{layout:false} app.locals.pretty = true app.use bodyParser.urlencoded({extended:true}) app.use express.cookieParser() app.use express.session(secret: 'super-duper-secret-secret') app.use express.methodOverride() app.use express.multipart() app.use express.static(__dirname + '/dist/') return app.configure 'development', -> app.use express.errorHandler() return require('./app/router') app http.createServer(app).listen app.get('port'), -> console.log 'Express server listening on port ' + app.get('port') return
true
###* * Node.js Login Boilerplate * More Info : http://bit.ly/LsODY8 * Copyright (c) 2013 PI:NAME:<NAME>END_PI * ### express = require('express') http = require('http') bodyParser = require('body-parser') multer = require('multer') app = express() app.configure -> app.set 'port', 8000 app.set 'views', __dirname + '/app/views' app.set 'view engine', 'jade' app.set 'view options',{layout:false} app.locals.pretty = true app.use bodyParser.urlencoded({extended:true}) app.use express.cookieParser() app.use express.session(secret: 'super-duper-secret-secret') app.use express.methodOverride() app.use express.multipart() app.use express.static(__dirname + '/dist/') return app.configure 'development', -> app.use express.errorHandler() return require('./app/router') app http.createServer(app).listen app.get('port'), -> console.log 'Express server listening on port ' + app.get('port') return
[ { "context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan", "end": 18, "score": 0.9998850226402283, "start": 10, "tag": "NAME", "value": "Tim Knip" }, { "context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new...
source/javascripts/new_src/loaders/collada/morph.coffee
andrew-aladev/three.js
0
# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com # @author aladjev.andrew@gmail.com #= require new_src/loaders/collada/source #= require new_src/loaders/collada/input class Morph constructor: (loader) -> @method = null @source = null @targets = null @weights = null @loader = loader parse: (element) -> sources = {} inputs = [] @method = element.getAttribute("method") @source = element.getAttribute("source").replace /^#/, "" length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "source" source = new THREE.Collada.Source(@loader).parse child sources[source.id] = source when "targets" inputs = @parseInputs child else console.warn child.nodeName length = inputs.length for i in [0...length] input = inputs[i] source = sources[input.source] switch input.semantic when "MORPH_TARGET" @targets = source.read() when "MORPH_WEIGHT" @weights = source.read() this parseInputs: (element) -> inputs = [] length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "input" inputs.push new THREE.Collada.Input().parse child inputs namespace "THREE.Collada", (exports) -> exports.Morph = Morph
113851
# @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com # @author <EMAIL> #= require new_src/loaders/collada/source #= require new_src/loaders/collada/input class Morph constructor: (loader) -> @method = null @source = null @targets = null @weights = null @loader = loader parse: (element) -> sources = {} inputs = [] @method = element.getAttribute("method") @source = element.getAttribute("source").replace /^#/, "" length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "source" source = new THREE.Collada.Source(@loader).parse child sources[source.id] = source when "targets" inputs = @parseInputs child else console.warn child.nodeName length = inputs.length for i in [0...length] input = inputs[i] source = sources[input.source] switch input.semantic when "MORPH_TARGET" @targets = source.read() when "MORPH_WEIGHT" @weights = source.read() this parseInputs: (element) -> inputs = [] length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "input" inputs.push new THREE.Collada.Input().parse child inputs namespace "THREE.Collada", (exports) -> exports.Morph = Morph
true
# @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com # @author PI:EMAIL:<EMAIL>END_PI #= require new_src/loaders/collada/source #= require new_src/loaders/collada/input class Morph constructor: (loader) -> @method = null @source = null @targets = null @weights = null @loader = loader parse: (element) -> sources = {} inputs = [] @method = element.getAttribute("method") @source = element.getAttribute("source").replace /^#/, "" length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "source" source = new THREE.Collada.Source(@loader).parse child sources[source.id] = source when "targets" inputs = @parseInputs child else console.warn child.nodeName length = inputs.length for i in [0...length] input = inputs[i] source = sources[input.source] switch input.semantic when "MORPH_TARGET" @targets = source.read() when "MORPH_WEIGHT" @weights = source.read() this parseInputs: (element) -> inputs = [] length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "input" inputs.push new THREE.Collada.Input().parse child inputs namespace "THREE.Collada", (exports) -> exports.Morph = Morph
[ { "context": "ut:\n# -\n\n'scopeName': 'source.juniper'\n'name': 'Juniper'\n'fileTypes': [\n 'jun'\n]\n'patterns': [\n {\n '", "end": 121, "score": 0.646151602268219, "start": 114, "tag": "NAME", "value": "Juniper" } ]
grammars/juniper.cson
calebh/language-juniper
1
# If this is your first time writing a language grammar, check out: # - 'scopeName': 'source.juniper' 'name': 'Juniper' 'fileTypes': [ 'jun' ] 'patterns': [ { 'include': '#line-comments' } { 'include': '#comments' } { 'include': '#inlinecpp' } { 'include': '#module' } { 'include': '#open' } { 'include': '#type' } { 'include': '#function' } { 'include': '#keywords' } { 'include': '#number' } { 'include': '#builtintypes' } { 'include': '#include' } ] 'repository': 'type': 'patterns' : [ { 'begin': '\\b(type)\\s+([A-Za-z0-9_]+)\\b' 'end': '=' 'beginCaptures': '1': 'name': 'keyword.other.juniper' '2': 'name': 'entity.name.type.juniper' } ] 'line-comments': 'patterns': [ { 'match': '//.*$' 'name': 'comment.line.double-slash.juniper' } ] 'comments': 'patterns': [ { 'begin': '\\(\\*' 'end': '\\*\\)' 'name': 'comment.block.juniper' } ] 'module': 'patterns' : [ { 'match': '\\b(module)\\s+\\b([A-Za-z0-9_]+)$' 'captures': '1': 'name': 'keyword.other.module-definition.juniper' '2': 'name': 'entity.name.section' } ] 'open': 'patterns' : [ { 'begin': '\\b(open)\\s*\\(' 'end': '\\)' 'beginCaptures': '1': 'name': 'keyword.other.juniper' 'patterns': [ { 'include': '#comments' } { 'include': '#line-comments' } { 'match': '\\s*,\\s*' } { 'match': '\\b[A-Za-z0-9_]+\\b' 'name': 'entity.name.section.juniper' } ] } ] 'include': 'patterns' : [ { 'begin': '\\b(include)\\s*\\(' 'end': '\\)' 'beginCaptures': '1': 'name': 'keyword.other.juniper' 'patterns': [ { 'match': '".*?[^\\\\]"' 'name': 'string.quoted.double' } { 'include': '#comments' } { 'include': '#line-comments' } { 'match': '\\s*,\\s*' } ] } ] 'function': 'patterns': [ { 'begin': '\\b(fun)\\s+([A-Za-z0-9_]+)\\b' 'end': '=' 'beginCaptures': '1': 'name': 'keyword.other.juniper' '2': 'name': 'entity.name.function.juniper' 'patterns': [ { 'include': '#comments' } { 'include': '#line-comments' } { 'include': '#builtintypes' } ] } ] 'keywords': 'patterns': [ { 'match': '\\b(->|=>|fn|if|then|in|else|elif|let|set|ref|of|do|for|case|while|to|downto|end|array|mutable|\\(\\))\\b' 'name': 'keyword.other.juniper' } { 'match': '\\b(!=|==|and|or|not|~~~|\\|\\|\\||&&&|<|>|<=|>=|mod|\\+|-|\\*|\\/|!|<<<|>>>)\\b' 'name': 'keyword.operator.juniper' } { 'match': '\\b(true|false)\\b' 'name': 'constant.language.juniper' } ] 'builtintypes': 'patterns': [ { 'match': '\\b(uint8|int8|uint16|int16|uint32|int32|uint64|int64|unit|double|float)\\b' 'name': 'storage.type.juniper' } ] 'inlinecpp': 'patterns': [ { 'begin': '#' 'end': '#' 'patterns': [ { 'include': 'source.cpp' } ] } ] 'number': 'patterns':[ { 'match': '\\b-?[0-9]+\\b' 'name': 'constant.numeric.juniper' } { 'match': '\\b-?[0-9]+\.[0-9]+\\b' 'name': 'constant.numeric.juniper' } ]
16285
# If this is your first time writing a language grammar, check out: # - 'scopeName': 'source.juniper' 'name': '<NAME>' 'fileTypes': [ 'jun' ] 'patterns': [ { 'include': '#line-comments' } { 'include': '#comments' } { 'include': '#inlinecpp' } { 'include': '#module' } { 'include': '#open' } { 'include': '#type' } { 'include': '#function' } { 'include': '#keywords' } { 'include': '#number' } { 'include': '#builtintypes' } { 'include': '#include' } ] 'repository': 'type': 'patterns' : [ { 'begin': '\\b(type)\\s+([A-Za-z0-9_]+)\\b' 'end': '=' 'beginCaptures': '1': 'name': 'keyword.other.juniper' '2': 'name': 'entity.name.type.juniper' } ] 'line-comments': 'patterns': [ { 'match': '//.*$' 'name': 'comment.line.double-slash.juniper' } ] 'comments': 'patterns': [ { 'begin': '\\(\\*' 'end': '\\*\\)' 'name': 'comment.block.juniper' } ] 'module': 'patterns' : [ { 'match': '\\b(module)\\s+\\b([A-Za-z0-9_]+)$' 'captures': '1': 'name': 'keyword.other.module-definition.juniper' '2': 'name': 'entity.name.section' } ] 'open': 'patterns' : [ { 'begin': '\\b(open)\\s*\\(' 'end': '\\)' 'beginCaptures': '1': 'name': 'keyword.other.juniper' 'patterns': [ { 'include': '#comments' } { 'include': '#line-comments' } { 'match': '\\s*,\\s*' } { 'match': '\\b[A-Za-z0-9_]+\\b' 'name': 'entity.name.section.juniper' } ] } ] 'include': 'patterns' : [ { 'begin': '\\b(include)\\s*\\(' 'end': '\\)' 'beginCaptures': '1': 'name': 'keyword.other.juniper' 'patterns': [ { 'match': '".*?[^\\\\]"' 'name': 'string.quoted.double' } { 'include': '#comments' } { 'include': '#line-comments' } { 'match': '\\s*,\\s*' } ] } ] 'function': 'patterns': [ { 'begin': '\\b(fun)\\s+([A-Za-z0-9_]+)\\b' 'end': '=' 'beginCaptures': '1': 'name': 'keyword.other.juniper' '2': 'name': 'entity.name.function.juniper' 'patterns': [ { 'include': '#comments' } { 'include': '#line-comments' } { 'include': '#builtintypes' } ] } ] 'keywords': 'patterns': [ { 'match': '\\b(->|=>|fn|if|then|in|else|elif|let|set|ref|of|do|for|case|while|to|downto|end|array|mutable|\\(\\))\\b' 'name': 'keyword.other.juniper' } { 'match': '\\b(!=|==|and|or|not|~~~|\\|\\|\\||&&&|<|>|<=|>=|mod|\\+|-|\\*|\\/|!|<<<|>>>)\\b' 'name': 'keyword.operator.juniper' } { 'match': '\\b(true|false)\\b' 'name': 'constant.language.juniper' } ] 'builtintypes': 'patterns': [ { 'match': '\\b(uint8|int8|uint16|int16|uint32|int32|uint64|int64|unit|double|float)\\b' 'name': 'storage.type.juniper' } ] 'inlinecpp': 'patterns': [ { 'begin': '#' 'end': '#' 'patterns': [ { 'include': 'source.cpp' } ] } ] 'number': 'patterns':[ { 'match': '\\b-?[0-9]+\\b' 'name': 'constant.numeric.juniper' } { 'match': '\\b-?[0-9]+\.[0-9]+\\b' 'name': 'constant.numeric.juniper' } ]
true
# If this is your first time writing a language grammar, check out: # - 'scopeName': 'source.juniper' 'name': 'PI:NAME:<NAME>END_PI' 'fileTypes': [ 'jun' ] 'patterns': [ { 'include': '#line-comments' } { 'include': '#comments' } { 'include': '#inlinecpp' } { 'include': '#module' } { 'include': '#open' } { 'include': '#type' } { 'include': '#function' } { 'include': '#keywords' } { 'include': '#number' } { 'include': '#builtintypes' } { 'include': '#include' } ] 'repository': 'type': 'patterns' : [ { 'begin': '\\b(type)\\s+([A-Za-z0-9_]+)\\b' 'end': '=' 'beginCaptures': '1': 'name': 'keyword.other.juniper' '2': 'name': 'entity.name.type.juniper' } ] 'line-comments': 'patterns': [ { 'match': '//.*$' 'name': 'comment.line.double-slash.juniper' } ] 'comments': 'patterns': [ { 'begin': '\\(\\*' 'end': '\\*\\)' 'name': 'comment.block.juniper' } ] 'module': 'patterns' : [ { 'match': '\\b(module)\\s+\\b([A-Za-z0-9_]+)$' 'captures': '1': 'name': 'keyword.other.module-definition.juniper' '2': 'name': 'entity.name.section' } ] 'open': 'patterns' : [ { 'begin': '\\b(open)\\s*\\(' 'end': '\\)' 'beginCaptures': '1': 'name': 'keyword.other.juniper' 'patterns': [ { 'include': '#comments' } { 'include': '#line-comments' } { 'match': '\\s*,\\s*' } { 'match': '\\b[A-Za-z0-9_]+\\b' 'name': 'entity.name.section.juniper' } ] } ] 'include': 'patterns' : [ { 'begin': '\\b(include)\\s*\\(' 'end': '\\)' 'beginCaptures': '1': 'name': 'keyword.other.juniper' 'patterns': [ { 'match': '".*?[^\\\\]"' 'name': 'string.quoted.double' } { 'include': '#comments' } { 'include': '#line-comments' } { 'match': '\\s*,\\s*' } ] } ] 'function': 'patterns': [ { 'begin': '\\b(fun)\\s+([A-Za-z0-9_]+)\\b' 'end': '=' 'beginCaptures': '1': 'name': 'keyword.other.juniper' '2': 'name': 'entity.name.function.juniper' 'patterns': [ { 'include': '#comments' } { 'include': '#line-comments' } { 'include': '#builtintypes' } ] } ] 'keywords': 'patterns': [ { 'match': '\\b(->|=>|fn|if|then|in|else|elif|let|set|ref|of|do|for|case|while|to|downto|end|array|mutable|\\(\\))\\b' 'name': 'keyword.other.juniper' } { 'match': '\\b(!=|==|and|or|not|~~~|\\|\\|\\||&&&|<|>|<=|>=|mod|\\+|-|\\*|\\/|!|<<<|>>>)\\b' 'name': 'keyword.operator.juniper' } { 'match': '\\b(true|false)\\b' 'name': 'constant.language.juniper' } ] 'builtintypes': 'patterns': [ { 'match': '\\b(uint8|int8|uint16|int16|uint32|int32|uint64|int64|unit|double|float)\\b' 'name': 'storage.type.juniper' } ] 'inlinecpp': 'patterns': [ { 'begin': '#' 'end': '#' 'patterns': [ { 'include': 'source.cpp' } ] } ] 'number': 'patterns':[ { 'match': '\\b-?[0-9]+\\b' 'name': 'constant.numeric.juniper' } { 'match': '\\b-?[0-9]+\.[0-9]+\\b' 'name': 'constant.numeric.juniper' } ]
[ { "context": "###\n grunt-breakshots\n https://github.com/EightMedia/grunt-breakshots\n\n Copyright (c) 2013 J. Tangeld", "end": 54, "score": 0.9989984035491943, "start": 44, "tag": "USERNAME", "value": "EightMedia" }, { "context": "/EightMedia/grunt-breakshots\n\n Copyright (c) ...
tasks/breakshots.coffee
EightMedia/grunt-breakshots
2
### grunt-breakshots https://github.com/EightMedia/grunt-breakshots Copyright (c) 2013 J. Tangelder Licensed under the MIT license. ### path = require 'path' jade = require 'jade' fs = require 'fs' module.exports = (grunt)-> # Please see the Grunt documentation for more information regarding task # creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask 'breakshots', 'Create screenshots of html files per breakpoint', -> # This task is asynchronous. done = @async() # Merge task-specific and/or target-specific options with these defaults. options = @options cwd: '.' url: 'http://localhost:8000/' ext: 'png' breakpoints: [320,480,640,768,1024,1200] # Keeps all pages pages = [] # Iterate over all specified file groups. @files.forEach (group)-> # Concat specified files. p = group.src .filter (filepath)-> # Warn on and remove invalid source files (if nonull was set). if not grunt.file.exists(filepath) or not grunt.file.isFile(filepath) return false true .map (filepath)-> filepath = path.relative(options.cwd, filepath) filename = filepath.split(path.sep).join(".") url: options.url + filepath, filename: filename, dest: path.normalize("#{group.dest}/#{filename}") Array::push.apply pages, p # Get path to phantomjs binary phantomjs = bin: require('phantomjs').path script: path.resolve(__dirname, '../phantomjs/render.coffee') # Process each filepath in-order. grunt.util.async.forEachSeries pages, (page, next)-> grunt.util.spawn cmd: phantomjs.bin args: [ phantomjs.script, options.ext, options.breakpoints.join(","), page.dest, page.url] , (err)-> if err console.error err done() else console.log "Rendered #{page.filename}" next() , # All screenshots have been made -> generateDocuments() done() # generate documents generateDocuments = ()-> template = path.resolve(__dirname, '../template/template.jade') fn = jade.compile fs.readFileSync(template), pretty: true filename: template for item in pages item.breakpoints = [] for size in options.breakpoints item.breakpoints.push size: size, file: item.filename compiled = fn pages: pages, options: options, item: item fs.writeFileSync("#{item.dest}.html", compiled) console.log "Generated #{item.dest}.html"
155376
### grunt-breakshots https://github.com/EightMedia/grunt-breakshots Copyright (c) 2013 <NAME> Licensed under the MIT license. ### path = require 'path' jade = require 'jade' fs = require 'fs' module.exports = (grunt)-> # Please see the Grunt documentation for more information regarding task # creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask 'breakshots', 'Create screenshots of html files per breakpoint', -> # This task is asynchronous. done = @async() # Merge task-specific and/or target-specific options with these defaults. options = @options cwd: '.' url: 'http://localhost:8000/' ext: 'png' breakpoints: [320,480,640,768,1024,1200] # Keeps all pages pages = [] # Iterate over all specified file groups. @files.forEach (group)-> # Concat specified files. p = group.src .filter (filepath)-> # Warn on and remove invalid source files (if nonull was set). if not grunt.file.exists(filepath) or not grunt.file.isFile(filepath) return false true .map (filepath)-> filepath = path.relative(options.cwd, filepath) filename = filepath.split(path.sep).join(".") url: options.url + filepath, filename: filename, dest: path.normalize("#{group.dest}/#{filename}") Array::push.apply pages, p # Get path to phantomjs binary phantomjs = bin: require('phantomjs').path script: path.resolve(__dirname, '../phantomjs/render.coffee') # Process each filepath in-order. grunt.util.async.forEachSeries pages, (page, next)-> grunt.util.spawn cmd: phantomjs.bin args: [ phantomjs.script, options.ext, options.breakpoints.join(","), page.dest, page.url] , (err)-> if err console.error err done() else console.log "Rendered #{page.filename}" next() , # All screenshots have been made -> generateDocuments() done() # generate documents generateDocuments = ()-> template = path.resolve(__dirname, '../template/template.jade') fn = jade.compile fs.readFileSync(template), pretty: true filename: template for item in pages item.breakpoints = [] for size in options.breakpoints item.breakpoints.push size: size, file: item.filename compiled = fn pages: pages, options: options, item: item fs.writeFileSync("#{item.dest}.html", compiled) console.log "Generated #{item.dest}.html"
true
### grunt-breakshots https://github.com/EightMedia/grunt-breakshots Copyright (c) 2013 PI:NAME:<NAME>END_PI Licensed under the MIT license. ### path = require 'path' jade = require 'jade' fs = require 'fs' module.exports = (grunt)-> # Please see the Grunt documentation for more information regarding task # creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask 'breakshots', 'Create screenshots of html files per breakpoint', -> # This task is asynchronous. done = @async() # Merge task-specific and/or target-specific options with these defaults. options = @options cwd: '.' url: 'http://localhost:8000/' ext: 'png' breakpoints: [320,480,640,768,1024,1200] # Keeps all pages pages = [] # Iterate over all specified file groups. @files.forEach (group)-> # Concat specified files. p = group.src .filter (filepath)-> # Warn on and remove invalid source files (if nonull was set). if not grunt.file.exists(filepath) or not grunt.file.isFile(filepath) return false true .map (filepath)-> filepath = path.relative(options.cwd, filepath) filename = filepath.split(path.sep).join(".") url: options.url + filepath, filename: filename, dest: path.normalize("#{group.dest}/#{filename}") Array::push.apply pages, p # Get path to phantomjs binary phantomjs = bin: require('phantomjs').path script: path.resolve(__dirname, '../phantomjs/render.coffee') # Process each filepath in-order. grunt.util.async.forEachSeries pages, (page, next)-> grunt.util.spawn cmd: phantomjs.bin args: [ phantomjs.script, options.ext, options.breakpoints.join(","), page.dest, page.url] , (err)-> if err console.error err done() else console.log "Rendered #{page.filename}" next() , # All screenshots have been made -> generateDocuments() done() # generate documents generateDocuments = ()-> template = path.resolve(__dirname, '../template/template.jade') fn = jade.compile fs.readFileSync(template), pretty: true filename: template for item in pages item.breakpoints = [] for size in options.breakpoints item.breakpoints.push size: size, file: item.filename compiled = fn pages: pages, options: options, item: item fs.writeFileSync("#{item.dest}.html", compiled) console.log "Generated #{item.dest}.html"
[ { "context": "###\n# grunt-svg2storeicons\n# https://github.com/PEM/grunt-svg2storeicons\n#\n# Copyright (c) 2013 Pierr", "end": 51, "score": 0.9780550599098206, "start": 48, "tag": "USERNAME", "value": "PEM" }, { "context": "om/PEM/grunt-svg2storeicons\n#\n# Copyright (c) 2013 Pierr...
Gruntfile.coffee
gruntjs-updater/grunt-svg2storeicons
0
### # grunt-svg2storeicons # https://github.com/PEM/grunt-svg2storeicons # # Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>) # Licensed under the MIT license. ### 'use strict' module.exports = (grunt) -> # Load all tasks plugins declared in package.json ((require 'matchdep').filterDev 'grunt-*').forEach grunt.loadNpmTasks # Load linter options coffeeLintOptions = grunt.file.readJSON './coffeelint.json' # Project configuration. grunt.initConfig # Lint all CoffeeScript files coffeelint: all: [ 'Gruntfile.coffee' 'tasks/*.coffee' 'lib/*.coffee' 'test/*.coffee' ] options: coffeeLintOptions # Before generating any new files, remove any previously-created files. clean: tests: ["tmp"] # Configuration to be run (and then tested). svg2storeicons: # Test icon creation for all profiles default_options: src: 'test/fixtures/icon.svg' dest: 'tmp/default_options' # Test icon creation for a single reduced_set: src: 'test/fixtures/icon.svg' dest: 'tmp/reduced_set' options: profiles: ['blackberry'] # Unit tests. mochaTest: test: options: reporter: 'spec' require: 'coffee-script' src: ['test/*.coffee'] # Actually load this plugin's task(s). grunt.loadTasks "tasks" # Whenever the "test" task is run, first clean the "tmp" dir, then run this # plugin's task(s), then test the result. grunt.registerTask 'test', [ 'clean' 'svg2storeicons' 'mochaTest' ] # By default, lint and run all tests. grunt.registerTask 'default', [ 'coffeelint' 'test' ]
26254
### # grunt-svg2storeicons # https://github.com/PEM/grunt-svg2storeicons # # Copyright (c) 2013 <NAME> (PEM-- <<EMAIL>>) # Licensed under the MIT license. ### 'use strict' module.exports = (grunt) -> # Load all tasks plugins declared in package.json ((require 'matchdep').filterDev 'grunt-*').forEach grunt.loadNpmTasks # Load linter options coffeeLintOptions = grunt.file.readJSON './coffeelint.json' # Project configuration. grunt.initConfig # Lint all CoffeeScript files coffeelint: all: [ 'Gruntfile.coffee' 'tasks/*.coffee' 'lib/*.coffee' 'test/*.coffee' ] options: coffeeLintOptions # Before generating any new files, remove any previously-created files. clean: tests: ["tmp"] # Configuration to be run (and then tested). svg2storeicons: # Test icon creation for all profiles default_options: src: 'test/fixtures/icon.svg' dest: 'tmp/default_options' # Test icon creation for a single reduced_set: src: 'test/fixtures/icon.svg' dest: 'tmp/reduced_set' options: profiles: ['blackberry'] # Unit tests. mochaTest: test: options: reporter: 'spec' require: 'coffee-script' src: ['test/*.coffee'] # Actually load this plugin's task(s). grunt.loadTasks "tasks" # Whenever the "test" task is run, first clean the "tmp" dir, then run this # plugin's task(s), then test the result. grunt.registerTask 'test', [ 'clean' 'svg2storeicons' 'mochaTest' ] # By default, lint and run all tests. grunt.registerTask 'default', [ 'coffeelint' 'test' ]
true
### # grunt-svg2storeicons # https://github.com/PEM/grunt-svg2storeicons # # Copyright (c) 2013 PI:NAME:<NAME>END_PI (PEM-- <PI:EMAIL:<EMAIL>END_PI>) # Licensed under the MIT license. ### 'use strict' module.exports = (grunt) -> # Load all tasks plugins declared in package.json ((require 'matchdep').filterDev 'grunt-*').forEach grunt.loadNpmTasks # Load linter options coffeeLintOptions = grunt.file.readJSON './coffeelint.json' # Project configuration. grunt.initConfig # Lint all CoffeeScript files coffeelint: all: [ 'Gruntfile.coffee' 'tasks/*.coffee' 'lib/*.coffee' 'test/*.coffee' ] options: coffeeLintOptions # Before generating any new files, remove any previously-created files. clean: tests: ["tmp"] # Configuration to be run (and then tested). svg2storeicons: # Test icon creation for all profiles default_options: src: 'test/fixtures/icon.svg' dest: 'tmp/default_options' # Test icon creation for a single reduced_set: src: 'test/fixtures/icon.svg' dest: 'tmp/reduced_set' options: profiles: ['blackberry'] # Unit tests. mochaTest: test: options: reporter: 'spec' require: 'coffee-script' src: ['test/*.coffee'] # Actually load this plugin's task(s). grunt.loadTasks "tasks" # Whenever the "test" task is run, first clean the "tmp" dir, then run this # plugin's task(s), then test the result. grunt.registerTask 'test', [ 'clean' 'svg2storeicons' 'mochaTest' ] # By default, lint and run all tests. grunt.registerTask 'default', [ 'coffeelint' 'test' ]
[ { "context": "g of Scheme expression to JS/Coffee array\r\n#\r\n# by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>\r\n# (C) MIT Style Lic", "end": 79, "score": 0.9998531341552734, "start": 63, "tag": "NAME", "value": "Dmitry Soshnikov" }, { "context": "ion to JS/Coffee array\r\n#\r\n...
parse.coffee
DmitrySoshnikov/scheme-on-coffee
7
# Pre-parsing of Scheme expression to JS/Coffee array # # by Dmitry Soshnikov <dmitry.soshnikov@gmail.com> # (C) MIT Style License # window.parse = (exp) -> exp = exp .replace(/;.*$/gm, "") # strip comments .replace(/^\s+|\s+$/g, "") # and trailing whitespaces return [exp] if isVariable(exp) or exp is '' exp = exp .replace(/\'\(/g, "(list ") # and replace Lisp's '(1 2 3) with (list 1, 2, 3) .replace(/\'([^ ]+)/g, "(quote $1)") # and remove ' to handle 'list .replace(/apply\s*(.+)\(list\s*([^)]+)\)/g, "$1 $2") # replace (apply <proc> (list 1 2 3)) with (proc 1 2 3) .replace(/\(/g, "[") # replace Lisp's parens... .replace(/\)/g, "]") # ... with JS's array squares .replace(/\s+/g, ",") # replace spaces in expressions with commas to get real JS arrays # Wrap expression(s) with an array to be able # execute sequence of statements. We could use wrapping # with (begin ...) instead, but for now build JS sequence exp = "[#{exp}]" # quote the names and build JS arrays of expressions expessions = eval(exp.replace(/([^,\[\]0-9]+?(?=(,|\])))/g, "'$1'")) # conver each expression into Lisp's list format expessions.map (e) -> if isVariable(e) then e else JSArray2LispList(e)
160138
# Pre-parsing of Scheme expression to JS/Coffee array # # by <NAME> <<EMAIL>> # (C) MIT Style License # window.parse = (exp) -> exp = exp .replace(/;.*$/gm, "") # strip comments .replace(/^\s+|\s+$/g, "") # and trailing whitespaces return [exp] if isVariable(exp) or exp is '' exp = exp .replace(/\'\(/g, "(list ") # and replace Lisp's '(1 2 3) with (list 1, 2, 3) .replace(/\'([^ ]+)/g, "(quote $1)") # and remove ' to handle 'list .replace(/apply\s*(.+)\(list\s*([^)]+)\)/g, "$1 $2") # replace (apply <proc> (list 1 2 3)) with (proc 1 2 3) .replace(/\(/g, "[") # replace Lisp's parens... .replace(/\)/g, "]") # ... with JS's array squares .replace(/\s+/g, ",") # replace spaces in expressions with commas to get real JS arrays # Wrap expression(s) with an array to be able # execute sequence of statements. We could use wrapping # with (begin ...) instead, but for now build JS sequence exp = "[#{exp}]" # quote the names and build JS arrays of expressions expessions = eval(exp.replace(/([^,\[\]0-9]+?(?=(,|\])))/g, "'$1'")) # conver each expression into Lisp's list format expessions.map (e) -> if isVariable(e) then e else JSArray2LispList(e)
true
# Pre-parsing of Scheme expression to JS/Coffee array # # by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # (C) MIT Style License # window.parse = (exp) -> exp = exp .replace(/;.*$/gm, "") # strip comments .replace(/^\s+|\s+$/g, "") # and trailing whitespaces return [exp] if isVariable(exp) or exp is '' exp = exp .replace(/\'\(/g, "(list ") # and replace Lisp's '(1 2 3) with (list 1, 2, 3) .replace(/\'([^ ]+)/g, "(quote $1)") # and remove ' to handle 'list .replace(/apply\s*(.+)\(list\s*([^)]+)\)/g, "$1 $2") # replace (apply <proc> (list 1 2 3)) with (proc 1 2 3) .replace(/\(/g, "[") # replace Lisp's parens... .replace(/\)/g, "]") # ... with JS's array squares .replace(/\s+/g, ",") # replace spaces in expressions with commas to get real JS arrays # Wrap expression(s) with an array to be able # execute sequence of statements. We could use wrapping # with (begin ...) instead, but for now build JS sequence exp = "[#{exp}]" # quote the names and build JS arrays of expressions expessions = eval(exp.replace(/([^,\[\]0-9]+?(?=(,|\])))/g, "'$1'")) # conver each expression into Lisp's list format expessions.map (e) -> if isVariable(e) then e else JSArray2LispList(e)
[ { "context": "##\n# MIT License\n#\n# Copyright (c) 2016 Jérôme Quéré <contact@jeromequere.com>\n#\n# Permission is hereb", "end": 52, "score": 0.9998103976249695, "start": 40, "tag": "NAME", "value": "Jérôme Quéré" }, { "context": " MIT License\n#\n# Copyright (c) 2016 Jérôme Quéré ...
src/services/GitlabProvider.coffee
jerome-quere/la-metric-gitlab
1
## # MIT License # # Copyright (c) 2016 Jérôme Quéré <contact@jeromequere.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. ## _ = require('lodash') request = require('request-promise') class GitlabProvider setUrl: (@glUrl) -> this setToken: (@glToken) -> this $get: () -> new GitlabService(@glUrl, @glToken) class GitlabService constructor: (@glUrl, @glToken) -> @todayStats = date: null issuesCount: 0 @getOpenedIssuesCount = _.throttle(@_getOpenedIssuesCount, 500, {trailing: false}) @getCriticalOpenedIssuesCount = _.throttle(@_getCriticalOpenedIssuesCount, 500, {trailing: false}) getProjectsCount: () -> @getCount "/projects/all" getGroups: () -> @getAll "/groups" getTodayIssuesCount: () -> @getOpenedIssuesCount().then (count) => count - @todayStats.issuesCount _getCriticalOpenedIssuesCount: () => @getIssuesCount({state: 'opened', 'labels': 'Critical'}) _getOpenedIssuesCount: () => @getIssuesCount({state: 'opened'}).then (count) => now = new Date() if @todayStats.date == null or now.getDate() != @todayStats.date.getDate() @todayStats.date = now @todayStats.issuesCount = count return count getIssuesCount: (filters) => @getGroups().then (groups) => promises = groups.map (group) => @getCount("/groups/#{group.id}/issues", filters) return Promise.all(promises).then (counts) -> counts.reduce (a, b) -> a + b get: (path, query = {}) -> request method: 'GET' uri: "#{@glUrl}/api/v3#{path}" qs: query json: true headers: 'PRIVATE-TOKEN': @glToken resolveWithFullResponse: true getCount: (path, query = {}) -> @get(path, query).then (response) -> parseInt(response.headers['x-total']) getAll: (path, query = {}, page = 1) -> query.page = page @get(path, query).then (response) => items = response.body if (response.headers['x-total-pages'] > page) return @getAll(path, query, page + 1).then (data) -> items.concat(data) return items module.exports = GitlabProvider
190060
## # MIT License # # Copyright (c) 2016 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ## _ = require('lodash') request = require('request-promise') class GitlabProvider setUrl: (@glUrl) -> this setToken: (@glToken) -> this $get: () -> new GitlabService(@glUrl, @glToken) class GitlabService constructor: (@glUrl, @glToken) -> @todayStats = date: null issuesCount: 0 @getOpenedIssuesCount = _.throttle(@_getOpenedIssuesCount, 500, {trailing: false}) @getCriticalOpenedIssuesCount = _.throttle(@_getCriticalOpenedIssuesCount, 500, {trailing: false}) getProjectsCount: () -> @getCount "/projects/all" getGroups: () -> @getAll "/groups" getTodayIssuesCount: () -> @getOpenedIssuesCount().then (count) => count - @todayStats.issuesCount _getCriticalOpenedIssuesCount: () => @getIssuesCount({state: 'opened', 'labels': 'Critical'}) _getOpenedIssuesCount: () => @getIssuesCount({state: 'opened'}).then (count) => now = new Date() if @todayStats.date == null or now.getDate() != @todayStats.date.getDate() @todayStats.date = now @todayStats.issuesCount = count return count getIssuesCount: (filters) => @getGroups().then (groups) => promises = groups.map (group) => @getCount("/groups/#{group.id}/issues", filters) return Promise.all(promises).then (counts) -> counts.reduce (a, b) -> a + b get: (path, query = {}) -> request method: 'GET' uri: "#{@glUrl}/api/v3#{path}" qs: query json: true headers: 'PRIVATE-TOKEN': @glToken resolveWithFullResponse: true getCount: (path, query = {}) -> @get(path, query).then (response) -> parseInt(response.headers['x-total']) getAll: (path, query = {}, page = 1) -> query.page = page @get(path, query).then (response) => items = response.body if (response.headers['x-total-pages'] > page) return @getAll(path, query, page + 1).then (data) -> items.concat(data) return items module.exports = GitlabProvider
true
## # MIT License # # Copyright (c) 2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ## _ = require('lodash') request = require('request-promise') class GitlabProvider setUrl: (@glUrl) -> this setToken: (@glToken) -> this $get: () -> new GitlabService(@glUrl, @glToken) class GitlabService constructor: (@glUrl, @glToken) -> @todayStats = date: null issuesCount: 0 @getOpenedIssuesCount = _.throttle(@_getOpenedIssuesCount, 500, {trailing: false}) @getCriticalOpenedIssuesCount = _.throttle(@_getCriticalOpenedIssuesCount, 500, {trailing: false}) getProjectsCount: () -> @getCount "/projects/all" getGroups: () -> @getAll "/groups" getTodayIssuesCount: () -> @getOpenedIssuesCount().then (count) => count - @todayStats.issuesCount _getCriticalOpenedIssuesCount: () => @getIssuesCount({state: 'opened', 'labels': 'Critical'}) _getOpenedIssuesCount: () => @getIssuesCount({state: 'opened'}).then (count) => now = new Date() if @todayStats.date == null or now.getDate() != @todayStats.date.getDate() @todayStats.date = now @todayStats.issuesCount = count return count getIssuesCount: (filters) => @getGroups().then (groups) => promises = groups.map (group) => @getCount("/groups/#{group.id}/issues", filters) return Promise.all(promises).then (counts) -> counts.reduce (a, b) -> a + b get: (path, query = {}) -> request method: 'GET' uri: "#{@glUrl}/api/v3#{path}" qs: query json: true headers: 'PRIVATE-TOKEN': @glToken resolveWithFullResponse: true getCount: (path, query = {}) -> @get(path, query).then (response) -> parseInt(response.headers['x-total']) getAll: (path, query = {}, page = 1) -> query.page = page @get(path, query).then (response) => items = response.body if (response.headers['x-total-pages'] > page) return @getAll(path, query, page + 1).then (data) -> items.concat(data) return items module.exports = GitlabProvider
[ { "context": "->\n parts= _.getKeyParts keypath\n key= parts.pop()\n container= if parts.length \n _.getKe", "end": 1781, "score": 0.859412431716919, "start": 1778, "tag": "KEY", "value": "pop" } ]
src/tools.coffee
elucidata/ogre.js
1
changeEvent= require './change-event' module.exports= _= extend: require('lodash-node/compat/objects/assign') clone: require('lodash-node/compat/objects/clone') compact: require('lodash-node/compat/arrays/compact') isPlainObject: require('lodash-node/compat/objects/isPlainObject') isEqual: require('lodash-node/compat/objects/isEqual') keys: require('lodash-node/compat/objects/keys') startsWith: (str, starts) -> return yes if starts is '' return no if str is null or starts is null str= String str starts= String starts str.length >= starts.length and str.slice(0, starts.length) is starts type: do -> _toString= Object::toString elemParser= /\[object HTML(.*)\]/ classToType= {} for name in "Array Boolean Date Function NodeList Null Number RegExp String Undefined ".split(" ") classToType["[object " + name + "]"] = name.toLowerCase() (obj) -> strType = _toString.call obj if found= classToType[ strType ] found else if found= strType.match elemParser found[1].toLowerCase() else "object" warnOnce: do -> count= 0 api= (msg)-> if count is 0 console.warn msg # err= new Error() # console.dir err.stack count += 1 api.clear= -> count= 0 api getKeyParts: (keypath)-> _.compact keypath.split '.' getKeyPath: (source, keypath='', create=no)-> parts= _.getKeyParts keypath obj= source while obj? and parts.length key= parts.shift() if not obj[ key ] obj[ key ]= {} if create is yes obj= obj[ key ] obj setKeyPath: (source, keypath='', data, replace)-> parts= _.getKeyParts keypath key= parts.pop() container= if parts.length _.getKeyPath source, parts.join('.'), yes else source current= container[key] if replace is yes or not _.isPlainObject data # console.log "$ replace key:", key, 'keypath:', keypath, 'type:', type(data), 'replace (forced):', replace return no if _.isEqual container[key], data container[key]= data else # console.log "$ merge key:", key, 'keypath:', keypath, 'type:', type(data), 'existing:', container[key], 'new:', data, 'replace (forced):', replace merged= _.extend _.clone(current or {}), data #data= return no if _.isEqual current, merged container[key]= merged data= merged changeEvent keypath, data, current
40482
changeEvent= require './change-event' module.exports= _= extend: require('lodash-node/compat/objects/assign') clone: require('lodash-node/compat/objects/clone') compact: require('lodash-node/compat/arrays/compact') isPlainObject: require('lodash-node/compat/objects/isPlainObject') isEqual: require('lodash-node/compat/objects/isEqual') keys: require('lodash-node/compat/objects/keys') startsWith: (str, starts) -> return yes if starts is '' return no if str is null or starts is null str= String str starts= String starts str.length >= starts.length and str.slice(0, starts.length) is starts type: do -> _toString= Object::toString elemParser= /\[object HTML(.*)\]/ classToType= {} for name in "Array Boolean Date Function NodeList Null Number RegExp String Undefined ".split(" ") classToType["[object " + name + "]"] = name.toLowerCase() (obj) -> strType = _toString.call obj if found= classToType[ strType ] found else if found= strType.match elemParser found[1].toLowerCase() else "object" warnOnce: do -> count= 0 api= (msg)-> if count is 0 console.warn msg # err= new Error() # console.dir err.stack count += 1 api.clear= -> count= 0 api getKeyParts: (keypath)-> _.compact keypath.split '.' getKeyPath: (source, keypath='', create=no)-> parts= _.getKeyParts keypath obj= source while obj? and parts.length key= parts.shift() if not obj[ key ] obj[ key ]= {} if create is yes obj= obj[ key ] obj setKeyPath: (source, keypath='', data, replace)-> parts= _.getKeyParts keypath key= parts.<KEY>() container= if parts.length _.getKeyPath source, parts.join('.'), yes else source current= container[key] if replace is yes or not _.isPlainObject data # console.log "$ replace key:", key, 'keypath:', keypath, 'type:', type(data), 'replace (forced):', replace return no if _.isEqual container[key], data container[key]= data else # console.log "$ merge key:", key, 'keypath:', keypath, 'type:', type(data), 'existing:', container[key], 'new:', data, 'replace (forced):', replace merged= _.extend _.clone(current or {}), data #data= return no if _.isEqual current, merged container[key]= merged data= merged changeEvent keypath, data, current
true
changeEvent= require './change-event' module.exports= _= extend: require('lodash-node/compat/objects/assign') clone: require('lodash-node/compat/objects/clone') compact: require('lodash-node/compat/arrays/compact') isPlainObject: require('lodash-node/compat/objects/isPlainObject') isEqual: require('lodash-node/compat/objects/isEqual') keys: require('lodash-node/compat/objects/keys') startsWith: (str, starts) -> return yes if starts is '' return no if str is null or starts is null str= String str starts= String starts str.length >= starts.length and str.slice(0, starts.length) is starts type: do -> _toString= Object::toString elemParser= /\[object HTML(.*)\]/ classToType= {} for name in "Array Boolean Date Function NodeList Null Number RegExp String Undefined ".split(" ") classToType["[object " + name + "]"] = name.toLowerCase() (obj) -> strType = _toString.call obj if found= classToType[ strType ] found else if found= strType.match elemParser found[1].toLowerCase() else "object" warnOnce: do -> count= 0 api= (msg)-> if count is 0 console.warn msg # err= new Error() # console.dir err.stack count += 1 api.clear= -> count= 0 api getKeyParts: (keypath)-> _.compact keypath.split '.' getKeyPath: (source, keypath='', create=no)-> parts= _.getKeyParts keypath obj= source while obj? and parts.length key= parts.shift() if not obj[ key ] obj[ key ]= {} if create is yes obj= obj[ key ] obj setKeyPath: (source, keypath='', data, replace)-> parts= _.getKeyParts keypath key= parts.PI:KEY:<KEY>END_PI() container= if parts.length _.getKeyPath source, parts.join('.'), yes else source current= container[key] if replace is yes or not _.isPlainObject data # console.log "$ replace key:", key, 'keypath:', keypath, 'type:', type(data), 'replace (forced):', replace return no if _.isEqual container[key], data container[key]= data else # console.log "$ merge key:", key, 'keypath:', keypath, 'type:', type(data), 'existing:', container[key], 'new:', data, 'replace (forced):', replace merged= _.extend _.clone(current or {}), data #data= return no if _.isEqual current, merged container[key]= merged data= merged changeEvent keypath, data, current
[ { "context": "ovides pagination service.\n * @function\n * @author İsmail Demirbilek\n###\nangular.module 'esef.frontend.pagination', []", "end": 198, "score": 0.999891996383667, "start": 181, "tag": "NAME", "value": "İsmail Demirbilek" } ]
src/pagination/coffee/app.coffee
egemsoft/esef-frontend
0
'use strict' ###* * @ngdoc overview * @name esef.frontend.pagination * @description * Pagination module for esef-frontend. Provides pagination service. * @function * @author İsmail Demirbilek ### angular.module 'esef.frontend.pagination', []
32550
'use strict' ###* * @ngdoc overview * @name esef.frontend.pagination * @description * Pagination module for esef-frontend. Provides pagination service. * @function * @author <NAME> ### angular.module 'esef.frontend.pagination', []
true
'use strict' ###* * @ngdoc overview * @name esef.frontend.pagination * @description * Pagination module for esef-frontend. Provides pagination service. * @function * @author PI:NAME:<NAME>END_PI ### angular.module 'esef.frontend.pagination', []
[ { "context": "in all models if one changes\", ->\n testName = \"Teemu Testi\"\n scope.repo.activeModel.team.members[0].name ", "end": 860, "score": 0.9974983334541321, "start": 849, "tag": "NAME", "value": "Teemu Testi" } ]
app/coffee/controllerSpec.coffee
mathewsk/cypress-example-piechopper
17
describe 'AppCtrl', -> scope = null ctrl = null beforeEach -> module('piechopper') inject ($controller, $rootScope) -> scope = $rootScope.$new() ctrl = $controller('AppCtrl', $scope: scope) it "should have specific active model at the start", -> expect(scope.repo.activeModel).not.toBeUndefined() expect(scope.repo.activeModel.modelDef.id).toBe('6cfb9e85-90fc-4faa-954a-d99c8a9adc33') expect(scope.repo.activeModel).not.toBeUndefined() describe 'CalcCtrl', -> scope = null ctrl = null beforeEach -> module('piechopper') inject ($controller, $rootScope) -> $controller('AppCtrl', $scope: $rootScope) scope = $rootScope.$new() ctrl = $controller('CalcCtrl', $scope: scope) it "should automatically change member names in all models if one changes", -> testName = "Teemu Testi" scope.repo.activeModel.team.members[0].name = testName scope.$digest() for m in scope.repo.models do (m) -> expect(m.team.members[0].name).toBe(testName)
195943
describe 'AppCtrl', -> scope = null ctrl = null beforeEach -> module('piechopper') inject ($controller, $rootScope) -> scope = $rootScope.$new() ctrl = $controller('AppCtrl', $scope: scope) it "should have specific active model at the start", -> expect(scope.repo.activeModel).not.toBeUndefined() expect(scope.repo.activeModel.modelDef.id).toBe('6cfb9e85-90fc-4faa-954a-d99c8a9adc33') expect(scope.repo.activeModel).not.toBeUndefined() describe 'CalcCtrl', -> scope = null ctrl = null beforeEach -> module('piechopper') inject ($controller, $rootScope) -> $controller('AppCtrl', $scope: $rootScope) scope = $rootScope.$new() ctrl = $controller('CalcCtrl', $scope: scope) it "should automatically change member names in all models if one changes", -> testName = "<NAME>" scope.repo.activeModel.team.members[0].name = testName scope.$digest() for m in scope.repo.models do (m) -> expect(m.team.members[0].name).toBe(testName)
true
describe 'AppCtrl', -> scope = null ctrl = null beforeEach -> module('piechopper') inject ($controller, $rootScope) -> scope = $rootScope.$new() ctrl = $controller('AppCtrl', $scope: scope) it "should have specific active model at the start", -> expect(scope.repo.activeModel).not.toBeUndefined() expect(scope.repo.activeModel.modelDef.id).toBe('6cfb9e85-90fc-4faa-954a-d99c8a9adc33') expect(scope.repo.activeModel).not.toBeUndefined() describe 'CalcCtrl', -> scope = null ctrl = null beforeEach -> module('piechopper') inject ($controller, $rootScope) -> $controller('AppCtrl', $scope: $rootScope) scope = $rootScope.$new() ctrl = $controller('CalcCtrl', $scope: scope) it "should automatically change member names in all models if one changes", -> testName = "PI:NAME:<NAME>END_PI" scope.repo.activeModel.team.members[0].name = testName scope.$digest() for m in scope.repo.models do (m) -> expect(m.team.members[0].name).toBe(testName)
[ { "context": "'t be blank\"] }\n \n user.set \"firstName\", \"Joe\"\n \n assert.deepEqual user.validate(), tru", "end": 497, "score": 0.9995446801185608, "start": 494, "tag": "NAME", "value": "Joe" } ]
test/cases/model/validationTest.coffee
ludicast/tower
1
require '../../config' scope = null criteria = null user = null describeWith = (store) -> describe "Tower.Model.Validation (Tower.Store.#{store.constructor.name})", -> beforeEach (done) -> App.User.store(store) user = new App.User(id: 1) done() it 'should be invalid', -> assert.deepEqual user.validate(), false assert.deepEqual user.errors, { 'firstName' : ["firstName can't be blank"] } user.set "firstName", "Joe" assert.deepEqual user.validate(), true assert.deepEqual user.errors, [] user.set "firstName", null assert.deepEqual user.validate(), false assert.deepEqual user.errors, { 'firstName' : ["firstName can't be blank"] } it 'should validate from attribute definition', -> page = new App.Page(title: "A App.Page") assert.deepEqual page.validate(), false assert.deepEqual page.errors, { 'rating': ['rating must be a minimum of 0', 'rating must be a maximum of 10' ] } page.set "rating", 10 assert.deepEqual page.validate(), true assert.deepEqual page.errors, [] describe 'length, min, max', -> describeWith(new Tower.Store.Memory(name: "users", type: "App.User")) describeWith(new Tower.Store.MongoDB(name: "users", type: "App.User"))
66379
require '../../config' scope = null criteria = null user = null describeWith = (store) -> describe "Tower.Model.Validation (Tower.Store.#{store.constructor.name})", -> beforeEach (done) -> App.User.store(store) user = new App.User(id: 1) done() it 'should be invalid', -> assert.deepEqual user.validate(), false assert.deepEqual user.errors, { 'firstName' : ["firstName can't be blank"] } user.set "firstName", "<NAME>" assert.deepEqual user.validate(), true assert.deepEqual user.errors, [] user.set "firstName", null assert.deepEqual user.validate(), false assert.deepEqual user.errors, { 'firstName' : ["firstName can't be blank"] } it 'should validate from attribute definition', -> page = new App.Page(title: "A App.Page") assert.deepEqual page.validate(), false assert.deepEqual page.errors, { 'rating': ['rating must be a minimum of 0', 'rating must be a maximum of 10' ] } page.set "rating", 10 assert.deepEqual page.validate(), true assert.deepEqual page.errors, [] describe 'length, min, max', -> describeWith(new Tower.Store.Memory(name: "users", type: "App.User")) describeWith(new Tower.Store.MongoDB(name: "users", type: "App.User"))
true
require '../../config' scope = null criteria = null user = null describeWith = (store) -> describe "Tower.Model.Validation (Tower.Store.#{store.constructor.name})", -> beforeEach (done) -> App.User.store(store) user = new App.User(id: 1) done() it 'should be invalid', -> assert.deepEqual user.validate(), false assert.deepEqual user.errors, { 'firstName' : ["firstName can't be blank"] } user.set "firstName", "PI:NAME:<NAME>END_PI" assert.deepEqual user.validate(), true assert.deepEqual user.errors, [] user.set "firstName", null assert.deepEqual user.validate(), false assert.deepEqual user.errors, { 'firstName' : ["firstName can't be blank"] } it 'should validate from attribute definition', -> page = new App.Page(title: "A App.Page") assert.deepEqual page.validate(), false assert.deepEqual page.errors, { 'rating': ['rating must be a minimum of 0', 'rating must be a maximum of 10' ] } page.set "rating", 10 assert.deepEqual page.validate(), true assert.deepEqual page.errors, [] describe 'length, min, max', -> describeWith(new Tower.Store.Memory(name: "users", type: "App.User")) describeWith(new Tower.Store.MongoDB(name: "users", type: "App.User"))
[ { "context": "==============\n\nmodule.exports = \n firstName: \"Baptiste\"\n lastName: \"Vannesson\"\n", "end": 141, "score": 0.9997859001159668, "start": 133, "tag": "NAME", "value": "Baptiste" }, { "context": "ports = \n firstName: \"Baptiste\"\n lastName: \"Vannesson\...
GoF/idiomatic/Creational/Singleton/CoffeeScript/API/me.coffee
irynaO/JavaScript-Design-Patterns
293
'use strict' # ============================== # SINGLETON: "ME" # ============================== module.exports = firstName: "Baptiste" lastName: "Vannesson"
201021
'use strict' # ============================== # SINGLETON: "ME" # ============================== module.exports = firstName: "<NAME>" lastName: "<NAME>"
true
'use strict' # ============================== # SINGLETON: "ME" # ============================== module.exports = firstName: "PI:NAME:<NAME>END_PI" lastName: "PI:NAME:<NAME>END_PI"
[ { "context": ": false\n 'public-key': null\n 'pusher-key': '79ae88bd931ea68464d9'\n 'cdn-base': 'http://www.ucarecdn.com'\n 'u", "end": 708, "score": 0.9996377229690552, "start": 688, "tag": "KEY", "value": "79ae88bd931ea68464d9" } ]
app/assets/javascripts/uploadcare/settings.js.coffee
uniiverse/uploadcare-widget
0
{ expose namespace, utils, jQuery: $ } = uploadcare namespace 'uploadcare.settings', (ns) -> defaults = # developer hooks 'live': true 'manual-start': false 'locale': null 'locale-pluralize': null 'locale-translations': null # widget settings 'system-dialog': false 'crop': 'disabled' 'preview-step': false 'images-only': false 'clearable': false 'multiple': false 'multiple-max': 0 'multiple-min': 1 'path-value': false 'tabs': 'file url facebook instagram flickr gdrive evernote box skydrive' 'preferred-types': '' # upload settings 'autostore': false 'public-key': null 'pusher-key': '79ae88bd931ea68464d9' 'cdn-base': 'http://www.ucarecdn.com' 'url-base': 'https://upload.uploadcare.com' 'social-base': 'https://social.uploadcare.com' # maintain settings 'script-base': if SCRIPT_BASE? then SCRIPT_BASE else '' presets = 'tabs': all: 'file url facebook dropbox gdrive instagram flickr vk evernote box skydrive' default: defaults.tabs str2arr = (value) -> unless $.isArray value value = $.trim value value = if value then value.split(' ') else [] value arrayOptions = (settings, keys) -> for key in keys value = source = str2arr(settings[key]) if presets.hasOwnProperty(key) value = [] for item in source if presets[key].hasOwnProperty(item) value = value.concat(str2arr(presets[key][item])) else value.push(item) settings[key] = utils.unique(value) settings urlOptions = (settings, keys) -> for key in keys when settings[key]? settings[key] = utils.normalizeUrl(settings[key]) settings flagOptions = (settings, keys) -> for key in keys when settings[key]? value = settings[key] if $.type(value) == 'string' # "", "..." -> true # "false", "disabled" -> false value = $.trim(value).toLowerCase() settings[key] = not (value in ['false', 'disabled']) else settings[key] = !!value settings intOptions = (settings, keys) -> for key in keys when settings[key]? settings[key] = parseInt(settings[key]) settings parseCrop = (val) -> reRatio = /^([0-9]+)([x:])([0-9]+)\s*(|upscale|minimum)$/i ratio = reRatio.exec($.trim(val.toLowerCase())) or [] downscale: ratio[2] == 'x' upscale: !! ratio[4] notLess: ratio[4] == 'minimum' preferedSize: [+ratio[1], +ratio[3]] if ratio.length normalize = (settings) -> arrayOptions settings, [ 'tabs' 'preferredTypes' ] urlOptions settings, [ 'cdnBase' 'socialBase' 'urlBase' 'scriptBase' ] flagOptions settings, [ 'autostore' 'imagesOnly' 'multiple' 'clearable' 'pathValue' 'previewStep' 'systemDialog' ] intOptions settings, [ 'multipleMax' 'multipleMin' ] if not $.isArray settings.crop if /^(disabled?|false|null)$/i.test(settings.crop) or settings.multiple settings.crop = false else if $.isPlainObject settings.crop # old format settings.crop = [settings.crop] else settings.crop = $.map(settings.crop.split(','), parseCrop) if settings.crop or settings.multiple settings.previewStep = true if settings.crop settings.pathValue = true if not utils.abilities.sendFileAPI settings.systemDialog = false settings # Defaults (not normalized) publicDefaults = {} for own key, value of defaults publicDefaults[$.camelCase(key)] = value expose 'defaults', publicDefaults # Defaults + global variables ns.globals = utils.once -> values = {} for own key, fallback of defaults value = window["UPLOADCARE_#{utils.upperCase(key)}"] values[$.camelCase(key)] = if value? then value else fallback unless values.publicKey utils.commonWarning('publicKey') normalize(values) # Defaults + global variables + global overrides (once from uploadcare.start) # Not publicly-accessible ns.common = utils.once (settings) -> result = normalize $.extend({}, ns.globals(), settings or {}) waitForSettingsCb.fire result result # Defaults + global variables + global overrides + local overrides ns.build = (settings) -> normalize $.extend({}, ns.common(), settings or {}) waitForSettingsCb = $.Callbacks "once memory" # Like build() but won't cause settings freezing if they still didn't ns.waitForSettings = (settings, fn) -> waitForSettingsCb.add (common) -> fn normalize $.extend({}, common, settings or {}) class ns.CssCollector constructor: () -> @urls = [] @styles = [] addUrl: (url) -> if not /^https?:\/\//i.test(url) throw new Error('Embedded urls should be absolute. ' + url) unless url in @urls @urls.push url addStyle: (style) -> @styles.push style uploadcare.tabsCss = new ns.CssCollector
123322
{ expose namespace, utils, jQuery: $ } = uploadcare namespace 'uploadcare.settings', (ns) -> defaults = # developer hooks 'live': true 'manual-start': false 'locale': null 'locale-pluralize': null 'locale-translations': null # widget settings 'system-dialog': false 'crop': 'disabled' 'preview-step': false 'images-only': false 'clearable': false 'multiple': false 'multiple-max': 0 'multiple-min': 1 'path-value': false 'tabs': 'file url facebook instagram flickr gdrive evernote box skydrive' 'preferred-types': '' # upload settings 'autostore': false 'public-key': null 'pusher-key': '<KEY>' 'cdn-base': 'http://www.ucarecdn.com' 'url-base': 'https://upload.uploadcare.com' 'social-base': 'https://social.uploadcare.com' # maintain settings 'script-base': if SCRIPT_BASE? then SCRIPT_BASE else '' presets = 'tabs': all: 'file url facebook dropbox gdrive instagram flickr vk evernote box skydrive' default: defaults.tabs str2arr = (value) -> unless $.isArray value value = $.trim value value = if value then value.split(' ') else [] value arrayOptions = (settings, keys) -> for key in keys value = source = str2arr(settings[key]) if presets.hasOwnProperty(key) value = [] for item in source if presets[key].hasOwnProperty(item) value = value.concat(str2arr(presets[key][item])) else value.push(item) settings[key] = utils.unique(value) settings urlOptions = (settings, keys) -> for key in keys when settings[key]? settings[key] = utils.normalizeUrl(settings[key]) settings flagOptions = (settings, keys) -> for key in keys when settings[key]? value = settings[key] if $.type(value) == 'string' # "", "..." -> true # "false", "disabled" -> false value = $.trim(value).toLowerCase() settings[key] = not (value in ['false', 'disabled']) else settings[key] = !!value settings intOptions = (settings, keys) -> for key in keys when settings[key]? settings[key] = parseInt(settings[key]) settings parseCrop = (val) -> reRatio = /^([0-9]+)([x:])([0-9]+)\s*(|upscale|minimum)$/i ratio = reRatio.exec($.trim(val.toLowerCase())) or [] downscale: ratio[2] == 'x' upscale: !! ratio[4] notLess: ratio[4] == 'minimum' preferedSize: [+ratio[1], +ratio[3]] if ratio.length normalize = (settings) -> arrayOptions settings, [ 'tabs' 'preferredTypes' ] urlOptions settings, [ 'cdnBase' 'socialBase' 'urlBase' 'scriptBase' ] flagOptions settings, [ 'autostore' 'imagesOnly' 'multiple' 'clearable' 'pathValue' 'previewStep' 'systemDialog' ] intOptions settings, [ 'multipleMax' 'multipleMin' ] if not $.isArray settings.crop if /^(disabled?|false|null)$/i.test(settings.crop) or settings.multiple settings.crop = false else if $.isPlainObject settings.crop # old format settings.crop = [settings.crop] else settings.crop = $.map(settings.crop.split(','), parseCrop) if settings.crop or settings.multiple settings.previewStep = true if settings.crop settings.pathValue = true if not utils.abilities.sendFileAPI settings.systemDialog = false settings # Defaults (not normalized) publicDefaults = {} for own key, value of defaults publicDefaults[$.camelCase(key)] = value expose 'defaults', publicDefaults # Defaults + global variables ns.globals = utils.once -> values = {} for own key, fallback of defaults value = window["UPLOADCARE_#{utils.upperCase(key)}"] values[$.camelCase(key)] = if value? then value else fallback unless values.publicKey utils.commonWarning('publicKey') normalize(values) # Defaults + global variables + global overrides (once from uploadcare.start) # Not publicly-accessible ns.common = utils.once (settings) -> result = normalize $.extend({}, ns.globals(), settings or {}) waitForSettingsCb.fire result result # Defaults + global variables + global overrides + local overrides ns.build = (settings) -> normalize $.extend({}, ns.common(), settings or {}) waitForSettingsCb = $.Callbacks "once memory" # Like build() but won't cause settings freezing if they still didn't ns.waitForSettings = (settings, fn) -> waitForSettingsCb.add (common) -> fn normalize $.extend({}, common, settings or {}) class ns.CssCollector constructor: () -> @urls = [] @styles = [] addUrl: (url) -> if not /^https?:\/\//i.test(url) throw new Error('Embedded urls should be absolute. ' + url) unless url in @urls @urls.push url addStyle: (style) -> @styles.push style uploadcare.tabsCss = new ns.CssCollector
true
{ expose namespace, utils, jQuery: $ } = uploadcare namespace 'uploadcare.settings', (ns) -> defaults = # developer hooks 'live': true 'manual-start': false 'locale': null 'locale-pluralize': null 'locale-translations': null # widget settings 'system-dialog': false 'crop': 'disabled' 'preview-step': false 'images-only': false 'clearable': false 'multiple': false 'multiple-max': 0 'multiple-min': 1 'path-value': false 'tabs': 'file url facebook instagram flickr gdrive evernote box skydrive' 'preferred-types': '' # upload settings 'autostore': false 'public-key': null 'pusher-key': 'PI:KEY:<KEY>END_PI' 'cdn-base': 'http://www.ucarecdn.com' 'url-base': 'https://upload.uploadcare.com' 'social-base': 'https://social.uploadcare.com' # maintain settings 'script-base': if SCRIPT_BASE? then SCRIPT_BASE else '' presets = 'tabs': all: 'file url facebook dropbox gdrive instagram flickr vk evernote box skydrive' default: defaults.tabs str2arr = (value) -> unless $.isArray value value = $.trim value value = if value then value.split(' ') else [] value arrayOptions = (settings, keys) -> for key in keys value = source = str2arr(settings[key]) if presets.hasOwnProperty(key) value = [] for item in source if presets[key].hasOwnProperty(item) value = value.concat(str2arr(presets[key][item])) else value.push(item) settings[key] = utils.unique(value) settings urlOptions = (settings, keys) -> for key in keys when settings[key]? settings[key] = utils.normalizeUrl(settings[key]) settings flagOptions = (settings, keys) -> for key in keys when settings[key]? value = settings[key] if $.type(value) == 'string' # "", "..." -> true # "false", "disabled" -> false value = $.trim(value).toLowerCase() settings[key] = not (value in ['false', 'disabled']) else settings[key] = !!value settings intOptions = (settings, keys) -> for key in keys when settings[key]? settings[key] = parseInt(settings[key]) settings parseCrop = (val) -> reRatio = /^([0-9]+)([x:])([0-9]+)\s*(|upscale|minimum)$/i ratio = reRatio.exec($.trim(val.toLowerCase())) or [] downscale: ratio[2] == 'x' upscale: !! ratio[4] notLess: ratio[4] == 'minimum' preferedSize: [+ratio[1], +ratio[3]] if ratio.length normalize = (settings) -> arrayOptions settings, [ 'tabs' 'preferredTypes' ] urlOptions settings, [ 'cdnBase' 'socialBase' 'urlBase' 'scriptBase' ] flagOptions settings, [ 'autostore' 'imagesOnly' 'multiple' 'clearable' 'pathValue' 'previewStep' 'systemDialog' ] intOptions settings, [ 'multipleMax' 'multipleMin' ] if not $.isArray settings.crop if /^(disabled?|false|null)$/i.test(settings.crop) or settings.multiple settings.crop = false else if $.isPlainObject settings.crop # old format settings.crop = [settings.crop] else settings.crop = $.map(settings.crop.split(','), parseCrop) if settings.crop or settings.multiple settings.previewStep = true if settings.crop settings.pathValue = true if not utils.abilities.sendFileAPI settings.systemDialog = false settings # Defaults (not normalized) publicDefaults = {} for own key, value of defaults publicDefaults[$.camelCase(key)] = value expose 'defaults', publicDefaults # Defaults + global variables ns.globals = utils.once -> values = {} for own key, fallback of defaults value = window["UPLOADCARE_#{utils.upperCase(key)}"] values[$.camelCase(key)] = if value? then value else fallback unless values.publicKey utils.commonWarning('publicKey') normalize(values) # Defaults + global variables + global overrides (once from uploadcare.start) # Not publicly-accessible ns.common = utils.once (settings) -> result = normalize $.extend({}, ns.globals(), settings or {}) waitForSettingsCb.fire result result # Defaults + global variables + global overrides + local overrides ns.build = (settings) -> normalize $.extend({}, ns.common(), settings or {}) waitForSettingsCb = $.Callbacks "once memory" # Like build() but won't cause settings freezing if they still didn't ns.waitForSettings = (settings, fn) -> waitForSettingsCb.add (common) -> fn normalize $.extend({}, common, settings or {}) class ns.CssCollector constructor: () -> @urls = [] @styles = [] addUrl: (url) -> if not /^https?:\/\//i.test(url) throw new Error('Embedded urls should be absolute. ' + url) unless url in @urls @urls.push url addStyle: (style) -> @styles.push style uploadcare.tabsCss = new ns.CssCollector
[ { "context": "the 789 should have the diff property with value hoff\"\n test.ok anotherBucket.getById(\"456\")?, \"th", "end": 8299, "score": 0.9217618703842163, "start": 8296, "tag": "NAME", "value": "off" }, { "context": "st.expect 5\n @myBucket.set {id: \"4711\", name: \"t...
test/test.coffee
KONDENSATOR/bucket-node
1
bucket = require "../index.js" exports.testBucket_group1 = { setUp : (callback) -> bucket.initSingletonBucket "./test.db", (instance) => if instance? @myBucket = instance @myBucket.set {id: "123", fluff: "fluff", diff: "diff1"} @myBucket.set {id: "456", fluff: "fluff", diff: "diff2"} @myBucket.store () => callback() else console.log "Failed!" tearDown : (callback) -> @myBucket.obliterate () => callback() testGetById : (test) -> test.expect(3) data = {id: "test-id", niff: "niff", nuff: "nuff"} @myBucket.set(data) get = @myBucket.getById("test-id") test.ok(!get?, "object shouldn't be available here...") get = @myBucket.getById("test-id", true) test.ok(get?, "object should be availabel using the include dirty flag") @myBucket.store () => get = @myBucket.getById("test-id") test.ok(get?, "object should be available after store") test.done() testFindWhere : (test) -> test.expect(3) found = @myBucket.findWhere({diff: "diff1"}) test.ok(found?, "There should be a matching object...") test.equal(found.id, "123", "Should be the object with id 123") found = @myBucket.findWhere({diff: "diff3"}) test.ok(!found?, "Shouldn't be such an object") test.done() testWhere : (test) -> test.expect 4 found = @myBucket.where({fluff: "fluff"}) test.equal(found.length, 2, "Should be two objects") @myBucket.set({fluff: "fluff", diff: "diff3"}) found = @myBucket.where({fluff: "fluff"}) test.equal(found.length, 2, "Should be two objects, since the set one is dirty...") found = @myBucket.where({fluff: "fluff"}, true) test.equal(found.length, 3, "Should be three objects when dirty is included.") found = @myBucket.where({diff : "diffOther"}) test.equal(found.length, 0, "No object found should return empty array.") test.done() testAutoId : (test) -> test.expect(1) data = {niff: "niff", nuff: "nuff"} @myBucket.set(data) @myBucket.store () => where = (@myBucket.where {niff: "niff"})[0] test.ok(where.id?, "ID should be auto-assigned") test.done() testHasChanges : (test) -> test.expect 5 test.ok(!@myBucket.hasChanges(), "Shouldn't have changes before any operations...") @myBucket.set {fjorp: "fjorp"} test.ok(@myBucket.hasChanges(), "Un-stored set, should have changes") @myBucket.discardUnstoredChanges() test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after discard") @myBucket.deleteById("456") test.ok(@myBucket.hasChanges(), "Un-stored delete, should have changes") @myBucket.store () => test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after store") test.done() testHasChangesImpatient : (test) -> test.expect 5 test.ok(!@myBucket.hasChanges(), "Shouldn't have changes before any operations...") @myBucket.set {fjorp: "fjorp"} test.ok(@myBucket.hasChanges(), "Un-stored set, should have changes") @myBucket.discardUnstoredChanges() test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after discard") @myBucket.deleteById("456") test.ok(@myBucket.hasChanges(), "Un-stored delete, should have changes") @myBucket.store () -> test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after store") test.done() testStore : (test) -> test.expect 2 test.equal(@myBucket.where({fluff : "fluff"}).length, 2, "Should contain two fluffs after setup") @myBucket.set({fluff : "fluff", miff : "miff"}) @myBucket.store => anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load -> itms = anotherBucket.where({fluff : "fluff"}) length = itms.length test.equal(length, 3, "Should contain three fluffs after store and reload") anotherBucket.close () -> test.done() testStoreImpatient : (test) -> test.expect 3 test.equal(@myBucket.where({fluff : "fluff"}).length, 2, "Should contain two fluffs after setup") @myBucket.set({fluff : "fluff", miff : "miff"}) @myBucket.store => anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load -> test.equal(anotherBucket.where({fluff : "fluff"}).length, 3, "Should contain three fluffs after store and reload") anotherBucket.close () -> test.done() test.equal(@myBucket.where({fluff : "fluff"}).length, 3, "Should contain three fluffs after impatient store") testReplace : (test) -> test.expect 7 @myBucket.set({id : "456", fluff: "floff", fiff: "fiff"}) object = @myBucket.getById("456", true) test.equal(object.fiff, "fiff", "Should be the updated object") test.equal(object.fluff, "floff", "Should be the updated fluff") @myBucket.store => objectInner = @myBucket.getById "456" test.equal(objectInner.fiff, "fiff", "Should be the updated object after store") test.equal(objectInner.fluff, "floff", "Should be the updated fluff after store") anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => objectInnerest = anotherBucket.getById "456" test.ok(objectInnerest?, "Object shouldn't be null here...") test.equal(objectInnerest.fiff, "fiff", "Should be the updated object after store and load") test.equal(objectInnerest.fluff, "floff", "Should be the updated fluff after store and load") anotherBucket.close -> test.done() testReplaceImpatient : (test) -> test.expect 4 @myBucket.set({id : "456", fluff: "floff", fiff: "fiff"}) object = @myBucket.getById("456", true) test.equal(object.fiff, "fiff", "Should be the updated object") test.equal(object.fluff, "floff", "Should be the updated fluff") @myBucket.store -> object = @myBucket.getById "456" test.equal(object.fiff, "fiff", "Should be the updated object after store") test.equal(object.fluff, "floff", "Should be the updated fluff after store") test.done() testStoreEmpty : (test) -> test.expect 1 @myBucket.store (err, message) => test.equal(message, "No changes to save", "Should be status: no changes to save") test.done() testDelete : (test) -> test.expect 2 @myBucket.deleteById "456" @myBucket.store () => object = @myBucket.getById("456"); test.ok(!object?, "Object with id 456 should be deleted here...") anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => object = anotherBucket.getById "456" test.ok(!object?, "Object with id 456 should be deleted in thei bucket as well...") anotherBucket.close () => test.done() testDeleteImpatient : (test) -> test.expect 1 @myBucket.deleteById "456" @myBucket.store () -> object = @myBucket.getById("456"); test.ok(!object?, "Object with id 456 should be deleted here...") test.done() testBunchOfImpatientStores : (test) -> test.expect 9 @myBucket.set({fluff: "fluff", piff: "piff"}) @myBucket.store -> test.equal(@myBucket.where({fluff: "fluff"}).length, 3, "Should be three fluff objects"); @myBucket.deleteById "456" @myBucket.store -> test.equal(@myBucket.where({fluff: "fluff"}).length, 2, "Should be two fluff objects"); @myBucket.set({id: "456", fluff: "fluff"}) @myBucket.store -> @myBucket.set({id: "456", fluff: "fluff", diff: "diff"}) @myBucket.set({id: "789", fluff: "fluff", diff: "hoff"}) @myBucket.store -> @myBucket.set({id: "456", fluff: "fluff", diff: "diff2"}) @myBucket.store => test.equal @myBucket.getById("456").diff, "diff2", "the new 456 should have the diff property with value diff2" @myBucket.set({id: "456", fluff: "fluff"}) @myBucket.store => test.equal(@myBucket.where({fluff: "fluff"}).length, 4, "Should be three fluff objects"); test.ok !@myBucket.getById("456").diff?, "teh new 456 shouldn't have the diff property" anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => test.equal(anotherBucket.where({fluff: "fluff"}).length, 4, "Should be three fluff objects in the saved file"); test.equal @myBucket.getById("789").diff, "hoff", "the 789 should have the diff property with value hoff" test.ok anotherBucket.getById("456")?, "the 456 object should exist" test.ok !anotherBucket.getById("456")?.diff?, "the new 456 shouldn't have the diff property in the saved file" anotherBucket.close => test.done() testStoreEqualObjects : (test) -> test.expect 5 @myBucket.set {id: "4711", name: "torsten", arr: [1, 2, 3]} @myBucket.store (err, res, num) => test.equal num, 1, "should be one object written" test.equal @myBucket.getById("4711").arr[2], 3, "Arr object should be 3" @myBucket.set {id: "4711", name: "torsten", arr: [1, 2, 3]} @myBucket.store (err, res, num) => test.equal num, 0, "Writing the same object shouldn't result in writes..." @myBucket.set {id: "4711", name: "torsten", arr: [1, 2, 4]} @myBucket.store (err, res, num) => test.equal num, 1, "Writing changes should result in write..." test.equal @myBucket.getById("4711").arr[2], 4, "Arr object should be 4" test.done() }
174779
bucket = require "../index.js" exports.testBucket_group1 = { setUp : (callback) -> bucket.initSingletonBucket "./test.db", (instance) => if instance? @myBucket = instance @myBucket.set {id: "123", fluff: "fluff", diff: "diff1"} @myBucket.set {id: "456", fluff: "fluff", diff: "diff2"} @myBucket.store () => callback() else console.log "Failed!" tearDown : (callback) -> @myBucket.obliterate () => callback() testGetById : (test) -> test.expect(3) data = {id: "test-id", niff: "niff", nuff: "nuff"} @myBucket.set(data) get = @myBucket.getById("test-id") test.ok(!get?, "object shouldn't be available here...") get = @myBucket.getById("test-id", true) test.ok(get?, "object should be availabel using the include dirty flag") @myBucket.store () => get = @myBucket.getById("test-id") test.ok(get?, "object should be available after store") test.done() testFindWhere : (test) -> test.expect(3) found = @myBucket.findWhere({diff: "diff1"}) test.ok(found?, "There should be a matching object...") test.equal(found.id, "123", "Should be the object with id 123") found = @myBucket.findWhere({diff: "diff3"}) test.ok(!found?, "Shouldn't be such an object") test.done() testWhere : (test) -> test.expect 4 found = @myBucket.where({fluff: "fluff"}) test.equal(found.length, 2, "Should be two objects") @myBucket.set({fluff: "fluff", diff: "diff3"}) found = @myBucket.where({fluff: "fluff"}) test.equal(found.length, 2, "Should be two objects, since the set one is dirty...") found = @myBucket.where({fluff: "fluff"}, true) test.equal(found.length, 3, "Should be three objects when dirty is included.") found = @myBucket.where({diff : "diffOther"}) test.equal(found.length, 0, "No object found should return empty array.") test.done() testAutoId : (test) -> test.expect(1) data = {niff: "niff", nuff: "nuff"} @myBucket.set(data) @myBucket.store () => where = (@myBucket.where {niff: "niff"})[0] test.ok(where.id?, "ID should be auto-assigned") test.done() testHasChanges : (test) -> test.expect 5 test.ok(!@myBucket.hasChanges(), "Shouldn't have changes before any operations...") @myBucket.set {fjorp: "fjorp"} test.ok(@myBucket.hasChanges(), "Un-stored set, should have changes") @myBucket.discardUnstoredChanges() test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after discard") @myBucket.deleteById("456") test.ok(@myBucket.hasChanges(), "Un-stored delete, should have changes") @myBucket.store () => test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after store") test.done() testHasChangesImpatient : (test) -> test.expect 5 test.ok(!@myBucket.hasChanges(), "Shouldn't have changes before any operations...") @myBucket.set {fjorp: "fjorp"} test.ok(@myBucket.hasChanges(), "Un-stored set, should have changes") @myBucket.discardUnstoredChanges() test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after discard") @myBucket.deleteById("456") test.ok(@myBucket.hasChanges(), "Un-stored delete, should have changes") @myBucket.store () -> test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after store") test.done() testStore : (test) -> test.expect 2 test.equal(@myBucket.where({fluff : "fluff"}).length, 2, "Should contain two fluffs after setup") @myBucket.set({fluff : "fluff", miff : "miff"}) @myBucket.store => anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load -> itms = anotherBucket.where({fluff : "fluff"}) length = itms.length test.equal(length, 3, "Should contain three fluffs after store and reload") anotherBucket.close () -> test.done() testStoreImpatient : (test) -> test.expect 3 test.equal(@myBucket.where({fluff : "fluff"}).length, 2, "Should contain two fluffs after setup") @myBucket.set({fluff : "fluff", miff : "miff"}) @myBucket.store => anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load -> test.equal(anotherBucket.where({fluff : "fluff"}).length, 3, "Should contain three fluffs after store and reload") anotherBucket.close () -> test.done() test.equal(@myBucket.where({fluff : "fluff"}).length, 3, "Should contain three fluffs after impatient store") testReplace : (test) -> test.expect 7 @myBucket.set({id : "456", fluff: "floff", fiff: "fiff"}) object = @myBucket.getById("456", true) test.equal(object.fiff, "fiff", "Should be the updated object") test.equal(object.fluff, "floff", "Should be the updated fluff") @myBucket.store => objectInner = @myBucket.getById "456" test.equal(objectInner.fiff, "fiff", "Should be the updated object after store") test.equal(objectInner.fluff, "floff", "Should be the updated fluff after store") anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => objectInnerest = anotherBucket.getById "456" test.ok(objectInnerest?, "Object shouldn't be null here...") test.equal(objectInnerest.fiff, "fiff", "Should be the updated object after store and load") test.equal(objectInnerest.fluff, "floff", "Should be the updated fluff after store and load") anotherBucket.close -> test.done() testReplaceImpatient : (test) -> test.expect 4 @myBucket.set({id : "456", fluff: "floff", fiff: "fiff"}) object = @myBucket.getById("456", true) test.equal(object.fiff, "fiff", "Should be the updated object") test.equal(object.fluff, "floff", "Should be the updated fluff") @myBucket.store -> object = @myBucket.getById "456" test.equal(object.fiff, "fiff", "Should be the updated object after store") test.equal(object.fluff, "floff", "Should be the updated fluff after store") test.done() testStoreEmpty : (test) -> test.expect 1 @myBucket.store (err, message) => test.equal(message, "No changes to save", "Should be status: no changes to save") test.done() testDelete : (test) -> test.expect 2 @myBucket.deleteById "456" @myBucket.store () => object = @myBucket.getById("456"); test.ok(!object?, "Object with id 456 should be deleted here...") anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => object = anotherBucket.getById "456" test.ok(!object?, "Object with id 456 should be deleted in thei bucket as well...") anotherBucket.close () => test.done() testDeleteImpatient : (test) -> test.expect 1 @myBucket.deleteById "456" @myBucket.store () -> object = @myBucket.getById("456"); test.ok(!object?, "Object with id 456 should be deleted here...") test.done() testBunchOfImpatientStores : (test) -> test.expect 9 @myBucket.set({fluff: "fluff", piff: "piff"}) @myBucket.store -> test.equal(@myBucket.where({fluff: "fluff"}).length, 3, "Should be three fluff objects"); @myBucket.deleteById "456" @myBucket.store -> test.equal(@myBucket.where({fluff: "fluff"}).length, 2, "Should be two fluff objects"); @myBucket.set({id: "456", fluff: "fluff"}) @myBucket.store -> @myBucket.set({id: "456", fluff: "fluff", diff: "diff"}) @myBucket.set({id: "789", fluff: "fluff", diff: "hoff"}) @myBucket.store -> @myBucket.set({id: "456", fluff: "fluff", diff: "diff2"}) @myBucket.store => test.equal @myBucket.getById("456").diff, "diff2", "the new 456 should have the diff property with value diff2" @myBucket.set({id: "456", fluff: "fluff"}) @myBucket.store => test.equal(@myBucket.where({fluff: "fluff"}).length, 4, "Should be three fluff objects"); test.ok !@myBucket.getById("456").diff?, "teh new 456 shouldn't have the diff property" anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => test.equal(anotherBucket.where({fluff: "fluff"}).length, 4, "Should be three fluff objects in the saved file"); test.equal @myBucket.getById("789").diff, "hoff", "the 789 should have the diff property with value h<NAME>" test.ok anotherBucket.getById("456")?, "the 456 object should exist" test.ok !anotherBucket.getById("456")?.diff?, "the new 456 shouldn't have the diff property in the saved file" anotherBucket.close => test.done() testStoreEqualObjects : (test) -> test.expect 5 @myBucket.set {id: "4711", name: "<NAME>", arr: [1, 2, 3]} @myBucket.store (err, res, num) => test.equal num, 1, "should be one object written" test.equal @myBucket.getById("4711").arr[2], 3, "Arr object should be 3" @myBucket.set {id: "4711", name: "<NAME>", arr: [1, 2, 3]} @myBucket.store (err, res, num) => test.equal num, 0, "Writing the same object shouldn't result in writes..." @myBucket.set {id: "4711", name: "<NAME>", arr: [1, 2, 4]} @myBucket.store (err, res, num) => test.equal num, 1, "Writing changes should result in write..." test.equal @myBucket.getById("4711").arr[2], 4, "Arr object should be 4" test.done() }
true
bucket = require "../index.js" exports.testBucket_group1 = { setUp : (callback) -> bucket.initSingletonBucket "./test.db", (instance) => if instance? @myBucket = instance @myBucket.set {id: "123", fluff: "fluff", diff: "diff1"} @myBucket.set {id: "456", fluff: "fluff", diff: "diff2"} @myBucket.store () => callback() else console.log "Failed!" tearDown : (callback) -> @myBucket.obliterate () => callback() testGetById : (test) -> test.expect(3) data = {id: "test-id", niff: "niff", nuff: "nuff"} @myBucket.set(data) get = @myBucket.getById("test-id") test.ok(!get?, "object shouldn't be available here...") get = @myBucket.getById("test-id", true) test.ok(get?, "object should be availabel using the include dirty flag") @myBucket.store () => get = @myBucket.getById("test-id") test.ok(get?, "object should be available after store") test.done() testFindWhere : (test) -> test.expect(3) found = @myBucket.findWhere({diff: "diff1"}) test.ok(found?, "There should be a matching object...") test.equal(found.id, "123", "Should be the object with id 123") found = @myBucket.findWhere({diff: "diff3"}) test.ok(!found?, "Shouldn't be such an object") test.done() testWhere : (test) -> test.expect 4 found = @myBucket.where({fluff: "fluff"}) test.equal(found.length, 2, "Should be two objects") @myBucket.set({fluff: "fluff", diff: "diff3"}) found = @myBucket.where({fluff: "fluff"}) test.equal(found.length, 2, "Should be two objects, since the set one is dirty...") found = @myBucket.where({fluff: "fluff"}, true) test.equal(found.length, 3, "Should be three objects when dirty is included.") found = @myBucket.where({diff : "diffOther"}) test.equal(found.length, 0, "No object found should return empty array.") test.done() testAutoId : (test) -> test.expect(1) data = {niff: "niff", nuff: "nuff"} @myBucket.set(data) @myBucket.store () => where = (@myBucket.where {niff: "niff"})[0] test.ok(where.id?, "ID should be auto-assigned") test.done() testHasChanges : (test) -> test.expect 5 test.ok(!@myBucket.hasChanges(), "Shouldn't have changes before any operations...") @myBucket.set {fjorp: "fjorp"} test.ok(@myBucket.hasChanges(), "Un-stored set, should have changes") @myBucket.discardUnstoredChanges() test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after discard") @myBucket.deleteById("456") test.ok(@myBucket.hasChanges(), "Un-stored delete, should have changes") @myBucket.store () => test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after store") test.done() testHasChangesImpatient : (test) -> test.expect 5 test.ok(!@myBucket.hasChanges(), "Shouldn't have changes before any operations...") @myBucket.set {fjorp: "fjorp"} test.ok(@myBucket.hasChanges(), "Un-stored set, should have changes") @myBucket.discardUnstoredChanges() test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after discard") @myBucket.deleteById("456") test.ok(@myBucket.hasChanges(), "Un-stored delete, should have changes") @myBucket.store () -> test.ok(!@myBucket.hasChanges(), "Shouldn't have changes after store") test.done() testStore : (test) -> test.expect 2 test.equal(@myBucket.where({fluff : "fluff"}).length, 2, "Should contain two fluffs after setup") @myBucket.set({fluff : "fluff", miff : "miff"}) @myBucket.store => anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load -> itms = anotherBucket.where({fluff : "fluff"}) length = itms.length test.equal(length, 3, "Should contain three fluffs after store and reload") anotherBucket.close () -> test.done() testStoreImpatient : (test) -> test.expect 3 test.equal(@myBucket.where({fluff : "fluff"}).length, 2, "Should contain two fluffs after setup") @myBucket.set({fluff : "fluff", miff : "miff"}) @myBucket.store => anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load -> test.equal(anotherBucket.where({fluff : "fluff"}).length, 3, "Should contain three fluffs after store and reload") anotherBucket.close () -> test.done() test.equal(@myBucket.where({fluff : "fluff"}).length, 3, "Should contain three fluffs after impatient store") testReplace : (test) -> test.expect 7 @myBucket.set({id : "456", fluff: "floff", fiff: "fiff"}) object = @myBucket.getById("456", true) test.equal(object.fiff, "fiff", "Should be the updated object") test.equal(object.fluff, "floff", "Should be the updated fluff") @myBucket.store => objectInner = @myBucket.getById "456" test.equal(objectInner.fiff, "fiff", "Should be the updated object after store") test.equal(objectInner.fluff, "floff", "Should be the updated fluff after store") anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => objectInnerest = anotherBucket.getById "456" test.ok(objectInnerest?, "Object shouldn't be null here...") test.equal(objectInnerest.fiff, "fiff", "Should be the updated object after store and load") test.equal(objectInnerest.fluff, "floff", "Should be the updated fluff after store and load") anotherBucket.close -> test.done() testReplaceImpatient : (test) -> test.expect 4 @myBucket.set({id : "456", fluff: "floff", fiff: "fiff"}) object = @myBucket.getById("456", true) test.equal(object.fiff, "fiff", "Should be the updated object") test.equal(object.fluff, "floff", "Should be the updated fluff") @myBucket.store -> object = @myBucket.getById "456" test.equal(object.fiff, "fiff", "Should be the updated object after store") test.equal(object.fluff, "floff", "Should be the updated fluff after store") test.done() testStoreEmpty : (test) -> test.expect 1 @myBucket.store (err, message) => test.equal(message, "No changes to save", "Should be status: no changes to save") test.done() testDelete : (test) -> test.expect 2 @myBucket.deleteById "456" @myBucket.store () => object = @myBucket.getById("456"); test.ok(!object?, "Object with id 456 should be deleted here...") anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => object = anotherBucket.getById "456" test.ok(!object?, "Object with id 456 should be deleted in thei bucket as well...") anotherBucket.close () => test.done() testDeleteImpatient : (test) -> test.expect 1 @myBucket.deleteById "456" @myBucket.store () -> object = @myBucket.getById("456"); test.ok(!object?, "Object with id 456 should be deleted here...") test.done() testBunchOfImpatientStores : (test) -> test.expect 9 @myBucket.set({fluff: "fluff", piff: "piff"}) @myBucket.store -> test.equal(@myBucket.where({fluff: "fluff"}).length, 3, "Should be three fluff objects"); @myBucket.deleteById "456" @myBucket.store -> test.equal(@myBucket.where({fluff: "fluff"}).length, 2, "Should be two fluff objects"); @myBucket.set({id: "456", fluff: "fluff"}) @myBucket.store -> @myBucket.set({id: "456", fluff: "fluff", diff: "diff"}) @myBucket.set({id: "789", fluff: "fluff", diff: "hoff"}) @myBucket.store -> @myBucket.set({id: "456", fluff: "fluff", diff: "diff2"}) @myBucket.store => test.equal @myBucket.getById("456").diff, "diff2", "the new 456 should have the diff property with value diff2" @myBucket.set({id: "456", fluff: "fluff"}) @myBucket.store => test.equal(@myBucket.where({fluff: "fluff"}).length, 4, "Should be three fluff objects"); test.ok !@myBucket.getById("456").diff?, "teh new 456 shouldn't have the diff property" anotherBucket = new bucket.Bucket("./test.db") anotherBucket.load => test.equal(anotherBucket.where({fluff: "fluff"}).length, 4, "Should be three fluff objects in the saved file"); test.equal @myBucket.getById("789").diff, "hoff", "the 789 should have the diff property with value hPI:NAME:<NAME>END_PI" test.ok anotherBucket.getById("456")?, "the 456 object should exist" test.ok !anotherBucket.getById("456")?.diff?, "the new 456 shouldn't have the diff property in the saved file" anotherBucket.close => test.done() testStoreEqualObjects : (test) -> test.expect 5 @myBucket.set {id: "4711", name: "PI:NAME:<NAME>END_PI", arr: [1, 2, 3]} @myBucket.store (err, res, num) => test.equal num, 1, "should be one object written" test.equal @myBucket.getById("4711").arr[2], 3, "Arr object should be 3" @myBucket.set {id: "4711", name: "PI:NAME:<NAME>END_PI", arr: [1, 2, 3]} @myBucket.store (err, res, num) => test.equal num, 0, "Writing the same object shouldn't result in writes..." @myBucket.set {id: "4711", name: "PI:NAME:<NAME>END_PI", arr: [1, 2, 4]} @myBucket.store (err, res, num) => test.equal num, 1, "Writing changes should result in write..." test.equal @myBucket.getById("4711").arr[2], 4, "Arr object should be 4" test.done() }
[ { "context": "g \"called redrawToIframe\"\n \n key = '1n3uci3ucTqJOA1nIDO90ihfPPJkpM6JQRSdwZdLN6aQ'\n dat = document.getElementById(\"location\"", "end": 8246, "score": 0.999776303768158, "start": 8202, "tag": "KEY", "value": "1n3uci3ucTqJOA1nIDO90ihfPPJkpM6JQRSdwZdLN6aQ...
app/assets/javascripts/gmapapi.coffee
cloudhc/hello-play
0
# ________ ________ ________ ___ _______ _______ # |\ __ \|\ __ \|\ __ \ |\ \ |\ ___ \ |\ ___ \ # \ \ \|\ /\ \ \|\ \ \ \|\ /_ \ \ \ \ \ __/|\ \ __/| # \ \ __ \ \ \\\ \ \ __ \ \ \ \ \ \ \_|/_\ \ \_|/__ # \ \ \|\ \ \ \\\ \ \ \|\ \ \ \ \____\ \ \_|\ \ \ \_|\ \ # \ \_______\ \_______\ \_______\ \ \_______\ \_______\ \_______\ # \|_______|\|_______|\|_______| \|_______|\|_______|\|_______| jQuery ($) -> # Make the following global variables map = null infowindow = null request = null icons = null specific_icon = null marker = null markers = null value = null collection = null getTypes = null place = null pois = null # main entry init = () -> # Setup map options mapOptions = center: new google.maps.LatLng(47.5865, -122.150) zoom: 11 streetViewControl: false panControl: false mapTypeId: google.maps.MapTypeId.ROADMAP zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL mapTypeControlOptions: mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'] # Setup POI types getTypes = (types=[]) -> icons = restaurant: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue.png' park: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png' school:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/orange.png' university:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/orange.png' store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' department_store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' clothing_store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' shopping_mall:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' gym: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red.png' health: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red.png' museum:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' movie_theater:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' amusement_park: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' art_gallery: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' if not types.length for key of icons key else for icon in types if icon of icons return icons[icon] # Create the map with above options in div map = new google.maps.Map(document.getElementById("map"),mapOptions) # Drop marker in the same location marker = new google.maps.Marker map: map animation: google.maps.Animation.DROP position: new google.maps.LatLng(47.53772, -122.1153) icon: 'http://maps.google.com/mapfiles/arrow.png' # Create a request field to hold POIs request = location: new google.maps.LatLng(47.58816, -122.16342) radius: '7000' types: getTypes() # Create the infowindow(popup over marker) infowindow = new google.maps.InfoWindow() # Setup places nearby search (it setups points near the center marker) service = new google.maps.places.PlacesService(map) service.nearbySearch(request, callback) # draw polyline drawPolyline() # draw path drawPathPolyline() # Create the callback function to loop thru the places (object) callback = (results, status) -> pois = [] if status is google.maps.places.PlacesServiceStatus.OK for index, attrs of results poi = results[index] pois.push(poi) all = document.getElementById('all') google.maps.event.addDomListenerOnce all, 'click', -> for index, v of pois createMarker v console.log v.types school = document.getElementById('school') google.maps.event.addDomListenerOnce school, 'click', -> for index, v of pois if v.types.indexOf('school') != -1 createMarker v # Create the actual markers for the looped places createMarker = (place) -> # Create markers for of the types assigned above in getTypes function marker = new google.maps.Marker map: map position: place.geometry.location icon: getTypes(place.types) # Create a click listener that shows a info window with places name google.maps.event.addListener marker, 'click', -> infowindow.setContent(place.name) infowindow.open(map,@) placesList = document.getElementById('results') placesList.innerHTML += '<p class="' + place.types + '">' + place.name + '</p>'; # sample code for draw polyline drawPolyline = () -> # Showing the path flightPlanCoordinates = [ {lat: 37.322701, lng: 127.022245}, {lat: 33.395369, lng: 126.494901}, {lat: 35.849403, lng: 128.553308} ] flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2 }) flightPath.setMap(map) # Define the symbol, using one of the predefined paths ('CIRCLE') # supplied by the Google Maps JavaScript API. drawPathPolyline = () -> lineSymbol = path: google.maps.SymbolPath.CIRCLE, scale: 8, strokeColor: '#393' # Create the polyline and add the symbol to it via the 'icons' property. line = new google.maps.Polyline({ path: flightPlanCoordinates, icons: [{ icon: lineSymbol, offset: '100%' }], map: map }); animateCircle(line) # Use the DOM setInterval() function to change the offset of the symbol at fixed intervals. animateCircle = (line) -> count = 0; window.setInterval(() -> count = (count + 1) % 200 icons = line.get('icons') icons[0].offset = (count / 2) + '%' line.set('icons', icons) , 20) # Create the click event handler $('#clear').click -> console.log "Clear button clicked!" clearList = document.getElementById('results') clearList.innerHTML = "<p></p>" # move to location $('#transform').click -> console.log "transform button clicked!" transformToAxis() # transform address to axis transformToAxis = () -> console.log "called transformToAxis" geocoder = new google.maps.Geocoder(); address = document.getElementById("address").value; geocoder.geocode({'address': address}, (results, status) -> if status == google.maps.GeocoderStatus.OK darwin = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); map.setCenter(darwin) else alert("Geocode was not successful for the following reason: " + status) ) # search into google spreadsheets $('#nearBySearch').click -> console.log "nearBySearch button click!" drawToIframe() drawMarkerToPlace() # draw to iframe tag drawToIframe = () -> console.log "called redrawToIframe" key = '1n3uci3ucTqJOA1nIDO90ihfPPJkpM6JQRSdwZdLN6aQ' dat = document.getElementById("location").value sqlByCategory = { movie : ['0', "SELECT B,C,D,E,F,G,H,I,J WHERE B CONTAINS '#{dat}'"], book : ['325940056', "SELECT B,C,D,E,F,G,H,I WHERE B CONTAINS '#{dat}'"], concert : ['152989327', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}'"], lecture : ['904106426', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}'"], travel : ['1432675087', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}' OR G CONTAINS '#{dat}'"] } # reload source attribute of iframe. category = switch $('#category').val() when 'Movie' then sqlByCategory.movie when 'Book' then sqlByCategory.book when 'Concert' then sqlByCategory.concert when 'Lecture' then sqlByCategory.lecture when 'Travel' then sqlByCategory.travel else sqlByCategory.travel $('#travelList').attr('src', makeQueryOutHTML(key, category[0], category[1])) # make a query string makeQueryOutHTML = (sheet_key, sheet_gid, sql_stmt) -> console.log "called makeQueryOutHTML : #{sql_stmt}" query = "https://spreadsheets.google.com/tq?tqx=out:html&tq=#{sql_stmt}&key=#{sheet_key}&gid=#{sheet_gid}" # draw marker to place drawMarkerToPlace = () -> console.log "called drawMarkerToPlace" address = document.getElementById("location").value; geocoder = new google.maps.Geocoder(); geocoder.geocode({'address': address}, (results, status) -> if status == google.maps.GeocoderStatus.OK darwin = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); # create marker object marker = new google.maps.Marker map: map animation: google.maps.Animation.DROP position: darwin icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png' # Create the infowindow(popup over marker) infowindow = new google.maps.InfoWindow() # register click event handler google.maps.event.addListener marker, "click", () -> infowindow.open(map, marker) # move to center map.setCenter(darwin) else console.log "error" ) init()
72574
# ________ ________ ________ ___ _______ _______ # |\ __ \|\ __ \|\ __ \ |\ \ |\ ___ \ |\ ___ \ # \ \ \|\ /\ \ \|\ \ \ \|\ /_ \ \ \ \ \ __/|\ \ __/| # \ \ __ \ \ \\\ \ \ __ \ \ \ \ \ \ \_|/_\ \ \_|/__ # \ \ \|\ \ \ \\\ \ \ \|\ \ \ \ \____\ \ \_|\ \ \ \_|\ \ # \ \_______\ \_______\ \_______\ \ \_______\ \_______\ \_______\ # \|_______|\|_______|\|_______| \|_______|\|_______|\|_______| jQuery ($) -> # Make the following global variables map = null infowindow = null request = null icons = null specific_icon = null marker = null markers = null value = null collection = null getTypes = null place = null pois = null # main entry init = () -> # Setup map options mapOptions = center: new google.maps.LatLng(47.5865, -122.150) zoom: 11 streetViewControl: false panControl: false mapTypeId: google.maps.MapTypeId.ROADMAP zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL mapTypeControlOptions: mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'] # Setup POI types getTypes = (types=[]) -> icons = restaurant: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue.png' park: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png' school:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/orange.png' university:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/orange.png' store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' department_store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' clothing_store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' shopping_mall:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' gym: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red.png' health: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red.png' museum:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' movie_theater:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' amusement_park: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' art_gallery: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' if not types.length for key of icons key else for icon in types if icon of icons return icons[icon] # Create the map with above options in div map = new google.maps.Map(document.getElementById("map"),mapOptions) # Drop marker in the same location marker = new google.maps.Marker map: map animation: google.maps.Animation.DROP position: new google.maps.LatLng(47.53772, -122.1153) icon: 'http://maps.google.com/mapfiles/arrow.png' # Create a request field to hold POIs request = location: new google.maps.LatLng(47.58816, -122.16342) radius: '7000' types: getTypes() # Create the infowindow(popup over marker) infowindow = new google.maps.InfoWindow() # Setup places nearby search (it setups points near the center marker) service = new google.maps.places.PlacesService(map) service.nearbySearch(request, callback) # draw polyline drawPolyline() # draw path drawPathPolyline() # Create the callback function to loop thru the places (object) callback = (results, status) -> pois = [] if status is google.maps.places.PlacesServiceStatus.OK for index, attrs of results poi = results[index] pois.push(poi) all = document.getElementById('all') google.maps.event.addDomListenerOnce all, 'click', -> for index, v of pois createMarker v console.log v.types school = document.getElementById('school') google.maps.event.addDomListenerOnce school, 'click', -> for index, v of pois if v.types.indexOf('school') != -1 createMarker v # Create the actual markers for the looped places createMarker = (place) -> # Create markers for of the types assigned above in getTypes function marker = new google.maps.Marker map: map position: place.geometry.location icon: getTypes(place.types) # Create a click listener that shows a info window with places name google.maps.event.addListener marker, 'click', -> infowindow.setContent(place.name) infowindow.open(map,@) placesList = document.getElementById('results') placesList.innerHTML += '<p class="' + place.types + '">' + place.name + '</p>'; # sample code for draw polyline drawPolyline = () -> # Showing the path flightPlanCoordinates = [ {lat: 37.322701, lng: 127.022245}, {lat: 33.395369, lng: 126.494901}, {lat: 35.849403, lng: 128.553308} ] flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2 }) flightPath.setMap(map) # Define the symbol, using one of the predefined paths ('CIRCLE') # supplied by the Google Maps JavaScript API. drawPathPolyline = () -> lineSymbol = path: google.maps.SymbolPath.CIRCLE, scale: 8, strokeColor: '#393' # Create the polyline and add the symbol to it via the 'icons' property. line = new google.maps.Polyline({ path: flightPlanCoordinates, icons: [{ icon: lineSymbol, offset: '100%' }], map: map }); animateCircle(line) # Use the DOM setInterval() function to change the offset of the symbol at fixed intervals. animateCircle = (line) -> count = 0; window.setInterval(() -> count = (count + 1) % 200 icons = line.get('icons') icons[0].offset = (count / 2) + '%' line.set('icons', icons) , 20) # Create the click event handler $('#clear').click -> console.log "Clear button clicked!" clearList = document.getElementById('results') clearList.innerHTML = "<p></p>" # move to location $('#transform').click -> console.log "transform button clicked!" transformToAxis() # transform address to axis transformToAxis = () -> console.log "called transformToAxis" geocoder = new google.maps.Geocoder(); address = document.getElementById("address").value; geocoder.geocode({'address': address}, (results, status) -> if status == google.maps.GeocoderStatus.OK darwin = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); map.setCenter(darwin) else alert("Geocode was not successful for the following reason: " + status) ) # search into google spreadsheets $('#nearBySearch').click -> console.log "nearBySearch button click!" drawToIframe() drawMarkerToPlace() # draw to iframe tag drawToIframe = () -> console.log "called redrawToIframe" key = '<KEY>' dat = document.getElementById("location").value sqlByCategory = { movie : ['0', "SELECT B,C,D,E,F,G,H,I,J WHERE B CONTAINS '#{dat}'"], book : ['325940056', "SELECT B,C,D,E,F,G,H,I WHERE B CONTAINS '#{dat}'"], concert : ['152989327', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}'"], lecture : ['904106426', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}'"], travel : ['1432675087', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}' OR G CONTAINS '#{dat}'"] } # reload source attribute of iframe. category = switch $('#category').val() when 'Movie' then sqlByCategory.movie when 'Book' then sqlByCategory.book when 'Concert' then sqlByCategory.concert when 'Lecture' then sqlByCategory.lecture when 'Travel' then sqlByCategory.travel else sqlByCategory.travel $('#travelList').attr('src', makeQueryOutHTML(key, category[0], category[1])) # make a query string makeQueryOutHTML = (sheet_key, sheet_gid, sql_stmt) -> console.log "called makeQueryOutHTML : #{sql_stmt}" query = "https://spreadsheets.google.com/tq?tqx=out:html&tq=#{sql_stmt}&key=#{sheet_key}&gid=#{sheet_gid}" # draw marker to place drawMarkerToPlace = () -> console.log "called drawMarkerToPlace" address = document.getElementById("location").value; geocoder = new google.maps.Geocoder(); geocoder.geocode({'address': address}, (results, status) -> if status == google.maps.GeocoderStatus.OK darwin = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); # create marker object marker = new google.maps.Marker map: map animation: google.maps.Animation.DROP position: darwin icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png' # Create the infowindow(popup over marker) infowindow = new google.maps.InfoWindow() # register click event handler google.maps.event.addListener marker, "click", () -> infowindow.open(map, marker) # move to center map.setCenter(darwin) else console.log "error" ) init()
true
# ________ ________ ________ ___ _______ _______ # |\ __ \|\ __ \|\ __ \ |\ \ |\ ___ \ |\ ___ \ # \ \ \|\ /\ \ \|\ \ \ \|\ /_ \ \ \ \ \ __/|\ \ __/| # \ \ __ \ \ \\\ \ \ __ \ \ \ \ \ \ \_|/_\ \ \_|/__ # \ \ \|\ \ \ \\\ \ \ \|\ \ \ \ \____\ \ \_|\ \ \ \_|\ \ # \ \_______\ \_______\ \_______\ \ \_______\ \_______\ \_______\ # \|_______|\|_______|\|_______| \|_______|\|_______|\|_______| jQuery ($) -> # Make the following global variables map = null infowindow = null request = null icons = null specific_icon = null marker = null markers = null value = null collection = null getTypes = null place = null pois = null # main entry init = () -> # Setup map options mapOptions = center: new google.maps.LatLng(47.5865, -122.150) zoom: 11 streetViewControl: false panControl: false mapTypeId: google.maps.MapTypeId.ROADMAP zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL mapTypeControlOptions: mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'] # Setup POI types getTypes = (types=[]) -> icons = restaurant: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue.png' park: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png' school:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/orange.png' university:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/orange.png' store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' department_store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' clothing_store: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' shopping_mall:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/yellow.png' gym: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red.png' health: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red.png' museum:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' movie_theater:'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' amusement_park: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' art_gallery: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/purple.png' if not types.length for key of icons key else for icon in types if icon of icons return icons[icon] # Create the map with above options in div map = new google.maps.Map(document.getElementById("map"),mapOptions) # Drop marker in the same location marker = new google.maps.Marker map: map animation: google.maps.Animation.DROP position: new google.maps.LatLng(47.53772, -122.1153) icon: 'http://maps.google.com/mapfiles/arrow.png' # Create a request field to hold POIs request = location: new google.maps.LatLng(47.58816, -122.16342) radius: '7000' types: getTypes() # Create the infowindow(popup over marker) infowindow = new google.maps.InfoWindow() # Setup places nearby search (it setups points near the center marker) service = new google.maps.places.PlacesService(map) service.nearbySearch(request, callback) # draw polyline drawPolyline() # draw path drawPathPolyline() # Create the callback function to loop thru the places (object) callback = (results, status) -> pois = [] if status is google.maps.places.PlacesServiceStatus.OK for index, attrs of results poi = results[index] pois.push(poi) all = document.getElementById('all') google.maps.event.addDomListenerOnce all, 'click', -> for index, v of pois createMarker v console.log v.types school = document.getElementById('school') google.maps.event.addDomListenerOnce school, 'click', -> for index, v of pois if v.types.indexOf('school') != -1 createMarker v # Create the actual markers for the looped places createMarker = (place) -> # Create markers for of the types assigned above in getTypes function marker = new google.maps.Marker map: map position: place.geometry.location icon: getTypes(place.types) # Create a click listener that shows a info window with places name google.maps.event.addListener marker, 'click', -> infowindow.setContent(place.name) infowindow.open(map,@) placesList = document.getElementById('results') placesList.innerHTML += '<p class="' + place.types + '">' + place.name + '</p>'; # sample code for draw polyline drawPolyline = () -> # Showing the path flightPlanCoordinates = [ {lat: 37.322701, lng: 127.022245}, {lat: 33.395369, lng: 126.494901}, {lat: 35.849403, lng: 128.553308} ] flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2 }) flightPath.setMap(map) # Define the symbol, using one of the predefined paths ('CIRCLE') # supplied by the Google Maps JavaScript API. drawPathPolyline = () -> lineSymbol = path: google.maps.SymbolPath.CIRCLE, scale: 8, strokeColor: '#393' # Create the polyline and add the symbol to it via the 'icons' property. line = new google.maps.Polyline({ path: flightPlanCoordinates, icons: [{ icon: lineSymbol, offset: '100%' }], map: map }); animateCircle(line) # Use the DOM setInterval() function to change the offset of the symbol at fixed intervals. animateCircle = (line) -> count = 0; window.setInterval(() -> count = (count + 1) % 200 icons = line.get('icons') icons[0].offset = (count / 2) + '%' line.set('icons', icons) , 20) # Create the click event handler $('#clear').click -> console.log "Clear button clicked!" clearList = document.getElementById('results') clearList.innerHTML = "<p></p>" # move to location $('#transform').click -> console.log "transform button clicked!" transformToAxis() # transform address to axis transformToAxis = () -> console.log "called transformToAxis" geocoder = new google.maps.Geocoder(); address = document.getElementById("address").value; geocoder.geocode({'address': address}, (results, status) -> if status == google.maps.GeocoderStatus.OK darwin = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); map.setCenter(darwin) else alert("Geocode was not successful for the following reason: " + status) ) # search into google spreadsheets $('#nearBySearch').click -> console.log "nearBySearch button click!" drawToIframe() drawMarkerToPlace() # draw to iframe tag drawToIframe = () -> console.log "called redrawToIframe" key = 'PI:KEY:<KEY>END_PI' dat = document.getElementById("location").value sqlByCategory = { movie : ['0', "SELECT B,C,D,E,F,G,H,I,J WHERE B CONTAINS '#{dat}'"], book : ['325940056', "SELECT B,C,D,E,F,G,H,I WHERE B CONTAINS '#{dat}'"], concert : ['152989327', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}'"], lecture : ['904106426', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}'"], travel : ['1432675087', "SELECT B,C,D,E,F,G WHERE B CONTAINS '#{dat}' OR G CONTAINS '#{dat}'"] } # reload source attribute of iframe. category = switch $('#category').val() when 'Movie' then sqlByCategory.movie when 'Book' then sqlByCategory.book when 'Concert' then sqlByCategory.concert when 'Lecture' then sqlByCategory.lecture when 'Travel' then sqlByCategory.travel else sqlByCategory.travel $('#travelList').attr('src', makeQueryOutHTML(key, category[0], category[1])) # make a query string makeQueryOutHTML = (sheet_key, sheet_gid, sql_stmt) -> console.log "called makeQueryOutHTML : #{sql_stmt}" query = "https://spreadsheets.google.com/tq?tqx=out:html&tq=#{sql_stmt}&key=#{sheet_key}&gid=#{sheet_gid}" # draw marker to place drawMarkerToPlace = () -> console.log "called drawMarkerToPlace" address = document.getElementById("location").value; geocoder = new google.maps.Geocoder(); geocoder.geocode({'address': address}, (results, status) -> if status == google.maps.GeocoderStatus.OK darwin = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); # create marker object marker = new google.maps.Marker map: map animation: google.maps.Animation.DROP position: darwin icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png' # Create the infowindow(popup over marker) infowindow = new google.maps.InfoWindow() # register click event handler google.maps.event.addListener marker, "click", () -> infowindow.open(map, marker) # move to center map.setCenter(darwin) else console.log "error" ) init()
[ { "context": "entID': '1646621778998777'\n # 'clientSecret': '491d294a0b463f3dac5658ec962650c2'\n 'clientID': '1646621778998777'\n 'clientSe", "end": 169, "score": 0.9995924234390259, "start": 137, "tag": "KEY", "value": "491d294a0b463f3dac5658ec962650c2" }, { "context": "li...
src/config/auth.coffee
tonymuu/koalie-backend
0
module.exports = 'facebookAuth': ######## prod credentials ########### # 'clientID': '1646621778998777' # 'clientSecret': '491d294a0b463f3dac5658ec962650c2' 'clientID': '1646621778998777' 'clientSecret': '491d294a0b463f3dac5658ec962650c2' 'callbackURL': 'http://localhost:3000/auth/facebook/callback'
225866
module.exports = 'facebookAuth': ######## prod credentials ########### # 'clientID': '1646621778998777' # 'clientSecret': '<KEY>' 'clientID': '1646621778998777' 'clientSecret': '<KEY>' 'callbackURL': 'http://localhost:3000/auth/facebook/callback'
true
module.exports = 'facebookAuth': ######## prod credentials ########### # 'clientID': '1646621778998777' # 'clientSecret': 'PI:KEY:<KEY>END_PI' 'clientID': '1646621778998777' 'clientSecret': 'PI:KEY:<KEY>END_PI' 'callbackURL': 'http://localhost:3000/auth/facebook/callback'
[ { "context": "s\n # altersql.push ' '\n\n {\n name: fkName,\n column,\n referenced_table,\n ", "end": 9085, "score": 0.9865169525146484, "start": 9083, "tag": "NAME", "value": "fk" }, { "context": " # altersql.push ' '\n\n {\n name: fkN...
src/schema/SchemaCompiler.coffee
smbape/node-dblayer
0
_ = require 'lodash' module.exports = class SchemaCompiler constructor: (options = {})-> columnCompiler = this.columnCompiler = new this.ColumnCompiler options this.indent = options.indent or ' ' this.LF = options.LF or '\n' this.delimiter = options.delimiter or ';' for prop in ['adapter', 'args', 'words'] @[prop] = columnCompiler[prop] for method in ['escape', 'escapeId', 'escapeSearch', 'escapeBeginWith', 'escapeEndWith'] if 'function' is typeof this.adapter[method] @[method] = this.adapter[method].bind this.adapter this.options = _.clone options # https://dev.mysql.com/doc/refman/5.7/en/create-table.html # http://www.postgresql.org/docs/9.4/static/sql-createtable.html SchemaCompiler::createTable = (tableModel, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, args, indent, LF, delimiter} = @ tableName = tableModel.name tableNameId = escapeId tableName args.tableModel = tableName tablesql = [] spaceLen = ' '.repeat(66 - 10 - tableName.length - 2) tablesql.push """ /*==============================================================*/ /* Table: #{tableName}#{spaceLen}*/ /*==============================================================*/ """ tablesql.push.apply tablesql, [LF, words.create_table, ' '] if options.if_not_exists tablesql.push words.if_not_exists tablesql.push ' ' tablesql.push.apply tablesql, [tableNameId, ' (', LF] tablespec = [] # column definition for column, spec of tableModel.columns columnId = escapeId(column) length = columnId.length spaceLen = 21 - length if spaceLen <= 0 spaceLen = 1 length++ else length = 21 colsql = [columnId, ' '.repeat(spaceLen)] args.column = column type = columnCompiler.getTypeString(spec) colsql.push type if not type console.log spec length += type.length spaceLen = 42 - length if spaceLen <= 0 spaceLen = 1 colsql.push ' '.repeat(spaceLen) colsql.push columnCompiler.getColumnModifier(spec) tablespec.push indent + colsql.join(' ') # primary key if (pk = tableModel.constraints['PRIMARY KEY']) and not _.isEmpty(pk) count = 0 for pkName, columns of pk if ++count is 2 err = new Error "#{tableName} has more than one primary key" err.code = 'MULTIPLE_PK' throw err tablespec.push indent + words.constraint + ' ' + columnCompiler.pkString(pkName, columns) # unique indexes if (uk = tableModel.constraints.UNIQUE) and not _.isEmpty(uk) for ukName, columns of uk tablespec.push indent + words.constraint + ' ' + columnCompiler.ukString(ukName, columns) tablesql.push tablespec.join(',' + LF) tablesql.push LF tablesql.push ')' # indexes if tableModel.indexes and not _.isEmpty(tableModel.indexes) tablesql.push delimiter tablesql.push LF count = 0 for indexName, columns of tableModel.indexes if count is 0 count = 1 else tablesql.push delimiter tablesql.push LF tablesql.push LF spaceLen = ' '.repeat(66 - 10 - indexName.length - 2) tablesql.push """ /*==============================================================*/ /* Index: #{indexName}#{spaceLen}*/ /*==============================================================*/ """ tablesql.push.apply tablesql, [LF, words.create_index, ' ', columnCompiler.indexString(indexName, columns, tableNameId)] # foreign keys altersql = [] if (fk = tableModel.constraints['FOREIGN KEY']) and not _.isEmpty(fk) for fkName, constraint of fk { column referenced_table referenced_column delete_rule update_rule } = constraint altersql.push.apply altersql, [ LF, words.alter_table, ' ', escapeId(tableName) LF, indent, words.add_constraint, ' ', escapeId(fkName), ' ', words.foreign_key, ' (', escapeId(column), ')' LF, indent, indent, words.references, ' ', escapeId(referenced_table), ' (', escapeId(referenced_column) + ')' ] delete_rule = if delete_rule then delete_rule.toLowerCase() else 'restrict' update_rule = if update_rule then update_rule.toLowerCase() else 'restrict' if delete_rule not in this.validUpdateActions err = new Error "unknown delete rule #{delete_rule}" err.code = 'UPDATE RULE' throw err if update_rule not in this.validUpdateActions err = new Error "unknown update rule #{update_rule}" err.code = 'UPDATE RULE' throw err altersql.push.apply altersql, [LF, indent, indent, words.on_delete, ' ', words[delete_rule], ' ', words.on_update, ' ', words[update_rule], delimiter, LF] {create: tablesql.join(''), alter: altersql.slice(1).join('')} # http://www.postgresql.org/docs/9.4/static/sql-droptable.html # https://dev.mysql.com/doc/refman/5.7/en/drop-table.html # DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] SchemaCompiler::dropTable = (tableName, options)-> options = _.defaults {}, options, this.options {words, escapeId} = @ tablesql = [words.drop_table] if options.if_exists tablesql.push words.if_exists tablesql.push escapeId(tableName) if options.cascade tablesql.push words.cascade else if options.restrict tablesql.push words.restrict tablesql.join(' ') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ COLUMN ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] # # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [COLUMN] (col_name column_definition,...) SchemaCompiler::addColumn = (tableName, column, spec, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, args, indent, LF} = @ args.table = tableName args.column = column columnId = escapeId(column) altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [ escapeId(tableName), LF, indent, words.add_column, ' ', escapeId(column), ' ', columnCompiler.getTypeString(spec), ' ', columnCompiler.getColumnModifier(spec) ] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] PRIMARY KEY ( column_name [, ... ] ) index_parameters [ NOT VALID ] # # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... SchemaCompiler::addPrimaryKey = (tableName, newPkName, newColumns, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [escapeId(tableName), LF, indent, words.add_constraint, ' ', columnCompiler.pkString(newPkName, newColumns)] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] FOREIGN KEY ( column_name [, ... ] ) # REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ NOT VALID ] # [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] # action: # [NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT] # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) # REFERENCES tbl_name (index_col_name,...) # [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option] # action: # [RESTRICT | CASCADE | SET NULL | NO ACTION] SchemaCompiler::addForeignKey = (tableModel, key, options)-> options = _.defaults {}, options, this.options {words, escapeId, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' { name: fkName, column, referenced_table, referenced_column, delete_rule, update_rule } = key altersql.push.apply altersql, [ escapeId(tableModel.name), LF, indent, words.add_constraint, ' ', escapeId(fkName), ' ', words.foreign_key, ' (', escapeId(column), ')' LF, indent, indent, words.references, ' ', escapeId(referenced_table), ' (', escapeId(referenced_column) + ')' ] delete_rule = if delete_rule then delete_rule.toLowerCase() else 'restrict' update_rule = if update_rule then update_rule.toLowerCase() else 'restrict' if delete_rule not in this.validUpdateActions err = new Error "unknown delete rule #{delete_rule}" err.code = 'UPDATE RULE' throw err if update_rule not in this.validUpdateActions err = new Error "unknown update rule #{update_rule}" err.code = 'UPDATE RULE' throw err altersql.push.apply altersql, [LF, indent, indent, words.on_delete, ' ', words[delete_rule], ' ', words.on_update, ' ', words[update_rule]] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] UNIQUE ( column_name [, ... ] ) index_parameters # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] SchemaCompiler::addUniqueIndex = (tableName, indexName, columns, options)-> options = _.defaults {}, options, this.options {words, escapeId, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [escapeId(tableName), LF, indent, words.add_constraint, ' ', escapeId(indexName), ' ', words.unique, ' (', columns.map(escapeId).join(', '), ')' ] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-createindex.html # CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ name ] ON table_name # ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ) # # https://dev.mysql.com/doc/refman/5.7/en/create-index.html # CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name # (index_col_name,...) [index_option] [algorithm_option | lock_option] ... SchemaCompiler::addIndex = (tableName, indexName, columns, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler} = @ [words.create_index, ' ', columnCompiler.indexString(indexName, columns, escapeId(tableName))].join('') SchemaCompiler::getDatabaseModel = (pMgr, options)-> dbmodel = {} propToColumn = (prop)-> definition.properties[prop].column for className, definition of pMgr.classes tableName = definition.table if options.lower_case_table_names is 1 tableName = tableName.toLowerCase() tableModel = dbmodel[tableName] = name: tableName columns: {} constraints: 'PRIMARY KEY': {} 'FOREIGN KEY': {} 'UNIQUE': {} indexes: {} if definition.id and definition.id.column primaryKey = 'PK_' + (definition.id.pk or tableName) tableModel.constraints['PRIMARY KEY'][primaryKey] = [definition.id.column] column = tableModel.columns[definition.id.column] = this.getSpec definition.id, pMgr if not column.type throw new Error "[#{className}] No type has been defined for id" column.nullable = false # a primary key implies unique index and not null # indexKey = tableName + '_PK' # tableModel.constraints.UNIQUE[indexKey] = [definition.id.column] if definition.id.className parentDef = pMgr._getDefinition definition.id.className # a primary key implies unique index and not null, no need for another index this.addForeignKeyConstraint 'EXT', tableModel, definition.id, parentDef, _.defaults({fkindex: false}, options) if _.isEmpty tableModel.constraints['PRIMARY KEY'] delete tableModel.constraints['PRIMARY KEY'] for mixin, index in definition.mixins if mixin.column is definition.id.column continue parentDef = pMgr._getDefinition mixin.className column = tableModel.columns[mixin.column] = this.getSpec mixin, pMgr if not column.type throw new Error "[#{className}] No type has been defined for mixin #{mixin.className}" column.nullable = false # a unique index will be added [foreignKey, indexKey] = this.addForeignKeyConstraint 'EXT', tableModel, mixin, parentDef, _.defaults({fkindex: false}, options) # enforce unique key tableModel.constraints.UNIQUE[indexKey] = [mixin.column] for prop, propDef of definition.properties column = tableModel.columns[propDef.column] = this.getSpec propDef, pMgr if not column.type throw new Error "[#{className}] No type has been defined for property #{prop}" if propDef.className parentDef = pMgr._getDefinition propDef.className this.addForeignKeyConstraint 'HAS', tableModel, propDef, parentDef, options if _.isEmpty tableModel.constraints['FOREIGN KEY'] delete tableModel.constraints['FOREIGN KEY'] {unique, names} = definition.constraints for key, properties of unique name = 'UK_' + names[key] tableModel.constraints.UNIQUE[name] = properties.map propToColumn if _.isEmpty tableModel.constraints.UNIQUE delete tableModel.constraints.UNIQUE for name, properties in definition.indexes tableModel.indexes[name] = properties.map propToColumn dbmodel SchemaCompiler::getSpec = (model, pMgr)-> spec = _.pick model, pMgr.specProperties if spec.defaultValue spec.defaultValue = this.escape spec.defaultValue spec SchemaCompiler::addForeignKeyConstraint = (name, tableModel, propDef, parentDef, options = {})-> keyName = propDef.fk or "#{tableModel.name}_#{propDef.column}_#{name}_#{parentDef.table}_#{parentDef.id.column}" foreignKey = "FK_#{keyName}" tableModel.constraints['FOREIGN KEY'][foreignKey] = column: propDef.column referenced_table: parentDef.table referenced_column: parentDef.id.column update_rule: 'RESTRICT' delete_rule: 'RESTRICT' # https://www.postgresql.org/docs/9.4/static/ddl-constraints.html # A foreign key must reference columns that either are a primary key or form a unique constraint. # This means that the referenced columns always have an index (the one underlying the primary key or unique constraint); # so checks on whether a referencing row has a match will be efficient. # Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, # it is often a good idea to index the referencing columns too. # Because this is not always needed, and there are many choices available on how to index, # declaration of a foreign key constraint does not automatically create an index on the referencing columns. # # https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html # MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. # In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. # Such an index is created on the referencing table automatically if it does not exist. # This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. # index_name, if given, is used as described previously. indexKey = "#{keyName}_FK" if ! propDef.unique and propDef.fkindex isnt false and options.fkindex isnt false tableModel.indexes[indexKey] = [propDef.column] [foreignKey, indexKey]
42511
_ = require 'lodash' module.exports = class SchemaCompiler constructor: (options = {})-> columnCompiler = this.columnCompiler = new this.ColumnCompiler options this.indent = options.indent or ' ' this.LF = options.LF or '\n' this.delimiter = options.delimiter or ';' for prop in ['adapter', 'args', 'words'] @[prop] = columnCompiler[prop] for method in ['escape', 'escapeId', 'escapeSearch', 'escapeBeginWith', 'escapeEndWith'] if 'function' is typeof this.adapter[method] @[method] = this.adapter[method].bind this.adapter this.options = _.clone options # https://dev.mysql.com/doc/refman/5.7/en/create-table.html # http://www.postgresql.org/docs/9.4/static/sql-createtable.html SchemaCompiler::createTable = (tableModel, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, args, indent, LF, delimiter} = @ tableName = tableModel.name tableNameId = escapeId tableName args.tableModel = tableName tablesql = [] spaceLen = ' '.repeat(66 - 10 - tableName.length - 2) tablesql.push """ /*==============================================================*/ /* Table: #{tableName}#{spaceLen}*/ /*==============================================================*/ """ tablesql.push.apply tablesql, [LF, words.create_table, ' '] if options.if_not_exists tablesql.push words.if_not_exists tablesql.push ' ' tablesql.push.apply tablesql, [tableNameId, ' (', LF] tablespec = [] # column definition for column, spec of tableModel.columns columnId = escapeId(column) length = columnId.length spaceLen = 21 - length if spaceLen <= 0 spaceLen = 1 length++ else length = 21 colsql = [columnId, ' '.repeat(spaceLen)] args.column = column type = columnCompiler.getTypeString(spec) colsql.push type if not type console.log spec length += type.length spaceLen = 42 - length if spaceLen <= 0 spaceLen = 1 colsql.push ' '.repeat(spaceLen) colsql.push columnCompiler.getColumnModifier(spec) tablespec.push indent + colsql.join(' ') # primary key if (pk = tableModel.constraints['PRIMARY KEY']) and not _.isEmpty(pk) count = 0 for pkName, columns of pk if ++count is 2 err = new Error "#{tableName} has more than one primary key" err.code = 'MULTIPLE_PK' throw err tablespec.push indent + words.constraint + ' ' + columnCompiler.pkString(pkName, columns) # unique indexes if (uk = tableModel.constraints.UNIQUE) and not _.isEmpty(uk) for ukName, columns of uk tablespec.push indent + words.constraint + ' ' + columnCompiler.ukString(ukName, columns) tablesql.push tablespec.join(',' + LF) tablesql.push LF tablesql.push ')' # indexes if tableModel.indexes and not _.isEmpty(tableModel.indexes) tablesql.push delimiter tablesql.push LF count = 0 for indexName, columns of tableModel.indexes if count is 0 count = 1 else tablesql.push delimiter tablesql.push LF tablesql.push LF spaceLen = ' '.repeat(66 - 10 - indexName.length - 2) tablesql.push """ /*==============================================================*/ /* Index: #{indexName}#{spaceLen}*/ /*==============================================================*/ """ tablesql.push.apply tablesql, [LF, words.create_index, ' ', columnCompiler.indexString(indexName, columns, tableNameId)] # foreign keys altersql = [] if (fk = tableModel.constraints['FOREIGN KEY']) and not _.isEmpty(fk) for fkName, constraint of fk { column referenced_table referenced_column delete_rule update_rule } = constraint altersql.push.apply altersql, [ LF, words.alter_table, ' ', escapeId(tableName) LF, indent, words.add_constraint, ' ', escapeId(fkName), ' ', words.foreign_key, ' (', escapeId(column), ')' LF, indent, indent, words.references, ' ', escapeId(referenced_table), ' (', escapeId(referenced_column) + ')' ] delete_rule = if delete_rule then delete_rule.toLowerCase() else 'restrict' update_rule = if update_rule then update_rule.toLowerCase() else 'restrict' if delete_rule not in this.validUpdateActions err = new Error "unknown delete rule #{delete_rule}" err.code = 'UPDATE RULE' throw err if update_rule not in this.validUpdateActions err = new Error "unknown update rule #{update_rule}" err.code = 'UPDATE RULE' throw err altersql.push.apply altersql, [LF, indent, indent, words.on_delete, ' ', words[delete_rule], ' ', words.on_update, ' ', words[update_rule], delimiter, LF] {create: tablesql.join(''), alter: altersql.slice(1).join('')} # http://www.postgresql.org/docs/9.4/static/sql-droptable.html # https://dev.mysql.com/doc/refman/5.7/en/drop-table.html # DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] SchemaCompiler::dropTable = (tableName, options)-> options = _.defaults {}, options, this.options {words, escapeId} = @ tablesql = [words.drop_table] if options.if_exists tablesql.push words.if_exists tablesql.push escapeId(tableName) if options.cascade tablesql.push words.cascade else if options.restrict tablesql.push words.restrict tablesql.join(' ') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ COLUMN ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] # # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [COLUMN] (col_name column_definition,...) SchemaCompiler::addColumn = (tableName, column, spec, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, args, indent, LF} = @ args.table = tableName args.column = column columnId = escapeId(column) altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [ escapeId(tableName), LF, indent, words.add_column, ' ', escapeId(column), ' ', columnCompiler.getTypeString(spec), ' ', columnCompiler.getColumnModifier(spec) ] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] PRIMARY KEY ( column_name [, ... ] ) index_parameters [ NOT VALID ] # # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... SchemaCompiler::addPrimaryKey = (tableName, newPkName, newColumns, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [escapeId(tableName), LF, indent, words.add_constraint, ' ', columnCompiler.pkString(newPkName, newColumns)] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] FOREIGN KEY ( column_name [, ... ] ) # REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ NOT VALID ] # [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] # action: # [NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT] # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) # REFERENCES tbl_name (index_col_name,...) # [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option] # action: # [RESTRICT | CASCADE | SET NULL | NO ACTION] SchemaCompiler::addForeignKey = (tableModel, key, options)-> options = _.defaults {}, options, this.options {words, escapeId, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' { name: <NAME> <NAME>, column, referenced_table, referenced_column, delete_rule, update_rule } = key altersql.push.apply altersql, [ escapeId(tableModel.name), LF, indent, words.add_constraint, ' ', escapeId(fkName), ' ', words.foreign_key, ' (', escapeId(column), ')' LF, indent, indent, words.references, ' ', escapeId(referenced_table), ' (', escapeId(referenced_column) + ')' ] delete_rule = if delete_rule then delete_rule.toLowerCase() else 'restrict' update_rule = if update_rule then update_rule.toLowerCase() else 'restrict' if delete_rule not in this.validUpdateActions err = new Error "unknown delete rule #{delete_rule}" err.code = 'UPDATE RULE' throw err if update_rule not in this.validUpdateActions err = new Error "unknown update rule #{update_rule}" err.code = 'UPDATE RULE' throw err altersql.push.apply altersql, [LF, indent, indent, words.on_delete, ' ', words[delete_rule], ' ', words.on_update, ' ', words[update_rule]] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] UNIQUE ( column_name [, ... ] ) index_parameters # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] SchemaCompiler::addUniqueIndex = (tableName, indexName, columns, options)-> options = _.defaults {}, options, this.options {words, escapeId, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [escapeId(tableName), LF, indent, words.add_constraint, ' ', escapeId(indexName), ' ', words.unique, ' (', columns.map(escapeId).join(', '), ')' ] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-createindex.html # CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ name ] ON table_name # ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ) # # https://dev.mysql.com/doc/refman/5.7/en/create-index.html # CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name # (index_col_name,...) [index_option] [algorithm_option | lock_option] ... SchemaCompiler::addIndex = (tableName, indexName, columns, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler} = @ [words.create_index, ' ', columnCompiler.indexString(indexName, columns, escapeId(tableName))].join('') SchemaCompiler::getDatabaseModel = (pMgr, options)-> dbmodel = {} propToColumn = (prop)-> definition.properties[prop].column for className, definition of pMgr.classes tableName = definition.table if options.lower_case_table_names is 1 tableName = tableName.toLowerCase() tableModel = dbmodel[tableName] = name: tableName columns: {} constraints: 'PRIMARY KEY': {} 'FOREIGN KEY': {} 'UNIQUE': {} indexes: {} if definition.id and definition.id.column primaryKey = 'PK_' + (definition.id.pk or tableName) tableModel.constraints['PRIMARY KEY'][primaryKey] = [definition.id.column] column = tableModel.columns[definition.id.column] = this.getSpec definition.id, pMgr if not column.type throw new Error "[#{className}] No type has been defined for id" column.nullable = false # a primary key implies unique index and not null # indexKey = tableName + '_PK' # tableModel.constraints.UNIQUE[indexKey] = [definition.id.column] if definition.id.className parentDef = pMgr._getDefinition definition.id.className # a primary key implies unique index and not null, no need for another index this.addForeignKeyConstraint 'EXT', tableModel, definition.id, parentDef, _.defaults({fkindex: false}, options) if _.isEmpty tableModel.constraints['PRIMARY KEY'] delete tableModel.constraints['PRIMARY KEY'] for mixin, index in definition.mixins if mixin.column is definition.id.column continue parentDef = pMgr._getDefinition mixin.className column = tableModel.columns[mixin.column] = this.getSpec mixin, pMgr if not column.type throw new Error "[#{className}] No type has been defined for mixin #{mixin.className}" column.nullable = false # a unique index will be added [foreignKey, indexKey] = this.addForeignKeyConstraint 'EXT', tableModel, mixin, parentDef, _.defaults({fkindex: false}, options) # enforce unique key tableModel.constraints.UNIQUE[indexKey] = [mixin.column] for prop, propDef of definition.properties column = tableModel.columns[propDef.column] = this.getSpec propDef, pMgr if not column.type throw new Error "[#{className}] No type has been defined for property #{prop}" if propDef.className parentDef = pMgr._getDefinition propDef.className this.addForeignKeyConstraint 'HAS', tableModel, propDef, parentDef, options if _.isEmpty tableModel.constraints['FOREIGN KEY'] delete tableModel.constraints['FOREIGN KEY'] {unique, names} = definition.constraints for key, properties of unique name = 'UK_' + names[key] tableModel.constraints.UNIQUE[name] = properties.map propToColumn if _.isEmpty tableModel.constraints.UNIQUE delete tableModel.constraints.UNIQUE for name, properties in definition.indexes tableModel.indexes[name] = properties.map propToColumn dbmodel SchemaCompiler::getSpec = (model, pMgr)-> spec = _.pick model, pMgr.specProperties if spec.defaultValue spec.defaultValue = this.escape spec.defaultValue spec SchemaCompiler::addForeignKeyConstraint = (name, tableModel, propDef, parentDef, options = {})-> keyName = propDef.fk or "#{tableModel.name}_#{propDef.column}_#{name}_#{parentDef.table}_#{parentDef.id.column}" foreignKey = "<KEY>#{keyName}" tableModel.constraints['FOREIGN KEY'][foreignKey] = column: propDef.column referenced_table: parentDef.table referenced_column: parentDef.id.column update_rule: 'RESTRICT' delete_rule: 'RESTRICT' # https://www.postgresql.org/docs/9.4/static/ddl-constraints.html # A foreign key must reference columns that either are a primary key or form a unique constraint. # This means that the referenced columns always have an index (the one underlying the primary key or unique constraint); # so checks on whether a referencing row has a match will be efficient. # Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, # it is often a good idea to index the referencing columns too. # Because this is not always needed, and there are many choices available on how to index, # declaration of a foreign key constraint does not automatically create an index on the referencing columns. # # https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html # MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. # In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. # Such an index is created on the referencing table automatically if it does not exist. # This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. # index_name, if given, is used as described previously. indexKey = <KEY>key<KEY>" if ! propDef.unique and propDef.fkindex isnt false and options.fkindex isnt false tableModel.indexes[indexKey] = [propDef.column] [foreignKey, indexKey]
true
_ = require 'lodash' module.exports = class SchemaCompiler constructor: (options = {})-> columnCompiler = this.columnCompiler = new this.ColumnCompiler options this.indent = options.indent or ' ' this.LF = options.LF or '\n' this.delimiter = options.delimiter or ';' for prop in ['adapter', 'args', 'words'] @[prop] = columnCompiler[prop] for method in ['escape', 'escapeId', 'escapeSearch', 'escapeBeginWith', 'escapeEndWith'] if 'function' is typeof this.adapter[method] @[method] = this.adapter[method].bind this.adapter this.options = _.clone options # https://dev.mysql.com/doc/refman/5.7/en/create-table.html # http://www.postgresql.org/docs/9.4/static/sql-createtable.html SchemaCompiler::createTable = (tableModel, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, args, indent, LF, delimiter} = @ tableName = tableModel.name tableNameId = escapeId tableName args.tableModel = tableName tablesql = [] spaceLen = ' '.repeat(66 - 10 - tableName.length - 2) tablesql.push """ /*==============================================================*/ /* Table: #{tableName}#{spaceLen}*/ /*==============================================================*/ """ tablesql.push.apply tablesql, [LF, words.create_table, ' '] if options.if_not_exists tablesql.push words.if_not_exists tablesql.push ' ' tablesql.push.apply tablesql, [tableNameId, ' (', LF] tablespec = [] # column definition for column, spec of tableModel.columns columnId = escapeId(column) length = columnId.length spaceLen = 21 - length if spaceLen <= 0 spaceLen = 1 length++ else length = 21 colsql = [columnId, ' '.repeat(spaceLen)] args.column = column type = columnCompiler.getTypeString(spec) colsql.push type if not type console.log spec length += type.length spaceLen = 42 - length if spaceLen <= 0 spaceLen = 1 colsql.push ' '.repeat(spaceLen) colsql.push columnCompiler.getColumnModifier(spec) tablespec.push indent + colsql.join(' ') # primary key if (pk = tableModel.constraints['PRIMARY KEY']) and not _.isEmpty(pk) count = 0 for pkName, columns of pk if ++count is 2 err = new Error "#{tableName} has more than one primary key" err.code = 'MULTIPLE_PK' throw err tablespec.push indent + words.constraint + ' ' + columnCompiler.pkString(pkName, columns) # unique indexes if (uk = tableModel.constraints.UNIQUE) and not _.isEmpty(uk) for ukName, columns of uk tablespec.push indent + words.constraint + ' ' + columnCompiler.ukString(ukName, columns) tablesql.push tablespec.join(',' + LF) tablesql.push LF tablesql.push ')' # indexes if tableModel.indexes and not _.isEmpty(tableModel.indexes) tablesql.push delimiter tablesql.push LF count = 0 for indexName, columns of tableModel.indexes if count is 0 count = 1 else tablesql.push delimiter tablesql.push LF tablesql.push LF spaceLen = ' '.repeat(66 - 10 - indexName.length - 2) tablesql.push """ /*==============================================================*/ /* Index: #{indexName}#{spaceLen}*/ /*==============================================================*/ """ tablesql.push.apply tablesql, [LF, words.create_index, ' ', columnCompiler.indexString(indexName, columns, tableNameId)] # foreign keys altersql = [] if (fk = tableModel.constraints['FOREIGN KEY']) and not _.isEmpty(fk) for fkName, constraint of fk { column referenced_table referenced_column delete_rule update_rule } = constraint altersql.push.apply altersql, [ LF, words.alter_table, ' ', escapeId(tableName) LF, indent, words.add_constraint, ' ', escapeId(fkName), ' ', words.foreign_key, ' (', escapeId(column), ')' LF, indent, indent, words.references, ' ', escapeId(referenced_table), ' (', escapeId(referenced_column) + ')' ] delete_rule = if delete_rule then delete_rule.toLowerCase() else 'restrict' update_rule = if update_rule then update_rule.toLowerCase() else 'restrict' if delete_rule not in this.validUpdateActions err = new Error "unknown delete rule #{delete_rule}" err.code = 'UPDATE RULE' throw err if update_rule not in this.validUpdateActions err = new Error "unknown update rule #{update_rule}" err.code = 'UPDATE RULE' throw err altersql.push.apply altersql, [LF, indent, indent, words.on_delete, ' ', words[delete_rule], ' ', words.on_update, ' ', words[update_rule], delimiter, LF] {create: tablesql.join(''), alter: altersql.slice(1).join('')} # http://www.postgresql.org/docs/9.4/static/sql-droptable.html # https://dev.mysql.com/doc/refman/5.7/en/drop-table.html # DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] SchemaCompiler::dropTable = (tableName, options)-> options = _.defaults {}, options, this.options {words, escapeId} = @ tablesql = [words.drop_table] if options.if_exists tablesql.push words.if_exists tablesql.push escapeId(tableName) if options.cascade tablesql.push words.cascade else if options.restrict tablesql.push words.restrict tablesql.join(' ') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ COLUMN ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] # # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [COLUMN] (col_name column_definition,...) SchemaCompiler::addColumn = (tableName, column, spec, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, args, indent, LF} = @ args.table = tableName args.column = column columnId = escapeId(column) altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [ escapeId(tableName), LF, indent, words.add_column, ' ', escapeId(column), ' ', columnCompiler.getTypeString(spec), ' ', columnCompiler.getColumnModifier(spec) ] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] PRIMARY KEY ( column_name [, ... ] ) index_parameters [ NOT VALID ] # # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... SchemaCompiler::addPrimaryKey = (tableName, newPkName, newColumns, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [escapeId(tableName), LF, indent, words.add_constraint, ' ', columnCompiler.pkString(newPkName, newColumns)] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] FOREIGN KEY ( column_name [, ... ] ) # REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ NOT VALID ] # [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] # action: # [NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT] # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) # REFERENCES tbl_name (index_col_name,...) # [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option] # action: # [RESTRICT | CASCADE | SET NULL | NO ACTION] SchemaCompiler::addForeignKey = (tableModel, key, options)-> options = _.defaults {}, options, this.options {words, escapeId, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' { name: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI, column, referenced_table, referenced_column, delete_rule, update_rule } = key altersql.push.apply altersql, [ escapeId(tableModel.name), LF, indent, words.add_constraint, ' ', escapeId(fkName), ' ', words.foreign_key, ' (', escapeId(column), ')' LF, indent, indent, words.references, ' ', escapeId(referenced_table), ' (', escapeId(referenced_column) + ')' ] delete_rule = if delete_rule then delete_rule.toLowerCase() else 'restrict' update_rule = if update_rule then update_rule.toLowerCase() else 'restrict' if delete_rule not in this.validUpdateActions err = new Error "unknown delete rule #{delete_rule}" err.code = 'UPDATE RULE' throw err if update_rule not in this.validUpdateActions err = new Error "unknown update rule #{update_rule}" err.code = 'UPDATE RULE' throw err altersql.push.apply altersql, [LF, indent, indent, words.on_delete, ' ', words[delete_rule], ' ', words.on_update, ' ', words[update_rule]] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-altertable.html # ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ] # ADD [ constraint_name ] UNIQUE ( column_name [, ... ] ) index_parameters # https://dev.mysql.com/doc/refman/5.7/en/alter-table.html # ALTER [IGNORE] TABLE tbl_name # ADD [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] SchemaCompiler::addUniqueIndex = (tableName, indexName, columns, options)-> options = _.defaults {}, options, this.options {words, escapeId, indent, LF} = @ altersql = [words.alter_table, ' '] # if options.if_exists # altersql.push words.if_exists # altersql.push ' ' altersql.push.apply altersql, [escapeId(tableName), LF, indent, words.add_constraint, ' ', escapeId(indexName), ' ', words.unique, ' (', columns.map(escapeId).join(', '), ')' ] altersql.join('') # http://www.postgresql.org/docs/9.4/static/sql-createindex.html # CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ name ] ON table_name # ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ) # # https://dev.mysql.com/doc/refman/5.7/en/create-index.html # CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name # (index_col_name,...) [index_option] [algorithm_option | lock_option] ... SchemaCompiler::addIndex = (tableName, indexName, columns, options)-> options = _.defaults {}, options, this.options {words, escapeId, columnCompiler} = @ [words.create_index, ' ', columnCompiler.indexString(indexName, columns, escapeId(tableName))].join('') SchemaCompiler::getDatabaseModel = (pMgr, options)-> dbmodel = {} propToColumn = (prop)-> definition.properties[prop].column for className, definition of pMgr.classes tableName = definition.table if options.lower_case_table_names is 1 tableName = tableName.toLowerCase() tableModel = dbmodel[tableName] = name: tableName columns: {} constraints: 'PRIMARY KEY': {} 'FOREIGN KEY': {} 'UNIQUE': {} indexes: {} if definition.id and definition.id.column primaryKey = 'PK_' + (definition.id.pk or tableName) tableModel.constraints['PRIMARY KEY'][primaryKey] = [definition.id.column] column = tableModel.columns[definition.id.column] = this.getSpec definition.id, pMgr if not column.type throw new Error "[#{className}] No type has been defined for id" column.nullable = false # a primary key implies unique index and not null # indexKey = tableName + '_PK' # tableModel.constraints.UNIQUE[indexKey] = [definition.id.column] if definition.id.className parentDef = pMgr._getDefinition definition.id.className # a primary key implies unique index and not null, no need for another index this.addForeignKeyConstraint 'EXT', tableModel, definition.id, parentDef, _.defaults({fkindex: false}, options) if _.isEmpty tableModel.constraints['PRIMARY KEY'] delete tableModel.constraints['PRIMARY KEY'] for mixin, index in definition.mixins if mixin.column is definition.id.column continue parentDef = pMgr._getDefinition mixin.className column = tableModel.columns[mixin.column] = this.getSpec mixin, pMgr if not column.type throw new Error "[#{className}] No type has been defined for mixin #{mixin.className}" column.nullable = false # a unique index will be added [foreignKey, indexKey] = this.addForeignKeyConstraint 'EXT', tableModel, mixin, parentDef, _.defaults({fkindex: false}, options) # enforce unique key tableModel.constraints.UNIQUE[indexKey] = [mixin.column] for prop, propDef of definition.properties column = tableModel.columns[propDef.column] = this.getSpec propDef, pMgr if not column.type throw new Error "[#{className}] No type has been defined for property #{prop}" if propDef.className parentDef = pMgr._getDefinition propDef.className this.addForeignKeyConstraint 'HAS', tableModel, propDef, parentDef, options if _.isEmpty tableModel.constraints['FOREIGN KEY'] delete tableModel.constraints['FOREIGN KEY'] {unique, names} = definition.constraints for key, properties of unique name = 'UK_' + names[key] tableModel.constraints.UNIQUE[name] = properties.map propToColumn if _.isEmpty tableModel.constraints.UNIQUE delete tableModel.constraints.UNIQUE for name, properties in definition.indexes tableModel.indexes[name] = properties.map propToColumn dbmodel SchemaCompiler::getSpec = (model, pMgr)-> spec = _.pick model, pMgr.specProperties if spec.defaultValue spec.defaultValue = this.escape spec.defaultValue spec SchemaCompiler::addForeignKeyConstraint = (name, tableModel, propDef, parentDef, options = {})-> keyName = propDef.fk or "#{tableModel.name}_#{propDef.column}_#{name}_#{parentDef.table}_#{parentDef.id.column}" foreignKey = "PI:KEY:<KEY>END_PI#{keyName}" tableModel.constraints['FOREIGN KEY'][foreignKey] = column: propDef.column referenced_table: parentDef.table referenced_column: parentDef.id.column update_rule: 'RESTRICT' delete_rule: 'RESTRICT' # https://www.postgresql.org/docs/9.4/static/ddl-constraints.html # A foreign key must reference columns that either are a primary key or form a unique constraint. # This means that the referenced columns always have an index (the one underlying the primary key or unique constraint); # so checks on whether a referencing row has a match will be efficient. # Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, # it is often a good idea to index the referencing columns too. # Because this is not always needed, and there are many choices available on how to index, # declaration of a foreign key constraint does not automatically create an index on the referencing columns. # # https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html # MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. # In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. # Such an index is created on the referencing table automatically if it does not exist. # This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. # index_name, if given, is used as described previously. indexKey = PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI" if ! propDef.unique and propDef.fkindex isnt false and options.fkindex isnt false tableModel.indexes[indexKey] = [propDef.column] [foreignKey, indexKey]
[ { "context": "##############################################\n#\n# Markus 1/23/2017\n#\n#####################################", "end": 75, "score": 0.9987417459487915, "start": 69, "tag": "NAME", "value": "Markus" } ]
server/methods/permissions.coffee
agottschalk10/worklearn
0
################################################################ # # Markus 1/23/2017 # ################################################################ ################################################################ Meteor.methods add_db_permission: (role, collection_name, field) -> user = Meteor.user() if !user throw new Meteor.Error('Not permitted.') if !Roles.userIsInRole(user._id, 'db_admin') throw new Meteor.Error('Not permitted.') check role, String check field, String check collection_name, String # TODO: is this necessary? # secret = Secrets.findOne() # if not collection_name in secret.collections # throw new Meteor.Error 'Collection not present: ' + collection collection = get_collection_save collection_name if not collection throw new Meteor.Error 'Collection not present: ' + collection # role = Roles.findOne {name:role} # if not role # throw new Meteor.Error 'Role not present: ' + role filter = role: role field: field collection_name: collection._name mod = $set: modify: true read: true res = Permissions.upsert filter, mod return res remove_permission: (id) -> user = Meteor.user() if !user throw new Meteor.Error 'Not permitted.' if !Roles.userIsInRole user._id, 'db_admin' throw new Meteor.Error 'Not permitted.' check id, String Permissions.remove(id)
208222
################################################################ # # <NAME> 1/23/2017 # ################################################################ ################################################################ Meteor.methods add_db_permission: (role, collection_name, field) -> user = Meteor.user() if !user throw new Meteor.Error('Not permitted.') if !Roles.userIsInRole(user._id, 'db_admin') throw new Meteor.Error('Not permitted.') check role, String check field, String check collection_name, String # TODO: is this necessary? # secret = Secrets.findOne() # if not collection_name in secret.collections # throw new Meteor.Error 'Collection not present: ' + collection collection = get_collection_save collection_name if not collection throw new Meteor.Error 'Collection not present: ' + collection # role = Roles.findOne {name:role} # if not role # throw new Meteor.Error 'Role not present: ' + role filter = role: role field: field collection_name: collection._name mod = $set: modify: true read: true res = Permissions.upsert filter, mod return res remove_permission: (id) -> user = Meteor.user() if !user throw new Meteor.Error 'Not permitted.' if !Roles.userIsInRole user._id, 'db_admin' throw new Meteor.Error 'Not permitted.' check id, String Permissions.remove(id)
true
################################################################ # # PI:NAME:<NAME>END_PI 1/23/2017 # ################################################################ ################################################################ Meteor.methods add_db_permission: (role, collection_name, field) -> user = Meteor.user() if !user throw new Meteor.Error('Not permitted.') if !Roles.userIsInRole(user._id, 'db_admin') throw new Meteor.Error('Not permitted.') check role, String check field, String check collection_name, String # TODO: is this necessary? # secret = Secrets.findOne() # if not collection_name in secret.collections # throw new Meteor.Error 'Collection not present: ' + collection collection = get_collection_save collection_name if not collection throw new Meteor.Error 'Collection not present: ' + collection # role = Roles.findOne {name:role} # if not role # throw new Meteor.Error 'Role not present: ' + role filter = role: role field: field collection_name: collection._name mod = $set: modify: true read: true res = Permissions.upsert filter, mod return res remove_permission: (id) -> user = Meteor.user() if !user throw new Meteor.Error 'Not permitted.' if !Roles.userIsInRole user._id, 'db_admin' throw new Meteor.Error 'Not permitted.' check id, String Permissions.remove(id)
[ { "context": " @\n\n set: (id, data, callback) ->\n key = @_key(id)\n data = JSON.stringify(data)\n # de", "end": 524, "score": 0.8217121958732605, "start": 519, "tag": "KEY", "value": "@_key" }, { "context": " set: (id, data, callback) ->\n key = @_key(id...
record/connectors/memcached.coffee
printercu/costa
1
# debug = require('debug') 'record:connector:memcached' module.exports = class Memcached extends require('coffee_classkit').Module @extendsWithProto().concern() @include require './redis' class @ClassMethods nextId: (callback) -> key = @_keySeq 'id' @kv.incr key, 1, (err, value) => return callback? err, value if err? || value @kv.set key, 1, 0, (err) -> return callback? err if err callback? null, 1 @ set: (id, data, callback) -> key = @_key(id) data = JSON.stringify(data) # debug "SET #{key} #{data}" @kv.set key, data, 0, callback @ getMulti: (ids, callback) -> return setImmediate(-> callback null, []) unless ids.length keys = (@_key id for id in ids) @kv.mget keys, (err, items) => return callback? err if err result = [] for key in keys item_json = items[key] if item_json try item = JSON.parse item_json item = null unless typeof item is 'object' catch err return callback? err item.__proto__ = @prototype if item else item = null result.push item callback? null, result @
15487
# debug = require('debug') 'record:connector:memcached' module.exports = class Memcached extends require('coffee_classkit').Module @extendsWithProto().concern() @include require './redis' class @ClassMethods nextId: (callback) -> key = @_keySeq 'id' @kv.incr key, 1, (err, value) => return callback? err, value if err? || value @kv.set key, 1, 0, (err) -> return callback? err if err callback? null, 1 @ set: (id, data, callback) -> key = <KEY>(<KEY>) data = JSON.stringify(data) # debug "SET #{key} #{data}" @kv.set key, data, 0, callback @ getMulti: (ids, callback) -> return setImmediate(-> callback null, []) unless ids.length keys = (@_key id for id in ids) @kv.mget keys, (err, items) => return callback? err if err result = [] for key in keys item_json = items[key] if item_json try item = JSON.parse item_json item = null unless typeof item is 'object' catch err return callback? err item.__proto__ = @prototype if item else item = null result.push item callback? null, result @
true
# debug = require('debug') 'record:connector:memcached' module.exports = class Memcached extends require('coffee_classkit').Module @extendsWithProto().concern() @include require './redis' class @ClassMethods nextId: (callback) -> key = @_keySeq 'id' @kv.incr key, 1, (err, value) => return callback? err, value if err? || value @kv.set key, 1, 0, (err) -> return callback? err if err callback? null, 1 @ set: (id, data, callback) -> key = PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI) data = JSON.stringify(data) # debug "SET #{key} #{data}" @kv.set key, data, 0, callback @ getMulti: (ids, callback) -> return setImmediate(-> callback null, []) unless ids.length keys = (@_key id for id in ids) @kv.mget keys, (err, items) => return callback? err if err result = [] for key in keys item_json = items[key] if item_json try item = JSON.parse item_json item = null unless typeof item is 'object' catch err return callback? err item.__proto__ = @prototype if item else item = null result.push item callback? null, result @
[ { "context": "card_types = [\n {\n name: 'amex'\n pattern: /^3[47]/\n valid_length: [ 15 ]\n", "end": 33, "score": 0.5452522039413452, "start": 30, "tag": "NAME", "value": "ame" }, { "context": "-9])/\n valid_length: [ 16 ]\n }\n {\n name: 'laser'\n pattern: /^(6...
templates/conekta.js-0.6.0/src/card.js.coffee
josmrhyde/Base
0
card_types = [ { name: 'amex' pattern: /^3[47]/ valid_length: [ 15 ] } { name: 'diners_club_carte_blanche' pattern: /^30[0-5]/ valid_length: [ 14 ] } { name: 'diners_club_international' pattern: /^36/ valid_length: [ 14 ] } { name: 'jcb' pattern: /^35(2[89]|[3-8][0-9])/ valid_length: [ 16 ] } { name: 'laser' pattern: /^(6304|670[69]|6771)/ valid_length: [ 16..19 ] } { name: 'visa_electron' pattern: /^(4026|417500|4508|4844|491(3|7))/ valid_length: [ 16 ] } { name: 'visa' pattern: /^4/ valid_length: [ 16 ] } { name: 'mastercard' pattern: /^5[1-5]/ valid_length: [ 16 ] } { name: 'maestro' pattern: /^(5018|5020|5038|6304|6759|676[1-3])/ valid_length: [ 12..19 ] } { name: 'discover' pattern: /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/ valid_length: [ 16 ] } ] is_valid_luhn = (number) -> sum = 0 for digit, n in number.split('').reverse() digit = +digit # the + casts the string to int if n % 2 digit *= 2 if digit < 10 then sum += digit else sum += digit - 9 else sum += digit sum % 10 == 0 is_valid_length = (number, card_type) -> number.length in card_type.valid_length accepted_cards = ['visa', 'mastercard', 'maestro', 'visa_electron', 'amex', 'laser', 'diners_club_carte_blanche', 'diners_club_international', 'discover', 'jcb'] get_card_type = (number) -> for card_type in (card for card in card_types when card.name in accepted_cards) if number.match card_type.pattern return card_type null parseMonth = (month)-> if typeof month == 'string' and month.match(/^[\d]{1,2}$/) parseInt(month) else month parseYear = (year)-> if typeof year == 'number' and year < 100 year += 2000 if typeof year == 'string' and year.match(/^([\d]{2,2}|20[\d]{2,2})$/) if year.match(/^([\d]{2,2})$/) year = '20' + year parseInt(year) else year Conekta.card = {} Conekta.card.getBrand = (number)-> if typeof number == 'string' number = number.replace /[ -]/g, '' else if typeof number == 'number' number = toString(number) brand = get_card_type number if brand and brand.name return brand.name null Conekta.card.validateCVC = (cvc)-> (typeof cvc == 'number' and cvc >=0 and cvc < 10000) or (typeof cvc == 'string' and cvc.match(/^[\d]{3,4}$/) != null) Conekta.card.validateExpMonth = (exp_month)-> month = parseMonth(exp_month) (typeof month == 'number' and month > 0 and month < 13) Conekta.card.validateExpYear = (exp_year)-> year = parseYear(exp_year) (typeof year == 'number' and year > 2013 and year < 2035) Conekta.card.validateExpirationDate = (exp_month, exp_year)-> month = parseMonth(exp_month) year = parseYear(exp_year) if (typeof month == 'number' and month > 0 and month < 13) and (typeof year == 'number' and year > 2013 and year < 2035) ((new Date(year, month, new Date(year, month,0).getDate())) > (new Date())) else false #Deprecating this method Conekta.card.validateExpiry = (exp_month, exp_year)-> Conekta.card.validateExpirationDate(exp_month, exp_year) Conekta.card.validateName = (name) -> (typeof name == 'string' and name.match(/^\s*[A-z]+\s+[A-z]+[\sA-z]*$/) != null and name.match(/visa|master\s*card|amex|american\s*express|banorte|banamex|bancomer|hsbc|scotiabank|jcb|diners\s*club|discover/i) == null) Conekta.card.validateNumber = (number) -> if typeof number == 'string' number = number.replace /[ -]/g, '' else if typeof number == 'number' number = number.toString() else number = "" card_type = get_card_type number luhn_valid = false length_valid = false if card_type? luhn_valid = is_valid_luhn number length_valid = is_valid_length number, card_type luhn_valid && length_valid
103634
card_types = [ { name: '<NAME>x' pattern: /^3[47]/ valid_length: [ 15 ] } { name: 'diners_club_carte_blanche' pattern: /^30[0-5]/ valid_length: [ 14 ] } { name: 'diners_club_international' pattern: /^36/ valid_length: [ 14 ] } { name: 'jcb' pattern: /^35(2[89]|[3-8][0-9])/ valid_length: [ 16 ] } { name: '<NAME>' pattern: /^(6304|670[69]|6771)/ valid_length: [ 16..19 ] } { name: 'visa_electron' pattern: /^(4026|417500|4508|4844|491(3|7))/ valid_length: [ 16 ] } { name: '<NAME>' pattern: /^4/ valid_length: [ 16 ] } { name: '<NAME>' pattern: /^5[1-5]/ valid_length: [ 16 ] } { name: '<NAME>' pattern: /^(5018|5020|5038|6304|6759|676[1-3])/ valid_length: [ 12..19 ] } { name: '<NAME>' pattern: /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/ valid_length: [ 16 ] } ] is_valid_luhn = (number) -> sum = 0 for digit, n in number.split('').reverse() digit = +digit # the + casts the string to int if n % 2 digit *= 2 if digit < 10 then sum += digit else sum += digit - 9 else sum += digit sum % 10 == 0 is_valid_length = (number, card_type) -> number.length in card_type.valid_length accepted_cards = ['visa', 'mastercard', 'maestro', 'visa_electron', 'amex', 'laser', 'diners_club_carte_blanche', 'diners_club_international', 'discover', 'jcb'] get_card_type = (number) -> for card_type in (card for card in card_types when card.name in accepted_cards) if number.match card_type.pattern return card_type null parseMonth = (month)-> if typeof month == 'string' and month.match(/^[\d]{1,2}$/) parseInt(month) else month parseYear = (year)-> if typeof year == 'number' and year < 100 year += 2000 if typeof year == 'string' and year.match(/^([\d]{2,2}|20[\d]{2,2})$/) if year.match(/^([\d]{2,2})$/) year = '20' + year parseInt(year) else year Conekta.card = {} Conekta.card.getBrand = (number)-> if typeof number == 'string' number = number.replace /[ -]/g, '' else if typeof number == 'number' number = toString(number) brand = get_card_type number if brand and brand.name return brand.name null Conekta.card.validateCVC = (cvc)-> (typeof cvc == 'number' and cvc >=0 and cvc < 10000) or (typeof cvc == 'string' and cvc.match(/^[\d]{3,4}$/) != null) Conekta.card.validateExpMonth = (exp_month)-> month = parseMonth(exp_month) (typeof month == 'number' and month > 0 and month < 13) Conekta.card.validateExpYear = (exp_year)-> year = parseYear(exp_year) (typeof year == 'number' and year > 2013 and year < 2035) Conekta.card.validateExpirationDate = (exp_month, exp_year)-> month = parseMonth(exp_month) year = parseYear(exp_year) if (typeof month == 'number' and month > 0 and month < 13) and (typeof year == 'number' and year > 2013 and year < 2035) ((new Date(year, month, new Date(year, month,0).getDate())) > (new Date())) else false #Deprecating this method Conekta.card.validateExpiry = (exp_month, exp_year)-> Conekta.card.validateExpirationDate(exp_month, exp_year) Conekta.card.validateName = (name) -> (typeof name == 'string' and name.match(/^\s*[A-z]+\s+[A-z]+[\sA-z]*$/) != null and name.match(/visa|master\s*card|amex|american\s*express|banorte|banamex|bancomer|hsbc|scotiabank|jcb|diners\s*club|discover/i) == null) Conekta.card.validateNumber = (number) -> if typeof number == 'string' number = number.replace /[ -]/g, '' else if typeof number == 'number' number = number.toString() else number = "" card_type = get_card_type number luhn_valid = false length_valid = false if card_type? luhn_valid = is_valid_luhn number length_valid = is_valid_length number, card_type luhn_valid && length_valid
true
card_types = [ { name: 'PI:NAME:<NAME>END_PIx' pattern: /^3[47]/ valid_length: [ 15 ] } { name: 'diners_club_carte_blanche' pattern: /^30[0-5]/ valid_length: [ 14 ] } { name: 'diners_club_international' pattern: /^36/ valid_length: [ 14 ] } { name: 'jcb' pattern: /^35(2[89]|[3-8][0-9])/ valid_length: [ 16 ] } { name: 'PI:NAME:<NAME>END_PI' pattern: /^(6304|670[69]|6771)/ valid_length: [ 16..19 ] } { name: 'visa_electron' pattern: /^(4026|417500|4508|4844|491(3|7))/ valid_length: [ 16 ] } { name: 'PI:NAME:<NAME>END_PI' pattern: /^4/ valid_length: [ 16 ] } { name: 'PI:NAME:<NAME>END_PI' pattern: /^5[1-5]/ valid_length: [ 16 ] } { name: 'PI:NAME:<NAME>END_PI' pattern: /^(5018|5020|5038|6304|6759|676[1-3])/ valid_length: [ 12..19 ] } { name: 'PI:NAME:<NAME>END_PI' pattern: /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/ valid_length: [ 16 ] } ] is_valid_luhn = (number) -> sum = 0 for digit, n in number.split('').reverse() digit = +digit # the + casts the string to int if n % 2 digit *= 2 if digit < 10 then sum += digit else sum += digit - 9 else sum += digit sum % 10 == 0 is_valid_length = (number, card_type) -> number.length in card_type.valid_length accepted_cards = ['visa', 'mastercard', 'maestro', 'visa_electron', 'amex', 'laser', 'diners_club_carte_blanche', 'diners_club_international', 'discover', 'jcb'] get_card_type = (number) -> for card_type in (card for card in card_types when card.name in accepted_cards) if number.match card_type.pattern return card_type null parseMonth = (month)-> if typeof month == 'string' and month.match(/^[\d]{1,2}$/) parseInt(month) else month parseYear = (year)-> if typeof year == 'number' and year < 100 year += 2000 if typeof year == 'string' and year.match(/^([\d]{2,2}|20[\d]{2,2})$/) if year.match(/^([\d]{2,2})$/) year = '20' + year parseInt(year) else year Conekta.card = {} Conekta.card.getBrand = (number)-> if typeof number == 'string' number = number.replace /[ -]/g, '' else if typeof number == 'number' number = toString(number) brand = get_card_type number if brand and brand.name return brand.name null Conekta.card.validateCVC = (cvc)-> (typeof cvc == 'number' and cvc >=0 and cvc < 10000) or (typeof cvc == 'string' and cvc.match(/^[\d]{3,4}$/) != null) Conekta.card.validateExpMonth = (exp_month)-> month = parseMonth(exp_month) (typeof month == 'number' and month > 0 and month < 13) Conekta.card.validateExpYear = (exp_year)-> year = parseYear(exp_year) (typeof year == 'number' and year > 2013 and year < 2035) Conekta.card.validateExpirationDate = (exp_month, exp_year)-> month = parseMonth(exp_month) year = parseYear(exp_year) if (typeof month == 'number' and month > 0 and month < 13) and (typeof year == 'number' and year > 2013 and year < 2035) ((new Date(year, month, new Date(year, month,0).getDate())) > (new Date())) else false #Deprecating this method Conekta.card.validateExpiry = (exp_month, exp_year)-> Conekta.card.validateExpirationDate(exp_month, exp_year) Conekta.card.validateName = (name) -> (typeof name == 'string' and name.match(/^\s*[A-z]+\s+[A-z]+[\sA-z]*$/) != null and name.match(/visa|master\s*card|amex|american\s*express|banorte|banamex|bancomer|hsbc|scotiabank|jcb|diners\s*club|discover/i) == null) Conekta.card.validateNumber = (number) -> if typeof number == 'string' number = number.replace /[ -]/g, '' else if typeof number == 'number' number = number.toString() else number = "" card_type = get_card_type number luhn_valid = false length_valid = false if card_type? luhn_valid = is_valid_luhn number length_valid = is_valid_length number, card_type luhn_valid && length_valid
[ { "context": "m'\n\tauth = process.env.HUBOT_CODEBASE_APIAUTH || 'jollyscience/jollyscience:3kqo5bdat3uln2bnv90mvvti1stuonjg99bn", "end": 1219, "score": 0.9229260087013245, "start": 1207, "tag": "PASSWORD", "value": "jollyscience" }, { "context": "e\", { context: \"codebase\", source...
src/codebase.coffee
jollyscience/josi-access
1
# Description: # Codebase Stuff # # Dependencies: # None # # Configuration: # None # # Commands: # hubot report codebase users - 'These are the users I know about...' # hubot report codebase activity - 'Here are the latest 20 updates.' # hubot report codebase projects - 'These are all of the projects I can find.' # hubot report codebase project <permalink> - 'Here is what I know about <permalink>' # hubot create codebase project <Full Project Name> - 'New Project created!' # hubot delete codebase project <permalink> - 'Permanently delete the project?' # hubot create codebase ticket in project <permalink> with summary <summary> - 'New ticket created! Here is the link.' # hubot report codebase open tickets in project <permalink> - 'Here are the open tickets I found...' # hubot report codebase updates to ticket <ticket_id> in project <permalink> - 'That ticket has XX updates. Here they are...' Codebase = require('node-codebase') _ = require('underscore') module.exports = (robot) -> baseUrl = process.env.HUBOT_CODEBASE_BASEURL || 'jollyscience.codebasehq.com' apiUrl = process.env.HUBOT_CODEBASE_APIURL || 'api3.codebasehq.com' auth = process.env.HUBOT_CODEBASE_APIAUTH || 'jollyscience/jollyscience:3kqo5bdat3uln2bnv90mvvti1stuonjg99bnz1p4' robot.brain.codebase = robot.brain.codebase or {} cb = new Codebase( apiUrl, auth ) # ROBOT RESPONDERS # REPORT USERS robot.respond /report codebase users/i, (msg) -> msg.send 'Okay. I\'ll go get a list of all Codebase users...' robot.brain.codebase.users = robot.brain.codebase.users or {} cb.users.all( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] ul = data.users.user for user in ul then do (user) => if _.isObject(user.company[0]) co = 'Freelance' else co = user.company.join(', ') r.push "#{user.username} | #{user.firstName} #{user.lastName} (#{co})" # set the username in the codebase.users object, and store the data robot.brain.codebase.users[user.username] = user msg.send r.join('\n') # emitting an event so we can capture the data elsewhere robot.brain.emit "alias_context_update", { context: "codebase", source: "users", key: "username", msg: msg } ) # REPORT ALL ACTIVITY robot.respond /report codebase activity/i, (msg) -> msg.send 'Okay. I\'m checking for codebase activity...' cb.activity( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" r = [] for item in data.events.event then do (item) => r.push "#{item.timestamp} - #{item.title}" msg.send r.join("\n") ) # REPORT SINGLE PROJECT robot.respond /report codebase project (.*)/i, (msg) -> msg.send 'Okay. I am searching the haystack for ' + msg.match[1] cb.projects.specific( msg.match[1], (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" p = data.project p.overview = 'No Description' if !_.isString(p.overview) msg.send "#{p.name} is an #{p.status} project in the #{p.groupId} group, and is described as #{p.overview}." msg.send "You can visit the project on Codebase here: http://#{baseUrl}/projects/#{p.permalink}" ) # REPORT ALL PROJECTS robot.respond /report codebase projects/i, (msg) -> msg.send 'Okay. I am checking for codebase projects...' cb.projects.all( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" r = ['The Codebase projects I know about are as follows:'] for item in data.projects.project then do (item) => r.push "#{item.name} (#{item.permalink})" msg.send r.join(' | ') msg.send "That is all of them. #{r.length} total." ) # CREATE PROJECT robot.respond /create codebase project (.*)/i, (msg) -> msg.send 'Alright... I am oiling my tools for work...' msg.send 'connecting to codebase...' cb.projects.create( msg.match[1], (err, data) -> msg.send 'navigating the matrix...' if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else project = data.project msg.send "Project Created!\n#{project.name} - #{project.permalink}" ) # DELETE PROJECT robot.respond /delete codebase project (.*)/i, (msg) -> msg.send 'I am not allowed do that right now. It is just too unsafe.' # cb.projects.deleteProject( msg.match[1], (err, data) -> # if (err) # e = JSON.stringify(data.data) # msg.send ('Awe man... I messed up... #{e}') # msg.send JSON.stringify(data) # ) # GET OPEN TICKETS robot.respond /report codebase open tickets in project ([a-z_0-9-]+)/i, (msg) -> # robot.respond /cb report open tix in ([a-z_0-9-]+)/i, (msg) -> p = msg.match[1] msg.send "Okay. I\'ll look up open tickets in #{p}..." cb.tickets.allQuery(p, {query: 'resolution:open', page: 1}, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] msg.send "found some..." tix = data.tickets.ticket for ticket in tix then do (ticket) => ticket.assignee = 'Unassigned' if !_.isString(ticket.assignee) r.push "##{ticket.ticketId[0]._} (#{ticket.ticketType}) | #{ticket.summary}\n[#{ticket.reporter} -> #{ticket.assignee}]\n---" m = r.join('\n') msg.send "Here are the open tickets I found: \n#{m}" ) # GET TICKET UPDATES robot.respond /report codebase updates to ticket ([0-9]+) in project ([a-z_0-9-]+)/i, (msg) -> t = msg.match[1] p = msg.match[2] msg.send "Okay. I\'ll try to find ticket #{t} in #{p}" cb.tickets.notes.all( p, t, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] l = data.ticketNotes.ticketNote.length - 1 msg.send "Ticket #{t} has been updated #{l} times." for note in data.ticketNotes.ticketNote then do (note) => r.push "#{note.updates}" msg.send r.join() ) # CREATE TICKET robot.respond /create codebase ticket in project ([a-z_0-9-]+) with summary (.*)/i, (msg) -> p = msg.match[1] s = msg.match[2] msg.send "Okay. I\'ll try to create a new ticket in #{p} with a summary of \'#{s}\'" cb.tickets.create( p, { summary: s, description: 'DUMMY Description'}, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else msg.send 'Great news! I created a new ticket.' msg.send "The ticket can be found here: http://#{baseUrl}/projects/#{p}/tickets/#{data.ticket.ticketId[0]._} with the summary: #{data.ticket.summary}" ) # MY Stuff robot.respond /show my open codebase tickets/i, (msg) -> msg.send "Sure. Which project?" msg.waitResponse (msg) -> project = msg.match[1] msg.send "Okay. I will check project #{project} for your open tickets. Now what is your user name?" msg.waitResponse (msg) -> username = msg.match[1] msg.send "Okay #{username}. I will check #{project} for your open tickets." msg.send "Just kidding." robot.respond /codebase report/i, (msg) -> user = robot.brain.userForName(msg.message.user.name) if user msg.send "Okay, #{user.name}. Would you like to hear about <activity>, or a specific <project>?" msg.waitResponse (msg) -> answer = msg.match[1] if (answer == "activity") msg.send "Okay. I will check on the activity." else if (answer == "project") msg.send "Okay. Which project?" else msg.send "Uh... you\'re confusing..." msg.message.text = "hubot image me confused penguin" robot.receive msg.message else msg.send "Woah. What is your codebase username?" msg.waitResponse (msg) -> username = msg.match[1] msg.send = "Ok, #{username}"
218053
# Description: # Codebase Stuff # # Dependencies: # None # # Configuration: # None # # Commands: # hubot report codebase users - 'These are the users I know about...' # hubot report codebase activity - 'Here are the latest 20 updates.' # hubot report codebase projects - 'These are all of the projects I can find.' # hubot report codebase project <permalink> - 'Here is what I know about <permalink>' # hubot create codebase project <Full Project Name> - 'New Project created!' # hubot delete codebase project <permalink> - 'Permanently delete the project?' # hubot create codebase ticket in project <permalink> with summary <summary> - 'New ticket created! Here is the link.' # hubot report codebase open tickets in project <permalink> - 'Here are the open tickets I found...' # hubot report codebase updates to ticket <ticket_id> in project <permalink> - 'That ticket has XX updates. Here they are...' Codebase = require('node-codebase') _ = require('underscore') module.exports = (robot) -> baseUrl = process.env.HUBOT_CODEBASE_BASEURL || 'jollyscience.codebasehq.com' apiUrl = process.env.HUBOT_CODEBASE_APIURL || 'api3.codebasehq.com' auth = process.env.HUBOT_CODEBASE_APIAUTH || '<PASSWORD>/jollyscience:3kqo5bdat3uln2bnv90mvvti1stuonjg99bnz1p4' robot.brain.codebase = robot.brain.codebase or {} cb = new Codebase( apiUrl, auth ) # ROBOT RESPONDERS # REPORT USERS robot.respond /report codebase users/i, (msg) -> msg.send 'Okay. I\'ll go get a list of all Codebase users...' robot.brain.codebase.users = robot.brain.codebase.users or {} cb.users.all( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] ul = data.users.user for user in ul then do (user) => if _.isObject(user.company[0]) co = 'Freelance' else co = user.company.join(', ') r.push "#{user.username} | #{user.firstName} #{user.lastName} (#{co})" # set the username in the codebase.users object, and store the data robot.brain.codebase.users[user.username] = user msg.send r.join('\n') # emitting an event so we can capture the data elsewhere robot.brain.emit "alias_context_update", { context: "codebase", source: "users", key: "username", msg: msg } ) # REPORT ALL ACTIVITY robot.respond /report codebase activity/i, (msg) -> msg.send 'Okay. I\'m checking for codebase activity...' cb.activity( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" r = [] for item in data.events.event then do (item) => r.push "#{item.timestamp} - #{item.title}" msg.send r.join("\n") ) # REPORT SINGLE PROJECT robot.respond /report codebase project (.*)/i, (msg) -> msg.send 'Okay. I am searching the haystack for ' + msg.match[1] cb.projects.specific( msg.match[1], (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" p = data.project p.overview = 'No Description' if !_.isString(p.overview) msg.send "#{p.name} is an #{p.status} project in the #{p.groupId} group, and is described as #{p.overview}." msg.send "You can visit the project on Codebase here: http://#{baseUrl}/projects/#{p.permalink}" ) # REPORT ALL PROJECTS robot.respond /report codebase projects/i, (msg) -> msg.send 'Okay. I am checking for codebase projects...' cb.projects.all( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" r = ['The Codebase projects I know about are as follows:'] for item in data.projects.project then do (item) => r.push "#{item.name} (#{item.permalink})" msg.send r.join(' | ') msg.send "That is all of them. #{r.length} total." ) # CREATE PROJECT robot.respond /create codebase project (.*)/i, (msg) -> msg.send 'Alright... I am oiling my tools for work...' msg.send 'connecting to codebase...' cb.projects.create( msg.match[1], (err, data) -> msg.send 'navigating the matrix...' if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else project = data.project msg.send "Project Created!\n#{project.name} - #{project.permalink}" ) # DELETE PROJECT robot.respond /delete codebase project (.*)/i, (msg) -> msg.send 'I am not allowed do that right now. It is just too unsafe.' # cb.projects.deleteProject( msg.match[1], (err, data) -> # if (err) # e = JSON.stringify(data.data) # msg.send ('Awe man... I messed up... #{e}') # msg.send JSON.stringify(data) # ) # GET OPEN TICKETS robot.respond /report codebase open tickets in project ([a-z_0-9-]+)/i, (msg) -> # robot.respond /cb report open tix in ([a-z_0-9-]+)/i, (msg) -> p = msg.match[1] msg.send "Okay. I\'ll look up open tickets in #{p}..." cb.tickets.allQuery(p, {query: 'resolution:open', page: 1}, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] msg.send "found some..." tix = data.tickets.ticket for ticket in tix then do (ticket) => ticket.assignee = 'Unassigned' if !_.isString(ticket.assignee) r.push "##{ticket.ticketId[0]._} (#{ticket.ticketType}) | #{ticket.summary}\n[#{ticket.reporter} -> #{ticket.assignee}]\n---" m = r.join('\n') msg.send "Here are the open tickets I found: \n#{m}" ) # GET TICKET UPDATES robot.respond /report codebase updates to ticket ([0-9]+) in project ([a-z_0-9-]+)/i, (msg) -> t = msg.match[1] p = msg.match[2] msg.send "Okay. I\'ll try to find ticket #{t} in #{p}" cb.tickets.notes.all( p, t, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] l = data.ticketNotes.ticketNote.length - 1 msg.send "Ticket #{t} has been updated #{l} times." for note in data.ticketNotes.ticketNote then do (note) => r.push "#{note.updates}" msg.send r.join() ) # CREATE TICKET robot.respond /create codebase ticket in project ([a-z_0-9-]+) with summary (.*)/i, (msg) -> p = msg.match[1] s = msg.match[2] msg.send "Okay. I\'ll try to create a new ticket in #{p} with a summary of \'#{s}\'" cb.tickets.create( p, { summary: s, description: 'DUMMY Description'}, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else msg.send 'Great news! I created a new ticket.' msg.send "The ticket can be found here: http://#{baseUrl}/projects/#{p}/tickets/#{data.ticket.ticketId[0]._} with the summary: #{data.ticket.summary}" ) # MY Stuff robot.respond /show my open codebase tickets/i, (msg) -> msg.send "Sure. Which project?" msg.waitResponse (msg) -> project = msg.match[1] msg.send "Okay. I will check project #{project} for your open tickets. Now what is your user name?" msg.waitResponse (msg) -> username = msg.match[1] msg.send "Okay #{username}. I will check #{project} for your open tickets." msg.send "Just kidding." robot.respond /codebase report/i, (msg) -> user = robot.brain.userForName(msg.message.user.name) if user msg.send "Okay, #{user.name}. Would you like to hear about <activity>, or a specific <project>?" msg.waitResponse (msg) -> answer = msg.match[1] if (answer == "activity") msg.send "Okay. I will check on the activity." else if (answer == "project") msg.send "Okay. Which project?" else msg.send "Uh... you\'re confusing..." msg.message.text = "hubot image me confused penguin" robot.receive msg.message else msg.send "Woah. What is your codebase username?" msg.waitResponse (msg) -> username = msg.match[1] msg.send = "Ok, #{username}"
true
# Description: # Codebase Stuff # # Dependencies: # None # # Configuration: # None # # Commands: # hubot report codebase users - 'These are the users I know about...' # hubot report codebase activity - 'Here are the latest 20 updates.' # hubot report codebase projects - 'These are all of the projects I can find.' # hubot report codebase project <permalink> - 'Here is what I know about <permalink>' # hubot create codebase project <Full Project Name> - 'New Project created!' # hubot delete codebase project <permalink> - 'Permanently delete the project?' # hubot create codebase ticket in project <permalink> with summary <summary> - 'New ticket created! Here is the link.' # hubot report codebase open tickets in project <permalink> - 'Here are the open tickets I found...' # hubot report codebase updates to ticket <ticket_id> in project <permalink> - 'That ticket has XX updates. Here they are...' Codebase = require('node-codebase') _ = require('underscore') module.exports = (robot) -> baseUrl = process.env.HUBOT_CODEBASE_BASEURL || 'jollyscience.codebasehq.com' apiUrl = process.env.HUBOT_CODEBASE_APIURL || 'api3.codebasehq.com' auth = process.env.HUBOT_CODEBASE_APIAUTH || 'PI:PASSWORD:<PASSWORD>END_PI/jollyscience:3kqo5bdat3uln2bnv90mvvti1stuonjg99bnz1p4' robot.brain.codebase = robot.brain.codebase or {} cb = new Codebase( apiUrl, auth ) # ROBOT RESPONDERS # REPORT USERS robot.respond /report codebase users/i, (msg) -> msg.send 'Okay. I\'ll go get a list of all Codebase users...' robot.brain.codebase.users = robot.brain.codebase.users or {} cb.users.all( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] ul = data.users.user for user in ul then do (user) => if _.isObject(user.company[0]) co = 'Freelance' else co = user.company.join(', ') r.push "#{user.username} | #{user.firstName} #{user.lastName} (#{co})" # set the username in the codebase.users object, and store the data robot.brain.codebase.users[user.username] = user msg.send r.join('\n') # emitting an event so we can capture the data elsewhere robot.brain.emit "alias_context_update", { context: "codebase", source: "users", key: "username", msg: msg } ) # REPORT ALL ACTIVITY robot.respond /report codebase activity/i, (msg) -> msg.send 'Okay. I\'m checking for codebase activity...' cb.activity( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" r = [] for item in data.events.event then do (item) => r.push "#{item.timestamp} - #{item.title}" msg.send r.join("\n") ) # REPORT SINGLE PROJECT robot.respond /report codebase project (.*)/i, (msg) -> msg.send 'Okay. I am searching the haystack for ' + msg.match[1] cb.projects.specific( msg.match[1], (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" p = data.project p.overview = 'No Description' if !_.isString(p.overview) msg.send "#{p.name} is an #{p.status} project in the #{p.groupId} group, and is described as #{p.overview}." msg.send "You can visit the project on Codebase here: http://#{baseUrl}/projects/#{p.permalink}" ) # REPORT ALL PROJECTS robot.respond /report codebase projects/i, (msg) -> msg.send 'Okay. I am checking for codebase projects...' cb.projects.all( (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" r = ['The Codebase projects I know about are as follows:'] for item in data.projects.project then do (item) => r.push "#{item.name} (#{item.permalink})" msg.send r.join(' | ') msg.send "That is all of them. #{r.length} total." ) # CREATE PROJECT robot.respond /create codebase project (.*)/i, (msg) -> msg.send 'Alright... I am oiling my tools for work...' msg.send 'connecting to codebase...' cb.projects.create( msg.match[1], (err, data) -> msg.send 'navigating the matrix...' if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else project = data.project msg.send "Project Created!\n#{project.name} - #{project.permalink}" ) # DELETE PROJECT robot.respond /delete codebase project (.*)/i, (msg) -> msg.send 'I am not allowed do that right now. It is just too unsafe.' # cb.projects.deleteProject( msg.match[1], (err, data) -> # if (err) # e = JSON.stringify(data.data) # msg.send ('Awe man... I messed up... #{e}') # msg.send JSON.stringify(data) # ) # GET OPEN TICKETS robot.respond /report codebase open tickets in project ([a-z_0-9-]+)/i, (msg) -> # robot.respond /cb report open tix in ([a-z_0-9-]+)/i, (msg) -> p = msg.match[1] msg.send "Okay. I\'ll look up open tickets in #{p}..." cb.tickets.allQuery(p, {query: 'resolution:open', page: 1}, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] msg.send "found some..." tix = data.tickets.ticket for ticket in tix then do (ticket) => ticket.assignee = 'Unassigned' if !_.isString(ticket.assignee) r.push "##{ticket.ticketId[0]._} (#{ticket.ticketType}) | #{ticket.summary}\n[#{ticket.reporter} -> #{ticket.assignee}]\n---" m = r.join('\n') msg.send "Here are the open tickets I found: \n#{m}" ) # GET TICKET UPDATES robot.respond /report codebase updates to ticket ([0-9]+) in project ([a-z_0-9-]+)/i, (msg) -> t = msg.match[1] p = msg.match[2] msg.send "Okay. I\'ll try to find ticket #{t} in #{p}" cb.tickets.notes.all( p, t, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else r = [] l = data.ticketNotes.ticketNote.length - 1 msg.send "Ticket #{t} has been updated #{l} times." for note in data.ticketNotes.ticketNote then do (note) => r.push "#{note.updates}" msg.send r.join() ) # CREATE TICKET robot.respond /create codebase ticket in project ([a-z_0-9-]+) with summary (.*)/i, (msg) -> p = msg.match[1] s = msg.match[2] msg.send "Okay. I\'ll try to create a new ticket in #{p} with a summary of \'#{s}\'" cb.tickets.create( p, { summary: s, description: 'DUMMY Description'}, (err, data) -> if (err) errmsg = JSON.stringify(data) msg.send "Oh no! #{errmsg}" else msg.send 'Great news! I created a new ticket.' msg.send "The ticket can be found here: http://#{baseUrl}/projects/#{p}/tickets/#{data.ticket.ticketId[0]._} with the summary: #{data.ticket.summary}" ) # MY Stuff robot.respond /show my open codebase tickets/i, (msg) -> msg.send "Sure. Which project?" msg.waitResponse (msg) -> project = msg.match[1] msg.send "Okay. I will check project #{project} for your open tickets. Now what is your user name?" msg.waitResponse (msg) -> username = msg.match[1] msg.send "Okay #{username}. I will check #{project} for your open tickets." msg.send "Just kidding." robot.respond /codebase report/i, (msg) -> user = robot.brain.userForName(msg.message.user.name) if user msg.send "Okay, #{user.name}. Would you like to hear about <activity>, or a specific <project>?" msg.waitResponse (msg) -> answer = msg.match[1] if (answer == "activity") msg.send "Okay. I will check on the activity." else if (answer == "project") msg.send "Okay. Which project?" else msg.send "Uh... you\'re confusing..." msg.message.text = "hubot image me confused penguin" robot.receive msg.message else msg.send "Woah. What is your codebase username?" msg.waitResponse (msg) -> username = msg.match[1] msg.send = "Ok, #{username}"
[ { "context": " attribute = new RogueGirl.Attribute('user', 'Peter')\n\n expect(attribute.name).to.eql('user')\n ", "end": 183, "score": 0.993537187576294, "start": 178, "tag": "NAME", "value": "Peter" }, { "context": "l('user')\n expect(attribute.value()).to.eql('Peter...
spec/rogue_girl/attribute_spec.coffee
smolnar/rogue-girl
0
#= require spec_helper describe 'RogueGirl.Attribute', -> describe '#build', -> it 'builds an attribute with value', -> attribute = new RogueGirl.Attribute('user', 'Peter') expect(attribute.name).to.eql('user') expect(attribute.value()).to.eql('Peter') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: 'Peter') it 'builds an attribute with function', -> n = 0 attribute = new RogueGirl.Attribute('user', -> "Peter ##{n += 1}") expect(attribute.name).to.eql('user') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: 'Peter #1') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: 'Peter #2')
188552
#= require spec_helper describe 'RogueGirl.Attribute', -> describe '#build', -> it 'builds an attribute with value', -> attribute = new RogueGirl.Attribute('user', '<NAME>') expect(attribute.name).to.eql('user') expect(attribute.value()).to.eql('<NAME>') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: '<NAME>') it 'builds an attribute with function', -> n = 0 attribute = new RogueGirl.Attribute('user', -> "<NAME> ##{n += 1}") expect(attribute.name).to.eql('user') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: '<NAME> #1') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: '<NAME> #2')
true
#= require spec_helper describe 'RogueGirl.Attribute', -> describe '#build', -> it 'builds an attribute with value', -> attribute = new RogueGirl.Attribute('user', 'PI:NAME:<NAME>END_PI') expect(attribute.name).to.eql('user') expect(attribute.value()).to.eql('PI:NAME:<NAME>END_PI') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: 'PI:NAME:<NAME>END_PI') it 'builds an attribute with function', -> n = 0 attribute = new RogueGirl.Attribute('user', -> "PI:NAME:<NAME>END_PI ##{n += 1}") expect(attribute.name).to.eql('user') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: 'PI:NAME:<NAME>END_PI #1') attributes = {} attribute.build(attributes) expect(attributes).to.eql(user: 'PI:NAME:<NAME>END_PI #2')
[ { "context": "ew for OLD source objects, i.e,. texts such\n # as Uhlenbeck (1917). The only modification of the base class i", "end": 253, "score": 0.994125485420227, "start": 244, "tag": "NAME", "value": "Uhlenbeck" }, { "context": " # options by author (in citation form, e.g., ...
app/scripts/views/source-select-field.coffee
OpenSourceFieldlinguistics/dative
7
define [ './select-field' './../utils/bibtex' ], (SelectFieldView, BibTeXUtils) -> # Source Select(menu) Field View # ------------------------------ # # A specialized SelectFieldView for OLD source objects, i.e,. texts such # as Uhlenbeck (1917). The only modification of the base class is that a # `selectTextGetter` is supplied, i.e., a function that takes a person # object and returns a string to go between <option> and </option>. class SourceSelectFieldView extends SelectFieldView initialize: (options) -> options.selectTextGetter = (option) -> "#{option.citationFormAuthor} (#{option.citationFormYear})" super options # Return the options for this source select field. Here we sort the source # options by author (in citation form, e.g., "Chomsky and Halle (1968)") # and we give them two new attributes for the convenience of # `@selectTextGetter`. getSelectOptions: -> r = @options[@optionsAttribute] or [] sortedOptions = [] for option in r citationFormAuthor = BibTeXUtils.getAuthor option option.citationFormAuthor = citationFormAuthor option.citationFormYear = BibTeXUtils.getYear option sortedOptions.push [citationFormAuthor.toLowerCase(), option] sortedOptions.sort() (o[1] for o in sortedOptions) getValueFromDOM: -> @getValueFromRelationalIdFromDOM super
205288
define [ './select-field' './../utils/bibtex' ], (SelectFieldView, BibTeXUtils) -> # Source Select(menu) Field View # ------------------------------ # # A specialized SelectFieldView for OLD source objects, i.e,. texts such # as <NAME> (1917). The only modification of the base class is that a # `selectTextGetter` is supplied, i.e., a function that takes a person # object and returns a string to go between <option> and </option>. class SourceSelectFieldView extends SelectFieldView initialize: (options) -> options.selectTextGetter = (option) -> "#{option.citationFormAuthor} (#{option.citationFormYear})" super options # Return the options for this source select field. Here we sort the source # options by author (in citation form, e.g., "<NAME> (1968)") # and we give them two new attributes for the convenience of # `@selectTextGetter`. getSelectOptions: -> r = @options[@optionsAttribute] or [] sortedOptions = [] for option in r citationFormAuthor = BibTeXUtils.getAuthor option option.citationFormAuthor = citationFormAuthor option.citationFormYear = BibTeXUtils.getYear option sortedOptions.push [citationFormAuthor.toLowerCase(), option] sortedOptions.sort() (o[1] for o in sortedOptions) getValueFromDOM: -> @getValueFromRelationalIdFromDOM super
true
define [ './select-field' './../utils/bibtex' ], (SelectFieldView, BibTeXUtils) -> # Source Select(menu) Field View # ------------------------------ # # A specialized SelectFieldView for OLD source objects, i.e,. texts such # as PI:NAME:<NAME>END_PI (1917). The only modification of the base class is that a # `selectTextGetter` is supplied, i.e., a function that takes a person # object and returns a string to go between <option> and </option>. class SourceSelectFieldView extends SelectFieldView initialize: (options) -> options.selectTextGetter = (option) -> "#{option.citationFormAuthor} (#{option.citationFormYear})" super options # Return the options for this source select field. Here we sort the source # options by author (in citation form, e.g., "PI:NAME:<NAME>END_PI (1968)") # and we give them two new attributes for the convenience of # `@selectTextGetter`. getSelectOptions: -> r = @options[@optionsAttribute] or [] sortedOptions = [] for option in r citationFormAuthor = BibTeXUtils.getAuthor option option.citationFormAuthor = citationFormAuthor option.citationFormYear = BibTeXUtils.getYear option sortedOptions.push [citationFormAuthor.toLowerCase(), option] sortedOptions.sort() (o[1] for o in sortedOptions) getValueFromDOM: -> @getValueFromRelationalIdFromDOM super
[ { "context": "inarySearchTree cmp\n tree.insert c,c for c in \"márton\"\n expect(trace).to.eql [\n \"á>m\"\n \"r>", "end": 862, "score": 0.8938320279121399, "start": 856, "tag": "NAME", "value": "márton" }, { "context": "SearchTree cmp\n tree.insert c,i for c, i ...
spec/binary-search-tree-spec.coffee
ldegen/geometry
0
describe "The Binary Search Tree", -> BinarySearchTree = require "../src/binary-search-tree" shortNode = (key)->(left=null,right=null)->[key,left,right] [m,ä,á,é,r,t,o,n] = (shortNode c for c in "mäáérton") _t = (k,v,l,r)-> key:k value:v left:l right:r trace = undefined beforeEach -> trace = [] cmp = (a,b)-> switch when a is 'á' and b is 'é' or a is 'é' and b is 'á' trace.push "#{a}!#{b}" return undefined when a<b trace.push "#{a}<#{b}" return -1 when a>b trace.push "#{a}>#{b}" return 1 else trace.push "#{a}=#{b}" return 0 it "is initially empty", -> tree = BinarySearchTree cmp expect(tree.empty()).to.be.truthy it "dynamically builds a tree", -> tree = BinarySearchTree cmp tree.insert c,c for c in "márton" expect(trace).to.eql [ "á>m" "r>m", "r<á" "t>m", "t<á", "t>r" "o>m", "o<á", "o<r" "n>m", "n<á", "n<r", "n<o" ] expect(tree.dumpKeys()).to.eql( m( null, á( r( o(n()), t() ) ) ) ) describe "get", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp tree.insert c,i for c, i in "márton" trace = [] it "returns the value for a key", -> v = tree.get 'r' expect(v).to.equal 2 expect(trace).to.eql ["r>m","r<á","r=r"] it "returns undefined if no node with that key is found", -> v = tree.get 'v' expect(v).to.be.undefined expect(trace).to.eql ["v>m", "v<á", "v>r", "v>t"] describe "in-order traversal", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp tree.insert c,i for c, i in "márton" trace = [] it "can traverse the tree inorder", -> node = tree.first() buf = "" while node?.key? buf+=node.key node = node.next() expect(buf).to.eql "mnortá" it "can traverse the tree in reverse order", -> node = tree.last() buf = "" while node?.key? buf=node.key+buf node = node.prev() expect(buf).to.eql "mnortá" describe "remove", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "márton" trace = [] it "removes leafs without otherwise changing the structure", -> tree.remove "t" expect(tree.dumpKeys()).to.eql( m( null, á( r(o(n())) ) ) ) it "inlines nodes with only a right child", -> tree.remove 'm' expect(tree.dumpKeys()).to.eql( á( r( o(n()), t() ) ) ) it "inlines nodes with only a left child", -> tree.remove 'á' expect(tree.dumpKeys()).to.eql( m( null, r( o(n()), t() ) ) ) it "replaces nodes with both children with its inorader neighbour", -> tree.remove 'r' expect(tree.dumpKeys()).to.eql( m( null, á( o( n(), t() ) ) ) ) describe "when inserting a key that conflicts with an existing key", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "márton" trace = [] it "removes the existing node and reports the conflicting keys", -> conflicts = [] tree.insert 'é',42, (a,b)->conflicts.push "#{a.key}!#{b.key}" expect(trace).to.eql [ 'é>m' 'é!á' ] expect(tree.dumpKeys()).to.eql( m(null,r(o(n()),t())) ) expect(conflicts).to.eql ["é!á"] describe "when encountering conflicts during removal", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "mäáérton" trace = [] expect(tree.dumpKeys()).to.eql( m( null, ä( á( r( o(n()), t() ) ), é() ) ) ) it "removes and reports the conflicting keys", -> conflicts = [] tree.remove 'ä', (a,b)->conflicts.push "#{a.key}!#{b.key}" expect(conflicts).to.eql ["á!é"] expect(tree.dumpKeys()).to.eql( m( null, t( r( o(n()) ) ) ) )
131180
describe "The Binary Search Tree", -> BinarySearchTree = require "../src/binary-search-tree" shortNode = (key)->(left=null,right=null)->[key,left,right] [m,ä,á,é,r,t,o,n] = (shortNode c for c in "mäáérton") _t = (k,v,l,r)-> key:k value:v left:l right:r trace = undefined beforeEach -> trace = [] cmp = (a,b)-> switch when a is 'á' and b is 'é' or a is 'é' and b is 'á' trace.push "#{a}!#{b}" return undefined when a<b trace.push "#{a}<#{b}" return -1 when a>b trace.push "#{a}>#{b}" return 1 else trace.push "#{a}=#{b}" return 0 it "is initially empty", -> tree = BinarySearchTree cmp expect(tree.empty()).to.be.truthy it "dynamically builds a tree", -> tree = BinarySearchTree cmp tree.insert c,c for c in "<NAME>" expect(trace).to.eql [ "á>m" "r>m", "r<á" "t>m", "t<á", "t>r" "o>m", "o<á", "o<r" "n>m", "n<á", "n<r", "n<o" ] expect(tree.dumpKeys()).to.eql( m( null, á( r( o(n()), t() ) ) ) ) describe "get", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp tree.insert c,i for c, i in "<NAME>árton" trace = [] it "returns the value for a key", -> v = tree.get 'r' expect(v).to.equal 2 expect(trace).to.eql ["r>m","r<á","r=r"] it "returns undefined if no node with that key is found", -> v = tree.get 'v' expect(v).to.be.undefined expect(trace).to.eql ["v>m", "v<á", "v>r", "v>t"] describe "in-order traversal", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp tree.insert c,i for c, i in "<NAME>" trace = [] it "can traverse the tree inorder", -> node = tree.first() buf = "" while node?.key? buf+=node.key node = node.next() expect(buf).to.eql "mnortá" it "can traverse the tree in reverse order", -> node = tree.last() buf = "" while node?.key? buf=node.key+buf node = node.prev() expect(buf).to.eql "mnortá" describe "remove", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "<NAME>" trace = [] it "removes leafs without otherwise changing the structure", -> tree.remove "t" expect(tree.dumpKeys()).to.eql( m( null, á( r(o(n())) ) ) ) it "inlines nodes with only a right child", -> tree.remove 'm' expect(tree.dumpKeys()).to.eql( á( r( o(n()), t() ) ) ) it "inlines nodes with only a left child", -> tree.remove 'á' expect(tree.dumpKeys()).to.eql( m( null, r( o(n()), t() ) ) ) it "replaces nodes with both children with its inorader neighbour", -> tree.remove 'r' expect(tree.dumpKeys()).to.eql( m( null, á( o( n(), t() ) ) ) ) describe "when inserting a key that conflicts with an existing key", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "<NAME>" trace = [] it "removes the existing node and reports the conflicting keys", -> conflicts = [] tree.insert 'é',42, (a,b)->conflicts.push "#{a.key}!#{b.key}" expect(trace).to.eql [ 'é>m' 'é!á' ] expect(tree.dumpKeys()).to.eql( m(null,r(o(n()),t())) ) expect(conflicts).to.eql ["é!á"] describe "when encountering conflicts during removal", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "<NAME>" trace = [] expect(tree.dumpKeys()).to.eql( m( null, ä( á( r( o(n()), t() ) ), é() ) ) ) it "removes and reports the conflicting keys", -> conflicts = [] tree.remove 'ä', (a,b)->conflicts.push "#{a.key}!#{b.key}" expect(conflicts).to.eql ["á!é"] expect(tree.dumpKeys()).to.eql( m( null, t( r( o(n()) ) ) ) )
true
describe "The Binary Search Tree", -> BinarySearchTree = require "../src/binary-search-tree" shortNode = (key)->(left=null,right=null)->[key,left,right] [m,ä,á,é,r,t,o,n] = (shortNode c for c in "mäáérton") _t = (k,v,l,r)-> key:k value:v left:l right:r trace = undefined beforeEach -> trace = [] cmp = (a,b)-> switch when a is 'á' and b is 'é' or a is 'é' and b is 'á' trace.push "#{a}!#{b}" return undefined when a<b trace.push "#{a}<#{b}" return -1 when a>b trace.push "#{a}>#{b}" return 1 else trace.push "#{a}=#{b}" return 0 it "is initially empty", -> tree = BinarySearchTree cmp expect(tree.empty()).to.be.truthy it "dynamically builds a tree", -> tree = BinarySearchTree cmp tree.insert c,c for c in "PI:NAME:<NAME>END_PI" expect(trace).to.eql [ "á>m" "r>m", "r<á" "t>m", "t<á", "t>r" "o>m", "o<á", "o<r" "n>m", "n<á", "n<r", "n<o" ] expect(tree.dumpKeys()).to.eql( m( null, á( r( o(n()), t() ) ) ) ) describe "get", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp tree.insert c,i for c, i in "PI:NAME:<NAME>END_PIárton" trace = [] it "returns the value for a key", -> v = tree.get 'r' expect(v).to.equal 2 expect(trace).to.eql ["r>m","r<á","r=r"] it "returns undefined if no node with that key is found", -> v = tree.get 'v' expect(v).to.be.undefined expect(trace).to.eql ["v>m", "v<á", "v>r", "v>t"] describe "in-order traversal", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp tree.insert c,i for c, i in "PI:NAME:<NAME>END_PI" trace = [] it "can traverse the tree inorder", -> node = tree.first() buf = "" while node?.key? buf+=node.key node = node.next() expect(buf).to.eql "mnortá" it "can traverse the tree in reverse order", -> node = tree.last() buf = "" while node?.key? buf=node.key+buf node = node.prev() expect(buf).to.eql "mnortá" describe "remove", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "PI:NAME:<NAME>END_PI" trace = [] it "removes leafs without otherwise changing the structure", -> tree.remove "t" expect(tree.dumpKeys()).to.eql( m( null, á( r(o(n())) ) ) ) it "inlines nodes with only a right child", -> tree.remove 'm' expect(tree.dumpKeys()).to.eql( á( r( o(n()), t() ) ) ) it "inlines nodes with only a left child", -> tree.remove 'á' expect(tree.dumpKeys()).to.eql( m( null, r( o(n()), t() ) ) ) it "replaces nodes with both children with its inorader neighbour", -> tree.remove 'r' expect(tree.dumpKeys()).to.eql( m( null, á( o( n(), t() ) ) ) ) describe "when inserting a key that conflicts with an existing key", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "PI:NAME:<NAME>END_PI" trace = [] it "removes the existing node and reports the conflicting keys", -> conflicts = [] tree.insert 'é',42, (a,b)->conflicts.push "#{a.key}!#{b.key}" expect(trace).to.eql [ 'é>m' 'é!á' ] expect(tree.dumpKeys()).to.eql( m(null,r(o(n()),t())) ) expect(conflicts).to.eql ["é!á"] describe "when encountering conflicts during removal", -> tree = undefined beforeEach -> tree = BinarySearchTree cmp, -> 0.1 tree.insert c,i for c, i in "PI:NAME:<NAME>END_PI" trace = [] expect(tree.dumpKeys()).to.eql( m( null, ä( á( r( o(n()), t() ) ), é() ) ) ) it "removes and reports the conflicting keys", -> conflicts = [] tree.remove 'ä', (a,b)->conflicts.push "#{a.key}!#{b.key}" expect(conflicts).to.eql ["á!é"] expect(tree.dumpKeys()).to.eql( m( null, t( r( o(n()) ) ) ) )
[ { "context": "els/LevelSession'\n\ntestPost =\n data:\n email: 'scott@codecombat.com'\n id: '12345678'\n merges:\n INTERESTS: ", "end": 331, "score": 0.9999215602874756, "start": 311, "tag": "EMAIL", "value": "scott@codecombat.com" }, { "context": ", Diplomats, Ambassa...
spec/server/functional/mail.spec.coffee
kbespalyi/codecombat
1
require '../common' utils = require '../utils' mail = require '../../../server/routes/mail' sendwithus = require '../../../server/sendwithus' User = require '../../../server/models/User' request = require '../request' LevelSession = require '../../../server/models/LevelSession' testPost = data: email: 'scott@codecombat.com' id: '12345678' merges: INTERESTS: 'Announcements, Adventurers, Archmages, Scribes, Diplomats, Ambassadors, Artisans' FNAME: 'Scott' LNAME: 'Erickson' describe 'handleProfileUpdate', -> it 'updates emails from the data passed in', (done) -> u = new User() mail.handleProfileUpdate(u, testPost) expect(u.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeTruthy() done() describe 'handleUnsubscribe', -> it 'turns off all news and notifications', (done) -> u = new User({generalNews: {enabled: true}, archmageNews: {enabled: true}, anyNotes: {enabled: true}}) mail.handleUnsubscribe(u) expect(u.isEmailSubscriptionEnabled('generalNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeFalsy() done() # This can be re-enabled on demand to test it, but for some async reason this # crashes jasmine soon afterward. describe 'sendNextStepsEmail', -> xit 'Sends the email', utils.wrap (done) -> user = yield utils.initUser({generalNews: {enabled: true}, anyNotes: {enabled: true}}) expect(user.id).toBeDefined() yield new LevelSession({ creator: user.id permissions: simplePermissions level: original: 'dungeon-arena' state: complete: true }).save() yield new LevelSession({ creator: user.id permissions: simplePermissions level: original: 'dungeon-arena-2' state: complete: true }).save() spyOn(sendwithus.api, 'send').and.callFake (options, cb) -> expect(options.recipient.address).toBe(user.get('email')) cb() done() mail.sendNextStepsEmail(user, new Date, 5) .pend('Breaks other tests — must be run alone')
60530
require '../common' utils = require '../utils' mail = require '../../../server/routes/mail' sendwithus = require '../../../server/sendwithus' User = require '../../../server/models/User' request = require '../request' LevelSession = require '../../../server/models/LevelSession' testPost = data: email: '<EMAIL>' id: '12345678' merges: INTERESTS: 'Announcements, Adventurers, Archmages, Scribes, Diplomats, Ambassadors, Artisans' FNAME: '<NAME>' LNAME: '<NAME>' describe 'handleProfileUpdate', -> it 'updates emails from the data passed in', (done) -> u = new User() mail.handleProfileUpdate(u, testPost) expect(u.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeTruthy() done() describe 'handleUnsubscribe', -> it 'turns off all news and notifications', (done) -> u = new User({generalNews: {enabled: true}, archmageNews: {enabled: true}, anyNotes: {enabled: true}}) mail.handleUnsubscribe(u) expect(u.isEmailSubscriptionEnabled('generalNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeFalsy() done() # This can be re-enabled on demand to test it, but for some async reason this # crashes jasmine soon afterward. describe 'sendNextStepsEmail', -> xit 'Sends the email', utils.wrap (done) -> user = yield utils.initUser({generalNews: {enabled: true}, anyNotes: {enabled: true}}) expect(user.id).toBeDefined() yield new LevelSession({ creator: user.id permissions: simplePermissions level: original: 'dungeon-arena' state: complete: true }).save() yield new LevelSession({ creator: user.id permissions: simplePermissions level: original: 'dungeon-arena-2' state: complete: true }).save() spyOn(sendwithus.api, 'send').and.callFake (options, cb) -> expect(options.recipient.address).toBe(user.get('email')) cb() done() mail.sendNextStepsEmail(user, new Date, 5) .pend('Breaks other tests — must be run alone')
true
require '../common' utils = require '../utils' mail = require '../../../server/routes/mail' sendwithus = require '../../../server/sendwithus' User = require '../../../server/models/User' request = require '../request' LevelSession = require '../../../server/models/LevelSession' testPost = data: email: 'PI:EMAIL:<EMAIL>END_PI' id: '12345678' merges: INTERESTS: 'Announcements, Adventurers, Archmages, Scribes, Diplomats, Ambassadors, Artisans' FNAME: 'PI:NAME:<NAME>END_PI' LNAME: 'PI:NAME:<NAME>END_PI' describe 'handleProfileUpdate', -> it 'updates emails from the data passed in', (done) -> u = new User() mail.handleProfileUpdate(u, testPost) expect(u.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeTruthy() expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeTruthy() done() describe 'handleUnsubscribe', -> it 'turns off all news and notifications', (done) -> u = new User({generalNews: {enabled: true}, archmageNews: {enabled: true}, anyNotes: {enabled: true}}) mail.handleUnsubscribe(u) expect(u.isEmailSubscriptionEnabled('generalNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeFalsy() expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeFalsy() done() # This can be re-enabled on demand to test it, but for some async reason this # crashes jasmine soon afterward. describe 'sendNextStepsEmail', -> xit 'Sends the email', utils.wrap (done) -> user = yield utils.initUser({generalNews: {enabled: true}, anyNotes: {enabled: true}}) expect(user.id).toBeDefined() yield new LevelSession({ creator: user.id permissions: simplePermissions level: original: 'dungeon-arena' state: complete: true }).save() yield new LevelSession({ creator: user.id permissions: simplePermissions level: original: 'dungeon-arena-2' state: complete: true }).save() spyOn(sendwithus.api, 'send').and.callFake (options, cb) -> expect(options.recipient.address).toBe(user.get('email')) cb() done() mail.sendNextStepsEmail(user, new Date, 5) .pend('Breaks other tests — must be run alone')
[ { "context": "(user) ->\n return '' unless user?\n u =\n name: user.name\n email: user.email\n token: user.token\n", "end": 72, "score": 0.5428692102432251, "start": 68, "tag": "NAME", "value": "user" }, { "context": ") ->\n return '' unless user?\n u =\n name: user.n...
server/http/auth/createAuthScript.coffee
stevelacy/portal
0
module.exports = (user) -> return '' unless user? u = name: user.name email: user.email token: user.token image: user.image online: user.online return u
149107
module.exports = (user) -> return '' unless user? u = name: <NAME>.name email: user.email token: user.token image: user.image online: user.online return u
true
module.exports = (user) -> return '' unless user? u = name: PI:NAME:<NAME>END_PI.name email: user.email token: user.token image: user.image online: user.online return u
[ { "context": "lInNewTab\", url}\n\n copyCurrentUrl: ->\n # TODO(ilya): When the following bug is fixed, revisit this a", "end": 14963, "score": 0.8946846127510071, "start": 14959, "tag": "NAME", "value": "ilya" } ]
content_scripts/vimium_frontend.coffee
iscriptology/edge-vimium
21
# # This content script must be run prior to domReady so that we perform some operations very early. # chrome = browser isEnabledForUrl = true isIncognitoMode = false try if not window.indexedDB isIncognitoMode = true catch error isIncognitoMode = true normalMode = null # We track whther the current window has the focus or not. windowIsFocused = do -> windowHasFocus = null DomUtils.documentReady -> windowHasFocus = document.hasFocus() window.addEventListener "focus", (event) -> windowHasFocus = true if event.target == window; true window.addEventListener "blur", (event) -> windowHasFocus = false if event.target == window; true -> windowHasFocus # The types in <input type="..."> that we consider for focusInput command. Right now this is recalculated in # each content script. Alternatively we could calculate it once in the background page and use a request to # fetch it each time. # Should we include the HTML5 date pickers here? # The corresponding XPath for such elements. textInputXPath = (-> textInputTypes = [ "text", "search", "email", "url", "number", "password", "date", "tel" ] inputElements = ["input[" + "(" + textInputTypes.map((type) -> '@type="' + type + '"').join(" or ") + "or not(@type))" + " and not(@disabled or @readonly)]", "textarea", "*[@contenteditable='' or translate(@contenteditable, 'TRUE', 'true')='true']"] DomUtils.makeXPath(inputElements) )() # This is set by Frame.registerFrameId(). A frameId of 0 indicates that this is the top frame in the tab. frameId = null # For debugging only. This logs to the console on the background page. bgLog = (args...) -> args = (arg.toString() for arg in args) chrome.runtime.sendMessage handler: "log", message: args.join " " # If an input grabs the focus before the user has interacted with the page, then grab it back (if the # grabBackFocus option is set). class GrabBackFocus extends Mode constructor: -> super name: "grab-back-focus" keydown: => @alwaysContinueBubbling => @exit() @push _name: "grab-back-focus-mousedown" mousedown: => @alwaysContinueBubbling => @exit() Settings.use "grabBackFocus", (grabBackFocus) => # It is possible that this mode exits (e.g. due to a key event) before the settings are ready -- in # which case we should not install this grab-back-focus watcher. if @modeIsActive if grabBackFocus @push _name: "grab-back-focus-focus" focus: (event) => @grabBackFocus event.target # An input may already be focused. If so, grab back the focus. @grabBackFocus document.activeElement if document.activeElement else @exit() grabBackFocus: (element) -> return @continueBubbling unless DomUtils.isEditable element element.blur() @suppressEvent # Pages can load new content dynamically and change the displayed URL using history.pushState. Since this can # often be indistinguishable from an actual new page load for the user, we should also re-start GrabBackFocus # for these as well. This fixes issue #1622. handlerStack.push _name: "GrabBackFocus-pushState-monitor" click: (event) -> # If a focusable element is focused, the user must have clicked on it. Retain focus and bail. return true if DomUtils.isFocusable document.activeElement target = event.target while target # Often, a link which triggers a content load and url change with javascript will also have the new # url as it's href attribute. if target.tagName == "A" and target.origin == document.location.origin and # Clicking the link will change the url of this frame. (target.pathName != document.location.pathName or target.search != document.location.search) and (target.target in ["", "_self"] or (target.target == "_parent" and window.parent == window) or (target.target == "_top" and window.top == window)) return new GrabBackFocus() else target = target.parentElement true class NormalMode extends KeyHandlerMode constructor: (options = {}) -> super extend options, name: "normal" indicator: false # There is no mode indicator in normal mode. commandHandler: @commandHandler.bind this chrome.storage.local.get "normalModeKeyStateMapping", (items) => @setKeyMapping items.normalModeKeyStateMapping chrome.storage.onChanged.addListener (changes, area) => if area == "local" and changes.normalModeKeyStateMapping?.newValue @setKeyMapping changes.normalModeKeyStateMapping.newValue # Initialize components which normal mode depends upon. Scroller.init() FindModeHistory.init() commandHandler: ({command: registryEntry, count}) -> count *= registryEntry.options.count ? 1 count = 1 if registryEntry.noRepeat if registryEntry.repeatLimit? and registryEntry.repeatLimit < count return unless confirm """ You have asked Vimium to perform #{count} repetitions of the command: #{registryEntry.description}.\n Are you sure you want to continue?""" if registryEntry.topFrame # We never return to a UI-component frame (e.g. the help dialog), it might have lost the focus. sourceFrameId = if window.isVimiumUIComponent then 0 else frameId chrome.runtime.sendMessage handler: "sendMessageToFrames", message: {name: "runInTopFrame", sourceFrameId, registryEntry} else if registryEntry.background chrome.runtime.sendMessage {handler: "runBackgroundCommand", registryEntry, count} else Utils.invokeCommandString registryEntry.command, count installModes = -> # Install the permanent modes. The permanently-installed insert mode tracks focus/blur events, and # activates/deactivates itself accordingly. normalMode = new NormalMode new InsertMode permanent: true new GrabBackFocus if isEnabledForUrl normalMode # Return the normalMode object (for the tests). initializeOnEnabledStateKnown = (isEnabledForUrl) -> installModes() unless normalMode if isEnabledForUrl # We only initialize (and activate) the Vomnibar in the top frame. Also, we do not initialize the # Vomnibar until we know that Vimium is enabled. Thereafter, there's no more initialization to do. DomUtils.documentComplete Vomnibar.init.bind Vomnibar if DomUtils.isTopFrame() initializeOnEnabledStateKnown = -> # # Complete initialization work that should be done prior to DOMReady. # initializePreDomReady = -> installListeners() Frame.init() checkIfEnabledForUrl document.hasFocus() requestHandlers = focusFrame: (request) -> if (frameId == request.frameId) then focusThisFrame request getScrollPosition: (ignoredA, ignoredB, sendResponse) -> sendResponse scrollX: window.scrollX, scrollY: window.scrollY if frameId == 0 setScrollPosition: setScrollPosition frameFocused: -> # A frame has received the focus; we don't care here (UI components handle this). checkEnabledAfterURLChange: checkEnabledAfterURLChange runInTopFrame: ({sourceFrameId, registryEntry}) -> Utils.invokeCommandString registryEntry.command, sourceFrameId, registryEntry if DomUtils.isTopFrame() linkHintsMessage: (request) -> HintCoordinator[request.messageType] request chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> # These requests are intended for the background page, but they're delivered to the options page too. unless request.handler and not request.name if isEnabledForUrl or request.name in ["checkEnabledAfterURLChange", "runInTopFrame"] requestHandlers[request.name] request, sender, sendResponse false # Ensure that the sendResponse callback is freed. # Wrapper to install event listeners. Syntactic sugar. installListener = (element, event, callback) -> element.addEventListener(event, -> if isEnabledForUrl then callback.apply(this, arguments) else true , true) # # Installing or uninstalling listeners is error prone. Instead we elect to check isEnabledForUrl each time so # we know whether the listener should run or not. # Run this as early as possible, so the page can't register any event handlers before us. # Note: We install the listeners even if Vimium is disabled. See comment in commit # 6446cf04c7b44c3d419dc450a73b60bcaf5cdf02. # installListeners = Utils.makeIdempotent -> # Key event handlers fire on window before they do on document. Prefer window for key events so the page # can't set handlers to grab the keys before us. for type in ["keydown", "keypress", "keyup", "click", "focus", "blur", "mousedown", "scroll"] do (type) -> installListener window, type, (event) -> handlerStack.bubbleEvent type, event installListener document, "DOMActivate", (event) -> handlerStack.bubbleEvent 'DOMActivate', event # # Whenever we get the focus: # - Tell the background page this frame's URL. # - Check if we should be enabled. # onFocus = (event) -> if event.target == window chrome.runtime.sendMessage handler: "frameFocused" checkIfEnabledForUrl true # We install these listeners directly (that is, we don't use installListener) because we still need to receive # events when Vimium is not enabled. window.addEventListener "focus", onFocus window.addEventListener "hashchange", onFocus initializeOnDomReady = -> # Tell the background page we're in the domReady state. Frame.postMessage "domReady" Frame = port: null listeners: {} addEventListener: (handler, callback) -> @listeners[handler] = callback postMessage: (handler, request = {}) -> @port.postMessage extend request, {handler} linkHintsMessage: (request) -> HintCoordinator[request.messageType] request registerFrameId: ({chromeFrameId}) -> frameId = window.frameId = chromeFrameId # We register a frame immediately only if it is focused or its window isn't tiny. We register tiny # frames later, when necessary. This affects focusFrame() and link hints. if windowIsFocused() or not DomUtils.windowIsTooSmall() Frame.postMessage "registerFrame" else postRegisterFrame = -> window.removeEventListener "focus", focusHandler window.removeEventListener "resize", resizeHandler Frame.postMessage "registerFrame" window.addEventListener "focus", focusHandler = -> postRegisterFrame() if event.target == window window.addEventListener "resize", resizeHandler = -> postRegisterFrame() unless DomUtils.windowIsTooSmall() init: -> @port = chrome.runtime.connect name: "frames" @port.onMessage.addListener (request) => (@listeners[request.handler] ? this[request.handler]) request # We disable the content scripts when we lose contact with the background page, or on unload. @port.onDisconnect.addListener disconnect = Utils.makeIdempotent => @disconnect() window.addEventListener "unload", disconnect disconnect: -> try @postMessage "unregisterFrame" try @port.disconnect() @postMessage = @disconnect = -> @port = null @listeners = {} HintCoordinator.exit isSuccess: false handlerStack.reset() isEnabledForUrl = false window.removeEventListener "focus", onFocus window.removeEventListener "hashchange", onFocus setScrollPosition = ({ scrollX, scrollY }) -> if DomUtils.isTopFrame() DomUtils.documentReady -> window.focus() document.body.focus() if 0 < scrollX or 0 < scrollY Marks.setPreviousPosition() window.scrollTo scrollX, scrollY flashFrame = -> DomUtils.documentReady -> # Create a shadow DOM wrapping the frame so the page's styles don't interfere with ours. highlightedFrameElement = DomUtils.createElement "div" # PhantomJS doesn't support createShadowRoot, so guard against its non-existance. _shadowDOM = highlightedFrameElement.createShadowRoot?() ? highlightedFrameElement # Inject stylesheet. _styleSheet = DomUtils.createElement "style" _styleSheet.innerHTML = "@import url(\"#{chrome.runtime.getURL("content_scripts/vimium.css")}\");" _shadowDOM.appendChild _styleSheet _frameEl = DomUtils.createElement "div" _frameEl.className = "vimiumReset vimiumHighlightedFrame" _shadowDOM.appendChild _frameEl flashFrame = -> document.documentElement.appendChild highlightedFrameElement setTimeout (-> highlightedFrameElement.remove()), 200 # # Called from the backend in order to change frame focus. # focusThisFrame = (request) -> unless request.forceFocusThisFrame if DomUtils.windowIsTooSmall() or document.body?.tagName.toLowerCase() == "frameset" # This frame is too small to focus or it's a frameset. Cancel and tell the background page to focus the # next frame instead. This affects sites like Google Inbox, which have many tiny iframes. See #1317. chrome.runtime.sendMessage handler: "nextFrame" return window.focus() flashFrame() if request.highlight extend window, scrollToBottom: -> Marks.setPreviousPosition() Scroller.scrollTo "y", "max" scrollToTop: (count) -> Marks.setPreviousPosition() Scroller.scrollTo "y", (count - 1) * Settings.get("scrollStepSize") scrollToLeft: -> Scroller.scrollTo "x", 0 scrollToRight: -> Scroller.scrollTo "x", "max" scrollUp: (count) -> Scroller.scrollBy "y", -1 * Settings.get("scrollStepSize") * count scrollDown: (count) -> Scroller.scrollBy "y", Settings.get("scrollStepSize") * count scrollPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1/2 * count scrollPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1/2 * count scrollFullPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1 * count scrollFullPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1 * count scrollLeft: (count) -> Scroller.scrollBy "x", -1 * Settings.get("scrollStepSize") * count scrollRight: (count) -> Scroller.scrollBy "x", Settings.get("scrollStepSize") * count extend window, reload: -> window.location.reload() goBack: (count) -> history.go(-count) goForward: (count) -> history.go(count) goUp: (count) -> url = window.location.href if (url[url.length - 1] == "/") url = url.substring(0, url.length - 1) urlsplit = url.split("/") # make sure we haven't hit the base domain yet if (urlsplit.length > 3) urlsplit = urlsplit.slice(0, Math.max(3, urlsplit.length - count)) window.location.href = urlsplit.join('/') goToRoot: -> window.location.href = window.location.origin mainFrame: -> focusThisFrame highlight: true, forceFocusThisFrame: true toggleViewSource: -> chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) -> if (url.substr(0, 12) == "view-source:") url = url.substr(12, url.length - 12) else url = "view-source:" + url chrome.runtime.sendMessage {handler: "openUrlInNewTab", url} copyCurrentUrl: -> # TODO(ilya): When the following bug is fixed, revisit this approach of sending back to the background # page to copy. # http://code.google.com/p/chromium/issues/detail?id=55188 chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) -> chrome.runtime.sendMessage { handler: "copyToClipboard", data: url } url = url[0..25] + "...." if 28 < url.length HUD.showForDuration("Yanked #{url}", 2000) enterInsertMode: -> # If a focusable element receives the focus, then we exit and leave the permanently-installed insert-mode # instance to take over. new InsertMode global: true, exitOnFocus: true enterVisualMode: -> new VisualMode userLaunchedMode: true enterVisualLineMode: -> new VisualLineMode userLaunchedMode: true passNextKey: (count) -> new PassNextKeyMode count focusInput: do -> # Track the most recently focused input element. recentlyFocusedElement = null window.addEventListener "focus", (event) -> recentlyFocusedElement = event.target if DomUtils.isEditable event.target , true (count, mode = InsertMode) -> # Focus the first input element on the page, and create overlays to highlight all the input elements, with # the currently-focused element highlighted specially. Tabbing will shift focus to the next input element. # Pressing any other key will remove the overlays and the special tab behavior. # The mode argument is the mode to enter once an input is selected. resultSet = DomUtils.evaluateXPath textInputXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE visibleInputs = for i in [0...resultSet.snapshotLength] by 1 element = resultSet.snapshotItem i continue unless DomUtils.getVisibleClientRect element, true { element, rect: Rect.copy element.getBoundingClientRect() } if visibleInputs.length == 0 HUD.showForDuration("There are no inputs to focus.", 1000) return # This is a hack to improve usability on the Vimium options page. We prime the recently-focused input # to be the key-mappings input. Arguably, this is the input that the user is most likely to use. recentlyFocusedElement ?= document.getElementById "keyMappings" if window.isVimiumOptionsPage selectedInputIndex = if count == 1 # As the starting index, we pick that of the most recently focused input element (or 0). elements = visibleInputs.map (visibleInput) -> visibleInput.element Math.max 0, elements.indexOf recentlyFocusedElement else Math.min(count, visibleInputs.length) - 1 hints = for tuple in visibleInputs hint = DomUtils.createElement "div" hint.className = "vimiumReset internalVimiumInputHint vimiumInputHint" # minus 1 for the border hint.style.left = (tuple.rect.left - 1) + window.scrollX + "px" hint.style.top = (tuple.rect.top - 1) + window.scrollY + "px" hint.style.width = tuple.rect.width + "px" hint.style.height = tuple.rect.height + "px" hint new class FocusSelector extends Mode constructor: -> super name: "focus-selector" exitOnClick: true keydown: (event) => if event.keyCode == KeyboardUtils.keyCodes.tab hints[selectedInputIndex].classList.remove 'internalVimiumSelectedInputHint' selectedInputIndex += hints.length + (if event.shiftKey then -1 else 1) selectedInputIndex %= hints.length hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint' DomUtils.simulateSelect visibleInputs[selectedInputIndex].element @suppressEvent else unless event.keyCode == KeyboardUtils.keyCodes.shiftKey @exit() # Give the new mode the opportunity to handle the event. @restartBubbling @hintContainingDiv = DomUtils.addElementList hints, id: "vimiumInputMarkerContainer" className: "vimiumReset" DomUtils.simulateSelect visibleInputs[selectedInputIndex].element if visibleInputs.length == 1 @exit() return else hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint' exit: -> super() DomUtils.removeElement @hintContainingDiv if mode and document.activeElement and DomUtils.isEditable document.activeElement new mode singleton: "post-find-mode/focus-input" targetElement: document.activeElement indicator: false # Checks if Vimium should be enabled or not in this frame. As a side effect, it also informs the background # page whether this frame has the focus, allowing the background page to track the active frame's URL and set # the page icon. checkIfEnabledForUrl = do -> Frame.addEventListener "isEnabledForUrl", (response) -> {isEnabledForUrl, passKeys, frameIsFocused} = response initializeOnEnabledStateKnown isEnabledForUrl normalMode.setPassKeys passKeys # Hide the HUD if we're not enabled. HUD.hide true, false unless isEnabledForUrl (frameIsFocused = windowIsFocused()) -> Frame.postMessage "isEnabledForUrl", {frameIsFocused, url: window.location.toString()} # When we're informed by the background page that a URL in this tab has changed, we check if we have the # correct enabled state (but only if this frame has the focus). checkEnabledAfterURLChange = -> checkIfEnabledForUrl() if windowIsFocused() handleEscapeForFindMode = -> document.body.classList.remove("vimiumFindMode") # removing the class does not re-color existing selections. we recreate the current selection so it reverts # back to the default color. selection = window.getSelection() unless selection.isCollapsed range = window.getSelection().getRangeAt(0) window.getSelection().removeAllRanges() window.getSelection().addRange(range) focusFoundLink() || selectFoundInputElement() # <esc> sends us into insert mode if possible, but <cr> does not. # <esc> corresponds approximately to 'nevermind, I have found it already' while <cr> means 'I want to save # this query and do more searches with it' handleEnterForFindMode = -> focusFoundLink() document.body.classList.add("vimiumFindMode") FindMode.saveQuery() focusFoundLink = -> if (FindMode.query.hasResults) link = getLinkFromSelection() link.focus() if link selectFoundInputElement = -> # Since the last focused element might not be the one currently pointed to by find (e.g. the current one # might be disabled and therefore unable to receive focus), we use the approximate heuristic of checking # that the last anchor node is an ancestor of our element. findModeAnchorNode = document.getSelection().anchorNode if (FindMode.query.hasResults && document.activeElement && DomUtils.isSelectable(document.activeElement) && DomUtils.isDOMDescendant(findModeAnchorNode, document.activeElement)) DomUtils.simulateSelect(document.activeElement) findAndFocus = (backwards) -> Marks.setPreviousPosition() FindMode.query.hasResults = FindMode.execute null, {backwards} if FindMode.query.hasResults focusFoundLink() new PostFindMode() else HUD.showForDuration("No matches for '#{FindMode.query.rawQuery}'", 1000) performFind = (count) -> findAndFocus false for [0...count] by 1 performBackwardsFind = (count) -> findAndFocus true for [0...count] by 1 getLinkFromSelection = -> node = window.getSelection().anchorNode while (node && node != document.body) return node if (node.nodeName.toLowerCase() == "a") node = node.parentNode null # used by the findAndFollow* functions. followLink = (linkElement) -> if (linkElement.nodeName.toLowerCase() == "link") window.location.href = linkElement.href else # if we can click on it, don't simply set location.href: some next/prev links are meant to trigger AJAX # calls, like the 'more' button on GitHub's newsfeed. linkElement.scrollIntoView() DomUtils.simulateClick(linkElement) # # Find and follow a link which matches any one of a list of strings. If there are multiple such links, they # are prioritized for shortness, by their position in :linkStrings, how far down the page they are located, # and finally by whether the match is exact. Practically speaking, this means we favor 'next page' over 'the # next big thing', and 'more' over 'nextcompany', even if 'next' occurs before 'more' in :linkStrings. # findAndFollowLink = (linkStrings) -> linksXPath = DomUtils.makeXPath(["a", "*[@onclick or @role='link' or contains(@class, 'button')]"]) links = DomUtils.evaluateXPath(linksXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) candidateLinks = [] # at the end of this loop, candidateLinks will contain all visible links that match our patterns # links lower in the page are more likely to be the ones we want, so we loop through the snapshot backwards for i in [(links.snapshotLength - 1)..0] by -1 link = links.snapshotItem(i) # ensure link is visible (we don't mind if it is scrolled offscreen) boundingClientRect = link.getBoundingClientRect() if (boundingClientRect.width == 0 || boundingClientRect.height == 0) continue computedStyle = window.getComputedStyle(link, null) if (computedStyle.getPropertyValue("visibility") != "visible" || computedStyle.getPropertyValue("display") == "none") continue linkMatches = false for linkString in linkStrings if link.innerText.toLowerCase().indexOf(linkString) != -1 || 0 <= link.value?.indexOf? linkString linkMatches = true break continue unless linkMatches candidateLinks.push(link) return if (candidateLinks.length == 0) for link in candidateLinks link.wordCount = link.innerText.trim().split(/\s+/).length # We can use this trick to ensure that Array.sort is stable. We need this property to retain the reverse # in-page order of the links. candidateLinks.forEach((a,i) -> a.originalIndex = i) # favor shorter links, and ignore those that are more than one word longer than the shortest link candidateLinks = candidateLinks .sort((a, b) -> if (a.wordCount == b.wordCount) then a.originalIndex - b.originalIndex else a.wordCount - b.wordCount ) .filter((a) -> a.wordCount <= candidateLinks[0].wordCount + 1) for linkString in linkStrings exactWordRegex = if /\b/.test(linkString[0]) or /\b/.test(linkString[linkString.length - 1]) new RegExp "\\b" + linkString + "\\b", "i" else new RegExp linkString, "i" for candidateLink in candidateLinks if exactWordRegex.test(candidateLink.innerText) || (candidateLink.value && exactWordRegex.test(candidateLink.value)) followLink(candidateLink) return true false findAndFollowRel = (value) -> relTags = ["link", "a", "area"] for tag in relTags elements = document.getElementsByTagName(tag) for element in elements if (element.hasAttribute("rel") && element.rel.toLowerCase() == value) followLink(element) return true window.goPrevious = -> previousPatterns = Settings.get("previousPatterns") || "" previousStrings = previousPatterns.split(",").filter( (s) -> s.trim().length ) findAndFollowRel("prev") || findAndFollowLink(previousStrings) window.goNext = -> nextPatterns = Settings.get("nextPatterns") || "" nextStrings = nextPatterns.split(",").filter( (s) -> s.trim().length ) findAndFollowRel("next") || findAndFollowLink(nextStrings) # Enters find mode. Returns the new find-mode instance. enterFindMode = -> Marks.setPreviousPosition() new FindMode() window.showHelp = (sourceFrameId) -> chrome.runtime.sendMessage handler: "getHelpDialogHtml", (response) -> HelpDialog.toggle {sourceFrameId, html: response} # If we are in the help dialog iframe, then HelpDialog is already defined with the necessary functions. window.HelpDialog ?= helpUI: null isShowing: -> @helpUI?.showing abort: -> @helpUI.hide false if @isShowing() toggle: (request) -> DomUtils.documentComplete => @helpUI ?= new UIComponent "pages/help_dialog.html", "vimiumHelpDialogFrame", -> if @helpUI? and @isShowing() @helpUI.hide() else if @helpUI? @helpUI.activate extend request, name: "activate", focus: true initializePreDomReady() DomUtils.documentReady initializeOnDomReady root = exports ? window root.handlerStack = handlerStack root.frameId = frameId root.Frame = Frame root.windowIsFocused = windowIsFocused root.bgLog = bgLog # These are exported for find mode and link-hints mode. extend root, {handleEscapeForFindMode, handleEnterForFindMode, performFind, performBackwardsFind, enterFindMode, focusThisFrame} # These are exported only for the tests. extend root, {installModes, installListeners}
181227
# # This content script must be run prior to domReady so that we perform some operations very early. # chrome = browser isEnabledForUrl = true isIncognitoMode = false try if not window.indexedDB isIncognitoMode = true catch error isIncognitoMode = true normalMode = null # We track whther the current window has the focus or not. windowIsFocused = do -> windowHasFocus = null DomUtils.documentReady -> windowHasFocus = document.hasFocus() window.addEventListener "focus", (event) -> windowHasFocus = true if event.target == window; true window.addEventListener "blur", (event) -> windowHasFocus = false if event.target == window; true -> windowHasFocus # The types in <input type="..."> that we consider for focusInput command. Right now this is recalculated in # each content script. Alternatively we could calculate it once in the background page and use a request to # fetch it each time. # Should we include the HTML5 date pickers here? # The corresponding XPath for such elements. textInputXPath = (-> textInputTypes = [ "text", "search", "email", "url", "number", "password", "date", "tel" ] inputElements = ["input[" + "(" + textInputTypes.map((type) -> '@type="' + type + '"').join(" or ") + "or not(@type))" + " and not(@disabled or @readonly)]", "textarea", "*[@contenteditable='' or translate(@contenteditable, 'TRUE', 'true')='true']"] DomUtils.makeXPath(inputElements) )() # This is set by Frame.registerFrameId(). A frameId of 0 indicates that this is the top frame in the tab. frameId = null # For debugging only. This logs to the console on the background page. bgLog = (args...) -> args = (arg.toString() for arg in args) chrome.runtime.sendMessage handler: "log", message: args.join " " # If an input grabs the focus before the user has interacted with the page, then grab it back (if the # grabBackFocus option is set). class GrabBackFocus extends Mode constructor: -> super name: "grab-back-focus" keydown: => @alwaysContinueBubbling => @exit() @push _name: "grab-back-focus-mousedown" mousedown: => @alwaysContinueBubbling => @exit() Settings.use "grabBackFocus", (grabBackFocus) => # It is possible that this mode exits (e.g. due to a key event) before the settings are ready -- in # which case we should not install this grab-back-focus watcher. if @modeIsActive if grabBackFocus @push _name: "grab-back-focus-focus" focus: (event) => @grabBackFocus event.target # An input may already be focused. If so, grab back the focus. @grabBackFocus document.activeElement if document.activeElement else @exit() grabBackFocus: (element) -> return @continueBubbling unless DomUtils.isEditable element element.blur() @suppressEvent # Pages can load new content dynamically and change the displayed URL using history.pushState. Since this can # often be indistinguishable from an actual new page load for the user, we should also re-start GrabBackFocus # for these as well. This fixes issue #1622. handlerStack.push _name: "GrabBackFocus-pushState-monitor" click: (event) -> # If a focusable element is focused, the user must have clicked on it. Retain focus and bail. return true if DomUtils.isFocusable document.activeElement target = event.target while target # Often, a link which triggers a content load and url change with javascript will also have the new # url as it's href attribute. if target.tagName == "A" and target.origin == document.location.origin and # Clicking the link will change the url of this frame. (target.pathName != document.location.pathName or target.search != document.location.search) and (target.target in ["", "_self"] or (target.target == "_parent" and window.parent == window) or (target.target == "_top" and window.top == window)) return new GrabBackFocus() else target = target.parentElement true class NormalMode extends KeyHandlerMode constructor: (options = {}) -> super extend options, name: "normal" indicator: false # There is no mode indicator in normal mode. commandHandler: @commandHandler.bind this chrome.storage.local.get "normalModeKeyStateMapping", (items) => @setKeyMapping items.normalModeKeyStateMapping chrome.storage.onChanged.addListener (changes, area) => if area == "local" and changes.normalModeKeyStateMapping?.newValue @setKeyMapping changes.normalModeKeyStateMapping.newValue # Initialize components which normal mode depends upon. Scroller.init() FindModeHistory.init() commandHandler: ({command: registryEntry, count}) -> count *= registryEntry.options.count ? 1 count = 1 if registryEntry.noRepeat if registryEntry.repeatLimit? and registryEntry.repeatLimit < count return unless confirm """ You have asked Vimium to perform #{count} repetitions of the command: #{registryEntry.description}.\n Are you sure you want to continue?""" if registryEntry.topFrame # We never return to a UI-component frame (e.g. the help dialog), it might have lost the focus. sourceFrameId = if window.isVimiumUIComponent then 0 else frameId chrome.runtime.sendMessage handler: "sendMessageToFrames", message: {name: "runInTopFrame", sourceFrameId, registryEntry} else if registryEntry.background chrome.runtime.sendMessage {handler: "runBackgroundCommand", registryEntry, count} else Utils.invokeCommandString registryEntry.command, count installModes = -> # Install the permanent modes. The permanently-installed insert mode tracks focus/blur events, and # activates/deactivates itself accordingly. normalMode = new NormalMode new InsertMode permanent: true new GrabBackFocus if isEnabledForUrl normalMode # Return the normalMode object (for the tests). initializeOnEnabledStateKnown = (isEnabledForUrl) -> installModes() unless normalMode if isEnabledForUrl # We only initialize (and activate) the Vomnibar in the top frame. Also, we do not initialize the # Vomnibar until we know that Vimium is enabled. Thereafter, there's no more initialization to do. DomUtils.documentComplete Vomnibar.init.bind Vomnibar if DomUtils.isTopFrame() initializeOnEnabledStateKnown = -> # # Complete initialization work that should be done prior to DOMReady. # initializePreDomReady = -> installListeners() Frame.init() checkIfEnabledForUrl document.hasFocus() requestHandlers = focusFrame: (request) -> if (frameId == request.frameId) then focusThisFrame request getScrollPosition: (ignoredA, ignoredB, sendResponse) -> sendResponse scrollX: window.scrollX, scrollY: window.scrollY if frameId == 0 setScrollPosition: setScrollPosition frameFocused: -> # A frame has received the focus; we don't care here (UI components handle this). checkEnabledAfterURLChange: checkEnabledAfterURLChange runInTopFrame: ({sourceFrameId, registryEntry}) -> Utils.invokeCommandString registryEntry.command, sourceFrameId, registryEntry if DomUtils.isTopFrame() linkHintsMessage: (request) -> HintCoordinator[request.messageType] request chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> # These requests are intended for the background page, but they're delivered to the options page too. unless request.handler and not request.name if isEnabledForUrl or request.name in ["checkEnabledAfterURLChange", "runInTopFrame"] requestHandlers[request.name] request, sender, sendResponse false # Ensure that the sendResponse callback is freed. # Wrapper to install event listeners. Syntactic sugar. installListener = (element, event, callback) -> element.addEventListener(event, -> if isEnabledForUrl then callback.apply(this, arguments) else true , true) # # Installing or uninstalling listeners is error prone. Instead we elect to check isEnabledForUrl each time so # we know whether the listener should run or not. # Run this as early as possible, so the page can't register any event handlers before us. # Note: We install the listeners even if Vimium is disabled. See comment in commit # 6446cf04c7b44c3d419dc450a73b60bcaf5cdf02. # installListeners = Utils.makeIdempotent -> # Key event handlers fire on window before they do on document. Prefer window for key events so the page # can't set handlers to grab the keys before us. for type in ["keydown", "keypress", "keyup", "click", "focus", "blur", "mousedown", "scroll"] do (type) -> installListener window, type, (event) -> handlerStack.bubbleEvent type, event installListener document, "DOMActivate", (event) -> handlerStack.bubbleEvent 'DOMActivate', event # # Whenever we get the focus: # - Tell the background page this frame's URL. # - Check if we should be enabled. # onFocus = (event) -> if event.target == window chrome.runtime.sendMessage handler: "frameFocused" checkIfEnabledForUrl true # We install these listeners directly (that is, we don't use installListener) because we still need to receive # events when Vimium is not enabled. window.addEventListener "focus", onFocus window.addEventListener "hashchange", onFocus initializeOnDomReady = -> # Tell the background page we're in the domReady state. Frame.postMessage "domReady" Frame = port: null listeners: {} addEventListener: (handler, callback) -> @listeners[handler] = callback postMessage: (handler, request = {}) -> @port.postMessage extend request, {handler} linkHintsMessage: (request) -> HintCoordinator[request.messageType] request registerFrameId: ({chromeFrameId}) -> frameId = window.frameId = chromeFrameId # We register a frame immediately only if it is focused or its window isn't tiny. We register tiny # frames later, when necessary. This affects focusFrame() and link hints. if windowIsFocused() or not DomUtils.windowIsTooSmall() Frame.postMessage "registerFrame" else postRegisterFrame = -> window.removeEventListener "focus", focusHandler window.removeEventListener "resize", resizeHandler Frame.postMessage "registerFrame" window.addEventListener "focus", focusHandler = -> postRegisterFrame() if event.target == window window.addEventListener "resize", resizeHandler = -> postRegisterFrame() unless DomUtils.windowIsTooSmall() init: -> @port = chrome.runtime.connect name: "frames" @port.onMessage.addListener (request) => (@listeners[request.handler] ? this[request.handler]) request # We disable the content scripts when we lose contact with the background page, or on unload. @port.onDisconnect.addListener disconnect = Utils.makeIdempotent => @disconnect() window.addEventListener "unload", disconnect disconnect: -> try @postMessage "unregisterFrame" try @port.disconnect() @postMessage = @disconnect = -> @port = null @listeners = {} HintCoordinator.exit isSuccess: false handlerStack.reset() isEnabledForUrl = false window.removeEventListener "focus", onFocus window.removeEventListener "hashchange", onFocus setScrollPosition = ({ scrollX, scrollY }) -> if DomUtils.isTopFrame() DomUtils.documentReady -> window.focus() document.body.focus() if 0 < scrollX or 0 < scrollY Marks.setPreviousPosition() window.scrollTo scrollX, scrollY flashFrame = -> DomUtils.documentReady -> # Create a shadow DOM wrapping the frame so the page's styles don't interfere with ours. highlightedFrameElement = DomUtils.createElement "div" # PhantomJS doesn't support createShadowRoot, so guard against its non-existance. _shadowDOM = highlightedFrameElement.createShadowRoot?() ? highlightedFrameElement # Inject stylesheet. _styleSheet = DomUtils.createElement "style" _styleSheet.innerHTML = "@import url(\"#{chrome.runtime.getURL("content_scripts/vimium.css")}\");" _shadowDOM.appendChild _styleSheet _frameEl = DomUtils.createElement "div" _frameEl.className = "vimiumReset vimiumHighlightedFrame" _shadowDOM.appendChild _frameEl flashFrame = -> document.documentElement.appendChild highlightedFrameElement setTimeout (-> highlightedFrameElement.remove()), 200 # # Called from the backend in order to change frame focus. # focusThisFrame = (request) -> unless request.forceFocusThisFrame if DomUtils.windowIsTooSmall() or document.body?.tagName.toLowerCase() == "frameset" # This frame is too small to focus or it's a frameset. Cancel and tell the background page to focus the # next frame instead. This affects sites like Google Inbox, which have many tiny iframes. See #1317. chrome.runtime.sendMessage handler: "nextFrame" return window.focus() flashFrame() if request.highlight extend window, scrollToBottom: -> Marks.setPreviousPosition() Scroller.scrollTo "y", "max" scrollToTop: (count) -> Marks.setPreviousPosition() Scroller.scrollTo "y", (count - 1) * Settings.get("scrollStepSize") scrollToLeft: -> Scroller.scrollTo "x", 0 scrollToRight: -> Scroller.scrollTo "x", "max" scrollUp: (count) -> Scroller.scrollBy "y", -1 * Settings.get("scrollStepSize") * count scrollDown: (count) -> Scroller.scrollBy "y", Settings.get("scrollStepSize") * count scrollPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1/2 * count scrollPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1/2 * count scrollFullPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1 * count scrollFullPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1 * count scrollLeft: (count) -> Scroller.scrollBy "x", -1 * Settings.get("scrollStepSize") * count scrollRight: (count) -> Scroller.scrollBy "x", Settings.get("scrollStepSize") * count extend window, reload: -> window.location.reload() goBack: (count) -> history.go(-count) goForward: (count) -> history.go(count) goUp: (count) -> url = window.location.href if (url[url.length - 1] == "/") url = url.substring(0, url.length - 1) urlsplit = url.split("/") # make sure we haven't hit the base domain yet if (urlsplit.length > 3) urlsplit = urlsplit.slice(0, Math.max(3, urlsplit.length - count)) window.location.href = urlsplit.join('/') goToRoot: -> window.location.href = window.location.origin mainFrame: -> focusThisFrame highlight: true, forceFocusThisFrame: true toggleViewSource: -> chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) -> if (url.substr(0, 12) == "view-source:") url = url.substr(12, url.length - 12) else url = "view-source:" + url chrome.runtime.sendMessage {handler: "openUrlInNewTab", url} copyCurrentUrl: -> # TODO(<NAME>): When the following bug is fixed, revisit this approach of sending back to the background # page to copy. # http://code.google.com/p/chromium/issues/detail?id=55188 chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) -> chrome.runtime.sendMessage { handler: "copyToClipboard", data: url } url = url[0..25] + "...." if 28 < url.length HUD.showForDuration("Yanked #{url}", 2000) enterInsertMode: -> # If a focusable element receives the focus, then we exit and leave the permanently-installed insert-mode # instance to take over. new InsertMode global: true, exitOnFocus: true enterVisualMode: -> new VisualMode userLaunchedMode: true enterVisualLineMode: -> new VisualLineMode userLaunchedMode: true passNextKey: (count) -> new PassNextKeyMode count focusInput: do -> # Track the most recently focused input element. recentlyFocusedElement = null window.addEventListener "focus", (event) -> recentlyFocusedElement = event.target if DomUtils.isEditable event.target , true (count, mode = InsertMode) -> # Focus the first input element on the page, and create overlays to highlight all the input elements, with # the currently-focused element highlighted specially. Tabbing will shift focus to the next input element. # Pressing any other key will remove the overlays and the special tab behavior. # The mode argument is the mode to enter once an input is selected. resultSet = DomUtils.evaluateXPath textInputXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE visibleInputs = for i in [0...resultSet.snapshotLength] by 1 element = resultSet.snapshotItem i continue unless DomUtils.getVisibleClientRect element, true { element, rect: Rect.copy element.getBoundingClientRect() } if visibleInputs.length == 0 HUD.showForDuration("There are no inputs to focus.", 1000) return # This is a hack to improve usability on the Vimium options page. We prime the recently-focused input # to be the key-mappings input. Arguably, this is the input that the user is most likely to use. recentlyFocusedElement ?= document.getElementById "keyMappings" if window.isVimiumOptionsPage selectedInputIndex = if count == 1 # As the starting index, we pick that of the most recently focused input element (or 0). elements = visibleInputs.map (visibleInput) -> visibleInput.element Math.max 0, elements.indexOf recentlyFocusedElement else Math.min(count, visibleInputs.length) - 1 hints = for tuple in visibleInputs hint = DomUtils.createElement "div" hint.className = "vimiumReset internalVimiumInputHint vimiumInputHint" # minus 1 for the border hint.style.left = (tuple.rect.left - 1) + window.scrollX + "px" hint.style.top = (tuple.rect.top - 1) + window.scrollY + "px" hint.style.width = tuple.rect.width + "px" hint.style.height = tuple.rect.height + "px" hint new class FocusSelector extends Mode constructor: -> super name: "focus-selector" exitOnClick: true keydown: (event) => if event.keyCode == KeyboardUtils.keyCodes.tab hints[selectedInputIndex].classList.remove 'internalVimiumSelectedInputHint' selectedInputIndex += hints.length + (if event.shiftKey then -1 else 1) selectedInputIndex %= hints.length hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint' DomUtils.simulateSelect visibleInputs[selectedInputIndex].element @suppressEvent else unless event.keyCode == KeyboardUtils.keyCodes.shiftKey @exit() # Give the new mode the opportunity to handle the event. @restartBubbling @hintContainingDiv = DomUtils.addElementList hints, id: "vimiumInputMarkerContainer" className: "vimiumReset" DomUtils.simulateSelect visibleInputs[selectedInputIndex].element if visibleInputs.length == 1 @exit() return else hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint' exit: -> super() DomUtils.removeElement @hintContainingDiv if mode and document.activeElement and DomUtils.isEditable document.activeElement new mode singleton: "post-find-mode/focus-input" targetElement: document.activeElement indicator: false # Checks if Vimium should be enabled or not in this frame. As a side effect, it also informs the background # page whether this frame has the focus, allowing the background page to track the active frame's URL and set # the page icon. checkIfEnabledForUrl = do -> Frame.addEventListener "isEnabledForUrl", (response) -> {isEnabledForUrl, passKeys, frameIsFocused} = response initializeOnEnabledStateKnown isEnabledForUrl normalMode.setPassKeys passKeys # Hide the HUD if we're not enabled. HUD.hide true, false unless isEnabledForUrl (frameIsFocused = windowIsFocused()) -> Frame.postMessage "isEnabledForUrl", {frameIsFocused, url: window.location.toString()} # When we're informed by the background page that a URL in this tab has changed, we check if we have the # correct enabled state (but only if this frame has the focus). checkEnabledAfterURLChange = -> checkIfEnabledForUrl() if windowIsFocused() handleEscapeForFindMode = -> document.body.classList.remove("vimiumFindMode") # removing the class does not re-color existing selections. we recreate the current selection so it reverts # back to the default color. selection = window.getSelection() unless selection.isCollapsed range = window.getSelection().getRangeAt(0) window.getSelection().removeAllRanges() window.getSelection().addRange(range) focusFoundLink() || selectFoundInputElement() # <esc> sends us into insert mode if possible, but <cr> does not. # <esc> corresponds approximately to 'nevermind, I have found it already' while <cr> means 'I want to save # this query and do more searches with it' handleEnterForFindMode = -> focusFoundLink() document.body.classList.add("vimiumFindMode") FindMode.saveQuery() focusFoundLink = -> if (FindMode.query.hasResults) link = getLinkFromSelection() link.focus() if link selectFoundInputElement = -> # Since the last focused element might not be the one currently pointed to by find (e.g. the current one # might be disabled and therefore unable to receive focus), we use the approximate heuristic of checking # that the last anchor node is an ancestor of our element. findModeAnchorNode = document.getSelection().anchorNode if (FindMode.query.hasResults && document.activeElement && DomUtils.isSelectable(document.activeElement) && DomUtils.isDOMDescendant(findModeAnchorNode, document.activeElement)) DomUtils.simulateSelect(document.activeElement) findAndFocus = (backwards) -> Marks.setPreviousPosition() FindMode.query.hasResults = FindMode.execute null, {backwards} if FindMode.query.hasResults focusFoundLink() new PostFindMode() else HUD.showForDuration("No matches for '#{FindMode.query.rawQuery}'", 1000) performFind = (count) -> findAndFocus false for [0...count] by 1 performBackwardsFind = (count) -> findAndFocus true for [0...count] by 1 getLinkFromSelection = -> node = window.getSelection().anchorNode while (node && node != document.body) return node if (node.nodeName.toLowerCase() == "a") node = node.parentNode null # used by the findAndFollow* functions. followLink = (linkElement) -> if (linkElement.nodeName.toLowerCase() == "link") window.location.href = linkElement.href else # if we can click on it, don't simply set location.href: some next/prev links are meant to trigger AJAX # calls, like the 'more' button on GitHub's newsfeed. linkElement.scrollIntoView() DomUtils.simulateClick(linkElement) # # Find and follow a link which matches any one of a list of strings. If there are multiple such links, they # are prioritized for shortness, by their position in :linkStrings, how far down the page they are located, # and finally by whether the match is exact. Practically speaking, this means we favor 'next page' over 'the # next big thing', and 'more' over 'nextcompany', even if 'next' occurs before 'more' in :linkStrings. # findAndFollowLink = (linkStrings) -> linksXPath = DomUtils.makeXPath(["a", "*[@onclick or @role='link' or contains(@class, 'button')]"]) links = DomUtils.evaluateXPath(linksXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) candidateLinks = [] # at the end of this loop, candidateLinks will contain all visible links that match our patterns # links lower in the page are more likely to be the ones we want, so we loop through the snapshot backwards for i in [(links.snapshotLength - 1)..0] by -1 link = links.snapshotItem(i) # ensure link is visible (we don't mind if it is scrolled offscreen) boundingClientRect = link.getBoundingClientRect() if (boundingClientRect.width == 0 || boundingClientRect.height == 0) continue computedStyle = window.getComputedStyle(link, null) if (computedStyle.getPropertyValue("visibility") != "visible" || computedStyle.getPropertyValue("display") == "none") continue linkMatches = false for linkString in linkStrings if link.innerText.toLowerCase().indexOf(linkString) != -1 || 0 <= link.value?.indexOf? linkString linkMatches = true break continue unless linkMatches candidateLinks.push(link) return if (candidateLinks.length == 0) for link in candidateLinks link.wordCount = link.innerText.trim().split(/\s+/).length # We can use this trick to ensure that Array.sort is stable. We need this property to retain the reverse # in-page order of the links. candidateLinks.forEach((a,i) -> a.originalIndex = i) # favor shorter links, and ignore those that are more than one word longer than the shortest link candidateLinks = candidateLinks .sort((a, b) -> if (a.wordCount == b.wordCount) then a.originalIndex - b.originalIndex else a.wordCount - b.wordCount ) .filter((a) -> a.wordCount <= candidateLinks[0].wordCount + 1) for linkString in linkStrings exactWordRegex = if /\b/.test(linkString[0]) or /\b/.test(linkString[linkString.length - 1]) new RegExp "\\b" + linkString + "\\b", "i" else new RegExp linkString, "i" for candidateLink in candidateLinks if exactWordRegex.test(candidateLink.innerText) || (candidateLink.value && exactWordRegex.test(candidateLink.value)) followLink(candidateLink) return true false findAndFollowRel = (value) -> relTags = ["link", "a", "area"] for tag in relTags elements = document.getElementsByTagName(tag) for element in elements if (element.hasAttribute("rel") && element.rel.toLowerCase() == value) followLink(element) return true window.goPrevious = -> previousPatterns = Settings.get("previousPatterns") || "" previousStrings = previousPatterns.split(",").filter( (s) -> s.trim().length ) findAndFollowRel("prev") || findAndFollowLink(previousStrings) window.goNext = -> nextPatterns = Settings.get("nextPatterns") || "" nextStrings = nextPatterns.split(",").filter( (s) -> s.trim().length ) findAndFollowRel("next") || findAndFollowLink(nextStrings) # Enters find mode. Returns the new find-mode instance. enterFindMode = -> Marks.setPreviousPosition() new FindMode() window.showHelp = (sourceFrameId) -> chrome.runtime.sendMessage handler: "getHelpDialogHtml", (response) -> HelpDialog.toggle {sourceFrameId, html: response} # If we are in the help dialog iframe, then HelpDialog is already defined with the necessary functions. window.HelpDialog ?= helpUI: null isShowing: -> @helpUI?.showing abort: -> @helpUI.hide false if @isShowing() toggle: (request) -> DomUtils.documentComplete => @helpUI ?= new UIComponent "pages/help_dialog.html", "vimiumHelpDialogFrame", -> if @helpUI? and @isShowing() @helpUI.hide() else if @helpUI? @helpUI.activate extend request, name: "activate", focus: true initializePreDomReady() DomUtils.documentReady initializeOnDomReady root = exports ? window root.handlerStack = handlerStack root.frameId = frameId root.Frame = Frame root.windowIsFocused = windowIsFocused root.bgLog = bgLog # These are exported for find mode and link-hints mode. extend root, {handleEscapeForFindMode, handleEnterForFindMode, performFind, performBackwardsFind, enterFindMode, focusThisFrame} # These are exported only for the tests. extend root, {installModes, installListeners}
true
# # This content script must be run prior to domReady so that we perform some operations very early. # chrome = browser isEnabledForUrl = true isIncognitoMode = false try if not window.indexedDB isIncognitoMode = true catch error isIncognitoMode = true normalMode = null # We track whther the current window has the focus or not. windowIsFocused = do -> windowHasFocus = null DomUtils.documentReady -> windowHasFocus = document.hasFocus() window.addEventListener "focus", (event) -> windowHasFocus = true if event.target == window; true window.addEventListener "blur", (event) -> windowHasFocus = false if event.target == window; true -> windowHasFocus # The types in <input type="..."> that we consider for focusInput command. Right now this is recalculated in # each content script. Alternatively we could calculate it once in the background page and use a request to # fetch it each time. # Should we include the HTML5 date pickers here? # The corresponding XPath for such elements. textInputXPath = (-> textInputTypes = [ "text", "search", "email", "url", "number", "password", "date", "tel" ] inputElements = ["input[" + "(" + textInputTypes.map((type) -> '@type="' + type + '"').join(" or ") + "or not(@type))" + " and not(@disabled or @readonly)]", "textarea", "*[@contenteditable='' or translate(@contenteditable, 'TRUE', 'true')='true']"] DomUtils.makeXPath(inputElements) )() # This is set by Frame.registerFrameId(). A frameId of 0 indicates that this is the top frame in the tab. frameId = null # For debugging only. This logs to the console on the background page. bgLog = (args...) -> args = (arg.toString() for arg in args) chrome.runtime.sendMessage handler: "log", message: args.join " " # If an input grabs the focus before the user has interacted with the page, then grab it back (if the # grabBackFocus option is set). class GrabBackFocus extends Mode constructor: -> super name: "grab-back-focus" keydown: => @alwaysContinueBubbling => @exit() @push _name: "grab-back-focus-mousedown" mousedown: => @alwaysContinueBubbling => @exit() Settings.use "grabBackFocus", (grabBackFocus) => # It is possible that this mode exits (e.g. due to a key event) before the settings are ready -- in # which case we should not install this grab-back-focus watcher. if @modeIsActive if grabBackFocus @push _name: "grab-back-focus-focus" focus: (event) => @grabBackFocus event.target # An input may already be focused. If so, grab back the focus. @grabBackFocus document.activeElement if document.activeElement else @exit() grabBackFocus: (element) -> return @continueBubbling unless DomUtils.isEditable element element.blur() @suppressEvent # Pages can load new content dynamically and change the displayed URL using history.pushState. Since this can # often be indistinguishable from an actual new page load for the user, we should also re-start GrabBackFocus # for these as well. This fixes issue #1622. handlerStack.push _name: "GrabBackFocus-pushState-monitor" click: (event) -> # If a focusable element is focused, the user must have clicked on it. Retain focus and bail. return true if DomUtils.isFocusable document.activeElement target = event.target while target # Often, a link which triggers a content load and url change with javascript will also have the new # url as it's href attribute. if target.tagName == "A" and target.origin == document.location.origin and # Clicking the link will change the url of this frame. (target.pathName != document.location.pathName or target.search != document.location.search) and (target.target in ["", "_self"] or (target.target == "_parent" and window.parent == window) or (target.target == "_top" and window.top == window)) return new GrabBackFocus() else target = target.parentElement true class NormalMode extends KeyHandlerMode constructor: (options = {}) -> super extend options, name: "normal" indicator: false # There is no mode indicator in normal mode. commandHandler: @commandHandler.bind this chrome.storage.local.get "normalModeKeyStateMapping", (items) => @setKeyMapping items.normalModeKeyStateMapping chrome.storage.onChanged.addListener (changes, area) => if area == "local" and changes.normalModeKeyStateMapping?.newValue @setKeyMapping changes.normalModeKeyStateMapping.newValue # Initialize components which normal mode depends upon. Scroller.init() FindModeHistory.init() commandHandler: ({command: registryEntry, count}) -> count *= registryEntry.options.count ? 1 count = 1 if registryEntry.noRepeat if registryEntry.repeatLimit? and registryEntry.repeatLimit < count return unless confirm """ You have asked Vimium to perform #{count} repetitions of the command: #{registryEntry.description}.\n Are you sure you want to continue?""" if registryEntry.topFrame # We never return to a UI-component frame (e.g. the help dialog), it might have lost the focus. sourceFrameId = if window.isVimiumUIComponent then 0 else frameId chrome.runtime.sendMessage handler: "sendMessageToFrames", message: {name: "runInTopFrame", sourceFrameId, registryEntry} else if registryEntry.background chrome.runtime.sendMessage {handler: "runBackgroundCommand", registryEntry, count} else Utils.invokeCommandString registryEntry.command, count installModes = -> # Install the permanent modes. The permanently-installed insert mode tracks focus/blur events, and # activates/deactivates itself accordingly. normalMode = new NormalMode new InsertMode permanent: true new GrabBackFocus if isEnabledForUrl normalMode # Return the normalMode object (for the tests). initializeOnEnabledStateKnown = (isEnabledForUrl) -> installModes() unless normalMode if isEnabledForUrl # We only initialize (and activate) the Vomnibar in the top frame. Also, we do not initialize the # Vomnibar until we know that Vimium is enabled. Thereafter, there's no more initialization to do. DomUtils.documentComplete Vomnibar.init.bind Vomnibar if DomUtils.isTopFrame() initializeOnEnabledStateKnown = -> # # Complete initialization work that should be done prior to DOMReady. # initializePreDomReady = -> installListeners() Frame.init() checkIfEnabledForUrl document.hasFocus() requestHandlers = focusFrame: (request) -> if (frameId == request.frameId) then focusThisFrame request getScrollPosition: (ignoredA, ignoredB, sendResponse) -> sendResponse scrollX: window.scrollX, scrollY: window.scrollY if frameId == 0 setScrollPosition: setScrollPosition frameFocused: -> # A frame has received the focus; we don't care here (UI components handle this). checkEnabledAfterURLChange: checkEnabledAfterURLChange runInTopFrame: ({sourceFrameId, registryEntry}) -> Utils.invokeCommandString registryEntry.command, sourceFrameId, registryEntry if DomUtils.isTopFrame() linkHintsMessage: (request) -> HintCoordinator[request.messageType] request chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> # These requests are intended for the background page, but they're delivered to the options page too. unless request.handler and not request.name if isEnabledForUrl or request.name in ["checkEnabledAfterURLChange", "runInTopFrame"] requestHandlers[request.name] request, sender, sendResponse false # Ensure that the sendResponse callback is freed. # Wrapper to install event listeners. Syntactic sugar. installListener = (element, event, callback) -> element.addEventListener(event, -> if isEnabledForUrl then callback.apply(this, arguments) else true , true) # # Installing or uninstalling listeners is error prone. Instead we elect to check isEnabledForUrl each time so # we know whether the listener should run or not. # Run this as early as possible, so the page can't register any event handlers before us. # Note: We install the listeners even if Vimium is disabled. See comment in commit # 6446cf04c7b44c3d419dc450a73b60bcaf5cdf02. # installListeners = Utils.makeIdempotent -> # Key event handlers fire on window before they do on document. Prefer window for key events so the page # can't set handlers to grab the keys before us. for type in ["keydown", "keypress", "keyup", "click", "focus", "blur", "mousedown", "scroll"] do (type) -> installListener window, type, (event) -> handlerStack.bubbleEvent type, event installListener document, "DOMActivate", (event) -> handlerStack.bubbleEvent 'DOMActivate', event # # Whenever we get the focus: # - Tell the background page this frame's URL. # - Check if we should be enabled. # onFocus = (event) -> if event.target == window chrome.runtime.sendMessage handler: "frameFocused" checkIfEnabledForUrl true # We install these listeners directly (that is, we don't use installListener) because we still need to receive # events when Vimium is not enabled. window.addEventListener "focus", onFocus window.addEventListener "hashchange", onFocus initializeOnDomReady = -> # Tell the background page we're in the domReady state. Frame.postMessage "domReady" Frame = port: null listeners: {} addEventListener: (handler, callback) -> @listeners[handler] = callback postMessage: (handler, request = {}) -> @port.postMessage extend request, {handler} linkHintsMessage: (request) -> HintCoordinator[request.messageType] request registerFrameId: ({chromeFrameId}) -> frameId = window.frameId = chromeFrameId # We register a frame immediately only if it is focused or its window isn't tiny. We register tiny # frames later, when necessary. This affects focusFrame() and link hints. if windowIsFocused() or not DomUtils.windowIsTooSmall() Frame.postMessage "registerFrame" else postRegisterFrame = -> window.removeEventListener "focus", focusHandler window.removeEventListener "resize", resizeHandler Frame.postMessage "registerFrame" window.addEventListener "focus", focusHandler = -> postRegisterFrame() if event.target == window window.addEventListener "resize", resizeHandler = -> postRegisterFrame() unless DomUtils.windowIsTooSmall() init: -> @port = chrome.runtime.connect name: "frames" @port.onMessage.addListener (request) => (@listeners[request.handler] ? this[request.handler]) request # We disable the content scripts when we lose contact with the background page, or on unload. @port.onDisconnect.addListener disconnect = Utils.makeIdempotent => @disconnect() window.addEventListener "unload", disconnect disconnect: -> try @postMessage "unregisterFrame" try @port.disconnect() @postMessage = @disconnect = -> @port = null @listeners = {} HintCoordinator.exit isSuccess: false handlerStack.reset() isEnabledForUrl = false window.removeEventListener "focus", onFocus window.removeEventListener "hashchange", onFocus setScrollPosition = ({ scrollX, scrollY }) -> if DomUtils.isTopFrame() DomUtils.documentReady -> window.focus() document.body.focus() if 0 < scrollX or 0 < scrollY Marks.setPreviousPosition() window.scrollTo scrollX, scrollY flashFrame = -> DomUtils.documentReady -> # Create a shadow DOM wrapping the frame so the page's styles don't interfere with ours. highlightedFrameElement = DomUtils.createElement "div" # PhantomJS doesn't support createShadowRoot, so guard against its non-existance. _shadowDOM = highlightedFrameElement.createShadowRoot?() ? highlightedFrameElement # Inject stylesheet. _styleSheet = DomUtils.createElement "style" _styleSheet.innerHTML = "@import url(\"#{chrome.runtime.getURL("content_scripts/vimium.css")}\");" _shadowDOM.appendChild _styleSheet _frameEl = DomUtils.createElement "div" _frameEl.className = "vimiumReset vimiumHighlightedFrame" _shadowDOM.appendChild _frameEl flashFrame = -> document.documentElement.appendChild highlightedFrameElement setTimeout (-> highlightedFrameElement.remove()), 200 # # Called from the backend in order to change frame focus. # focusThisFrame = (request) -> unless request.forceFocusThisFrame if DomUtils.windowIsTooSmall() or document.body?.tagName.toLowerCase() == "frameset" # This frame is too small to focus or it's a frameset. Cancel and tell the background page to focus the # next frame instead. This affects sites like Google Inbox, which have many tiny iframes. See #1317. chrome.runtime.sendMessage handler: "nextFrame" return window.focus() flashFrame() if request.highlight extend window, scrollToBottom: -> Marks.setPreviousPosition() Scroller.scrollTo "y", "max" scrollToTop: (count) -> Marks.setPreviousPosition() Scroller.scrollTo "y", (count - 1) * Settings.get("scrollStepSize") scrollToLeft: -> Scroller.scrollTo "x", 0 scrollToRight: -> Scroller.scrollTo "x", "max" scrollUp: (count) -> Scroller.scrollBy "y", -1 * Settings.get("scrollStepSize") * count scrollDown: (count) -> Scroller.scrollBy "y", Settings.get("scrollStepSize") * count scrollPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1/2 * count scrollPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1/2 * count scrollFullPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1 * count scrollFullPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1 * count scrollLeft: (count) -> Scroller.scrollBy "x", -1 * Settings.get("scrollStepSize") * count scrollRight: (count) -> Scroller.scrollBy "x", Settings.get("scrollStepSize") * count extend window, reload: -> window.location.reload() goBack: (count) -> history.go(-count) goForward: (count) -> history.go(count) goUp: (count) -> url = window.location.href if (url[url.length - 1] == "/") url = url.substring(0, url.length - 1) urlsplit = url.split("/") # make sure we haven't hit the base domain yet if (urlsplit.length > 3) urlsplit = urlsplit.slice(0, Math.max(3, urlsplit.length - count)) window.location.href = urlsplit.join('/') goToRoot: -> window.location.href = window.location.origin mainFrame: -> focusThisFrame highlight: true, forceFocusThisFrame: true toggleViewSource: -> chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) -> if (url.substr(0, 12) == "view-source:") url = url.substr(12, url.length - 12) else url = "view-source:" + url chrome.runtime.sendMessage {handler: "openUrlInNewTab", url} copyCurrentUrl: -> # TODO(PI:NAME:<NAME>END_PI): When the following bug is fixed, revisit this approach of sending back to the background # page to copy. # http://code.google.com/p/chromium/issues/detail?id=55188 chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) -> chrome.runtime.sendMessage { handler: "copyToClipboard", data: url } url = url[0..25] + "...." if 28 < url.length HUD.showForDuration("Yanked #{url}", 2000) enterInsertMode: -> # If a focusable element receives the focus, then we exit and leave the permanently-installed insert-mode # instance to take over. new InsertMode global: true, exitOnFocus: true enterVisualMode: -> new VisualMode userLaunchedMode: true enterVisualLineMode: -> new VisualLineMode userLaunchedMode: true passNextKey: (count) -> new PassNextKeyMode count focusInput: do -> # Track the most recently focused input element. recentlyFocusedElement = null window.addEventListener "focus", (event) -> recentlyFocusedElement = event.target if DomUtils.isEditable event.target , true (count, mode = InsertMode) -> # Focus the first input element on the page, and create overlays to highlight all the input elements, with # the currently-focused element highlighted specially. Tabbing will shift focus to the next input element. # Pressing any other key will remove the overlays and the special tab behavior. # The mode argument is the mode to enter once an input is selected. resultSet = DomUtils.evaluateXPath textInputXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE visibleInputs = for i in [0...resultSet.snapshotLength] by 1 element = resultSet.snapshotItem i continue unless DomUtils.getVisibleClientRect element, true { element, rect: Rect.copy element.getBoundingClientRect() } if visibleInputs.length == 0 HUD.showForDuration("There are no inputs to focus.", 1000) return # This is a hack to improve usability on the Vimium options page. We prime the recently-focused input # to be the key-mappings input. Arguably, this is the input that the user is most likely to use. recentlyFocusedElement ?= document.getElementById "keyMappings" if window.isVimiumOptionsPage selectedInputIndex = if count == 1 # As the starting index, we pick that of the most recently focused input element (or 0). elements = visibleInputs.map (visibleInput) -> visibleInput.element Math.max 0, elements.indexOf recentlyFocusedElement else Math.min(count, visibleInputs.length) - 1 hints = for tuple in visibleInputs hint = DomUtils.createElement "div" hint.className = "vimiumReset internalVimiumInputHint vimiumInputHint" # minus 1 for the border hint.style.left = (tuple.rect.left - 1) + window.scrollX + "px" hint.style.top = (tuple.rect.top - 1) + window.scrollY + "px" hint.style.width = tuple.rect.width + "px" hint.style.height = tuple.rect.height + "px" hint new class FocusSelector extends Mode constructor: -> super name: "focus-selector" exitOnClick: true keydown: (event) => if event.keyCode == KeyboardUtils.keyCodes.tab hints[selectedInputIndex].classList.remove 'internalVimiumSelectedInputHint' selectedInputIndex += hints.length + (if event.shiftKey then -1 else 1) selectedInputIndex %= hints.length hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint' DomUtils.simulateSelect visibleInputs[selectedInputIndex].element @suppressEvent else unless event.keyCode == KeyboardUtils.keyCodes.shiftKey @exit() # Give the new mode the opportunity to handle the event. @restartBubbling @hintContainingDiv = DomUtils.addElementList hints, id: "vimiumInputMarkerContainer" className: "vimiumReset" DomUtils.simulateSelect visibleInputs[selectedInputIndex].element if visibleInputs.length == 1 @exit() return else hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint' exit: -> super() DomUtils.removeElement @hintContainingDiv if mode and document.activeElement and DomUtils.isEditable document.activeElement new mode singleton: "post-find-mode/focus-input" targetElement: document.activeElement indicator: false # Checks if Vimium should be enabled or not in this frame. As a side effect, it also informs the background # page whether this frame has the focus, allowing the background page to track the active frame's URL and set # the page icon. checkIfEnabledForUrl = do -> Frame.addEventListener "isEnabledForUrl", (response) -> {isEnabledForUrl, passKeys, frameIsFocused} = response initializeOnEnabledStateKnown isEnabledForUrl normalMode.setPassKeys passKeys # Hide the HUD if we're not enabled. HUD.hide true, false unless isEnabledForUrl (frameIsFocused = windowIsFocused()) -> Frame.postMessage "isEnabledForUrl", {frameIsFocused, url: window.location.toString()} # When we're informed by the background page that a URL in this tab has changed, we check if we have the # correct enabled state (but only if this frame has the focus). checkEnabledAfterURLChange = -> checkIfEnabledForUrl() if windowIsFocused() handleEscapeForFindMode = -> document.body.classList.remove("vimiumFindMode") # removing the class does not re-color existing selections. we recreate the current selection so it reverts # back to the default color. selection = window.getSelection() unless selection.isCollapsed range = window.getSelection().getRangeAt(0) window.getSelection().removeAllRanges() window.getSelection().addRange(range) focusFoundLink() || selectFoundInputElement() # <esc> sends us into insert mode if possible, but <cr> does not. # <esc> corresponds approximately to 'nevermind, I have found it already' while <cr> means 'I want to save # this query and do more searches with it' handleEnterForFindMode = -> focusFoundLink() document.body.classList.add("vimiumFindMode") FindMode.saveQuery() focusFoundLink = -> if (FindMode.query.hasResults) link = getLinkFromSelection() link.focus() if link selectFoundInputElement = -> # Since the last focused element might not be the one currently pointed to by find (e.g. the current one # might be disabled and therefore unable to receive focus), we use the approximate heuristic of checking # that the last anchor node is an ancestor of our element. findModeAnchorNode = document.getSelection().anchorNode if (FindMode.query.hasResults && document.activeElement && DomUtils.isSelectable(document.activeElement) && DomUtils.isDOMDescendant(findModeAnchorNode, document.activeElement)) DomUtils.simulateSelect(document.activeElement) findAndFocus = (backwards) -> Marks.setPreviousPosition() FindMode.query.hasResults = FindMode.execute null, {backwards} if FindMode.query.hasResults focusFoundLink() new PostFindMode() else HUD.showForDuration("No matches for '#{FindMode.query.rawQuery}'", 1000) performFind = (count) -> findAndFocus false for [0...count] by 1 performBackwardsFind = (count) -> findAndFocus true for [0...count] by 1 getLinkFromSelection = -> node = window.getSelection().anchorNode while (node && node != document.body) return node if (node.nodeName.toLowerCase() == "a") node = node.parentNode null # used by the findAndFollow* functions. followLink = (linkElement) -> if (linkElement.nodeName.toLowerCase() == "link") window.location.href = linkElement.href else # if we can click on it, don't simply set location.href: some next/prev links are meant to trigger AJAX # calls, like the 'more' button on GitHub's newsfeed. linkElement.scrollIntoView() DomUtils.simulateClick(linkElement) # # Find and follow a link which matches any one of a list of strings. If there are multiple such links, they # are prioritized for shortness, by their position in :linkStrings, how far down the page they are located, # and finally by whether the match is exact. Practically speaking, this means we favor 'next page' over 'the # next big thing', and 'more' over 'nextcompany', even if 'next' occurs before 'more' in :linkStrings. # findAndFollowLink = (linkStrings) -> linksXPath = DomUtils.makeXPath(["a", "*[@onclick or @role='link' or contains(@class, 'button')]"]) links = DomUtils.evaluateXPath(linksXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) candidateLinks = [] # at the end of this loop, candidateLinks will contain all visible links that match our patterns # links lower in the page are more likely to be the ones we want, so we loop through the snapshot backwards for i in [(links.snapshotLength - 1)..0] by -1 link = links.snapshotItem(i) # ensure link is visible (we don't mind if it is scrolled offscreen) boundingClientRect = link.getBoundingClientRect() if (boundingClientRect.width == 0 || boundingClientRect.height == 0) continue computedStyle = window.getComputedStyle(link, null) if (computedStyle.getPropertyValue("visibility") != "visible" || computedStyle.getPropertyValue("display") == "none") continue linkMatches = false for linkString in linkStrings if link.innerText.toLowerCase().indexOf(linkString) != -1 || 0 <= link.value?.indexOf? linkString linkMatches = true break continue unless linkMatches candidateLinks.push(link) return if (candidateLinks.length == 0) for link in candidateLinks link.wordCount = link.innerText.trim().split(/\s+/).length # We can use this trick to ensure that Array.sort is stable. We need this property to retain the reverse # in-page order of the links. candidateLinks.forEach((a,i) -> a.originalIndex = i) # favor shorter links, and ignore those that are more than one word longer than the shortest link candidateLinks = candidateLinks .sort((a, b) -> if (a.wordCount == b.wordCount) then a.originalIndex - b.originalIndex else a.wordCount - b.wordCount ) .filter((a) -> a.wordCount <= candidateLinks[0].wordCount + 1) for linkString in linkStrings exactWordRegex = if /\b/.test(linkString[0]) or /\b/.test(linkString[linkString.length - 1]) new RegExp "\\b" + linkString + "\\b", "i" else new RegExp linkString, "i" for candidateLink in candidateLinks if exactWordRegex.test(candidateLink.innerText) || (candidateLink.value && exactWordRegex.test(candidateLink.value)) followLink(candidateLink) return true false findAndFollowRel = (value) -> relTags = ["link", "a", "area"] for tag in relTags elements = document.getElementsByTagName(tag) for element in elements if (element.hasAttribute("rel") && element.rel.toLowerCase() == value) followLink(element) return true window.goPrevious = -> previousPatterns = Settings.get("previousPatterns") || "" previousStrings = previousPatterns.split(",").filter( (s) -> s.trim().length ) findAndFollowRel("prev") || findAndFollowLink(previousStrings) window.goNext = -> nextPatterns = Settings.get("nextPatterns") || "" nextStrings = nextPatterns.split(",").filter( (s) -> s.trim().length ) findAndFollowRel("next") || findAndFollowLink(nextStrings) # Enters find mode. Returns the new find-mode instance. enterFindMode = -> Marks.setPreviousPosition() new FindMode() window.showHelp = (sourceFrameId) -> chrome.runtime.sendMessage handler: "getHelpDialogHtml", (response) -> HelpDialog.toggle {sourceFrameId, html: response} # If we are in the help dialog iframe, then HelpDialog is already defined with the necessary functions. window.HelpDialog ?= helpUI: null isShowing: -> @helpUI?.showing abort: -> @helpUI.hide false if @isShowing() toggle: (request) -> DomUtils.documentComplete => @helpUI ?= new UIComponent "pages/help_dialog.html", "vimiumHelpDialogFrame", -> if @helpUI? and @isShowing() @helpUI.hide() else if @helpUI? @helpUI.activate extend request, name: "activate", focus: true initializePreDomReady() DomUtils.documentReady initializeOnDomReady root = exports ? window root.handlerStack = handlerStack root.frameId = frameId root.Frame = Frame root.windowIsFocused = windowIsFocused root.bgLog = bgLog # These are exported for find mode and link-hints mode. extend root, {handleEscapeForFindMode, handleEnterForFindMode, performFind, performBackwardsFind, enterFindMode, focusThisFrame} # These are exported only for the tests. extend root, {installModes, installListeners}
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999158978462219, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/loading-overlay.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. overlay = document.getElementsByClassName 'js-loading-overlay' show = -> return if overlay.length == 0 overlay[0].classList.add 'loading-overlay--visible' show = _.debounce show, 5000, maxWait: 5000 hide = -> return if overlay.length == 0 show.cancel() overlay[0].classList.remove 'loading-overlay--visible' @LoadingOverlay = show: show hide: hide
14392
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. overlay = document.getElementsByClassName 'js-loading-overlay' show = -> return if overlay.length == 0 overlay[0].classList.add 'loading-overlay--visible' show = _.debounce show, 5000, maxWait: 5000 hide = -> return if overlay.length == 0 show.cancel() overlay[0].classList.remove 'loading-overlay--visible' @LoadingOverlay = show: show hide: hide
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. overlay = document.getElementsByClassName 'js-loading-overlay' show = -> return if overlay.length == 0 overlay[0].classList.add 'loading-overlay--visible' show = _.debounce show, 5000, maxWait: 5000 hide = -> return if overlay.length == 0 show.cancel() overlay[0].classList.remove 'loading-overlay--visible' @LoadingOverlay = show: show hide: hide
[ { "context": "###\n@Author: Kristinita\n@Date: 2018-03-20 10:35:20\n@Last Modified time:", "end": 23, "score": 0.9998233914375305, "start": 13, "tag": "NAME", "value": "Kristinita" }, { "context": "#####\n# JQuery carousel and/or slideshow\n# http://kenwheeler.github.io/slick/\n$(d...
themes/sashapelican/static/coffee/Slick/slick.coffee
Kristinita/KristinitaPelicanCI
0
### @Author: Kristinita @Date: 2018-03-20 10:35:20 @Last Modified time: 2018-03-21 09:49:03 ### ######### # Slick # ######### # JQuery carousel and/or slideshow # http://kenwheeler.github.io/slick/ $(document).ready -> $('.slider').slick ### [NOTE] If “ondemand”, need wrap each image in <div>: https://github.com/kenwheeler/slick/issues/1473#issuecomment-150086856 “ondemand” vs “progressive”: https://stackoverflow.com/a/25726743/5951529 [NOTE] First 3 images load not lazy, after images load lazy. ### lazyLoad: 'ondemand' autoplay: true # [NOTE] If true, slides works incorrect. variableWidth: false adaptiveHeight: true slidesToShow: 1 fade: true speed: 1000 arrows: false slidesToScroll: 1 autoplaySpeed: 2000 pauseOnFocus: false pauseOnHover: false return
71175
### @Author: <NAME> @Date: 2018-03-20 10:35:20 @Last Modified time: 2018-03-21 09:49:03 ### ######### # Slick # ######### # JQuery carousel and/or slideshow # http://kenwheeler.github.io/slick/ $(document).ready -> $('.slider').slick ### [NOTE] If “ondemand”, need wrap each image in <div>: https://github.com/kenwheeler/slick/issues/1473#issuecomment-150086856 “ondemand” vs “progressive”: https://stackoverflow.com/a/25726743/5951529 [NOTE] First 3 images load not lazy, after images load lazy. ### lazyLoad: 'ondemand' autoplay: true # [NOTE] If true, slides works incorrect. variableWidth: false adaptiveHeight: true slidesToShow: 1 fade: true speed: 1000 arrows: false slidesToScroll: 1 autoplaySpeed: 2000 pauseOnFocus: false pauseOnHover: false return
true
### @Author: PI:NAME:<NAME>END_PI @Date: 2018-03-20 10:35:20 @Last Modified time: 2018-03-21 09:49:03 ### ######### # Slick # ######### # JQuery carousel and/or slideshow # http://kenwheeler.github.io/slick/ $(document).ready -> $('.slider').slick ### [NOTE] If “ondemand”, need wrap each image in <div>: https://github.com/kenwheeler/slick/issues/1473#issuecomment-150086856 “ondemand” vs “progressive”: https://stackoverflow.com/a/25726743/5951529 [NOTE] First 3 images load not lazy, after images load lazy. ### lazyLoad: 'ondemand' autoplay: true # [NOTE] If true, slides works incorrect. variableWidth: false adaptiveHeight: true slidesToShow: 1 fade: true speed: 1000 arrows: false slidesToScroll: 1 autoplaySpeed: 2000 pauseOnFocus: false pauseOnHover: false return
[ { "context": "cord[attr] ? \"null\"\n flatKey = key.join String.fromCharCode(0)\n if not tot", "end": 691, "score": 0.6604684591293335, "start": 687, "tag": "KEY", "value": "join" }, { "context": "ll\"\n flatKey = key.join String.fromCharC...
subtotal.coffee
Sakuto/subtotal
50
callWithJQuery = (pivotModule) -> if typeof exports is "object" and typeof module is "object" # CommonJS pivotModule require("jquery") else if typeof define is "function" and define.amd # AMD define ["jquery"], pivotModule # Plain browser env else pivotModule jQuery callWithJQuery ($) -> class SubtotalPivotData extends $.pivotUtilities.PivotData constructor: (input, opts) -> super input, opts processKey = (record, totals, keys, attrs, getAggregator) -> key = [] addKey = false for attr in attrs key.push record[attr] ? "null" flatKey = key.join String.fromCharCode(0) if not totals[flatKey] totals[flatKey] = getAggregator key.slice() addKey = true totals[flatKey].push record keys.push key if addKey return key processRecord: (record) -> #this code is called in a tight loop rowKey = [] colKey = [] @allTotal.push record rowKey = processKey record, @rowTotals, @rowKeys, @rowAttrs, (key) => return @aggregator this, key, [] colKey = processKey record, @colTotals, @colKeys, @colAttrs, (key) => return @aggregator this, [], key m = rowKey.length-1 n = colKey.length-1 return if m < 0 or n < 0 for i in [0..m] fRowKey = rowKey.slice(0, i+1) flatRowKey = fRowKey.join String.fromCharCode(0) @tree[flatRowKey] = {} if not @tree[flatRowKey] for j in [0..n] fColKey = colKey.slice 0, j+1 flatColKey = fColKey.join String.fromCharCode(0) @tree[flatRowKey][flatColKey] = @aggregator this, fRowKey, fColKey if not @tree[flatRowKey][flatColKey] @tree[flatRowKey][flatColKey].push record $.pivotUtilities.SubtotalPivotData = SubtotalPivotData SubtotalRenderer = (pivotData, opts) -> defaults = table: clickCallback: null localeStrings: totals: "Totals", subtotalOf: "Subtotal of" arrowCollapsed: "\u25B6" arrowExpanded: "\u25E2" rowSubtotalDisplay: displayOnTop: true disableFrom: 99999 collapseAt: 99999 hideOnExpand: false disableExpandCollapse: false colSubtotalDisplay: displayOnTop: true disableFrom: 99999 collapseAt: 99999 hideOnExpand: false disableExpandCollapse: false opts = $.extend true, {}, defaults, opts opts.rowSubtotalDisplay.disableFrom = 0 if opts.rowSubtotalDisplay.disableSubtotal opts.rowSubtotalDisplay.disableFrom = opts.rowSubtotalDisplay.disableAfter+1 if typeof opts.rowSubtotalDisplay.disableAfter isnt 'undefined' and opts.rowSubtotalDisplay.disableAfter isnt null opts.rowSubtotalDisplay.collapseAt = opts.collapseRowsAt if typeof opts.rowSubtotalDisplay.collapseAt isnt 'undefined' and opts.collapseRowsAt isnt null opts.colSubtotalDisplay.disableFrom = 0 if opts.colSubtotalDisplay.disableSubtotal opts.colSubtotalDisplay.disableFrom = opts.colSubtotalDisplay.disableAfter+1 if typeof opts.colSubtotalDisplay.disableAfter isnt 'undefined' and opts.colSubtotalDisplay.disableAfter isnt null opts.colSubtotalDisplay.collapseAt = opts.collapseColsAt if typeof opts.colSubtotalDisplay.collapseAt isnt 'undefined' and opts.collapseColsAt isnt null colAttrs = pivotData.colAttrs rowAttrs = pivotData.rowAttrs rowKeys = pivotData.getRowKeys() colKeys = pivotData.getColKeys() tree = pivotData.tree rowTotals = pivotData.rowTotals colTotals = pivotData.colTotals allTotal = pivotData.allTotal classRowHide = "rowhide" classRowShow = "rowshow" classColHide = "colhide" classColShow = "colshow" clickStatusExpanded = "expanded" clickStatusCollapsed = "collapsed" classExpanded = "expanded" classCollapsed = "collapsed" classRowExpanded = "rowexpanded" classRowCollapsed = "rowcollapsed" classColExpanded = "colexpanded" classColCollapsed = "colcollapsed" arrowExpanded = opts.arrowExpanded arrowCollapsed = opts.arrowCollapsed # Based on http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript -- Begin hasClass = (element, className) -> regExp = new RegExp "(?:^|\\s)" + className + "(?!\\S)", "g" element.className.match(regExp) isnt null removeClass = (element, className) -> for name in className.split " " regExp = new RegExp "(?:^|\\s)" + name + "(?!\\S)", "g" element.className = element.className.replace regExp, '' addClass = (element, className) -> for name in className.split " " element.className += (" " + name) if not hasClass element, name replaceClass = (element, replaceClassName, byClassName) -> removeClass element, replaceClassName addClass element, byClassName # Based on http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript -- End createElement = (elementType, className, textContent, attributes, eventHandlers) -> e = document.createElement elementType e.className = className if className? e.textContent = textContent if textContent? e.setAttribute attr, val for own attr, val of attributes if attributes? e.addEventListener event, handler for own event, handler of eventHandlers if eventHandlers? return e setAttributes = (e, attrs) -> e.setAttribute a, v for own a, v of attrs processKeys = (keysArr, className, opts) -> lastIdx = keysArr[0].length-1 headers = children: [] row = 0 keysArr.reduce( (val0, k0) => col = 0 k0.reduce( (acc, curVal, curIdx, arr) => if not acc[curVal] key = k0.slice 0, col+1 acc[curVal] = row: row col: col descendants: 0 children: [] text: curVal key: key flatKey: key.join String.fromCharCode(0) firstLeaf: null leaves: 0 parent: if col isnt 0 then acc else null th: createElement "th", className, curVal childrenSpan: 0 acc.children.push curVal if col > 0 acc.descendants++ col++ if curIdx == lastIdx node = headers for i in [0..lastIdx-1] when lastIdx > 0 node[k0[i]].leaves++ if not node[k0[i]].firstLeaf node[k0[i]].firstLeaf = acc[curVal] node = node[k0[i]] return headers return acc[curVal] headers) row++ return headers headers) return headers buildAxisHeader = (axisHeaders, col, attrs, opts) -> ah = text: attrs[col] expandedCount: 0 expandables: 0 attrHeaders: [] clickStatus: clickStatusExpanded onClick: collapseAxis arrow = "#{arrowExpanded} " hClass = classExpanded if col >= opts.collapseAt arrow = "#{arrowCollapsed} " hClass = classCollapsed ah.clickStatus = clickStatusCollapsed ah.onClick = expandAxis if col == attrs.length-1 or col >= opts.disableFrom or opts.disableExpandCollapse arrow = "" ah.th = createElement "th", "pvtAxisLabel #{hClass}", "#{arrow}#{ah.text}" if col < attrs.length-1 and col < opts.disableFrom and not opts.disableExpandCollapse ah.th.onclick = (event) -> event = event || window.event ah.onClick axisHeaders, col, attrs, opts axisHeaders.ah.push ah return ah buildColAxisHeaders = (thead, rowAttrs, colAttrs, opts) -> axisHeaders = collapseAttrHeader: collapseCol expandAttrHeader: expandCol ah: [] for attr, col in colAttrs ah = buildAxisHeader axisHeaders, col, colAttrs, opts.colSubtotalDisplay ah.tr = createElement "tr" ah.tr.appendChild createElement "th", null, null, {colspan: rowAttrs.length, rowspan: colAttrs.length} if col is 0 and rowAttrs.length isnt 0 ah.tr.appendChild ah.th thead.appendChild ah.tr return axisHeaders buildRowAxisHeaders = (thead, rowAttrs, colAttrs, opts) -> axisHeaders = collapseAttrHeader: collapseRow expandAttrHeader: expandRow ah: [] tr: createElement "tr" for col in [0..rowAttrs.length-1] ah = buildAxisHeader axisHeaders, col, rowAttrs, opts.rowSubtotalDisplay axisHeaders.tr.appendChild ah.th if colAttrs.length != 0 th = createElement "th" axisHeaders.tr.appendChild th thead.appendChild axisHeaders.tr return axisHeaders getHeaderText = (h, attrs, opts) -> arrow = " #{arrowExpanded} " arrow = "" if h.col == attrs.length-1 or h.col >= opts.disableFrom or opts.disableExpandCollapse or h.children.length is 0 return "#{arrow}#{h.text}" buildColHeader = (axisHeaders, attrHeaders, h, rowAttrs, colAttrs, node, opts) -> # DF Recurse buildColHeader axisHeaders, attrHeaders, h[chKey], rowAttrs, colAttrs, node, opts for chKey in h.children # Process ah = axisHeaders.ah[h.col] ah.attrHeaders.push h h.node = node.counter h.onClick = collapseCol addClass h.th, "#{classColShow} col#{h.row} colcol#{h.col} #{classColExpanded}" h.th.setAttribute "data-colnode", h.node h.th.colSpan = h.childrenSpan if h.children.length isnt 0 h.th.rowSpan = 2 if h.children.length is 0 and rowAttrs.length isnt 0 h.th.textContent = getHeaderText h, colAttrs, opts.colSubtotalDisplay if h.children.length isnt 0 and h.col < opts.colSubtotalDisplay.disableFrom ah.expandables++ ah.expandedCount += 1 h.th.colSpan++ if not opts.colSubtotalDisplay.hideOnExpand if not opts.colSubtotalDisplay.disableExpandCollapse h.th.onclick = (event) -> event = event || window.event h.onClick axisHeaders, h, opts.colSubtotalDisplay h.sTh = createElement "th", "pvtColLabelFiller #{classColShow} col#{h.row} colcol#{h.col} #{classColExpanded}" h.sTh.setAttribute "data-colnode", h.node h.sTh.rowSpan = colAttrs.length-h.col replaceClass h.sTh, classColShow, classColHide if opts.colSubtotalDisplay.hideOnExpand h[h.children[0]].tr.appendChild h.sTh h.parent?.childrenSpan += h.th.colSpan h.clickStatus = clickStatusExpanded ah.tr.appendChild h.th h.tr = ah.tr attrHeaders.push h node.counter++ buildRowTotalsHeader = (tr, rowAttrs, colAttrs) -> th = createElement "th", "pvtTotalLabel rowTotal", opts.localeStrings.totals, rowspan: if colAttrs.length is 0 then 1 else colAttrs.length + (if rowAttrs.length is 0 then 0 else 1) tr.appendChild th buildRowHeader = (tbody, axisHeaders, attrHeaders, h, rowAttrs, colAttrs, node, opts) -> # DF Recurse buildRowHeader tbody, axisHeaders, attrHeaders, h[chKey], rowAttrs, colAttrs, node, opts for chKey in h.children # Process ah = axisHeaders.ah[h.col] ah.attrHeaders.push h h.node = node.counter h.onClick = collapseRow firstChild = h[h.children[0]] if h.children.length isnt 0 addClass h.th, "#{classRowShow} row#{h.row} rowcol#{h.col} #{classRowExpanded}" h.th.setAttribute "data-rownode", h.node h.th.colSpan = 2 if h.col is rowAttrs.length-1 and colAttrs.length isnt 0 h.th.rowSpan = h.childrenSpan if h.children.length isnt 0 h.th.textContent = getHeaderText h, rowAttrs, opts.rowSubtotalDisplay h.tr = createElement "tr", "row#{h.row}" h.tr.appendChild h.th if h.children.length is 0 tbody.appendChild h.tr else tbody.insertBefore h.tr, firstChild.tr if h.children.length isnt 0 and h.col < opts.rowSubtotalDisplay.disableFrom ++ah.expandedCount ++ah.expandables if not opts.rowSubtotalDisplay.disableExpandCollapse h.th.onclick = (event) -> event = event || window.event h.onClick axisHeaders, h, opts.rowSubtotalDisplay h.sTh = createElement "th", "pvtRowLabelFiller row#{h.row} rowcol#{h.col} #{classRowExpanded} #{classRowShow}" replaceClass h.sTh, classRowShow, classRowHide if opts.rowSubtotalDisplay.hideOnExpand h.sTh.setAttribute "data-rownode", h.node h.sTh.colSpan = rowAttrs.length-(h.col+1) + if colAttrs.length != 0 then 1 else 0 if opts.rowSubtotalDisplay.displayOnTop h.tr.appendChild h.sTh else h.th.rowSpan += 1 # if not opts.rowSubtotalDisplay.hideOnExpand h.sTr = createElement "tr", "row#{h.row}" h.sTr.appendChild h.sTh tbody.appendChild h.sTr h.th.rowSpan++ if h.children.length isnt 0 h.parent?.childrenSpan += h.th.rowSpan h.clickStatus = clickStatusExpanded attrHeaders.push h node.counter++ getTableEventHandlers = (value, rowKey, colKey, rowAttrs, colAttrs, opts) -> return if not opts.table?.eventHandlers eventHandlers = {} for own event, handler of opts.table.eventHandlers filters = {} filters[attr] = colKey[i] for own i, attr of colAttrs when colKey[i]? filters[attr] = rowKey[i] for own i, attr of rowAttrs when rowKey[i]? eventHandlers[event] = (e) -> handler(e, value, filters, pivotData) return eventHandlers buildValues = (tbody, colAttrHeaders, rowAttrHeaders, rowAttrs, colAttrs, opts) -> for rh in rowAttrHeaders when rh.col is rowAttrs.length-1 or (rh.children.length isnt 0 and rh.col < opts.rowSubtotalDisplay.disableFrom) rCls = "pvtVal row#{rh.row} rowcol#{rh.col} #{classRowExpanded}" if rh.children.length > 0 rCls += " pvtRowSubtotal" rCls += if opts.rowSubtotalDisplay.hideOnExpand then " #{classRowHide}" else " #{classRowShow}" else rCls += " #{classRowShow}" tr = if rh.sTr then rh.sTr else rh.tr for ch in colAttrHeaders when ch.col is colAttrs.length-1 or (ch.children.length isnt 0 and ch.col < opts.colSubtotalDisplay.disableFrom) aggregator = tree[rh.flatKey][ch.flatKey] ? {value: (-> null), format: -> ""} val = aggregator.value() cls = " #{rCls} col#{ch.row} colcol#{ch.col} #{classColExpanded}" if ch.children.length > 0 cls += " pvtColSubtotal" cls += if opts.colSubtotalDisplay.hideOnExpand then " #{classColHide}" else " #{classColShow}" else cls += " #{classColShow}" td = createElement "td", cls, aggregator.format(val), "data-value": val "data-rownode": rh.node "data-colnode": ch.node, getTableEventHandlers val, rh.key, ch.key, rowAttrs, colAttrs, opts tr.appendChild td # buildRowTotal totalAggregator = rowTotals[rh.flatKey] val = totalAggregator.value() td = createElement "td", "pvtTotal rowTotal #{rCls}", totalAggregator.format(val), "data-value": val "data-row": "row#{rh.row}" "data-rowcol": "col#{rh.col}" "data-rownode": rh.node, getTableEventHandlers val, rh.key, [], rowAttrs, colAttrs, opts tr.appendChild td buildColTotalsHeader = (rowAttrs, colAttrs) -> tr = createElement "tr" colspan = rowAttrs.length + (if colAttrs.length == 0 then 0 else 1) th = createElement "th", "pvtTotalLabel colTotal", opts.localeStrings.totals, {colspan: colspan} tr.appendChild th return tr buildColTotals = (tr, attrHeaders, rowAttrs, colAttrs, opts) -> for h in attrHeaders when h.col is colAttrs.length-1 or (h.children.length isnt 0 and h.col < opts.colSubtotalDisplay.disableFrom) clsNames = "pvtVal pvtTotal colTotal #{classColExpanded} col#{h.row} colcol#{h.col}" if h.children.length isnt 0 clsNames += " pvtColSubtotal" clsNames += if opts.colSubtotalDisplay.hideOnExpand then " #{classColHide}" else " #{classColShow}" else clsNames += " #{classColShow}" totalAggregator = colTotals[h.flatKey] val = totalAggregator.value() td = createElement "td", clsNames, totalAggregator.format(val), "data-value": val "data-for": "col#{h.col}" "data-colnode": "#{h.node}", getTableEventHandlers val, [], h.key, rowAttrs, colAttrs, opts tr.appendChild td buildGrandTotal = (tbody, tr, rowAttrs, colAttrs, opts) -> totalAggregator = allTotal val = totalAggregator.value() td = createElement "td", "pvtGrandTotal", totalAggregator.format(val), {"data-value": val}, getTableEventHandlers val, [], [], rowAttrs, colAttrs, opts tr.appendChild td tbody.appendChild tr collapseAxisHeaders = (axisHeaders, col, opts) -> collapsible = Math.min axisHeaders.ah.length-2, opts.disableFrom-1 return if col > collapsible for i in [col..collapsible] ah = axisHeaders.ah[i] replaceClass ah.th, classExpanded, classCollapsed ah.th.textContent = " #{arrowCollapsed} #{ah.text}" ah.clickStatus = clickStatusCollapsed ah.onClick = expandAxis adjustAxisHeader = (axisHeaders, col, opts) -> ah = axisHeaders.ah[col] if ah.expandedCount is 0 collapseAxisHeaders axisHeaders, col, opts else if ah.expandedCount is ah.expandables replaceClass ah.th, classCollapsed, classExpanded ah.th.textContent = " #{arrowExpanded} #{ah.text}" ah.clickStatus = clickStatusExpanded ah.onClick = collapseAxis hideChildCol = (ch) -> $(ch.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{ch.node}\"], th[data-colnode=\"#{ch.node}\"]" .removeClass classColShow .addClass classColHide collapseHiddenColSubtotal = (h, opts) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass classColExpanded .addClass classColCollapsed h.th.textContent = " #{arrowCollapsed} #{h.text}" if h.children.length isnt 0 h.th.colSpan = 1 collapseShowColSubtotal = (h, opts) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass classColExpanded .addClass classColCollapsed .removeClass classColHide .addClass classColShow h.th.textContent = " #{arrowCollapsed} #{h.text}" if h.children.length isnt 0 h.th.colSpan = 1 collapseChildCol = (ch, h) -> collapseChildCol ch[chKey], h for chKey in ch.children when hasClass ch[chKey].th, classColShow hideChildCol ch collapseCol = (axisHeaders, h, opts) -> colSpan = h.th.colSpan - 1 collapseChildCol h[chKey], h for chKey in h.children when hasClass h[chKey].th, classColShow if h.col < opts.disableFrom if hasClass h.th, classColHide collapseHiddenColSubtotal h, opts else collapseShowColSubtotal h, opts p = h.parent while p p.th.colSpan -= colSpan p = p.parent h.clickStatus = clickStatusCollapsed h.onClick = expandCol axisHeaders.ah[h.col].expandedCount-- adjustAxisHeader axisHeaders, h.col, opts showChildCol = (ch) -> $(ch.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{ch.node}\"], th[data-colnode=\"#{ch.node}\"]" .removeClass classColHide .addClass classColShow expandHideColSubtotal = (h) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass "#{classColCollapsed} #{classColShow}" .addClass "#{classColExpanded} #{classColHide}" replaceClass h.th, classColHide, classColShow h.th.textContent = " #{arrowExpanded} #{h.text}" expandShowColSubtotal = (h) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass "#{classColCollapsed} #{classColHide}" .addClass "#{classColExpanded} #{classColShow}" h.th.colSpan++ h.th.textContent = " #{arrowExpanded} #{h.text}" expandChildCol = (ch, opts) -> if ch.children.length isnt 0 and opts.hideOnExpand and ch.clickStatus is clickStatusExpanded replaceClass ch.th, classColHide, classColShow else showChildCol ch if ch.sTh and ch.clickStatus is clickStatusExpanded and opts.hideOnExpand replaceClass ch.sTh, classColShow, classColHide expandChildCol ch[chKey], opts for chKey in ch.children if (ch.clickStatus is clickStatusExpanded or ch.col >= opts.disableFrom) expandCol = (axisHeaders, h, opts) -> if h.clickStatus is clickStatusExpanded adjustAxisHeader axisHeaders, h.col, opts return colSpan = 0 for chKey in h.children ch = h[chKey] expandChildCol ch, opts colSpan += ch.th.colSpan h.th.colSpan = colSpan if h.col < opts.disableFrom if opts.hideOnExpand expandHideColSubtotal h --colSpan else expandShowColSubtotal h p = h.parent while p p.th.colSpan += colSpan p = p.parent h.clickStatus = clickStatusExpanded h.onClick = collapseCol axisHeaders.ah[h.col].expandedCount++ adjustAxisHeader axisHeaders, h.col, opts hideChildRow = (ch, opts) -> replaceClass cell, classRowShow, classRowHide for cell in ch.tr.querySelectorAll "th, td" replaceClass cell, classRowShow, classRowHide for cell in ch.sTr.querySelectorAll "th, td" if ch.sTr collapseShowRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowCollapsed} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowExpanded} #{classRowHide}" addClass cell, "#{classRowCollapsed} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowExpanded} #{classRowHide}" addClass cell, "#{classRowCollapsed} #{classRowShow}" collapseChildRow = (ch, h, opts) -> collapseChildRow ch[chKey], h, opts for chKey in ch.children hideChildRow ch, opts collapseRow = (axisHeaders, h, opts) -> collapseChildRow h[chKey], h, opts for chKey in h.children collapseShowRowSubtotal h, opts h.clickStatus = clickStatusCollapsed h.onClick = expandRow axisHeaders.ah[h.col].expandedCount-- adjustAxisHeader axisHeaders, h.col, opts showChildRow = (ch, opts) -> replaceClass cell, classRowHide, classRowShow for cell in ch.tr.querySelectorAll "th, td" replaceClass cell, classRowHide, classRowShow for cell in ch.sTr.querySelectorAll "th, td" if ch.sTr expandShowRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowExpanded} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" expandHideRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowExpanded} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowShow}" addClass cell, "#{classRowExpanded} #{classRowHide}" removeClass h.th, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowShow}" addClass cell, "#{classRowExpanded} #{classRowHide}" expandChildRow = (ch, opts) -> if ch.children.length isnt 0 and opts.hideOnExpand and ch.clickStatus is clickStatusExpanded replaceClass ch.th, classRowHide, classRowShow else showChildRow ch, opts if ch.sTh and ch.clickStatus is clickStatusExpanded and opts.hideOnExpand replaceClass ch.sTh, classRowShow, classRowHide expandChildRow ch[chKey], opts for chKey in ch.children if (ch.clickStatus is clickStatusExpanded or ch.col >= opts.disableFrom) expandRow = (axisHeaders, h, opts) -> if h.clickStatus is clickStatusExpanded adjustAxisHeader axisHeaders, h.col, opts return for chKey in h.children ch = h[chKey] expandChildRow ch, opts if h.children.length isnt 0 if opts.hideOnExpand expandHideRowSubtotal h, opts else expandShowRowSubtotal h, opts h.clickStatus = clickStatusExpanded h.onClick = collapseRow axisHeaders.ah[h.col].expandedCount++ adjustAxisHeader axisHeaders, h.col, opts collapseAxis = (axisHeaders, col, attrs, opts) -> collapsible = Math.min attrs.length-2, opts.disableFrom-1 return if col > collapsible axisHeaders.collapseAttrHeader axisHeaders, h, opts for h in axisHeaders.ah[i].attrHeaders when h.clickStatus is clickStatusExpanded and h.children.length isnt 0 for i in [collapsible..col] by -1 expandAxis = (axisHeaders, col, attrs, opts) -> ah = axisHeaders.ah[col] axisHeaders.expandAttrHeader axisHeaders, h, opts for h in axisHeaders.ah[i].attrHeaders for i in [0..col] # when h.clickStatus is clickStatusCollapsed and h.children.length isnt 0 for i in [0..col] main = (rowAttrs, rowKeys, colAttrs, colKeys) -> rowAttrHeaders = [] colAttrHeaders = [] colKeyHeaders = processKeys colKeys, "pvtColLabel" if colAttrs.length isnt 0 and colKeys.length isnt 0 rowKeyHeaders = processKeys rowKeys, "pvtRowLabel" if rowAttrs.length isnt 0 and rowKeys.length isnt 0 result = createElement "table", "pvtTable", null, {style: "display: none;"} thead = createElement "thead" result.appendChild thead if colAttrs.length isnt 0 colAxisHeaders = buildColAxisHeaders thead, rowAttrs, colAttrs, opts node = counter: 0 buildColHeader colAxisHeaders, colAttrHeaders, colKeyHeaders[chKey], rowAttrs, colAttrs, node, opts for chKey in colKeyHeaders.children buildRowTotalsHeader colAxisHeaders.ah[0].tr, rowAttrs, colAttrs tbody = createElement "tbody" result.appendChild tbody if rowAttrs.length isnt 0 rowAxisHeaders = buildRowAxisHeaders thead, rowAttrs, colAttrs, opts buildRowTotalsHeader rowAxisHeaders.tr, rowAttrs, colAttrs if colAttrs.length is 0 node = counter: 0 buildRowHeader tbody, rowAxisHeaders, rowAttrHeaders, rowKeyHeaders[chKey], rowAttrs, colAttrs, node, opts for chKey in rowKeyHeaders.children buildValues tbody, colAttrHeaders, rowAttrHeaders, rowAttrs, colAttrs, opts tr = buildColTotalsHeader rowAttrs, colAttrs buildColTotals tr, colAttrHeaders, rowAttrs, colAttrs, opts if colAttrs.length > 0 buildGrandTotal tbody, tr, rowAttrs, colAttrs, opts collapseAxis colAxisHeaders, opts.colSubtotalDisplay.collapseAt, colAttrs, opts.colSubtotalDisplay collapseAxis rowAxisHeaders, opts.rowSubtotalDisplay.collapseAt, rowAttrs, opts.rowSubtotalDisplay result.setAttribute "data-numrows", rowKeys.length result.setAttribute "data-numcols", colKeys.length result.style.display = "" return result return main rowAttrs, rowKeys, colAttrs, colKeys $.pivotUtilities.subtotal_renderers = "Table With Subtotal": (pvtData, opts) -> SubtotalRenderer pvtData, opts "Table With Subtotal Bar Chart": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).barchart() "Table With Subtotal Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "heatmap", opts "Table With Subtotal Row Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "rowheatmap", opts "Table With Subtotal Col Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "colheatmap", opts # # Aggregators # usFmtPct = $.pivotUtilities.numberFormat digitsAfterDecimal:1, scaler: 100, suffix: "%" aggregatorTemplates = $.pivotUtilities.aggregatorTemplates; subtotalAggregatorTemplates = fractionOf: (wrapped, type="row", formatter=usFmtPct) -> (x...) -> (data, rowKey, colKey) -> rowKey = [] if typeof rowKey is "undefined" colKey = [] if typeof colKey is "undefined" selector: {row: [rowKey.slice(0, -1),[]], col: [[], colKey.slice(0, -1)]}[type] inner: wrapped(x...)(data, rowKey, colKey) push: (record) -> @inner.push record format: formatter value: -> @inner.value() / data.getAggregator(@selector...).inner.value() numInputs: wrapped(x...)().numInputs $.pivotUtilities.subtotalAggregatorTemplates = subtotalAggregatorTemplates $.pivotUtilities.subtotal_aggregators = do (tpl = aggregatorTemplates, sTpl = subtotalAggregatorTemplates) -> "Sum As Fraction Of Parent Row": sTpl.fractionOf(tpl.sum(), "row", usFmtPct) "Sum As Fraction Of Parent Column": sTpl.fractionOf(tpl.sum(), "col", usFmtPct) "Count As Fraction Of Parent Row": sTpl.fractionOf(tpl.count(), "row", usFmtPct) "Count As Fraction Of Parent Column": sTpl.fractionOf(tpl.count(), "col", usFmtPct)
207518
callWithJQuery = (pivotModule) -> if typeof exports is "object" and typeof module is "object" # CommonJS pivotModule require("jquery") else if typeof define is "function" and define.amd # AMD define ["jquery"], pivotModule # Plain browser env else pivotModule jQuery callWithJQuery ($) -> class SubtotalPivotData extends $.pivotUtilities.PivotData constructor: (input, opts) -> super input, opts processKey = (record, totals, keys, attrs, getAggregator) -> key = [] addKey = false for attr in attrs key.push record[attr] ? "null" flatKey = key.<KEY> String.from<KEY>(0) if not totals[flatKey] totals[flatKey] = getAggregator key.slice() addKey = true totals[flatKey].push record keys.push key if addKey return key processRecord: (record) -> #this code is called in a tight loop rowKey = [] colKey = [] @allTotal.push record rowKey = processKey record, @rowTotals, @rowKeys, @rowAttrs, (key) => return @aggregator this, key, [] colKey = processKey record, @colTotals, @colKeys, @colAttrs, (key) => return @aggregator this, [], key m = rowKey.length-1 n = colKey.length-1 return if m < 0 or n < 0 for i in [0..m] fRowKey = rowKey.slice(0, i+1) flatRowKey = fRowKey.join String.fromCharCode(0) @tree[flatRowKey] = {} if not @tree[flatRowKey] for j in [0..n] fColKey = colKey.slice 0, j+1 flatColKey = fColKey.join String.fromCharCode(0) @tree[flatRowKey][flatColKey] = @aggregator this, fRowKey, fColKey if not @tree[flatRowKey][flatColKey] @tree[flatRowKey][flatColKey].push record $.pivotUtilities.SubtotalPivotData = SubtotalPivotData SubtotalRenderer = (pivotData, opts) -> defaults = table: clickCallback: null localeStrings: totals: "Totals", subtotalOf: "Subtotal of" arrowCollapsed: "\u25B6" arrowExpanded: "\u25E2" rowSubtotalDisplay: displayOnTop: true disableFrom: 99999 collapseAt: 99999 hideOnExpand: false disableExpandCollapse: false colSubtotalDisplay: displayOnTop: true disableFrom: 99999 collapseAt: 99999 hideOnExpand: false disableExpandCollapse: false opts = $.extend true, {}, defaults, opts opts.rowSubtotalDisplay.disableFrom = 0 if opts.rowSubtotalDisplay.disableSubtotal opts.rowSubtotalDisplay.disableFrom = opts.rowSubtotalDisplay.disableAfter+1 if typeof opts.rowSubtotalDisplay.disableAfter isnt 'undefined' and opts.rowSubtotalDisplay.disableAfter isnt null opts.rowSubtotalDisplay.collapseAt = opts.collapseRowsAt if typeof opts.rowSubtotalDisplay.collapseAt isnt 'undefined' and opts.collapseRowsAt isnt null opts.colSubtotalDisplay.disableFrom = 0 if opts.colSubtotalDisplay.disableSubtotal opts.colSubtotalDisplay.disableFrom = opts.colSubtotalDisplay.disableAfter+1 if typeof opts.colSubtotalDisplay.disableAfter isnt 'undefined' and opts.colSubtotalDisplay.disableAfter isnt null opts.colSubtotalDisplay.collapseAt = opts.collapseColsAt if typeof opts.colSubtotalDisplay.collapseAt isnt 'undefined' and opts.collapseColsAt isnt null colAttrs = pivotData.colAttrs rowAttrs = pivotData.rowAttrs rowKeys = pivotData.getRowKeys() colKeys = pivotData.getColKeys() tree = pivotData.tree rowTotals = pivotData.rowTotals colTotals = pivotData.colTotals allTotal = pivotData.allTotal classRowHide = "rowhide" classRowShow = "rowshow" classColHide = "colhide" classColShow = "colshow" clickStatusExpanded = "expanded" clickStatusCollapsed = "collapsed" classExpanded = "expanded" classCollapsed = "collapsed" classRowExpanded = "rowexpanded" classRowCollapsed = "rowcollapsed" classColExpanded = "colexpanded" classColCollapsed = "colcollapsed" arrowExpanded = opts.arrowExpanded arrowCollapsed = opts.arrowCollapsed # Based on http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript -- Begin hasClass = (element, className) -> regExp = new RegExp "(?:^|\\s)" + className + "(?!\\S)", "g" element.className.match(regExp) isnt null removeClass = (element, className) -> for name in className.split " " regExp = new RegExp "(?:^|\\s)" + name + "(?!\\S)", "g" element.className = element.className.replace regExp, '' addClass = (element, className) -> for name in className.split " " element.className += (" " + name) if not hasClass element, name replaceClass = (element, replaceClassName, byClassName) -> removeClass element, replaceClassName addClass element, byClassName # Based on http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript -- End createElement = (elementType, className, textContent, attributes, eventHandlers) -> e = document.createElement elementType e.className = className if className? e.textContent = textContent if textContent? e.setAttribute attr, val for own attr, val of attributes if attributes? e.addEventListener event, handler for own event, handler of eventHandlers if eventHandlers? return e setAttributes = (e, attrs) -> e.setAttribute a, v for own a, v of attrs processKeys = (keysArr, className, opts) -> lastIdx = keysArr[0].length-1 headers = children: [] row = 0 keysArr.reduce( (val0, k0) => col = 0 k0.reduce( (acc, curVal, curIdx, arr) => if not acc[curVal] key = k0.slice 0, col+1 acc[curVal] = row: row col: col descendants: 0 children: [] text: curVal key: key flatKey: key.join String.fromCharCode(0) firstLeaf: null leaves: 0 parent: if col isnt 0 then acc else null th: createElement "th", className, curVal childrenSpan: 0 acc.children.push curVal if col > 0 acc.descendants++ col++ if curIdx == lastIdx node = headers for i in [0..lastIdx-1] when lastIdx > 0 node[k0[i]].leaves++ if not node[k0[i]].firstLeaf node[k0[i]].firstLeaf = acc[curVal] node = node[k0[i]] return headers return acc[curVal] headers) row++ return headers headers) return headers buildAxisHeader = (axisHeaders, col, attrs, opts) -> ah = text: attrs[col] expandedCount: 0 expandables: 0 attrHeaders: [] clickStatus: clickStatusExpanded onClick: collapseAxis arrow = "#{arrowExpanded} " hClass = classExpanded if col >= opts.collapseAt arrow = "#{arrowCollapsed} " hClass = classCollapsed ah.clickStatus = clickStatusCollapsed ah.onClick = expandAxis if col == attrs.length-1 or col >= opts.disableFrom or opts.disableExpandCollapse arrow = "" ah.th = createElement "th", "pvtAxisLabel #{hClass}", "#{arrow}#{ah.text}" if col < attrs.length-1 and col < opts.disableFrom and not opts.disableExpandCollapse ah.th.onclick = (event) -> event = event || window.event ah.onClick axisHeaders, col, attrs, opts axisHeaders.ah.push ah return ah buildColAxisHeaders = (thead, rowAttrs, colAttrs, opts) -> axisHeaders = collapseAttrHeader: collapseCol expandAttrHeader: expandCol ah: [] for attr, col in colAttrs ah = buildAxisHeader axisHeaders, col, colAttrs, opts.colSubtotalDisplay ah.tr = createElement "tr" ah.tr.appendChild createElement "th", null, null, {colspan: rowAttrs.length, rowspan: colAttrs.length} if col is 0 and rowAttrs.length isnt 0 ah.tr.appendChild ah.th thead.appendChild ah.tr return axisHeaders buildRowAxisHeaders = (thead, rowAttrs, colAttrs, opts) -> axisHeaders = collapseAttrHeader: collapseRow expandAttrHeader: expandRow ah: [] tr: createElement "tr" for col in [0..rowAttrs.length-1] ah = buildAxisHeader axisHeaders, col, rowAttrs, opts.rowSubtotalDisplay axisHeaders.tr.appendChild ah.th if colAttrs.length != 0 th = createElement "th" axisHeaders.tr.appendChild th thead.appendChild axisHeaders.tr return axisHeaders getHeaderText = (h, attrs, opts) -> arrow = " #{arrowExpanded} " arrow = "" if h.col == attrs.length-1 or h.col >= opts.disableFrom or opts.disableExpandCollapse or h.children.length is 0 return "#{arrow}#{h.text}" buildColHeader = (axisHeaders, attrHeaders, h, rowAttrs, colAttrs, node, opts) -> # DF Recurse buildColHeader axisHeaders, attrHeaders, h[chKey], rowAttrs, colAttrs, node, opts for chKey in h.children # Process ah = axisHeaders.ah[h.col] ah.attrHeaders.push h h.node = node.counter h.onClick = collapseCol addClass h.th, "#{classColShow} col#{h.row} colcol#{h.col} #{classColExpanded}" h.th.setAttribute "data-colnode", h.node h.th.colSpan = h.childrenSpan if h.children.length isnt 0 h.th.rowSpan = 2 if h.children.length is 0 and rowAttrs.length isnt 0 h.th.textContent = getHeaderText h, colAttrs, opts.colSubtotalDisplay if h.children.length isnt 0 and h.col < opts.colSubtotalDisplay.disableFrom ah.expandables++ ah.expandedCount += 1 h.th.colSpan++ if not opts.colSubtotalDisplay.hideOnExpand if not opts.colSubtotalDisplay.disableExpandCollapse h.th.onclick = (event) -> event = event || window.event h.onClick axisHeaders, h, opts.colSubtotalDisplay h.sTh = createElement "th", "pvtColLabelFiller #{classColShow} col#{h.row} colcol#{h.col} #{classColExpanded}" h.sTh.setAttribute "data-colnode", h.node h.sTh.rowSpan = colAttrs.length-h.col replaceClass h.sTh, classColShow, classColHide if opts.colSubtotalDisplay.hideOnExpand h[h.children[0]].tr.appendChild h.sTh h.parent?.childrenSpan += h.th.colSpan h.clickStatus = clickStatusExpanded ah.tr.appendChild h.th h.tr = ah.tr attrHeaders.push h node.counter++ buildRowTotalsHeader = (tr, rowAttrs, colAttrs) -> th = createElement "th", "pvtTotalLabel rowTotal", opts.localeStrings.totals, rowspan: if colAttrs.length is 0 then 1 else colAttrs.length + (if rowAttrs.length is 0 then 0 else 1) tr.appendChild th buildRowHeader = (tbody, axisHeaders, attrHeaders, h, rowAttrs, colAttrs, node, opts) -> # DF Recurse buildRowHeader tbody, axisHeaders, attrHeaders, h[chKey], rowAttrs, colAttrs, node, opts for chKey in h.children # Process ah = axisHeaders.ah[h.col] ah.attrHeaders.push h h.node = node.counter h.onClick = collapseRow firstChild = h[h.children[0]] if h.children.length isnt 0 addClass h.th, "#{classRowShow} row#{h.row} rowcol#{h.col} #{classRowExpanded}" h.th.setAttribute "data-rownode", h.node h.th.colSpan = 2 if h.col is rowAttrs.length-1 and colAttrs.length isnt 0 h.th.rowSpan = h.childrenSpan if h.children.length isnt 0 h.th.textContent = getHeaderText h, rowAttrs, opts.rowSubtotalDisplay h.tr = createElement "tr", "row#{h.row}" h.tr.appendChild h.th if h.children.length is 0 tbody.appendChild h.tr else tbody.insertBefore h.tr, firstChild.tr if h.children.length isnt 0 and h.col < opts.rowSubtotalDisplay.disableFrom ++ah.expandedCount ++ah.expandables if not opts.rowSubtotalDisplay.disableExpandCollapse h.th.onclick = (event) -> event = event || window.event h.onClick axisHeaders, h, opts.rowSubtotalDisplay h.sTh = createElement "th", "pvtRowLabelFiller row#{h.row} rowcol#{h.col} #{classRowExpanded} #{classRowShow}" replaceClass h.sTh, classRowShow, classRowHide if opts.rowSubtotalDisplay.hideOnExpand h.sTh.setAttribute "data-rownode", h.node h.sTh.colSpan = rowAttrs.length-(h.col+1) + if colAttrs.length != 0 then 1 else 0 if opts.rowSubtotalDisplay.displayOnTop h.tr.appendChild h.sTh else h.th.rowSpan += 1 # if not opts.rowSubtotalDisplay.hideOnExpand h.sTr = createElement "tr", "row#{h.row}" h.sTr.appendChild h.sTh tbody.appendChild h.sTr h.th.rowSpan++ if h.children.length isnt 0 h.parent?.childrenSpan += h.th.rowSpan h.clickStatus = clickStatusExpanded attrHeaders.push h node.counter++ getTableEventHandlers = (value, rowKey, colKey, rowAttrs, colAttrs, opts) -> return if not opts.table?.eventHandlers eventHandlers = {} for own event, handler of opts.table.eventHandlers filters = {} filters[attr] = colKey[i] for own i, attr of colAttrs when colKey[i]? filters[attr] = rowKey[i] for own i, attr of rowAttrs when rowKey[i]? eventHandlers[event] = (e) -> handler(e, value, filters, pivotData) return eventHandlers buildValues = (tbody, colAttrHeaders, rowAttrHeaders, rowAttrs, colAttrs, opts) -> for rh in rowAttrHeaders when rh.col is rowAttrs.length-1 or (rh.children.length isnt 0 and rh.col < opts.rowSubtotalDisplay.disableFrom) rCls = "pvtVal row#{rh.row} rowcol#{rh.col} #{classRowExpanded}" if rh.children.length > 0 rCls += " pvtRowSubtotal" rCls += if opts.rowSubtotalDisplay.hideOnExpand then " #{classRowHide}" else " #{classRowShow}" else rCls += " #{classRowShow}" tr = if rh.sTr then rh.sTr else rh.tr for ch in colAttrHeaders when ch.col is colAttrs.length-1 or (ch.children.length isnt 0 and ch.col < opts.colSubtotalDisplay.disableFrom) aggregator = tree[rh.flatKey][ch.flatKey] ? {value: (-> null), format: -> ""} val = aggregator.value() cls = " #{rCls} col#{ch.row} colcol#{ch.col} #{classColExpanded}" if ch.children.length > 0 cls += " pvtColSubtotal" cls += if opts.colSubtotalDisplay.hideOnExpand then " #{classColHide}" else " #{classColShow}" else cls += " #{classColShow}" td = createElement "td", cls, aggregator.format(val), "data-value": val "data-rownode": rh.node "data-colnode": ch.node, getTableEventHandlers val, rh.key, ch.key, rowAttrs, colAttrs, opts tr.appendChild td # buildRowTotal totalAggregator = rowTotals[rh.flatKey] val = totalAggregator.value() td = createElement "td", "pvtTotal rowTotal #{rCls}", totalAggregator.format(val), "data-value": val "data-row": "row#{rh.row}" "data-rowcol": "col#{rh.col}" "data-rownode": rh.node, getTableEventHandlers val, rh.key, [], rowAttrs, colAttrs, opts tr.appendChild td buildColTotalsHeader = (rowAttrs, colAttrs) -> tr = createElement "tr" colspan = rowAttrs.length + (if colAttrs.length == 0 then 0 else 1) th = createElement "th", "pvtTotalLabel colTotal", opts.localeStrings.totals, {colspan: colspan} tr.appendChild th return tr buildColTotals = (tr, attrHeaders, rowAttrs, colAttrs, opts) -> for h in attrHeaders when h.col is colAttrs.length-1 or (h.children.length isnt 0 and h.col < opts.colSubtotalDisplay.disableFrom) clsNames = "pvtVal pvtTotal colTotal #{classColExpanded} col#{h.row} colcol#{h.col}" if h.children.length isnt 0 clsNames += " pvtColSubtotal" clsNames += if opts.colSubtotalDisplay.hideOnExpand then " #{classColHide}" else " #{classColShow}" else clsNames += " #{classColShow}" totalAggregator = colTotals[h.flatKey] val = totalAggregator.value() td = createElement "td", clsNames, totalAggregator.format(val), "data-value": val "data-for": "col#{h.col}" "data-colnode": "#{h.node}", getTableEventHandlers val, [], h.key, rowAttrs, colAttrs, opts tr.appendChild td buildGrandTotal = (tbody, tr, rowAttrs, colAttrs, opts) -> totalAggregator = allTotal val = totalAggregator.value() td = createElement "td", "pvtGrandTotal", totalAggregator.format(val), {"data-value": val}, getTableEventHandlers val, [], [], rowAttrs, colAttrs, opts tr.appendChild td tbody.appendChild tr collapseAxisHeaders = (axisHeaders, col, opts) -> collapsible = Math.min axisHeaders.ah.length-2, opts.disableFrom-1 return if col > collapsible for i in [col..collapsible] ah = axisHeaders.ah[i] replaceClass ah.th, classExpanded, classCollapsed ah.th.textContent = " #{arrowCollapsed} #{ah.text}" ah.clickStatus = clickStatusCollapsed ah.onClick = expandAxis adjustAxisHeader = (axisHeaders, col, opts) -> ah = axisHeaders.ah[col] if ah.expandedCount is 0 collapseAxisHeaders axisHeaders, col, opts else if ah.expandedCount is ah.expandables replaceClass ah.th, classCollapsed, classExpanded ah.th.textContent = " #{arrowExpanded} #{ah.text}" ah.clickStatus = clickStatusExpanded ah.onClick = collapseAxis hideChildCol = (ch) -> $(ch.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{ch.node}\"], th[data-colnode=\"#{ch.node}\"]" .removeClass classColShow .addClass classColHide collapseHiddenColSubtotal = (h, opts) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass classColExpanded .addClass classColCollapsed h.th.textContent = " #{arrowCollapsed} #{h.text}" if h.children.length isnt 0 h.th.colSpan = 1 collapseShowColSubtotal = (h, opts) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass classColExpanded .addClass classColCollapsed .removeClass classColHide .addClass classColShow h.th.textContent = " #{arrowCollapsed} #{h.text}" if h.children.length isnt 0 h.th.colSpan = 1 collapseChildCol = (ch, h) -> collapseChildCol ch[chKey], h for chKey in ch.children when hasClass ch[chKey].th, classColShow hideChildCol ch collapseCol = (axisHeaders, h, opts) -> colSpan = h.th.colSpan - 1 collapseChildCol h[chKey], h for chKey in h.children when hasClass h[chKey].th, classColShow if h.col < opts.disableFrom if hasClass h.th, classColHide collapseHiddenColSubtotal h, opts else collapseShowColSubtotal h, opts p = h.parent while p p.th.colSpan -= colSpan p = p.parent h.clickStatus = clickStatusCollapsed h.onClick = expandCol axisHeaders.ah[h.col].expandedCount-- adjustAxisHeader axisHeaders, h.col, opts showChildCol = (ch) -> $(ch.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{ch.node}\"], th[data-colnode=\"#{ch.node}\"]" .removeClass classColHide .addClass classColShow expandHideColSubtotal = (h) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass "#{classColCollapsed} #{classColShow}" .addClass "#{classColExpanded} #{classColHide}" replaceClass h.th, classColHide, classColShow h.th.textContent = " #{arrowExpanded} #{h.text}" expandShowColSubtotal = (h) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass "#{classColCollapsed} #{classColHide}" .addClass "#{classColExpanded} #{classColShow}" h.th.colSpan++ h.th.textContent = " #{arrowExpanded} #{h.text}" expandChildCol = (ch, opts) -> if ch.children.length isnt 0 and opts.hideOnExpand and ch.clickStatus is clickStatusExpanded replaceClass ch.th, classColHide, classColShow else showChildCol ch if ch.sTh and ch.clickStatus is clickStatusExpanded and opts.hideOnExpand replaceClass ch.sTh, classColShow, classColHide expandChildCol ch[chKey], opts for chKey in ch.children if (ch.clickStatus is clickStatusExpanded or ch.col >= opts.disableFrom) expandCol = (axisHeaders, h, opts) -> if h.clickStatus is clickStatusExpanded adjustAxisHeader axisHeaders, h.col, opts return colSpan = 0 for chKey in h.children ch = h[chKey] expandChildCol ch, opts colSpan += ch.th.colSpan h.th.colSpan = colSpan if h.col < opts.disableFrom if opts.hideOnExpand expandHideColSubtotal h --colSpan else expandShowColSubtotal h p = h.parent while p p.th.colSpan += colSpan p = p.parent h.clickStatus = clickStatusExpanded h.onClick = collapseCol axisHeaders.ah[h.col].expandedCount++ adjustAxisHeader axisHeaders, h.col, opts hideChildRow = (ch, opts) -> replaceClass cell, classRowShow, classRowHide for cell in ch.tr.querySelectorAll "th, td" replaceClass cell, classRowShow, classRowHide for cell in ch.sTr.querySelectorAll "th, td" if ch.sTr collapseShowRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowCollapsed} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowExpanded} #{classRowHide}" addClass cell, "#{classRowCollapsed} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowExpanded} #{classRowHide}" addClass cell, "#{classRowCollapsed} #{classRowShow}" collapseChildRow = (ch, h, opts) -> collapseChildRow ch[chKey], h, opts for chKey in ch.children hideChildRow ch, opts collapseRow = (axisHeaders, h, opts) -> collapseChildRow h[chKey], h, opts for chKey in h.children collapseShowRowSubtotal h, opts h.clickStatus = clickStatusCollapsed h.onClick = expandRow axisHeaders.ah[h.col].expandedCount-- adjustAxisHeader axisHeaders, h.col, opts showChildRow = (ch, opts) -> replaceClass cell, classRowHide, classRowShow for cell in ch.tr.querySelectorAll "th, td" replaceClass cell, classRowHide, classRowShow for cell in ch.sTr.querySelectorAll "th, td" if ch.sTr expandShowRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowExpanded} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" expandHideRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowExpanded} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowShow}" addClass cell, "#{classRowExpanded} #{classRowHide}" removeClass h.th, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowShow}" addClass cell, "#{classRowExpanded} #{classRowHide}" expandChildRow = (ch, opts) -> if ch.children.length isnt 0 and opts.hideOnExpand and ch.clickStatus is clickStatusExpanded replaceClass ch.th, classRowHide, classRowShow else showChildRow ch, opts if ch.sTh and ch.clickStatus is clickStatusExpanded and opts.hideOnExpand replaceClass ch.sTh, classRowShow, classRowHide expandChildRow ch[chKey], opts for chKey in ch.children if (ch.clickStatus is clickStatusExpanded or ch.col >= opts.disableFrom) expandRow = (axisHeaders, h, opts) -> if h.clickStatus is clickStatusExpanded adjustAxisHeader axisHeaders, h.col, opts return for chKey in h.children ch = h[chKey] expandChildRow ch, opts if h.children.length isnt 0 if opts.hideOnExpand expandHideRowSubtotal h, opts else expandShowRowSubtotal h, opts h.clickStatus = clickStatusExpanded h.onClick = collapseRow axisHeaders.ah[h.col].expandedCount++ adjustAxisHeader axisHeaders, h.col, opts collapseAxis = (axisHeaders, col, attrs, opts) -> collapsible = Math.min attrs.length-2, opts.disableFrom-1 return if col > collapsible axisHeaders.collapseAttrHeader axisHeaders, h, opts for h in axisHeaders.ah[i].attrHeaders when h.clickStatus is clickStatusExpanded and h.children.length isnt 0 for i in [collapsible..col] by -1 expandAxis = (axisHeaders, col, attrs, opts) -> ah = axisHeaders.ah[col] axisHeaders.expandAttrHeader axisHeaders, h, opts for h in axisHeaders.ah[i].attrHeaders for i in [0..col] # when h.clickStatus is clickStatusCollapsed and h.children.length isnt 0 for i in [0..col] main = (rowAttrs, rowKeys, colAttrs, colKeys) -> rowAttrHeaders = [] colAttrHeaders = [] colKeyHeaders = processKeys colKeys, "pvtColLabel" if colAttrs.length isnt 0 and colKeys.length isnt 0 rowKeyHeaders = processKeys rowKeys, "pvtRowLabel" if rowAttrs.length isnt 0 and rowKeys.length isnt 0 result = createElement "table", "pvtTable", null, {style: "display: none;"} thead = createElement "thead" result.appendChild thead if colAttrs.length isnt 0 colAxisHeaders = buildColAxisHeaders thead, rowAttrs, colAttrs, opts node = counter: 0 buildColHeader colAxisHeaders, colAttrHeaders, colKeyHeaders[chKey], rowAttrs, colAttrs, node, opts for chKey in colKeyHeaders.children buildRowTotalsHeader colAxisHeaders.ah[0].tr, rowAttrs, colAttrs tbody = createElement "tbody" result.appendChild tbody if rowAttrs.length isnt 0 rowAxisHeaders = buildRowAxisHeaders thead, rowAttrs, colAttrs, opts buildRowTotalsHeader rowAxisHeaders.tr, rowAttrs, colAttrs if colAttrs.length is 0 node = counter: 0 buildRowHeader tbody, rowAxisHeaders, rowAttrHeaders, rowKeyHeaders[chKey], rowAttrs, colAttrs, node, opts for chKey in rowKeyHeaders.children buildValues tbody, colAttrHeaders, rowAttrHeaders, rowAttrs, colAttrs, opts tr = buildColTotalsHeader rowAttrs, colAttrs buildColTotals tr, colAttrHeaders, rowAttrs, colAttrs, opts if colAttrs.length > 0 buildGrandTotal tbody, tr, rowAttrs, colAttrs, opts collapseAxis colAxisHeaders, opts.colSubtotalDisplay.collapseAt, colAttrs, opts.colSubtotalDisplay collapseAxis rowAxisHeaders, opts.rowSubtotalDisplay.collapseAt, rowAttrs, opts.rowSubtotalDisplay result.setAttribute "data-numrows", rowKeys.length result.setAttribute "data-numcols", colKeys.length result.style.display = "" return result return main rowAttrs, rowKeys, colAttrs, colKeys $.pivotUtilities.subtotal_renderers = "Table With Subtotal": (pvtData, opts) -> SubtotalRenderer pvtData, opts "Table With Subtotal Bar Chart": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).barchart() "Table With Subtotal Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "heatmap", opts "Table With Subtotal Row Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "rowheatmap", opts "Table With Subtotal Col Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "colheatmap", opts # # Aggregators # usFmtPct = $.pivotUtilities.numberFormat digitsAfterDecimal:1, scaler: 100, suffix: "%" aggregatorTemplates = $.pivotUtilities.aggregatorTemplates; subtotalAggregatorTemplates = fractionOf: (wrapped, type="row", formatter=usFmtPct) -> (x...) -> (data, rowKey, colKey) -> rowKey = [] if typeof rowKey is "undefined" colKey = [] if typeof colKey is "undefined" selector: {row: [rowKey.slice(0, -1),[]], col: [[], colKey.slice(0, -1)]}[type] inner: wrapped(x...)(data, rowKey, colKey) push: (record) -> @inner.push record format: formatter value: -> @inner.value() / data.getAggregator(@selector...).inner.value() numInputs: wrapped(x...)().numInputs $.pivotUtilities.subtotalAggregatorTemplates = subtotalAggregatorTemplates $.pivotUtilities.subtotal_aggregators = do (tpl = aggregatorTemplates, sTpl = subtotalAggregatorTemplates) -> "Sum As Fraction Of Parent Row": sTpl.fractionOf(tpl.sum(), "row", usFmtPct) "Sum As Fraction Of Parent Column": sTpl.fractionOf(tpl.sum(), "col", usFmtPct) "Count As Fraction Of Parent Row": sTpl.fractionOf(tpl.count(), "row", usFmtPct) "Count As Fraction Of Parent Column": sTpl.fractionOf(tpl.count(), "col", usFmtPct)
true
callWithJQuery = (pivotModule) -> if typeof exports is "object" and typeof module is "object" # CommonJS pivotModule require("jquery") else if typeof define is "function" and define.amd # AMD define ["jquery"], pivotModule # Plain browser env else pivotModule jQuery callWithJQuery ($) -> class SubtotalPivotData extends $.pivotUtilities.PivotData constructor: (input, opts) -> super input, opts processKey = (record, totals, keys, attrs, getAggregator) -> key = [] addKey = false for attr in attrs key.push record[attr] ? "null" flatKey = key.PI:KEY:<KEY>END_PI String.fromPI:KEY:<KEY>END_PI(0) if not totals[flatKey] totals[flatKey] = getAggregator key.slice() addKey = true totals[flatKey].push record keys.push key if addKey return key processRecord: (record) -> #this code is called in a tight loop rowKey = [] colKey = [] @allTotal.push record rowKey = processKey record, @rowTotals, @rowKeys, @rowAttrs, (key) => return @aggregator this, key, [] colKey = processKey record, @colTotals, @colKeys, @colAttrs, (key) => return @aggregator this, [], key m = rowKey.length-1 n = colKey.length-1 return if m < 0 or n < 0 for i in [0..m] fRowKey = rowKey.slice(0, i+1) flatRowKey = fRowKey.join String.fromCharCode(0) @tree[flatRowKey] = {} if not @tree[flatRowKey] for j in [0..n] fColKey = colKey.slice 0, j+1 flatColKey = fColKey.join String.fromCharCode(0) @tree[flatRowKey][flatColKey] = @aggregator this, fRowKey, fColKey if not @tree[flatRowKey][flatColKey] @tree[flatRowKey][flatColKey].push record $.pivotUtilities.SubtotalPivotData = SubtotalPivotData SubtotalRenderer = (pivotData, opts) -> defaults = table: clickCallback: null localeStrings: totals: "Totals", subtotalOf: "Subtotal of" arrowCollapsed: "\u25B6" arrowExpanded: "\u25E2" rowSubtotalDisplay: displayOnTop: true disableFrom: 99999 collapseAt: 99999 hideOnExpand: false disableExpandCollapse: false colSubtotalDisplay: displayOnTop: true disableFrom: 99999 collapseAt: 99999 hideOnExpand: false disableExpandCollapse: false opts = $.extend true, {}, defaults, opts opts.rowSubtotalDisplay.disableFrom = 0 if opts.rowSubtotalDisplay.disableSubtotal opts.rowSubtotalDisplay.disableFrom = opts.rowSubtotalDisplay.disableAfter+1 if typeof opts.rowSubtotalDisplay.disableAfter isnt 'undefined' and opts.rowSubtotalDisplay.disableAfter isnt null opts.rowSubtotalDisplay.collapseAt = opts.collapseRowsAt if typeof opts.rowSubtotalDisplay.collapseAt isnt 'undefined' and opts.collapseRowsAt isnt null opts.colSubtotalDisplay.disableFrom = 0 if opts.colSubtotalDisplay.disableSubtotal opts.colSubtotalDisplay.disableFrom = opts.colSubtotalDisplay.disableAfter+1 if typeof opts.colSubtotalDisplay.disableAfter isnt 'undefined' and opts.colSubtotalDisplay.disableAfter isnt null opts.colSubtotalDisplay.collapseAt = opts.collapseColsAt if typeof opts.colSubtotalDisplay.collapseAt isnt 'undefined' and opts.collapseColsAt isnt null colAttrs = pivotData.colAttrs rowAttrs = pivotData.rowAttrs rowKeys = pivotData.getRowKeys() colKeys = pivotData.getColKeys() tree = pivotData.tree rowTotals = pivotData.rowTotals colTotals = pivotData.colTotals allTotal = pivotData.allTotal classRowHide = "rowhide" classRowShow = "rowshow" classColHide = "colhide" classColShow = "colshow" clickStatusExpanded = "expanded" clickStatusCollapsed = "collapsed" classExpanded = "expanded" classCollapsed = "collapsed" classRowExpanded = "rowexpanded" classRowCollapsed = "rowcollapsed" classColExpanded = "colexpanded" classColCollapsed = "colcollapsed" arrowExpanded = opts.arrowExpanded arrowCollapsed = opts.arrowCollapsed # Based on http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript -- Begin hasClass = (element, className) -> regExp = new RegExp "(?:^|\\s)" + className + "(?!\\S)", "g" element.className.match(regExp) isnt null removeClass = (element, className) -> for name in className.split " " regExp = new RegExp "(?:^|\\s)" + name + "(?!\\S)", "g" element.className = element.className.replace regExp, '' addClass = (element, className) -> for name in className.split " " element.className += (" " + name) if not hasClass element, name replaceClass = (element, replaceClassName, byClassName) -> removeClass element, replaceClassName addClass element, byClassName # Based on http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript -- End createElement = (elementType, className, textContent, attributes, eventHandlers) -> e = document.createElement elementType e.className = className if className? e.textContent = textContent if textContent? e.setAttribute attr, val for own attr, val of attributes if attributes? e.addEventListener event, handler for own event, handler of eventHandlers if eventHandlers? return e setAttributes = (e, attrs) -> e.setAttribute a, v for own a, v of attrs processKeys = (keysArr, className, opts) -> lastIdx = keysArr[0].length-1 headers = children: [] row = 0 keysArr.reduce( (val0, k0) => col = 0 k0.reduce( (acc, curVal, curIdx, arr) => if not acc[curVal] key = k0.slice 0, col+1 acc[curVal] = row: row col: col descendants: 0 children: [] text: curVal key: key flatKey: key.join String.fromCharCode(0) firstLeaf: null leaves: 0 parent: if col isnt 0 then acc else null th: createElement "th", className, curVal childrenSpan: 0 acc.children.push curVal if col > 0 acc.descendants++ col++ if curIdx == lastIdx node = headers for i in [0..lastIdx-1] when lastIdx > 0 node[k0[i]].leaves++ if not node[k0[i]].firstLeaf node[k0[i]].firstLeaf = acc[curVal] node = node[k0[i]] return headers return acc[curVal] headers) row++ return headers headers) return headers buildAxisHeader = (axisHeaders, col, attrs, opts) -> ah = text: attrs[col] expandedCount: 0 expandables: 0 attrHeaders: [] clickStatus: clickStatusExpanded onClick: collapseAxis arrow = "#{arrowExpanded} " hClass = classExpanded if col >= opts.collapseAt arrow = "#{arrowCollapsed} " hClass = classCollapsed ah.clickStatus = clickStatusCollapsed ah.onClick = expandAxis if col == attrs.length-1 or col >= opts.disableFrom or opts.disableExpandCollapse arrow = "" ah.th = createElement "th", "pvtAxisLabel #{hClass}", "#{arrow}#{ah.text}" if col < attrs.length-1 and col < opts.disableFrom and not opts.disableExpandCollapse ah.th.onclick = (event) -> event = event || window.event ah.onClick axisHeaders, col, attrs, opts axisHeaders.ah.push ah return ah buildColAxisHeaders = (thead, rowAttrs, colAttrs, opts) -> axisHeaders = collapseAttrHeader: collapseCol expandAttrHeader: expandCol ah: [] for attr, col in colAttrs ah = buildAxisHeader axisHeaders, col, colAttrs, opts.colSubtotalDisplay ah.tr = createElement "tr" ah.tr.appendChild createElement "th", null, null, {colspan: rowAttrs.length, rowspan: colAttrs.length} if col is 0 and rowAttrs.length isnt 0 ah.tr.appendChild ah.th thead.appendChild ah.tr return axisHeaders buildRowAxisHeaders = (thead, rowAttrs, colAttrs, opts) -> axisHeaders = collapseAttrHeader: collapseRow expandAttrHeader: expandRow ah: [] tr: createElement "tr" for col in [0..rowAttrs.length-1] ah = buildAxisHeader axisHeaders, col, rowAttrs, opts.rowSubtotalDisplay axisHeaders.tr.appendChild ah.th if colAttrs.length != 0 th = createElement "th" axisHeaders.tr.appendChild th thead.appendChild axisHeaders.tr return axisHeaders getHeaderText = (h, attrs, opts) -> arrow = " #{arrowExpanded} " arrow = "" if h.col == attrs.length-1 or h.col >= opts.disableFrom or opts.disableExpandCollapse or h.children.length is 0 return "#{arrow}#{h.text}" buildColHeader = (axisHeaders, attrHeaders, h, rowAttrs, colAttrs, node, opts) -> # DF Recurse buildColHeader axisHeaders, attrHeaders, h[chKey], rowAttrs, colAttrs, node, opts for chKey in h.children # Process ah = axisHeaders.ah[h.col] ah.attrHeaders.push h h.node = node.counter h.onClick = collapseCol addClass h.th, "#{classColShow} col#{h.row} colcol#{h.col} #{classColExpanded}" h.th.setAttribute "data-colnode", h.node h.th.colSpan = h.childrenSpan if h.children.length isnt 0 h.th.rowSpan = 2 if h.children.length is 0 and rowAttrs.length isnt 0 h.th.textContent = getHeaderText h, colAttrs, opts.colSubtotalDisplay if h.children.length isnt 0 and h.col < opts.colSubtotalDisplay.disableFrom ah.expandables++ ah.expandedCount += 1 h.th.colSpan++ if not opts.colSubtotalDisplay.hideOnExpand if not opts.colSubtotalDisplay.disableExpandCollapse h.th.onclick = (event) -> event = event || window.event h.onClick axisHeaders, h, opts.colSubtotalDisplay h.sTh = createElement "th", "pvtColLabelFiller #{classColShow} col#{h.row} colcol#{h.col} #{classColExpanded}" h.sTh.setAttribute "data-colnode", h.node h.sTh.rowSpan = colAttrs.length-h.col replaceClass h.sTh, classColShow, classColHide if opts.colSubtotalDisplay.hideOnExpand h[h.children[0]].tr.appendChild h.sTh h.parent?.childrenSpan += h.th.colSpan h.clickStatus = clickStatusExpanded ah.tr.appendChild h.th h.tr = ah.tr attrHeaders.push h node.counter++ buildRowTotalsHeader = (tr, rowAttrs, colAttrs) -> th = createElement "th", "pvtTotalLabel rowTotal", opts.localeStrings.totals, rowspan: if colAttrs.length is 0 then 1 else colAttrs.length + (if rowAttrs.length is 0 then 0 else 1) tr.appendChild th buildRowHeader = (tbody, axisHeaders, attrHeaders, h, rowAttrs, colAttrs, node, opts) -> # DF Recurse buildRowHeader tbody, axisHeaders, attrHeaders, h[chKey], rowAttrs, colAttrs, node, opts for chKey in h.children # Process ah = axisHeaders.ah[h.col] ah.attrHeaders.push h h.node = node.counter h.onClick = collapseRow firstChild = h[h.children[0]] if h.children.length isnt 0 addClass h.th, "#{classRowShow} row#{h.row} rowcol#{h.col} #{classRowExpanded}" h.th.setAttribute "data-rownode", h.node h.th.colSpan = 2 if h.col is rowAttrs.length-1 and colAttrs.length isnt 0 h.th.rowSpan = h.childrenSpan if h.children.length isnt 0 h.th.textContent = getHeaderText h, rowAttrs, opts.rowSubtotalDisplay h.tr = createElement "tr", "row#{h.row}" h.tr.appendChild h.th if h.children.length is 0 tbody.appendChild h.tr else tbody.insertBefore h.tr, firstChild.tr if h.children.length isnt 0 and h.col < opts.rowSubtotalDisplay.disableFrom ++ah.expandedCount ++ah.expandables if not opts.rowSubtotalDisplay.disableExpandCollapse h.th.onclick = (event) -> event = event || window.event h.onClick axisHeaders, h, opts.rowSubtotalDisplay h.sTh = createElement "th", "pvtRowLabelFiller row#{h.row} rowcol#{h.col} #{classRowExpanded} #{classRowShow}" replaceClass h.sTh, classRowShow, classRowHide if opts.rowSubtotalDisplay.hideOnExpand h.sTh.setAttribute "data-rownode", h.node h.sTh.colSpan = rowAttrs.length-(h.col+1) + if colAttrs.length != 0 then 1 else 0 if opts.rowSubtotalDisplay.displayOnTop h.tr.appendChild h.sTh else h.th.rowSpan += 1 # if not opts.rowSubtotalDisplay.hideOnExpand h.sTr = createElement "tr", "row#{h.row}" h.sTr.appendChild h.sTh tbody.appendChild h.sTr h.th.rowSpan++ if h.children.length isnt 0 h.parent?.childrenSpan += h.th.rowSpan h.clickStatus = clickStatusExpanded attrHeaders.push h node.counter++ getTableEventHandlers = (value, rowKey, colKey, rowAttrs, colAttrs, opts) -> return if not opts.table?.eventHandlers eventHandlers = {} for own event, handler of opts.table.eventHandlers filters = {} filters[attr] = colKey[i] for own i, attr of colAttrs when colKey[i]? filters[attr] = rowKey[i] for own i, attr of rowAttrs when rowKey[i]? eventHandlers[event] = (e) -> handler(e, value, filters, pivotData) return eventHandlers buildValues = (tbody, colAttrHeaders, rowAttrHeaders, rowAttrs, colAttrs, opts) -> for rh in rowAttrHeaders when rh.col is rowAttrs.length-1 or (rh.children.length isnt 0 and rh.col < opts.rowSubtotalDisplay.disableFrom) rCls = "pvtVal row#{rh.row} rowcol#{rh.col} #{classRowExpanded}" if rh.children.length > 0 rCls += " pvtRowSubtotal" rCls += if opts.rowSubtotalDisplay.hideOnExpand then " #{classRowHide}" else " #{classRowShow}" else rCls += " #{classRowShow}" tr = if rh.sTr then rh.sTr else rh.tr for ch in colAttrHeaders when ch.col is colAttrs.length-1 or (ch.children.length isnt 0 and ch.col < opts.colSubtotalDisplay.disableFrom) aggregator = tree[rh.flatKey][ch.flatKey] ? {value: (-> null), format: -> ""} val = aggregator.value() cls = " #{rCls} col#{ch.row} colcol#{ch.col} #{classColExpanded}" if ch.children.length > 0 cls += " pvtColSubtotal" cls += if opts.colSubtotalDisplay.hideOnExpand then " #{classColHide}" else " #{classColShow}" else cls += " #{classColShow}" td = createElement "td", cls, aggregator.format(val), "data-value": val "data-rownode": rh.node "data-colnode": ch.node, getTableEventHandlers val, rh.key, ch.key, rowAttrs, colAttrs, opts tr.appendChild td # buildRowTotal totalAggregator = rowTotals[rh.flatKey] val = totalAggregator.value() td = createElement "td", "pvtTotal rowTotal #{rCls}", totalAggregator.format(val), "data-value": val "data-row": "row#{rh.row}" "data-rowcol": "col#{rh.col}" "data-rownode": rh.node, getTableEventHandlers val, rh.key, [], rowAttrs, colAttrs, opts tr.appendChild td buildColTotalsHeader = (rowAttrs, colAttrs) -> tr = createElement "tr" colspan = rowAttrs.length + (if colAttrs.length == 0 then 0 else 1) th = createElement "th", "pvtTotalLabel colTotal", opts.localeStrings.totals, {colspan: colspan} tr.appendChild th return tr buildColTotals = (tr, attrHeaders, rowAttrs, colAttrs, opts) -> for h in attrHeaders when h.col is colAttrs.length-1 or (h.children.length isnt 0 and h.col < opts.colSubtotalDisplay.disableFrom) clsNames = "pvtVal pvtTotal colTotal #{classColExpanded} col#{h.row} colcol#{h.col}" if h.children.length isnt 0 clsNames += " pvtColSubtotal" clsNames += if opts.colSubtotalDisplay.hideOnExpand then " #{classColHide}" else " #{classColShow}" else clsNames += " #{classColShow}" totalAggregator = colTotals[h.flatKey] val = totalAggregator.value() td = createElement "td", clsNames, totalAggregator.format(val), "data-value": val "data-for": "col#{h.col}" "data-colnode": "#{h.node}", getTableEventHandlers val, [], h.key, rowAttrs, colAttrs, opts tr.appendChild td buildGrandTotal = (tbody, tr, rowAttrs, colAttrs, opts) -> totalAggregator = allTotal val = totalAggregator.value() td = createElement "td", "pvtGrandTotal", totalAggregator.format(val), {"data-value": val}, getTableEventHandlers val, [], [], rowAttrs, colAttrs, opts tr.appendChild td tbody.appendChild tr collapseAxisHeaders = (axisHeaders, col, opts) -> collapsible = Math.min axisHeaders.ah.length-2, opts.disableFrom-1 return if col > collapsible for i in [col..collapsible] ah = axisHeaders.ah[i] replaceClass ah.th, classExpanded, classCollapsed ah.th.textContent = " #{arrowCollapsed} #{ah.text}" ah.clickStatus = clickStatusCollapsed ah.onClick = expandAxis adjustAxisHeader = (axisHeaders, col, opts) -> ah = axisHeaders.ah[col] if ah.expandedCount is 0 collapseAxisHeaders axisHeaders, col, opts else if ah.expandedCount is ah.expandables replaceClass ah.th, classCollapsed, classExpanded ah.th.textContent = " #{arrowExpanded} #{ah.text}" ah.clickStatus = clickStatusExpanded ah.onClick = collapseAxis hideChildCol = (ch) -> $(ch.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{ch.node}\"], th[data-colnode=\"#{ch.node}\"]" .removeClass classColShow .addClass classColHide collapseHiddenColSubtotal = (h, opts) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass classColExpanded .addClass classColCollapsed h.th.textContent = " #{arrowCollapsed} #{h.text}" if h.children.length isnt 0 h.th.colSpan = 1 collapseShowColSubtotal = (h, opts) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass classColExpanded .addClass classColCollapsed .removeClass classColHide .addClass classColShow h.th.textContent = " #{arrowCollapsed} #{h.text}" if h.children.length isnt 0 h.th.colSpan = 1 collapseChildCol = (ch, h) -> collapseChildCol ch[chKey], h for chKey in ch.children when hasClass ch[chKey].th, classColShow hideChildCol ch collapseCol = (axisHeaders, h, opts) -> colSpan = h.th.colSpan - 1 collapseChildCol h[chKey], h for chKey in h.children when hasClass h[chKey].th, classColShow if h.col < opts.disableFrom if hasClass h.th, classColHide collapseHiddenColSubtotal h, opts else collapseShowColSubtotal h, opts p = h.parent while p p.th.colSpan -= colSpan p = p.parent h.clickStatus = clickStatusCollapsed h.onClick = expandCol axisHeaders.ah[h.col].expandedCount-- adjustAxisHeader axisHeaders, h.col, opts showChildCol = (ch) -> $(ch.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{ch.node}\"], th[data-colnode=\"#{ch.node}\"]" .removeClass classColHide .addClass classColShow expandHideColSubtotal = (h) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass "#{classColCollapsed} #{classColShow}" .addClass "#{classColExpanded} #{classColHide}" replaceClass h.th, classColHide, classColShow h.th.textContent = " #{arrowExpanded} #{h.text}" expandShowColSubtotal = (h) -> $(h.th).closest 'table.pvtTable' .find "tbody tr td[data-colnode=\"#{h.node}\"], th[data-colnode=\"#{h.node}\"]" .removeClass "#{classColCollapsed} #{classColHide}" .addClass "#{classColExpanded} #{classColShow}" h.th.colSpan++ h.th.textContent = " #{arrowExpanded} #{h.text}" expandChildCol = (ch, opts) -> if ch.children.length isnt 0 and opts.hideOnExpand and ch.clickStatus is clickStatusExpanded replaceClass ch.th, classColHide, classColShow else showChildCol ch if ch.sTh and ch.clickStatus is clickStatusExpanded and opts.hideOnExpand replaceClass ch.sTh, classColShow, classColHide expandChildCol ch[chKey], opts for chKey in ch.children if (ch.clickStatus is clickStatusExpanded or ch.col >= opts.disableFrom) expandCol = (axisHeaders, h, opts) -> if h.clickStatus is clickStatusExpanded adjustAxisHeader axisHeaders, h.col, opts return colSpan = 0 for chKey in h.children ch = h[chKey] expandChildCol ch, opts colSpan += ch.th.colSpan h.th.colSpan = colSpan if h.col < opts.disableFrom if opts.hideOnExpand expandHideColSubtotal h --colSpan else expandShowColSubtotal h p = h.parent while p p.th.colSpan += colSpan p = p.parent h.clickStatus = clickStatusExpanded h.onClick = collapseCol axisHeaders.ah[h.col].expandedCount++ adjustAxisHeader axisHeaders, h.col, opts hideChildRow = (ch, opts) -> replaceClass cell, classRowShow, classRowHide for cell in ch.tr.querySelectorAll "th, td" replaceClass cell, classRowShow, classRowHide for cell in ch.sTr.querySelectorAll "th, td" if ch.sTr collapseShowRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowCollapsed} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowExpanded} #{classRowHide}" addClass cell, "#{classRowCollapsed} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowExpanded} #{classRowHide}" addClass cell, "#{classRowCollapsed} #{classRowShow}" collapseChildRow = (ch, h, opts) -> collapseChildRow ch[chKey], h, opts for chKey in ch.children hideChildRow ch, opts collapseRow = (axisHeaders, h, opts) -> collapseChildRow h[chKey], h, opts for chKey in h.children collapseShowRowSubtotal h, opts h.clickStatus = clickStatusCollapsed h.onClick = expandRow axisHeaders.ah[h.col].expandedCount-- adjustAxisHeader axisHeaders, h.col, opts showChildRow = (ch, opts) -> replaceClass cell, classRowHide, classRowShow for cell in ch.tr.querySelectorAll "th, td" replaceClass cell, classRowHide, classRowShow for cell in ch.sTr.querySelectorAll "th, td" if ch.sTr expandShowRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowExpanded} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" expandHideRowSubtotal = (h, opts) -> h.th.textContent = " #{arrowExpanded} #{h.text}" for cell in h.tr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowShow}" addClass cell, "#{classRowExpanded} #{classRowHide}" removeClass h.th, "#{classRowCollapsed} #{classRowHide}" addClass cell, "#{classRowExpanded} #{classRowShow}" if h.sTr for cell in h.sTr.querySelectorAll "th, td" removeClass cell, "#{classRowCollapsed} #{classRowShow}" addClass cell, "#{classRowExpanded} #{classRowHide}" expandChildRow = (ch, opts) -> if ch.children.length isnt 0 and opts.hideOnExpand and ch.clickStatus is clickStatusExpanded replaceClass ch.th, classRowHide, classRowShow else showChildRow ch, opts if ch.sTh and ch.clickStatus is clickStatusExpanded and opts.hideOnExpand replaceClass ch.sTh, classRowShow, classRowHide expandChildRow ch[chKey], opts for chKey in ch.children if (ch.clickStatus is clickStatusExpanded or ch.col >= opts.disableFrom) expandRow = (axisHeaders, h, opts) -> if h.clickStatus is clickStatusExpanded adjustAxisHeader axisHeaders, h.col, opts return for chKey in h.children ch = h[chKey] expandChildRow ch, opts if h.children.length isnt 0 if opts.hideOnExpand expandHideRowSubtotal h, opts else expandShowRowSubtotal h, opts h.clickStatus = clickStatusExpanded h.onClick = collapseRow axisHeaders.ah[h.col].expandedCount++ adjustAxisHeader axisHeaders, h.col, opts collapseAxis = (axisHeaders, col, attrs, opts) -> collapsible = Math.min attrs.length-2, opts.disableFrom-1 return if col > collapsible axisHeaders.collapseAttrHeader axisHeaders, h, opts for h in axisHeaders.ah[i].attrHeaders when h.clickStatus is clickStatusExpanded and h.children.length isnt 0 for i in [collapsible..col] by -1 expandAxis = (axisHeaders, col, attrs, opts) -> ah = axisHeaders.ah[col] axisHeaders.expandAttrHeader axisHeaders, h, opts for h in axisHeaders.ah[i].attrHeaders for i in [0..col] # when h.clickStatus is clickStatusCollapsed and h.children.length isnt 0 for i in [0..col] main = (rowAttrs, rowKeys, colAttrs, colKeys) -> rowAttrHeaders = [] colAttrHeaders = [] colKeyHeaders = processKeys colKeys, "pvtColLabel" if colAttrs.length isnt 0 and colKeys.length isnt 0 rowKeyHeaders = processKeys rowKeys, "pvtRowLabel" if rowAttrs.length isnt 0 and rowKeys.length isnt 0 result = createElement "table", "pvtTable", null, {style: "display: none;"} thead = createElement "thead" result.appendChild thead if colAttrs.length isnt 0 colAxisHeaders = buildColAxisHeaders thead, rowAttrs, colAttrs, opts node = counter: 0 buildColHeader colAxisHeaders, colAttrHeaders, colKeyHeaders[chKey], rowAttrs, colAttrs, node, opts for chKey in colKeyHeaders.children buildRowTotalsHeader colAxisHeaders.ah[0].tr, rowAttrs, colAttrs tbody = createElement "tbody" result.appendChild tbody if rowAttrs.length isnt 0 rowAxisHeaders = buildRowAxisHeaders thead, rowAttrs, colAttrs, opts buildRowTotalsHeader rowAxisHeaders.tr, rowAttrs, colAttrs if colAttrs.length is 0 node = counter: 0 buildRowHeader tbody, rowAxisHeaders, rowAttrHeaders, rowKeyHeaders[chKey], rowAttrs, colAttrs, node, opts for chKey in rowKeyHeaders.children buildValues tbody, colAttrHeaders, rowAttrHeaders, rowAttrs, colAttrs, opts tr = buildColTotalsHeader rowAttrs, colAttrs buildColTotals tr, colAttrHeaders, rowAttrs, colAttrs, opts if colAttrs.length > 0 buildGrandTotal tbody, tr, rowAttrs, colAttrs, opts collapseAxis colAxisHeaders, opts.colSubtotalDisplay.collapseAt, colAttrs, opts.colSubtotalDisplay collapseAxis rowAxisHeaders, opts.rowSubtotalDisplay.collapseAt, rowAttrs, opts.rowSubtotalDisplay result.setAttribute "data-numrows", rowKeys.length result.setAttribute "data-numcols", colKeys.length result.style.display = "" return result return main rowAttrs, rowKeys, colAttrs, colKeys $.pivotUtilities.subtotal_renderers = "Table With Subtotal": (pvtData, opts) -> SubtotalRenderer pvtData, opts "Table With Subtotal Bar Chart": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).barchart() "Table With Subtotal Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "heatmap", opts "Table With Subtotal Row Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "rowheatmap", opts "Table With Subtotal Col Heatmap": (pvtData, opts) -> $(SubtotalRenderer pvtData, opts).heatmap "colheatmap", opts # # Aggregators # usFmtPct = $.pivotUtilities.numberFormat digitsAfterDecimal:1, scaler: 100, suffix: "%" aggregatorTemplates = $.pivotUtilities.aggregatorTemplates; subtotalAggregatorTemplates = fractionOf: (wrapped, type="row", formatter=usFmtPct) -> (x...) -> (data, rowKey, colKey) -> rowKey = [] if typeof rowKey is "undefined" colKey = [] if typeof colKey is "undefined" selector: {row: [rowKey.slice(0, -1),[]], col: [[], colKey.slice(0, -1)]}[type] inner: wrapped(x...)(data, rowKey, colKey) push: (record) -> @inner.push record format: formatter value: -> @inner.value() / data.getAggregator(@selector...).inner.value() numInputs: wrapped(x...)().numInputs $.pivotUtilities.subtotalAggregatorTemplates = subtotalAggregatorTemplates $.pivotUtilities.subtotal_aggregators = do (tpl = aggregatorTemplates, sTpl = subtotalAggregatorTemplates) -> "Sum As Fraction Of Parent Row": sTpl.fractionOf(tpl.sum(), "row", usFmtPct) "Sum As Fraction Of Parent Column": sTpl.fractionOf(tpl.sum(), "col", usFmtPct) "Count As Fraction Of Parent Row": sTpl.fractionOf(tpl.count(), "row", usFmtPct) "Count As Fraction Of Parent Column": sTpl.fractionOf(tpl.count(), "col", usFmtPct)
[ { "context": "30749edcd0a554bd94e301c651\",\n \"authorName\": \"Bee Wilkerson\",\n \"relativeDate\": \"6 days ago\",\n \"auth", "end": 370, "score": 0.9995821714401245, "start": 357, "tag": "NAME", "value": "Bee Wilkerson" }, { "context": "exit) ->\n format = (\"\"\"{...
atom.symlink/packages/git-time-machine/lib/git-utils.coffee
sanata-/dotenv
0
{BufferedProcess} = require "atom" _ = require('underscore-plus'); path = require "path" fs = require "fs" GitUtils = exports ### returns an array of javascript objects representing the commits that effected the requested file with line stats, that looks like this: [{ "id": "1c41d8f647f7ad30749edcd0a554bd94e301c651", "authorName": "Bee Wilkerson", "relativeDate": "6 days ago", "authorDate": 1450881433, "message": "docs all work again after refactoring to bumble-build", "body": "", "hash": "1c41d8f", "linesAdded": 2, "linesDeleted": 2 }, { ... }] ### GitUtils.getFileCommitHistory = (fileName, callback)-> logItems = [] lastCommitObj = null stdout = (output) -> lastCommitObj = GitUtils._parseGitLogOutput(output, lastCommitObj, logItems) exit = (code) -> GitUtils._onFinishedParse(code, logItems, callback) return GitUtils._fetchFileHistory(fileName, stdout, exit) # Implementation GitUtils._parseGitLogOutput = (output, lastCommitObj, logItems) -> logLines = output.split("\n") for line in logLines if line[0] == '{' && line[line.length-1] == '}' lastCommitObj = GitUtils._parseCommitObj(line) logItems.push lastCommitObj if lastCommitObj else if line[0] == '{' # this will happen when there are newlines in the commit message lastCommitObj = line else if _.isString(lastCommitObj) lastCommitObj += line if line[line.length-1] == '}' lastCommitObj = GitUtils._parseCommitObj(lastCommitObj) logItems.push lastCommitObj if lastCommitObj else if lastCommitObj? && (matches = line.match(/^(\d+)\s*(\d+).*/)) # git log --num-stat appends line stats on separate line lastCommitObj.linesAdded = Number.parseInt(matches[1]) lastCommitObj.linesDeleted = Number.parseInt(matches[2]) return lastCommitObj GitUtils._parseCommitObj = (line) -> encLine = line.replace(/\t/g, ' ') # tabs mess with JSON parse .replace(/\"/g, "'") # sorry, can't parse with quotes in body or message .replace(/(\n|\n\r)/g, '<br>') .replace(/\r/g, '<br>') .replace(/\#\/dquotes\//g, '"') try return JSON.parse(encLine) catch console.warn "failed to parse JSON #{encLine}" return null # note this is spied on by unit test. See spec/git-utils-spec.coffee GitUtils._onFinishedParse = (code, logItems, callback) -> if code is 0 and logItems.length isnt 0 callback logItems else callback [] return GitUtils._fetchFileHistory = (fileName, stdout, exit) -> format = ("""{"id": "%H", "authorName": "%an", "relativeDate": "%cr", "authorDate": %at, """ + """ "message": "%s", "body": "%b", "hash": "%h"}""").replace(/\"/g, "#/dquotes/") return new BufferedProcess { command: "git", args: [ "-C", path.dirname(fileName), "log", "--pretty=format:#{format}", "--topo-order", "--date=local", "--numstat", fileName ], stdout, exit }
55910
{BufferedProcess} = require "atom" _ = require('underscore-plus'); path = require "path" fs = require "fs" GitUtils = exports ### returns an array of javascript objects representing the commits that effected the requested file with line stats, that looks like this: [{ "id": "1c41d8f647f7ad30749edcd0a554bd94e301c651", "authorName": "<NAME>", "relativeDate": "6 days ago", "authorDate": 1450881433, "message": "docs all work again after refactoring to bumble-build", "body": "", "hash": "1c41d8f", "linesAdded": 2, "linesDeleted": 2 }, { ... }] ### GitUtils.getFileCommitHistory = (fileName, callback)-> logItems = [] lastCommitObj = null stdout = (output) -> lastCommitObj = GitUtils._parseGitLogOutput(output, lastCommitObj, logItems) exit = (code) -> GitUtils._onFinishedParse(code, logItems, callback) return GitUtils._fetchFileHistory(fileName, stdout, exit) # Implementation GitUtils._parseGitLogOutput = (output, lastCommitObj, logItems) -> logLines = output.split("\n") for line in logLines if line[0] == '{' && line[line.length-1] == '}' lastCommitObj = GitUtils._parseCommitObj(line) logItems.push lastCommitObj if lastCommitObj else if line[0] == '{' # this will happen when there are newlines in the commit message lastCommitObj = line else if _.isString(lastCommitObj) lastCommitObj += line if line[line.length-1] == '}' lastCommitObj = GitUtils._parseCommitObj(lastCommitObj) logItems.push lastCommitObj if lastCommitObj else if lastCommitObj? && (matches = line.match(/^(\d+)\s*(\d+).*/)) # git log --num-stat appends line stats on separate line lastCommitObj.linesAdded = Number.parseInt(matches[1]) lastCommitObj.linesDeleted = Number.parseInt(matches[2]) return lastCommitObj GitUtils._parseCommitObj = (line) -> encLine = line.replace(/\t/g, ' ') # tabs mess with JSON parse .replace(/\"/g, "'") # sorry, can't parse with quotes in body or message .replace(/(\n|\n\r)/g, '<br>') .replace(/\r/g, '<br>') .replace(/\#\/dquotes\//g, '"') try return JSON.parse(encLine) catch console.warn "failed to parse JSON #{encLine}" return null # note this is spied on by unit test. See spec/git-utils-spec.coffee GitUtils._onFinishedParse = (code, logItems, callback) -> if code is 0 and logItems.length isnt 0 callback logItems else callback [] return GitUtils._fetchFileHistory = (fileName, stdout, exit) -> format = ("""{"id": "%H", "authorName": "%an", "relativeDate": "%cr", "authorDate": %at, """ + """ "message": "%s", "body": "%b", "hash": "%h"}""").replace(/\"/g, "#/dquotes/") return new BufferedProcess { command: "git", args: [ "-C", path.dirname(fileName), "log", "--pretty=format:#{format}", "--topo-order", "--date=local", "--numstat", fileName ], stdout, exit }
true
{BufferedProcess} = require "atom" _ = require('underscore-plus'); path = require "path" fs = require "fs" GitUtils = exports ### returns an array of javascript objects representing the commits that effected the requested file with line stats, that looks like this: [{ "id": "1c41d8f647f7ad30749edcd0a554bd94e301c651", "authorName": "PI:NAME:<NAME>END_PI", "relativeDate": "6 days ago", "authorDate": 1450881433, "message": "docs all work again after refactoring to bumble-build", "body": "", "hash": "1c41d8f", "linesAdded": 2, "linesDeleted": 2 }, { ... }] ### GitUtils.getFileCommitHistory = (fileName, callback)-> logItems = [] lastCommitObj = null stdout = (output) -> lastCommitObj = GitUtils._parseGitLogOutput(output, lastCommitObj, logItems) exit = (code) -> GitUtils._onFinishedParse(code, logItems, callback) return GitUtils._fetchFileHistory(fileName, stdout, exit) # Implementation GitUtils._parseGitLogOutput = (output, lastCommitObj, logItems) -> logLines = output.split("\n") for line in logLines if line[0] == '{' && line[line.length-1] == '}' lastCommitObj = GitUtils._parseCommitObj(line) logItems.push lastCommitObj if lastCommitObj else if line[0] == '{' # this will happen when there are newlines in the commit message lastCommitObj = line else if _.isString(lastCommitObj) lastCommitObj += line if line[line.length-1] == '}' lastCommitObj = GitUtils._parseCommitObj(lastCommitObj) logItems.push lastCommitObj if lastCommitObj else if lastCommitObj? && (matches = line.match(/^(\d+)\s*(\d+).*/)) # git log --num-stat appends line stats on separate line lastCommitObj.linesAdded = Number.parseInt(matches[1]) lastCommitObj.linesDeleted = Number.parseInt(matches[2]) return lastCommitObj GitUtils._parseCommitObj = (line) -> encLine = line.replace(/\t/g, ' ') # tabs mess with JSON parse .replace(/\"/g, "'") # sorry, can't parse with quotes in body or message .replace(/(\n|\n\r)/g, '<br>') .replace(/\r/g, '<br>') .replace(/\#\/dquotes\//g, '"') try return JSON.parse(encLine) catch console.warn "failed to parse JSON #{encLine}" return null # note this is spied on by unit test. See spec/git-utils-spec.coffee GitUtils._onFinishedParse = (code, logItems, callback) -> if code is 0 and logItems.length isnt 0 callback logItems else callback [] return GitUtils._fetchFileHistory = (fileName, stdout, exit) -> format = ("""{"id": "%H", "authorName": "%an", "relativeDate": "%cr", "authorDate": %at, """ + """ "message": "%s", "body": "%b", "hash": "%h"}""").replace(/\"/g, "#/dquotes/") return new BufferedProcess { command: "git", args: [ "-C", path.dirname(fileName), "log", "--pretty=format:#{format}", "--topo-order", "--date=local", "--numstat", fileName ], stdout, exit }
[ { "context": "\n# 紀錄登入資訊的 Model\n $scope.loginInfo =\n email: \"Alice@meigic.tw\"\n password: \"Alice0000\"\n rememberMe: false\n", "end": 241, "score": 0.9999293088912964, "start": 226, "tag": "EMAIL", "value": "Alice@meigic.tw" }, { "context": "nfo =\n email: \"Alice@m...
app/assets/javascripts/view_controllers.coffee
hackboard/hackboard
5
controllers = angular.module 'hackboardControllers', [] # Login, Register Controller controllers.controller 'UserCtrl', ['$scope', 'User', '$window', ($scope, User, $window)-> # 紀錄登入資訊的 Model $scope.loginInfo = email: "Alice@meigic.tw" password: "Alice0000" rememberMe: false hasError: false hasWarning: false # 註冊資訊的Model $scope.registerInfo = email: '' nickname: '' password: '' password_confirmation: '' agree: false hasError: false hasWarning: false warning_message: '' nicknameDirty: false $scope.$watch('registerInfo.email', (old, newv)-> $scope.registerInfo.avatar = md5($scope.registerInfo.email) ) # 登入按鈕按下時要做的動作 $scope.btnLogin = ()-> # reset message $scope.loginInfo.hasError = false $scope.loginInfo.hasWarning = false User.login( $scope.loginInfo.email $scope.loginInfo.password $scope.loginInfo.rememberMe ) .success((data, status)-> $window.location.href = '/boards' ) .error((data, status)-> if data == "UMSE01" or data == "UMSE02" $scope.loginInfo.hasWarning = true else $scope.loginInfo.hasError = true ) # 從登入轉到註冊卡片,並帶入資料 $scope.btnRegister = ()-> $scope.registerInfo.email = $scope.loginInfo.email resetAllError() switchCard $("#loginCard"), $("#signupCard") resetAllError = ()-> $scope.loginInfo.hasError = $scope.loginInfo.hasWarning = $scope.registerInfo.hasError = $scope.registerInfo.hasWarning = false resetSignUpAllError = ()-> $scope.registerInfo.hasError = $scope.registerInfo.hasWarning = false $scope.registerInfo.warning_message = '' cleanUpSignUpInformations = ()-> $scope.registerInfo.email = $scope.registerInfo.nickname = $scope.registerInfo.password = $scope.registerInfo.password_confirmation = '' $scope.registerInfo.agree = false #按下註冊鈕 $scope.btnSignUp = ()-> #Reset $scope.registerInfo.hasError = false $scope.registerInfo.hasWarning = false $scope.registerInfo.warning_message = '' #Check e-mail pattern if $scope.signUpForm.signUpEmail.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your E-Mail does not match the pattern.It Should be abc@efg.com.' return #Check shortname is match pattern if $scope.signUpForm.nickName.$error.required or $scope.signUpForm.nickName.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your short name dose not match the pattern. May content illegal character.' return #Check password and passwordConfirmation at least 8 character if $scope.signUpForm.password.$error.minlength or $scope.signUpForm.password_confirmation.$error.minlength $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your password needs at least 8 characters.' return #Check password and passwordConfirmation match pattern if $scope.signUpForm.password.$error.pattern or $scope.signUpForm.password_confirmation.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your password does not match the pattern. May content illegal character.' return #Check password and passwordConfirmation are same... if $scope.registerInfo.password != $scope.registerInfo.password_confirmation $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Passwords are not the same.' return #Check agree checkbox is checked if $scope.registerInfo.agree == false $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'You need to agree Term of Service.' return #Sign up... User.signUp( $scope.registerInfo.email, $scope.registerInfo.nickname, $scope.registerInfo.password, $scope.registerInfo.password_confirmation ) .success((data, status)-> $scope.loginInfo.email = $scope.registerInfo.email $scope.loginInfo.password = '' #clean up ... cleanUpSignUpInformations() resetSignUpAllError() #Flip to login scene switchCard $('#signupCard'), $('#loginCard') ) .error((data, status)-> if data == "UMSE03" $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Account already exist.' else if data == "UMSE04" $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Passwords dose not the same.' else $scope.registerInfo.hasError = true ) #Change shortname when email been done (Cannot change when type in email account) $scope.putToNickname = ()-> if !$scope.signUpForm.signUpEmail.$error.pattern $scope.registerInfo.nickname = $scope.registerInfo.email.split("@")[0] ] # Boards Page controllers.controller 'BoardsCtrl', ['$scope', 'User', 'Board', '$window', 'timeAgo', '$http', ($scope, User, Board, $window, timeAgo, $http)-> $scope.boards = { pin: [], other: [] } $http.get('/api/user/current_user').success((data, status)-> $scope.current_user = data $scope.current_user.avatar = md5(data.email) ) # async load boards data Board.boards().success((data, status)-> $scope.boards = data ) # sortable setting $scope.pinBoardSortOptions = { containment: '#pinned-boards', additionalPlaceholderClass: 'ui column', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id } $scope.otherBoardSortOptions = { containment: '#other-boards', additionalPlaceholderClass: 'ui column', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id } # processing pin and unpin $scope.pin = (id)-> angular.forEach $scope.boards.other, (value, key)-> if value.id == id $scope.boards.pin.push $scope.boards.other[key] $scope.boards.other.splice key, 1 Board.pin(id) $scope.unpin = (id)-> angular.forEach $scope.boards.pin, (value, key)-> if value.id == id $scope.boards.other.push $scope.boards.pin[key] $scope.boards.pin.splice key, 1 Board.unpin(id) # new board $scope.newBoard = ()-> Board.create().success((data, status)-> # $scope.boards.other.push data.board $window.location.href = '/board/' + data.board.id ) # click card to board $scope.toBoard = (id)-> $window.location.href = '/board/' + id ] # board Page controllers.controller 'BoardCtrl', ['$scope', '$window', 'Board', '$http', ($scope, $window, Board, $http)-> $scope.uuid = guid() $scope.dontSend = false board_id = parseInt($window.location.pathname.split('/')[2]) $scope.board = [ flows: [] ] $scope.stash = [] $scope.$watch('stash', ((oldVal, newVal)-> $http.post('/api/boards/' + $scope.board.id + '/stash/', { uuid: $scope.uuid, stash: $scope.stash }) ), true) $scope.getlabelname = (shortname) -> return unless shortname name = shortname.split(/[\s,]+/) if name.length is 1 name = name[0].slice(0, 2).toUpperCase() return name else i = 0 while i < name.length name[i] = name[i].slice(0, 1) i++ return name.join("").slice(0, 2).toUpperCase() $scope.stashSortOptions = { accept: (sourceItemHandleScope, destSortableScope)-> $(sourceItemHandleScope.element).css("opacity", 0.5) return true itemMoved: (obj)-> console.log "itemMoved" console.log($scope.stash) console.log obj } # # flow sortable setting $scope.flowSortOptions = { containment: '#board-content', additionalPlaceholderClass: 'ui-list-placeholder', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id orderChanged: (obj)-> flowOrder = [] for key of $scope.board.flows flowOrder.push $scope.board.flows[key].id $http.post('/api/flows/updateorder', { data: flowOrder }) itemMoved: (obj)-> console.log obj } $scope.taskSortOptions = { # containment: '#board-content', # additionalPlaceholderClass: 'ui grid ui-board-content', accept: (sourceItemHandleScope, destSortableScope)-> if sourceItemHandleScope.itemScope.hasOwnProperty('flow') return false true orderChanged: (obj)-> taskOrder = [] for key of obj.dest.sortableScope.modelValue taskOrder.push obj.dest.sortableScope.modelValue[key].id $http.post('/api/boards/' + $scope.board.id + '/updatetaskorder', { uuid: $scope.uuid data: taskOrder }) itemMoved: (obj)-> console.log obj task = obj.source.itemScope.task oldFlowID = task.flow_id newFlowID = null for key of $scope.board.flows for key2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[key2].id == task.id newFlowID = $scope.board.flows[key].id $scope.board.flows[key].tasks[key2].flow_id = newFlowID taskOrder = [] for key of obj.dest.sortableScope.modelValue taskOrder.push obj.dest.sortableScope.modelValue[key].id $http.post('/api/boards/' + $scope.board.id + '/task/move', { uuid: $scope.uuid taskId: obj.source.itemScope.modelValue.id sFlow: oldFlowID dFlow: newFlowID order: taskOrder }) } Board.board(board_id).success((data, status)-> $scope.board = data Board.flows($scope.board.id).success((data, status)-> $scope.board.flows = data $scope.$watch('board', ((old, nv)-> if $scope.dontSend == false $http.post('/api/update', { uuid: $scope.uuid board: $scope.board }) else $scope.dontSend = false ), true) ) ).error((data, status)-> $window.location.href = "/boards" ) $scope.titleClick = (id)-> $('#board-detail-modal').modal({ transition: 'slide down', duration: '100ms', onVisible: ()-> $(window).resize() }).modal('show') $scope.taskClick = (id)-> angular.forEach($scope.board.flows, (value, key)-> angular.forEach(value.tasks, (task, key)-> if task.id == id $scope.taskData = task ) angular.forEach(value.flows, (subflow, key)-> angular.forEach(subflow.tasks, (task, key)-> if task.id == id $scope.taskData = task ) ) ) $('#task-detail-modal').modal({ transition: 'slide down', duration: '100ms', onVisible: ()-> $(window).resize() }).modal('show') $scope.newFlow = ()-> $http.post('/api/boards/' + $scope.board.id + '/flows/add', {uuid: $scope.uuid}).success((data, status)-> $scope.board.flows.push data ) $scope.newTask = (id)-> $http.post('/api/boards/' + $scope.board.id + '/flows/' + id + '/task/add', {uuid: $scope.uuid}).success( (data, status)-> angular.forEach($scope.board.flows, (flow, key)-> angular.forEach(flow.flows, (subFlow, key2)-> if subFlow.id == id subFlow.tasks.push data ) if flow.id == id flow.tasks.push data ) ) hbSocket = io.connect 'http://localhost:33555' hbSocket.on 'hb', (message)-> # console.log message console.log "message from:" + message.uuid if message.board_id == $scope.board.id and message.uuid != $scope.uuid $scope.dontSend = true switch message.type when "flowOrderChange" processFlowOrderChange(message.order) when "taskOrderChange" processTaskOrderChange(message.flow_id, message.order) when "taskMove" processTaskMove(message.task_id, message.sFlow, message.dFlow, message.order) when "taskAdd" processTaskAdd(message.task) when "flowAdd" processFlowAdd(message.flow) when "boardChange" processBoardChange(message.board) when "flowDataChange" processFlowChange(message.flow) when "taskDataChange" processDataChange(message.task) else console.log message processDataChange = (task)-> for key of $scope.board.flows for key2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[key2].id == task.id $scope.board.flows[key].tasks[key2].name = task.name $scope.board.flows[key].tasks[key2].description = task.description $scope.board.flows[key].tasks[key2].updated_at = task.updated_at break processFlowChange = (flow)-> for key of $scope.board.flows if $scope.board.flows[key].id == flow.id $scope.board.flows[key].name = flow.name break processBoardChange = (board)-> console.log "processBoardChange" $scope.board.name = board.name $scope.board.description = board.description processFlowAdd = (flow)-> console.log "processFlowAdd" console.log flow is_already = false for key of $scope.board.flows if $scope.board.flows[key].id == flow.id is_already = true break if !is_already flow.tasks = [] flow.flows = [] $scope.board.flows.push flow processTaskAdd = (task)-> flowid = task.flow_id for key of $scope.board.flows if $scope.board.flows[key].id == flowid has_task = false for k2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[k2].id == task.id has_task = true break if !has_task $scope.board.flows[key].tasks.push task processTaskMove = (taskid, oldFlowID, newFlowID, order)-> console.log "processTaskMove" for key of $scope.board.flows if $scope.board.flows[key].id == oldFlowID findInOldFlow = null for k2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[k2].id == taskid console.log $scope.board.flows[key].tasks[k2] findInOldFlow = $scope.board.flows[key].tasks[k2] for k3 of $scope.board.flows if $scope.board.flows[k3].id == newFlowID $scope.board.flows[k3].tasks.push findInOldFlow $scope.board.flows[key].tasks.splice k2, 1 break processTaskOrderChange(newFlowID, order) break processFlowOrderChange = (newOrder)-> console.log "processFlowOrderChange" dirty = false for key of $scope.board.flows if $scope.board.flows[key].id != newOrder[key] dirty = true break if dirty newOrderFlows = [] for flowID of newOrder for key of $scope.board.flows if $scope.board.flows[key].id == newOrder[flowID] newOrderFlows.push $scope.board.flows[key] break $scope.board.flows = newOrderFlows processTaskOrderChange = (flow_id, newOrder)-> console.log "processTaskOrderChange", flow_id, newOrder targetFlow = null for key of $scope.board.flows if $scope.board.flows[key].id == flow_id targetFlow = $scope.board.flows[key] break dirty = false if targetFlow for key of targetFlow.tasks if targetFlow.tasks[key].id != newOrder[key] dirty = true break if dirty newOrderTasks = [] for taskKey of newOrder for key of targetFlow.tasks if targetFlow.tasks[key].id == newOrder[taskKey] newOrderTasks.push targetFlow.tasks[key] break targetFlow.tasks = newOrderTasks ] controllers.controller 'BoardSidebarController' , ['$scope', '$window', 'Board', '$http', ($scope, $window, Board, $http)-> board_id = parseInt($window.location.pathname.split('/')[2]) $scope.board = [ flows: [] ] $scope.current_user = {} $http.get('/api/user/current_user').success((data, status)-> $scope.current_user = data $scope.current_user.avatar = md5(data.email) $scope.current_user.shortname = $scope.getlabelname(data.name) $scope.$watch('current_user.name', (oldValue, newValue)-> $scope.current_user.shortname = $scope.getlabelname($scope.current_user.name) if oldValue != newValue $http.post('/api/user/' + $scope.current_user.id + '/save', { name: $scope.current_user.name }) ) ) Board.board(board_id).success((data, status)-> $scope.board = data Board.flows($scope.board.id).success((data, status)-> $scope.board.flows = data $scope.$watch('board', ((old, nv)-> if $scope.dontSend == false $http.post('/api/update', { uuid: $scope.uuid board: $scope.board }) else $scope.dontSend = false ), true) ) ).error((data, status)-> $window.location.href = "/boards" ) $scope.removeBoardMember = (id)-> angular.forEach($scope.board.users, (value, key)-> if value.id == id $http.post('/api/baords/' + $scope.board.id + '/users/delete/' + value.id) $scope.board.users.splice key, 1 ) $scope.selpeople = "" $scope.people = [] $scope.findPeople = (name)-> $http.get('/api/user/find/' + name) .success( (data, status)-> console.log data $scope.people = data ) $scope.addmember = (member)-> $http.post('/api/boards/' + $scope.board.id + '/users/add/' + member).success( (data, status)-> $scope.board.users.push(data) $scope.selpeople = "" ).error(()-> $scope.selpeople = "" ) $scope.getlabelname = (shortname) -> return unless shortname name = shortname.split(/[\s,]+/) if name.length is 1 name = name[0].slice(0, 2).toUpperCase() return name else i = 0 while i < name.length name[i] = name[i].slice(0, 1) i++ return name.join("").slice(0, 2).toUpperCase() ]
102201
controllers = angular.module 'hackboardControllers', [] # Login, Register Controller controllers.controller 'UserCtrl', ['$scope', 'User', '$window', ($scope, User, $window)-> # 紀錄登入資訊的 Model $scope.loginInfo = email: "<EMAIL>" password: "<PASSWORD>" rememberMe: false hasError: false hasWarning: false # 註冊資訊的Model $scope.registerInfo = email: '' nickname: '' password: '' password_confirmation: '' agree: false hasError: false hasWarning: false warning_message: '' nicknameDirty: false $scope.$watch('registerInfo.email', (old, newv)-> $scope.registerInfo.avatar = md5($scope.registerInfo.email) ) # 登入按鈕按下時要做的動作 $scope.btnLogin = ()-> # reset message $scope.loginInfo.hasError = false $scope.loginInfo.hasWarning = false User.login( $scope.loginInfo.email $scope.loginInfo.password $scope.loginInfo.rememberMe ) .success((data, status)-> $window.location.href = '/boards' ) .error((data, status)-> if data == "UMSE01" or data == "UMSE02" $scope.loginInfo.hasWarning = true else $scope.loginInfo.hasError = true ) # 從登入轉到註冊卡片,並帶入資料 $scope.btnRegister = ()-> $scope.registerInfo.email = $scope.loginInfo.email resetAllError() switchCard $("#loginCard"), $("#signupCard") resetAllError = ()-> $scope.loginInfo.hasError = $scope.loginInfo.hasWarning = $scope.registerInfo.hasError = $scope.registerInfo.hasWarning = false resetSignUpAllError = ()-> $scope.registerInfo.hasError = $scope.registerInfo.hasWarning = false $scope.registerInfo.warning_message = '' cleanUpSignUpInformations = ()-> $scope.registerInfo.email = $scope.registerInfo.nickname = $scope.registerInfo.password = $scope.registerInfo.password_confirmation = '' $scope.registerInfo.agree = false #按下註冊鈕 $scope.btnSignUp = ()-> #Reset $scope.registerInfo.hasError = false $scope.registerInfo.hasWarning = false $scope.registerInfo.warning_message = '' #Check e-mail pattern if $scope.signUpForm.signUpEmail.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your E-Mail does not match the pattern.It Should be <EMAIL>.' return #Check shortname is match pattern if $scope.signUpForm.nickName.$error.required or $scope.signUpForm.nickName.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your short name dose not match the pattern. May content illegal character.' return #Check password and passwordConfirmation at least 8 character if $scope.signUpForm.password.$error.minlength or $scope.signUpForm.password_confirmation.$error.minlength $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your password needs at least 8 characters.' return #Check password and passwordConfirmation match pattern if $scope.signUpForm.password.$error.pattern or $scope.signUpForm.password_confirmation.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your password does not match the pattern. May content illegal character.' return #Check password and passwordConfirmation are same... if $scope.registerInfo.password != $scope.registerInfo.password_confirmation $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Passwords are not the same.' return #Check agree checkbox is checked if $scope.registerInfo.agree == false $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'You need to agree Term of Service.' return #Sign up... User.signUp( $scope.registerInfo.email, $scope.registerInfo.nickname, $scope.registerInfo.password, $scope.registerInfo.password_confirmation ) .success((data, status)-> $scope.loginInfo.email = $scope.registerInfo.email $scope.loginInfo.password = '' #clean up ... cleanUpSignUpInformations() resetSignUpAllError() #Flip to login scene switchCard $('#signupCard'), $('#loginCard') ) .error((data, status)-> if data == "UMSE03" $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Account already exist.' else if data == "UMSE04" $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Passwords dose not the same.' else $scope.registerInfo.hasError = true ) #Change shortname when email been done (Cannot change when type in email account) $scope.putToNickname = ()-> if !$scope.signUpForm.signUpEmail.$error.pattern $scope.registerInfo.nickname = $scope.registerInfo.email.split("@")[0] ] # Boards Page controllers.controller 'BoardsCtrl', ['$scope', 'User', 'Board', '$window', 'timeAgo', '$http', ($scope, User, Board, $window, timeAgo, $http)-> $scope.boards = { pin: [], other: [] } $http.get('/api/user/current_user').success((data, status)-> $scope.current_user = data $scope.current_user.avatar = md5(data.email) ) # async load boards data Board.boards().success((data, status)-> $scope.boards = data ) # sortable setting $scope.pinBoardSortOptions = { containment: '#pinned-boards', additionalPlaceholderClass: 'ui column', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id } $scope.otherBoardSortOptions = { containment: '#other-boards', additionalPlaceholderClass: 'ui column', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id } # processing pin and unpin $scope.pin = (id)-> angular.forEach $scope.boards.other, (value, key)-> if value.id == id $scope.boards.pin.push $scope.boards.other[key] $scope.boards.other.splice key, 1 Board.pin(id) $scope.unpin = (id)-> angular.forEach $scope.boards.pin, (value, key)-> if value.id == id $scope.boards.other.push $scope.boards.pin[key] $scope.boards.pin.splice key, 1 Board.unpin(id) # new board $scope.newBoard = ()-> Board.create().success((data, status)-> # $scope.boards.other.push data.board $window.location.href = '/board/' + data.board.id ) # click card to board $scope.toBoard = (id)-> $window.location.href = '/board/' + id ] # board Page controllers.controller 'BoardCtrl', ['$scope', '$window', 'Board', '$http', ($scope, $window, Board, $http)-> $scope.uuid = guid() $scope.dontSend = false board_id = parseInt($window.location.pathname.split('/')[2]) $scope.board = [ flows: [] ] $scope.stash = [] $scope.$watch('stash', ((oldVal, newVal)-> $http.post('/api/boards/' + $scope.board.id + '/stash/', { uuid: $scope.uuid, stash: $scope.stash }) ), true) $scope.getlabelname = (shortname) -> return unless shortname name = shortname.split(/[\s,]+/) if name.length is 1 name = name[0].slice(0, 2).toUpperCase() return name else i = 0 while i < name.length name[i] = name[i].slice(0, 1) i++ return name.join("").slice(0, 2).toUpperCase() $scope.stashSortOptions = { accept: (sourceItemHandleScope, destSortableScope)-> $(sourceItemHandleScope.element).css("opacity", 0.5) return true itemMoved: (obj)-> console.log "itemMoved" console.log($scope.stash) console.log obj } # # flow sortable setting $scope.flowSortOptions = { containment: '#board-content', additionalPlaceholderClass: 'ui-list-placeholder', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id orderChanged: (obj)-> flowOrder = [] for key of $scope.board.flows flowOrder.push $scope.board.flows[key].id $http.post('/api/flows/updateorder', { data: flowOrder }) itemMoved: (obj)-> console.log obj } $scope.taskSortOptions = { # containment: '#board-content', # additionalPlaceholderClass: 'ui grid ui-board-content', accept: (sourceItemHandleScope, destSortableScope)-> if sourceItemHandleScope.itemScope.hasOwnProperty('flow') return false true orderChanged: (obj)-> taskOrder = [] for key of obj.dest.sortableScope.modelValue taskOrder.push obj.dest.sortableScope.modelValue[key].id $http.post('/api/boards/' + $scope.board.id + '/updatetaskorder', { uuid: $scope.uuid data: taskOrder }) itemMoved: (obj)-> console.log obj task = obj.source.itemScope.task oldFlowID = task.flow_id newFlowID = null for key of $scope.board.flows for key2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[key2].id == task.id newFlowID = $scope.board.flows[key].id $scope.board.flows[key].tasks[key2].flow_id = newFlowID taskOrder = [] for key of obj.dest.sortableScope.modelValue taskOrder.push obj.dest.sortableScope.modelValue[key].id $http.post('/api/boards/' + $scope.board.id + '/task/move', { uuid: $scope.uuid taskId: obj.source.itemScope.modelValue.id sFlow: oldFlowID dFlow: newFlowID order: taskOrder }) } Board.board(board_id).success((data, status)-> $scope.board = data Board.flows($scope.board.id).success((data, status)-> $scope.board.flows = data $scope.$watch('board', ((old, nv)-> if $scope.dontSend == false $http.post('/api/update', { uuid: $scope.uuid board: $scope.board }) else $scope.dontSend = false ), true) ) ).error((data, status)-> $window.location.href = "/boards" ) $scope.titleClick = (id)-> $('#board-detail-modal').modal({ transition: 'slide down', duration: '100ms', onVisible: ()-> $(window).resize() }).modal('show') $scope.taskClick = (id)-> angular.forEach($scope.board.flows, (value, key)-> angular.forEach(value.tasks, (task, key)-> if task.id == id $scope.taskData = task ) angular.forEach(value.flows, (subflow, key)-> angular.forEach(subflow.tasks, (task, key)-> if task.id == id $scope.taskData = task ) ) ) $('#task-detail-modal').modal({ transition: 'slide down', duration: '100ms', onVisible: ()-> $(window).resize() }).modal('show') $scope.newFlow = ()-> $http.post('/api/boards/' + $scope.board.id + '/flows/add', {uuid: $scope.uuid}).success((data, status)-> $scope.board.flows.push data ) $scope.newTask = (id)-> $http.post('/api/boards/' + $scope.board.id + '/flows/' + id + '/task/add', {uuid: $scope.uuid}).success( (data, status)-> angular.forEach($scope.board.flows, (flow, key)-> angular.forEach(flow.flows, (subFlow, key2)-> if subFlow.id == id subFlow.tasks.push data ) if flow.id == id flow.tasks.push data ) ) hbSocket = io.connect 'http://localhost:33555' hbSocket.on 'hb', (message)-> # console.log message console.log "message from:" + message.uuid if message.board_id == $scope.board.id and message.uuid != $scope.uuid $scope.dontSend = true switch message.type when "flowOrderChange" processFlowOrderChange(message.order) when "taskOrderChange" processTaskOrderChange(message.flow_id, message.order) when "taskMove" processTaskMove(message.task_id, message.sFlow, message.dFlow, message.order) when "taskAdd" processTaskAdd(message.task) when "flowAdd" processFlowAdd(message.flow) when "boardChange" processBoardChange(message.board) when "flowDataChange" processFlowChange(message.flow) when "taskDataChange" processDataChange(message.task) else console.log message processDataChange = (task)-> for key of $scope.board.flows for key2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[key2].id == task.id $scope.board.flows[key].tasks[key2].name = task.name $scope.board.flows[key].tasks[key2].description = task.description $scope.board.flows[key].tasks[key2].updated_at = task.updated_at break processFlowChange = (flow)-> for key of $scope.board.flows if $scope.board.flows[key].id == flow.id $scope.board.flows[key].name = flow.name break processBoardChange = (board)-> console.log "processBoardChange" $scope.board.name = board.name $scope.board.description = board.description processFlowAdd = (flow)-> console.log "processFlowAdd" console.log flow is_already = false for key of $scope.board.flows if $scope.board.flows[key].id == flow.id is_already = true break if !is_already flow.tasks = [] flow.flows = [] $scope.board.flows.push flow processTaskAdd = (task)-> flowid = task.flow_id for key of $scope.board.flows if $scope.board.flows[key].id == flowid has_task = false for k2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[k2].id == task.id has_task = true break if !has_task $scope.board.flows[key].tasks.push task processTaskMove = (taskid, oldFlowID, newFlowID, order)-> console.log "processTaskMove" for key of $scope.board.flows if $scope.board.flows[key].id == oldFlowID findInOldFlow = null for k2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[k2].id == taskid console.log $scope.board.flows[key].tasks[k2] findInOldFlow = $scope.board.flows[key].tasks[k2] for k3 of $scope.board.flows if $scope.board.flows[k3].id == newFlowID $scope.board.flows[k3].tasks.push findInOldFlow $scope.board.flows[key].tasks.splice k2, 1 break processTaskOrderChange(newFlowID, order) break processFlowOrderChange = (newOrder)-> console.log "processFlowOrderChange" dirty = false for key of $scope.board.flows if $scope.board.flows[key].id != newOrder[key] dirty = true break if dirty newOrderFlows = [] for flowID of newOrder for key of $scope.board.flows if $scope.board.flows[key].id == newOrder[flowID] newOrderFlows.push $scope.board.flows[key] break $scope.board.flows = newOrderFlows processTaskOrderChange = (flow_id, newOrder)-> console.log "processTaskOrderChange", flow_id, newOrder targetFlow = null for key of $scope.board.flows if $scope.board.flows[key].id == flow_id targetFlow = $scope.board.flows[key] break dirty = false if targetFlow for key of targetFlow.tasks if targetFlow.tasks[key].id != newOrder[key] dirty = true break if dirty newOrderTasks = [] for taskKey of newOrder for key of targetFlow.tasks if targetFlow.tasks[key].id == newOrder[taskKey] newOrderTasks.push targetFlow.tasks[key] break targetFlow.tasks = newOrderTasks ] controllers.controller 'BoardSidebarController' , ['$scope', '$window', 'Board', '$http', ($scope, $window, Board, $http)-> board_id = parseInt($window.location.pathname.split('/')[2]) $scope.board = [ flows: [] ] $scope.current_user = {} $http.get('/api/user/current_user').success((data, status)-> $scope.current_user = data $scope.current_user.avatar = md5(data.email) $scope.current_user.shortname = $scope.getlabelname(data.name) $scope.$watch('current_user.name', (oldValue, newValue)-> $scope.current_user.shortname = $scope.getlabelname($scope.current_user.name) if oldValue != newValue $http.post('/api/user/' + $scope.current_user.id + '/save', { name: $scope.current_user.name }) ) ) Board.board(board_id).success((data, status)-> $scope.board = data Board.flows($scope.board.id).success((data, status)-> $scope.board.flows = data $scope.$watch('board', ((old, nv)-> if $scope.dontSend == false $http.post('/api/update', { uuid: $scope.uuid board: $scope.board }) else $scope.dontSend = false ), true) ) ).error((data, status)-> $window.location.href = "/boards" ) $scope.removeBoardMember = (id)-> angular.forEach($scope.board.users, (value, key)-> if value.id == id $http.post('/api/baords/' + $scope.board.id + '/users/delete/' + value.id) $scope.board.users.splice key, 1 ) $scope.selpeople = "" $scope.people = [] $scope.findPeople = (name)-> $http.get('/api/user/find/' + name) .success( (data, status)-> console.log data $scope.people = data ) $scope.addmember = (member)-> $http.post('/api/boards/' + $scope.board.id + '/users/add/' + member).success( (data, status)-> $scope.board.users.push(data) $scope.selpeople = "" ).error(()-> $scope.selpeople = "" ) $scope.getlabelname = (shortname) -> return unless shortname name = shortname.split(/[\s,]+/) if name.length is 1 name = name[0].slice(0, 2).toUpperCase() return name else i = 0 while i < name.length name[i] = name[i].slice(0, 1) i++ return name.join("").slice(0, 2).toUpperCase() ]
true
controllers = angular.module 'hackboardControllers', [] # Login, Register Controller controllers.controller 'UserCtrl', ['$scope', 'User', '$window', ($scope, User, $window)-> # 紀錄登入資訊的 Model $scope.loginInfo = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" rememberMe: false hasError: false hasWarning: false # 註冊資訊的Model $scope.registerInfo = email: '' nickname: '' password: '' password_confirmation: '' agree: false hasError: false hasWarning: false warning_message: '' nicknameDirty: false $scope.$watch('registerInfo.email', (old, newv)-> $scope.registerInfo.avatar = md5($scope.registerInfo.email) ) # 登入按鈕按下時要做的動作 $scope.btnLogin = ()-> # reset message $scope.loginInfo.hasError = false $scope.loginInfo.hasWarning = false User.login( $scope.loginInfo.email $scope.loginInfo.password $scope.loginInfo.rememberMe ) .success((data, status)-> $window.location.href = '/boards' ) .error((data, status)-> if data == "UMSE01" or data == "UMSE02" $scope.loginInfo.hasWarning = true else $scope.loginInfo.hasError = true ) # 從登入轉到註冊卡片,並帶入資料 $scope.btnRegister = ()-> $scope.registerInfo.email = $scope.loginInfo.email resetAllError() switchCard $("#loginCard"), $("#signupCard") resetAllError = ()-> $scope.loginInfo.hasError = $scope.loginInfo.hasWarning = $scope.registerInfo.hasError = $scope.registerInfo.hasWarning = false resetSignUpAllError = ()-> $scope.registerInfo.hasError = $scope.registerInfo.hasWarning = false $scope.registerInfo.warning_message = '' cleanUpSignUpInformations = ()-> $scope.registerInfo.email = $scope.registerInfo.nickname = $scope.registerInfo.password = $scope.registerInfo.password_confirmation = '' $scope.registerInfo.agree = false #按下註冊鈕 $scope.btnSignUp = ()-> #Reset $scope.registerInfo.hasError = false $scope.registerInfo.hasWarning = false $scope.registerInfo.warning_message = '' #Check e-mail pattern if $scope.signUpForm.signUpEmail.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your E-Mail does not match the pattern.It Should be PI:EMAIL:<EMAIL>END_PI.' return #Check shortname is match pattern if $scope.signUpForm.nickName.$error.required or $scope.signUpForm.nickName.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your short name dose not match the pattern. May content illegal character.' return #Check password and passwordConfirmation at least 8 character if $scope.signUpForm.password.$error.minlength or $scope.signUpForm.password_confirmation.$error.minlength $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your password needs at least 8 characters.' return #Check password and passwordConfirmation match pattern if $scope.signUpForm.password.$error.pattern or $scope.signUpForm.password_confirmation.$error.pattern $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Your password does not match the pattern. May content illegal character.' return #Check password and passwordConfirmation are same... if $scope.registerInfo.password != $scope.registerInfo.password_confirmation $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Passwords are not the same.' return #Check agree checkbox is checked if $scope.registerInfo.agree == false $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'You need to agree Term of Service.' return #Sign up... User.signUp( $scope.registerInfo.email, $scope.registerInfo.nickname, $scope.registerInfo.password, $scope.registerInfo.password_confirmation ) .success((data, status)-> $scope.loginInfo.email = $scope.registerInfo.email $scope.loginInfo.password = '' #clean up ... cleanUpSignUpInformations() resetSignUpAllError() #Flip to login scene switchCard $('#signupCard'), $('#loginCard') ) .error((data, status)-> if data == "UMSE03" $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Account already exist.' else if data == "UMSE04" $scope.registerInfo.hasWarning = true $scope.registerInfo.warning_message = 'Passwords dose not the same.' else $scope.registerInfo.hasError = true ) #Change shortname when email been done (Cannot change when type in email account) $scope.putToNickname = ()-> if !$scope.signUpForm.signUpEmail.$error.pattern $scope.registerInfo.nickname = $scope.registerInfo.email.split("@")[0] ] # Boards Page controllers.controller 'BoardsCtrl', ['$scope', 'User', 'Board', '$window', 'timeAgo', '$http', ($scope, User, Board, $window, timeAgo, $http)-> $scope.boards = { pin: [], other: [] } $http.get('/api/user/current_user').success((data, status)-> $scope.current_user = data $scope.current_user.avatar = md5(data.email) ) # async load boards data Board.boards().success((data, status)-> $scope.boards = data ) # sortable setting $scope.pinBoardSortOptions = { containment: '#pinned-boards', additionalPlaceholderClass: 'ui column', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id } $scope.otherBoardSortOptions = { containment: '#other-boards', additionalPlaceholderClass: 'ui column', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id } # processing pin and unpin $scope.pin = (id)-> angular.forEach $scope.boards.other, (value, key)-> if value.id == id $scope.boards.pin.push $scope.boards.other[key] $scope.boards.other.splice key, 1 Board.pin(id) $scope.unpin = (id)-> angular.forEach $scope.boards.pin, (value, key)-> if value.id == id $scope.boards.other.push $scope.boards.pin[key] $scope.boards.pin.splice key, 1 Board.unpin(id) # new board $scope.newBoard = ()-> Board.create().success((data, status)-> # $scope.boards.other.push data.board $window.location.href = '/board/' + data.board.id ) # click card to board $scope.toBoard = (id)-> $window.location.href = '/board/' + id ] # board Page controllers.controller 'BoardCtrl', ['$scope', '$window', 'Board', '$http', ($scope, $window, Board, $http)-> $scope.uuid = guid() $scope.dontSend = false board_id = parseInt($window.location.pathname.split('/')[2]) $scope.board = [ flows: [] ] $scope.stash = [] $scope.$watch('stash', ((oldVal, newVal)-> $http.post('/api/boards/' + $scope.board.id + '/stash/', { uuid: $scope.uuid, stash: $scope.stash }) ), true) $scope.getlabelname = (shortname) -> return unless shortname name = shortname.split(/[\s,]+/) if name.length is 1 name = name[0].slice(0, 2).toUpperCase() return name else i = 0 while i < name.length name[i] = name[i].slice(0, 1) i++ return name.join("").slice(0, 2).toUpperCase() $scope.stashSortOptions = { accept: (sourceItemHandleScope, destSortableScope)-> $(sourceItemHandleScope.element).css("opacity", 0.5) return true itemMoved: (obj)-> console.log "itemMoved" console.log($scope.stash) console.log obj } # # flow sortable setting $scope.flowSortOptions = { containment: '#board-content', additionalPlaceholderClass: 'ui-list-placeholder', accept: (sourceItemHandleScope, destSortableScope)-> sourceItemHandleScope.itemScope.sortableScope.$id == destSortableScope.$id orderChanged: (obj)-> flowOrder = [] for key of $scope.board.flows flowOrder.push $scope.board.flows[key].id $http.post('/api/flows/updateorder', { data: flowOrder }) itemMoved: (obj)-> console.log obj } $scope.taskSortOptions = { # containment: '#board-content', # additionalPlaceholderClass: 'ui grid ui-board-content', accept: (sourceItemHandleScope, destSortableScope)-> if sourceItemHandleScope.itemScope.hasOwnProperty('flow') return false true orderChanged: (obj)-> taskOrder = [] for key of obj.dest.sortableScope.modelValue taskOrder.push obj.dest.sortableScope.modelValue[key].id $http.post('/api/boards/' + $scope.board.id + '/updatetaskorder', { uuid: $scope.uuid data: taskOrder }) itemMoved: (obj)-> console.log obj task = obj.source.itemScope.task oldFlowID = task.flow_id newFlowID = null for key of $scope.board.flows for key2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[key2].id == task.id newFlowID = $scope.board.flows[key].id $scope.board.flows[key].tasks[key2].flow_id = newFlowID taskOrder = [] for key of obj.dest.sortableScope.modelValue taskOrder.push obj.dest.sortableScope.modelValue[key].id $http.post('/api/boards/' + $scope.board.id + '/task/move', { uuid: $scope.uuid taskId: obj.source.itemScope.modelValue.id sFlow: oldFlowID dFlow: newFlowID order: taskOrder }) } Board.board(board_id).success((data, status)-> $scope.board = data Board.flows($scope.board.id).success((data, status)-> $scope.board.flows = data $scope.$watch('board', ((old, nv)-> if $scope.dontSend == false $http.post('/api/update', { uuid: $scope.uuid board: $scope.board }) else $scope.dontSend = false ), true) ) ).error((data, status)-> $window.location.href = "/boards" ) $scope.titleClick = (id)-> $('#board-detail-modal').modal({ transition: 'slide down', duration: '100ms', onVisible: ()-> $(window).resize() }).modal('show') $scope.taskClick = (id)-> angular.forEach($scope.board.flows, (value, key)-> angular.forEach(value.tasks, (task, key)-> if task.id == id $scope.taskData = task ) angular.forEach(value.flows, (subflow, key)-> angular.forEach(subflow.tasks, (task, key)-> if task.id == id $scope.taskData = task ) ) ) $('#task-detail-modal').modal({ transition: 'slide down', duration: '100ms', onVisible: ()-> $(window).resize() }).modal('show') $scope.newFlow = ()-> $http.post('/api/boards/' + $scope.board.id + '/flows/add', {uuid: $scope.uuid}).success((data, status)-> $scope.board.flows.push data ) $scope.newTask = (id)-> $http.post('/api/boards/' + $scope.board.id + '/flows/' + id + '/task/add', {uuid: $scope.uuid}).success( (data, status)-> angular.forEach($scope.board.flows, (flow, key)-> angular.forEach(flow.flows, (subFlow, key2)-> if subFlow.id == id subFlow.tasks.push data ) if flow.id == id flow.tasks.push data ) ) hbSocket = io.connect 'http://localhost:33555' hbSocket.on 'hb', (message)-> # console.log message console.log "message from:" + message.uuid if message.board_id == $scope.board.id and message.uuid != $scope.uuid $scope.dontSend = true switch message.type when "flowOrderChange" processFlowOrderChange(message.order) when "taskOrderChange" processTaskOrderChange(message.flow_id, message.order) when "taskMove" processTaskMove(message.task_id, message.sFlow, message.dFlow, message.order) when "taskAdd" processTaskAdd(message.task) when "flowAdd" processFlowAdd(message.flow) when "boardChange" processBoardChange(message.board) when "flowDataChange" processFlowChange(message.flow) when "taskDataChange" processDataChange(message.task) else console.log message processDataChange = (task)-> for key of $scope.board.flows for key2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[key2].id == task.id $scope.board.flows[key].tasks[key2].name = task.name $scope.board.flows[key].tasks[key2].description = task.description $scope.board.flows[key].tasks[key2].updated_at = task.updated_at break processFlowChange = (flow)-> for key of $scope.board.flows if $scope.board.flows[key].id == flow.id $scope.board.flows[key].name = flow.name break processBoardChange = (board)-> console.log "processBoardChange" $scope.board.name = board.name $scope.board.description = board.description processFlowAdd = (flow)-> console.log "processFlowAdd" console.log flow is_already = false for key of $scope.board.flows if $scope.board.flows[key].id == flow.id is_already = true break if !is_already flow.tasks = [] flow.flows = [] $scope.board.flows.push flow processTaskAdd = (task)-> flowid = task.flow_id for key of $scope.board.flows if $scope.board.flows[key].id == flowid has_task = false for k2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[k2].id == task.id has_task = true break if !has_task $scope.board.flows[key].tasks.push task processTaskMove = (taskid, oldFlowID, newFlowID, order)-> console.log "processTaskMove" for key of $scope.board.flows if $scope.board.flows[key].id == oldFlowID findInOldFlow = null for k2 of $scope.board.flows[key].tasks if $scope.board.flows[key].tasks[k2].id == taskid console.log $scope.board.flows[key].tasks[k2] findInOldFlow = $scope.board.flows[key].tasks[k2] for k3 of $scope.board.flows if $scope.board.flows[k3].id == newFlowID $scope.board.flows[k3].tasks.push findInOldFlow $scope.board.flows[key].tasks.splice k2, 1 break processTaskOrderChange(newFlowID, order) break processFlowOrderChange = (newOrder)-> console.log "processFlowOrderChange" dirty = false for key of $scope.board.flows if $scope.board.flows[key].id != newOrder[key] dirty = true break if dirty newOrderFlows = [] for flowID of newOrder for key of $scope.board.flows if $scope.board.flows[key].id == newOrder[flowID] newOrderFlows.push $scope.board.flows[key] break $scope.board.flows = newOrderFlows processTaskOrderChange = (flow_id, newOrder)-> console.log "processTaskOrderChange", flow_id, newOrder targetFlow = null for key of $scope.board.flows if $scope.board.flows[key].id == flow_id targetFlow = $scope.board.flows[key] break dirty = false if targetFlow for key of targetFlow.tasks if targetFlow.tasks[key].id != newOrder[key] dirty = true break if dirty newOrderTasks = [] for taskKey of newOrder for key of targetFlow.tasks if targetFlow.tasks[key].id == newOrder[taskKey] newOrderTasks.push targetFlow.tasks[key] break targetFlow.tasks = newOrderTasks ] controllers.controller 'BoardSidebarController' , ['$scope', '$window', 'Board', '$http', ($scope, $window, Board, $http)-> board_id = parseInt($window.location.pathname.split('/')[2]) $scope.board = [ flows: [] ] $scope.current_user = {} $http.get('/api/user/current_user').success((data, status)-> $scope.current_user = data $scope.current_user.avatar = md5(data.email) $scope.current_user.shortname = $scope.getlabelname(data.name) $scope.$watch('current_user.name', (oldValue, newValue)-> $scope.current_user.shortname = $scope.getlabelname($scope.current_user.name) if oldValue != newValue $http.post('/api/user/' + $scope.current_user.id + '/save', { name: $scope.current_user.name }) ) ) Board.board(board_id).success((data, status)-> $scope.board = data Board.flows($scope.board.id).success((data, status)-> $scope.board.flows = data $scope.$watch('board', ((old, nv)-> if $scope.dontSend == false $http.post('/api/update', { uuid: $scope.uuid board: $scope.board }) else $scope.dontSend = false ), true) ) ).error((data, status)-> $window.location.href = "/boards" ) $scope.removeBoardMember = (id)-> angular.forEach($scope.board.users, (value, key)-> if value.id == id $http.post('/api/baords/' + $scope.board.id + '/users/delete/' + value.id) $scope.board.users.splice key, 1 ) $scope.selpeople = "" $scope.people = [] $scope.findPeople = (name)-> $http.get('/api/user/find/' + name) .success( (data, status)-> console.log data $scope.people = data ) $scope.addmember = (member)-> $http.post('/api/boards/' + $scope.board.id + '/users/add/' + member).success( (data, status)-> $scope.board.users.push(data) $scope.selpeople = "" ).error(()-> $scope.selpeople = "" ) $scope.getlabelname = (shortname) -> return unless shortname name = shortname.split(/[\s,]+/) if name.length is 1 name = name[0].slice(0, 2).toUpperCase() return name else i = 0 while i < name.length name[i] = name[i].slice(0, 1) i++ return name.join("").slice(0, 2).toUpperCase() ]
[ { "context": ", jqXHR) ->\n $.growl.notice({ title: '주문서 메모', message: '저장되었습니다.' })\n error: (jqXHR, tex", "end": 3449, "score": 0.8171762824058533, "start": 3448, "tag": "NAME", "value": "모" } ]
public/assets/coffee/order-id-purchase-payment-done.coffee
ejang/OpenCloset-Share-Web
2
$.fn.editable.defaults.ajaxOptions = type: "PUT" dataType: 'json' $ -> order_id = location.pathname.split('/')[2] $.ajax "/clothes/recommend?order_id=#{order_id}", type: 'GET' dataType: 'json' success: (data, textStatus, jqXHR) -> template = JST['recommend'] html = template(data) $('#recommend-clothes').append(html) error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('#staff-list').editable params: (params) -> params[params.name] = params.value params $('#staff-list').editable 'submit', ajaxOptions: type: "PUT" dataType: 'json' $('.total-price').text($('#order-price').text()) $('.datepicker').datepicker language: 'kr' startDate: '+1d' todayHighlight: true autoclose: true format: 'yyyy-mm-dd' $('#from-date').on 'change', -> from = $(@).val() to = moment(from).add(4, 'days').format('YYYY-MM-DD') $('#to-date').val(to) $('#rental_date').val(from) $('#target_date').val(to) $('#form-clothes-code').submit (e) -> e.preventDefault() $this = $(@) $input = $this.find('input[name="code"]') code = $input.val().toUpperCase() url = $this.prop('action').replace(/xxx/, code) $.ajax url, type: 'GET' dataType: 'json' success: (data, textStatus, jqXHR) -> data._category = data.category data.category = OpenCloset.category[data.category] data.status = OpenCloset.status[data.status_id] data.labelColor = OpenCloset.status.color[data.status_id] data.disabled = switch data.status_id when "2", "3", "7", "8", "45", "46", "47" then true else false template = JST['clothes-item'] html = template(data) $('#table-clothes tbody').append(html) error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title:textStatus, message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $input.val('') $('#btn-update-order').click (e) -> $this = $(@) return if $this.hasClass('disabled') $this.addClass('disabled') ## 주문품목과 대여품목을 비교 rental_categories = [] order_categories = $('#order-categories').data('categories').split(/ /) $('#form-update-order input[name=clothes_code]:checked').each (i, el) -> category = $(el).data('category') rental_categories.push(category) rental_categories = _.uniq(rental_categories) diff = _.difference order_categories, rental_categories if diff.length unless confirm "주문품목과 대여품목이 다릅니다. 계속하시겠습니까?" $this.removeClass('disabled') return url = $('#form-update-order').prop('action') $.ajax url, type: 'PUT' data: $('#form-update-order').serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') if $('#alert').get(0) msg = $('#alert').prop('title') $.growl.error({ message: msg }) $('#form-order-desc').submit (e) -> e.preventDefault() $this = $(@) $this.find('.btn-success').addClass('disabled') $.ajax $this.prop('action'), type: 'PUT' data: $this.serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> $.growl.notice({ title: '주문서 메모', message: '저장되었습니다.' }) error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title:textStatus, message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $this.find('.btn-success').removeClass('disabled')
125920
$.fn.editable.defaults.ajaxOptions = type: "PUT" dataType: 'json' $ -> order_id = location.pathname.split('/')[2] $.ajax "/clothes/recommend?order_id=#{order_id}", type: 'GET' dataType: 'json' success: (data, textStatus, jqXHR) -> template = JST['recommend'] html = template(data) $('#recommend-clothes').append(html) error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('#staff-list').editable params: (params) -> params[params.name] = params.value params $('#staff-list').editable 'submit', ajaxOptions: type: "PUT" dataType: 'json' $('.total-price').text($('#order-price').text()) $('.datepicker').datepicker language: 'kr' startDate: '+1d' todayHighlight: true autoclose: true format: 'yyyy-mm-dd' $('#from-date').on 'change', -> from = $(@).val() to = moment(from).add(4, 'days').format('YYYY-MM-DD') $('#to-date').val(to) $('#rental_date').val(from) $('#target_date').val(to) $('#form-clothes-code').submit (e) -> e.preventDefault() $this = $(@) $input = $this.find('input[name="code"]') code = $input.val().toUpperCase() url = $this.prop('action').replace(/xxx/, code) $.ajax url, type: 'GET' dataType: 'json' success: (data, textStatus, jqXHR) -> data._category = data.category data.category = OpenCloset.category[data.category] data.status = OpenCloset.status[data.status_id] data.labelColor = OpenCloset.status.color[data.status_id] data.disabled = switch data.status_id when "2", "3", "7", "8", "45", "46", "47" then true else false template = JST['clothes-item'] html = template(data) $('#table-clothes tbody').append(html) error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title:textStatus, message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $input.val('') $('#btn-update-order').click (e) -> $this = $(@) return if $this.hasClass('disabled') $this.addClass('disabled') ## 주문품목과 대여품목을 비교 rental_categories = [] order_categories = $('#order-categories').data('categories').split(/ /) $('#form-update-order input[name=clothes_code]:checked').each (i, el) -> category = $(el).data('category') rental_categories.push(category) rental_categories = _.uniq(rental_categories) diff = _.difference order_categories, rental_categories if diff.length unless confirm "주문품목과 대여품목이 다릅니다. 계속하시겠습니까?" $this.removeClass('disabled') return url = $('#form-update-order').prop('action') $.ajax url, type: 'PUT' data: $('#form-update-order').serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') if $('#alert').get(0) msg = $('#alert').prop('title') $.growl.error({ message: msg }) $('#form-order-desc').submit (e) -> e.preventDefault() $this = $(@) $this.find('.btn-success').addClass('disabled') $.ajax $this.prop('action'), type: 'PUT' data: $this.serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> $.growl.notice({ title: '주문서 메<NAME>', message: '저장되었습니다.' }) error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title:textStatus, message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $this.find('.btn-success').removeClass('disabled')
true
$.fn.editable.defaults.ajaxOptions = type: "PUT" dataType: 'json' $ -> order_id = location.pathname.split('/')[2] $.ajax "/clothes/recommend?order_id=#{order_id}", type: 'GET' dataType: 'json' success: (data, textStatus, jqXHR) -> template = JST['recommend'] html = template(data) $('#recommend-clothes').append(html) error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('#staff-list').editable params: (params) -> params[params.name] = params.value params $('#staff-list').editable 'submit', ajaxOptions: type: "PUT" dataType: 'json' $('.total-price').text($('#order-price').text()) $('.datepicker').datepicker language: 'kr' startDate: '+1d' todayHighlight: true autoclose: true format: 'yyyy-mm-dd' $('#from-date').on 'change', -> from = $(@).val() to = moment(from).add(4, 'days').format('YYYY-MM-DD') $('#to-date').val(to) $('#rental_date').val(from) $('#target_date').val(to) $('#form-clothes-code').submit (e) -> e.preventDefault() $this = $(@) $input = $this.find('input[name="code"]') code = $input.val().toUpperCase() url = $this.prop('action').replace(/xxx/, code) $.ajax url, type: 'GET' dataType: 'json' success: (data, textStatus, jqXHR) -> data._category = data.category data.category = OpenCloset.category[data.category] data.status = OpenCloset.status[data.status_id] data.labelColor = OpenCloset.status.color[data.status_id] data.disabled = switch data.status_id when "2", "3", "7", "8", "45", "46", "47" then true else false template = JST['clothes-item'] html = template(data) $('#table-clothes tbody').append(html) error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title:textStatus, message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $input.val('') $('#btn-update-order').click (e) -> $this = $(@) return if $this.hasClass('disabled') $this.addClass('disabled') ## 주문품목과 대여품목을 비교 rental_categories = [] order_categories = $('#order-categories').data('categories').split(/ /) $('#form-update-order input[name=clothes_code]:checked').each (i, el) -> category = $(el).data('category') rental_categories.push(category) rental_categories = _.uniq(rental_categories) diff = _.difference order_categories, rental_categories if diff.length unless confirm "주문품목과 대여품목이 다릅니다. 계속하시겠습니까?" $this.removeClass('disabled') return url = $('#form-update-order').prop('action') $.ajax url, type: 'PUT' data: $('#form-update-order').serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') if $('#alert').get(0) msg = $('#alert').prop('title') $.growl.error({ message: msg }) $('#form-order-desc').submit (e) -> e.preventDefault() $this = $(@) $this.find('.btn-success').addClass('disabled') $.ajax $this.prop('action'), type: 'PUT' data: $this.serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> $.growl.notice({ title: '주문서 메PI:NAME:<NAME>END_PI', message: '저장되었습니다.' }) error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title:textStatus, message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $this.find('.btn-success').removeClass('disabled')
[ { "context": "ion = Hippodrome.createAction\n displayName: 'test1'\n build: -> {}\n\n store = makeTempStore\n ", "end": 2254, "score": 0.6125511527061462, "start": 2250, "tag": "NAME", "value": "test" }, { "context": "ion = Hippodrome.createAction\n displayName: 'te...
test/store_spec.coffee
Structural/hippodrome
0
Hippodrome = require('../dist/hippodrome') _ = require('lodash') # This is annoying, but because the Dispatcher is a single instance across all # tests, stores created in one test still have their callbacks registered in # subsequent tests, unless we get rid of them like this. unregisterStore = (store) -> _.forEach store._storeImpl.dispatcherIdsByAction, (id, action) -> Hippodrome.Dispatcher.unregister(action, id) describe 'Stores', -> tempStores = [] makeTempStore = (options) -> store = Hippodrome.createStore(options) tempStores.push(store) return store beforeEach -> tempStores = [] afterEach -> _.forEach tempStores, unregisterStore it 'don\'t expose properties not in public', -> store = makeTempStore propOne: 'one' public: propTwo: 'two' expect(store.propOne).toBe(undefined) expect(store.propTwo).toBe('two') it 'functions in public have access to non-public properties', -> store = makeTempStore prop: 'value' public: fn: () -> "My Property Is: #{@prop}" expect(store.fn()).toBe('My Property Is: value') it 'run registered functions on trigger', -> store = makeTempStore public: doTrigger: () -> @trigger() ran = false store.register(() -> ran = true) store.doTrigger() expect(ran).toBe(true) it 'don\'t run unregistered functions on trigger', -> store = makeTempStore public: doTrigger: () -> @trigger() ran = false callback = () -> @trigger() store.register(callback) store.unregister(callback) store.doTrigger() expect(ran).toBe(false) it 'run initialize on Hippodrome start', -> store = makeTempStore initialize: -> @ran = true ran: false public: isRun: () -> @ran Hippodrome.start() expect(store.isRun()).toBe(true) it 'run initialize with options on Hippodrome start', -> store = Hippodrome.createStore initialize: (options) -> @x = options.n * 2 public: value: () -> @x Hippodrome.start(n: 6) expect(store.value()).toBe(12) it 'run registered functions on action dispatch', -> action = Hippodrome.createAction displayName: 'test1' build: -> {} store = makeTempStore initialize: -> @dispatch(action).to(@doAction) ran: false doAction: (payload) -> @ran = true public: isRun: () -> @ran Hippodrome.start() action() expect(store.isRun()).toBe(true) it 'run registered functions by name on action dispatch', -> action = Hippodrome.createAction displayName: 'test2' build: -> {} store = makeTempStore initialize: -> @dispatch(action).to('doAction') ran: false doAction: (payload) -> @ran = true public: isRun: () -> @ran Hippodrome.start() action() expect(store.isRun()).toBe(true) it 'run registered functions with payload data', -> action = Hippodrome.createAction displayName: 'test3' build: (n) -> {n: n} store = makeTempStore initialize: -> @dispatch(action).to(@doAction) x: 0 doAction: (payload) -> @x = payload.n * payload.n public: value: () -> @x Hippodrome.start() action(4) expect(store.value()).toBe(16) it 'run callbacks after other stores', -> action = Hippodrome.createAction displayName: 'test4' build: (n) -> {n: n} first = makeTempStore initialize: -> @dispatch(action).to(@doAction) x: 0 doAction: (payload) -> @x = payload.n * payload.n public: value: () -> @x second = makeTempStore initialize: -> @dispatch(action).after(first).to(@doAction) x: 0 doAction: (payload) -> @x = first.value() + payload.n public: value: () -> @x Hippodrome.start() action(5) expect(first.value()).toBe(25) expect(second.value()).toBe(30) it 'run callbacks after other stores no matter declaration order', -> action = Hippodrome.createAction displayName: 'test8' build: (n) -> {n: n} second = makeTempStore initialize: -> @x = 0 @dispatch(action).after(first).to(@doAction) doAction: (payload) -> @x = payload.n + first.value() public: value: () -> @x first = makeTempStore initialize: -> @x = 0 @dispatch(action).to(@doAction) doAction: (payload) -> @x = payload.n * 2 public: value: () -> @x Hippodrome.start() action(3) expect(first.value()).toBe(6) expect(second.value()).toBe(9) it 'fail when stores create a circular dependency', -> action = Hippodrome.createAction build: -> {} one = makeTempStore initialize: -> @dispatch(action).after(three).to(@doAction) doAction: (payload) -> @ran = true two = makeTempStore initialize: -> @dispatch(action).after(one).to(@doAction) doAction: (payload) -> @ran = true three = makeTempStore initialize: -> @dispatch(action).after(two).to(@doAction) doAction: (payload) -> @ran = true Hippodrome.start() expect(action).toThrow() it 'fail when the prerequisite store does not handle action', -> action = Hippodrome.createAction build: -> {} one = makeTempStore displayName: 'one' two = makeTempStore initialize: -> @dispatch(action).after(one).to(@doAction) doAction: -> @ran = true Hippodrome.start() expect(action).toThrow() it 'fail when registering for same action more than once', -> action = Hippodrome.createAction build: -> {} store = makeTempStore initialize: -> @dispatch(action).to(->) @dispatch(action).to(->) expect(Hippodrome.start).toThrow()
164216
Hippodrome = require('../dist/hippodrome') _ = require('lodash') # This is annoying, but because the Dispatcher is a single instance across all # tests, stores created in one test still have their callbacks registered in # subsequent tests, unless we get rid of them like this. unregisterStore = (store) -> _.forEach store._storeImpl.dispatcherIdsByAction, (id, action) -> Hippodrome.Dispatcher.unregister(action, id) describe 'Stores', -> tempStores = [] makeTempStore = (options) -> store = Hippodrome.createStore(options) tempStores.push(store) return store beforeEach -> tempStores = [] afterEach -> _.forEach tempStores, unregisterStore it 'don\'t expose properties not in public', -> store = makeTempStore propOne: 'one' public: propTwo: 'two' expect(store.propOne).toBe(undefined) expect(store.propTwo).toBe('two') it 'functions in public have access to non-public properties', -> store = makeTempStore prop: 'value' public: fn: () -> "My Property Is: #{@prop}" expect(store.fn()).toBe('My Property Is: value') it 'run registered functions on trigger', -> store = makeTempStore public: doTrigger: () -> @trigger() ran = false store.register(() -> ran = true) store.doTrigger() expect(ran).toBe(true) it 'don\'t run unregistered functions on trigger', -> store = makeTempStore public: doTrigger: () -> @trigger() ran = false callback = () -> @trigger() store.register(callback) store.unregister(callback) store.doTrigger() expect(ran).toBe(false) it 'run initialize on Hippodrome start', -> store = makeTempStore initialize: -> @ran = true ran: false public: isRun: () -> @ran Hippodrome.start() expect(store.isRun()).toBe(true) it 'run initialize with options on Hippodrome start', -> store = Hippodrome.createStore initialize: (options) -> @x = options.n * 2 public: value: () -> @x Hippodrome.start(n: 6) expect(store.value()).toBe(12) it 'run registered functions on action dispatch', -> action = Hippodrome.createAction displayName: '<NAME>1' build: -> {} store = makeTempStore initialize: -> @dispatch(action).to(@doAction) ran: false doAction: (payload) -> @ran = true public: isRun: () -> @ran Hippodrome.start() action() expect(store.isRun()).toBe(true) it 'run registered functions by name on action dispatch', -> action = Hippodrome.createAction displayName: '<NAME>2' build: -> {} store = makeTempStore initialize: -> @dispatch(action).to('doAction') ran: false doAction: (payload) -> @ran = true public: isRun: () -> @ran Hippodrome.start() action() expect(store.isRun()).toBe(true) it 'run registered functions with payload data', -> action = Hippodrome.createAction displayName: '<NAME>3' build: (n) -> {n: n} store = makeTempStore initialize: -> @dispatch(action).to(@doAction) x: 0 doAction: (payload) -> @x = payload.n * payload.n public: value: () -> @x Hippodrome.start() action(4) expect(store.value()).toBe(16) it 'run callbacks after other stores', -> action = Hippodrome.createAction displayName: '<NAME>' build: (n) -> {n: n} first = makeTempStore initialize: -> @dispatch(action).to(@doAction) x: 0 doAction: (payload) -> @x = payload.n * payload.n public: value: () -> @x second = makeTempStore initialize: -> @dispatch(action).after(first).to(@doAction) x: 0 doAction: (payload) -> @x = first.value() + payload.n public: value: () -> @x Hippodrome.start() action(5) expect(first.value()).toBe(25) expect(second.value()).toBe(30) it 'run callbacks after other stores no matter declaration order', -> action = Hippodrome.createAction displayName: 'test8' build: (n) -> {n: n} second = makeTempStore initialize: -> @x = 0 @dispatch(action).after(first).to(@doAction) doAction: (payload) -> @x = payload.n + first.value() public: value: () -> @x first = makeTempStore initialize: -> @x = 0 @dispatch(action).to(@doAction) doAction: (payload) -> @x = payload.n * 2 public: value: () -> @x Hippodrome.start() action(3) expect(first.value()).toBe(6) expect(second.value()).toBe(9) it 'fail when stores create a circular dependency', -> action = Hippodrome.createAction build: -> {} one = makeTempStore initialize: -> @dispatch(action).after(three).to(@doAction) doAction: (payload) -> @ran = true two = makeTempStore initialize: -> @dispatch(action).after(one).to(@doAction) doAction: (payload) -> @ran = true three = makeTempStore initialize: -> @dispatch(action).after(two).to(@doAction) doAction: (payload) -> @ran = true Hippodrome.start() expect(action).toThrow() it 'fail when the prerequisite store does not handle action', -> action = Hippodrome.createAction build: -> {} one = makeTempStore displayName: 'one' two = makeTempStore initialize: -> @dispatch(action).after(one).to(@doAction) doAction: -> @ran = true Hippodrome.start() expect(action).toThrow() it 'fail when registering for same action more than once', -> action = Hippodrome.createAction build: -> {} store = makeTempStore initialize: -> @dispatch(action).to(->) @dispatch(action).to(->) expect(Hippodrome.start).toThrow()
true
Hippodrome = require('../dist/hippodrome') _ = require('lodash') # This is annoying, but because the Dispatcher is a single instance across all # tests, stores created in one test still have their callbacks registered in # subsequent tests, unless we get rid of them like this. unregisterStore = (store) -> _.forEach store._storeImpl.dispatcherIdsByAction, (id, action) -> Hippodrome.Dispatcher.unregister(action, id) describe 'Stores', -> tempStores = [] makeTempStore = (options) -> store = Hippodrome.createStore(options) tempStores.push(store) return store beforeEach -> tempStores = [] afterEach -> _.forEach tempStores, unregisterStore it 'don\'t expose properties not in public', -> store = makeTempStore propOne: 'one' public: propTwo: 'two' expect(store.propOne).toBe(undefined) expect(store.propTwo).toBe('two') it 'functions in public have access to non-public properties', -> store = makeTempStore prop: 'value' public: fn: () -> "My Property Is: #{@prop}" expect(store.fn()).toBe('My Property Is: value') it 'run registered functions on trigger', -> store = makeTempStore public: doTrigger: () -> @trigger() ran = false store.register(() -> ran = true) store.doTrigger() expect(ran).toBe(true) it 'don\'t run unregistered functions on trigger', -> store = makeTempStore public: doTrigger: () -> @trigger() ran = false callback = () -> @trigger() store.register(callback) store.unregister(callback) store.doTrigger() expect(ran).toBe(false) it 'run initialize on Hippodrome start', -> store = makeTempStore initialize: -> @ran = true ran: false public: isRun: () -> @ran Hippodrome.start() expect(store.isRun()).toBe(true) it 'run initialize with options on Hippodrome start', -> store = Hippodrome.createStore initialize: (options) -> @x = options.n * 2 public: value: () -> @x Hippodrome.start(n: 6) expect(store.value()).toBe(12) it 'run registered functions on action dispatch', -> action = Hippodrome.createAction displayName: 'PI:NAME:<NAME>END_PI1' build: -> {} store = makeTempStore initialize: -> @dispatch(action).to(@doAction) ran: false doAction: (payload) -> @ran = true public: isRun: () -> @ran Hippodrome.start() action() expect(store.isRun()).toBe(true) it 'run registered functions by name on action dispatch', -> action = Hippodrome.createAction displayName: 'PI:NAME:<NAME>END_PI2' build: -> {} store = makeTempStore initialize: -> @dispatch(action).to('doAction') ran: false doAction: (payload) -> @ran = true public: isRun: () -> @ran Hippodrome.start() action() expect(store.isRun()).toBe(true) it 'run registered functions with payload data', -> action = Hippodrome.createAction displayName: 'PI:NAME:<NAME>END_PI3' build: (n) -> {n: n} store = makeTempStore initialize: -> @dispatch(action).to(@doAction) x: 0 doAction: (payload) -> @x = payload.n * payload.n public: value: () -> @x Hippodrome.start() action(4) expect(store.value()).toBe(16) it 'run callbacks after other stores', -> action = Hippodrome.createAction displayName: 'PI:NAME:<NAME>END_PI' build: (n) -> {n: n} first = makeTempStore initialize: -> @dispatch(action).to(@doAction) x: 0 doAction: (payload) -> @x = payload.n * payload.n public: value: () -> @x second = makeTempStore initialize: -> @dispatch(action).after(first).to(@doAction) x: 0 doAction: (payload) -> @x = first.value() + payload.n public: value: () -> @x Hippodrome.start() action(5) expect(first.value()).toBe(25) expect(second.value()).toBe(30) it 'run callbacks after other stores no matter declaration order', -> action = Hippodrome.createAction displayName: 'test8' build: (n) -> {n: n} second = makeTempStore initialize: -> @x = 0 @dispatch(action).after(first).to(@doAction) doAction: (payload) -> @x = payload.n + first.value() public: value: () -> @x first = makeTempStore initialize: -> @x = 0 @dispatch(action).to(@doAction) doAction: (payload) -> @x = payload.n * 2 public: value: () -> @x Hippodrome.start() action(3) expect(first.value()).toBe(6) expect(second.value()).toBe(9) it 'fail when stores create a circular dependency', -> action = Hippodrome.createAction build: -> {} one = makeTempStore initialize: -> @dispatch(action).after(three).to(@doAction) doAction: (payload) -> @ran = true two = makeTempStore initialize: -> @dispatch(action).after(one).to(@doAction) doAction: (payload) -> @ran = true three = makeTempStore initialize: -> @dispatch(action).after(two).to(@doAction) doAction: (payload) -> @ran = true Hippodrome.start() expect(action).toThrow() it 'fail when the prerequisite store does not handle action', -> action = Hippodrome.createAction build: -> {} one = makeTempStore displayName: 'one' two = makeTempStore initialize: -> @dispatch(action).after(one).to(@doAction) doAction: -> @ran = true Hippodrome.start() expect(action).toThrow() it 'fail when registering for same action more than once', -> action = Hippodrome.createAction build: -> {} store = makeTempStore initialize: -> @dispatch(action).to(->) @dispatch(action).to(->) expect(Hippodrome.start).toThrow()
[ { "context": "b:\n# @(#)$Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $\n# @author: koolb@hotmail.com\n# @description: De", "end": 75, "score": 0.5638165473937988, "start": 69, "tag": "USERNAME", "value": "noppix" }, { "context": "ffee 543 2014-11-05 00:41:31Z knoppix $\n# @author:...
src/bg.coffee
koolb/devops-ce-demo
0
# vim:ts=2 expandtab: # @(#)$Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $ # @author: koolb@hotmail.com # @description: Demo/fake sidepanel updater # @usage: click on open items to see content and check to make it mine! # # @release state: alpha testing only many functions do not yet exist # console.log "#(@) $Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $" console.log 'bg.html starting!' console.log "this is %0", @ chrome.tabs.onUpdated.addListener (tabId) -> chrome.pageAction.show tabId chrome.tabs.getSelected null, (tab) -> chrome.pageAction.show tab.id chrome.pageAction.onClicked.addListener (tab) -> chrome.tabs.getSelected null, (tab) -> chrome.tabs.sendRequest tab.id, {callFunction: "toggleSB"}, (response) -> console.log response console.log 'bg.html done.'
217151
# vim:ts=2 expandtab: # @(#)$Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $ # @author: <EMAIL> # @description: Demo/fake sidepanel updater # @usage: click on open items to see content and check to make it mine! # # @release state: alpha testing only many functions do not yet exist # console.log "#(@) $Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $" console.log 'bg.html starting!' console.log "this is %0", @ chrome.tabs.onUpdated.addListener (tabId) -> chrome.pageAction.show tabId chrome.tabs.getSelected null, (tab) -> chrome.pageAction.show tab.id chrome.pageAction.onClicked.addListener (tab) -> chrome.tabs.getSelected null, (tab) -> chrome.tabs.sendRequest tab.id, {callFunction: "toggleSB"}, (response) -> console.log response console.log 'bg.html done.'
true
# vim:ts=2 expandtab: # @(#)$Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $ # @author: PI:EMAIL:<EMAIL>END_PI # @description: Demo/fake sidepanel updater # @usage: click on open items to see content and check to make it mine! # # @release state: alpha testing only many functions do not yet exist # console.log "#(@) $Id: bg.coffee 543 2014-11-05 00:41:31Z knoppix $" console.log 'bg.html starting!' console.log "this is %0", @ chrome.tabs.onUpdated.addListener (tabId) -> chrome.pageAction.show tabId chrome.tabs.getSelected null, (tab) -> chrome.pageAction.show tab.id chrome.pageAction.onClicked.addListener (tab) -> chrome.tabs.getSelected null, (tab) -> chrome.tabs.sendRequest tab.id, {callFunction: "toggleSB"}, (response) -> console.log response console.log 'bg.html done.'
[ { "context": "arseToken} = require('../index')(encryptionKey: '135x!')({config:{}})\n\nuserId = new Date().valueOf().to", "end": 113, "score": 0.8806249499320984, "start": 110, "tag": "KEY", "value": "35x" }, { "context": "ed\nconsole.log 'decrypted', decrypted\npassword = \"monkey12...
src/test/test.coffee
ndxbxrme/rs-token
0
{encrypt, decrypt, hashPassword, checkHash, generateToken, parseToken} = require('../index')(encryptionKey: '135x!')({config:{}}) userId = new Date().valueOf().toString(23) console.log 'userId', userId encrypted = encrypt userId console.log 'encrypted', encrypted decrypted = decrypt encrypted console.log 'decrypted', decrypted password = "monkey123" console.log 'password', password hash = hashPassword password console.log 'hash', hash console.log 'pass matches hash =', checkHash password, hash token = generateToken userId, 4 console.log 'token', token parsedId = parseToken token console.log 'parsed userId', parsedId
221264
{encrypt, decrypt, hashPassword, checkHash, generateToken, parseToken} = require('../index')(encryptionKey: '1<KEY>!')({config:{}}) userId = new Date().valueOf().toString(23) console.log 'userId', userId encrypted = encrypt userId console.log 'encrypted', encrypted decrypted = decrypt encrypted console.log 'decrypted', decrypted password = "<PASSWORD>" console.log 'password', password hash = hashPassword password console.log 'hash', hash console.log 'pass matches hash =', checkHash password, hash token = generateToken userId, 4 console.log 'token', token parsedId = parseToken token console.log 'parsed userId', parsedId
true
{encrypt, decrypt, hashPassword, checkHash, generateToken, parseToken} = require('../index')(encryptionKey: '1PI:KEY:<KEY>END_PI!')({config:{}}) userId = new Date().valueOf().toString(23) console.log 'userId', userId encrypted = encrypt userId console.log 'encrypted', encrypted decrypted = decrypt encrypted console.log 'decrypted', decrypted password = "PI:PASSWORD:<PASSWORD>END_PI" console.log 'password', password hash = hashPassword password console.log 'hash', hash console.log 'pass matches hash =', checkHash password, hash token = generateToken userId, 4 console.log 'token', token parsedId = parseToken token console.log 'parsed userId', parsedId
[ { "context": "t> - Send <text> to <phone number>\n#\n# Author:\n# Kazuma Ieiri\n\nquerystring = require 'querystring'\nclient = req", "end": 590, "score": 0.9998847842216492, "start": 578, "tag": "NAME", "value": "Kazuma Ieiri" } ]
src/twilio-call.coffee
hbkr/hubot-twilio-call
5
# Description # A Hubot script that calls the twilio API # # Dependencies: # "querystring": "0.2.0", # "twilio": "2.2.1" # # Configuration: # HUBOT_TWILIO_FROM_PHONE_NUMBER (from phone number) # HUBOT_TWILIO_ACCOUNT_SID (twilio API account SID) # HUBOT_TWILIO_AUTH_TOKEN (twilio API auth token) # HUBOT_TWILIO_VOICE_TYPE (twilio API voice type) # HUBOT_TWILIO_LANGUAGE (twilio API language) # # Commands: # hubot call <phone number> <text> - Call to <phone number> say <text> # hubot sms <phone number> <text> - Send <text> to <phone number> # # Author: # Kazuma Ieiri querystring = require 'querystring' client = require('twilio')(process.env.HUBOT_TWILIO_ACCOUNT_SID, process.env.HUBOT_TWILIO_AUTH_TOKEN) module.exports = (robot) -> robot.respond /(call|sms) ([^"]+)/i, (msg) -> options = msg.match[2].split(' ') to_phone_number = options[0] send_text = options[1] return unless send_text? #call if msg.match[1] == "call" twiml = "<Response><Say voice=\"#{process.env.HUBOT_TWILIO_VOICE_TYPE ? "woman"}\" language=\"#{process.env.HUBOT_TWILIO_LANGUAGE ? "ja-jp"}\">#{send_text}</Say></Response>" client.makeCall { to: to_phone_number from: process.env.HUBOT_TWILIO_FROM_PHONE_NUMBER url: "http://twimlets.com/echo?Twiml=#{querystring.escape(twiml)}" }, (err, responseData) -> if err? robot.logger.error err msg.send("error: #{err.message}") else msg.send("Call to #{to_phone_number}") #sms else client.sendMessage { to: to_phone_number from: process.env.HUBOT_TWILIO_FROM_PHONE_NUMBER body: send_text }, (err, responseData) -> if err? robot.logger.error err msg.send("error: #{err.message}") else msg.send("Send to #{to_phone_number}")
178225
# Description # A Hubot script that calls the twilio API # # Dependencies: # "querystring": "0.2.0", # "twilio": "2.2.1" # # Configuration: # HUBOT_TWILIO_FROM_PHONE_NUMBER (from phone number) # HUBOT_TWILIO_ACCOUNT_SID (twilio API account SID) # HUBOT_TWILIO_AUTH_TOKEN (twilio API auth token) # HUBOT_TWILIO_VOICE_TYPE (twilio API voice type) # HUBOT_TWILIO_LANGUAGE (twilio API language) # # Commands: # hubot call <phone number> <text> - Call to <phone number> say <text> # hubot sms <phone number> <text> - Send <text> to <phone number> # # Author: # <NAME> querystring = require 'querystring' client = require('twilio')(process.env.HUBOT_TWILIO_ACCOUNT_SID, process.env.HUBOT_TWILIO_AUTH_TOKEN) module.exports = (robot) -> robot.respond /(call|sms) ([^"]+)/i, (msg) -> options = msg.match[2].split(' ') to_phone_number = options[0] send_text = options[1] return unless send_text? #call if msg.match[1] == "call" twiml = "<Response><Say voice=\"#{process.env.HUBOT_TWILIO_VOICE_TYPE ? "woman"}\" language=\"#{process.env.HUBOT_TWILIO_LANGUAGE ? "ja-jp"}\">#{send_text}</Say></Response>" client.makeCall { to: to_phone_number from: process.env.HUBOT_TWILIO_FROM_PHONE_NUMBER url: "http://twimlets.com/echo?Twiml=#{querystring.escape(twiml)}" }, (err, responseData) -> if err? robot.logger.error err msg.send("error: #{err.message}") else msg.send("Call to #{to_phone_number}") #sms else client.sendMessage { to: to_phone_number from: process.env.HUBOT_TWILIO_FROM_PHONE_NUMBER body: send_text }, (err, responseData) -> if err? robot.logger.error err msg.send("error: #{err.message}") else msg.send("Send to #{to_phone_number}")
true
# Description # A Hubot script that calls the twilio API # # Dependencies: # "querystring": "0.2.0", # "twilio": "2.2.1" # # Configuration: # HUBOT_TWILIO_FROM_PHONE_NUMBER (from phone number) # HUBOT_TWILIO_ACCOUNT_SID (twilio API account SID) # HUBOT_TWILIO_AUTH_TOKEN (twilio API auth token) # HUBOT_TWILIO_VOICE_TYPE (twilio API voice type) # HUBOT_TWILIO_LANGUAGE (twilio API language) # # Commands: # hubot call <phone number> <text> - Call to <phone number> say <text> # hubot sms <phone number> <text> - Send <text> to <phone number> # # Author: # PI:NAME:<NAME>END_PI querystring = require 'querystring' client = require('twilio')(process.env.HUBOT_TWILIO_ACCOUNT_SID, process.env.HUBOT_TWILIO_AUTH_TOKEN) module.exports = (robot) -> robot.respond /(call|sms) ([^"]+)/i, (msg) -> options = msg.match[2].split(' ') to_phone_number = options[0] send_text = options[1] return unless send_text? #call if msg.match[1] == "call" twiml = "<Response><Say voice=\"#{process.env.HUBOT_TWILIO_VOICE_TYPE ? "woman"}\" language=\"#{process.env.HUBOT_TWILIO_LANGUAGE ? "ja-jp"}\">#{send_text}</Say></Response>" client.makeCall { to: to_phone_number from: process.env.HUBOT_TWILIO_FROM_PHONE_NUMBER url: "http://twimlets.com/echo?Twiml=#{querystring.escape(twiml)}" }, (err, responseData) -> if err? robot.logger.error err msg.send("error: #{err.message}") else msg.send("Call to #{to_phone_number}") #sms else client.sendMessage { to: to_phone_number from: process.env.HUBOT_TWILIO_FROM_PHONE_NUMBER body: send_text }, (err, responseData) -> if err? robot.logger.error err msg.send("error: #{err.message}") else msg.send("Send to #{to_phone_number}")
[ { "context": "eep.equal {\n calvin:\n id: 'calvin'\n startTime: '2016-09-28T14:00:00Z'\n ", "end": 1257, "score": 0.8197587728500366, "start": 1251, "tag": "NAME", "value": "calvin" } ]
test/integration/non-recurring-today-we-are-in-it-spec.coffee
octoblu/groundhog-day-service
0
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' moment = require 'moment' request = require 'request' sinon = require 'sinon' NON_RECURRING_TODAY_WE_ARE_IN_IT = require '../fixtures/non-recurring-today-we-are-in-it.cson' Server = require '../../src/server' describe 'non-recurring-today-we-are-in-it', -> beforeEach 'Go back in time to 8am MST 2016-09-28 ', => sinon.useFakeTimers moment('2016-09-28T15:00:00Z').valueOf() afterEach 'Back to the future', => sinon.restore() beforeEach (done) -> @server = new Server disableLogging: true, logFn: => @server.run (error) => return done error if error? @request = request.defaults baseUrl: "http://localhost:#{@server.address().port}" json: true done() afterEach (done) -> @server.destroy done describe 'On POST /agenda', -> beforeEach (done) -> @request.post '/agendas', body: NON_RECURRING_TODAY_WE_ARE_IN_IT, (error, @response, @body) => done error it 'should respond with a 200', -> expect(@response.statusCode).to.equal 200 it 'should respond an object containing the meeting', -> expect(@body).to.deep.equal { calvin: id: 'calvin' startTime: '2016-09-28T14:00:00Z' endTime: '2016-09-28T16:00:00Z' }
18649
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' moment = require 'moment' request = require 'request' sinon = require 'sinon' NON_RECURRING_TODAY_WE_ARE_IN_IT = require '../fixtures/non-recurring-today-we-are-in-it.cson' Server = require '../../src/server' describe 'non-recurring-today-we-are-in-it', -> beforeEach 'Go back in time to 8am MST 2016-09-28 ', => sinon.useFakeTimers moment('2016-09-28T15:00:00Z').valueOf() afterEach 'Back to the future', => sinon.restore() beforeEach (done) -> @server = new Server disableLogging: true, logFn: => @server.run (error) => return done error if error? @request = request.defaults baseUrl: "http://localhost:#{@server.address().port}" json: true done() afterEach (done) -> @server.destroy done describe 'On POST /agenda', -> beforeEach (done) -> @request.post '/agendas', body: NON_RECURRING_TODAY_WE_ARE_IN_IT, (error, @response, @body) => done error it 'should respond with a 200', -> expect(@response.statusCode).to.equal 200 it 'should respond an object containing the meeting', -> expect(@body).to.deep.equal { calvin: id: '<NAME>' startTime: '2016-09-28T14:00:00Z' endTime: '2016-09-28T16:00:00Z' }
true
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' moment = require 'moment' request = require 'request' sinon = require 'sinon' NON_RECURRING_TODAY_WE_ARE_IN_IT = require '../fixtures/non-recurring-today-we-are-in-it.cson' Server = require '../../src/server' describe 'non-recurring-today-we-are-in-it', -> beforeEach 'Go back in time to 8am MST 2016-09-28 ', => sinon.useFakeTimers moment('2016-09-28T15:00:00Z').valueOf() afterEach 'Back to the future', => sinon.restore() beforeEach (done) -> @server = new Server disableLogging: true, logFn: => @server.run (error) => return done error if error? @request = request.defaults baseUrl: "http://localhost:#{@server.address().port}" json: true done() afterEach (done) -> @server.destroy done describe 'On POST /agenda', -> beforeEach (done) -> @request.post '/agendas', body: NON_RECURRING_TODAY_WE_ARE_IN_IT, (error, @response, @body) => done error it 'should respond with a 200', -> expect(@response.statusCode).to.equal 200 it 'should respond an object containing the meeting', -> expect(@body).to.deep.equal { calvin: id: 'PI:NAME:<NAME>END_PI' startTime: '2016-09-28T14:00:00Z' endTime: '2016-09-28T16:00:00Z' }
[ { "context": "require(\"./Framer\")\n\n# Made with Framer\n# by Pete Lada\n# www.framerjs.com\n\n# Background\nbg = new Backgro", "end": 54, "score": 0.9998833537101746, "start": 45, "tag": "NAME", "value": "Pete Lada" } ]
src/index.coffee
irwansyahwii/-SimpleLayer
0
require("./Framer") # Made with Framer # by Pete Lada # www.framerjs.com # Background bg = new BackgroundLayer backgroundColor: "#439FD8", name:"BackgroundLayer" # Defaults and variables animSpeed = .25 defaultAnimCurve = "spring(250,25,5)" smallBounce = "spring(250,25,2)" margin = 20 noAnim = curve: "ease" time: 0 delay: 0 logoDefaultAnim = curve: "ease" time: .2 delay: 0 logoReturningAnim = curve: defaultAnimCurve time: .3 delay: .1 Framer.Defaults.Animation = curve: defaultAnimCurve time: animSpeed # Create image layers photoArea = new Layer x:0, y:0, width:640, height:640, image:"images/photo-area.png", scale: .86, opacity: 0, name: "photoArea" closePhoto = new Layer x: 560, y: 40, width: 50, height: 50, backgroundColor: "transparent", name: "closePhoto" container = new Layer x: 0, y:0, width: 640, height: 1136, backgroundColor: "transparent", name: "container" container.clip = false container.scroll = true container.states.animationOptions = curve: smallBounce containerMask = new Layer x: 0, y: -50, width: 640, height: 1963 + 50, backgroundColor: "rgba(0,0,0,.8)", opacity:0 , name: "containerMask" header = new Layer x: 0, y: 0, width: 640, height: 413, backgroundColor: "#439FD8", name: "header" logo = new Layer x:0, y:114, width:328, height:70, image:"images/guidebook_logo_dark.png", name: "logo" store = new Layer x:0, y:413, width:640, height:1963, image:"images/store.png", name: "store" codePlaceholder = new Layer x:20, y:22, width:171, height:34, image:"images/code-placeholder.png", opacity: 0, name: "codePlaceholder" searchBar = new Layer x:30, y:304, width:580, height:79, backgroundColor: "white", borderRadius: "8px", name: "searchBar" searchBar.shadowX = 0 searchPlaceholder = new Layer x:20, y:22, width:171, height:37, image:"images/search-placeholder.png", name: "searchPlaceholder" reset = new Layer x: 0, y: 413, width: 640, height: 2376, backgroundColor: "rgba(255,255,255,.6)", opacity: 0, name: "reset" redeemText = new Layer x:0, y:114, width:362, height:65, image:"images/redeem-text.png", opacity: 0, name: "redeemText" cancelSearch = new Layer x:525, y:20, width:40, height:40, image:"images/cancel-search.png", opacity: 0, index: 0, name: "cancelSearch" useCode = new Layer x:0, y:searchBar.y-30-43, width:180, height:43, image:"images/use-code.png", name: "useCode" useCode.centerX() qrButton = new Layer x: searchBar.width - 200, y: 0, width: 200, height: searchBar.height, backgroundColor: "transparent", name: "qrButton" qr = new Layer x:150, y:0, width:34, height:34, image:"images/qr.png", name: "qr" ptr = new Layer x:0, y: header.height - 100, height: 100, width: 640, backgroundColor:"transparent", name: "ptr" ptrBorder = new Layer x: 0, y: ptr.height-2, height: 2, width: 640, backgroundColor: "#D7E1E9", name: "ptrBorder" arrow = new Layer x:0, y:0, width:33, height:44, image:"images/pull-arrow.png", name: "arrow" refresh = new Layer x:0, y:0, width:44, height:44, image:"images/refresh.png", opacity: 0, name: "refresh" # Add sublayers ptr.addSubLayer arrow ptr.addSubLayer ptrBorder ptr.addSubLayer refresh arrow.center() refresh.center() ptr.index = 0 qrButton.addSubLayer qr container.addSubLayer store container.addSubLayer header container.addSubLayer containerMask container.addSubLayer reset header.addSubLayer useCode header.addSubLayer redeemText header.addSubLayer logo header.addSubLayer searchBar searchBar.addSubLayer searchPlaceholder searchBar.addSubLayer codePlaceholder codePlaceholder.centerY() searchBar.addSubLayer qrButton qr.centerY() searchBar.addSubLayer cancelSearch # Center redeem and logo within parent redeemText.centerX() logo.centerX() # States for various items qrButton.states.add hidden: opacity: 0 container.states.add scanning: y: photoArea.height photoArea.states.add scanning: scale: 1 opacity: 1 containerMask.states.add scanning: opacity: 1 header.states.add searching: y: -(header.height - margin - searchBar.height - margin) redeeming: height: header.height - useCode.height - margin stickySearch: y: 0 height: margin + searchBar.height + margin stickyReturn: y: 0 height: 413 searchBar.states.add searching: y: header.height - margin - searchBar.height redeeming: y: useCode.y sticky: y: margin stickyReturn: y:304 reset.states.add searching: opacity: 1 y: margin + searchBar.height + margin usingCode: opacity: 1 y: header.height - useCode.height - margin scanning: opacity: .001 y: 0 codePlaceholder.states.add redeeming: opacity: 1 redeemText.states.add visible: opacity: 1 useCode.states.add hidden: opacity: 0 pressed: scale: .9 logo.states.add searching: y: logo.y - 50 opacity: 0 returning: y: logo.y opacity: 1 hidden: opacity: 0 store.states.add searching: y: 20 + searchBar.height + 20 opacity: 1 redeeming: y: header.height - useCode.height - margin scanning: y: header.height + photoArea.height blur: 5 refreshing: y: header.height + 100 searchPlaceholder.states.add hidden: opacity:0 x: searchPlaceholder.x - 100 cancelSearch.states.add visible: opacity: 1 index: 1 ptr.states.add refreshing: y: header.height redeemText.states.animationOptions = curve: "ease" time: animSpeed searchPlaceholder.states.animationOptions = curve: smallBounce time: animSpeed cancelSearch.states.animationOptions = curve: "ease" time: animSpeed # State functions resetView = -> searchPlaceholder.states.switch "default" qrButton.states.switch "default" header.states.switch "default" logo.states.switch "returning" store.states.switch "default" reset.states.switch "default" cancelSearch.states.switch "default" redeemText.states.switch "default" #***** searchBar.states.switch "default" useCode.states.switch "default" container.states.switch "default" #***** containerMask.states.switch "default" photoArea.states.switch "default" #***** codePlaceholder.states.switch "default" Utils.delay 0.5, -> bg.backgroundColor = "#439FD8" qrButton.index = 100 initSearch = -> if !sticky header.states.switch "searching" logo.states.switch "searching" qrButton.states.switch "hidden" store.states.switch "searching" reset.states.switch "searching" cancelSearch.states.switch "visible" searchBar.states.switch "searching" useCode.states.switch "hidden" qrButton.index = 0 else reset.states.switch "searching" initRedeem = -> searchPlaceholder.states.switch "hidden" reset.states.switch "usingCode" searchBar.states.switch "redeeming" cancelSearch.states.switch "visible" redeemText.states.switch "visible" logo.states.switch "hidden" useCode.states.switch "hidden" header.states.switch "redeeming" store.states.switch "redeeming" codePlaceholder.states.switch "redeeming" qrButton.states.switch "hidden" qrButton.index = 0 initScan = -> container.states.switch "scanning" reset.states.switch "scanning" containerMask.states.switch "scanning" bg.backgroundColor = "black" photoArea.states.switch "scanning" initStickySearch = -> header.states.switch "stickySearch" logo.states.switch "hidden" container.removeSubLayer header searchBar.states.switch "sticky" cancelStickySearch = -> container.addSubLayer header header.index = 1 header.states.switch "stickyReturn" searchBar.states.switch "stickyReturn" searchBar.states.switch "default" # Events searchPlaceholder.on Events.Click, -> console.log "searchPlaceholder on Click" initSearch() qrButton.on Events.Click, -> initScan() qr.on Events.Click, -> initScan() useCode.on Events.TouchStart, -> this.states.switch "pressed" useCode.on Events.MouseOut, -> this.states.switch "default" useCode.on Events.Click, -> initRedeem() reset.on Events.Click, -> resetView() cancelSearch.on Events.Click, -> console.log "cancelSearch on Click" # searchPlaceholder.states.switch "default" resetView() closePhoto.on Events.Click, -> resetView() # State switch functions # These change the animation for an item based on its new state logo.states.on Events.StateWillSwitch, (oldState, newState) -> if newState == 'returning' logo.states.animationOptions = logoReturningAnim else logo.states.animationOptions = logoDefaultAnim reset.on Events.AnimationStart, (event, layer) -> layer.visible = true reset.on Events.AnimationEnd, (event, layer) -> if layer.opacity == 0 layer.visible = false else layer.visible = true header.on Events.StateWillSwitch, (oldState, newState) -> if newState == "stickyReturn" header.states.animationOptions = noAnim else if newState == "stickySearch" header.states.animationOptions = noAnim else header.states.animationOptions = Framer.Defaults.Animation searchBar.on Events.StateWillSwitch, (oldState, newState) -> if newState is "sticky" or sticky searchBar.states.animationOptions = noAnim else searchBar.states.animationOptions = Framer.Defaults.Animation # Pull to refresh spin = -> refresh.animate properties: rotation: 1080 time: 1.5 curve: "linear" Utils.delay 1.5, -> refresh.rotation = 0 spin() spin() startY = 0 storeStartY = store.y store.draggable.enabled = true store.draggable.speedX = 0 store.on Events.DragStart, (event) -> bg.backgroundColor = "#F6FBFE" startY = event.pageY store.on Events.DragMove, (event) -> deltaY = startY - event.pageY store.y = storeStartY - deltaY ptr.y = store.y - ptr.height if deltaY > 0 header.y = -deltaY if deltaY < -100 arrow.animate properties: rotation: 180 time: .12 curve: "ease" else arrow.animate properties: rotation: 0 time: .12 curve: "ease" store.on Events.DragEnd, (event) -> deltaY = startY - event.pageY if deltaY < -100 startRefresh() else store.states.switch "default" ptr.states.switch "default" header.states.switch "default" startRefresh = -> store.states.switch "refreshing" ptr.states.switch "refreshing" refresh.animate properties: opacity: 1 time: .2 curve: "ease" arrow.animate properties: opacity: 0 time: .2 curve: "ease" Utils.delay 2, -> endRefresh() endRefresh = -> store.states.switch "default" ptr.states.switch "default" refresh.opacity = 0 arrow.animate properties: opacity: 1 time: .2 curve: "ease" Utils.delay .2, -> bg.backgroundColor = "#439FD8" arrow.rotation = 0 # Scroll events sticky = false opacity = 1 limit = header.height - 20 - searchBar.height - 20 container.on Events.Scroll, -> x = Utils.modulate(container.scrollY, [0, limit-100], [1, 0], true) y = Utils.modulate(container.scrollY, [0, limit], [1, 0], true) logo.opacity = x useCode.opacity = y if container.scrollY > limit if !sticky initStickySearch() sticky = true else cancelStickySearch() sticky = false
161402
require("./Framer") # Made with Framer # by <NAME> # www.framerjs.com # Background bg = new BackgroundLayer backgroundColor: "#439FD8", name:"BackgroundLayer" # Defaults and variables animSpeed = .25 defaultAnimCurve = "spring(250,25,5)" smallBounce = "spring(250,25,2)" margin = 20 noAnim = curve: "ease" time: 0 delay: 0 logoDefaultAnim = curve: "ease" time: .2 delay: 0 logoReturningAnim = curve: defaultAnimCurve time: .3 delay: .1 Framer.Defaults.Animation = curve: defaultAnimCurve time: animSpeed # Create image layers photoArea = new Layer x:0, y:0, width:640, height:640, image:"images/photo-area.png", scale: .86, opacity: 0, name: "photoArea" closePhoto = new Layer x: 560, y: 40, width: 50, height: 50, backgroundColor: "transparent", name: "closePhoto" container = new Layer x: 0, y:0, width: 640, height: 1136, backgroundColor: "transparent", name: "container" container.clip = false container.scroll = true container.states.animationOptions = curve: smallBounce containerMask = new Layer x: 0, y: -50, width: 640, height: 1963 + 50, backgroundColor: "rgba(0,0,0,.8)", opacity:0 , name: "containerMask" header = new Layer x: 0, y: 0, width: 640, height: 413, backgroundColor: "#439FD8", name: "header" logo = new Layer x:0, y:114, width:328, height:70, image:"images/guidebook_logo_dark.png", name: "logo" store = new Layer x:0, y:413, width:640, height:1963, image:"images/store.png", name: "store" codePlaceholder = new Layer x:20, y:22, width:171, height:34, image:"images/code-placeholder.png", opacity: 0, name: "codePlaceholder" searchBar = new Layer x:30, y:304, width:580, height:79, backgroundColor: "white", borderRadius: "8px", name: "searchBar" searchBar.shadowX = 0 searchPlaceholder = new Layer x:20, y:22, width:171, height:37, image:"images/search-placeholder.png", name: "searchPlaceholder" reset = new Layer x: 0, y: 413, width: 640, height: 2376, backgroundColor: "rgba(255,255,255,.6)", opacity: 0, name: "reset" redeemText = new Layer x:0, y:114, width:362, height:65, image:"images/redeem-text.png", opacity: 0, name: "redeemText" cancelSearch = new Layer x:525, y:20, width:40, height:40, image:"images/cancel-search.png", opacity: 0, index: 0, name: "cancelSearch" useCode = new Layer x:0, y:searchBar.y-30-43, width:180, height:43, image:"images/use-code.png", name: "useCode" useCode.centerX() qrButton = new Layer x: searchBar.width - 200, y: 0, width: 200, height: searchBar.height, backgroundColor: "transparent", name: "qrButton" qr = new Layer x:150, y:0, width:34, height:34, image:"images/qr.png", name: "qr" ptr = new Layer x:0, y: header.height - 100, height: 100, width: 640, backgroundColor:"transparent", name: "ptr" ptrBorder = new Layer x: 0, y: ptr.height-2, height: 2, width: 640, backgroundColor: "#D7E1E9", name: "ptrBorder" arrow = new Layer x:0, y:0, width:33, height:44, image:"images/pull-arrow.png", name: "arrow" refresh = new Layer x:0, y:0, width:44, height:44, image:"images/refresh.png", opacity: 0, name: "refresh" # Add sublayers ptr.addSubLayer arrow ptr.addSubLayer ptrBorder ptr.addSubLayer refresh arrow.center() refresh.center() ptr.index = 0 qrButton.addSubLayer qr container.addSubLayer store container.addSubLayer header container.addSubLayer containerMask container.addSubLayer reset header.addSubLayer useCode header.addSubLayer redeemText header.addSubLayer logo header.addSubLayer searchBar searchBar.addSubLayer searchPlaceholder searchBar.addSubLayer codePlaceholder codePlaceholder.centerY() searchBar.addSubLayer qrButton qr.centerY() searchBar.addSubLayer cancelSearch # Center redeem and logo within parent redeemText.centerX() logo.centerX() # States for various items qrButton.states.add hidden: opacity: 0 container.states.add scanning: y: photoArea.height photoArea.states.add scanning: scale: 1 opacity: 1 containerMask.states.add scanning: opacity: 1 header.states.add searching: y: -(header.height - margin - searchBar.height - margin) redeeming: height: header.height - useCode.height - margin stickySearch: y: 0 height: margin + searchBar.height + margin stickyReturn: y: 0 height: 413 searchBar.states.add searching: y: header.height - margin - searchBar.height redeeming: y: useCode.y sticky: y: margin stickyReturn: y:304 reset.states.add searching: opacity: 1 y: margin + searchBar.height + margin usingCode: opacity: 1 y: header.height - useCode.height - margin scanning: opacity: .001 y: 0 codePlaceholder.states.add redeeming: opacity: 1 redeemText.states.add visible: opacity: 1 useCode.states.add hidden: opacity: 0 pressed: scale: .9 logo.states.add searching: y: logo.y - 50 opacity: 0 returning: y: logo.y opacity: 1 hidden: opacity: 0 store.states.add searching: y: 20 + searchBar.height + 20 opacity: 1 redeeming: y: header.height - useCode.height - margin scanning: y: header.height + photoArea.height blur: 5 refreshing: y: header.height + 100 searchPlaceholder.states.add hidden: opacity:0 x: searchPlaceholder.x - 100 cancelSearch.states.add visible: opacity: 1 index: 1 ptr.states.add refreshing: y: header.height redeemText.states.animationOptions = curve: "ease" time: animSpeed searchPlaceholder.states.animationOptions = curve: smallBounce time: animSpeed cancelSearch.states.animationOptions = curve: "ease" time: animSpeed # State functions resetView = -> searchPlaceholder.states.switch "default" qrButton.states.switch "default" header.states.switch "default" logo.states.switch "returning" store.states.switch "default" reset.states.switch "default" cancelSearch.states.switch "default" redeemText.states.switch "default" #***** searchBar.states.switch "default" useCode.states.switch "default" container.states.switch "default" #***** containerMask.states.switch "default" photoArea.states.switch "default" #***** codePlaceholder.states.switch "default" Utils.delay 0.5, -> bg.backgroundColor = "#439FD8" qrButton.index = 100 initSearch = -> if !sticky header.states.switch "searching" logo.states.switch "searching" qrButton.states.switch "hidden" store.states.switch "searching" reset.states.switch "searching" cancelSearch.states.switch "visible" searchBar.states.switch "searching" useCode.states.switch "hidden" qrButton.index = 0 else reset.states.switch "searching" initRedeem = -> searchPlaceholder.states.switch "hidden" reset.states.switch "usingCode" searchBar.states.switch "redeeming" cancelSearch.states.switch "visible" redeemText.states.switch "visible" logo.states.switch "hidden" useCode.states.switch "hidden" header.states.switch "redeeming" store.states.switch "redeeming" codePlaceholder.states.switch "redeeming" qrButton.states.switch "hidden" qrButton.index = 0 initScan = -> container.states.switch "scanning" reset.states.switch "scanning" containerMask.states.switch "scanning" bg.backgroundColor = "black" photoArea.states.switch "scanning" initStickySearch = -> header.states.switch "stickySearch" logo.states.switch "hidden" container.removeSubLayer header searchBar.states.switch "sticky" cancelStickySearch = -> container.addSubLayer header header.index = 1 header.states.switch "stickyReturn" searchBar.states.switch "stickyReturn" searchBar.states.switch "default" # Events searchPlaceholder.on Events.Click, -> console.log "searchPlaceholder on Click" initSearch() qrButton.on Events.Click, -> initScan() qr.on Events.Click, -> initScan() useCode.on Events.TouchStart, -> this.states.switch "pressed" useCode.on Events.MouseOut, -> this.states.switch "default" useCode.on Events.Click, -> initRedeem() reset.on Events.Click, -> resetView() cancelSearch.on Events.Click, -> console.log "cancelSearch on Click" # searchPlaceholder.states.switch "default" resetView() closePhoto.on Events.Click, -> resetView() # State switch functions # These change the animation for an item based on its new state logo.states.on Events.StateWillSwitch, (oldState, newState) -> if newState == 'returning' logo.states.animationOptions = logoReturningAnim else logo.states.animationOptions = logoDefaultAnim reset.on Events.AnimationStart, (event, layer) -> layer.visible = true reset.on Events.AnimationEnd, (event, layer) -> if layer.opacity == 0 layer.visible = false else layer.visible = true header.on Events.StateWillSwitch, (oldState, newState) -> if newState == "stickyReturn" header.states.animationOptions = noAnim else if newState == "stickySearch" header.states.animationOptions = noAnim else header.states.animationOptions = Framer.Defaults.Animation searchBar.on Events.StateWillSwitch, (oldState, newState) -> if newState is "sticky" or sticky searchBar.states.animationOptions = noAnim else searchBar.states.animationOptions = Framer.Defaults.Animation # Pull to refresh spin = -> refresh.animate properties: rotation: 1080 time: 1.5 curve: "linear" Utils.delay 1.5, -> refresh.rotation = 0 spin() spin() startY = 0 storeStartY = store.y store.draggable.enabled = true store.draggable.speedX = 0 store.on Events.DragStart, (event) -> bg.backgroundColor = "#F6FBFE" startY = event.pageY store.on Events.DragMove, (event) -> deltaY = startY - event.pageY store.y = storeStartY - deltaY ptr.y = store.y - ptr.height if deltaY > 0 header.y = -deltaY if deltaY < -100 arrow.animate properties: rotation: 180 time: .12 curve: "ease" else arrow.animate properties: rotation: 0 time: .12 curve: "ease" store.on Events.DragEnd, (event) -> deltaY = startY - event.pageY if deltaY < -100 startRefresh() else store.states.switch "default" ptr.states.switch "default" header.states.switch "default" startRefresh = -> store.states.switch "refreshing" ptr.states.switch "refreshing" refresh.animate properties: opacity: 1 time: .2 curve: "ease" arrow.animate properties: opacity: 0 time: .2 curve: "ease" Utils.delay 2, -> endRefresh() endRefresh = -> store.states.switch "default" ptr.states.switch "default" refresh.opacity = 0 arrow.animate properties: opacity: 1 time: .2 curve: "ease" Utils.delay .2, -> bg.backgroundColor = "#439FD8" arrow.rotation = 0 # Scroll events sticky = false opacity = 1 limit = header.height - 20 - searchBar.height - 20 container.on Events.Scroll, -> x = Utils.modulate(container.scrollY, [0, limit-100], [1, 0], true) y = Utils.modulate(container.scrollY, [0, limit], [1, 0], true) logo.opacity = x useCode.opacity = y if container.scrollY > limit if !sticky initStickySearch() sticky = true else cancelStickySearch() sticky = false
true
require("./Framer") # Made with Framer # by PI:NAME:<NAME>END_PI # www.framerjs.com # Background bg = new BackgroundLayer backgroundColor: "#439FD8", name:"BackgroundLayer" # Defaults and variables animSpeed = .25 defaultAnimCurve = "spring(250,25,5)" smallBounce = "spring(250,25,2)" margin = 20 noAnim = curve: "ease" time: 0 delay: 0 logoDefaultAnim = curve: "ease" time: .2 delay: 0 logoReturningAnim = curve: defaultAnimCurve time: .3 delay: .1 Framer.Defaults.Animation = curve: defaultAnimCurve time: animSpeed # Create image layers photoArea = new Layer x:0, y:0, width:640, height:640, image:"images/photo-area.png", scale: .86, opacity: 0, name: "photoArea" closePhoto = new Layer x: 560, y: 40, width: 50, height: 50, backgroundColor: "transparent", name: "closePhoto" container = new Layer x: 0, y:0, width: 640, height: 1136, backgroundColor: "transparent", name: "container" container.clip = false container.scroll = true container.states.animationOptions = curve: smallBounce containerMask = new Layer x: 0, y: -50, width: 640, height: 1963 + 50, backgroundColor: "rgba(0,0,0,.8)", opacity:0 , name: "containerMask" header = new Layer x: 0, y: 0, width: 640, height: 413, backgroundColor: "#439FD8", name: "header" logo = new Layer x:0, y:114, width:328, height:70, image:"images/guidebook_logo_dark.png", name: "logo" store = new Layer x:0, y:413, width:640, height:1963, image:"images/store.png", name: "store" codePlaceholder = new Layer x:20, y:22, width:171, height:34, image:"images/code-placeholder.png", opacity: 0, name: "codePlaceholder" searchBar = new Layer x:30, y:304, width:580, height:79, backgroundColor: "white", borderRadius: "8px", name: "searchBar" searchBar.shadowX = 0 searchPlaceholder = new Layer x:20, y:22, width:171, height:37, image:"images/search-placeholder.png", name: "searchPlaceholder" reset = new Layer x: 0, y: 413, width: 640, height: 2376, backgroundColor: "rgba(255,255,255,.6)", opacity: 0, name: "reset" redeemText = new Layer x:0, y:114, width:362, height:65, image:"images/redeem-text.png", opacity: 0, name: "redeemText" cancelSearch = new Layer x:525, y:20, width:40, height:40, image:"images/cancel-search.png", opacity: 0, index: 0, name: "cancelSearch" useCode = new Layer x:0, y:searchBar.y-30-43, width:180, height:43, image:"images/use-code.png", name: "useCode" useCode.centerX() qrButton = new Layer x: searchBar.width - 200, y: 0, width: 200, height: searchBar.height, backgroundColor: "transparent", name: "qrButton" qr = new Layer x:150, y:0, width:34, height:34, image:"images/qr.png", name: "qr" ptr = new Layer x:0, y: header.height - 100, height: 100, width: 640, backgroundColor:"transparent", name: "ptr" ptrBorder = new Layer x: 0, y: ptr.height-2, height: 2, width: 640, backgroundColor: "#D7E1E9", name: "ptrBorder" arrow = new Layer x:0, y:0, width:33, height:44, image:"images/pull-arrow.png", name: "arrow" refresh = new Layer x:0, y:0, width:44, height:44, image:"images/refresh.png", opacity: 0, name: "refresh" # Add sublayers ptr.addSubLayer arrow ptr.addSubLayer ptrBorder ptr.addSubLayer refresh arrow.center() refresh.center() ptr.index = 0 qrButton.addSubLayer qr container.addSubLayer store container.addSubLayer header container.addSubLayer containerMask container.addSubLayer reset header.addSubLayer useCode header.addSubLayer redeemText header.addSubLayer logo header.addSubLayer searchBar searchBar.addSubLayer searchPlaceholder searchBar.addSubLayer codePlaceholder codePlaceholder.centerY() searchBar.addSubLayer qrButton qr.centerY() searchBar.addSubLayer cancelSearch # Center redeem and logo within parent redeemText.centerX() logo.centerX() # States for various items qrButton.states.add hidden: opacity: 0 container.states.add scanning: y: photoArea.height photoArea.states.add scanning: scale: 1 opacity: 1 containerMask.states.add scanning: opacity: 1 header.states.add searching: y: -(header.height - margin - searchBar.height - margin) redeeming: height: header.height - useCode.height - margin stickySearch: y: 0 height: margin + searchBar.height + margin stickyReturn: y: 0 height: 413 searchBar.states.add searching: y: header.height - margin - searchBar.height redeeming: y: useCode.y sticky: y: margin stickyReturn: y:304 reset.states.add searching: opacity: 1 y: margin + searchBar.height + margin usingCode: opacity: 1 y: header.height - useCode.height - margin scanning: opacity: .001 y: 0 codePlaceholder.states.add redeeming: opacity: 1 redeemText.states.add visible: opacity: 1 useCode.states.add hidden: opacity: 0 pressed: scale: .9 logo.states.add searching: y: logo.y - 50 opacity: 0 returning: y: logo.y opacity: 1 hidden: opacity: 0 store.states.add searching: y: 20 + searchBar.height + 20 opacity: 1 redeeming: y: header.height - useCode.height - margin scanning: y: header.height + photoArea.height blur: 5 refreshing: y: header.height + 100 searchPlaceholder.states.add hidden: opacity:0 x: searchPlaceholder.x - 100 cancelSearch.states.add visible: opacity: 1 index: 1 ptr.states.add refreshing: y: header.height redeemText.states.animationOptions = curve: "ease" time: animSpeed searchPlaceholder.states.animationOptions = curve: smallBounce time: animSpeed cancelSearch.states.animationOptions = curve: "ease" time: animSpeed # State functions resetView = -> searchPlaceholder.states.switch "default" qrButton.states.switch "default" header.states.switch "default" logo.states.switch "returning" store.states.switch "default" reset.states.switch "default" cancelSearch.states.switch "default" redeemText.states.switch "default" #***** searchBar.states.switch "default" useCode.states.switch "default" container.states.switch "default" #***** containerMask.states.switch "default" photoArea.states.switch "default" #***** codePlaceholder.states.switch "default" Utils.delay 0.5, -> bg.backgroundColor = "#439FD8" qrButton.index = 100 initSearch = -> if !sticky header.states.switch "searching" logo.states.switch "searching" qrButton.states.switch "hidden" store.states.switch "searching" reset.states.switch "searching" cancelSearch.states.switch "visible" searchBar.states.switch "searching" useCode.states.switch "hidden" qrButton.index = 0 else reset.states.switch "searching" initRedeem = -> searchPlaceholder.states.switch "hidden" reset.states.switch "usingCode" searchBar.states.switch "redeeming" cancelSearch.states.switch "visible" redeemText.states.switch "visible" logo.states.switch "hidden" useCode.states.switch "hidden" header.states.switch "redeeming" store.states.switch "redeeming" codePlaceholder.states.switch "redeeming" qrButton.states.switch "hidden" qrButton.index = 0 initScan = -> container.states.switch "scanning" reset.states.switch "scanning" containerMask.states.switch "scanning" bg.backgroundColor = "black" photoArea.states.switch "scanning" initStickySearch = -> header.states.switch "stickySearch" logo.states.switch "hidden" container.removeSubLayer header searchBar.states.switch "sticky" cancelStickySearch = -> container.addSubLayer header header.index = 1 header.states.switch "stickyReturn" searchBar.states.switch "stickyReturn" searchBar.states.switch "default" # Events searchPlaceholder.on Events.Click, -> console.log "searchPlaceholder on Click" initSearch() qrButton.on Events.Click, -> initScan() qr.on Events.Click, -> initScan() useCode.on Events.TouchStart, -> this.states.switch "pressed" useCode.on Events.MouseOut, -> this.states.switch "default" useCode.on Events.Click, -> initRedeem() reset.on Events.Click, -> resetView() cancelSearch.on Events.Click, -> console.log "cancelSearch on Click" # searchPlaceholder.states.switch "default" resetView() closePhoto.on Events.Click, -> resetView() # State switch functions # These change the animation for an item based on its new state logo.states.on Events.StateWillSwitch, (oldState, newState) -> if newState == 'returning' logo.states.animationOptions = logoReturningAnim else logo.states.animationOptions = logoDefaultAnim reset.on Events.AnimationStart, (event, layer) -> layer.visible = true reset.on Events.AnimationEnd, (event, layer) -> if layer.opacity == 0 layer.visible = false else layer.visible = true header.on Events.StateWillSwitch, (oldState, newState) -> if newState == "stickyReturn" header.states.animationOptions = noAnim else if newState == "stickySearch" header.states.animationOptions = noAnim else header.states.animationOptions = Framer.Defaults.Animation searchBar.on Events.StateWillSwitch, (oldState, newState) -> if newState is "sticky" or sticky searchBar.states.animationOptions = noAnim else searchBar.states.animationOptions = Framer.Defaults.Animation # Pull to refresh spin = -> refresh.animate properties: rotation: 1080 time: 1.5 curve: "linear" Utils.delay 1.5, -> refresh.rotation = 0 spin() spin() startY = 0 storeStartY = store.y store.draggable.enabled = true store.draggable.speedX = 0 store.on Events.DragStart, (event) -> bg.backgroundColor = "#F6FBFE" startY = event.pageY store.on Events.DragMove, (event) -> deltaY = startY - event.pageY store.y = storeStartY - deltaY ptr.y = store.y - ptr.height if deltaY > 0 header.y = -deltaY if deltaY < -100 arrow.animate properties: rotation: 180 time: .12 curve: "ease" else arrow.animate properties: rotation: 0 time: .12 curve: "ease" store.on Events.DragEnd, (event) -> deltaY = startY - event.pageY if deltaY < -100 startRefresh() else store.states.switch "default" ptr.states.switch "default" header.states.switch "default" startRefresh = -> store.states.switch "refreshing" ptr.states.switch "refreshing" refresh.animate properties: opacity: 1 time: .2 curve: "ease" arrow.animate properties: opacity: 0 time: .2 curve: "ease" Utils.delay 2, -> endRefresh() endRefresh = -> store.states.switch "default" ptr.states.switch "default" refresh.opacity = 0 arrow.animate properties: opacity: 1 time: .2 curve: "ease" Utils.delay .2, -> bg.backgroundColor = "#439FD8" arrow.rotation = 0 # Scroll events sticky = false opacity = 1 limit = header.height - 20 - searchBar.height - 20 container.on Events.Scroll, -> x = Utils.modulate(container.scrollY, [0, limit-100], [1, 0], true) y = Utils.modulate(container.scrollY, [0, limit], [1, 0], true) logo.opacity = x useCode.opacity = y if container.scrollY > limit if !sticky initStickySearch() sticky = true else cancelStickySearch() sticky = false
[ { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 35, "score": 0.9998775124549866, "start": 21, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.o...
test/parser/scala-parser.test.coffee
uppalapatisujitha/CodingConventionofCommitHistory
421
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/scala-parser' describe 'scala-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'a = 1;', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #4', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t a = 1; ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \ta = 1;', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'a = 1;', {} convention.indent.tab.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1 describe 'classname >', -> it 'camelcases with capitalzied #1', -> convention = parser.classname 'class MyFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #2', -> convention = parser.classname 'class My1stFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #3', -> convention = parser.classname 'trait MyFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #4', -> convention = parser.classname 'class myFairLady', {} convention.classname.capital.should.equal 0 it 'camelcases with non-capitalzied #1', -> convention = parser.classname 'class myFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #2', -> convention = parser.classname 'class my1stFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #3', -> convention = parser.classname 'trait myFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #4', -> convention = parser.classname 'trait MyFairLady', {} convention.classname.nocapital.should.equal 0 describe 'variablename >', -> it 'camelcases with capitalzied #1', -> convention = parser.variablename 'val myValue = ...', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #2', -> convention = parser.variablename 'def myMethod = ...', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #3', -> convention = parser.variablename 'var myVariable', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #4', -> convention = parser.variablename 'val MY_VALUE = ...', {} convention.variablename.camelcase.should.equal 0 it 'camelcases with non-capitalzied #1', -> convention = parser.variablename 'val MyValue = ...', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #2', -> convention = parser.variablename 'def MyMethod = ...', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #3', -> convention = parser.variablename 'var MyVariable', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #4', -> convention = parser.variablename 'val MY_VALUE = ...', {} convention.variablename.noncamelcase.should.equal 0 describe 'parametertype >', -> it 'parameter type with one space #1', -> convention = parser.parametertype 'def add(a: Int, b: Int) = a + b', {} convention.parametertype.tracespace.should.equal 1 it 'parameter type with one space #2', -> convention = parser.parametertype 'def add(a:Int, b: Int) = a + b', {} convention.parametertype.tracespace.should.equal 1 it 'parameter type with one space #3', -> convention = parser.parametertype 'def add(a:Int, b:Int): Unit = a + b', {} convention.parametertype.tracespace.should.equal 0 it 'parameter type with both space #1', -> convention = parser.parametertype 'def add(a : Int, b : Int) = a + b', {} convention.parametertype.bothspace.should.equal 1 it 'parameter type with both space #2', -> convention = parser.parametertype 'def add(a:Int, b : Int) = a + b', {} convention.parametertype.bothspace.should.equal 1 it 'parameter type with both space #3', -> convention = parser.parametertype 'def add(a:Int, b: Int) : Unit = a + b', {} convention.parametertype.bothspace.should.equal 0 it 'parameter type with no space #1', -> convention = parser.parametertype 'def add(a:Int, b:Int) = a + b', {} convention.parametertype.nospace.should.equal 1 it 'parameter type with no space #2', -> convention = parser.parametertype 'def add(a: Int, b:Int) = a + b', {} convention.parametertype.nospace.should.equal 1 it 'parameter type with no space #2', -> convention = parser.parametertype 'def add(a: Int, b: Int):Unit = a + b', {} convention.parametertype.nospace.should.equal 0
87313
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/scala-parser' describe 'scala-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'a = 1;', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #4', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t a = 1; ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \ta = 1;', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'a = 1;', {} convention.indent.tab.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1 describe 'classname >', -> it 'camelcases with capitalzied #1', -> convention = parser.classname 'class MyFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #2', -> convention = parser.classname 'class My1stFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #3', -> convention = parser.classname 'trait MyFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #4', -> convention = parser.classname 'class myFairLady', {} convention.classname.capital.should.equal 0 it 'camelcases with non-capitalzied #1', -> convention = parser.classname 'class myFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #2', -> convention = parser.classname 'class my1stFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #3', -> convention = parser.classname 'trait myFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #4', -> convention = parser.classname 'trait MyFairLady', {} convention.classname.nocapital.should.equal 0 describe 'variablename >', -> it 'camelcases with capitalzied #1', -> convention = parser.variablename 'val myValue = ...', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #2', -> convention = parser.variablename 'def myMethod = ...', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #3', -> convention = parser.variablename 'var myVariable', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #4', -> convention = parser.variablename 'val MY_VALUE = ...', {} convention.variablename.camelcase.should.equal 0 it 'camelcases with non-capitalzied #1', -> convention = parser.variablename 'val MyValue = ...', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #2', -> convention = parser.variablename 'def MyMethod = ...', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #3', -> convention = parser.variablename 'var MyVariable', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #4', -> convention = parser.variablename 'val MY_VALUE = ...', {} convention.variablename.noncamelcase.should.equal 0 describe 'parametertype >', -> it 'parameter type with one space #1', -> convention = parser.parametertype 'def add(a: Int, b: Int) = a + b', {} convention.parametertype.tracespace.should.equal 1 it 'parameter type with one space #2', -> convention = parser.parametertype 'def add(a:Int, b: Int) = a + b', {} convention.parametertype.tracespace.should.equal 1 it 'parameter type with one space #3', -> convention = parser.parametertype 'def add(a:Int, b:Int): Unit = a + b', {} convention.parametertype.tracespace.should.equal 0 it 'parameter type with both space #1', -> convention = parser.parametertype 'def add(a : Int, b : Int) = a + b', {} convention.parametertype.bothspace.should.equal 1 it 'parameter type with both space #2', -> convention = parser.parametertype 'def add(a:Int, b : Int) = a + b', {} convention.parametertype.bothspace.should.equal 1 it 'parameter type with both space #3', -> convention = parser.parametertype 'def add(a:Int, b: Int) : Unit = a + b', {} convention.parametertype.bothspace.should.equal 0 it 'parameter type with no space #1', -> convention = parser.parametertype 'def add(a:Int, b:Int) = a + b', {} convention.parametertype.nospace.should.equal 1 it 'parameter type with no space #2', -> convention = parser.parametertype 'def add(a: Int, b:Int) = a + b', {} convention.parametertype.nospace.should.equal 1 it 'parameter type with no space #2', -> convention = parser.parametertype 'def add(a: Int, b: Int):Unit = a + b', {} convention.parametertype.nospace.should.equal 0
true
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/scala-parser' describe 'scala-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'a = 1;', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #4', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t a = 1; ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \ta = 1;', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'a = 1;', {} convention.indent.tab.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1 describe 'classname >', -> it 'camelcases with capitalzied #1', -> convention = parser.classname 'class MyFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #2', -> convention = parser.classname 'class My1stFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #3', -> convention = parser.classname 'trait MyFairLady', {} convention.classname.capital.should.equal 1 it 'camelcases with capitalzied #4', -> convention = parser.classname 'class myFairLady', {} convention.classname.capital.should.equal 0 it 'camelcases with non-capitalzied #1', -> convention = parser.classname 'class myFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #2', -> convention = parser.classname 'class my1stFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #3', -> convention = parser.classname 'trait myFairLady', {} convention.classname.nocapital.should.equal 1 it 'camelcases with non-capitalzied #4', -> convention = parser.classname 'trait MyFairLady', {} convention.classname.nocapital.should.equal 0 describe 'variablename >', -> it 'camelcases with capitalzied #1', -> convention = parser.variablename 'val myValue = ...', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #2', -> convention = parser.variablename 'def myMethod = ...', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #3', -> convention = parser.variablename 'var myVariable', {} convention.variablename.camelcase.should.equal 1 it 'camelcases with capitalzied #4', -> convention = parser.variablename 'val MY_VALUE = ...', {} convention.variablename.camelcase.should.equal 0 it 'camelcases with non-capitalzied #1', -> convention = parser.variablename 'val MyValue = ...', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #2', -> convention = parser.variablename 'def MyMethod = ...', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #3', -> convention = parser.variablename 'var MyVariable', {} convention.variablename.noncamelcase.should.equal 1 it 'camelcases with non-capitalzied #4', -> convention = parser.variablename 'val MY_VALUE = ...', {} convention.variablename.noncamelcase.should.equal 0 describe 'parametertype >', -> it 'parameter type with one space #1', -> convention = parser.parametertype 'def add(a: Int, b: Int) = a + b', {} convention.parametertype.tracespace.should.equal 1 it 'parameter type with one space #2', -> convention = parser.parametertype 'def add(a:Int, b: Int) = a + b', {} convention.parametertype.tracespace.should.equal 1 it 'parameter type with one space #3', -> convention = parser.parametertype 'def add(a:Int, b:Int): Unit = a + b', {} convention.parametertype.tracespace.should.equal 0 it 'parameter type with both space #1', -> convention = parser.parametertype 'def add(a : Int, b : Int) = a + b', {} convention.parametertype.bothspace.should.equal 1 it 'parameter type with both space #2', -> convention = parser.parametertype 'def add(a:Int, b : Int) = a + b', {} convention.parametertype.bothspace.should.equal 1 it 'parameter type with both space #3', -> convention = parser.parametertype 'def add(a:Int, b: Int) : Unit = a + b', {} convention.parametertype.bothspace.should.equal 0 it 'parameter type with no space #1', -> convention = parser.parametertype 'def add(a:Int, b:Int) = a + b', {} convention.parametertype.nospace.should.equal 1 it 'parameter type with no space #2', -> convention = parser.parametertype 'def add(a: Int, b:Int) = a + b', {} convention.parametertype.nospace.should.equal 1 it 'parameter type with no space #2', -> convention = parser.parametertype 'def add(a: Int, b: Int):Unit = a + b', {} convention.parametertype.nospace.should.equal 0
[ { "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.9998838305473328, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Je...
node_modules/konsserto/lib/src/Konsserto/Vendor/Twig/Extension/TwigFunctionMethod.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. ### # # TwigFunctionMethod # # @author Jessym Reziga <jessym@konsserto.com> # class TwigFunctionMethod constructor:(@method) -> getMethod:() -> return @method module.exports = TwigFunctionMethod
97455
### * 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. ### # # TwigFunctionMethod # # @author <NAME> <<EMAIL>> # class TwigFunctionMethod constructor:(@method) -> getMethod:() -> return @method module.exports = TwigFunctionMethod
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. ### # # TwigFunctionMethod # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class TwigFunctionMethod constructor:(@method) -> getMethod:() -> return @method module.exports = TwigFunctionMethod
[ { "context": "e or @district()\n shehiaUnit?.name or @shehia()\n ]\n else\n [@district()", "end": 44474, "score": 0.9745113253593445, "start": 44468, "tag": "USERNAME", "value": "shehia" }, { "context": ")\n ]\n else\n [@di...
_attachments/app/models/Case.coffee
Abdillah390/matatizo
0
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ moment = require 'moment' Dhis2 = require './Dhis2' CONST = require "../Constants" humanize = require 'underscore.string/humanize' titleize = require 'underscore.string/titleize' PouchDB = require 'pouchdb-core' radix64 = require('radix-64')() HouseholdMember = require './HouseholdMember' Question = require './Question' Individual = require './Individual' TertiaryIndex = require './TertiaryIndex' class Case constructor: (options) -> @caseID = options?.caseID @loadFromResultDocs(options.results) if options?.results loadFromResultDocs: (resultDocs) -> @caseResults = resultDocs @questions = [] this["Household Members"] = [] this["Neighbor Households"] = [] userRequiresDeidentification = (Coconut.currentUser?.hasRole("reports") or Coconut.currentUser is null) and not Coconut.currentUser?.hasRole("admin") _.each resultDocs, (resultDoc) => resultDoc = resultDoc.toJSON() if resultDoc.toJSON? if userRequiresDeidentification _.each resultDoc, (value,key) -> resultDoc[key] = b64_sha1(value) if value? and _.contains(Coconut.identifyingAttributes, key) if resultDoc.question @caseID ?= resultDoc["MalariaCaseID"].trim() @questions.push resultDoc.question if resultDoc.question is "Household Members" this["Household Members"].push resultDoc householdMember = new HouseholdMember() householdMember.load(resultDoc) (@householdMembers or= []).push(householdMember) else if resultDoc.question is "Household" and resultDoc.Reasonforvisitinghousehold is "Index Case Neighbors" this["Neighbor Households"].push resultDoc else if resultDoc.question is "Facility" dateOfPositiveResults = resultDoc.DateOfPositiveResults if dateOfPositiveResults? dayMonthYearMatch = dateOfPositiveResults.match(/^(\d\d).(\d\d).(20\d\d)/) if dayMonthYearMatch [day,month,year] = dayMonthYearMatch[1..] if day > 31 or month > 12 console.error "Invalid DateOfPositiveResults: #{this}" else resultDoc.DateOfPositiveResults = "#{year}-#{month}-#{day}" if this[resultDoc.question]? # Duplicate if (this[resultDoc.question].complete is "true" or this[resultDoc.question].complete is true) and (resultDoc.complete isnt "true" or resultDoc.complete isnt true) #console.warn "Using the result marked as complete" return # Use the version already loaded which is marked as complete else if this[resultDoc.question].complete and resultDoc.complete console.warn "Duplicate complete entries for case: #{@caseID}" this[resultDoc.question] = resultDoc else @caseID ?= resultDoc["caseid"].trim() @questions.push "USSD Notification" this["USSD Notification"] = resultDoc fetch: (options) => unless @caseID return Promise.reject "No caseID to fetch data for" Coconut.database.query "cases", key: @caseID include_docs: true .catch (error) -> options?.error() Promise.reject(error) .then (result) => if result.rows.length is 0 options?.error("Could not find any existing data for case #{@caseID}") Promise.reject ("Could not find any existing data for case #{@caseID}") @loadFromResultDocs(_.pluck(result.rows, "doc")) options?.success() Promise.resolve() toJSON: => returnVal = {} _.each @questions, (question) => returnVal[question] = this[question] return returnVal deIdentify: (result) -> flatten: (questions = @questions) -> returnVal = {} _.each questions, (question) => type = question _.each this[question], (value, field) -> if _.isObject value _.each value, (arrayValue, arrayField) -> returnVal["#{question}-#{field}: #{arrayField}"] = arrayValue else returnVal["#{question}:#{field}"] = value returnVal caseId: => @caseID LastModifiedAt: => _.chain(@toJSON()) .map (data, question) -> if _(data).isArray() _(data).pluck("lastModifiedAt") else data?.lastModifiedAt .flatten() .max (lastModifiedAt) -> moment(lastModifiedAt).unix() .value() Questions: -> _.keys(@toJSON()).join(", ") MalariaCaseID: -> @caseID user: -> userId = @.Household?.user || @.Facility?.user || @["Case Notification"]?.user allUserIds: -> users = [] users.push @.Household?.user users.push @.Facility?.user users.push @["Case Notification"]?.user _(users).chain().uniq().compact().value() allUserNames: => for userId in @allUserIds() Coconut.nameByUsername[userId] or "Unknown" allUserNamesString: => @allUserNames()?.join(", ") facility: -> @facilityUnit()?.name or "UNKNOWN" #@["Case Notification"]?.FacilityName.toUpperCase() or @["USSD Notification"]?.hf.toUpperCase() or @["Facility"]?.FacilityName or "UNKNOWN" facilityType: => facilityUnit = @facilityUnit() unless facilityUnit? console.warn "Unknown facility name for: #{@caseID}. Returning UNKNOWN for facilityType." return "UNKNOWN" GeoHierarchy.facilityTypeForFacilityUnit(@facilityUnit()) facilityDhis2OrganisationUnitId: => GeoHierarchy.findFirst(@facility(), "FACILITY")?.id isShehiaValid: => if @validShehia() then true else false validShehia: => @shehiaUnit()?.name ### # Try and find a shehia is in our database if @.Household?.Shehia and GeoHierarchy.validShehia(@.Household.Shehia) return @.Household?.Shehia else if @.Facility?.Shehia and GeoHierarchy.validShehia(@.Facility.Shehia) return @.Facility?.Shehia else if @["Case Notification"]?.Shehia and GeoHierarchy.validShehia(@["Case Notification"]?.Shehia) return @["Case Notification"]?.Shehia else if @["USSD Notification"]?.shehia and GeoHierarchy.validShehia(@["USSD Notification"]?.shehia) return @["USSD Notification"]?.shehia return null ### shehiaUnit: (shehiaName, districtName) => if shehiaName? and GeoHierarchy.validShehia(shehiaName) # Can pass in a shehiaName - useful for positive Individuals with different focal area else shehiaName = null # Priority order to find the best facilityName for name in [@Household?.Shehia, @Facility?.Shehia, @["Case Notification"]?.Shehia, @["USSD Notification"]?.shehia] continue unless name? name = name.trim() if GeoHierarchy.validShehia(name) shehiaName = name break unless shehiaName? # If we have no valid shehia name, then try and use facility return @facilityUnit()?.ancestorAtLevel("SHEHIA") else shehiaUnits = GeoHierarchy.find(shehiaName,"SHEHIA") if shehiaUnits.length is 1 return shehiaUnits[0] else if shehiaUnits.length > 1 # At this point we have a shehia name, but it is not unique, so we can use any data to select the correct one # Shehia names are not unique across Zanzibar, but they are unique per island # We also have region which is a level between district and island. # Strategy: get another sub-island location from the data, then limit the # list of shehias to that same island # * "District" that was passed in (used for focal areas) # Is Shehia in district? # * "District" from Household # Is Shehia in district? # * "District for Shehia" from Case Notification # Is Shehia in district? # * Facility District # Is Shehia in District # * Facility Name # Is Shehia parent of facility # * If REGION for FACILTY unit matches one of the shehia's region # * If ISLAND for FACILTY unit matches one of the shehia's region for district in [districtName, @Household?["District"], @["Case Notification"]?["District for Shehia"], @["Case Notification"]?["District for Facility"], @["USSD Notification"]?.facility_district] continue unless district? district = district.trim() districtUnit = GeoHierarchy.findOneMatchOrUndefined(district, "DISTRICT") if districtUnit? for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("DISTRICT") is districtUnit return shehiaUnit # CHECK THE REGION LEVEL for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("REGION") is districtUnit.ancestorAtLevel("REGION") return shehiaUnit # CHECK THE ISLAND LEVEL for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("ISLAND") is districtUnit.ancestorAtLevel("ISLAND") return shehiaUnit # In case we couldn't find a facility district above, try and use the facility unit which comes from the name facilityUnit = @facilityUnit() if facilityUnit? facilityUnitShehia = facilityUnit.ancestorAtLevel("SHEHIA") for shehiaUnit in shehiaUnits if shehiaUnit is facilityUnitShehia return shehiaUnit for level in ["DISTRICT", "REGION", "ISLAND"] facilityUnitAtLevel = facilityUnit.ancestorAtLevel(level) for shehiaUnit in shehiaUnits shehiaUnitAtLevel = shehiaUnit.ancestorAtLevel(level) #console.log "shehiaUnitAtLevel: #{shehiaUnitAtLevel.id}: #{shehiaUnitAtLevel.name}" #console.log "facilityUnitAtLevel: #{facilityUnitAtLevel.id}: #{facilityUnitAtLevel.name}" if shehiaUnitAtLevel is facilityUnitAtLevel return shehiaUnit villageFromGPS: => longitude = @householdLocationLongitude() latitude = @householdLocationLatitude() if longitude? and latitude? GeoHierarchy.villagePropertyFromGPS(longitude, latitude) shehiaUnitFromGPS: => longitude = @householdLocationLongitude() latitude = @householdLocationLatitude() if longitude? and latitude? GeoHierarchy.findByGPS(longitude, latitude, "SHEHIA") shehiaFromGPS: => @shehiaUnitFromGPS()?.name facilityUnit: => facilityName = null # Priority order to find the best facilityName for name in [@Facility?.FacilityName, @["Case Notification"]?.FacilityName, @["USSD Notification"]?["hf"]] continue unless name? name = name.trim() if GeoHierarchy.validFacility(name) facilityName = name break if facilityName facilityUnits = GeoHierarchy.find(facilityName, "HEALTH FACILITIES") if facilityUnits.length is 1 return facilityUnits[0] else if facilityUnits.length is 0 return null else if facilityUnits.length > 1 facilityDistrictName = null for name in [@Facility?.DistrictForFacility, @["Case Notification"]?.DistrictForFacility, @["USSD Notification"]?["facility_district"]] if name? and GeoHierarchy.validDistrict(name) facilityDistrictName = name break if facilityDistrictName? facilityDistrictUnits = GeoHierarchy.find(facilityDistrictName, "DISTRICT") for facilityUnit in facilityUnits for facilityDistrictUnit in facilityDistrictUnits if facilityUnit.ancestorAtLevel("DISTRICT") is facilityDistrictUnit return facilityUnit householdShehiaUnit: => @shehiaUnit() householdShehia: => @householdShehiaUnit()?.name shehia: -> returnVal = @validShehia() return returnVal if returnVal? # If no valid shehia is found, then return whatever was entered (or null) returnVal = @.Household?.Shehia || @.Facility?.Shehia || @["Case Notification"]?.shehia || @["USSD Notification"]?.shehia if @hasCompleteFacility() if @complete() console.warn "Case was followed up to household, but shehia name: #{returnVal} is not a valid shehia. #{@MalariaCaseID()}." else console.warn "Case was followed up to facility, but shehia name: #{returnVal} is not a valid shehia: #{@MalariaCaseID()}." return returnVal village: -> @["Facility"]?.Village facilityDistrict: -> facilityDistrict = @["USSD Notification"]?.facility_district unless facilityDistrict and GeoHierarchy.validDistrict(facilityDistrict) facilityDistrict = @facilityUnit()?.ancestorAtLevel("DISTRICT").name unless facilityDistrict #if @["USSD Notification"]?.facility_district is "WEST" and _(GeoHierarchy.find(@shehia(), "SHEHIA").map( (u) => u.ancestors()[0].name )).include "MAGHARIBI A" # MEEDS doesn't have WEST split # # # WEST got split, but DHIS2 uses A & B, so use shehia to figure out the right one if @["USSD Notification"]?.facility_district is "WEST" if shehia = @validShehia() for shehia in GeoHierarchy.find(shehia, "SHEHIA") if shehia.ancestorAtLevel("DISTRICT").name.match(/MAGHARIBI/) return shehia.ancestorAtLevel("DISTRICT").name else return "MAGHARIBI A" #Check the shehia to see if it is either MAGHARIBI A or MAGHARIBI B console.warn "Could not find a district for USSD notification: #{JSON.stringify @["USSD Notification"]}" return "UNKNOWN" GeoHierarchy.swahiliDistrictName(facilityDistrict) districtUnit: -> districtUnit = @shehiaUnit()?.ancestorAtLevel("DISTRICT") or @facilityUnit()?.ancestorAtLevel("DISTRICT") return districtUnit if districtUnit? for name in [@Facility?.DistrictForFacility, @["Case Notification"]?.DistrictForFacility, @["USSD Notification"]?["facility_district"]] if name? and GeoHierarchy.validDistrict(name) return GeoHierarchy.findOneMatchOrUndefined(name, "DISTRICT") district: => @districtUnit()?.name or "UNKNOWN" islandUnit: => @districtUnit()?.ancestorAtLevel("ISLANDS") island: => @islandUnit()?.name or "UNKNOWN" highRiskShehia: (date) => date = moment().startOf('year').format("YYYY-MM") unless date if Coconut.shehias_high_risk?[date]? _(Coconut.shehias_high_risk[date]).contains @shehia() else false locationBy: (geographicLevel) => return @validShehia() if geographicLevel.match(/shehia/i) district = @district() if district? return district if geographicLevel.match(/district/i) GeoHierarchy.getAncestorAtLevel(district, "DISTRICT", geographicLevel) else console.warn "No district for case: #{@caseID}" # namesOfAdministrativeLevels # Nation, Island, Region, District, Shehia, Facility # Example: #"ZANZIBAR","PEMBA","KUSINI PEMBA","MKOANI","WAMBAA","MWANAMASHUNGI namesOfAdministrativeLevels: () => district = @district() if district districtAncestors = _(GeoHierarchy.findFirst(district, "DISTRICT")?.ancestors()).pluck "name" result = districtAncestors.reverse().concat(district).concat(@shehia()).concat(@facility()) result.join(",") possibleQuestions: -> ["Case Notification", "Facility","Household","Household Members"] questionStatus: => result = {} _.each @possibleQuestions(), (question) => if question is "Household Members" if @["Household Members"].length is 0 result["Household Members"] = false else result["Household Members"] = true for member in @["Household Members"] unless member.complete? and (member.complete is true or member.complete is "true") result["Household Members"] = false else result[question] = (@[question]?.complete is "true" or @[question]?.complete is true) return result lastQuestionCompleted: => questionStatus = @questionStatus() for question in @possibleQuestions().reverse() return question if questionStatus[question] return "None" hasHouseholdMembersWithRepeatedNames: => @repeatedNamesInSameHousehold() isnt null repeatedNamesInSameHousehold: => names = {} for individual in @positiveAndNegativeIndividualObjects() name = individual.name() if name? and name isnt "" names[name] or= 0 names[name] += 1 repeatedNames = [] for name, frequency of names if frequency > 1 repeatedNames.push name if repeatedNames.length > 0 return repeatedNames.join(", ") else return null oneAndOnlyOneIndexCase: => numberOfIndexCases = 0 for individual in @positiveIndividualObjects() if individual.data.HouseholdMemberType is "Index Case" numberOfIndexCases+=1 console.log "numberOfIndexCases: #{numberOfIndexCases}" if numberOfIndexCases isnt 1 return numberOfIndexCases is 1 hasIndexCaseClassified: => @classificationsByHouseholdMemberType().match(/Index Case/) complete: => @questionStatus()["Household Members"] is true status: => if @["Facility"]?["Lost To Followup"] is "Yes" return "Lost To Followup" else if @complete() return "Followed up" else returnVal = "" for question, status of @questionStatus() if status is false returnVal = if question is "Household Members" and not @hasIndexCaseClassified() "Household Members does not have a classified Index Case" else if question is "Household Member" "<a href='##{Coconut.databaseName}/show/results/Household%20Members'>#{question}</a> in Progress" else url = if @[question]?._id "##{Coconut.databaseName}/edit/result/#{@[question]._id}" else "##{Coconut.databaseName}/show/results/#{question}" "<a href='#{url}'>#{question}</a> in Progress" break returnVal hasCompleteFacility: => @.Facility?.complete is "true" or @.Facility?.complete is true notCompleteFacilityAfter24Hours: => @moreThan24HoursSinceFacilityNotifed() and not @hasCompleteFacility() notFollowedUpAfter48Hours: => @moreThan48HoursSinceFacilityNotifed() and not @followedUp() followedUpWithin48Hours: => not @notFollowedUpAfter48Hours() notFollowedUpAfterXHours: => @moreThanXHoursSinceFacilityNotifed() and not @followedUp() followedUpWithinXHours: => not @notFollowedUpAfterXHours() completeHouseholdVisit: => @complete() dateHouseholdVisitCompleted: => if @completeHouseholdVisit() @.Household?.lastModifiedAt or @["Household Members"]?[0]?.lastModifiedAt or @Facility?.lastModifiedAt # When the household has two cases followedUp: => @completeHouseholdVisit() # Includes any kind of travel including only within Zanzibar indexCaseHasTravelHistory: => @.Facility?.TravelledOvernightinpastmonth?.match(/Yes/) or false indexCaseHasNoTravelHistory: => not @indexCaseHasTravelHistory() location: (type) -> # Not sure how this works, since we are using the facility name with a database of shehias #WardHierarchy[type](@toJSON()["Case Notification"]?["FacilityName"]) GeoHierarchy.findOneShehia(@toJSON()["Case Notification"]?["FacilityName"])?[type.toUpperCase()] withinLocation: (location) -> return @location(location.type) is location.name # This is just a count of househhold members not how many are positive # It excludes neighbor households completeIndexCaseHouseholdMembers: => return [] unless @["Household"]? _(@["Household Members"]).filter (householdMember) => # HeadOfHouseholdName used to determine if it is neighbor household (householdMember.HeadofHouseholdName is @["Household"].HeadofHouseholdName or householdMember.HeadOfHouseholdName is @["Household"].HeadOfHouseholdName) and (householdMember.complete is "true" or householdMember.complete is true) hasCompleteIndexCaseHouseholdMembers: => @completeIndexCaseHouseholdMembers().length > 0 # Note that this doesn't include Index - this is unclear function name positiveIndividualsAtIndexHousehold: => console.warn "Function name not clear consider using positiveIndividualsExcludingIndex instead" _(@completeIndexCaseHouseholdMembers()).filter (householdMember) -> householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### numberPositiveIndividualsAtIndexHousehold: => throw "Deprecated since name was confusing about whether index case was included, use numberPositiveIndividualsExcludingIndex" @positiveIndividualsAtIndexHousehold().length ### numberPositiveIndividualsExcludingIndex: => @positiveIndividualsExcludingIndex().length hasAdditionalPositiveIndividualsAtIndexHousehold: => @numberPositiveIndividualsExcludingIndex() > 0 completeNeighborHouseholds: => _(@["Neighbor Households"]).filter (household) => household.complete is "true" or household.complete is true completeNeighborHouseholdMembers: => return [] unless @["Household"]? _(@["Household Members"]).filter (householdMember) => (householdMember.HeadOfHouseholdName isnt @["Household"].HeadOfHouseholdName) and (householdMember.complete is "true" or householdMember.complete is true) hasCompleteNeighborHouseholdMembers: => @completeIndexCaseHouseholdMembers().length > 0 positiveIndividualsAtNeighborHouseholds: -> _(@completeNeighborHouseholdMembers()).filter (householdMember) -> householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### # Handles pre-2019 and post-2019 positiveIndividualsAtIndexHouseholdAndNeighborHouseholds: -> throw "Deprecated" _(@["Household Members"]).filter (householdMember) => householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### positiveIndividualsUnder5: => _(@positiveIndividuals()).filter (householdMemberOrNeighbor) => age = @ageInYears(householdMemberOrNeighbor.Age, householdMemberOrNeighbor.AgeInYearsMonthsDays) age and age < 5 positiveIndividualsOver5: => _(@positiveIndividuals()).filter (householdMemberOrNeighbor) => age = @ageInYears(householdMemberOrNeighbor.Age, householdMemberOrNeighbor.AgeInYearsMonthsDays) age and age >= 5 numberPositiveIndividuals: -> @positiveIndividuals().length numberHouseholdMembers: -> @["Household Members"].length numberHouseholdMembersTestedAndUntested: => numberHouseholdMembersFromHousehold = @["Household"]?["TotalNumberOfResidentsInTheHousehold"] or @["Household"]?["TotalNumberofResidentsintheHousehold"] numberHouseholdMembersWithRecord = @numberHouseholdMembers() # Some cases have more member records than TotalNumberofResidentsintheHousehold so use higher Math.max(numberHouseholdMembersFromHousehold, numberHouseholdMembersWithRecord) numberHouseholdMembersTested: => numberHouseholdMemberRecordsWithTest = _(@["Household Members"]).filter (householdMember) => switch householdMember.MalariaTestResult when "NPF", "PF", "Mixed" return true switch householdMember["MalariaTestPerformed"] when "mRDT", "Microscopy" return true .length # Check if we have pre 2019 data by checking for classifications # If there is no classification then either it was pre-2019 or followup is not done, so we need to add on an additional individual that was tested (index case) classifiedNonIndexCases = _(@["Household Members"]).filter (householdMember) => householdMember.CaseCategory? and householdMember.HouseholdMemberType isnt "Index Case" # If there is at least a case notification then we know the index case was tested if classifiedNonIndexCases.length is 0 numberHouseholdMemberRecordsWithTest+1 else numberHouseholdMemberRecordsWithTest percentOfHouseholdMembersTested: => (@numberHouseholdMembersTested()/@numberHouseholdMembersTestedAndUntested()*100).toFixed(0) updateIndividualIndex: => @tertiaryIndex or= new TertiaryIndex name: "Individual" @tertiaryIndex.updateIndexForCases({caseIDs:[@MalariaCaseID()]}) positiveIndividualObjects: => for positiveIndividual in @positiveIndividuals() new Individual(positiveIndividual, @) positiveIndividuals: => @positiveIndividualsIncludingIndex() #This function is good - don't use completeIndexCaseHouseholdMembers positiveIndividualsIncludingIndex: => positiveIndividualsExcludingIndex = @positiveIndividualsExcludingIndex() positiveIndividualsIndexCasesOnly = @positiveIndividualsIndexCasesOnly() nonIndexHaveCaseCategory = _(positiveIndividualsExcludingIndex).any (positiveIndividual) -> positiveIndividual.CaseCategory? indexHaveCaseCategory = _(positiveIndividualsIndexCasesOnly).any (positiveIndividual) -> positiveIndividual.CaseCategory? # Don't try and find an index case if there are already classified individuals # Probably these just have the wrong Household Member Type results = if nonIndexHaveCaseCategory and not indexHaveCaseCategory positiveIndividualsExcludingIndex else positiveIndividualsIndexCasesOnly?.concat(positiveIndividualsExcludingIndex) for result in results result["Malaria Positive"] = true result positiveAndNegativeIndividuals: => for individual in @positiveIndividuals().concat(@negativeIndividuals()) individual["Date Of Malaria Results"] = @dateOfMalariaResultFromIndividual(individual) individual positiveAndNegativeIndividualObjects: => for individual in @positiveAndNegativeIndividuals() new Individual(individual, @) positiveIndividualsExcludingIndex: => # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedNonIndexIndividuals = _(@["Household Members"]).filter (householdMember) => householdMember.CaseCategory? and householdMember.HouseholdMemberType isnt "Index Case" results = if classifiedNonIndexIndividuals.length > 0 classifiedNonIndexIndividuals else # If there is no classification then there will be no index case in the list of household members (pre 2019 style). This also includes neighbor households. _(@["Household Members"]).filter (householdMember) => householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" for result in results # Make sure result.HouseholdMemberType = "Other Household Member" result positiveIndividualsIndexCasesOnly: => # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedIndexCases = @["Household Members"].filter (householdMember) -> householdMember.CaseCategory isnt null and householdMember.HouseholdMemberType is "Index Case" if classifiedIndexCases.length > 0 classifiedIndexCases else # Case hasn't been followed up yet or pre 2019 data which didn't capture index case as a household member, so use facility data for index and then check for positive household members extraProperties = { MalariaCaseID: @MalariaCaseID() HouseholdMemberType: "Index Case" } if @["Facility"] # Note that if you don't start with an empty object then the first argument gets mutated [_.extend {}, @["Facility"], @["Household"], extraProperties] else if @["USSD Notification"] [_.extend {}, @["USSD Notification"], @["Household"], extraProperties] else [] negativeIndividuals: => # I've reversed the logic of positiveIndividualsExcludingIndex # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedIndividuals = [] unclassifiedNonIndexIndividuals = [] _(@["Household Members"]).map (householdMember) => if householdMember.CaseCategory? classifiedIndividuals.push householdMember else if householdMember.HouseholdMemberType isnt "Index Case" # These are the ones we want but only if others are classified unclassifiedNonIndexIndividuals.push householdMember # if we have classification then index is in the household member data # So we can return the unclassified cases which must all be negative results = if classifiedIndividuals.length > 0 unclassifiedNonIndexIndividuals else # If there is no classification then there will be no index case in the list of household members (pre 2019 style). This also includes neighbor households. _(@["Household Members"]).filter (householdMember) => (householdMember.complete is true or householdMember.complete is "true") and householdMember.MalariaTestResult isnt "PF" and householdMember.MalariaTestResult isnt "Mixed" for result in results result["Date Of Malaria Results"] = @dateOfMalariaResultFromIndividual(result) result["Malaria Positive"] = false result numberPositiveIndividuals: => @positiveIndividuals().length numberPositiveIndividualsUnder5: => @positiveIndividualsUnder5().length numberPositiveIndividualsOver5: => @positiveIndividualsOver5().length massScreenCase: => @Household?["Reason for visiting household"]? is "Mass Screen" indexCasePatientName: -> if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) return "#{@["Facility"].FirstName} #{@["Facility"].LastName}" if @["USSD Notification"]? return @["USSD Notification"]?.name if @["Case Notification"]? return @["Case Notification"]?.Name # Not sure why the casing is weird - put this in to support mobile client indexCaseDiagnosisDate: => @IndexCaseDiagnosisDate() IndexCaseDiagnosisDateAndTime: -> # If we don't have the hour/minute of the diagnosis date # Then assume that everyone gets tested at 8am if @["Facility"]?.DateAndTimeOfPositiveResults? return moment(@["Facility"]?.DateAndTimeOfPositiveResults).format("YYYY-MM-DD HH:mm") if @["Facility"]?.DateOfPositiveResults? date = @["Facility"].DateOfPositiveResults momentDate = if date.match(/^20\d\d/) moment(@["Facility"].DateOfPositiveResults) else moment(@["Facility"].DateOfPositiveResults, "DD-MM-YYYY") if momentDate.isValid() return momentDate.set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") if @["USSD Notification"]? return moment(@["USSD Notification"].date).set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") else if @["Case Notification"]? return moment(@["Case Notification"].createdAt).set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") IndexCaseDiagnosisDate: => if indexCaseDiagnosisDateAndTime = @IndexCaseDiagnosisDateAndTime() moment(indexCaseDiagnosisDateAndTime).format("YYYY-MM-DD") IndexCaseDiagnosisDateIsoWeek: => indexCaseDiagnosisDate = @IndexCaseDiagnosisDate() if indexCaseDiagnosisDate moment(indexCaseDiagnosisDate).format("GGGG-WW") householdMembersDiagnosisDates: => @householdMembersDiagnosisDate() householdMembersDiagnosisDate: => returnVal = [] _.each @["Household Members"]?, (member) -> returnVal.push member.lastModifiedAt if member.MalariaTestResult is "PF" or member.MalariaTestResult is "Mixed" ageInYears: (age = @Facility?.Age, ageInMonthsYearsOrDays = (@Facility?.AgeinMonthsOrYears or @Facility?.AgeInYearsMonthsDays)) => return null unless age? and ageInMonthsYearsOrDays? if ageInMonthsYearsOrDays is "Months" age / 12.0 else if ageInMonthsYearsOrDays is "Days" age / 365.0 else age ### return null unless @Facility if @Facility["Age in Months Or Years"]? and @Facility["Age in Months Or Years"] is "Months" @Facility["Age"] / 12.0 else @Facility["Age"] ### isUnder5: => ageInYears = @ageInYears() if ageInYears ageInYears < 5 else null householdLocationLatitude: => parseFloat(@Location?["LocationLatitude"] or @Household?["HouseholdLocationLatitude"] or @Household?["Household Location - Latitude"]) or @Household?["HouseholdLocation-latitude"] householdLocationLongitude: => parseFloat(@Location?["LocationLongitude"] or @Household?["HouseholdLocationLongitude"] or @Household?["Household Location - Longitude"]) or @Household?["HouseholdLocation-longitude"] householdLocationAccuracy: => parseFloat(@Location?["LocationAccuracy"] or @Household?["HouseholdLocationAccuracy"] or @Household?["Household Location - Accuracy"]) resultsAsArray: => _.chain @possibleQuestions() .map (question) => @[question] .flatten() .compact() .value() fetchResults: (options) => results = _.map @resultsAsArray(), (result) => returnVal = new Result() returnVal.id = result._id returnVal count = 0 _.each results, (result) -> result.fetch success: -> count += 1 options.success(results) if count >= results.length return results updateCaseID: (newCaseID) -> @fetchResults success: (results) -> _.each results, (result) -> throw "No MalariaCaseID" unless result.attributes.MalariaCaseID? result.save MalariaCaseID: newCaseID issuesRequiringCleaning: () -> # Case has multiple USSD notifications resultCount = {} questionTypes = "USSD Notification, Case Notification, Facility, Household, Household Members".split(/, /) _.each questionTypes, (questionType) -> resultCount[questionType] = 0 _.each @caseResults, (result) -> resultCount["USSD Notification"]++ if result.caseid? resultCount[result.question]++ if result.question? issues = [] _.each questionTypes[0..3], (questionType) -> issues.push "#{resultCount[questionType]} #{questionType}s" if resultCount[questionType] > 1 issues.push "Not followed up" unless @followedUp() issues.push "Orphaned result" if @caseResults.length is 1 issues.push "Missing case notification" unless @["Case Notification"]? or @["Case Notification"]?.length is 0 return issues allResultsByQuestion: -> returnVal = {} _.each "USSD Notification, Case Notification, Facility, Household".split(/, /), (question) -> returnVal[question] = [] _.each @caseResults, (result) -> if result["question"]? returnVal[result["question"]].push result else if result.hf? returnVal["USSD Notification"].push result return returnVal redundantResults: -> redundantResults = [] _.each @allResultsByQuestion, (results, question) -> console.log _.sort(results, "createdAt") dateOfPositiveResults: => @IndexCaseDiagnosisDate() daysBetweenPositiveResultAndNotificationFromFacility: => dateOfPositiveResults = @dateOfPositiveResults() notificationDate = if @["USSD Notification"]? @["USSD Notification"].date if dateOfPositiveResults? and notificationDate? Math.abs(moment(dateOfPositiveResults).diff(notificationDate, 'days')) estimatedHoursBetweenPositiveResultAndNotificationFromFacility: => dateAndTimeOfPositiveResults = @IndexCaseDiagnosisDateAndTime() notificationDate = @["USSD Notification"]?.date or @["Case Notification"]?.createdAt if dateAndTimeOfPositiveResults? and notificationDate? Math.abs(moment(dateAndTimeOfPositiveResults).diff(notificationDate, 'hours')) lessThanOneDayBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility <= 1 oneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 1 and daysBetweenPositiveResultAndNotificationFromFacility <= 2 twoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 2 and daysBetweenPositiveResultAndNotificationFromFacility <= 3 moreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 3 daysBetweenPositiveResultAndCompleteHousehold: => dateOfPositiveResults = @dateOfPositiveResults() completeHouseholdVisit = @dateHouseholdVisitCompleted() if dateOfPositiveResults and completeHouseholdVisit Math.abs(moment(dateOfPositiveResults).diff(completeHouseholdVisit, 'days')) lessThanOneDayBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold <= 1 oneToTwoDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 1 and daysBetweenPositiveResultAndCompleteHousehold <= 2 twoToThreeDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 2 and daysBetweenPositiveResultAndCompleteHousehold <= 3 moreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 3 timeFacilityNotified: => if @["USSD Notification"]? @["USSD Notification"].date else null timeSinceFacilityNotified: => timeFacilityNotified = @timeFacilityNotified() if timeFacilityNotified? moment().diff(timeFacilityNotified) else null hoursSinceFacilityNotified: => timeSinceFacilityNotified = @timeSinceFacilityNotified() if timeSinceFacilityNotified? moment.duration(timeSinceFacilityNotified).asHours() else null moreThan24HoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > 24 moreThan48HoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > 48 moreThanXHoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > parseInt(Coconut.config.case_followup) timeFromSMSToCaseNotification: => if @["Case Notification"]? and @["USSD Notification"]? return moment(@["Case Notification"]?.createdAt).diff(@["USSD Notification"]?.date) # Note the replace call to handle a bug that created lastModified entries with timezones timeFromCaseNotificationToCompleteFacility: => if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) and @["Case Notification"]? return moment(@["Facility"].lastModifiedAt.replace(/\+0\d:00/,"")).diff(@["Case Notification"]?.createdAt) daysFromCaseNotificationToCompleteFacility: => if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) and @["Case Notification"]? moment.duration(@timeFromCaseNotificationToCompleteFacility()).asDays() householdComplete: => @complete() timeOfHouseholdComplete: => return null unless @householdComplete() latestLastModifiedTimeOfHouseholdMemberRecords = "" for householdMember in @["Household Members"] if householdMember.lastModifiedAt > latestLastModifiedTimeOfHouseholdMemberRecords latestLastModifiedTimeOfHouseholdMemberRecords = householdMember.lastModifiedAt latestLastModifiedTimeOfHouseholdMemberRecords timeFromFacilityToCompleteHousehold: => if @householdComplete() and @["Facility"]? return moment(@timeOfHouseholdComplete().replace(/\+0\d:00/,"")).diff(@["Facility"]?.lastModifiedAt) timeFromSMSToCompleteHousehold: => if @householdComplete() and @["USSD Notification"]? return moment(@timeOfHouseholdComplete().replace(/\+0\d:00/,"")).diff(@["USSD Notification"]?.date) hoursFromNotificationToCompleteHousehold: => Math.floor(moment.duration(@timeFromSMSToCompleteHousehold()).asHours()) daysFromSMSToCompleteHousehold: => if @householdComplete() and @["USSD Notification"]? moment.duration(@timeFromSMSToCompleteHousehold()).asDays() odkClassification: => if @["ODK 2017-2019"] switch @["ODK 2017-2019"]["case_classification:case_category"] when 1 then "Imported" when 2,3 then "Indigenous" when 4 then "Induced" when 5 then "Relapsing" classificationsWithPositiveIndividualObjects: => for positiveIndividual in @positiveIndividualObjects() { classification: positiveIndividual.classification() positiveIndividual: positiveIndividual } classificationsBy: (property) => (for data in @classificationsWithPositiveIndividualObjects() "#{data.positiveIndividual.data[property]}: #{data.classification}" ).join(", ") classificationsByFunction: (functionName) => (for data in @classificationsWithPositiveIndividualObjects() "#{data.positiveIndividual[functionName]()}: #{data.classification}" ).join(", ") classificationsByHouseholdMemberType: => # IF household member type is undefined it is either: # in progress index case # pre 2019 household member (for data in @classificationsWithPositiveIndividualObjects() if data.positiveIndividual.data.question isnt "Household Members" "Index Case: #{data.classification}" else if data.positiveIndividual.data["HouseholdMemberType"] is undefined "Household Member: #{data.classification}" else "#{data.positiveIndividual.data["HouseholdMemberType"]}: #{data.classification}" ).join(", ") classificationsByDiagnosisDate: => @classificationsByFunction("dateOfPositiveResults") classificationsByIsoYearIsoWeekFociDistrictFociShehia: => (for classificationWithPositiveIndividual in @classificationsWithPositiveIndividualObjects() classification = classificationWithPositiveIndividual.classification positiveIndividual = classificationWithPositiveIndividual.positiveIndividual dateOfPositiveResults = positiveIndividual.dateOfPositiveResults() date = if dateOfPositiveResults moment(dateOfPositiveResults) else # Use index case date if we are missing positiveIndividual's date if dateOfPositiveResults = @dateOfPositiveResults() moment(dateOfPositiveResults) if date? isoYear = date.isoWeekYear() isoWeek = date.isoWeek() fociDistrictShehia = if (focus = positiveIndividual.data["WhereCouldTheMalariaFocusBe"]) focus = focus.trim() if focus is "Patient Shehia" [@district(), @shehia()] else if focus is "Other Shehia Within Zanzibar" otherDistrict = positiveIndividual.data["WhichOtherDistrictWithinZanzibar"] otherShehia = positiveIndividual.data["WhichOtherShehiaWithinZanzibar"] shehiaUnit = @shehiaUnit(otherShehia, otherDistrict) [ shehiaUnit?.ancestorAtLevel("DISTRICT")?.name or @district() shehiaUnit?.name or @shehia() ] else [@district(), @shehia()] else if positiveIndividual.data.HouseholdMemberType is "Index Case" and (odkData = @["ODK 2017-2019"]) #TODO waiting to find out which ODK questions were used for this [@district(), @shehia()] else [@district(), @shehia()] [fociDistrict,fociShehia] = fociDistrictShehia "#{isoYear}:#{isoWeek}:#{fociDistrict}:#{fociShehia}:#{classification}" ).join(", ") evidenceForClassifications: => _(for householdMember in @["Household Members"] if householdMember.CaseCategory "#{householdMember.CaseCategory}: #{householdMember.SummarizeEvidenceUsedForClassification}" ).compact().join(", ") concatenateHouseholdMembers: (property) => _(for householdMember in @["Household Members"] if householdMember.CaseCategory "#{householdMember.CaseCategory}: #{householdMember[property]}" ).compact().join(", ") occupations: => @concatenateHouseholdMembers("Occupation") numbersSentTo: => @["USSD Notification"]?.numbersSentTo?.join(", ") # Data properties above # # ------------- # createOrUpdateOnDhis2: (options = {}) => options.malariaCase = @ Coconut.dhis2.createOrUpdateMalariaCase(options) spreadsheetRow: (question) => console.error "Must call loadSpreadsheetHeader at least once before calling spreadsheetRow" unless Coconut.spreadsheetHeader? spreadsheetRowObjectForResult = (fields,result) -> if result? _(fields).map (field) => if result[field]? if _.contains(Coconut.identifyingAttributes, field) return b64_sha1(result[field]) else return result[field] else return "" else return null if question is "Household Members" _(@[question]).map (householdMemberResult) -> spreadsheetRowObjectForResult(Coconut.spreadsheetHeader[question], householdMemberResult) else spreadsheetRowObjectForResult(Coconut.spreadsheetHeader[question], @[question]) spreadsheetRowString: (question) => if question is "Household Members" _(@spreadsheetRow(question)).map (householdMembersRows) -> result = _(householdMembersRows).map (data) -> "\"#{data}\"" .join(",") result += "--EOR--" if result isnt "" .join("") else result = _(@spreadsheetRow(question)).map (data) -> "\"#{data}\"" .join(",") result += "--EOR--" if result isnt "" summaryResult: (property,options) => priorityOrder = options?.priorityOrder or [ "Household" "Facility" "Case Notification" "USSD Notification" ] if property.match(/:/) propertyName = property priorityOrder = [property.split(/: */)[0]] # If prependQuestion then we only want to search within that question priorityOrder = [options.prependQuestion] if options?.prependQuestion # Make the labels be human readable by looking up the original question text and using that labelMappings = {} _(priorityOrder).each (question) -> return if question is "USSD Notification" labelMappings[question] = Coconut.questions.findWhere({_id:question}).safeLabelsToLabelsMappings() # Looks through the results in the prioritized order for a match findPrioritizedProperty = (propertyNames=[property]) => result = null _(propertyNames).each (propertyName) => return if result _(priorityOrder).each (question) => return if result return unless @[question]? if @[question][propertyName]? result = @[question][propertyName] property = labelMappings[question][propertyName] if labelMappings[question] and labelMappings[question][propertyName] return result result = null result = @[options.functionName]() if options?.functionName result = @[property]() if result is null and @[property] result = findPrioritizedProperty() if result is null if result is null result = findPrioritizedProperty(options.otherPropertyNames) if options?.otherPropertyNames result = JSON.stringify(result) if _(result).isObject() if _(result).isString() result = result?.trim() if options?.propertyName property = options.propertyName else property = titleize(humanize(property)) if options?.prependQuestion property = "#{options.prependQuestion}: #{property}" return {"#{property}": result} summaryCollection: => result = {} _(Case.summaryProperties).each (options, property) => summaryResult = @summaryResult(property, options) # Don't overwrite data if it is already there # Not exactly sure why this is needed, but there seem to be # Null duplicates that replace good data unless result[_(summaryResult).keys()[0]]? result = _(result).extend summaryResult return result summary: -> _(Case.summaryProperties).map (options, property) => @summaryResult(property, options) Case.summaryPropertiesKeys = -> _(Case.summaryProperties).map (options, key) -> if options.propertyName key = options.propertyName else key = s(key).humanize().titleize().value().replace("Numberof", "Number of") summaryAsCSVString: => _(@summary()).chain().map (summaryItem) -> "\"#{_(summaryItem).values()}\"" .flatten().value().join(",") + "--EOR--<br/>" Case.summaryProperties = { # TODO Document how the different options work # For now just look up at summaryResult function # propertyName is used to change the column name at the top of the CSV # otherPropertyNames is an array of other values to try and check # Case Notification MalariaCaseID: propertyName: "Malaria Case ID" IndexCaseDiagnosisDate: propertyName: "Index Case Diagnosis Date" IndexCaseDiagnosisDateIsoWeek: propertyName: "Index Case Diagnosis Date ISO Week" IndexCaseDiagnosisDateAndTime: propertyName: "Index Case Diagnosis Date And Time" classificationsByHouseholdMemberType: {} classificationsByDiagnosisDate: {} classificationsByIsoYearIsoWeekFociDistrictFociShehia: {} evidenceForClassifications: {} reasonForLostToFollowup: {} namesOfAdministrativeLevels: {} island: {} district: {} facility: {} facilityType: {} facilityDistrict: propertyName: "District of Facility" shehia: {} shehiaFromGPS: {} isShehiaValid: {} highRiskShehia: {} village: propertyName: "Village" villageFromGPS: {} IndexCasePatientName: propertyName: "Patient Name" ageInYears: {} Sex: {} isUnder5: propertyName: "Is Index Case Under 5" SMSSent: propertyName: "SMS Sent to DMSO" hasCaseNotification: {} numbersSentTo: {} source: {} source_phone: {} type: {} lastQuestionCompleted: {} hasCompleteFacility: {} notCompleteFacilityAfter24Hours: propertyName: "Not Complete Facility After 24 Hours" notFollowedUpAfter48Hours: propertyName: "Not Followed Up After 48 Hours" notFollowedUpAfterXHours: propertyName: "Not Followed Up After X Hours" followedUpWithin48Hours: propertyName: "Followed Up Within 48 Hours" completeHouseholdVisit: propertyName: "Complete Household Visit" CompleteHouseholdVisit: propertyName: "Complete Household Visit" numberHouseholdMembersTestedAndUntested: {} numberHouseholdMembersTested: {} NumberPositiveIndividualsAtIndexHousehold: {} NumberHouseholdOrNeighborMembers: {} NumberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholds: {} NumberHouseholdOrNeighborMembersTested: {} NumberPositiveIndividualsIncludingIndex: {} NumberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholdsUnder5: propertyName: "Number Positive Cases At Index Household And Neighbor Households Under 5" NumberSuspectedImportedCasesIncludingHouseholdMembers: {} MassScreenCase: {} CaseIdForOtherHouseholdMemberThatTestedPositiveAtAHealthFacility: propertyName: "Case ID for Other Household Member That Tested Positive at a Health Facility" CommentRemarks: {} ContactMobilePatientRelative: {} HasSomeoneFromTheSameHouseholdRecentlyTestedPositiveAtAHealthFacility: propertyName: "Has Someone From the Same Household Recently Tested Positive at a Health Facility" HeadOfHouseholdName: {} ParasiteSpecies: {} ReferenceInOpdRegister: propertyName: "Reference In OPD Register" TreatmentGiven: {} #Household CouponNumbers: {} FollowupNeighbors: {} HaveYouGivenCouponsForNets: {} HeadOfHouseholdName: {} HouseholdLocationAccuracy: propertyName: "Household Location - Accuracy" functionName: "householdLocationAccuracy" HouseholdLocationAltitude: propertyName: "Household Location - Altitude" HouseholdLocationAltitudeAccuracy: propertyName: "Household Location - Altitude Accuracy" HouseholdLocationDescription: propertyName: "Household Location - Description" HouseholdLocationHeading: propertyName: "Household Location - Heading" HouseholdLocationLatitude: propertyName: "Household Location - Latitude" functionName: "householdLocationLatitude" HouseholdLocationLongitude: propertyName: "Household Location - Longitude" functionName: "householdLocationLongitude" HouseholdLocationTimestamp: propertyName: "Household Location - Timestamp" IndexCaseIfPatientIsFemale1545YearsOfAgeIsSheIsPregant: propertyName: "Is Index Case Pregnant" IndexCasePatient: {} IndexCasePatientSCurrentStatus: propertyName: "Index Case Patient's Current Status" IndexCasePatientSTreatmentStatus: propertyName: "Index Case Patient's Treatment Status" IndexCaseSleptUnderLlinLastNight: propertyName: "Index Case Slept Under LLIN Last Night" IndexCaseDiagnosisDate: {} LastDateOfIrs: propertyName: "Last Date Of IRS" NumberOfHouseholdMembersTreatedForMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" NumberOfHouseholdMembersWithFeverOrHistoryOfFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" NumberOfLlin: propertyName: "Number Of LLIN" NumberOfSleepingPlacesBedsMattresses: propertyName: "Number of Sleeping Places (Beds/Mattresses)" NumberOfOtherHouseholdsWithin50StepsOfIndexCaseHousehold: propertyName: "Number of Other Households Within 50 Steps of Index Case Household" ReasonForVisitingHousehold: {} ShehaMjumbe: propertyName: "Sheha Mjumbe" TotalNumberOfResidentsInTheHousehold: {} DaysFromCaseNotificationToCompleteFacility: {} DaysFromSmsToCompleteHousehold: propertyName: "Days between SMS Sent to DMSO to Having Complete Household" DaysBetweenPositiveResultAndNotificationFromFacility: {} LessThanOneDayBetweenPositiveResultAndNotificationFromFacility: {} OneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: {} TwoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: {} MoreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: {} DaysBetweenPositiveResultAndCompleteHousehold: {} LessThanOneDayBetweenPositiveResultAndCompleteHousehold: {} OneToTwoDaysBetweenPositiveResultAndCompleteHousehold: {} TwoToThreeDaysBetweenPositiveResultAndCompleteHousehold: {} MoreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: {} "USSD Notification: Created At": otherPropertyNames: ["createdAt"] "USSD Notification: Date": otherPropertyNames: ["date"] "USSD Notification: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "USSD Notification: User": otherPropertyNames: ["user"] "Case Notification: Created At": otherPropertyNames: ["createdAt"] "Case Notification: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Case Notification: Saved By": otherPropertyNames: ["savedBy"] "Facility: Created At": otherPropertyNames: ["createdAt"] "Facility: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Facility: Saved By": otherPropertyNames: ["savedBy"] "Facility: User": otherPropertyNames: ["user"] "Household: Created At": otherPropertyNames: ["createdAt"] "Household: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Household: Saved By": otherPropertyNames: ["savedBy"] "Household: User": otherPropertyNames: ["user"] ## Old naming HeadofHouseholdName: propertyName: "Head Of Household Name" ContactMobilepatientrelative: propertyName: "Contact Mobile Patient Relative" IfYESlistALLplacestravelled: propertyName: "All Places Traveled to in Past Month" CaseIDforotherhouseholdmemberthattestedpositiveatahealthfacility: propertyName: "CaseID For Other Household Member That Tested Positive at a Health Facility" TravelledOvernightinpastmonth: propertyName: "Travelled Overnight in Past Month" Hassomeonefromthesamehouseholdrecentlytestedpositiveatahealthfacility: propertyName: "Has Someone From The Same Household Recently Tested Positive at a Health Facility" Reasonforvisitinghousehold: propertyName: "Reason For Visiting Household" Ifyeslistallplacestravelled: propertyName: "If Yes List All Places Travelled" Fevercurrentlyorinthelasttwoweeks: propertyName: "Fever Currently Or In The Last Two Weeks?" SleptunderLLINlastnight: propertyName: "Slept Under LLIN Last Night?" OvernightTravelinpastmonth: propertyName: "Overnight Travel in Past Month" ResidentofShehia: propertyName: "Resident of Shehia" TotalNumberofResidentsintheHousehold: propertyName: "Total Number of Residents in the Household" NumberofLLIN: propertyName: "Number of LLIN" NumberofSleepingPlacesbedsmattresses: propertyName: "Number of Sleeping Places (Beds/Mattresses)" NumberofHouseholdMemberswithFeverorHistoryofFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" NumberofHouseholdMembersTreatedforMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" LastdateofIRS: propertyName: "Last Date of IRS" Haveyougivencouponsfornets: propertyName: "Have you given coupon(s) for nets?" IndexcaseIfpatientisfemale1545yearsofageissheispregant: propertyName: "Index Case: If Patient is Female 15-45 Years of Age, Is She Pregnant?" IndexcasePatientscurrentstatus: propertyName: "Index case: Patient's current status" IndexcasePatientstreatmentstatus: propertyName: "Index case: Patient's treatment status" indexCasePatientName: propertyName: "Patient Name" IndexcasePatient: propertyName: "Index Case Patient" IndexcaseSleptunderLLINlastnight: propertyName: "Index case: Slept under LLIN last night?" IndexcaseOvernightTraveloutsideofZanzibarinthepastyear: propertyName: "Index Case Overnight Travel Outside of Zanzibar in the Past Year" IndexcaseOvernightTravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "Index Case Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar07daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 0-7 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar814daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 8-14 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar1521daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 15-21 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar2242daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 22-42 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar43365daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 43-365 Days Before Positive Test Result" ListalllocationsofovernighttravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "All Locations Of Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" daysBetweenPositiveResultAndNotificationFromFacility: {} estimatedHoursBetweenPositiveResultAndNotificationFromFacility: {} daysFromCaseNotificationToCompleteFacility: propertyName: "Days From Case Notification To Complete Facility" daysFromSMSToCompleteHousehold: propertyName: "Days between SMS Sent to DMSO to Having Complete Household" "HouseholdLocation-description": propertyName: "Household Location - Description" "HouseholdLocation-latitude": propertyName: "Household Location - Latitude" functionName: "householdLocationLatitude" "HouseholdLocation-longitude": propertyName: "Household Location - Longitude" functionName: "householdLocationLongitude" "HouseholdLocation-accuracy": propertyName: "Household Location - Accuracy" functionName: "householdLocationAccuracy" "HouseholdLocation-altitude": propertyName: "Household Location - Altitude" "HouseholdLocation-altitudeAccuracy": propertyName: "Household Location - Altitude Accuracy" "HouseholdLocation-timestamp": propertyName: "Household Location - Timestamp" travelLocationName: propertyName: "Travel Location Name" OvernightTravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" OvernightTraveloutsideofZanzibarinthepastyear: propertyName: "Overnight Travel Outside of Zanzibar In The Past Year" ReferredtoHealthFacility: propertyName: "Referred to Health Facility" hasCompleteFacility: propertyName: "Has Complete Facility" notCompleteFacilityAfter24Hours: propertyName: "Not Complete Facility After 24 Hours" notFollowedUpAfter48Hours: propertyName: "Not Followed Up After 48 Hours" followedUpWithin48Hours: propertyName: "Followed Up Within 48Hours" completeHouseholdVisit: propertyName: "Complete Household Visit" numberPositiveIndividualsExcludingIndex: propertyName: "Number Positive Individuals At Household Excluding Index" numberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholds: propertyName: "Number Positive Cases At Index Household And Neighbor Households" numberPositiveIndividuals: propertyName: "Number Positive Individuals" numberPositiveIndividualsUnder5: propertyName: "Number Positive Individuals Under 5" numberPositiveIndividualsOver5: propertyName: "Number Positive Individuals Over 5" NumberofHouseholdMembersTreatedforMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" NumberofHouseholdMemberswithFeverorHistoryofFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" massScreenCase: propertyName: "Mass Screen Case" TotalNumberofResidentsintheHousehold: propertyName: "Total Number Of Residents In The Household" lessThanOneDayBetweenPositiveResultAndNotificationFromFacility: propertyName: "Less Than One Day Between Positive Result And Notification From Facility" oneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "One To Two Days Between Positive Result And Notification From Facility" twoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "Two To Three Days Between Positive Result And Notification From Facility" moreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "More Than Three Days Between Positive Result And Notification From Facility" daysBetweenPositiveResultAndCompleteHousehold: propertyName: "Days Between Positive Result And Complete Household" lessThanOneDayBetweenPositiveResultAndCompleteHousehold: propertyName: "Less Than One Day Between Positive Result And Complete Household" oneToTwoDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "One To Two Days Between Positive Result And Complete Household" twoToThreeDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "Two To Three Days Between Positive Result And Complete Household" moreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "More Than Three Days Between Positive Result And Complete Household" occupations: {} dhis2CasesByTypeOfDetection: propertyName: "DHIS2 Cases by Type of Detection" dhis2CasesByClassification: propertyName: "DHIS2 Cases by Classification" dhis2CasesByAge: propertyName: "DHIS2 Cases by Age" dhis2CasesByGender: propertyName: "DHIS2 Cases by Gender" allUserNamesString: propertyName: "Malaria Surveillance Officers" wasTransferred: {} } dateOfMalariaResultFromIndividual: (positiveIndividual) => # First try and get the individuals' date, then the createdAt time (pre-2019) if all fails just use the date for the case or the date that the notification was made date = positiveIndividual.DateOfPositiveResults or positiveIndividual.createdAt or @dateOfPositiveResults() or positiveIndividual.date moment(date).format("YYYY-MM-DD") dhis2CasesByTypeOfDetection: => result = {} for positiveIndividual in @positiveIndividualsIndexCasesOnly() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= { "Passive": 0 "Active": 0 } result[date][shehia]["Passive"] += 1 for positiveIndividual in @positiveIndividualsExcludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= { "Passive": 0 "Active": 0 } result[date][shehia]["Active"] += 1 result dhis2CasesByClassification: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= {} result[date][shehia][positiveIndividual.CaseCategory or "Unclassified"] or= 0 result[date][shehia][positiveIndividual.CaseCategory or "Unclassified"] += 1 result dhis2CasesByAge: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() age = @ageInYears(positiveIndividual.Age, positiveIndividual.AgeInYearsMonthsDays) ageRange = if age? switch when age < 5 then "<5 yrs" when age < 15 then "5<15 yrs" when age < 25 then "15<25 yrs" when age >= 25 then ">25 yrs" else "Unknown" else "Unknown" date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= {} result[date][shehia][ageRange] or= 0 result[date][shehia][ageRange] += 1 result dhis2CasesByGender: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia gender = positiveIndividual.Sex if gender isnt "Male" or gender isnt "Female" then gender = "Unknown" result[date] or= {} result[date][shehia] or= {} result[date][shehia][gender] or=0 result[date][shehia][gender] += 1 result saveAndAddResultToCase: (result) => if @[result.question]? console.error "#{result.question} already exists for:" console.error @ return resultQuestion = result.question Coconut.database.put result .then (result) => console.log "saved:" console.log result @questions.push result.question @[result.question] = result Coconut.headerView.update() Coconut.showNotification( "#{resultQuestion} record created") .catch (error) -> console.error error createNextResult: => @fetch error: -> console.error error success: => if @["Household Members"] and @["Household Members"].length > 0 console.log "Household Members exists, no result created" # Don't create anything else if @Household?.complete console.log "Creating Household members and neighbor households if necessary" @createHouseholdMembers() @createNeighborHouseholds() else if @Facility?.complete console.log "Creating Household" @createHousehold() else if @["Case Notification"]?.complete console.log "Creating Facility" @createFacility() _.delay(Coconut.menuView.render, 500) createFacility: => @saveAndAddResultToCase _id: "result-case-#{@caseID}-Facility-#{radix64.encodeInt(moment().format('x'))}-#{Coconut.instanceId}" question: "Facility" MalariaCaseID: @caseID DistrictForFacility: @facilityDistrict() FacilityName: @facility() DistrictForShehia: @shehiaUnit().ancestorAtLevel("DISTRICT")?.name Shehia: @shehia() collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") createHousehold: => @saveAndAddResultToCase _id: "result-case-#{@caseID}-Household-#{radix64.encodeInt(moment().format('x'))}-#{Coconut.instanceId}" question: "Household" Reasonforvisitinghousehold: "Index Case Household" MalariaCaseID: @caseID HeadOfHouseholdName: @Facility.HeadOfHouseholdName District: @district() Shehia: @shehia() Village: @Facility.Village ShehaMjumbe: @Facility.ShehaMjumbe ContactMobilePatientRelative: @Facility.ContactMobilePatientRelative collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") createHouseholdMembers: => unless _(@questions).contains 'Household Members' _(@Household.TotalNumberOfResidentsInTheHousehold).times (index) => result = { _id: "result-case-#{@caseID}-Household-Members-#{radix64.encodeInt(moment().format('x'))}-#{radix64.encodeInt(Math.round(Math.random()*100000))}-#{Coconut.instanceId}" # There's a chance moment will be the same so add some randomness question: "Household Members" MalariaCaseID: @caseID HeadOfHouseholdName: @Household.HeadOfHouseholdName collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") } if index is 0 _(result).extend HouseholdMemberType: "Index Case" FirstName: @Facility?.FirstName LastName: @Facility?.LastName DateOfPositiveResults: @Facility?.DateOfPositiveResults DateAndTimeOfPositiveResults: @Facility?.DateAndTimeOfPositiveResults Sex: @Facility?.Sex Age: @Facility?.Age AgeInYearsMonthsDays: @Facility?.AgeInYearsMonthsDays MalariaMrdtTestResults: @Facility?.MalariaMrdtTestResults MalariaTestPerformed: @Facility?.MalariaTestPerformed Coconut.database.put result .then => @questions.push result.question @[result.question] = [] unless @[result.question] @[result.question].push result .catch (error) -> console.error error Coconut.headerView.update() Coconut.showNotification( "Household member record(s) created") createNeighborHouseholds: => # If there is more than one Household for this case, then Neighbor households must already have been created unless (_(@questions).filter (question) -> question is 'Household').length is 1 _(@Household.NumberOfOtherHouseholdsWithin50StepsOfIndexCaseHousehold).times => result = { _id: "result-case-#{@caseID}-Household-#{radix64.encodeInt(moment().format('x'))}-#{radix64.encodeInt(Math.round(Math.random()*100000))}-#{Coconut.instanceId}" # There's a chance moment will be the same so add some randomness ReasonForVisitingHousehold: "Index Case Neighbors" question: "Household" MalariaCaseID: @result.get "MalariaCaseID" Shehia: @result.get "Shehia" Village: @result.get "Village" ShehaMjumbe: @result.get "ShehaMjumbe" collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") } Coconut.database.put result .then => Coconut.headerView.update() .catch (error) -> console.error error Coconut.showNotification( "Neighbor Household created") wasTransferred: => @transferData().length > 0 transferData: => transferData = [] for question in @questions if @[question].transferred data = @[question].transferred data["question"] = question transferData.push data transferData Case.resetSpreadsheetForAllCases = => Coconut.database.get "CaseSpreadsheetData" .then (caseSpreadsheetData) -> Case.updateCaseSpreadsheetDocs(0,caseSpreadsheetData) .catch (error) -> console.error error Case.loadSpreadsheetHeader = (options) -> if Coconut.spreadsheetHeader options.success() else Coconut.database.get "spreadsheet_header" .catch (error) -> console.error error .then (result) -> Coconut.spreadsheetHeader = result.fields options.success() Case.updateCaseSpreadsheetDocs = (options) -> # defaults used for first run caseSpreadsheetData = {_id: "CaseSpreadsheetData" } changeSequence = 0 updateCaseSpreadsheetDocs = (changeSequence, caseSpreadsheetData) -> Case.updateCaseSpreadsheetDocsSince changeSequence: changeSequence error: (error) -> console.log "Error updating CaseSpreadsheetData:" console.log error options.error?() success: (numberCasesChanged,lastChangeSequenceProcessed) -> console.log "Updated CaseSpreadsheetData" caseSpreadsheetData.lastChangeSequenceProcessed = lastChangeSequenceProcessed console.log caseSpreadsheetData Coconut.database.put caseSpreadsheetData .catch (error) -> console.error error .then -> console.log numberCasesChanged if numberCasesChanged > 0 Case.updateCaseSpreadsheetDocs(options) #recurse else options?.success?() Coconut.database.get "CaseSpreadsheetData" .catch (error) -> console.log "Couldn't find 'CaseSpreadsheetData' using defaults: changeSequence: #{changeSequence}" updateCaseSpreadsheetDocs(changeSequence,caseSpreadsheetData) .then (result) -> caseSpreadsheetData = result changeSequence = result.lastChangeSequenceProcessed updateCaseSpreadsheetDocs(changeSequence,caseSpreadsheetData) Case.updateCaseSpreadsheetDocsSince = (options) -> Case.loadSpreadsheetHeader success: -> $.ajax url: "/#{Coconut.config.database_name()}/_changes" dataType: "json" data: since: options.changeSequence include_docs: true limit: 500 error: (error) => console.log "Error downloading changes after #{options.changeSequence}:" console.log error options.error?(error) success: (changes) => changedCases = _(changes.results).chain().map (change) -> change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question? .compact().uniq().value() lastChangeSequence = changes.results.pop()?.seq Case.updateSpreadsheetForCases caseIDs: changedCases error: (error) -> console.log "Error updating #{changedCases.length} cases, lastChangeSequence: #{lastChangeSequence}" console.log error success: -> console.log "Updated #{changedCases.length} cases, lastChangeSequence: #{lastChangeSequence}" options.success(changedCases.length, lastChangeSequence) Case.updateSpreadsheetForCases = (options) -> docsToSave = [] questions = "USSD Notification,Case Notification,Facility,Household,Household Members".split(",") options.success() if options.caseIDs.length is 0 finished = _.after options.caseIDs.length, -> Coconut.database.bulkDocs docsToSave .catch (error) -> console.error error .then -> options.success() _(options.caseIDs).each (caseID) -> malariaCase = new Case caseID: caseID malariaCase.fetch error: (error) -> console.log error success: -> docId = "spreadsheet_row_#{caseID}" spreadsheet_row_doc = {_id: docId} saveRowDoc = (result) -> spreadsheet_row_doc = result if result? # if the row already exists use the _rev _(questions).each (question) -> spreadsheet_row_doc[question] = malariaCase.spreadsheetRowString(question) spreadsheet_row_doc["Summary"] = malariaCase.summaryAsCSVString() docsToSave.push spreadsheet_row_doc finished() Coconut.database.get docId .catch (error) -> saveRowDoc() .then (result) -> saveRowDoc(result) Case.getCases = (options) -> Coconut.database.query "cases", keys: options.caseIDs include_docs: true .catch (error) -> options?.error(error) .then (result) => cases = _.chain(result.rows) .groupBy (row) => row.key .map (resultsByCaseID) => malariaCase = new Case results: _.pluck resultsByCaseID, "doc" malariaCase .compact() .value() options?.success?(cases) Promise.resolve(cases) # Used on mobile client Case.getCasesSummaryData = (startDate, endDate) => Coconut.database.query "casesWithSummaryData", startDate: startDate endDate: endDate descending: true include_docs: true .catch (error) => console.error JSON.stringify error .then (result) => _(result.rows).chain().map (row) => row.doc.MalariaCaseID ?= row.key # For case docs without MalariaCaseID add it (caseid etc) row.doc .groupBy "MalariaCaseID" .map (resultDocs, malariaCaseID) => new Case caseID: malariaCaseID results: resultDocs .value() Case.getLatestChangeForDatabase = -> new Promise (resolve,reject) => Coconut.database.changes descending: true include_docs: false limit: 1 .on "complete", (mostRecentChange) -> resolve(mostRecentChange.last_seq) .on "error", (error) -> reject error Case.getLatestChangeForCurrentSummaryDataDocs = -> Coconut.reportingDatabase.get "CaseSummaryData" .catch (error) -> console.error "Error while getLatestChangeForCurrentSummaryDataDocs: #{error}" if error.reason is "missing" return Promise.resolve(null) else return Promise.reject("Non-missing error when getLatestChangeForCurrentSummaryDataDocs") .then (caseSummaryData) -> return Promise.resolve(caseSummaryData?.lastChangeSequenceProcessed or null) Case.resetAllCaseSummaryDocs = (options) => # Docs to save designDocs = await Coconut.reportingDatabase.allDocs startkey: "_design" endkey: "_design\uf777" include_docs: true .then (result) -> Promise.resolve _(result.rows).map (row) -> doc = row.doc delete doc._rev doc otherDocsToSave = await Coconut.reportingDatabase.allDocs include_docs: true keys: [ "shehia metadata" ] .then (result) -> console.log result Promise.resolve( _(result.rows).chain().map (row) -> doc = row.doc delete doc._rev if doc doc .compact().value() ) docsToSave = designDocs.concat(otherDocsToSave) reportingDatabaseNameWithCredentials = Coconut.reportingDatabase.name await Coconut.reportingDatabase.destroy() .catch (error) -> console.error error throw "Error while destroying database" Coconut.reportingDatabase = new PouchDB(reportingDatabaseNameWithCredentials) await Coconut.reportingDatabase.bulkDocs docsToSave try latestChangeForDatabase = await Case.getLatestChangeForDatabase() console.log "Latest change: #{latestChangeForDatabase}" console.log "Retrieving all available case IDs" Coconut.database.query "cases/cases" .then (result) => allCases = _(result.rows).chain().pluck("key").uniq(true).reverse().value() console.log "Updating #{allCases.length} cases" await Case.updateSummaryForCases caseIDs: allCases console.log "Updated: #{allCases.length} cases" Coconut.reportingDatabase.upsert "CaseSummaryData", (doc) => doc.lastChangeSequenceProcessed = latestChangeForDatabase doc catch error console.error Case.updateCaseSummaryDocs = (options) -> latestChangeForDatabase = await Case.getLatestChangeForDatabase() latestChangeForCurrentSummaryDataDocs = await Case.getLatestChangeForCurrentSummaryDataDocs() #latestChangeForCurrentSummaryDataDocs = "3490519-g1AAAACseJzLYWBgYM5gTmEQTM4vTc5ISXIwNDLXMwBCwxygFFMiQ1JoaGhIVgZzEoPg_se5QDF2S3MjM8tkE2x68JgEMic0j4Vh5apVq7KAhu27jkcxUB1Q2Sog9R8IQMqPyGYBAJk5MBA" # console.log "latestChangeForDatabase: #{latestChangeForDatabase?.replace(/-.*/, "")}, latestChangeForCurrentSummaryDataDocs: #{latestChangeForCurrentSummaryDataDocs?.replace(/-.*/,"")}" if latestChangeForCurrentSummaryDataDocs numberLatestChangeForDatabase = parseInt(latestChangeForDatabase?.replace(/-.*/,"")) numberLatestChangeForCurrentSummaryDataDocs = parseInt(latestChangeForCurrentSummaryDataDocs?.replace(/-.*/,"")) if numberLatestChangeForDatabase - numberLatestChangeForCurrentSummaryDataDocs > 50000 console.log "Large number of changes, so just resetting since this is more efficient that reviewing every change." return Case.resetAllCaseSummaryDocs() unless latestChangeForCurrentSummaryDataDocs console.log "No recorded change for current summary data docs, so resetting" Case.resetAllCaseSummaryDocs() else #console.log "Getting changes since #{latestChangeForCurrentSummaryDataDocs.replace(/-.*/, "")}" # Get list of cases changed since latestChangeForCurrentSummaryDataDocs Coconut.database.changes since: latestChangeForCurrentSummaryDataDocs include_docs: true filter: "_view" view: "cases/cases" .then (result) => return if result.results.length is 0 #console.log "Found changes, now plucking case ids" changedCases = _(result.results).chain().map (change) -> change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question? .compact().uniq().value() #console.log "Changed cases: #{_(changedCases).length}" await Case.updateSummaryForCases caseIDs: changedCases console.log "Updated: #{changedCases.length} cases" Coconut.reportingDatabase.upsert "CaseSummaryData", (doc) => doc.lastChangeSequenceProcessed = latestChangeForDatabase doc .catch (error) => console.error error .then => console.log "CaseSummaryData updated through sequence: #{latestChangeForDatabase}" Case.updateSummaryForCases = (options) => new Promise (resolve, reject) => return resolve() if options.caseIDs.length is 0 numberOfCasesToProcess = options.caseIDs.length numberOfCasesProcessed = 0 numberOfCasesToProcessPerIteration = 100 while options.caseIDs.length > 0 caseIDs = options.caseIDs.splice(0,numberOfCasesToProcessPerIteration) # remove 100 caseids cases = await Case.getCases caseIDs: caseIDs docsToSave = [] for malariaCase in cases caseID = malariaCase.caseID docId = "case_summary_#{caseID}" currentCaseSummaryDoc = null try currentCaseSummaryDoc = await Coconut.reportingDatabase.get(docId) catch # Ignore if there is no document try updatedCaseSummaryDoc = malariaCase.summaryCollection() catch error console.error error updatedCaseSummaryDoc["_id"] = docId updatedCaseSummaryDoc._rev = currentCaseSummaryDoc._rev if currentCaseSummaryDoc? docsToSave.push updatedCaseSummaryDoc try await Coconut.reportingDatabase.bulkDocs(docsToSave) catch error console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}" console.error error numberOfCasesProcessed += caseIDs.length console.log "#{numberOfCasesProcessed}/#{numberOfCasesToProcess} #{Math.floor(numberOfCasesProcessed/numberOfCasesToProcess*100)}% (last ID: #{caseIDs.pop()})" resolve() ### I think this can be removed Case.getCasesByCaseIds = (options) -> Coconut.database.query "cases", keys: options.caseIDs include_docs: true .catch (error) -> console.error error .then (result) => groupedResults = _.chain(result.rows) .groupBy (row) => row.key .map (resultsByCaseID) => new Case results: _.pluck resultsByCaseID, "doc" .compact() .value() options.success groupedResults ### Case.createCaseView = (options) -> @case = options.case tables = [ "Summary" "USSD Notification" "Case Notification" "Facility" "Household" "Household Members" ] @mappings = { createdAt: "Created At" lastModifiedAt: "Last Modified At" question: "Question" user: "User" complete: "Complete" savedBy: "Saved By" } #hack to rename Question name in Case view report caseQuestions = @case.Questions().replace("Case Notification", "Case Notification Received").replace("USSD Notification","Case Notification Sent") Coconut.caseview = " <h5>Case ID: #{@case.MalariaCaseID()}</h5><button id='closeDialog' class='mdl-button mdl-js-button mdl-button--icon mdl-button--colored f-right'><i class='mdi mdi-close-circle mdi-24px'></i></button> <h6>Last Modified: #{@case.LastModifiedAt()}</h6> <h6>Questions: #{caseQuestions}</h6> " # USSD Notification doesn't have a mapping finished = _.after tables.length, => Coconut.caseview += _.map(tables, (tableType) => if (tableType is "Summary") @createObjectTable(tableType,@case.summaryCollection()) else if @case[tableType]? if tableType is "Household Members" _.map(@case[tableType], (householdMember) => @createObjectTable(tableType,householdMember) ).join("") else @createObjectTable(tableType,@case[tableType]) ).join("") options?.success() return false _(tables).each (question) => if question != "USSD Notification" question = new Question(id: question) question.fetch success: => _.extend(@mappings, question.safeLabelsToLabelsMappings()) finished() return false Case.createObjectTable = (name,object) -> #Hack to replace title to differ from Questions title name = "Case Notification Received" if name == 'Case Notification' name = "Case Notification Sent" if name == 'USSD Notification' " <h4 id=#{object._id}>#{name} <!-- <small><a href='#edit/result/#{object._id}'>Edit</a></small> --> </h4> <table class='mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp caseTable'> <thead> <tr> <th class='mdl-data-table__cell--non-numeric width65pct'>Field</th> <th class='mdl-data-table__cell--non-numeric'>Value</th> </tr> </thead> <tbody> #{ labels = CONST.Labels _.map(object, (value, field) => if !(Coconut.currentUser.isAdmin()) if (_.indexOf(['name','Name','FirstName','MiddleName','LastName','HeadOfHouseholdName','ContactMobilePatientRelative'],field) != -1) value = "************" return if "#{field}".match(/_id|_rev|collection/) " <tr> <td class='mdl-data-table__cell--non-numeric'> #{ @mappings[field] or labels[field] or field } </td> <td class='mdl-data-table__cell--non-numeric'>#{value}</td> </tr> " ).join("") } </tbody> </table> " Case.setup = => new Promise (resolve) => for docId in ["shehias_high_risk","shehias_received_irs"] await Coconut.database.get docId .catch (error) -> console.error JSON.stringify error .then (result) -> Coconut[docId] = result Promise.resolve() designDocs = { cases: (doc) -> emit(doc.MalariaCaseID, null) if doc.MalariaCaseID emit(doc.caseid, null) if doc.caseid casesWithSummaryData: (doc) -> if doc.MalariaCaseID date = doc.DateofPositiveResults or doc.lastModifiedAt match = date.match(/^(\d\d).(\d\d).(2\d\d\d)/) if match? date = "#{match[3]}-#{match[2]}-#{match[1]}" if doc.transferred? lastTransfer = doc.transferred[doc.transferred.length-1] if date.match(/^2\d\d\d\-\d\d-\d\d/) emit date, [doc.MalariaCaseID,doc.question,doc.complete,lastTransfer] if doc.caseid if document.transferred? lastTransfer = doc.transferred[doc.transferred.length-1] if doc.date.match(/^2\d\d\d\-\d\d-\d\d/) emit doc.date, [doc.caseid, "Facility Notification", null, lastTransfer] } for name, designDocFunction of designDocs designDoc = Utils.createDesignDoc name, designDocFunction await Coconut.database.upsert designDoc._id, (existingDoc) => return false if _(designDoc.views).isEqual(existingDoc?.views) console.log "Creating Case view: #{name}" designDoc .catch (error) => console.error error resolve() module.exports = Case
222069
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ moment = require 'moment' Dhis2 = require './Dhis2' CONST = require "../Constants" humanize = require 'underscore.string/humanize' titleize = require 'underscore.string/titleize' PouchDB = require 'pouchdb-core' radix64 = require('radix-64')() HouseholdMember = require './HouseholdMember' Question = require './Question' Individual = require './Individual' TertiaryIndex = require './TertiaryIndex' class Case constructor: (options) -> @caseID = options?.caseID @loadFromResultDocs(options.results) if options?.results loadFromResultDocs: (resultDocs) -> @caseResults = resultDocs @questions = [] this["Household Members"] = [] this["Neighbor Households"] = [] userRequiresDeidentification = (Coconut.currentUser?.hasRole("reports") or Coconut.currentUser is null) and not Coconut.currentUser?.hasRole("admin") _.each resultDocs, (resultDoc) => resultDoc = resultDoc.toJSON() if resultDoc.toJSON? if userRequiresDeidentification _.each resultDoc, (value,key) -> resultDoc[key] = b64_sha1(value) if value? and _.contains(Coconut.identifyingAttributes, key) if resultDoc.question @caseID ?= resultDoc["MalariaCaseID"].trim() @questions.push resultDoc.question if resultDoc.question is "Household Members" this["Household Members"].push resultDoc householdMember = new HouseholdMember() householdMember.load(resultDoc) (@householdMembers or= []).push(householdMember) else if resultDoc.question is "Household" and resultDoc.Reasonforvisitinghousehold is "Index Case Neighbors" this["Neighbor Households"].push resultDoc else if resultDoc.question is "Facility" dateOfPositiveResults = resultDoc.DateOfPositiveResults if dateOfPositiveResults? dayMonthYearMatch = dateOfPositiveResults.match(/^(\d\d).(\d\d).(20\d\d)/) if dayMonthYearMatch [day,month,year] = dayMonthYearMatch[1..] if day > 31 or month > 12 console.error "Invalid DateOfPositiveResults: #{this}" else resultDoc.DateOfPositiveResults = "#{year}-#{month}-#{day}" if this[resultDoc.question]? # Duplicate if (this[resultDoc.question].complete is "true" or this[resultDoc.question].complete is true) and (resultDoc.complete isnt "true" or resultDoc.complete isnt true) #console.warn "Using the result marked as complete" return # Use the version already loaded which is marked as complete else if this[resultDoc.question].complete and resultDoc.complete console.warn "Duplicate complete entries for case: #{@caseID}" this[resultDoc.question] = resultDoc else @caseID ?= resultDoc["caseid"].trim() @questions.push "USSD Notification" this["USSD Notification"] = resultDoc fetch: (options) => unless @caseID return Promise.reject "No caseID to fetch data for" Coconut.database.query "cases", key: @caseID include_docs: true .catch (error) -> options?.error() Promise.reject(error) .then (result) => if result.rows.length is 0 options?.error("Could not find any existing data for case #{@caseID}") Promise.reject ("Could not find any existing data for case #{@caseID}") @loadFromResultDocs(_.pluck(result.rows, "doc")) options?.success() Promise.resolve() toJSON: => returnVal = {} _.each @questions, (question) => returnVal[question] = this[question] return returnVal deIdentify: (result) -> flatten: (questions = @questions) -> returnVal = {} _.each questions, (question) => type = question _.each this[question], (value, field) -> if _.isObject value _.each value, (arrayValue, arrayField) -> returnVal["#{question}-#{field}: #{arrayField}"] = arrayValue else returnVal["#{question}:#{field}"] = value returnVal caseId: => @caseID LastModifiedAt: => _.chain(@toJSON()) .map (data, question) -> if _(data).isArray() _(data).pluck("lastModifiedAt") else data?.lastModifiedAt .flatten() .max (lastModifiedAt) -> moment(lastModifiedAt).unix() .value() Questions: -> _.keys(@toJSON()).join(", ") MalariaCaseID: -> @caseID user: -> userId = @.Household?.user || @.Facility?.user || @["Case Notification"]?.user allUserIds: -> users = [] users.push @.Household?.user users.push @.Facility?.user users.push @["Case Notification"]?.user _(users).chain().uniq().compact().value() allUserNames: => for userId in @allUserIds() Coconut.nameByUsername[userId] or "Unknown" allUserNamesString: => @allUserNames()?.join(", ") facility: -> @facilityUnit()?.name or "UNKNOWN" #@["Case Notification"]?.FacilityName.toUpperCase() or @["USSD Notification"]?.hf.toUpperCase() or @["Facility"]?.FacilityName or "UNKNOWN" facilityType: => facilityUnit = @facilityUnit() unless facilityUnit? console.warn "Unknown facility name for: #{@caseID}. Returning UNKNOWN for facilityType." return "UNKNOWN" GeoHierarchy.facilityTypeForFacilityUnit(@facilityUnit()) facilityDhis2OrganisationUnitId: => GeoHierarchy.findFirst(@facility(), "FACILITY")?.id isShehiaValid: => if @validShehia() then true else false validShehia: => @shehiaUnit()?.name ### # Try and find a shehia is in our database if @.Household?.Shehia and GeoHierarchy.validShehia(@.Household.Shehia) return @.Household?.Shehia else if @.Facility?.Shehia and GeoHierarchy.validShehia(@.Facility.Shehia) return @.Facility?.Shehia else if @["Case Notification"]?.Shehia and GeoHierarchy.validShehia(@["Case Notification"]?.Shehia) return @["Case Notification"]?.Shehia else if @["USSD Notification"]?.shehia and GeoHierarchy.validShehia(@["USSD Notification"]?.shehia) return @["USSD Notification"]?.shehia return null ### shehiaUnit: (shehiaName, districtName) => if shehiaName? and GeoHierarchy.validShehia(shehiaName) # Can pass in a shehiaName - useful for positive Individuals with different focal area else shehiaName = null # Priority order to find the best facilityName for name in [@Household?.Shehia, @Facility?.Shehia, @["Case Notification"]?.Shehia, @["USSD Notification"]?.shehia] continue unless name? name = name.trim() if GeoHierarchy.validShehia(name) shehiaName = name break unless shehiaName? # If we have no valid shehia name, then try and use facility return @facilityUnit()?.ancestorAtLevel("SHEHIA") else shehiaUnits = GeoHierarchy.find(shehiaName,"SHEHIA") if shehiaUnits.length is 1 return shehiaUnits[0] else if shehiaUnits.length > 1 # At this point we have a shehia name, but it is not unique, so we can use any data to select the correct one # Shehia names are not unique across Zanzibar, but they are unique per island # We also have region which is a level between district and island. # Strategy: get another sub-island location from the data, then limit the # list of shehias to that same island # * "District" that was passed in (used for focal areas) # Is Shehia in district? # * "District" from Household # Is Shehia in district? # * "District for Shehia" from Case Notification # Is Shehia in district? # * Facility District # Is Shehia in District # * Facility Name # Is Shehia parent of facility # * If REGION for FACILTY unit matches one of the shehia's region # * If ISLAND for FACILTY unit matches one of the shehia's region for district in [districtName, @Household?["District"], @["Case Notification"]?["District for Shehia"], @["Case Notification"]?["District for Facility"], @["USSD Notification"]?.facility_district] continue unless district? district = district.trim() districtUnit = GeoHierarchy.findOneMatchOrUndefined(district, "DISTRICT") if districtUnit? for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("DISTRICT") is districtUnit return shehiaUnit # CHECK THE REGION LEVEL for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("REGION") is districtUnit.ancestorAtLevel("REGION") return shehiaUnit # CHECK THE ISLAND LEVEL for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("ISLAND") is districtUnit.ancestorAtLevel("ISLAND") return shehiaUnit # In case we couldn't find a facility district above, try and use the facility unit which comes from the name facilityUnit = @facilityUnit() if facilityUnit? facilityUnitShehia = facilityUnit.ancestorAtLevel("SHEHIA") for shehiaUnit in shehiaUnits if shehiaUnit is facilityUnitShehia return shehiaUnit for level in ["DISTRICT", "REGION", "ISLAND"] facilityUnitAtLevel = facilityUnit.ancestorAtLevel(level) for shehiaUnit in shehiaUnits shehiaUnitAtLevel = shehiaUnit.ancestorAtLevel(level) #console.log "shehiaUnitAtLevel: #{shehiaUnitAtLevel.id}: #{shehiaUnitAtLevel.name}" #console.log "facilityUnitAtLevel: #{facilityUnitAtLevel.id}: #{facilityUnitAtLevel.name}" if shehiaUnitAtLevel is facilityUnitAtLevel return shehiaUnit villageFromGPS: => longitude = @householdLocationLongitude() latitude = @householdLocationLatitude() if longitude? and latitude? GeoHierarchy.villagePropertyFromGPS(longitude, latitude) shehiaUnitFromGPS: => longitude = @householdLocationLongitude() latitude = @householdLocationLatitude() if longitude? and latitude? GeoHierarchy.findByGPS(longitude, latitude, "SHEHIA") shehiaFromGPS: => @shehiaUnitFromGPS()?.name facilityUnit: => facilityName = null # Priority order to find the best facilityName for name in [@Facility?.FacilityName, @["Case Notification"]?.FacilityName, @["USSD Notification"]?["hf"]] continue unless name? name = name.trim() if GeoHierarchy.validFacility(name) facilityName = name break if facilityName facilityUnits = GeoHierarchy.find(facilityName, "HEALTH FACILITIES") if facilityUnits.length is 1 return facilityUnits[0] else if facilityUnits.length is 0 return null else if facilityUnits.length > 1 facilityDistrictName = null for name in [@Facility?.DistrictForFacility, @["Case Notification"]?.DistrictForFacility, @["USSD Notification"]?["facility_district"]] if name? and GeoHierarchy.validDistrict(name) facilityDistrictName = name break if facilityDistrictName? facilityDistrictUnits = GeoHierarchy.find(facilityDistrictName, "DISTRICT") for facilityUnit in facilityUnits for facilityDistrictUnit in facilityDistrictUnits if facilityUnit.ancestorAtLevel("DISTRICT") is facilityDistrictUnit return facilityUnit householdShehiaUnit: => @shehiaUnit() householdShehia: => @householdShehiaUnit()?.name shehia: -> returnVal = @validShehia() return returnVal if returnVal? # If no valid shehia is found, then return whatever was entered (or null) returnVal = @.Household?.Shehia || @.Facility?.Shehia || @["Case Notification"]?.shehia || @["USSD Notification"]?.shehia if @hasCompleteFacility() if @complete() console.warn "Case was followed up to household, but shehia name: #{returnVal} is not a valid shehia. #{@MalariaCaseID()}." else console.warn "Case was followed up to facility, but shehia name: #{returnVal} is not a valid shehia: #{@MalariaCaseID()}." return returnVal village: -> @["Facility"]?.Village facilityDistrict: -> facilityDistrict = @["USSD Notification"]?.facility_district unless facilityDistrict and GeoHierarchy.validDistrict(facilityDistrict) facilityDistrict = @facilityUnit()?.ancestorAtLevel("DISTRICT").name unless facilityDistrict #if @["USSD Notification"]?.facility_district is "WEST" and _(GeoHierarchy.find(@shehia(), "SHEHIA").map( (u) => u.ancestors()[0].name )).include "MAGHARIBI A" # MEEDS doesn't have WEST split # # # WEST got split, but DHIS2 uses A & B, so use shehia to figure out the right one if @["USSD Notification"]?.facility_district is "WEST" if shehia = @validShehia() for shehia in GeoHierarchy.find(shehia, "SHEHIA") if shehia.ancestorAtLevel("DISTRICT").name.match(/MAGHARIBI/) return shehia.ancestorAtLevel("DISTRICT").name else return "MAGHARIBI A" #Check the shehia to see if it is either MAGHARIBI A or MAGHARIBI B console.warn "Could not find a district for USSD notification: #{JSON.stringify @["USSD Notification"]}" return "UNKNOWN" GeoHierarchy.swahiliDistrictName(facilityDistrict) districtUnit: -> districtUnit = @shehiaUnit()?.ancestorAtLevel("DISTRICT") or @facilityUnit()?.ancestorAtLevel("DISTRICT") return districtUnit if districtUnit? for name in [@Facility?.DistrictForFacility, @["Case Notification"]?.DistrictForFacility, @["USSD Notification"]?["facility_district"]] if name? and GeoHierarchy.validDistrict(name) return GeoHierarchy.findOneMatchOrUndefined(name, "DISTRICT") district: => @districtUnit()?.name or "UNKNOWN" islandUnit: => @districtUnit()?.ancestorAtLevel("ISLANDS") island: => @islandUnit()?.name or "UNKNOWN" highRiskShehia: (date) => date = moment().startOf('year').format("YYYY-MM") unless date if Coconut.shehias_high_risk?[date]? _(Coconut.shehias_high_risk[date]).contains @shehia() else false locationBy: (geographicLevel) => return @validShehia() if geographicLevel.match(/shehia/i) district = @district() if district? return district if geographicLevel.match(/district/i) GeoHierarchy.getAncestorAtLevel(district, "DISTRICT", geographicLevel) else console.warn "No district for case: #{@caseID}" # namesOfAdministrativeLevels # Nation, Island, Region, District, Shehia, Facility # Example: #"ZANZIBAR","PEMBA","KUSINI PEMBA","MKOANI","WAMBAA","MWANAMASHUNGI namesOfAdministrativeLevels: () => district = @district() if district districtAncestors = _(GeoHierarchy.findFirst(district, "DISTRICT")?.ancestors()).pluck "name" result = districtAncestors.reverse().concat(district).concat(@shehia()).concat(@facility()) result.join(",") possibleQuestions: -> ["Case Notification", "Facility","Household","Household Members"] questionStatus: => result = {} _.each @possibleQuestions(), (question) => if question is "Household Members" if @["Household Members"].length is 0 result["Household Members"] = false else result["Household Members"] = true for member in @["Household Members"] unless member.complete? and (member.complete is true or member.complete is "true") result["Household Members"] = false else result[question] = (@[question]?.complete is "true" or @[question]?.complete is true) return result lastQuestionCompleted: => questionStatus = @questionStatus() for question in @possibleQuestions().reverse() return question if questionStatus[question] return "None" hasHouseholdMembersWithRepeatedNames: => @repeatedNamesInSameHousehold() isnt null repeatedNamesInSameHousehold: => names = {} for individual in @positiveAndNegativeIndividualObjects() name = individual.name() if name? and name isnt "" names[name] or= 0 names[name] += 1 repeatedNames = [] for name, frequency of names if frequency > 1 repeatedNames.push name if repeatedNames.length > 0 return repeatedNames.join(", ") else return null oneAndOnlyOneIndexCase: => numberOfIndexCases = 0 for individual in @positiveIndividualObjects() if individual.data.HouseholdMemberType is "Index Case" numberOfIndexCases+=1 console.log "numberOfIndexCases: #{numberOfIndexCases}" if numberOfIndexCases isnt 1 return numberOfIndexCases is 1 hasIndexCaseClassified: => @classificationsByHouseholdMemberType().match(/Index Case/) complete: => @questionStatus()["Household Members"] is true status: => if @["Facility"]?["Lost To Followup"] is "Yes" return "Lost To Followup" else if @complete() return "Followed up" else returnVal = "" for question, status of @questionStatus() if status is false returnVal = if question is "Household Members" and not @hasIndexCaseClassified() "Household Members does not have a classified Index Case" else if question is "Household Member" "<a href='##{Coconut.databaseName}/show/results/Household%20Members'>#{question}</a> in Progress" else url = if @[question]?._id "##{Coconut.databaseName}/edit/result/#{@[question]._id}" else "##{Coconut.databaseName}/show/results/#{question}" "<a href='#{url}'>#{question}</a> in Progress" break returnVal hasCompleteFacility: => @.Facility?.complete is "true" or @.Facility?.complete is true notCompleteFacilityAfter24Hours: => @moreThan24HoursSinceFacilityNotifed() and not @hasCompleteFacility() notFollowedUpAfter48Hours: => @moreThan48HoursSinceFacilityNotifed() and not @followedUp() followedUpWithin48Hours: => not @notFollowedUpAfter48Hours() notFollowedUpAfterXHours: => @moreThanXHoursSinceFacilityNotifed() and not @followedUp() followedUpWithinXHours: => not @notFollowedUpAfterXHours() completeHouseholdVisit: => @complete() dateHouseholdVisitCompleted: => if @completeHouseholdVisit() @.Household?.lastModifiedAt or @["Household Members"]?[0]?.lastModifiedAt or @Facility?.lastModifiedAt # When the household has two cases followedUp: => @completeHouseholdVisit() # Includes any kind of travel including only within Zanzibar indexCaseHasTravelHistory: => @.Facility?.TravelledOvernightinpastmonth?.match(/Yes/) or false indexCaseHasNoTravelHistory: => not @indexCaseHasTravelHistory() location: (type) -> # Not sure how this works, since we are using the facility name with a database of shehias #WardHierarchy[type](@toJSON()["Case Notification"]?["FacilityName"]) GeoHierarchy.findOneShehia(@toJSON()["Case Notification"]?["FacilityName"])?[type.toUpperCase()] withinLocation: (location) -> return @location(location.type) is location.name # This is just a count of househhold members not how many are positive # It excludes neighbor households completeIndexCaseHouseholdMembers: => return [] unless @["Household"]? _(@["Household Members"]).filter (householdMember) => # HeadOfHouseholdName used to determine if it is neighbor household (householdMember.HeadofHouseholdName is @["Household"].HeadofHouseholdName or householdMember.HeadOfHouseholdName is @["Household"].HeadOfHouseholdName) and (householdMember.complete is "true" or householdMember.complete is true) hasCompleteIndexCaseHouseholdMembers: => @completeIndexCaseHouseholdMembers().length > 0 # Note that this doesn't include Index - this is unclear function name positiveIndividualsAtIndexHousehold: => console.warn "Function name not clear consider using positiveIndividualsExcludingIndex instead" _(@completeIndexCaseHouseholdMembers()).filter (householdMember) -> householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### numberPositiveIndividualsAtIndexHousehold: => throw "Deprecated since name was confusing about whether index case was included, use numberPositiveIndividualsExcludingIndex" @positiveIndividualsAtIndexHousehold().length ### numberPositiveIndividualsExcludingIndex: => @positiveIndividualsExcludingIndex().length hasAdditionalPositiveIndividualsAtIndexHousehold: => @numberPositiveIndividualsExcludingIndex() > 0 completeNeighborHouseholds: => _(@["Neighbor Households"]).filter (household) => household.complete is "true" or household.complete is true completeNeighborHouseholdMembers: => return [] unless @["Household"]? _(@["Household Members"]).filter (householdMember) => (householdMember.HeadOfHouseholdName isnt @["Household"].HeadOfHouseholdName) and (householdMember.complete is "true" or householdMember.complete is true) hasCompleteNeighborHouseholdMembers: => @completeIndexCaseHouseholdMembers().length > 0 positiveIndividualsAtNeighborHouseholds: -> _(@completeNeighborHouseholdMembers()).filter (householdMember) -> householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### # Handles pre-2019 and post-2019 positiveIndividualsAtIndexHouseholdAndNeighborHouseholds: -> throw "Deprecated" _(@["Household Members"]).filter (householdMember) => householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### positiveIndividualsUnder5: => _(@positiveIndividuals()).filter (householdMemberOrNeighbor) => age = @ageInYears(householdMemberOrNeighbor.Age, householdMemberOrNeighbor.AgeInYearsMonthsDays) age and age < 5 positiveIndividualsOver5: => _(@positiveIndividuals()).filter (householdMemberOrNeighbor) => age = @ageInYears(householdMemberOrNeighbor.Age, householdMemberOrNeighbor.AgeInYearsMonthsDays) age and age >= 5 numberPositiveIndividuals: -> @positiveIndividuals().length numberHouseholdMembers: -> @["Household Members"].length numberHouseholdMembersTestedAndUntested: => numberHouseholdMembersFromHousehold = @["Household"]?["TotalNumberOfResidentsInTheHousehold"] or @["Household"]?["TotalNumberofResidentsintheHousehold"] numberHouseholdMembersWithRecord = @numberHouseholdMembers() # Some cases have more member records than TotalNumberofResidentsintheHousehold so use higher Math.max(numberHouseholdMembersFromHousehold, numberHouseholdMembersWithRecord) numberHouseholdMembersTested: => numberHouseholdMemberRecordsWithTest = _(@["Household Members"]).filter (householdMember) => switch householdMember.MalariaTestResult when "NPF", "PF", "Mixed" return true switch householdMember["MalariaTestPerformed"] when "mRDT", "Microscopy" return true .length # Check if we have pre 2019 data by checking for classifications # If there is no classification then either it was pre-2019 or followup is not done, so we need to add on an additional individual that was tested (index case) classifiedNonIndexCases = _(@["Household Members"]).filter (householdMember) => householdMember.CaseCategory? and householdMember.HouseholdMemberType isnt "Index Case" # If there is at least a case notification then we know the index case was tested if classifiedNonIndexCases.length is 0 numberHouseholdMemberRecordsWithTest+1 else numberHouseholdMemberRecordsWithTest percentOfHouseholdMembersTested: => (@numberHouseholdMembersTested()/@numberHouseholdMembersTestedAndUntested()*100).toFixed(0) updateIndividualIndex: => @tertiaryIndex or= new TertiaryIndex name: "Individual" @tertiaryIndex.updateIndexForCases({caseIDs:[@MalariaCaseID()]}) positiveIndividualObjects: => for positiveIndividual in @positiveIndividuals() new Individual(positiveIndividual, @) positiveIndividuals: => @positiveIndividualsIncludingIndex() #This function is good - don't use completeIndexCaseHouseholdMembers positiveIndividualsIncludingIndex: => positiveIndividualsExcludingIndex = @positiveIndividualsExcludingIndex() positiveIndividualsIndexCasesOnly = @positiveIndividualsIndexCasesOnly() nonIndexHaveCaseCategory = _(positiveIndividualsExcludingIndex).any (positiveIndividual) -> positiveIndividual.CaseCategory? indexHaveCaseCategory = _(positiveIndividualsIndexCasesOnly).any (positiveIndividual) -> positiveIndividual.CaseCategory? # Don't try and find an index case if there are already classified individuals # Probably these just have the wrong Household Member Type results = if nonIndexHaveCaseCategory and not indexHaveCaseCategory positiveIndividualsExcludingIndex else positiveIndividualsIndexCasesOnly?.concat(positiveIndividualsExcludingIndex) for result in results result["Malaria Positive"] = true result positiveAndNegativeIndividuals: => for individual in @positiveIndividuals().concat(@negativeIndividuals()) individual["Date Of Malaria Results"] = @dateOfMalariaResultFromIndividual(individual) individual positiveAndNegativeIndividualObjects: => for individual in @positiveAndNegativeIndividuals() new Individual(individual, @) positiveIndividualsExcludingIndex: => # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedNonIndexIndividuals = _(@["Household Members"]).filter (householdMember) => householdMember.CaseCategory? and householdMember.HouseholdMemberType isnt "Index Case" results = if classifiedNonIndexIndividuals.length > 0 classifiedNonIndexIndividuals else # If there is no classification then there will be no index case in the list of household members (pre 2019 style). This also includes neighbor households. _(@["Household Members"]).filter (householdMember) => householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" for result in results # Make sure result.HouseholdMemberType = "Other Household Member" result positiveIndividualsIndexCasesOnly: => # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedIndexCases = @["Household Members"].filter (householdMember) -> householdMember.CaseCategory isnt null and householdMember.HouseholdMemberType is "Index Case" if classifiedIndexCases.length > 0 classifiedIndexCases else # Case hasn't been followed up yet or pre 2019 data which didn't capture index case as a household member, so use facility data for index and then check for positive household members extraProperties = { MalariaCaseID: @MalariaCaseID() HouseholdMemberType: "Index Case" } if @["Facility"] # Note that if you don't start with an empty object then the first argument gets mutated [_.extend {}, @["Facility"], @["Household"], extraProperties] else if @["USSD Notification"] [_.extend {}, @["USSD Notification"], @["Household"], extraProperties] else [] negativeIndividuals: => # I've reversed the logic of positiveIndividualsExcludingIndex # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedIndividuals = [] unclassifiedNonIndexIndividuals = [] _(@["Household Members"]).map (householdMember) => if householdMember.CaseCategory? classifiedIndividuals.push householdMember else if householdMember.HouseholdMemberType isnt "Index Case" # These are the ones we want but only if others are classified unclassifiedNonIndexIndividuals.push householdMember # if we have classification then index is in the household member data # So we can return the unclassified cases which must all be negative results = if classifiedIndividuals.length > 0 unclassifiedNonIndexIndividuals else # If there is no classification then there will be no index case in the list of household members (pre 2019 style). This also includes neighbor households. _(@["Household Members"]).filter (householdMember) => (householdMember.complete is true or householdMember.complete is "true") and householdMember.MalariaTestResult isnt "PF" and householdMember.MalariaTestResult isnt "Mixed" for result in results result["Date Of Malaria Results"] = @dateOfMalariaResultFromIndividual(result) result["Malaria Positive"] = false result numberPositiveIndividuals: => @positiveIndividuals().length numberPositiveIndividualsUnder5: => @positiveIndividualsUnder5().length numberPositiveIndividualsOver5: => @positiveIndividualsOver5().length massScreenCase: => @Household?["Reason for visiting household"]? is "Mass Screen" indexCasePatientName: -> if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) return "#{@["Facility"].FirstName} #{@["Facility"].LastName}" if @["USSD Notification"]? return @["USSD Notification"]?.name if @["Case Notification"]? return @["Case Notification"]?.Name # Not sure why the casing is weird - put this in to support mobile client indexCaseDiagnosisDate: => @IndexCaseDiagnosisDate() IndexCaseDiagnosisDateAndTime: -> # If we don't have the hour/minute of the diagnosis date # Then assume that everyone gets tested at 8am if @["Facility"]?.DateAndTimeOfPositiveResults? return moment(@["Facility"]?.DateAndTimeOfPositiveResults).format("YYYY-MM-DD HH:mm") if @["Facility"]?.DateOfPositiveResults? date = @["Facility"].DateOfPositiveResults momentDate = if date.match(/^20\d\d/) moment(@["Facility"].DateOfPositiveResults) else moment(@["Facility"].DateOfPositiveResults, "DD-MM-YYYY") if momentDate.isValid() return momentDate.set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") if @["USSD Notification"]? return moment(@["USSD Notification"].date).set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") else if @["Case Notification"]? return moment(@["Case Notification"].createdAt).set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") IndexCaseDiagnosisDate: => if indexCaseDiagnosisDateAndTime = @IndexCaseDiagnosisDateAndTime() moment(indexCaseDiagnosisDateAndTime).format("YYYY-MM-DD") IndexCaseDiagnosisDateIsoWeek: => indexCaseDiagnosisDate = @IndexCaseDiagnosisDate() if indexCaseDiagnosisDate moment(indexCaseDiagnosisDate).format("GGGG-WW") householdMembersDiagnosisDates: => @householdMembersDiagnosisDate() householdMembersDiagnosisDate: => returnVal = [] _.each @["Household Members"]?, (member) -> returnVal.push member.lastModifiedAt if member.MalariaTestResult is "PF" or member.MalariaTestResult is "Mixed" ageInYears: (age = @Facility?.Age, ageInMonthsYearsOrDays = (@Facility?.AgeinMonthsOrYears or @Facility?.AgeInYearsMonthsDays)) => return null unless age? and ageInMonthsYearsOrDays? if ageInMonthsYearsOrDays is "Months" age / 12.0 else if ageInMonthsYearsOrDays is "Days" age / 365.0 else age ### return null unless @Facility if @Facility["Age in Months Or Years"]? and @Facility["Age in Months Or Years"] is "Months" @Facility["Age"] / 12.0 else @Facility["Age"] ### isUnder5: => ageInYears = @ageInYears() if ageInYears ageInYears < 5 else null householdLocationLatitude: => parseFloat(@Location?["LocationLatitude"] or @Household?["HouseholdLocationLatitude"] or @Household?["Household Location - Latitude"]) or @Household?["HouseholdLocation-latitude"] householdLocationLongitude: => parseFloat(@Location?["LocationLongitude"] or @Household?["HouseholdLocationLongitude"] or @Household?["Household Location - Longitude"]) or @Household?["HouseholdLocation-longitude"] householdLocationAccuracy: => parseFloat(@Location?["LocationAccuracy"] or @Household?["HouseholdLocationAccuracy"] or @Household?["Household Location - Accuracy"]) resultsAsArray: => _.chain @possibleQuestions() .map (question) => @[question] .flatten() .compact() .value() fetchResults: (options) => results = _.map @resultsAsArray(), (result) => returnVal = new Result() returnVal.id = result._id returnVal count = 0 _.each results, (result) -> result.fetch success: -> count += 1 options.success(results) if count >= results.length return results updateCaseID: (newCaseID) -> @fetchResults success: (results) -> _.each results, (result) -> throw "No MalariaCaseID" unless result.attributes.MalariaCaseID? result.save MalariaCaseID: newCaseID issuesRequiringCleaning: () -> # Case has multiple USSD notifications resultCount = {} questionTypes = "USSD Notification, Case Notification, Facility, Household, Household Members".split(/, /) _.each questionTypes, (questionType) -> resultCount[questionType] = 0 _.each @caseResults, (result) -> resultCount["USSD Notification"]++ if result.caseid? resultCount[result.question]++ if result.question? issues = [] _.each questionTypes[0..3], (questionType) -> issues.push "#{resultCount[questionType]} #{questionType}s" if resultCount[questionType] > 1 issues.push "Not followed up" unless @followedUp() issues.push "Orphaned result" if @caseResults.length is 1 issues.push "Missing case notification" unless @["Case Notification"]? or @["Case Notification"]?.length is 0 return issues allResultsByQuestion: -> returnVal = {} _.each "USSD Notification, Case Notification, Facility, Household".split(/, /), (question) -> returnVal[question] = [] _.each @caseResults, (result) -> if result["question"]? returnVal[result["question"]].push result else if result.hf? returnVal["USSD Notification"].push result return returnVal redundantResults: -> redundantResults = [] _.each @allResultsByQuestion, (results, question) -> console.log _.sort(results, "createdAt") dateOfPositiveResults: => @IndexCaseDiagnosisDate() daysBetweenPositiveResultAndNotificationFromFacility: => dateOfPositiveResults = @dateOfPositiveResults() notificationDate = if @["USSD Notification"]? @["USSD Notification"].date if dateOfPositiveResults? and notificationDate? Math.abs(moment(dateOfPositiveResults).diff(notificationDate, 'days')) estimatedHoursBetweenPositiveResultAndNotificationFromFacility: => dateAndTimeOfPositiveResults = @IndexCaseDiagnosisDateAndTime() notificationDate = @["USSD Notification"]?.date or @["Case Notification"]?.createdAt if dateAndTimeOfPositiveResults? and notificationDate? Math.abs(moment(dateAndTimeOfPositiveResults).diff(notificationDate, 'hours')) lessThanOneDayBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility <= 1 oneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 1 and daysBetweenPositiveResultAndNotificationFromFacility <= 2 twoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 2 and daysBetweenPositiveResultAndNotificationFromFacility <= 3 moreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 3 daysBetweenPositiveResultAndCompleteHousehold: => dateOfPositiveResults = @dateOfPositiveResults() completeHouseholdVisit = @dateHouseholdVisitCompleted() if dateOfPositiveResults and completeHouseholdVisit Math.abs(moment(dateOfPositiveResults).diff(completeHouseholdVisit, 'days')) lessThanOneDayBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold <= 1 oneToTwoDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 1 and daysBetweenPositiveResultAndCompleteHousehold <= 2 twoToThreeDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 2 and daysBetweenPositiveResultAndCompleteHousehold <= 3 moreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 3 timeFacilityNotified: => if @["USSD Notification"]? @["USSD Notification"].date else null timeSinceFacilityNotified: => timeFacilityNotified = @timeFacilityNotified() if timeFacilityNotified? moment().diff(timeFacilityNotified) else null hoursSinceFacilityNotified: => timeSinceFacilityNotified = @timeSinceFacilityNotified() if timeSinceFacilityNotified? moment.duration(timeSinceFacilityNotified).asHours() else null moreThan24HoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > 24 moreThan48HoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > 48 moreThanXHoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > parseInt(Coconut.config.case_followup) timeFromSMSToCaseNotification: => if @["Case Notification"]? and @["USSD Notification"]? return moment(@["Case Notification"]?.createdAt).diff(@["USSD Notification"]?.date) # Note the replace call to handle a bug that created lastModified entries with timezones timeFromCaseNotificationToCompleteFacility: => if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) and @["Case Notification"]? return moment(@["Facility"].lastModifiedAt.replace(/\+0\d:00/,"")).diff(@["Case Notification"]?.createdAt) daysFromCaseNotificationToCompleteFacility: => if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) and @["Case Notification"]? moment.duration(@timeFromCaseNotificationToCompleteFacility()).asDays() householdComplete: => @complete() timeOfHouseholdComplete: => return null unless @householdComplete() latestLastModifiedTimeOfHouseholdMemberRecords = "" for householdMember in @["Household Members"] if householdMember.lastModifiedAt > latestLastModifiedTimeOfHouseholdMemberRecords latestLastModifiedTimeOfHouseholdMemberRecords = householdMember.lastModifiedAt latestLastModifiedTimeOfHouseholdMemberRecords timeFromFacilityToCompleteHousehold: => if @householdComplete() and @["Facility"]? return moment(@timeOfHouseholdComplete().replace(/\+0\d:00/,"")).diff(@["Facility"]?.lastModifiedAt) timeFromSMSToCompleteHousehold: => if @householdComplete() and @["USSD Notification"]? return moment(@timeOfHouseholdComplete().replace(/\+0\d:00/,"")).diff(@["USSD Notification"]?.date) hoursFromNotificationToCompleteHousehold: => Math.floor(moment.duration(@timeFromSMSToCompleteHousehold()).asHours()) daysFromSMSToCompleteHousehold: => if @householdComplete() and @["USSD Notification"]? moment.duration(@timeFromSMSToCompleteHousehold()).asDays() odkClassification: => if @["ODK 2017-2019"] switch @["ODK 2017-2019"]["case_classification:case_category"] when 1 then "Imported" when 2,3 then "Indigenous" when 4 then "Induced" when 5 then "Relapsing" classificationsWithPositiveIndividualObjects: => for positiveIndividual in @positiveIndividualObjects() { classification: positiveIndividual.classification() positiveIndividual: positiveIndividual } classificationsBy: (property) => (for data in @classificationsWithPositiveIndividualObjects() "#{data.positiveIndividual.data[property]}: #{data.classification}" ).join(", ") classificationsByFunction: (functionName) => (for data in @classificationsWithPositiveIndividualObjects() "#{data.positiveIndividual[functionName]()}: #{data.classification}" ).join(", ") classificationsByHouseholdMemberType: => # IF household member type is undefined it is either: # in progress index case # pre 2019 household member (for data in @classificationsWithPositiveIndividualObjects() if data.positiveIndividual.data.question isnt "Household Members" "Index Case: #{data.classification}" else if data.positiveIndividual.data["HouseholdMemberType"] is undefined "Household Member: #{data.classification}" else "#{data.positiveIndividual.data["HouseholdMemberType"]}: #{data.classification}" ).join(", ") classificationsByDiagnosisDate: => @classificationsByFunction("dateOfPositiveResults") classificationsByIsoYearIsoWeekFociDistrictFociShehia: => (for classificationWithPositiveIndividual in @classificationsWithPositiveIndividualObjects() classification = classificationWithPositiveIndividual.classification positiveIndividual = classificationWithPositiveIndividual.positiveIndividual dateOfPositiveResults = positiveIndividual.dateOfPositiveResults() date = if dateOfPositiveResults moment(dateOfPositiveResults) else # Use index case date if we are missing positiveIndividual's date if dateOfPositiveResults = @dateOfPositiveResults() moment(dateOfPositiveResults) if date? isoYear = date.isoWeekYear() isoWeek = date.isoWeek() fociDistrictShehia = if (focus = positiveIndividual.data["WhereCouldTheMalariaFocusBe"]) focus = focus.trim() if focus is "Patient Shehia" [@district(), @shehia()] else if focus is "Other Shehia Within Zanzibar" otherDistrict = positiveIndividual.data["WhichOtherDistrictWithinZanzibar"] otherShehia = positiveIndividual.data["WhichOtherShehiaWithinZanzibar"] shehiaUnit = @shehiaUnit(otherShehia, otherDistrict) [ shehiaUnit?.ancestorAtLevel("DISTRICT")?.name or @district() shehiaUnit?.name or @shehia() ] else [@district(), @shehia()] else if positiveIndividual.data.HouseholdMemberType is "Index Case" and (odkData = @["ODK 2017-2019"]) #TODO waiting to find out which ODK questions were used for this [@district(), @shehia()] else [@district(), @shehia()] [fociDistrict,fociShehia] = fociDistrictShehia "#{isoYear}:#{isoWeek}:#{fociDistrict}:#{fociShehia}:#{classification}" ).join(", ") evidenceForClassifications: => _(for householdMember in @["Household Members"] if householdMember.CaseCategory "#{householdMember.CaseCategory}: #{householdMember.SummarizeEvidenceUsedForClassification}" ).compact().join(", ") concatenateHouseholdMembers: (property) => _(for householdMember in @["Household Members"] if householdMember.CaseCategory "#{householdMember.CaseCategory}: #{householdMember[property]}" ).compact().join(", ") occupations: => @concatenateHouseholdMembers("Occupation") numbersSentTo: => @["USSD Notification"]?.numbersSentTo?.join(", ") # Data properties above # # ------------- # createOrUpdateOnDhis2: (options = {}) => options.malariaCase = @ Coconut.dhis2.createOrUpdateMalariaCase(options) spreadsheetRow: (question) => console.error "Must call loadSpreadsheetHeader at least once before calling spreadsheetRow" unless Coconut.spreadsheetHeader? spreadsheetRowObjectForResult = (fields,result) -> if result? _(fields).map (field) => if result[field]? if _.contains(Coconut.identifyingAttributes, field) return b64_sha1(result[field]) else return result[field] else return "" else return null if question is "Household Members" _(@[question]).map (householdMemberResult) -> spreadsheetRowObjectForResult(Coconut.spreadsheetHeader[question], householdMemberResult) else spreadsheetRowObjectForResult(Coconut.spreadsheetHeader[question], @[question]) spreadsheetRowString: (question) => if question is "Household Members" _(@spreadsheetRow(question)).map (householdMembersRows) -> result = _(householdMembersRows).map (data) -> "\"#{data}\"" .join(",") result += "--EOR--" if result isnt "" .join("") else result = _(@spreadsheetRow(question)).map (data) -> "\"#{data}\"" .join(",") result += "--EOR--" if result isnt "" summaryResult: (property,options) => priorityOrder = options?.priorityOrder or [ "Household" "Facility" "Case Notification" "USSD Notification" ] if property.match(/:/) propertyName = property priorityOrder = [property.split(/: */)[0]] # If prependQuestion then we only want to search within that question priorityOrder = [options.prependQuestion] if options?.prependQuestion # Make the labels be human readable by looking up the original question text and using that labelMappings = {} _(priorityOrder).each (question) -> return if question is "USSD Notification" labelMappings[question] = Coconut.questions.findWhere({_id:question}).safeLabelsToLabelsMappings() # Looks through the results in the prioritized order for a match findPrioritizedProperty = (propertyNames=[property]) => result = null _(propertyNames).each (propertyName) => return if result _(priorityOrder).each (question) => return if result return unless @[question]? if @[question][propertyName]? result = @[question][propertyName] property = labelMappings[question][propertyName] if labelMappings[question] and labelMappings[question][propertyName] return result result = null result = @[options.functionName]() if options?.functionName result = @[property]() if result is null and @[property] result = findPrioritizedProperty() if result is null if result is null result = findPrioritizedProperty(options.otherPropertyNames) if options?.otherPropertyNames result = JSON.stringify(result) if _(result).isObject() if _(result).isString() result = result?.trim() if options?.propertyName property = options.propertyName else property = titleize(humanize(property)) if options?.prependQuestion property = "#{options.prependQuestion}: #{property}" return {"#{property}": result} summaryCollection: => result = {} _(Case.summaryProperties).each (options, property) => summaryResult = @summaryResult(property, options) # Don't overwrite data if it is already there # Not exactly sure why this is needed, but there seem to be # Null duplicates that replace good data unless result[_(summaryResult).keys()[0]]? result = _(result).extend summaryResult return result summary: -> _(Case.summaryProperties).map (options, property) => @summaryResult(property, options) Case.summaryPropertiesKeys = -> _(Case.summaryProperties).map (options, key) -> if options.propertyName key = options.propertyName else key = <KEY>key).<KEY>replace("Numberof", "Number of") summaryAsCSVString: => _(@summary()).chain().map (summaryItem) -> "\"#{_(summaryItem).values()}\"" .flatten().value().join(",") + "--EOR--<br/>" Case.summaryProperties = { # TODO Document how the different options work # For now just look up at summaryResult function # propertyName is used to change the column name at the top of the CSV # otherPropertyNames is an array of other values to try and check # Case Notification MalariaCaseID: propertyName: "Malaria Case ID" IndexCaseDiagnosisDate: propertyName: "Index Case Diagnosis Date" IndexCaseDiagnosisDateIsoWeek: propertyName: "Index Case Diagnosis Date ISO Week" IndexCaseDiagnosisDateAndTime: propertyName: "Index Case Diagnosis Date And Time" classificationsByHouseholdMemberType: {} classificationsByDiagnosisDate: {} classificationsByIsoYearIsoWeekFociDistrictFociShehia: {} evidenceForClassifications: {} reasonForLostToFollowup: {} namesOfAdministrativeLevels: {} island: {} district: {} facility: {} facilityType: {} facilityDistrict: propertyName: "District of Facility" shehia: {} shehiaFromGPS: {} isShehiaValid: {} highRiskShehia: {} village: propertyName: "Village" villageFromGPS: {} IndexCasePatientName: propertyName: "Patient Name" ageInYears: {} Sex: {} isUnder5: propertyName: "Is Index Case Under 5" SMSSent: propertyName: "SMS Sent to DMSO" hasCaseNotification: {} numbersSentTo: {} source: {} source_phone: {} type: {} lastQuestionCompleted: {} hasCompleteFacility: {} notCompleteFacilityAfter24Hours: propertyName: "Not Complete Facility After 24 Hours" notFollowedUpAfter48Hours: propertyName: "Not Followed Up After 48 Hours" notFollowedUpAfterXHours: propertyName: "Not Followed Up After X Hours" followedUpWithin48Hours: propertyName: "Followed Up Within 48 Hours" completeHouseholdVisit: propertyName: "Complete Household Visit" CompleteHouseholdVisit: propertyName: "Complete Household Visit" numberHouseholdMembersTestedAndUntested: {} numberHouseholdMembersTested: {} NumberPositiveIndividualsAtIndexHousehold: {} NumberHouseholdOrNeighborMembers: {} NumberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholds: {} NumberHouseholdOrNeighborMembersTested: {} NumberPositiveIndividualsIncludingIndex: {} NumberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholdsUnder5: propertyName: "Number Positive Cases At Index Household And Neighbor Households Under 5" NumberSuspectedImportedCasesIncludingHouseholdMembers: {} MassScreenCase: {} CaseIdForOtherHouseholdMemberThatTestedPositiveAtAHealthFacility: propertyName: "Case ID for Other Household Member That Tested Positive at a Health Facility" CommentRemarks: {} ContactMobilePatientRelative: {} HasSomeoneFromTheSameHouseholdRecentlyTestedPositiveAtAHealthFacility: propertyName: "Has Someone From the Same Household Recently Tested Positive at a Health Facility" HeadOfHouseholdName: {} ParasiteSpecies: {} ReferenceInOpdRegister: propertyName: "Reference In OPD Register" TreatmentGiven: {} #Household CouponNumbers: {} FollowupNeighbors: {} HaveYouGivenCouponsForNets: {} HeadOfHouseholdName: {} HouseholdLocationAccuracy: propertyName: "Household Location - Accuracy" functionName: "householdLocationAccuracy" HouseholdLocationAltitude: propertyName: "Household Location - Altitude" HouseholdLocationAltitudeAccuracy: propertyName: "Household Location - Altitude Accuracy" HouseholdLocationDescription: propertyName: "Household Location - Description" HouseholdLocationHeading: propertyName: "Household Location - Heading" HouseholdLocationLatitude: propertyName: "Household Location - Latitude" functionName: "householdLocationLatitude" HouseholdLocationLongitude: propertyName: "Household Location - Longitude" functionName: "householdLocationLongitude" HouseholdLocationTimestamp: propertyName: "Household Location - Timestamp" IndexCaseIfPatientIsFemale1545YearsOfAgeIsSheIsPregant: propertyName: "Is Index Case Pregnant" IndexCasePatient: {} IndexCasePatientSCurrentStatus: propertyName: "Index Case Patient's Current Status" IndexCasePatientSTreatmentStatus: propertyName: "Index Case Patient's Treatment Status" IndexCaseSleptUnderLlinLastNight: propertyName: "Index Case Slept Under LLIN Last Night" IndexCaseDiagnosisDate: {} LastDateOfIrs: propertyName: "Last Date Of IRS" NumberOfHouseholdMembersTreatedForMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" NumberOfHouseholdMembersWithFeverOrHistoryOfFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" NumberOfLlin: propertyName: "Number Of LLIN" NumberOfSleepingPlacesBedsMattresses: propertyName: "Number of Sleeping Places (Beds/Mattresses)" NumberOfOtherHouseholdsWithin50StepsOfIndexCaseHousehold: propertyName: "Number of Other Households Within 50 Steps of Index Case Household" ReasonForVisitingHousehold: {} ShehaMjumbe: propertyName: "<NAME>" TotalNumberOfResidentsInTheHousehold: {} DaysFromCaseNotificationToCompleteFacility: {} DaysFromSmsToCompleteHousehold: propertyName: "Days between SMS Sent to DMSO to Having Complete Household" DaysBetweenPositiveResultAndNotificationFromFacility: {} LessThanOneDayBetweenPositiveResultAndNotificationFromFacility: {} OneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: {} TwoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: {} MoreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: {} DaysBetweenPositiveResultAndCompleteHousehold: {} LessThanOneDayBetweenPositiveResultAndCompleteHousehold: {} OneToTwoDaysBetweenPositiveResultAndCompleteHousehold: {} TwoToThreeDaysBetweenPositiveResultAndCompleteHousehold: {} MoreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: {} "USSD Notification: Created At": otherPropertyNames: ["createdAt"] "USSD Notification: Date": otherPropertyNames: ["date"] "USSD Notification: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "USSD Notification: User": otherPropertyNames: ["user"] "Case Notification: Created At": otherPropertyNames: ["createdAt"] "Case Notification: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Case Notification: Saved By": otherPropertyNames: ["savedBy"] "Facility: Created At": otherPropertyNames: ["createdAt"] "Facility: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Facility: Saved By": otherPropertyNames: ["savedBy"] "Facility: User": otherPropertyNames: ["user"] "Household: Created At": otherPropertyNames: ["createdAt"] "Household: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Household: Saved By": otherPropertyNames: ["savedBy"] "Household: User": otherPropertyNames: ["user"] ## Old naming HeadofHouseholdName: propertyName: "Head Of Household <NAME>" ContactMobilepatientrelative: propertyName: "Contact Mobile Patient Relative" IfYESlistALLplacestravelled: propertyName: "All Places Traveled to in Past Month" CaseIDforotherhouseholdmemberthattestedpositiveatahealthfacility: propertyName: "CaseID For Other Household Member That Tested Positive at a Health Facility" TravelledOvernightinpastmonth: propertyName: "Travelled Overnight in Past Month" Hassomeonefromthesamehouseholdrecentlytestedpositiveatahealthfacility: propertyName: "Has Someone From The Same Household Recently Tested Positive at a Health Facility" Reasonforvisitinghousehold: propertyName: "Reason For Visiting Household" Ifyeslistallplacestravelled: propertyName: "If Yes List All Places Travelled" Fevercurrentlyorinthelasttwoweeks: propertyName: "Fever Currently Or In The Last Two Weeks?" SleptunderLLINlastnight: propertyName: "Slept Under LLIN Last Night?" OvernightTravelinpastmonth: propertyName: "Overnight Travel in Past Month" ResidentofShehia: propertyName: "Resident of Shehia" TotalNumberofResidentsintheHousehold: propertyName: "Total Number of Residents in the Household" NumberofLLIN: propertyName: "Number of LLIN" NumberofSleepingPlacesbedsmattresses: propertyName: "Number of Sleeping Places (Beds/Mattresses)" NumberofHouseholdMemberswithFeverorHistoryofFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" NumberofHouseholdMembersTreatedforMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" LastdateofIRS: propertyName: "Last Date of IRS" Haveyougivencouponsfornets: propertyName: "Have you given coupon(s) for nets?" IndexcaseIfpatientisfemale1545yearsofageissheispregant: propertyName: "Index Case: If Patient is Female 15-45 Years of Age, Is She Pregnant?" IndexcasePatientscurrentstatus: propertyName: "Index case: Patient's current status" IndexcasePatientstreatmentstatus: propertyName: "Index case: Patient's treatment status" indexCasePatientName: propertyName: "Patient Name" IndexcasePatient: propertyName: "Index Case Patient" IndexcaseSleptunderLLINlastnight: propertyName: "Index case: Slept under LLIN last night?" IndexcaseOvernightTraveloutsideofZanzibarinthepastyear: propertyName: "Index Case Overnight Travel Outside of Zanzibar in the Past Year" IndexcaseOvernightTravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "Index Case Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar07daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 0-7 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar814daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 8-14 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar1521daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 15-21 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar2242daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 22-42 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar43365daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 43-365 Days Before Positive Test Result" ListalllocationsofovernighttravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "All Locations Of Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" daysBetweenPositiveResultAndNotificationFromFacility: {} estimatedHoursBetweenPositiveResultAndNotificationFromFacility: {} daysFromCaseNotificationToCompleteFacility: propertyName: "Days From Case Notification To Complete Facility" daysFromSMSToCompleteHousehold: propertyName: "Days between SMS Sent to DMSO to Having Complete Household" "HouseholdLocation-description": propertyName: "Household Location - Description" "HouseholdLocation-latitude": propertyName: "Household Location - Latitude" functionName: "householdLocationLatitude" "HouseholdLocation-longitude": propertyName: "Household Location - Longitude" functionName: "householdLocationLongitude" "HouseholdLocation-accuracy": propertyName: "Household Location - Accuracy" functionName: "householdLocationAccuracy" "HouseholdLocation-altitude": propertyName: "Household Location - Altitude" "HouseholdLocation-altitudeAccuracy": propertyName: "Household Location - Altitude Accuracy" "HouseholdLocation-timestamp": propertyName: "Household Location - Timestamp" travelLocationName: propertyName: "Travel Location Name" OvernightTravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" OvernightTraveloutsideofZanzibarinthepastyear: propertyName: "Overnight Travel Outside of Zanzibar In The Past Year" ReferredtoHealthFacility: propertyName: "Referred to Health Facility" hasCompleteFacility: propertyName: "Has Complete Facility" notCompleteFacilityAfter24Hours: propertyName: "Not Complete Facility After 24 Hours" notFollowedUpAfter48Hours: propertyName: "Not Followed Up After 48 Hours" followedUpWithin48Hours: propertyName: "Followed Up Within 48Hours" completeHouseholdVisit: propertyName: "Complete Household Visit" numberPositiveIndividualsExcludingIndex: propertyName: "Number Positive Individuals At Household Excluding Index" numberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholds: propertyName: "Number Positive Cases At Index Household And Neighbor Households" numberPositiveIndividuals: propertyName: "Number Positive Individuals" numberPositiveIndividualsUnder5: propertyName: "Number Positive Individuals Under 5" numberPositiveIndividualsOver5: propertyName: "Number Positive Individuals Over 5" NumberofHouseholdMembersTreatedforMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" NumberofHouseholdMemberswithFeverorHistoryofFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" massScreenCase: propertyName: "Mass Screen Case" TotalNumberofResidentsintheHousehold: propertyName: "Total Number Of Residents In The Household" lessThanOneDayBetweenPositiveResultAndNotificationFromFacility: propertyName: "Less Than One Day Between Positive Result And Notification From Facility" oneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "One To Two Days Between Positive Result And Notification From Facility" twoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "Two To Three Days Between Positive Result And Notification From Facility" moreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "More Than Three Days Between Positive Result And Notification From Facility" daysBetweenPositiveResultAndCompleteHousehold: propertyName: "Days Between Positive Result And Complete Household" lessThanOneDayBetweenPositiveResultAndCompleteHousehold: propertyName: "Less Than One Day Between Positive Result And Complete Household" oneToTwoDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "One To Two Days Between Positive Result And Complete Household" twoToThreeDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "Two To Three Days Between Positive Result And Complete Household" moreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "More Than Three Days Between Positive Result And Complete Household" occupations: {} dhis2CasesByTypeOfDetection: propertyName: "DHIS2 Cases by Type of Detection" dhis2CasesByClassification: propertyName: "DHIS2 Cases by Classification" dhis2CasesByAge: propertyName: "DHIS2 Cases by Age" dhis2CasesByGender: propertyName: "DHIS2 Cases by Gender" allUserNamesString: propertyName: "<NAME>aria Surveillance Officers" wasTransferred: {} } dateOfMalariaResultFromIndividual: (positiveIndividual) => # First try and get the individuals' date, then the createdAt time (pre-2019) if all fails just use the date for the case or the date that the notification was made date = positiveIndividual.DateOfPositiveResults or positiveIndividual.createdAt or @dateOfPositiveResults() or positiveIndividual.date moment(date).format("YYYY-MM-DD") dhis2CasesByTypeOfDetection: => result = {} for positiveIndividual in @positiveIndividualsIndexCasesOnly() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= { "Passive": 0 "Active": 0 } result[date][shehia]["Passive"] += 1 for positiveIndividual in @positiveIndividualsExcludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= { "Passive": 0 "Active": 0 } result[date][shehia]["Active"] += 1 result dhis2CasesByClassification: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= {} result[date][shehia][positiveIndividual.CaseCategory or "Unclassified"] or= 0 result[date][shehia][positiveIndividual.CaseCategory or "Unclassified"] += 1 result dhis2CasesByAge: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() age = @ageInYears(positiveIndividual.Age, positiveIndividual.AgeInYearsMonthsDays) ageRange = if age? switch when age < 5 then "<5 yrs" when age < 15 then "5<15 yrs" when age < 25 then "15<25 yrs" when age >= 25 then ">25 yrs" else "Unknown" else "Unknown" date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= {} result[date][shehia][ageRange] or= 0 result[date][shehia][ageRange] += 1 result dhis2CasesByGender: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia gender = positiveIndividual.Sex if gender isnt "Male" or gender isnt "Female" then gender = "Unknown" result[date] or= {} result[date][shehia] or= {} result[date][shehia][gender] or=0 result[date][shehia][gender] += 1 result saveAndAddResultToCase: (result) => if @[result.question]? console.error "#{result.question} already exists for:" console.error @ return resultQuestion = result.question Coconut.database.put result .then (result) => console.log "saved:" console.log result @questions.push result.question @[result.question] = result Coconut.headerView.update() Coconut.showNotification( "#{resultQuestion} record created") .catch (error) -> console.error error createNextResult: => @fetch error: -> console.error error success: => if @["Household Members"] and @["Household Members"].length > 0 console.log "Household Members exists, no result created" # Don't create anything else if @Household?.complete console.log "Creating Household members and neighbor households if necessary" @createHouseholdMembers() @createNeighborHouseholds() else if @Facility?.complete console.log "Creating Household" @createHousehold() else if @["Case Notification"]?.complete console.log "Creating Facility" @createFacility() _.delay(Coconut.menuView.render, 500) createFacility: => @saveAndAddResultToCase _id: "result-case-#{@caseID}-Facility-#{radix64.encodeInt(moment().format('x'))}-#{Coconut.instanceId}" question: "Facility" MalariaCaseID: @caseID DistrictForFacility: @facilityDistrict() FacilityName: @facility() DistrictForShehia: @shehiaUnit().ancestorAtLevel("DISTRICT")?.name Shehia: @shehia() collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") createHousehold: => @saveAndAddResultToCase _id: "result-case-#{@caseID}-Household-#{radix64.encodeInt(moment().format('x'))}-#{Coconut.instanceId}" question: "Household" Reasonforvisitinghousehold: "Index Case Household" MalariaCaseID: @caseID HeadOfHouseholdName: @Facility.HeadOfHouseholdName District: @district() Shehia: @shehia() Village: @Facility.Village ShehaMjumbe: @Facility.ShehaMjumbe ContactMobilePatientRelative: @Facility.ContactMobilePatientRelative collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") createHouseholdMembers: => unless _(@questions).contains 'Household Members' _(@Household.TotalNumberOfResidentsInTheHousehold).times (index) => result = { _id: "result-case-#{@caseID}-Household-Members-#{radix64.encodeInt(moment().format('x'))}-#{radix64.encodeInt(Math.round(Math.random()*100000))}-#{Coconut.instanceId}" # There's a chance moment will be the same so add some randomness question: "Household Members" MalariaCaseID: @caseID HeadOfHouseholdName: @Household.HeadOfHouseholdName collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") } if index is 0 _(result).extend HouseholdMemberType: "Index Case" FirstName: @Facility?.FirstName LastName: @Facility?.LastName DateOfPositiveResults: @Facility?.DateOfPositiveResults DateAndTimeOfPositiveResults: @Facility?.DateAndTimeOfPositiveResults Sex: @Facility?.Sex Age: @Facility?.Age AgeInYearsMonthsDays: @Facility?.AgeInYearsMonthsDays MalariaMrdtTestResults: @Facility?.MalariaMrdtTestResults MalariaTestPerformed: @Facility?.MalariaTestPerformed Coconut.database.put result .then => @questions.push result.question @[result.question] = [] unless @[result.question] @[result.question].push result .catch (error) -> console.error error Coconut.headerView.update() Coconut.showNotification( "Household member record(s) created") createNeighborHouseholds: => # If there is more than one Household for this case, then Neighbor households must already have been created unless (_(@questions).filter (question) -> question is 'Household').length is 1 _(@Household.NumberOfOtherHouseholdsWithin50StepsOfIndexCaseHousehold).times => result = { _id: "result-case-#{@caseID}-Household-#{radix64.encodeInt(moment().format('x'))}-#{radix64.encodeInt(Math.round(Math.random()*100000))}-#{Coconut.instanceId}" # There's a chance moment will be the same so add some randomness ReasonForVisitingHousehold: "Index Case Neighbors" question: "Household" MalariaCaseID: @result.get "MalariaCaseID" Shehia: @result.get "Shehia" Village: @result.get "Village" ShehaMjumbe: @result.get "ShehaMjumbe" collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") } Coconut.database.put result .then => Coconut.headerView.update() .catch (error) -> console.error error Coconut.showNotification( "Neighbor Household created") wasTransferred: => @transferData().length > 0 transferData: => transferData = [] for question in @questions if @[question].transferred data = @[question].transferred data["question"] = question transferData.push data transferData Case.resetSpreadsheetForAllCases = => Coconut.database.get "CaseSpreadsheetData" .then (caseSpreadsheetData) -> Case.updateCaseSpreadsheetDocs(0,caseSpreadsheetData) .catch (error) -> console.error error Case.loadSpreadsheetHeader = (options) -> if Coconut.spreadsheetHeader options.success() else Coconut.database.get "spreadsheet_header" .catch (error) -> console.error error .then (result) -> Coconut.spreadsheetHeader = result.fields options.success() Case.updateCaseSpreadsheetDocs = (options) -> # defaults used for first run caseSpreadsheetData = {_id: "CaseSpreadsheetData" } changeSequence = 0 updateCaseSpreadsheetDocs = (changeSequence, caseSpreadsheetData) -> Case.updateCaseSpreadsheetDocsSince changeSequence: changeSequence error: (error) -> console.log "Error updating CaseSpreadsheetData:" console.log error options.error?() success: (numberCasesChanged,lastChangeSequenceProcessed) -> console.log "Updated CaseSpreadsheetData" caseSpreadsheetData.lastChangeSequenceProcessed = lastChangeSequenceProcessed console.log caseSpreadsheetData Coconut.database.put caseSpreadsheetData .catch (error) -> console.error error .then -> console.log numberCasesChanged if numberCasesChanged > 0 Case.updateCaseSpreadsheetDocs(options) #recurse else options?.success?() Coconut.database.get "CaseSpreadsheetData" .catch (error) -> console.log "Couldn't find 'CaseSpreadsheetData' using defaults: changeSequence: #{changeSequence}" updateCaseSpreadsheetDocs(changeSequence,caseSpreadsheetData) .then (result) -> caseSpreadsheetData = result changeSequence = result.lastChangeSequenceProcessed updateCaseSpreadsheetDocs(changeSequence,caseSpreadsheetData) Case.updateCaseSpreadsheetDocsSince = (options) -> Case.loadSpreadsheetHeader success: -> $.ajax url: "/#{Coconut.config.database_name()}/_changes" dataType: "json" data: since: options.changeSequence include_docs: true limit: 500 error: (error) => console.log "Error downloading changes after #{options.changeSequence}:" console.log error options.error?(error) success: (changes) => changedCases = _(changes.results).chain().map (change) -> change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question? .compact().uniq().value() lastChangeSequence = changes.results.pop()?.seq Case.updateSpreadsheetForCases caseIDs: changedCases error: (error) -> console.log "Error updating #{changedCases.length} cases, lastChangeSequence: #{lastChangeSequence}" console.log error success: -> console.log "Updated #{changedCases.length} cases, lastChangeSequence: #{lastChangeSequence}" options.success(changedCases.length, lastChangeSequence) Case.updateSpreadsheetForCases = (options) -> docsToSave = [] questions = "USSD Notification,Case Notification,Facility,Household,Household Members".split(",") options.success() if options.caseIDs.length is 0 finished = _.after options.caseIDs.length, -> Coconut.database.bulkDocs docsToSave .catch (error) -> console.error error .then -> options.success() _(options.caseIDs).each (caseID) -> malariaCase = new Case caseID: caseID malariaCase.fetch error: (error) -> console.log error success: -> docId = "spreadsheet_row_#{caseID}" spreadsheet_row_doc = {_id: docId} saveRowDoc = (result) -> spreadsheet_row_doc = result if result? # if the row already exists use the _rev _(questions).each (question) -> spreadsheet_row_doc[question] = malariaCase.spreadsheetRowString(question) spreadsheet_row_doc["Summary"] = malariaCase.summaryAsCSVString() docsToSave.push spreadsheet_row_doc finished() Coconut.database.get docId .catch (error) -> saveRowDoc() .then (result) -> saveRowDoc(result) Case.getCases = (options) -> Coconut.database.query "cases", keys: options.caseIDs include_docs: true .catch (error) -> options?.error(error) .then (result) => cases = _.chain(result.rows) .groupBy (row) => row.key .map (resultsByCaseID) => malariaCase = new Case results: _.pluck resultsByCaseID, "doc" malariaCase .compact() .value() options?.success?(cases) Promise.resolve(cases) # Used on mobile client Case.getCasesSummaryData = (startDate, endDate) => Coconut.database.query "casesWithSummaryData", startDate: startDate endDate: endDate descending: true include_docs: true .catch (error) => console.error JSON.stringify error .then (result) => _(result.rows).chain().map (row) => row.doc.MalariaCaseID ?= row.key # For case docs without MalariaCaseID add it (caseid etc) row.doc .groupBy "MalariaCaseID" .map (resultDocs, malariaCaseID) => new Case caseID: malariaCaseID results: resultDocs .value() Case.getLatestChangeForDatabase = -> new Promise (resolve,reject) => Coconut.database.changes descending: true include_docs: false limit: 1 .on "complete", (mostRecentChange) -> resolve(mostRecentChange.last_seq) .on "error", (error) -> reject error Case.getLatestChangeForCurrentSummaryDataDocs = -> Coconut.reportingDatabase.get "CaseSummaryData" .catch (error) -> console.error "Error while getLatestChangeForCurrentSummaryDataDocs: #{error}" if error.reason is "missing" return Promise.resolve(null) else return Promise.reject("Non-missing error when getLatestChangeForCurrentSummaryDataDocs") .then (caseSummaryData) -> return Promise.resolve(caseSummaryData?.lastChangeSequenceProcessed or null) Case.resetAllCaseSummaryDocs = (options) => # Docs to save designDocs = await Coconut.reportingDatabase.allDocs startkey: "_<KEY>" endkey: <KEY>" include_docs: true .then (result) -> Promise.resolve _(result.rows).map (row) -> doc = row.doc delete doc._rev doc otherDocsToSave = await Coconut.reportingDatabase.allDocs include_docs: true keys: [ "<KEY>" ] .then (result) -> console.log result Promise.resolve( _(result.rows).chain().map (row) -> doc = row.doc delete doc._rev if doc doc .compact().value() ) docsToSave = designDocs.concat(otherDocsToSave) reportingDatabaseNameWithCredentials = Coconut.reportingDatabase.name await Coconut.reportingDatabase.destroy() .catch (error) -> console.error error throw "Error while destroying database" Coconut.reportingDatabase = new PouchDB(reportingDatabaseNameWithCredentials) await Coconut.reportingDatabase.bulkDocs docsToSave try latestChangeForDatabase = await Case.getLatestChangeForDatabase() console.log "Latest change: #{latestChangeForDatabase}" console.log "Retrieving all available case IDs" Coconut.database.query "cases/cases" .then (result) => allCases = _(result.rows).chain().pluck("key").uniq(true).reverse().value() console.log "Updating #{allCases.length} cases" await Case.updateSummaryForCases caseIDs: allCases console.log "Updated: #{allCases.length} cases" Coconut.reportingDatabase.upsert "CaseSummaryData", (doc) => doc.lastChangeSequenceProcessed = latestChangeForDatabase doc catch error console.error Case.updateCaseSummaryDocs = (options) -> latestChangeForDatabase = await Case.getLatestChangeForDatabase() latestChangeForCurrentSummaryDataDocs = await Case.getLatestChangeForCurrentSummaryDataDocs() #latestChangeForCurrentSummaryDataDocs = "3490519-<KEY>" # console.log "latestChangeForDatabase: #{latestChangeForDatabase?.replace(/-.*/, "")}, latestChangeForCurrentSummaryDataDocs: #{latestChangeForCurrentSummaryDataDocs?.replace(/-.*/,"")}" if latestChangeForCurrentSummaryDataDocs numberLatestChangeForDatabase = parseInt(latestChangeForDatabase?.replace(/-.*/,"")) numberLatestChangeForCurrentSummaryDataDocs = parseInt(latestChangeForCurrentSummaryDataDocs?.replace(/-.*/,"")) if numberLatestChangeForDatabase - numberLatestChangeForCurrentSummaryDataDocs > 50000 console.log "Large number of changes, so just resetting since this is more efficient that reviewing every change." return Case.resetAllCaseSummaryDocs() unless latestChangeForCurrentSummaryDataDocs console.log "No recorded change for current summary data docs, so resetting" Case.resetAllCaseSummaryDocs() else #console.log "Getting changes since #{latestChangeForCurrentSummaryDataDocs.replace(/-.*/, "")}" # Get list of cases changed since latestChangeForCurrentSummaryDataDocs Coconut.database.changes since: latestChangeForCurrentSummaryDataDocs include_docs: true filter: "_view" view: "cases/cases" .then (result) => return if result.results.length is 0 #console.log "Found changes, now plucking case ids" changedCases = _(result.results).chain().map (change) -> change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question? .compact().uniq().value() #console.log "Changed cases: #{_(changedCases).length}" await Case.updateSummaryForCases caseIDs: changedCases console.log "Updated: #{changedCases.length} cases" Coconut.reportingDatabase.upsert "CaseSummaryData", (doc) => doc.lastChangeSequenceProcessed = latestChangeForDatabase doc .catch (error) => console.error error .then => console.log "CaseSummaryData updated through sequence: #{latestChangeForDatabase}" Case.updateSummaryForCases = (options) => new Promise (resolve, reject) => return resolve() if options.caseIDs.length is 0 numberOfCasesToProcess = options.caseIDs.length numberOfCasesProcessed = 0 numberOfCasesToProcessPerIteration = 100 while options.caseIDs.length > 0 caseIDs = options.caseIDs.splice(0,numberOfCasesToProcessPerIteration) # remove 100 caseids cases = await Case.getCases caseIDs: caseIDs docsToSave = [] for malariaCase in cases caseID = malariaCase.caseID docId = "case_summary_#{caseID}" currentCaseSummaryDoc = null try currentCaseSummaryDoc = await Coconut.reportingDatabase.get(docId) catch # Ignore if there is no document try updatedCaseSummaryDoc = malariaCase.summaryCollection() catch error console.error error updatedCaseSummaryDoc["_id"] = docId updatedCaseSummaryDoc._rev = currentCaseSummaryDoc._rev if currentCaseSummaryDoc? docsToSave.push updatedCaseSummaryDoc try await Coconut.reportingDatabase.bulkDocs(docsToSave) catch error console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}" console.error error numberOfCasesProcessed += caseIDs.length console.log "#{numberOfCasesProcessed}/#{numberOfCasesToProcess} #{Math.floor(numberOfCasesProcessed/numberOfCasesToProcess*100)}% (last ID: #{caseIDs.pop()})" resolve() ### I think this can be removed Case.getCasesByCaseIds = (options) -> Coconut.database.query "cases", keys: options.caseIDs include_docs: true .catch (error) -> console.error error .then (result) => groupedResults = _.chain(result.rows) .groupBy (row) => row.key .map (resultsByCaseID) => new Case results: _.pluck resultsByCaseID, "doc" .compact() .value() options.success groupedResults ### Case.createCaseView = (options) -> @case = options.case tables = [ "Summary" "USSD Notification" "Case Notification" "Facility" "Household" "Household Members" ] @mappings = { createdAt: "Created At" lastModifiedAt: "Last Modified At" question: "Question" user: "User" complete: "Complete" savedBy: "Saved By" } #hack to rename Question name in Case view report caseQuestions = @case.Questions().replace("Case Notification", "Case Notification Received").replace("USSD Notification","Case Notification Sent") Coconut.caseview = " <h5>Case ID: #{@case.MalariaCaseID()}</h5><button id='closeDialog' class='mdl-button mdl-js-button mdl-button--icon mdl-button--colored f-right'><i class='mdi mdi-close-circle mdi-24px'></i></button> <h6>Last Modified: #{@case.LastModifiedAt()}</h6> <h6>Questions: #{caseQuestions}</h6> " # USSD Notification doesn't have a mapping finished = _.after tables.length, => Coconut.caseview += _.map(tables, (tableType) => if (tableType is "Summary") @createObjectTable(tableType,@case.summaryCollection()) else if @case[tableType]? if tableType is "Household Members" _.map(@case[tableType], (householdMember) => @createObjectTable(tableType,householdMember) ).join("") else @createObjectTable(tableType,@case[tableType]) ).join("") options?.success() return false _(tables).each (question) => if question != "USSD Notification" question = new Question(id: question) question.fetch success: => _.extend(@mappings, question.safeLabelsToLabelsMappings()) finished() return false Case.createObjectTable = (name,object) -> #Hack to replace title to differ from Questions title name = "Case Notification Received" if name == 'Case Notification' name = "Case Notification Sent" if name == 'USSD Notification' " <h4 id=#{object._id}>#{name} <!-- <small><a href='#edit/result/#{object._id}'>Edit</a></small> --> </h4> <table class='mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp caseTable'> <thead> <tr> <th class='mdl-data-table__cell--non-numeric width65pct'>Field</th> <th class='mdl-data-table__cell--non-numeric'>Value</th> </tr> </thead> <tbody> #{ labels = CONST.Labels _.map(object, (value, field) => if !(Coconut.currentUser.isAdmin()) if (_.indexOf(['name','Name','FirstName','MiddleName','LastName','HeadOfHouseholdName','ContactMobilePatientRelative'],field) != -1) value = "************" return if "#{field}".match(/_id|_rev|collection/) " <tr> <td class='mdl-data-table__cell--non-numeric'> #{ @mappings[field] or labels[field] or field } </td> <td class='mdl-data-table__cell--non-numeric'>#{value}</td> </tr> " ).join("") } </tbody> </table> " Case.setup = => new Promise (resolve) => for docId in ["shehias_high_risk","shehias_received_irs"] await Coconut.database.get docId .catch (error) -> console.error JSON.stringify error .then (result) -> Coconut[docId] = result Promise.resolve() designDocs = { cases: (doc) -> emit(doc.MalariaCaseID, null) if doc.MalariaCaseID emit(doc.caseid, null) if doc.caseid casesWithSummaryData: (doc) -> if doc.MalariaCaseID date = doc.DateofPositiveResults or doc.lastModifiedAt match = date.match(/^(\d\d).(\d\d).(2\d\d\d)/) if match? date = "#{match[3]}-#{match[2]}-#{match[1]}" if doc.transferred? lastTransfer = doc.transferred[doc.transferred.length-1] if date.match(/^2\d\d\d\-\d\d-\d\d/) emit date, [doc.MalariaCaseID,doc.question,doc.complete,lastTransfer] if doc.caseid if document.transferred? lastTransfer = doc.transferred[doc.transferred.length-1] if doc.date.match(/^2\d\d\d\-\d\d-\d\d/) emit doc.date, [doc.caseid, "Facility Notification", null, lastTransfer] } for name, designDocFunction of designDocs designDoc = Utils.createDesignDoc name, designDocFunction await Coconut.database.upsert designDoc._id, (existingDoc) => return false if _(designDoc.views).isEqual(existingDoc?.views) console.log "Creating Case view: #{name}" designDoc .catch (error) => console.error error resolve() module.exports = Case
true
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ moment = require 'moment' Dhis2 = require './Dhis2' CONST = require "../Constants" humanize = require 'underscore.string/humanize' titleize = require 'underscore.string/titleize' PouchDB = require 'pouchdb-core' radix64 = require('radix-64')() HouseholdMember = require './HouseholdMember' Question = require './Question' Individual = require './Individual' TertiaryIndex = require './TertiaryIndex' class Case constructor: (options) -> @caseID = options?.caseID @loadFromResultDocs(options.results) if options?.results loadFromResultDocs: (resultDocs) -> @caseResults = resultDocs @questions = [] this["Household Members"] = [] this["Neighbor Households"] = [] userRequiresDeidentification = (Coconut.currentUser?.hasRole("reports") or Coconut.currentUser is null) and not Coconut.currentUser?.hasRole("admin") _.each resultDocs, (resultDoc) => resultDoc = resultDoc.toJSON() if resultDoc.toJSON? if userRequiresDeidentification _.each resultDoc, (value,key) -> resultDoc[key] = b64_sha1(value) if value? and _.contains(Coconut.identifyingAttributes, key) if resultDoc.question @caseID ?= resultDoc["MalariaCaseID"].trim() @questions.push resultDoc.question if resultDoc.question is "Household Members" this["Household Members"].push resultDoc householdMember = new HouseholdMember() householdMember.load(resultDoc) (@householdMembers or= []).push(householdMember) else if resultDoc.question is "Household" and resultDoc.Reasonforvisitinghousehold is "Index Case Neighbors" this["Neighbor Households"].push resultDoc else if resultDoc.question is "Facility" dateOfPositiveResults = resultDoc.DateOfPositiveResults if dateOfPositiveResults? dayMonthYearMatch = dateOfPositiveResults.match(/^(\d\d).(\d\d).(20\d\d)/) if dayMonthYearMatch [day,month,year] = dayMonthYearMatch[1..] if day > 31 or month > 12 console.error "Invalid DateOfPositiveResults: #{this}" else resultDoc.DateOfPositiveResults = "#{year}-#{month}-#{day}" if this[resultDoc.question]? # Duplicate if (this[resultDoc.question].complete is "true" or this[resultDoc.question].complete is true) and (resultDoc.complete isnt "true" or resultDoc.complete isnt true) #console.warn "Using the result marked as complete" return # Use the version already loaded which is marked as complete else if this[resultDoc.question].complete and resultDoc.complete console.warn "Duplicate complete entries for case: #{@caseID}" this[resultDoc.question] = resultDoc else @caseID ?= resultDoc["caseid"].trim() @questions.push "USSD Notification" this["USSD Notification"] = resultDoc fetch: (options) => unless @caseID return Promise.reject "No caseID to fetch data for" Coconut.database.query "cases", key: @caseID include_docs: true .catch (error) -> options?.error() Promise.reject(error) .then (result) => if result.rows.length is 0 options?.error("Could not find any existing data for case #{@caseID}") Promise.reject ("Could not find any existing data for case #{@caseID}") @loadFromResultDocs(_.pluck(result.rows, "doc")) options?.success() Promise.resolve() toJSON: => returnVal = {} _.each @questions, (question) => returnVal[question] = this[question] return returnVal deIdentify: (result) -> flatten: (questions = @questions) -> returnVal = {} _.each questions, (question) => type = question _.each this[question], (value, field) -> if _.isObject value _.each value, (arrayValue, arrayField) -> returnVal["#{question}-#{field}: #{arrayField}"] = arrayValue else returnVal["#{question}:#{field}"] = value returnVal caseId: => @caseID LastModifiedAt: => _.chain(@toJSON()) .map (data, question) -> if _(data).isArray() _(data).pluck("lastModifiedAt") else data?.lastModifiedAt .flatten() .max (lastModifiedAt) -> moment(lastModifiedAt).unix() .value() Questions: -> _.keys(@toJSON()).join(", ") MalariaCaseID: -> @caseID user: -> userId = @.Household?.user || @.Facility?.user || @["Case Notification"]?.user allUserIds: -> users = [] users.push @.Household?.user users.push @.Facility?.user users.push @["Case Notification"]?.user _(users).chain().uniq().compact().value() allUserNames: => for userId in @allUserIds() Coconut.nameByUsername[userId] or "Unknown" allUserNamesString: => @allUserNames()?.join(", ") facility: -> @facilityUnit()?.name or "UNKNOWN" #@["Case Notification"]?.FacilityName.toUpperCase() or @["USSD Notification"]?.hf.toUpperCase() or @["Facility"]?.FacilityName or "UNKNOWN" facilityType: => facilityUnit = @facilityUnit() unless facilityUnit? console.warn "Unknown facility name for: #{@caseID}. Returning UNKNOWN for facilityType." return "UNKNOWN" GeoHierarchy.facilityTypeForFacilityUnit(@facilityUnit()) facilityDhis2OrganisationUnitId: => GeoHierarchy.findFirst(@facility(), "FACILITY")?.id isShehiaValid: => if @validShehia() then true else false validShehia: => @shehiaUnit()?.name ### # Try and find a shehia is in our database if @.Household?.Shehia and GeoHierarchy.validShehia(@.Household.Shehia) return @.Household?.Shehia else if @.Facility?.Shehia and GeoHierarchy.validShehia(@.Facility.Shehia) return @.Facility?.Shehia else if @["Case Notification"]?.Shehia and GeoHierarchy.validShehia(@["Case Notification"]?.Shehia) return @["Case Notification"]?.Shehia else if @["USSD Notification"]?.shehia and GeoHierarchy.validShehia(@["USSD Notification"]?.shehia) return @["USSD Notification"]?.shehia return null ### shehiaUnit: (shehiaName, districtName) => if shehiaName? and GeoHierarchy.validShehia(shehiaName) # Can pass in a shehiaName - useful for positive Individuals with different focal area else shehiaName = null # Priority order to find the best facilityName for name in [@Household?.Shehia, @Facility?.Shehia, @["Case Notification"]?.Shehia, @["USSD Notification"]?.shehia] continue unless name? name = name.trim() if GeoHierarchy.validShehia(name) shehiaName = name break unless shehiaName? # If we have no valid shehia name, then try and use facility return @facilityUnit()?.ancestorAtLevel("SHEHIA") else shehiaUnits = GeoHierarchy.find(shehiaName,"SHEHIA") if shehiaUnits.length is 1 return shehiaUnits[0] else if shehiaUnits.length > 1 # At this point we have a shehia name, but it is not unique, so we can use any data to select the correct one # Shehia names are not unique across Zanzibar, but they are unique per island # We also have region which is a level between district and island. # Strategy: get another sub-island location from the data, then limit the # list of shehias to that same island # * "District" that was passed in (used for focal areas) # Is Shehia in district? # * "District" from Household # Is Shehia in district? # * "District for Shehia" from Case Notification # Is Shehia in district? # * Facility District # Is Shehia in District # * Facility Name # Is Shehia parent of facility # * If REGION for FACILTY unit matches one of the shehia's region # * If ISLAND for FACILTY unit matches one of the shehia's region for district in [districtName, @Household?["District"], @["Case Notification"]?["District for Shehia"], @["Case Notification"]?["District for Facility"], @["USSD Notification"]?.facility_district] continue unless district? district = district.trim() districtUnit = GeoHierarchy.findOneMatchOrUndefined(district, "DISTRICT") if districtUnit? for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("DISTRICT") is districtUnit return shehiaUnit # CHECK THE REGION LEVEL for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("REGION") is districtUnit.ancestorAtLevel("REGION") return shehiaUnit # CHECK THE ISLAND LEVEL for shehiaUnit in shehiaUnits if shehiaUnit.ancestorAtLevel("ISLAND") is districtUnit.ancestorAtLevel("ISLAND") return shehiaUnit # In case we couldn't find a facility district above, try and use the facility unit which comes from the name facilityUnit = @facilityUnit() if facilityUnit? facilityUnitShehia = facilityUnit.ancestorAtLevel("SHEHIA") for shehiaUnit in shehiaUnits if shehiaUnit is facilityUnitShehia return shehiaUnit for level in ["DISTRICT", "REGION", "ISLAND"] facilityUnitAtLevel = facilityUnit.ancestorAtLevel(level) for shehiaUnit in shehiaUnits shehiaUnitAtLevel = shehiaUnit.ancestorAtLevel(level) #console.log "shehiaUnitAtLevel: #{shehiaUnitAtLevel.id}: #{shehiaUnitAtLevel.name}" #console.log "facilityUnitAtLevel: #{facilityUnitAtLevel.id}: #{facilityUnitAtLevel.name}" if shehiaUnitAtLevel is facilityUnitAtLevel return shehiaUnit villageFromGPS: => longitude = @householdLocationLongitude() latitude = @householdLocationLatitude() if longitude? and latitude? GeoHierarchy.villagePropertyFromGPS(longitude, latitude) shehiaUnitFromGPS: => longitude = @householdLocationLongitude() latitude = @householdLocationLatitude() if longitude? and latitude? GeoHierarchy.findByGPS(longitude, latitude, "SHEHIA") shehiaFromGPS: => @shehiaUnitFromGPS()?.name facilityUnit: => facilityName = null # Priority order to find the best facilityName for name in [@Facility?.FacilityName, @["Case Notification"]?.FacilityName, @["USSD Notification"]?["hf"]] continue unless name? name = name.trim() if GeoHierarchy.validFacility(name) facilityName = name break if facilityName facilityUnits = GeoHierarchy.find(facilityName, "HEALTH FACILITIES") if facilityUnits.length is 1 return facilityUnits[0] else if facilityUnits.length is 0 return null else if facilityUnits.length > 1 facilityDistrictName = null for name in [@Facility?.DistrictForFacility, @["Case Notification"]?.DistrictForFacility, @["USSD Notification"]?["facility_district"]] if name? and GeoHierarchy.validDistrict(name) facilityDistrictName = name break if facilityDistrictName? facilityDistrictUnits = GeoHierarchy.find(facilityDistrictName, "DISTRICT") for facilityUnit in facilityUnits for facilityDistrictUnit in facilityDistrictUnits if facilityUnit.ancestorAtLevel("DISTRICT") is facilityDistrictUnit return facilityUnit householdShehiaUnit: => @shehiaUnit() householdShehia: => @householdShehiaUnit()?.name shehia: -> returnVal = @validShehia() return returnVal if returnVal? # If no valid shehia is found, then return whatever was entered (or null) returnVal = @.Household?.Shehia || @.Facility?.Shehia || @["Case Notification"]?.shehia || @["USSD Notification"]?.shehia if @hasCompleteFacility() if @complete() console.warn "Case was followed up to household, but shehia name: #{returnVal} is not a valid shehia. #{@MalariaCaseID()}." else console.warn "Case was followed up to facility, but shehia name: #{returnVal} is not a valid shehia: #{@MalariaCaseID()}." return returnVal village: -> @["Facility"]?.Village facilityDistrict: -> facilityDistrict = @["USSD Notification"]?.facility_district unless facilityDistrict and GeoHierarchy.validDistrict(facilityDistrict) facilityDistrict = @facilityUnit()?.ancestorAtLevel("DISTRICT").name unless facilityDistrict #if @["USSD Notification"]?.facility_district is "WEST" and _(GeoHierarchy.find(@shehia(), "SHEHIA").map( (u) => u.ancestors()[0].name )).include "MAGHARIBI A" # MEEDS doesn't have WEST split # # # WEST got split, but DHIS2 uses A & B, so use shehia to figure out the right one if @["USSD Notification"]?.facility_district is "WEST" if shehia = @validShehia() for shehia in GeoHierarchy.find(shehia, "SHEHIA") if shehia.ancestorAtLevel("DISTRICT").name.match(/MAGHARIBI/) return shehia.ancestorAtLevel("DISTRICT").name else return "MAGHARIBI A" #Check the shehia to see if it is either MAGHARIBI A or MAGHARIBI B console.warn "Could not find a district for USSD notification: #{JSON.stringify @["USSD Notification"]}" return "UNKNOWN" GeoHierarchy.swahiliDistrictName(facilityDistrict) districtUnit: -> districtUnit = @shehiaUnit()?.ancestorAtLevel("DISTRICT") or @facilityUnit()?.ancestorAtLevel("DISTRICT") return districtUnit if districtUnit? for name in [@Facility?.DistrictForFacility, @["Case Notification"]?.DistrictForFacility, @["USSD Notification"]?["facility_district"]] if name? and GeoHierarchy.validDistrict(name) return GeoHierarchy.findOneMatchOrUndefined(name, "DISTRICT") district: => @districtUnit()?.name or "UNKNOWN" islandUnit: => @districtUnit()?.ancestorAtLevel("ISLANDS") island: => @islandUnit()?.name or "UNKNOWN" highRiskShehia: (date) => date = moment().startOf('year').format("YYYY-MM") unless date if Coconut.shehias_high_risk?[date]? _(Coconut.shehias_high_risk[date]).contains @shehia() else false locationBy: (geographicLevel) => return @validShehia() if geographicLevel.match(/shehia/i) district = @district() if district? return district if geographicLevel.match(/district/i) GeoHierarchy.getAncestorAtLevel(district, "DISTRICT", geographicLevel) else console.warn "No district for case: #{@caseID}" # namesOfAdministrativeLevels # Nation, Island, Region, District, Shehia, Facility # Example: #"ZANZIBAR","PEMBA","KUSINI PEMBA","MKOANI","WAMBAA","MWANAMASHUNGI namesOfAdministrativeLevels: () => district = @district() if district districtAncestors = _(GeoHierarchy.findFirst(district, "DISTRICT")?.ancestors()).pluck "name" result = districtAncestors.reverse().concat(district).concat(@shehia()).concat(@facility()) result.join(",") possibleQuestions: -> ["Case Notification", "Facility","Household","Household Members"] questionStatus: => result = {} _.each @possibleQuestions(), (question) => if question is "Household Members" if @["Household Members"].length is 0 result["Household Members"] = false else result["Household Members"] = true for member in @["Household Members"] unless member.complete? and (member.complete is true or member.complete is "true") result["Household Members"] = false else result[question] = (@[question]?.complete is "true" or @[question]?.complete is true) return result lastQuestionCompleted: => questionStatus = @questionStatus() for question in @possibleQuestions().reverse() return question if questionStatus[question] return "None" hasHouseholdMembersWithRepeatedNames: => @repeatedNamesInSameHousehold() isnt null repeatedNamesInSameHousehold: => names = {} for individual in @positiveAndNegativeIndividualObjects() name = individual.name() if name? and name isnt "" names[name] or= 0 names[name] += 1 repeatedNames = [] for name, frequency of names if frequency > 1 repeatedNames.push name if repeatedNames.length > 0 return repeatedNames.join(", ") else return null oneAndOnlyOneIndexCase: => numberOfIndexCases = 0 for individual in @positiveIndividualObjects() if individual.data.HouseholdMemberType is "Index Case" numberOfIndexCases+=1 console.log "numberOfIndexCases: #{numberOfIndexCases}" if numberOfIndexCases isnt 1 return numberOfIndexCases is 1 hasIndexCaseClassified: => @classificationsByHouseholdMemberType().match(/Index Case/) complete: => @questionStatus()["Household Members"] is true status: => if @["Facility"]?["Lost To Followup"] is "Yes" return "Lost To Followup" else if @complete() return "Followed up" else returnVal = "" for question, status of @questionStatus() if status is false returnVal = if question is "Household Members" and not @hasIndexCaseClassified() "Household Members does not have a classified Index Case" else if question is "Household Member" "<a href='##{Coconut.databaseName}/show/results/Household%20Members'>#{question}</a> in Progress" else url = if @[question]?._id "##{Coconut.databaseName}/edit/result/#{@[question]._id}" else "##{Coconut.databaseName}/show/results/#{question}" "<a href='#{url}'>#{question}</a> in Progress" break returnVal hasCompleteFacility: => @.Facility?.complete is "true" or @.Facility?.complete is true notCompleteFacilityAfter24Hours: => @moreThan24HoursSinceFacilityNotifed() and not @hasCompleteFacility() notFollowedUpAfter48Hours: => @moreThan48HoursSinceFacilityNotifed() and not @followedUp() followedUpWithin48Hours: => not @notFollowedUpAfter48Hours() notFollowedUpAfterXHours: => @moreThanXHoursSinceFacilityNotifed() and not @followedUp() followedUpWithinXHours: => not @notFollowedUpAfterXHours() completeHouseholdVisit: => @complete() dateHouseholdVisitCompleted: => if @completeHouseholdVisit() @.Household?.lastModifiedAt or @["Household Members"]?[0]?.lastModifiedAt or @Facility?.lastModifiedAt # When the household has two cases followedUp: => @completeHouseholdVisit() # Includes any kind of travel including only within Zanzibar indexCaseHasTravelHistory: => @.Facility?.TravelledOvernightinpastmonth?.match(/Yes/) or false indexCaseHasNoTravelHistory: => not @indexCaseHasTravelHistory() location: (type) -> # Not sure how this works, since we are using the facility name with a database of shehias #WardHierarchy[type](@toJSON()["Case Notification"]?["FacilityName"]) GeoHierarchy.findOneShehia(@toJSON()["Case Notification"]?["FacilityName"])?[type.toUpperCase()] withinLocation: (location) -> return @location(location.type) is location.name # This is just a count of househhold members not how many are positive # It excludes neighbor households completeIndexCaseHouseholdMembers: => return [] unless @["Household"]? _(@["Household Members"]).filter (householdMember) => # HeadOfHouseholdName used to determine if it is neighbor household (householdMember.HeadofHouseholdName is @["Household"].HeadofHouseholdName or householdMember.HeadOfHouseholdName is @["Household"].HeadOfHouseholdName) and (householdMember.complete is "true" or householdMember.complete is true) hasCompleteIndexCaseHouseholdMembers: => @completeIndexCaseHouseholdMembers().length > 0 # Note that this doesn't include Index - this is unclear function name positiveIndividualsAtIndexHousehold: => console.warn "Function name not clear consider using positiveIndividualsExcludingIndex instead" _(@completeIndexCaseHouseholdMembers()).filter (householdMember) -> householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### numberPositiveIndividualsAtIndexHousehold: => throw "Deprecated since name was confusing about whether index case was included, use numberPositiveIndividualsExcludingIndex" @positiveIndividualsAtIndexHousehold().length ### numberPositiveIndividualsExcludingIndex: => @positiveIndividualsExcludingIndex().length hasAdditionalPositiveIndividualsAtIndexHousehold: => @numberPositiveIndividualsExcludingIndex() > 0 completeNeighborHouseholds: => _(@["Neighbor Households"]).filter (household) => household.complete is "true" or household.complete is true completeNeighborHouseholdMembers: => return [] unless @["Household"]? _(@["Household Members"]).filter (householdMember) => (householdMember.HeadOfHouseholdName isnt @["Household"].HeadOfHouseholdName) and (householdMember.complete is "true" or householdMember.complete is true) hasCompleteNeighborHouseholdMembers: => @completeIndexCaseHouseholdMembers().length > 0 positiveIndividualsAtNeighborHouseholds: -> _(@completeNeighborHouseholdMembers()).filter (householdMember) -> householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### # Handles pre-2019 and post-2019 positiveIndividualsAtIndexHouseholdAndNeighborHouseholds: -> throw "Deprecated" _(@["Household Members"]).filter (householdMember) => householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" or (householdMember.CaseCategory and householdMember.HouseholdMemberType is "Other Household Member") ### positiveIndividualsUnder5: => _(@positiveIndividuals()).filter (householdMemberOrNeighbor) => age = @ageInYears(householdMemberOrNeighbor.Age, householdMemberOrNeighbor.AgeInYearsMonthsDays) age and age < 5 positiveIndividualsOver5: => _(@positiveIndividuals()).filter (householdMemberOrNeighbor) => age = @ageInYears(householdMemberOrNeighbor.Age, householdMemberOrNeighbor.AgeInYearsMonthsDays) age and age >= 5 numberPositiveIndividuals: -> @positiveIndividuals().length numberHouseholdMembers: -> @["Household Members"].length numberHouseholdMembersTestedAndUntested: => numberHouseholdMembersFromHousehold = @["Household"]?["TotalNumberOfResidentsInTheHousehold"] or @["Household"]?["TotalNumberofResidentsintheHousehold"] numberHouseholdMembersWithRecord = @numberHouseholdMembers() # Some cases have more member records than TotalNumberofResidentsintheHousehold so use higher Math.max(numberHouseholdMembersFromHousehold, numberHouseholdMembersWithRecord) numberHouseholdMembersTested: => numberHouseholdMemberRecordsWithTest = _(@["Household Members"]).filter (householdMember) => switch householdMember.MalariaTestResult when "NPF", "PF", "Mixed" return true switch householdMember["MalariaTestPerformed"] when "mRDT", "Microscopy" return true .length # Check if we have pre 2019 data by checking for classifications # If there is no classification then either it was pre-2019 or followup is not done, so we need to add on an additional individual that was tested (index case) classifiedNonIndexCases = _(@["Household Members"]).filter (householdMember) => householdMember.CaseCategory? and householdMember.HouseholdMemberType isnt "Index Case" # If there is at least a case notification then we know the index case was tested if classifiedNonIndexCases.length is 0 numberHouseholdMemberRecordsWithTest+1 else numberHouseholdMemberRecordsWithTest percentOfHouseholdMembersTested: => (@numberHouseholdMembersTested()/@numberHouseholdMembersTestedAndUntested()*100).toFixed(0) updateIndividualIndex: => @tertiaryIndex or= new TertiaryIndex name: "Individual" @tertiaryIndex.updateIndexForCases({caseIDs:[@MalariaCaseID()]}) positiveIndividualObjects: => for positiveIndividual in @positiveIndividuals() new Individual(positiveIndividual, @) positiveIndividuals: => @positiveIndividualsIncludingIndex() #This function is good - don't use completeIndexCaseHouseholdMembers positiveIndividualsIncludingIndex: => positiveIndividualsExcludingIndex = @positiveIndividualsExcludingIndex() positiveIndividualsIndexCasesOnly = @positiveIndividualsIndexCasesOnly() nonIndexHaveCaseCategory = _(positiveIndividualsExcludingIndex).any (positiveIndividual) -> positiveIndividual.CaseCategory? indexHaveCaseCategory = _(positiveIndividualsIndexCasesOnly).any (positiveIndividual) -> positiveIndividual.CaseCategory? # Don't try and find an index case if there are already classified individuals # Probably these just have the wrong Household Member Type results = if nonIndexHaveCaseCategory and not indexHaveCaseCategory positiveIndividualsExcludingIndex else positiveIndividualsIndexCasesOnly?.concat(positiveIndividualsExcludingIndex) for result in results result["Malaria Positive"] = true result positiveAndNegativeIndividuals: => for individual in @positiveIndividuals().concat(@negativeIndividuals()) individual["Date Of Malaria Results"] = @dateOfMalariaResultFromIndividual(individual) individual positiveAndNegativeIndividualObjects: => for individual in @positiveAndNegativeIndividuals() new Individual(individual, @) positiveIndividualsExcludingIndex: => # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedNonIndexIndividuals = _(@["Household Members"]).filter (householdMember) => householdMember.CaseCategory? and householdMember.HouseholdMemberType isnt "Index Case" results = if classifiedNonIndexIndividuals.length > 0 classifiedNonIndexIndividuals else # If there is no classification then there will be no index case in the list of household members (pre 2019 style). This also includes neighbor households. _(@["Household Members"]).filter (householdMember) => householdMember.MalariaTestResult is "PF" or householdMember.MalariaTestResult is "Mixed" for result in results # Make sure result.HouseholdMemberType = "Other Household Member" result positiveIndividualsIndexCasesOnly: => # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedIndexCases = @["Household Members"].filter (householdMember) -> householdMember.CaseCategory isnt null and householdMember.HouseholdMemberType is "Index Case" if classifiedIndexCases.length > 0 classifiedIndexCases else # Case hasn't been followed up yet or pre 2019 data which didn't capture index case as a household member, so use facility data for index and then check for positive household members extraProperties = { MalariaCaseID: @MalariaCaseID() HouseholdMemberType: "Index Case" } if @["Facility"] # Note that if you don't start with an empty object then the first argument gets mutated [_.extend {}, @["Facility"], @["Household"], extraProperties] else if @["USSD Notification"] [_.extend {}, @["USSD Notification"], @["Household"], extraProperties] else [] negativeIndividuals: => # I've reversed the logic of positiveIndividualsExcludingIndex # if we have classification then index is in the household member data # Only positive individuals have a case category e.g. imported, so filter for non null values classifiedIndividuals = [] unclassifiedNonIndexIndividuals = [] _(@["Household Members"]).map (householdMember) => if householdMember.CaseCategory? classifiedIndividuals.push householdMember else if householdMember.HouseholdMemberType isnt "Index Case" # These are the ones we want but only if others are classified unclassifiedNonIndexIndividuals.push householdMember # if we have classification then index is in the household member data # So we can return the unclassified cases which must all be negative results = if classifiedIndividuals.length > 0 unclassifiedNonIndexIndividuals else # If there is no classification then there will be no index case in the list of household members (pre 2019 style). This also includes neighbor households. _(@["Household Members"]).filter (householdMember) => (householdMember.complete is true or householdMember.complete is "true") and householdMember.MalariaTestResult isnt "PF" and householdMember.MalariaTestResult isnt "Mixed" for result in results result["Date Of Malaria Results"] = @dateOfMalariaResultFromIndividual(result) result["Malaria Positive"] = false result numberPositiveIndividuals: => @positiveIndividuals().length numberPositiveIndividualsUnder5: => @positiveIndividualsUnder5().length numberPositiveIndividualsOver5: => @positiveIndividualsOver5().length massScreenCase: => @Household?["Reason for visiting household"]? is "Mass Screen" indexCasePatientName: -> if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) return "#{@["Facility"].FirstName} #{@["Facility"].LastName}" if @["USSD Notification"]? return @["USSD Notification"]?.name if @["Case Notification"]? return @["Case Notification"]?.Name # Not sure why the casing is weird - put this in to support mobile client indexCaseDiagnosisDate: => @IndexCaseDiagnosisDate() IndexCaseDiagnosisDateAndTime: -> # If we don't have the hour/minute of the diagnosis date # Then assume that everyone gets tested at 8am if @["Facility"]?.DateAndTimeOfPositiveResults? return moment(@["Facility"]?.DateAndTimeOfPositiveResults).format("YYYY-MM-DD HH:mm") if @["Facility"]?.DateOfPositiveResults? date = @["Facility"].DateOfPositiveResults momentDate = if date.match(/^20\d\d/) moment(@["Facility"].DateOfPositiveResults) else moment(@["Facility"].DateOfPositiveResults, "DD-MM-YYYY") if momentDate.isValid() return momentDate.set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") if @["USSD Notification"]? return moment(@["USSD Notification"].date).set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") else if @["Case Notification"]? return moment(@["Case Notification"].createdAt).set(hour:0,minute:0).format("YYYY-MM-DD HH:mm") IndexCaseDiagnosisDate: => if indexCaseDiagnosisDateAndTime = @IndexCaseDiagnosisDateAndTime() moment(indexCaseDiagnosisDateAndTime).format("YYYY-MM-DD") IndexCaseDiagnosisDateIsoWeek: => indexCaseDiagnosisDate = @IndexCaseDiagnosisDate() if indexCaseDiagnosisDate moment(indexCaseDiagnosisDate).format("GGGG-WW") householdMembersDiagnosisDates: => @householdMembersDiagnosisDate() householdMembersDiagnosisDate: => returnVal = [] _.each @["Household Members"]?, (member) -> returnVal.push member.lastModifiedAt if member.MalariaTestResult is "PF" or member.MalariaTestResult is "Mixed" ageInYears: (age = @Facility?.Age, ageInMonthsYearsOrDays = (@Facility?.AgeinMonthsOrYears or @Facility?.AgeInYearsMonthsDays)) => return null unless age? and ageInMonthsYearsOrDays? if ageInMonthsYearsOrDays is "Months" age / 12.0 else if ageInMonthsYearsOrDays is "Days" age / 365.0 else age ### return null unless @Facility if @Facility["Age in Months Or Years"]? and @Facility["Age in Months Or Years"] is "Months" @Facility["Age"] / 12.0 else @Facility["Age"] ### isUnder5: => ageInYears = @ageInYears() if ageInYears ageInYears < 5 else null householdLocationLatitude: => parseFloat(@Location?["LocationLatitude"] or @Household?["HouseholdLocationLatitude"] or @Household?["Household Location - Latitude"]) or @Household?["HouseholdLocation-latitude"] householdLocationLongitude: => parseFloat(@Location?["LocationLongitude"] or @Household?["HouseholdLocationLongitude"] or @Household?["Household Location - Longitude"]) or @Household?["HouseholdLocation-longitude"] householdLocationAccuracy: => parseFloat(@Location?["LocationAccuracy"] or @Household?["HouseholdLocationAccuracy"] or @Household?["Household Location - Accuracy"]) resultsAsArray: => _.chain @possibleQuestions() .map (question) => @[question] .flatten() .compact() .value() fetchResults: (options) => results = _.map @resultsAsArray(), (result) => returnVal = new Result() returnVal.id = result._id returnVal count = 0 _.each results, (result) -> result.fetch success: -> count += 1 options.success(results) if count >= results.length return results updateCaseID: (newCaseID) -> @fetchResults success: (results) -> _.each results, (result) -> throw "No MalariaCaseID" unless result.attributes.MalariaCaseID? result.save MalariaCaseID: newCaseID issuesRequiringCleaning: () -> # Case has multiple USSD notifications resultCount = {} questionTypes = "USSD Notification, Case Notification, Facility, Household, Household Members".split(/, /) _.each questionTypes, (questionType) -> resultCount[questionType] = 0 _.each @caseResults, (result) -> resultCount["USSD Notification"]++ if result.caseid? resultCount[result.question]++ if result.question? issues = [] _.each questionTypes[0..3], (questionType) -> issues.push "#{resultCount[questionType]} #{questionType}s" if resultCount[questionType] > 1 issues.push "Not followed up" unless @followedUp() issues.push "Orphaned result" if @caseResults.length is 1 issues.push "Missing case notification" unless @["Case Notification"]? or @["Case Notification"]?.length is 0 return issues allResultsByQuestion: -> returnVal = {} _.each "USSD Notification, Case Notification, Facility, Household".split(/, /), (question) -> returnVal[question] = [] _.each @caseResults, (result) -> if result["question"]? returnVal[result["question"]].push result else if result.hf? returnVal["USSD Notification"].push result return returnVal redundantResults: -> redundantResults = [] _.each @allResultsByQuestion, (results, question) -> console.log _.sort(results, "createdAt") dateOfPositiveResults: => @IndexCaseDiagnosisDate() daysBetweenPositiveResultAndNotificationFromFacility: => dateOfPositiveResults = @dateOfPositiveResults() notificationDate = if @["USSD Notification"]? @["USSD Notification"].date if dateOfPositiveResults? and notificationDate? Math.abs(moment(dateOfPositiveResults).diff(notificationDate, 'days')) estimatedHoursBetweenPositiveResultAndNotificationFromFacility: => dateAndTimeOfPositiveResults = @IndexCaseDiagnosisDateAndTime() notificationDate = @["USSD Notification"]?.date or @["Case Notification"]?.createdAt if dateAndTimeOfPositiveResults? and notificationDate? Math.abs(moment(dateAndTimeOfPositiveResults).diff(notificationDate, 'hours')) lessThanOneDayBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility <= 1 oneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 1 and daysBetweenPositiveResultAndNotificationFromFacility <= 2 twoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 2 and daysBetweenPositiveResultAndNotificationFromFacility <= 3 moreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: => if (daysBetweenPositiveResultAndNotificationFromFacility = @daysBetweenPositiveResultAndNotificationFromFacility())? daysBetweenPositiveResultAndNotificationFromFacility > 3 daysBetweenPositiveResultAndCompleteHousehold: => dateOfPositiveResults = @dateOfPositiveResults() completeHouseholdVisit = @dateHouseholdVisitCompleted() if dateOfPositiveResults and completeHouseholdVisit Math.abs(moment(dateOfPositiveResults).diff(completeHouseholdVisit, 'days')) lessThanOneDayBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold <= 1 oneToTwoDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 1 and daysBetweenPositiveResultAndCompleteHousehold <= 2 twoToThreeDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 2 and daysBetweenPositiveResultAndCompleteHousehold <= 3 moreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: => if (daysBetweenPositiveResultAndCompleteHousehold = @daysBetweenPositiveResultAndCompleteHousehold())? daysBetweenPositiveResultAndCompleteHousehold > 3 timeFacilityNotified: => if @["USSD Notification"]? @["USSD Notification"].date else null timeSinceFacilityNotified: => timeFacilityNotified = @timeFacilityNotified() if timeFacilityNotified? moment().diff(timeFacilityNotified) else null hoursSinceFacilityNotified: => timeSinceFacilityNotified = @timeSinceFacilityNotified() if timeSinceFacilityNotified? moment.duration(timeSinceFacilityNotified).asHours() else null moreThan24HoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > 24 moreThan48HoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > 48 moreThanXHoursSinceFacilityNotifed: => @hoursSinceFacilityNotified() > parseInt(Coconut.config.case_followup) timeFromSMSToCaseNotification: => if @["Case Notification"]? and @["USSD Notification"]? return moment(@["Case Notification"]?.createdAt).diff(@["USSD Notification"]?.date) # Note the replace call to handle a bug that created lastModified entries with timezones timeFromCaseNotificationToCompleteFacility: => if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) and @["Case Notification"]? return moment(@["Facility"].lastModifiedAt.replace(/\+0\d:00/,"")).diff(@["Case Notification"]?.createdAt) daysFromCaseNotificationToCompleteFacility: => if (@["Facility"]?.complete is "true" or @["Facility"]?.complete is true) and @["Case Notification"]? moment.duration(@timeFromCaseNotificationToCompleteFacility()).asDays() householdComplete: => @complete() timeOfHouseholdComplete: => return null unless @householdComplete() latestLastModifiedTimeOfHouseholdMemberRecords = "" for householdMember in @["Household Members"] if householdMember.lastModifiedAt > latestLastModifiedTimeOfHouseholdMemberRecords latestLastModifiedTimeOfHouseholdMemberRecords = householdMember.lastModifiedAt latestLastModifiedTimeOfHouseholdMemberRecords timeFromFacilityToCompleteHousehold: => if @householdComplete() and @["Facility"]? return moment(@timeOfHouseholdComplete().replace(/\+0\d:00/,"")).diff(@["Facility"]?.lastModifiedAt) timeFromSMSToCompleteHousehold: => if @householdComplete() and @["USSD Notification"]? return moment(@timeOfHouseholdComplete().replace(/\+0\d:00/,"")).diff(@["USSD Notification"]?.date) hoursFromNotificationToCompleteHousehold: => Math.floor(moment.duration(@timeFromSMSToCompleteHousehold()).asHours()) daysFromSMSToCompleteHousehold: => if @householdComplete() and @["USSD Notification"]? moment.duration(@timeFromSMSToCompleteHousehold()).asDays() odkClassification: => if @["ODK 2017-2019"] switch @["ODK 2017-2019"]["case_classification:case_category"] when 1 then "Imported" when 2,3 then "Indigenous" when 4 then "Induced" when 5 then "Relapsing" classificationsWithPositiveIndividualObjects: => for positiveIndividual in @positiveIndividualObjects() { classification: positiveIndividual.classification() positiveIndividual: positiveIndividual } classificationsBy: (property) => (for data in @classificationsWithPositiveIndividualObjects() "#{data.positiveIndividual.data[property]}: #{data.classification}" ).join(", ") classificationsByFunction: (functionName) => (for data in @classificationsWithPositiveIndividualObjects() "#{data.positiveIndividual[functionName]()}: #{data.classification}" ).join(", ") classificationsByHouseholdMemberType: => # IF household member type is undefined it is either: # in progress index case # pre 2019 household member (for data in @classificationsWithPositiveIndividualObjects() if data.positiveIndividual.data.question isnt "Household Members" "Index Case: #{data.classification}" else if data.positiveIndividual.data["HouseholdMemberType"] is undefined "Household Member: #{data.classification}" else "#{data.positiveIndividual.data["HouseholdMemberType"]}: #{data.classification}" ).join(", ") classificationsByDiagnosisDate: => @classificationsByFunction("dateOfPositiveResults") classificationsByIsoYearIsoWeekFociDistrictFociShehia: => (for classificationWithPositiveIndividual in @classificationsWithPositiveIndividualObjects() classification = classificationWithPositiveIndividual.classification positiveIndividual = classificationWithPositiveIndividual.positiveIndividual dateOfPositiveResults = positiveIndividual.dateOfPositiveResults() date = if dateOfPositiveResults moment(dateOfPositiveResults) else # Use index case date if we are missing positiveIndividual's date if dateOfPositiveResults = @dateOfPositiveResults() moment(dateOfPositiveResults) if date? isoYear = date.isoWeekYear() isoWeek = date.isoWeek() fociDistrictShehia = if (focus = positiveIndividual.data["WhereCouldTheMalariaFocusBe"]) focus = focus.trim() if focus is "Patient Shehia" [@district(), @shehia()] else if focus is "Other Shehia Within Zanzibar" otherDistrict = positiveIndividual.data["WhichOtherDistrictWithinZanzibar"] otherShehia = positiveIndividual.data["WhichOtherShehiaWithinZanzibar"] shehiaUnit = @shehiaUnit(otherShehia, otherDistrict) [ shehiaUnit?.ancestorAtLevel("DISTRICT")?.name or @district() shehiaUnit?.name or @shehia() ] else [@district(), @shehia()] else if positiveIndividual.data.HouseholdMemberType is "Index Case" and (odkData = @["ODK 2017-2019"]) #TODO waiting to find out which ODK questions were used for this [@district(), @shehia()] else [@district(), @shehia()] [fociDistrict,fociShehia] = fociDistrictShehia "#{isoYear}:#{isoWeek}:#{fociDistrict}:#{fociShehia}:#{classification}" ).join(", ") evidenceForClassifications: => _(for householdMember in @["Household Members"] if householdMember.CaseCategory "#{householdMember.CaseCategory}: #{householdMember.SummarizeEvidenceUsedForClassification}" ).compact().join(", ") concatenateHouseholdMembers: (property) => _(for householdMember in @["Household Members"] if householdMember.CaseCategory "#{householdMember.CaseCategory}: #{householdMember[property]}" ).compact().join(", ") occupations: => @concatenateHouseholdMembers("Occupation") numbersSentTo: => @["USSD Notification"]?.numbersSentTo?.join(", ") # Data properties above # # ------------- # createOrUpdateOnDhis2: (options = {}) => options.malariaCase = @ Coconut.dhis2.createOrUpdateMalariaCase(options) spreadsheetRow: (question) => console.error "Must call loadSpreadsheetHeader at least once before calling spreadsheetRow" unless Coconut.spreadsheetHeader? spreadsheetRowObjectForResult = (fields,result) -> if result? _(fields).map (field) => if result[field]? if _.contains(Coconut.identifyingAttributes, field) return b64_sha1(result[field]) else return result[field] else return "" else return null if question is "Household Members" _(@[question]).map (householdMemberResult) -> spreadsheetRowObjectForResult(Coconut.spreadsheetHeader[question], householdMemberResult) else spreadsheetRowObjectForResult(Coconut.spreadsheetHeader[question], @[question]) spreadsheetRowString: (question) => if question is "Household Members" _(@spreadsheetRow(question)).map (householdMembersRows) -> result = _(householdMembersRows).map (data) -> "\"#{data}\"" .join(",") result += "--EOR--" if result isnt "" .join("") else result = _(@spreadsheetRow(question)).map (data) -> "\"#{data}\"" .join(",") result += "--EOR--" if result isnt "" summaryResult: (property,options) => priorityOrder = options?.priorityOrder or [ "Household" "Facility" "Case Notification" "USSD Notification" ] if property.match(/:/) propertyName = property priorityOrder = [property.split(/: */)[0]] # If prependQuestion then we only want to search within that question priorityOrder = [options.prependQuestion] if options?.prependQuestion # Make the labels be human readable by looking up the original question text and using that labelMappings = {} _(priorityOrder).each (question) -> return if question is "USSD Notification" labelMappings[question] = Coconut.questions.findWhere({_id:question}).safeLabelsToLabelsMappings() # Looks through the results in the prioritized order for a match findPrioritizedProperty = (propertyNames=[property]) => result = null _(propertyNames).each (propertyName) => return if result _(priorityOrder).each (question) => return if result return unless @[question]? if @[question][propertyName]? result = @[question][propertyName] property = labelMappings[question][propertyName] if labelMappings[question] and labelMappings[question][propertyName] return result result = null result = @[options.functionName]() if options?.functionName result = @[property]() if result is null and @[property] result = findPrioritizedProperty() if result is null if result is null result = findPrioritizedProperty(options.otherPropertyNames) if options?.otherPropertyNames result = JSON.stringify(result) if _(result).isObject() if _(result).isString() result = result?.trim() if options?.propertyName property = options.propertyName else property = titleize(humanize(property)) if options?.prependQuestion property = "#{options.prependQuestion}: #{property}" return {"#{property}": result} summaryCollection: => result = {} _(Case.summaryProperties).each (options, property) => summaryResult = @summaryResult(property, options) # Don't overwrite data if it is already there # Not exactly sure why this is needed, but there seem to be # Null duplicates that replace good data unless result[_(summaryResult).keys()[0]]? result = _(result).extend summaryResult return result summary: -> _(Case.summaryProperties).map (options, property) => @summaryResult(property, options) Case.summaryPropertiesKeys = -> _(Case.summaryProperties).map (options, key) -> if options.propertyName key = options.propertyName else key = PI:KEY:<KEY>END_PIkey).PI:KEY:<KEY>END_PIreplace("Numberof", "Number of") summaryAsCSVString: => _(@summary()).chain().map (summaryItem) -> "\"#{_(summaryItem).values()}\"" .flatten().value().join(",") + "--EOR--<br/>" Case.summaryProperties = { # TODO Document how the different options work # For now just look up at summaryResult function # propertyName is used to change the column name at the top of the CSV # otherPropertyNames is an array of other values to try and check # Case Notification MalariaCaseID: propertyName: "Malaria Case ID" IndexCaseDiagnosisDate: propertyName: "Index Case Diagnosis Date" IndexCaseDiagnosisDateIsoWeek: propertyName: "Index Case Diagnosis Date ISO Week" IndexCaseDiagnosisDateAndTime: propertyName: "Index Case Diagnosis Date And Time" classificationsByHouseholdMemberType: {} classificationsByDiagnosisDate: {} classificationsByIsoYearIsoWeekFociDistrictFociShehia: {} evidenceForClassifications: {} reasonForLostToFollowup: {} namesOfAdministrativeLevels: {} island: {} district: {} facility: {} facilityType: {} facilityDistrict: propertyName: "District of Facility" shehia: {} shehiaFromGPS: {} isShehiaValid: {} highRiskShehia: {} village: propertyName: "Village" villageFromGPS: {} IndexCasePatientName: propertyName: "Patient Name" ageInYears: {} Sex: {} isUnder5: propertyName: "Is Index Case Under 5" SMSSent: propertyName: "SMS Sent to DMSO" hasCaseNotification: {} numbersSentTo: {} source: {} source_phone: {} type: {} lastQuestionCompleted: {} hasCompleteFacility: {} notCompleteFacilityAfter24Hours: propertyName: "Not Complete Facility After 24 Hours" notFollowedUpAfter48Hours: propertyName: "Not Followed Up After 48 Hours" notFollowedUpAfterXHours: propertyName: "Not Followed Up After X Hours" followedUpWithin48Hours: propertyName: "Followed Up Within 48 Hours" completeHouseholdVisit: propertyName: "Complete Household Visit" CompleteHouseholdVisit: propertyName: "Complete Household Visit" numberHouseholdMembersTestedAndUntested: {} numberHouseholdMembersTested: {} NumberPositiveIndividualsAtIndexHousehold: {} NumberHouseholdOrNeighborMembers: {} NumberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholds: {} NumberHouseholdOrNeighborMembersTested: {} NumberPositiveIndividualsIncludingIndex: {} NumberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholdsUnder5: propertyName: "Number Positive Cases At Index Household And Neighbor Households Under 5" NumberSuspectedImportedCasesIncludingHouseholdMembers: {} MassScreenCase: {} CaseIdForOtherHouseholdMemberThatTestedPositiveAtAHealthFacility: propertyName: "Case ID for Other Household Member That Tested Positive at a Health Facility" CommentRemarks: {} ContactMobilePatientRelative: {} HasSomeoneFromTheSameHouseholdRecentlyTestedPositiveAtAHealthFacility: propertyName: "Has Someone From the Same Household Recently Tested Positive at a Health Facility" HeadOfHouseholdName: {} ParasiteSpecies: {} ReferenceInOpdRegister: propertyName: "Reference In OPD Register" TreatmentGiven: {} #Household CouponNumbers: {} FollowupNeighbors: {} HaveYouGivenCouponsForNets: {} HeadOfHouseholdName: {} HouseholdLocationAccuracy: propertyName: "Household Location - Accuracy" functionName: "householdLocationAccuracy" HouseholdLocationAltitude: propertyName: "Household Location - Altitude" HouseholdLocationAltitudeAccuracy: propertyName: "Household Location - Altitude Accuracy" HouseholdLocationDescription: propertyName: "Household Location - Description" HouseholdLocationHeading: propertyName: "Household Location - Heading" HouseholdLocationLatitude: propertyName: "Household Location - Latitude" functionName: "householdLocationLatitude" HouseholdLocationLongitude: propertyName: "Household Location - Longitude" functionName: "householdLocationLongitude" HouseholdLocationTimestamp: propertyName: "Household Location - Timestamp" IndexCaseIfPatientIsFemale1545YearsOfAgeIsSheIsPregant: propertyName: "Is Index Case Pregnant" IndexCasePatient: {} IndexCasePatientSCurrentStatus: propertyName: "Index Case Patient's Current Status" IndexCasePatientSTreatmentStatus: propertyName: "Index Case Patient's Treatment Status" IndexCaseSleptUnderLlinLastNight: propertyName: "Index Case Slept Under LLIN Last Night" IndexCaseDiagnosisDate: {} LastDateOfIrs: propertyName: "Last Date Of IRS" NumberOfHouseholdMembersTreatedForMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" NumberOfHouseholdMembersWithFeverOrHistoryOfFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" NumberOfLlin: propertyName: "Number Of LLIN" NumberOfSleepingPlacesBedsMattresses: propertyName: "Number of Sleeping Places (Beds/Mattresses)" NumberOfOtherHouseholdsWithin50StepsOfIndexCaseHousehold: propertyName: "Number of Other Households Within 50 Steps of Index Case Household" ReasonForVisitingHousehold: {} ShehaMjumbe: propertyName: "PI:NAME:<NAME>END_PI" TotalNumberOfResidentsInTheHousehold: {} DaysFromCaseNotificationToCompleteFacility: {} DaysFromSmsToCompleteHousehold: propertyName: "Days between SMS Sent to DMSO to Having Complete Household" DaysBetweenPositiveResultAndNotificationFromFacility: {} LessThanOneDayBetweenPositiveResultAndNotificationFromFacility: {} OneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: {} TwoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: {} MoreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: {} DaysBetweenPositiveResultAndCompleteHousehold: {} LessThanOneDayBetweenPositiveResultAndCompleteHousehold: {} OneToTwoDaysBetweenPositiveResultAndCompleteHousehold: {} TwoToThreeDaysBetweenPositiveResultAndCompleteHousehold: {} MoreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: {} "USSD Notification: Created At": otherPropertyNames: ["createdAt"] "USSD Notification: Date": otherPropertyNames: ["date"] "USSD Notification: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "USSD Notification: User": otherPropertyNames: ["user"] "Case Notification: Created At": otherPropertyNames: ["createdAt"] "Case Notification: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Case Notification: Saved By": otherPropertyNames: ["savedBy"] "Facility: Created At": otherPropertyNames: ["createdAt"] "Facility: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Facility: Saved By": otherPropertyNames: ["savedBy"] "Facility: User": otherPropertyNames: ["user"] "Household: Created At": otherPropertyNames: ["createdAt"] "Household: Last Modified At": otherPropertyNames: ["lastModifiedAt"] "Household: Saved By": otherPropertyNames: ["savedBy"] "Household: User": otherPropertyNames: ["user"] ## Old naming HeadofHouseholdName: propertyName: "Head Of Household PI:NAME:<NAME>END_PI" ContactMobilepatientrelative: propertyName: "Contact Mobile Patient Relative" IfYESlistALLplacestravelled: propertyName: "All Places Traveled to in Past Month" CaseIDforotherhouseholdmemberthattestedpositiveatahealthfacility: propertyName: "CaseID For Other Household Member That Tested Positive at a Health Facility" TravelledOvernightinpastmonth: propertyName: "Travelled Overnight in Past Month" Hassomeonefromthesamehouseholdrecentlytestedpositiveatahealthfacility: propertyName: "Has Someone From The Same Household Recently Tested Positive at a Health Facility" Reasonforvisitinghousehold: propertyName: "Reason For Visiting Household" Ifyeslistallplacestravelled: propertyName: "If Yes List All Places Travelled" Fevercurrentlyorinthelasttwoweeks: propertyName: "Fever Currently Or In The Last Two Weeks?" SleptunderLLINlastnight: propertyName: "Slept Under LLIN Last Night?" OvernightTravelinpastmonth: propertyName: "Overnight Travel in Past Month" ResidentofShehia: propertyName: "Resident of Shehia" TotalNumberofResidentsintheHousehold: propertyName: "Total Number of Residents in the Household" NumberofLLIN: propertyName: "Number of LLIN" NumberofSleepingPlacesbedsmattresses: propertyName: "Number of Sleeping Places (Beds/Mattresses)" NumberofHouseholdMemberswithFeverorHistoryofFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" NumberofHouseholdMembersTreatedforMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" LastdateofIRS: propertyName: "Last Date of IRS" Haveyougivencouponsfornets: propertyName: "Have you given coupon(s) for nets?" IndexcaseIfpatientisfemale1545yearsofageissheispregant: propertyName: "Index Case: If Patient is Female 15-45 Years of Age, Is She Pregnant?" IndexcasePatientscurrentstatus: propertyName: "Index case: Patient's current status" IndexcasePatientstreatmentstatus: propertyName: "Index case: Patient's treatment status" indexCasePatientName: propertyName: "Patient Name" IndexcasePatient: propertyName: "Index Case Patient" IndexcaseSleptunderLLINlastnight: propertyName: "Index case: Slept under LLIN last night?" IndexcaseOvernightTraveloutsideofZanzibarinthepastyear: propertyName: "Index Case Overnight Travel Outside of Zanzibar in the Past Year" IndexcaseOvernightTravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "Index Case Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar07daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 0-7 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar814daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 8-14 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar1521daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 15-21 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar2242daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 22-42 Days Before Positive Test Result" AlllocationsandentrypointsfromovernighttraveloutsideZanzibar43365daysbeforepositivetestresult: propertyName: "All Locations and Entry Points From Overnight Travel Outside Zanzibar 43-365 Days Before Positive Test Result" ListalllocationsofovernighttravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "All Locations Of Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" daysBetweenPositiveResultAndNotificationFromFacility: {} estimatedHoursBetweenPositiveResultAndNotificationFromFacility: {} daysFromCaseNotificationToCompleteFacility: propertyName: "Days From Case Notification To Complete Facility" daysFromSMSToCompleteHousehold: propertyName: "Days between SMS Sent to DMSO to Having Complete Household" "HouseholdLocation-description": propertyName: "Household Location - Description" "HouseholdLocation-latitude": propertyName: "Household Location - Latitude" functionName: "householdLocationLatitude" "HouseholdLocation-longitude": propertyName: "Household Location - Longitude" functionName: "householdLocationLongitude" "HouseholdLocation-accuracy": propertyName: "Household Location - Accuracy" functionName: "householdLocationAccuracy" "HouseholdLocation-altitude": propertyName: "Household Location - Altitude" "HouseholdLocation-altitudeAccuracy": propertyName: "Household Location - Altitude Accuracy" "HouseholdLocation-timestamp": propertyName: "Household Location - Timestamp" travelLocationName: propertyName: "Travel Location Name" OvernightTravelwithinZanzibar1024daysbeforepositivetestresult: propertyName: "Overnight Travel Within Zanzibar 10-24 Days Before Positive Test Result" OvernightTraveloutsideofZanzibarinthepastyear: propertyName: "Overnight Travel Outside of Zanzibar In The Past Year" ReferredtoHealthFacility: propertyName: "Referred to Health Facility" hasCompleteFacility: propertyName: "Has Complete Facility" notCompleteFacilityAfter24Hours: propertyName: "Not Complete Facility After 24 Hours" notFollowedUpAfter48Hours: propertyName: "Not Followed Up After 48 Hours" followedUpWithin48Hours: propertyName: "Followed Up Within 48Hours" completeHouseholdVisit: propertyName: "Complete Household Visit" numberPositiveIndividualsExcludingIndex: propertyName: "Number Positive Individuals At Household Excluding Index" numberPositiveIndividualsAtIndexHouseholdAndNeighborHouseholds: propertyName: "Number Positive Cases At Index Household And Neighbor Households" numberPositiveIndividuals: propertyName: "Number Positive Individuals" numberPositiveIndividualsUnder5: propertyName: "Number Positive Individuals Under 5" numberPositiveIndividualsOver5: propertyName: "Number Positive Individuals Over 5" NumberofHouseholdMembersTreatedforMalariaWithinPastWeek: propertyName: "Number of Household Members Treated for Malaria Within Past Week" NumberofHouseholdMemberswithFeverorHistoryofFeverWithinPastWeek: propertyName: "Number of Household Members With Fever or History of Fever Within Past Week" massScreenCase: propertyName: "Mass Screen Case" TotalNumberofResidentsintheHousehold: propertyName: "Total Number Of Residents In The Household" lessThanOneDayBetweenPositiveResultAndNotificationFromFacility: propertyName: "Less Than One Day Between Positive Result And Notification From Facility" oneToTwoDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "One To Two Days Between Positive Result And Notification From Facility" twoToThreeDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "Two To Three Days Between Positive Result And Notification From Facility" moreThanThreeDaysBetweenPositiveResultAndNotificationFromFacility: propertyName: "More Than Three Days Between Positive Result And Notification From Facility" daysBetweenPositiveResultAndCompleteHousehold: propertyName: "Days Between Positive Result And Complete Household" lessThanOneDayBetweenPositiveResultAndCompleteHousehold: propertyName: "Less Than One Day Between Positive Result And Complete Household" oneToTwoDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "One To Two Days Between Positive Result And Complete Household" twoToThreeDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "Two To Three Days Between Positive Result And Complete Household" moreThanThreeDaysBetweenPositiveResultAndCompleteHousehold: propertyName: "More Than Three Days Between Positive Result And Complete Household" occupations: {} dhis2CasesByTypeOfDetection: propertyName: "DHIS2 Cases by Type of Detection" dhis2CasesByClassification: propertyName: "DHIS2 Cases by Classification" dhis2CasesByAge: propertyName: "DHIS2 Cases by Age" dhis2CasesByGender: propertyName: "DHIS2 Cases by Gender" allUserNamesString: propertyName: "PI:NAME:<NAME>END_PIaria Surveillance Officers" wasTransferred: {} } dateOfMalariaResultFromIndividual: (positiveIndividual) => # First try and get the individuals' date, then the createdAt time (pre-2019) if all fails just use the date for the case or the date that the notification was made date = positiveIndividual.DateOfPositiveResults or positiveIndividual.createdAt or @dateOfPositiveResults() or positiveIndividual.date moment(date).format("YYYY-MM-DD") dhis2CasesByTypeOfDetection: => result = {} for positiveIndividual in @positiveIndividualsIndexCasesOnly() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= { "Passive": 0 "Active": 0 } result[date][shehia]["Passive"] += 1 for positiveIndividual in @positiveIndividualsExcludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= { "Passive": 0 "Active": 0 } result[date][shehia]["Active"] += 1 result dhis2CasesByClassification: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= {} result[date][shehia][positiveIndividual.CaseCategory or "Unclassified"] or= 0 result[date][shehia][positiveIndividual.CaseCategory or "Unclassified"] += 1 result dhis2CasesByAge: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() age = @ageInYears(positiveIndividual.Age, positiveIndividual.AgeInYearsMonthsDays) ageRange = if age? switch when age < 5 then "<5 yrs" when age < 15 then "5<15 yrs" when age < 25 then "15<25 yrs" when age >= 25 then ">25 yrs" else "Unknown" else "Unknown" date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia result[date] or= {} result[date][shehia] or= {} result[date][shehia][ageRange] or= 0 result[date][shehia][ageRange] += 1 result dhis2CasesByGender: => result = {} for positiveIndividual in @positiveIndividualsIncludingIndex() date = @dateOfMalariaResultFromIndividual(positiveIndividual) shehia = @shehia() if date and shehia gender = positiveIndividual.Sex if gender isnt "Male" or gender isnt "Female" then gender = "Unknown" result[date] or= {} result[date][shehia] or= {} result[date][shehia][gender] or=0 result[date][shehia][gender] += 1 result saveAndAddResultToCase: (result) => if @[result.question]? console.error "#{result.question} already exists for:" console.error @ return resultQuestion = result.question Coconut.database.put result .then (result) => console.log "saved:" console.log result @questions.push result.question @[result.question] = result Coconut.headerView.update() Coconut.showNotification( "#{resultQuestion} record created") .catch (error) -> console.error error createNextResult: => @fetch error: -> console.error error success: => if @["Household Members"] and @["Household Members"].length > 0 console.log "Household Members exists, no result created" # Don't create anything else if @Household?.complete console.log "Creating Household members and neighbor households if necessary" @createHouseholdMembers() @createNeighborHouseholds() else if @Facility?.complete console.log "Creating Household" @createHousehold() else if @["Case Notification"]?.complete console.log "Creating Facility" @createFacility() _.delay(Coconut.menuView.render, 500) createFacility: => @saveAndAddResultToCase _id: "result-case-#{@caseID}-Facility-#{radix64.encodeInt(moment().format('x'))}-#{Coconut.instanceId}" question: "Facility" MalariaCaseID: @caseID DistrictForFacility: @facilityDistrict() FacilityName: @facility() DistrictForShehia: @shehiaUnit().ancestorAtLevel("DISTRICT")?.name Shehia: @shehia() collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") createHousehold: => @saveAndAddResultToCase _id: "result-case-#{@caseID}-Household-#{radix64.encodeInt(moment().format('x'))}-#{Coconut.instanceId}" question: "Household" Reasonforvisitinghousehold: "Index Case Household" MalariaCaseID: @caseID HeadOfHouseholdName: @Facility.HeadOfHouseholdName District: @district() Shehia: @shehia() Village: @Facility.Village ShehaMjumbe: @Facility.ShehaMjumbe ContactMobilePatientRelative: @Facility.ContactMobilePatientRelative collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") createHouseholdMembers: => unless _(@questions).contains 'Household Members' _(@Household.TotalNumberOfResidentsInTheHousehold).times (index) => result = { _id: "result-case-#{@caseID}-Household-Members-#{radix64.encodeInt(moment().format('x'))}-#{radix64.encodeInt(Math.round(Math.random()*100000))}-#{Coconut.instanceId}" # There's a chance moment will be the same so add some randomness question: "Household Members" MalariaCaseID: @caseID HeadOfHouseholdName: @Household.HeadOfHouseholdName collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") } if index is 0 _(result).extend HouseholdMemberType: "Index Case" FirstName: @Facility?.FirstName LastName: @Facility?.LastName DateOfPositiveResults: @Facility?.DateOfPositiveResults DateAndTimeOfPositiveResults: @Facility?.DateAndTimeOfPositiveResults Sex: @Facility?.Sex Age: @Facility?.Age AgeInYearsMonthsDays: @Facility?.AgeInYearsMonthsDays MalariaMrdtTestResults: @Facility?.MalariaMrdtTestResults MalariaTestPerformed: @Facility?.MalariaTestPerformed Coconut.database.put result .then => @questions.push result.question @[result.question] = [] unless @[result.question] @[result.question].push result .catch (error) -> console.error error Coconut.headerView.update() Coconut.showNotification( "Household member record(s) created") createNeighborHouseholds: => # If there is more than one Household for this case, then Neighbor households must already have been created unless (_(@questions).filter (question) -> question is 'Household').length is 1 _(@Household.NumberOfOtherHouseholdsWithin50StepsOfIndexCaseHousehold).times => result = { _id: "result-case-#{@caseID}-Household-#{radix64.encodeInt(moment().format('x'))}-#{radix64.encodeInt(Math.round(Math.random()*100000))}-#{Coconut.instanceId}" # There's a chance moment will be the same so add some randomness ReasonForVisitingHousehold: "Index Case Neighbors" question: "Household" MalariaCaseID: @result.get "MalariaCaseID" Shehia: @result.get "Shehia" Village: @result.get "Village" ShehaMjumbe: @result.get "ShehaMjumbe" collection: "result" createdAt: moment(new Date()).format(Coconut.config.get "date_format") lastModifiedAt: moment(new Date()).format(Coconut.config.get "date_format") } Coconut.database.put result .then => Coconut.headerView.update() .catch (error) -> console.error error Coconut.showNotification( "Neighbor Household created") wasTransferred: => @transferData().length > 0 transferData: => transferData = [] for question in @questions if @[question].transferred data = @[question].transferred data["question"] = question transferData.push data transferData Case.resetSpreadsheetForAllCases = => Coconut.database.get "CaseSpreadsheetData" .then (caseSpreadsheetData) -> Case.updateCaseSpreadsheetDocs(0,caseSpreadsheetData) .catch (error) -> console.error error Case.loadSpreadsheetHeader = (options) -> if Coconut.spreadsheetHeader options.success() else Coconut.database.get "spreadsheet_header" .catch (error) -> console.error error .then (result) -> Coconut.spreadsheetHeader = result.fields options.success() Case.updateCaseSpreadsheetDocs = (options) -> # defaults used for first run caseSpreadsheetData = {_id: "CaseSpreadsheetData" } changeSequence = 0 updateCaseSpreadsheetDocs = (changeSequence, caseSpreadsheetData) -> Case.updateCaseSpreadsheetDocsSince changeSequence: changeSequence error: (error) -> console.log "Error updating CaseSpreadsheetData:" console.log error options.error?() success: (numberCasesChanged,lastChangeSequenceProcessed) -> console.log "Updated CaseSpreadsheetData" caseSpreadsheetData.lastChangeSequenceProcessed = lastChangeSequenceProcessed console.log caseSpreadsheetData Coconut.database.put caseSpreadsheetData .catch (error) -> console.error error .then -> console.log numberCasesChanged if numberCasesChanged > 0 Case.updateCaseSpreadsheetDocs(options) #recurse else options?.success?() Coconut.database.get "CaseSpreadsheetData" .catch (error) -> console.log "Couldn't find 'CaseSpreadsheetData' using defaults: changeSequence: #{changeSequence}" updateCaseSpreadsheetDocs(changeSequence,caseSpreadsheetData) .then (result) -> caseSpreadsheetData = result changeSequence = result.lastChangeSequenceProcessed updateCaseSpreadsheetDocs(changeSequence,caseSpreadsheetData) Case.updateCaseSpreadsheetDocsSince = (options) -> Case.loadSpreadsheetHeader success: -> $.ajax url: "/#{Coconut.config.database_name()}/_changes" dataType: "json" data: since: options.changeSequence include_docs: true limit: 500 error: (error) => console.log "Error downloading changes after #{options.changeSequence}:" console.log error options.error?(error) success: (changes) => changedCases = _(changes.results).chain().map (change) -> change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question? .compact().uniq().value() lastChangeSequence = changes.results.pop()?.seq Case.updateSpreadsheetForCases caseIDs: changedCases error: (error) -> console.log "Error updating #{changedCases.length} cases, lastChangeSequence: #{lastChangeSequence}" console.log error success: -> console.log "Updated #{changedCases.length} cases, lastChangeSequence: #{lastChangeSequence}" options.success(changedCases.length, lastChangeSequence) Case.updateSpreadsheetForCases = (options) -> docsToSave = [] questions = "USSD Notification,Case Notification,Facility,Household,Household Members".split(",") options.success() if options.caseIDs.length is 0 finished = _.after options.caseIDs.length, -> Coconut.database.bulkDocs docsToSave .catch (error) -> console.error error .then -> options.success() _(options.caseIDs).each (caseID) -> malariaCase = new Case caseID: caseID malariaCase.fetch error: (error) -> console.log error success: -> docId = "spreadsheet_row_#{caseID}" spreadsheet_row_doc = {_id: docId} saveRowDoc = (result) -> spreadsheet_row_doc = result if result? # if the row already exists use the _rev _(questions).each (question) -> spreadsheet_row_doc[question] = malariaCase.spreadsheetRowString(question) spreadsheet_row_doc["Summary"] = malariaCase.summaryAsCSVString() docsToSave.push spreadsheet_row_doc finished() Coconut.database.get docId .catch (error) -> saveRowDoc() .then (result) -> saveRowDoc(result) Case.getCases = (options) -> Coconut.database.query "cases", keys: options.caseIDs include_docs: true .catch (error) -> options?.error(error) .then (result) => cases = _.chain(result.rows) .groupBy (row) => row.key .map (resultsByCaseID) => malariaCase = new Case results: _.pluck resultsByCaseID, "doc" malariaCase .compact() .value() options?.success?(cases) Promise.resolve(cases) # Used on mobile client Case.getCasesSummaryData = (startDate, endDate) => Coconut.database.query "casesWithSummaryData", startDate: startDate endDate: endDate descending: true include_docs: true .catch (error) => console.error JSON.stringify error .then (result) => _(result.rows).chain().map (row) => row.doc.MalariaCaseID ?= row.key # For case docs without MalariaCaseID add it (caseid etc) row.doc .groupBy "MalariaCaseID" .map (resultDocs, malariaCaseID) => new Case caseID: malariaCaseID results: resultDocs .value() Case.getLatestChangeForDatabase = -> new Promise (resolve,reject) => Coconut.database.changes descending: true include_docs: false limit: 1 .on "complete", (mostRecentChange) -> resolve(mostRecentChange.last_seq) .on "error", (error) -> reject error Case.getLatestChangeForCurrentSummaryDataDocs = -> Coconut.reportingDatabase.get "CaseSummaryData" .catch (error) -> console.error "Error while getLatestChangeForCurrentSummaryDataDocs: #{error}" if error.reason is "missing" return Promise.resolve(null) else return Promise.reject("Non-missing error when getLatestChangeForCurrentSummaryDataDocs") .then (caseSummaryData) -> return Promise.resolve(caseSummaryData?.lastChangeSequenceProcessed or null) Case.resetAllCaseSummaryDocs = (options) => # Docs to save designDocs = await Coconut.reportingDatabase.allDocs startkey: "_PI:KEY:<KEY>END_PI" endkey: PI:KEY:<KEY>END_PI" include_docs: true .then (result) -> Promise.resolve _(result.rows).map (row) -> doc = row.doc delete doc._rev doc otherDocsToSave = await Coconut.reportingDatabase.allDocs include_docs: true keys: [ "PI:KEY:<KEY>END_PI" ] .then (result) -> console.log result Promise.resolve( _(result.rows).chain().map (row) -> doc = row.doc delete doc._rev if doc doc .compact().value() ) docsToSave = designDocs.concat(otherDocsToSave) reportingDatabaseNameWithCredentials = Coconut.reportingDatabase.name await Coconut.reportingDatabase.destroy() .catch (error) -> console.error error throw "Error while destroying database" Coconut.reportingDatabase = new PouchDB(reportingDatabaseNameWithCredentials) await Coconut.reportingDatabase.bulkDocs docsToSave try latestChangeForDatabase = await Case.getLatestChangeForDatabase() console.log "Latest change: #{latestChangeForDatabase}" console.log "Retrieving all available case IDs" Coconut.database.query "cases/cases" .then (result) => allCases = _(result.rows).chain().pluck("key").uniq(true).reverse().value() console.log "Updating #{allCases.length} cases" await Case.updateSummaryForCases caseIDs: allCases console.log "Updated: #{allCases.length} cases" Coconut.reportingDatabase.upsert "CaseSummaryData", (doc) => doc.lastChangeSequenceProcessed = latestChangeForDatabase doc catch error console.error Case.updateCaseSummaryDocs = (options) -> latestChangeForDatabase = await Case.getLatestChangeForDatabase() latestChangeForCurrentSummaryDataDocs = await Case.getLatestChangeForCurrentSummaryDataDocs() #latestChangeForCurrentSummaryDataDocs = "3490519-PI:KEY:<KEY>END_PI" # console.log "latestChangeForDatabase: #{latestChangeForDatabase?.replace(/-.*/, "")}, latestChangeForCurrentSummaryDataDocs: #{latestChangeForCurrentSummaryDataDocs?.replace(/-.*/,"")}" if latestChangeForCurrentSummaryDataDocs numberLatestChangeForDatabase = parseInt(latestChangeForDatabase?.replace(/-.*/,"")) numberLatestChangeForCurrentSummaryDataDocs = parseInt(latestChangeForCurrentSummaryDataDocs?.replace(/-.*/,"")) if numberLatestChangeForDatabase - numberLatestChangeForCurrentSummaryDataDocs > 50000 console.log "Large number of changes, so just resetting since this is more efficient that reviewing every change." return Case.resetAllCaseSummaryDocs() unless latestChangeForCurrentSummaryDataDocs console.log "No recorded change for current summary data docs, so resetting" Case.resetAllCaseSummaryDocs() else #console.log "Getting changes since #{latestChangeForCurrentSummaryDataDocs.replace(/-.*/, "")}" # Get list of cases changed since latestChangeForCurrentSummaryDataDocs Coconut.database.changes since: latestChangeForCurrentSummaryDataDocs include_docs: true filter: "_view" view: "cases/cases" .then (result) => return if result.results.length is 0 #console.log "Found changes, now plucking case ids" changedCases = _(result.results).chain().map (change) -> change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question? .compact().uniq().value() #console.log "Changed cases: #{_(changedCases).length}" await Case.updateSummaryForCases caseIDs: changedCases console.log "Updated: #{changedCases.length} cases" Coconut.reportingDatabase.upsert "CaseSummaryData", (doc) => doc.lastChangeSequenceProcessed = latestChangeForDatabase doc .catch (error) => console.error error .then => console.log "CaseSummaryData updated through sequence: #{latestChangeForDatabase}" Case.updateSummaryForCases = (options) => new Promise (resolve, reject) => return resolve() if options.caseIDs.length is 0 numberOfCasesToProcess = options.caseIDs.length numberOfCasesProcessed = 0 numberOfCasesToProcessPerIteration = 100 while options.caseIDs.length > 0 caseIDs = options.caseIDs.splice(0,numberOfCasesToProcessPerIteration) # remove 100 caseids cases = await Case.getCases caseIDs: caseIDs docsToSave = [] for malariaCase in cases caseID = malariaCase.caseID docId = "case_summary_#{caseID}" currentCaseSummaryDoc = null try currentCaseSummaryDoc = await Coconut.reportingDatabase.get(docId) catch # Ignore if there is no document try updatedCaseSummaryDoc = malariaCase.summaryCollection() catch error console.error error updatedCaseSummaryDoc["_id"] = docId updatedCaseSummaryDoc._rev = currentCaseSummaryDoc._rev if currentCaseSummaryDoc? docsToSave.push updatedCaseSummaryDoc try await Coconut.reportingDatabase.bulkDocs(docsToSave) catch error console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}" console.error error numberOfCasesProcessed += caseIDs.length console.log "#{numberOfCasesProcessed}/#{numberOfCasesToProcess} #{Math.floor(numberOfCasesProcessed/numberOfCasesToProcess*100)}% (last ID: #{caseIDs.pop()})" resolve() ### I think this can be removed Case.getCasesByCaseIds = (options) -> Coconut.database.query "cases", keys: options.caseIDs include_docs: true .catch (error) -> console.error error .then (result) => groupedResults = _.chain(result.rows) .groupBy (row) => row.key .map (resultsByCaseID) => new Case results: _.pluck resultsByCaseID, "doc" .compact() .value() options.success groupedResults ### Case.createCaseView = (options) -> @case = options.case tables = [ "Summary" "USSD Notification" "Case Notification" "Facility" "Household" "Household Members" ] @mappings = { createdAt: "Created At" lastModifiedAt: "Last Modified At" question: "Question" user: "User" complete: "Complete" savedBy: "Saved By" } #hack to rename Question name in Case view report caseQuestions = @case.Questions().replace("Case Notification", "Case Notification Received").replace("USSD Notification","Case Notification Sent") Coconut.caseview = " <h5>Case ID: #{@case.MalariaCaseID()}</h5><button id='closeDialog' class='mdl-button mdl-js-button mdl-button--icon mdl-button--colored f-right'><i class='mdi mdi-close-circle mdi-24px'></i></button> <h6>Last Modified: #{@case.LastModifiedAt()}</h6> <h6>Questions: #{caseQuestions}</h6> " # USSD Notification doesn't have a mapping finished = _.after tables.length, => Coconut.caseview += _.map(tables, (tableType) => if (tableType is "Summary") @createObjectTable(tableType,@case.summaryCollection()) else if @case[tableType]? if tableType is "Household Members" _.map(@case[tableType], (householdMember) => @createObjectTable(tableType,householdMember) ).join("") else @createObjectTable(tableType,@case[tableType]) ).join("") options?.success() return false _(tables).each (question) => if question != "USSD Notification" question = new Question(id: question) question.fetch success: => _.extend(@mappings, question.safeLabelsToLabelsMappings()) finished() return false Case.createObjectTable = (name,object) -> #Hack to replace title to differ from Questions title name = "Case Notification Received" if name == 'Case Notification' name = "Case Notification Sent" if name == 'USSD Notification' " <h4 id=#{object._id}>#{name} <!-- <small><a href='#edit/result/#{object._id}'>Edit</a></small> --> </h4> <table class='mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp caseTable'> <thead> <tr> <th class='mdl-data-table__cell--non-numeric width65pct'>Field</th> <th class='mdl-data-table__cell--non-numeric'>Value</th> </tr> </thead> <tbody> #{ labels = CONST.Labels _.map(object, (value, field) => if !(Coconut.currentUser.isAdmin()) if (_.indexOf(['name','Name','FirstName','MiddleName','LastName','HeadOfHouseholdName','ContactMobilePatientRelative'],field) != -1) value = "************" return if "#{field}".match(/_id|_rev|collection/) " <tr> <td class='mdl-data-table__cell--non-numeric'> #{ @mappings[field] or labels[field] or field } </td> <td class='mdl-data-table__cell--non-numeric'>#{value}</td> </tr> " ).join("") } </tbody> </table> " Case.setup = => new Promise (resolve) => for docId in ["shehias_high_risk","shehias_received_irs"] await Coconut.database.get docId .catch (error) -> console.error JSON.stringify error .then (result) -> Coconut[docId] = result Promise.resolve() designDocs = { cases: (doc) -> emit(doc.MalariaCaseID, null) if doc.MalariaCaseID emit(doc.caseid, null) if doc.caseid casesWithSummaryData: (doc) -> if doc.MalariaCaseID date = doc.DateofPositiveResults or doc.lastModifiedAt match = date.match(/^(\d\d).(\d\d).(2\d\d\d)/) if match? date = "#{match[3]}-#{match[2]}-#{match[1]}" if doc.transferred? lastTransfer = doc.transferred[doc.transferred.length-1] if date.match(/^2\d\d\d\-\d\d-\d\d/) emit date, [doc.MalariaCaseID,doc.question,doc.complete,lastTransfer] if doc.caseid if document.transferred? lastTransfer = doc.transferred[doc.transferred.length-1] if doc.date.match(/^2\d\d\d\-\d\d-\d\d/) emit doc.date, [doc.caseid, "Facility Notification", null, lastTransfer] } for name, designDocFunction of designDocs designDoc = Utils.createDesignDoc name, designDocFunction await Coconut.database.upsert designDoc._id, (existingDoc) => return false if _(designDoc.views).isEqual(existingDoc?.views) console.log "Creating Case view: #{name}" designDoc .catch (error) => console.error error resolve() module.exports = Case
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999120831489563, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/global-drag.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @GlobalDrag constructor: -> $(document).on 'dragenter', @dragenter $(document).on 'dragover', @dragend dragenter: => # The event bubbles, prevent retriggering the event unless # it really has just started. return if @dragging @dragging = true $.publish 'dragenterGlobal' # Triggered during dragover because there's no other way to detect if mouse # is still within the viewport. # Thankfully dragover is practically triggered any time mouse is inside the # viewport. Absence of this event means mouse has left the viewport. # Side effects include stupid amount of {set,clear}Timeout. dragend: (e) => return unless @dragging trigger = => @dragging = false $.publish 'dragendGlobal' Timeout.clear @dragendTimer @dragendTimer = Timeout.set 100, trigger
127608
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @GlobalDrag constructor: -> $(document).on 'dragenter', @dragenter $(document).on 'dragover', @dragend dragenter: => # The event bubbles, prevent retriggering the event unless # it really has just started. return if @dragging @dragging = true $.publish 'dragenterGlobal' # Triggered during dragover because there's no other way to detect if mouse # is still within the viewport. # Thankfully dragover is practically triggered any time mouse is inside the # viewport. Absence of this event means mouse has left the viewport. # Side effects include stupid amount of {set,clear}Timeout. dragend: (e) => return unless @dragging trigger = => @dragging = false $.publish 'dragendGlobal' Timeout.clear @dragendTimer @dragendTimer = Timeout.set 100, trigger
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @GlobalDrag constructor: -> $(document).on 'dragenter', @dragenter $(document).on 'dragover', @dragend dragenter: => # The event bubbles, prevent retriggering the event unless # it really has just started. return if @dragging @dragging = true $.publish 'dragenterGlobal' # Triggered during dragover because there's no other way to detect if mouse # is still within the viewport. # Thankfully dragover is practically triggered any time mouse is inside the # viewport. Absence of this event means mouse has left the viewport. # Side effects include stupid amount of {set,clear}Timeout. dragend: (e) => return unless @dragging trigger = => @dragging = false $.publish 'dragendGlobal' Timeout.clear @dragendTimer @dragendTimer = Timeout.set 100, trigger
[ { "context": "re modelsDir + modName\n new exports.User(email: 'ze@example.com').fetch(withRelated: ['nucleus'])\n .then (usr)", "end": 2868, "score": 0.9999149441719055, "start": 2854, "tag": "EMAIL", "value": "ze@example.com" } ]
src/bookrack.coffee
aurium/bookrack
0
fs = require 'fs' # Main class # Bookrack instances stores the bookshelf+knex refferences and works as a # model store to the application. class Bookrack constructor: (options={})-> unless options.connection? throw new Error "You must to define a DB connection, or a knex object for Bookrack!" if options.connection.queryBuilder? knex = options.connection else knex = require('knex') options.connection bookshelf = require('bookshelf') knex bookshelf.plugin 'registry' bookshelf.plugin 'virtuals' bookshelf.plugin 'visibility' readOnly this, '_bookshelf', => bookshelf readOnly this, 'migrate', => @_bookshelf.knex.migrate readOnly this, 'seed', => @_bookshelf.knex.seed @loadModelsFromDir options.modelsDir if options.modelsDir? loadModelsFromDir: (dirPath)-> for file in fs.readdirSync dirPath when moduleExtRE.test file filePath = joinPath dirPath, file try @loadModelFile filePath catch err err.message = "ERROR when loading #{filePath}: #{err.message}" throw err loadModelFile: (filePath)-> [dir..., fileName] = filePath.split pathSep dir.unshift '/' if pathSep is '/' dir = resolvePath dir... modName = fileName.replace moduleExtRE, '' klass = file2class modName model = @defineModel require joinPath dir, modName unless klass is model.name console.error "WARNING: It is expected that module #{filePath} to define a model named #{klass}, however it defines #{model.name}." model defineModel: (confFunc)-> new Bookrack.Model this, confFunc hasPendingMigration: (callback)-> migrationDir = @migrate.config.directory if migrationDir[0] isnt '/' and migrationDir[0..1] isnt 'C:' console.error "WARNING: your `knexConfig.migrations.directory` is a relative path. This will be a problem! Use `path.resolve` on your config file." @migrate.currentVersion() .then (version)-> fs.readdir migrationDir, (err, list)=> return callback err if err numPendingMigrations = 0 for file in list if moduleExtRE.test file lastMigration = file.replace /_.*$/, '' if not version? or version is 'none' or version < lastMigration numPendingMigrations++ callback null, numPendingMigrations .catch (err)-> callback err ### fs = require 'fs' modelsDir = __dirname + '/../models/' timeout .1, -> for file in fs.readdirSync modelsDir when /\.coffee$/.test file modName = file.replace /\.coffee$/, '' klass = modName.replace /^(.)|[-_](.)/g, (s,g1,g2)-> (g1||g2).toUpperCase() exports[klass] = require modelsDir + modName new exports.User(email: 'ze@example.com').fetch(withRelated: ['nucleus']) .then (usr)-> console.log usr.constructor.toString() console.log 'User:', usr.get('email'), usr.get('fullName'), '!', exports.User.fullName console.log '------------------------------------------------------------' console.log 'Nucleus:', usr.related('nucleus').models[0].get 'name' .catch (err)-> console.log 'WTF', err ###
131789
fs = require 'fs' # Main class # Bookrack instances stores the bookshelf+knex refferences and works as a # model store to the application. class Bookrack constructor: (options={})-> unless options.connection? throw new Error "You must to define a DB connection, or a knex object for Bookrack!" if options.connection.queryBuilder? knex = options.connection else knex = require('knex') options.connection bookshelf = require('bookshelf') knex bookshelf.plugin 'registry' bookshelf.plugin 'virtuals' bookshelf.plugin 'visibility' readOnly this, '_bookshelf', => bookshelf readOnly this, 'migrate', => @_bookshelf.knex.migrate readOnly this, 'seed', => @_bookshelf.knex.seed @loadModelsFromDir options.modelsDir if options.modelsDir? loadModelsFromDir: (dirPath)-> for file in fs.readdirSync dirPath when moduleExtRE.test file filePath = joinPath dirPath, file try @loadModelFile filePath catch err err.message = "ERROR when loading #{filePath}: #{err.message}" throw err loadModelFile: (filePath)-> [dir..., fileName] = filePath.split pathSep dir.unshift '/' if pathSep is '/' dir = resolvePath dir... modName = fileName.replace moduleExtRE, '' klass = file2class modName model = @defineModel require joinPath dir, modName unless klass is model.name console.error "WARNING: It is expected that module #{filePath} to define a model named #{klass}, however it defines #{model.name}." model defineModel: (confFunc)-> new Bookrack.Model this, confFunc hasPendingMigration: (callback)-> migrationDir = @migrate.config.directory if migrationDir[0] isnt '/' and migrationDir[0..1] isnt 'C:' console.error "WARNING: your `knexConfig.migrations.directory` is a relative path. This will be a problem! Use `path.resolve` on your config file." @migrate.currentVersion() .then (version)-> fs.readdir migrationDir, (err, list)=> return callback err if err numPendingMigrations = 0 for file in list if moduleExtRE.test file lastMigration = file.replace /_.*$/, '' if not version? or version is 'none' or version < lastMigration numPendingMigrations++ callback null, numPendingMigrations .catch (err)-> callback err ### fs = require 'fs' modelsDir = __dirname + '/../models/' timeout .1, -> for file in fs.readdirSync modelsDir when /\.coffee$/.test file modName = file.replace /\.coffee$/, '' klass = modName.replace /^(.)|[-_](.)/g, (s,g1,g2)-> (g1||g2).toUpperCase() exports[klass] = require modelsDir + modName new exports.User(email: '<EMAIL>').fetch(withRelated: ['nucleus']) .then (usr)-> console.log usr.constructor.toString() console.log 'User:', usr.get('email'), usr.get('fullName'), '!', exports.User.fullName console.log '------------------------------------------------------------' console.log 'Nucleus:', usr.related('nucleus').models[0].get 'name' .catch (err)-> console.log 'WTF', err ###
true
fs = require 'fs' # Main class # Bookrack instances stores the bookshelf+knex refferences and works as a # model store to the application. class Bookrack constructor: (options={})-> unless options.connection? throw new Error "You must to define a DB connection, or a knex object for Bookrack!" if options.connection.queryBuilder? knex = options.connection else knex = require('knex') options.connection bookshelf = require('bookshelf') knex bookshelf.plugin 'registry' bookshelf.plugin 'virtuals' bookshelf.plugin 'visibility' readOnly this, '_bookshelf', => bookshelf readOnly this, 'migrate', => @_bookshelf.knex.migrate readOnly this, 'seed', => @_bookshelf.knex.seed @loadModelsFromDir options.modelsDir if options.modelsDir? loadModelsFromDir: (dirPath)-> for file in fs.readdirSync dirPath when moduleExtRE.test file filePath = joinPath dirPath, file try @loadModelFile filePath catch err err.message = "ERROR when loading #{filePath}: #{err.message}" throw err loadModelFile: (filePath)-> [dir..., fileName] = filePath.split pathSep dir.unshift '/' if pathSep is '/' dir = resolvePath dir... modName = fileName.replace moduleExtRE, '' klass = file2class modName model = @defineModel require joinPath dir, modName unless klass is model.name console.error "WARNING: It is expected that module #{filePath} to define a model named #{klass}, however it defines #{model.name}." model defineModel: (confFunc)-> new Bookrack.Model this, confFunc hasPendingMigration: (callback)-> migrationDir = @migrate.config.directory if migrationDir[0] isnt '/' and migrationDir[0..1] isnt 'C:' console.error "WARNING: your `knexConfig.migrations.directory` is a relative path. This will be a problem! Use `path.resolve` on your config file." @migrate.currentVersion() .then (version)-> fs.readdir migrationDir, (err, list)=> return callback err if err numPendingMigrations = 0 for file in list if moduleExtRE.test file lastMigration = file.replace /_.*$/, '' if not version? or version is 'none' or version < lastMigration numPendingMigrations++ callback null, numPendingMigrations .catch (err)-> callback err ### fs = require 'fs' modelsDir = __dirname + '/../models/' timeout .1, -> for file in fs.readdirSync modelsDir when /\.coffee$/.test file modName = file.replace /\.coffee$/, '' klass = modName.replace /^(.)|[-_](.)/g, (s,g1,g2)-> (g1||g2).toUpperCase() exports[klass] = require modelsDir + modName new exports.User(email: 'PI:EMAIL:<EMAIL>END_PI').fetch(withRelated: ['nucleus']) .then (usr)-> console.log usr.constructor.toString() console.log 'User:', usr.get('email'), usr.get('fullName'), '!', exports.User.fullName console.log '------------------------------------------------------------' console.log 'Nucleus:', usr.related('nucleus').models[0].get 'name' .catch (err)-> console.log 'WTF', err ###
[ { "context": "# \n# Bezier3d formula\n# @author David Ronai / Makiopolis.com / @Makio64 \n# \nclass Bezier3d\n\n\t", "end": 43, "score": 0.9998689889907837, "start": 32, "tag": "NAME", "value": "David Ronai" }, { "context": "# \n# Bezier3d formula\n# @author David Ronai / Makiopolis....
src/coffee/core/3d/Bezier3d.coffee
Makio64/Kyari
0
# # Bezier3d formula # @author David Ronai / Makiopolis.com / @Makio64 # class Bezier3d # p0 the starting point # p1 the anchor # p2 the ending point @calc = (p0,p1,p2,t)-> x = Math.pow(1 - t, 2) * p0.x + 2 * t * (1 - t) * p1.x + Math.pow(t, 2) * p2.x y = Math.pow(1 - t, 2) * p0.y + 2 * t * (1 - t) * p1.y + Math.pow(t, 2) * p2.y z = Math.pow(1 - t, 2) * p0.z + 2 * t * (1 - t) * p1.z + Math.pow(t, 2) * p2.z return new THREE.Vector3(x,y,z)
73386
# # Bezier3d formula # @author <NAME> / <EMAIL> / @Makio64 # class Bezier3d # p0 the starting point # p1 the anchor # p2 the ending point @calc = (p0,p1,p2,t)-> x = Math.pow(1 - t, 2) * p0.x + 2 * t * (1 - t) * p1.x + Math.pow(t, 2) * p2.x y = Math.pow(1 - t, 2) * p0.y + 2 * t * (1 - t) * p1.y + Math.pow(t, 2) * p2.y z = Math.pow(1 - t, 2) * p0.z + 2 * t * (1 - t) * p1.z + Math.pow(t, 2) * p2.z return new THREE.Vector3(x,y,z)
true
# # Bezier3d formula # @author PI:NAME:<NAME>END_PI / PI:EMAIL:<EMAIL>END_PI / @Makio64 # class Bezier3d # p0 the starting point # p1 the anchor # p2 the ending point @calc = (p0,p1,p2,t)-> x = Math.pow(1 - t, 2) * p0.x + 2 * t * (1 - t) * p1.x + Math.pow(t, 2) * p2.x y = Math.pow(1 - t, 2) * p0.y + 2 * t * (1 - t) * p1.y + Math.pow(t, 2) * p2.y z = Math.pow(1 - t, 2) * p0.z + 2 * t * (1 - t) * p1.z + Math.pow(t, 2) * p2.z return new THREE.Vector3(x,y,z)
[ { "context": " 'articles', {\n author_id: aid = ObjectId '4d8cd73191a5c50ce220002a'\n title: 'Hello Wurld'\n }, ->\n ", "end": 1702, "score": 0.8705459833145142, "start": 1678, "tag": "KEY", "value": "4d8cd73191a5c50ce220002a" }, { "context": " fabricate 'a...
src/api/apps/articles/test/model/index/retrieval.test.coffee
artsyjian/positron
0
_ = require 'underscore' moment = require 'moment' { db, fabricate, empty, fixtures } = require '../../../../../test/helpers/db' Article = require '../../../model/index' { ObjectId } = require 'mongojs' express = require 'express' fabricateGravity = require('@artsy/antigravity').fabricate gravity = require('@artsy/antigravity').server app = require('express')() bodyParser = require 'body-parser' sinon = require 'sinon' search = require '../../../../../lib/elasticsearch' describe 'Article Retrieval', -> before (done) -> app.use '/__gravity', gravity @server = app.listen 5000, -> search.client.indices.create index: 'articles_' + process.env.NODE_ENV , -> done() after (done) -> @server.close() search.client.indices.delete index: 'articles_' + process.env.NODE_ENV , -> done() beforeEach (done) -> empty -> fabricate 'articles', _.times(10, -> {}), -> done() describe '#where', -> it 'can return all articles along with total and counts', (done) -> Article.where { count: true }, (err, res) -> { total, count, results } = res total.should.equal 10 count.should.equal 10 results[0].title.should.equal 'Top Ten Booths' done() it 'can return all articles along with total and counts', (done) -> Article.where {}, (err, res) -> { total, count, results } = res total?.should.be.false() count?.should.be.false() results[0].title.should.equal 'Top Ten Booths' done() it 'can return articles by an author', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: 'Hello Wurld' }, -> Article.where { author_id: aid.toString(), count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can return articles by published', (done) -> fabricate 'articles', _.times(3, -> { published: false, title: 'Moo baz' }), -> Article.where { published: false, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 3 results[0].title.should.equal 'Moo baz' done() it 'can change skip and limit', (done) -> fabricate 'articles', [ { title: 'Hello Wurld' } { title: 'Foo Baz' } ], -> Article.where { offset: 1, limit: 3 }, (err, { results }) -> results[0].title.should.equal 'Hello Wurld' done() it 'sorts by -updated_at by default', (done) -> fabricate 'articles', [ { title: 'Hello Wurld', updated_at: moment().add(1, 'days').format() } ], -> Article.where {}, (err, { results }) -> results[0].title.should.equal 'Hello Wurld' done() it 'can find articles featured to an artist', (done) -> fabricate 'articles', [ { title: 'Foo' featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Bar' primary_featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz' featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] primary_featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { artist_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'BarBazFoo' done() ) it 'can find articles featured to an artwork', (done) -> fabricate 'articles', [ { title: 'Foo' featured_artwork_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz' featured_artwork_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { artwork_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'BazFoo' done() ) it 'can find articles sorted by an attr', (done) -> db.articles.drop -> fabricate 'articles', [ { title: 'C' }, { title: 'A' }, { title: 'B' } ], -> Article.where( { sort: '-title' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.containEql 'ABC' done() ) it 'can find articles added to multiple fairs', (done) -> fabricate 'articles', [ { title: 'C', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'A', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'B', fair_ids: [ObjectId('4dc98d149a96300001003032')] } ], -> Article.where( { fair_ids: ['4dc98d149a96300001003033', '4dc98d149a96300001003032'] } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'ABC' done() ) it 'can find articles by a fair', (done) -> fabricate 'articles', [ { title: 'C', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'A', fair_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { fair_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'AC' done() ) it 'can return articles by a fair programming id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: 'Hello Wurld' fair_programming_ids: [ ObjectId('52617c6c8b3b81f094000013') ] }, -> Article.where { fair_programming_id: '52617c6c8b3b81f094000013', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can return articles by a fair artsy id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: 'Hello Wurld' fair_artsy_ids: [ ObjectId('53da550a726169083c0a0700') ] }, -> Article.where { fair_artsy_id: '53da550a726169083c0a0700', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can return articles by a fair about id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: 'Hello Wurld' fair_about_ids: [ ObjectId('53da550a726169083c0a0700') ] }, -> Article.where { fair_about_id: '53da550a726169083c0a0700', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can find articles added to a partner', (done) -> fabricate 'articles', [ { title: 'Foo', partner_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Bar', partner_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz', partner_ids: [ObjectId('4dc98d149a96300001003031')] } ], -> Article.where( { partner_id: '4dc98d149a96300001003033' } (err, { results }) -> _.pluck(results, 'title').sort().join('').should.equal 'BarFoo' done() ) it 'can find articles by query', (done) -> fabricate 'articles', [ { thumbnail_title: 'Foo' } { thumbnail_title: 'Bar' } { thumbnail_title: 'Baz' } ], -> Article.where( { q: 'fo' } (err, {results}) -> results[0].thumbnail_title.should.equal 'Foo' done() ) it 'can find articles by all_by_author', (done) -> fabricate 'articles', [ { author_id: ObjectId '4d8cd73191a5c50ce220002a' contributing_authors: [ {id: ObjectId '4d8cd73191a5c50ce220002b'}] title: 'Hello Wurld' } { author_id: ObjectId '4d8cd73191a5c50ce220002b' title: 'Hello Waaarld' } ], -> Article.where { all_by_author: '4d8cd73191a5c50ce220002b', count: true }, (err, res) -> { total, count, results } = res total.should.equal 12 count.should.equal 2 results[0].title.should.equal 'Hello Waaarld' results[1].title.should.equal 'Hello Wurld' done() it 'can find articles by super article', (done) -> fabricate 'articles', [ { author_id: ObjectId '4d8cd73191a5c50ce220002a' title: 'Hello Wurld' is_super_article: false } { author_id: ObjectId '4d8cd73191a5c50ce220002b' title: 'Hello Waaarldie' is_super_article: true } { author_id: ObjectId '4d8cd73191a5c50ce220002b' title: 'Hello Waaarld' } ], -> Article.where { is_super_article: true, count: true }, (err, res) -> { total, count, results } = res total.should.equal 13 count.should.equal 1 results[0].title.should.equal 'Hello Waaarldie' done() it 'can find super article by article (opposite of the above test!)', (done) -> superArticleId = ObjectId '4d7ab73191a5c50ce220001c' childArticleId = ObjectId '4d8cd73191a5c50ce111111a' fabricate 'articles', [ { _id: childArticleId author_id: ObjectId '4d8cd73191a5c50ce220002a' title: 'Child Article' is_super_article: false } { _id: superArticleId author_id: ObjectId '4d8cd73191a5c50ce220002b' title: 'Super Article' is_super_article: true super_article: related_articles: [childArticleId] } ], -> Article.where { super_article_for: childArticleId.toString(), count: true }, (err, res) -> { total, count, results } = res total.should.equal 12 count.should.equal 1 results[0].title.should.equal 'Super Article' done() it 'can find articles by tags', (done) -> fabricate 'articles', [ { author_id: ObjectId '4d8cd73191a5c50ce220002a' tags: [ 'pickle', 'samosa' ] title: 'Hello Wuuuurld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002b' tags: [ 'pickle', 'muffin' ] title: 'Hello Waaarld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002c' tags: [ 'muffin', 'lentils' ] title: 'Hello Weeeerld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002e' tags: [ 'radio', 'pixels' ] title: 'Hello I am Weiiird - Electronics' } ], -> Article.where { tags: ['pickle', 'muffin'], count: true }, (err, res) -> { total, count, results } = res total.should.equal 14 count.should.equal 3 results[0].title.should.equal 'Hello Weeeerld - Food' results[1].title.should.equal 'Hello Waaarld - Food' results[2].title.should.equal 'Hello Wuuuurld - Food' done() it 'can find articles by tracking_tags', (done) -> fabricate 'articles', [ { author_id: ObjectId '4d8cd73191a5c50ce220002a' tracking_tags: [ 'video', 'evergreen' ] title: 'The Shanghai Art Project That’s Working to Save Us from a Dystopian Future' } { author_id: ObjectId '4d8cd73191a5c50ce220002b' tracking_tags: [ 'video', 'evergreen' ] title: '$448 Million Christie’s Post-War and Contemporary Sale Led by Bacon and Twombly' } { author_id: ObjectId '4d8cd73191a5c50ce220002c' tracking_tags: [ 'podcast', 'evergreen' ] title: '8 Works to Collect at ARCOlisboa' } { author_id: ObjectId '4d8cd73191a5c50ce220002e' tracking_tags: [ 'op-eds', 'explainers' ] title: 'NYC Releases Data That Will Help Shape the City’s Cultural Future' } ], -> Article.where { tracking_tags: ['video', 'evergreen'], count: true }, (err, res) -> { total, count, results } = res total.should.equal 14 count.should.equal 3 results[0].title.should.equal '8 Works to Collect at ARCOlisboa' results[1].title.should.equal '$448 Million Christie’s Post-War and Contemporary Sale Led by Bacon and Twombly' results[2].title.should.equal 'The Shanghai Art Project That’s Working to Save Us from a Dystopian Future' done() it 'can find articles by artist biography', (done) -> fabricate 'articles', [ { title: 'Hello Wurld' published: true biography_for_artist_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true biography_for_artist_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can find articles by channel_id', (done) -> fabricate 'articles', [ { title: 'Hello Wurld' published: true channel_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true channel_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can find articles by partner_channel_id', (done) -> fabricate 'articles', [ { title: 'Hello Wurld' published: true partner_channel_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true channel_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can find articles by scheduled', (done) -> fabricate 'articles', [ { title: 'Hello Wurld' published: false scheduled_publish_at: '555' } ], -> Article.where { scheduled: true count: true published: false }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can return articles by indexable', (done) -> fabricate 'articles', _.times(3, -> { indexable: false, title: 'Moo baz' }), -> Article.where { indexable: true, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 10 results[0].title.should.not.equal 'Moo baz' done() it 'can return articles by not indexable', (done) -> fabricate 'articles', _.times(3, -> { indexable: false, title: 'Moo baz' }), -> Article.where { indexable: false, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 3 results[0].title.should.equal 'Moo baz' done() it 'can omit articles', (done) -> fabricate 'articles', [ { title: 'Hello Wurld' _id: ObjectId('5086df098523e60002000018') published: true } ], -> Article.where { omit: ['5086df098523e60002000018'], count: true }, (err, { total, count, results }) -> total.should.equal 11 count.should.equal 10 done() describe '#find', -> it 'finds an article by an id string', (done) -> fabricate 'articles', { _id: ObjectId('5086df098523e60002000018') }, -> Article.find '5086df098523e60002000018', (err, article) -> article._id.toString().should.equal '5086df098523e60002000018' done() it 'can lookup an article by slug', (done) -> fabricate 'articles', { _id: ObjectId('5086df098523e60002000018') slugs: ['foo-bar'] }, -> Article.find 'foo-bar', (err, article) -> article._id.toString().should.equal '5086df098523e60002000018' done()
149738
_ = require 'underscore' moment = require 'moment' { db, fabricate, empty, fixtures } = require '../../../../../test/helpers/db' Article = require '../../../model/index' { ObjectId } = require 'mongojs' express = require 'express' fabricateGravity = require('@artsy/antigravity').fabricate gravity = require('@artsy/antigravity').server app = require('express')() bodyParser = require 'body-parser' sinon = require 'sinon' search = require '../../../../../lib/elasticsearch' describe 'Article Retrieval', -> before (done) -> app.use '/__gravity', gravity @server = app.listen 5000, -> search.client.indices.create index: 'articles_' + process.env.NODE_ENV , -> done() after (done) -> @server.close() search.client.indices.delete index: 'articles_' + process.env.NODE_ENV , -> done() beforeEach (done) -> empty -> fabricate 'articles', _.times(10, -> {}), -> done() describe '#where', -> it 'can return all articles along with total and counts', (done) -> Article.where { count: true }, (err, res) -> { total, count, results } = res total.should.equal 10 count.should.equal 10 results[0].title.should.equal 'Top Ten Booths' done() it 'can return all articles along with total and counts', (done) -> Article.where {}, (err, res) -> { total, count, results } = res total?.should.be.false() count?.should.be.false() results[0].title.should.equal 'Top Ten Booths' done() it 'can return articles by an author', (done) -> fabricate 'articles', { author_id: aid = ObjectId '<KEY>' title: 'Hello Wurld' }, -> Article.where { author_id: aid.toString(), count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can return articles by published', (done) -> fabricate 'articles', _.times(3, -> { published: false, title: 'Moo baz' }), -> Article.where { published: false, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 3 results[0].title.should.equal 'Moo baz' done() it 'can change skip and limit', (done) -> fabricate 'articles', [ { title: 'Hello <NAME>' } { title: 'Foo Baz' } ], -> Article.where { offset: 1, limit: 3 }, (err, { results }) -> results[0].title.should.equal 'Hello W<NAME>' done() it 'sorts by -updated_at by default', (done) -> fabricate 'articles', [ { title: '<NAME>', updated_at: moment().add(1, 'days').format() } ], -> Article.where {}, (err, { results }) -> results[0].title.should.equal 'Hello W<NAME>' done() it 'can find articles featured to an artist', (done) -> fabricate 'articles', [ { title: 'Foo' featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Bar' primary_featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz' featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] primary_featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { artist_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'BarBazFoo' done() ) it 'can find articles featured to an artwork', (done) -> fabricate 'articles', [ { title: 'Foo' featured_artwork_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz' featured_artwork_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { artwork_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'BazFoo' done() ) it 'can find articles sorted by an attr', (done) -> db.articles.drop -> fabricate 'articles', [ { title: 'C' }, { title: 'A' }, { title: 'B' } ], -> Article.where( { sort: '-title' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.containEql 'ABC' done() ) it 'can find articles added to multiple fairs', (done) -> fabricate 'articles', [ { title: 'C', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'A', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'B', fair_ids: [ObjectId('4dc98d149a96300001003032')] } ], -> Article.where( { fair_ids: ['4dc98d149a96300001003033', '4dc98d149a96300001003032'] } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'ABC' done() ) it 'can find articles by a fair', (done) -> fabricate 'articles', [ { title: 'C', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'A', fair_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { fair_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'AC' done() ) it 'can return articles by a fair programming id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: '<NAME> <NAME>' fair_programming_ids: [ ObjectId('52617c6c8b3b81f094000013') ] }, -> Article.where { fair_programming_id: '52617c6c8b3b81f094000013', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal '<NAME> <NAME>' done() it 'can return articles by a fair artsy id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: '<NAME>' fair_artsy_ids: [ ObjectId('53da550a726169083c0a0700') ] }, -> Article.where { fair_artsy_id: '53da550a726169083c0a0700', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal '<NAME> <NAME>' done() it 'can return articles by a fair about id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '<KEY> <PASSWORD>' title: '<NAME>' fair_about_ids: [ ObjectId('53da550a726169083c0a0700') ] }, -> Article.where { fair_about_id: '53da550a726169083c0a0700', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello <NAME>' done() it 'can find articles added to a partner', (done) -> fabricate 'articles', [ { title: 'Foo', partner_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Bar', partner_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz', partner_ids: [ObjectId('4dc98d149a96300001003031')] } ], -> Article.where( { partner_id: '4dc98d149a96300001003033' } (err, { results }) -> _.pluck(results, 'title').sort().join('').should.equal 'BarFoo' done() ) it 'can find articles by query', (done) -> fabricate 'articles', [ { thumbnail_title: 'Foo' } { thumbnail_title: 'Bar' } { thumbnail_title: 'Baz' } ], -> Article.where( { q: 'fo' } (err, {results}) -> results[0].thumbnail_title.should.equal 'Foo' done() ) it 'can find articles by all_by_author', (done) -> fabricate 'articles', [ { author_id: ObjectId '<KEY>' contributing_authors: [ {id: ObjectId '<PASSWORD>'}] title: 'Hello Wurld' } { author_id: ObjectId '<PASSWORD>' title: 'Hello W<NAME>' } ], -> Article.where { all_by_author: '<PASSWORD>', count: true }, (err, res) -> { total, count, results } = res total.should.equal 12 count.should.equal 2 results[0].title.should.equal 'Hello Waaarld' results[1].title.should.equal 'Hello Wurld' done() it 'can find articles by super article', (done) -> fabricate 'articles', [ { author_id: ObjectId '<KEY>' title: 'Hello <NAME>' is_super_article: false } { author_id: ObjectId '<PASSWORD>' title: '<NAME>' is_super_article: true } { author_id: ObjectId '<KEY> <PASSWORD>' title: 'Hello <NAME>' } ], -> Article.where { is_super_article: true, count: true }, (err, res) -> { total, count, results } = res total.should.equal 13 count.should.equal 1 results[0].title.should.equal 'Hello Waaarld<NAME>' done() it 'can find super article by article (opposite of the above test!)', (done) -> superArticleId = ObjectId '4d7ab73191a5c50ce220001c' childArticleId = ObjectId '4d8cd73191a5c50ce111111a' fabricate 'articles', [ { _id: childArticleId author_id: ObjectId '4<PASSWORD>' title: 'Child Article' is_super_article: false } { _id: superArticleId author_id: ObjectId '4d<PASSWORD>' title: 'Super Article' is_super_article: true super_article: related_articles: [childArticleId] } ], -> Article.where { super_article_for: childArticleId.toString(), count: true }, (err, res) -> { total, count, results } = res total.should.equal 12 count.should.equal 1 results[0].title.should.equal 'Super Article' done() it 'can find articles by tags', (done) -> fabricate 'articles', [ { author_id: ObjectId '<KEY> <PASSWORD>' tags: [ 'pickle', 'samosa' ] title: 'Hello Wuuuurld - Food' } { author_id: ObjectId '<KEY> <PASSWORD>0002b' tags: [ 'pickle', 'muffin' ] title: 'Hello Waaarld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002c' tags: [ 'muffin', 'lentils' ] title: 'Hello Weeeerld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002e' tags: [ 'radio', 'pixels' ] title: 'Hello I am Weiiird - Electronics' } ], -> Article.where { tags: ['pickle', 'muffin'], count: true }, (err, res) -> { total, count, results } = res total.should.equal 14 count.should.equal 3 results[0].title.should.equal 'Hello Weeeerld - Food' results[1].title.should.equal 'Hello Waaarld - Food' results[2].title.should.equal 'Hello Wuuuurld - Food' done() it 'can find articles by tracking_tags', (done) -> fabricate 'articles', [ { author_id: ObjectId '4d8cd73191a5c50ce220002a' tracking_tags: [ 'video', 'evergreen' ] title: 'The Shanghai Art Project That’s Working to Save Us from a Dystopian Future' } { author_id: ObjectId '4<PASSWORD>' tracking_tags: [ 'video', 'evergreen' ] title: '$448 Million Christie’s Post-War and Contemporary Sale Led by Bacon and Twombly' } { author_id: ObjectId '<PASSWORD>' tracking_tags: [ 'podcast', 'evergreen' ] title: '8 Works to Collect at ARCOlisboa' } { author_id: ObjectId '4d8cd73191a5c50ce220002e' tracking_tags: [ 'op-eds', 'explainers' ] title: 'NYC Releases Data That Will Help Shape the City’s Cultural Future' } ], -> Article.where { tracking_tags: ['video', 'evergreen'], count: true }, (err, res) -> { total, count, results } = res total.should.equal 14 count.should.equal 3 results[0].title.should.equal '8 Works to Collect at ARCOlisboa' results[1].title.should.equal '$448 Million Christie’s Post-War and Contemporary Sale Led by Bacon and Twombly' results[2].title.should.equal 'The Shanghai Art Project That’s Working to Save Us from a Dystopian Future' done() it 'can find articles by artist biography', (done) -> fabricate 'articles', [ { title: '<NAME>' published: true biography_for_artist_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true biography_for_artist_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello <NAME>' done() it 'can find articles by channel_id', (done) -> fabricate 'articles', [ { title: '<NAME> <NAME>' published: true channel_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true channel_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello W<NAME>' done() it 'can find articles by partner_channel_id', (done) -> fabricate 'articles', [ { title: '<NAME>' published: true partner_channel_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true channel_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello <NAME>' done() it 'can find articles by scheduled', (done) -> fabricate 'articles', [ { title: '<NAME>' published: false scheduled_publish_at: '555' } ], -> Article.where { scheduled: true count: true published: false }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello <NAME>' done() it 'can return articles by indexable', (done) -> fabricate 'articles', _.times(3, -> { indexable: false, title: 'Moo baz' }), -> Article.where { indexable: true, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 10 results[0].title.should.not.equal 'Moo baz' done() it 'can return articles by not indexable', (done) -> fabricate 'articles', _.times(3, -> { indexable: false, title: 'Moo baz' }), -> Article.where { indexable: false, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 3 results[0].title.should.equal 'Moo baz' done() it 'can omit articles', (done) -> fabricate 'articles', [ { title: '<NAME>' _id: ObjectId('5086df098523e60002000018') published: true } ], -> Article.where { omit: ['5086df098523e60002000018'], count: true }, (err, { total, count, results }) -> total.should.equal 11 count.should.equal 10 done() describe '#find', -> it 'finds an article by an id string', (done) -> fabricate 'articles', { _id: ObjectId('5086df098523e60002000018') }, -> Article.find '5086df098523e60002000018', (err, article) -> article._id.toString().should.equal '5086df098523e60002000018' done() it 'can lookup an article by slug', (done) -> fabricate 'articles', { _id: ObjectId('5086df098523e60002000018') slugs: ['foo-bar'] }, -> Article.find 'foo-bar', (err, article) -> article._id.toString().should.equal '5086df098523e60002000018' done()
true
_ = require 'underscore' moment = require 'moment' { db, fabricate, empty, fixtures } = require '../../../../../test/helpers/db' Article = require '../../../model/index' { ObjectId } = require 'mongojs' express = require 'express' fabricateGravity = require('@artsy/antigravity').fabricate gravity = require('@artsy/antigravity').server app = require('express')() bodyParser = require 'body-parser' sinon = require 'sinon' search = require '../../../../../lib/elasticsearch' describe 'Article Retrieval', -> before (done) -> app.use '/__gravity', gravity @server = app.listen 5000, -> search.client.indices.create index: 'articles_' + process.env.NODE_ENV , -> done() after (done) -> @server.close() search.client.indices.delete index: 'articles_' + process.env.NODE_ENV , -> done() beforeEach (done) -> empty -> fabricate 'articles', _.times(10, -> {}), -> done() describe '#where', -> it 'can return all articles along with total and counts', (done) -> Article.where { count: true }, (err, res) -> { total, count, results } = res total.should.equal 10 count.should.equal 10 results[0].title.should.equal 'Top Ten Booths' done() it 'can return all articles along with total and counts', (done) -> Article.where {}, (err, res) -> { total, count, results } = res total?.should.be.false() count?.should.be.false() results[0].title.should.equal 'Top Ten Booths' done() it 'can return articles by an author', (done) -> fabricate 'articles', { author_id: aid = ObjectId 'PI:KEY:<KEY>END_PI' title: 'Hello Wurld' }, -> Article.where { author_id: aid.toString(), count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello Wurld' done() it 'can return articles by published', (done) -> fabricate 'articles', _.times(3, -> { published: false, title: 'Moo baz' }), -> Article.where { published: false, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 3 results[0].title.should.equal 'Moo baz' done() it 'can change skip and limit', (done) -> fabricate 'articles', [ { title: 'Hello PI:NAME:<NAME>END_PI' } { title: 'Foo Baz' } ], -> Article.where { offset: 1, limit: 3 }, (err, { results }) -> results[0].title.should.equal 'Hello WPI:NAME:<NAME>END_PI' done() it 'sorts by -updated_at by default', (done) -> fabricate 'articles', [ { title: 'PI:NAME:<NAME>END_PI', updated_at: moment().add(1, 'days').format() } ], -> Article.where {}, (err, { results }) -> results[0].title.should.equal 'Hello WPI:NAME:<NAME>END_PI' done() it 'can find articles featured to an artist', (done) -> fabricate 'articles', [ { title: 'Foo' featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Bar' primary_featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz' featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] primary_featured_artist_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { artist_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'BarBazFoo' done() ) it 'can find articles featured to an artwork', (done) -> fabricate 'articles', [ { title: 'Foo' featured_artwork_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz' featured_artwork_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { artwork_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'BazFoo' done() ) it 'can find articles sorted by an attr', (done) -> db.articles.drop -> fabricate 'articles', [ { title: 'C' }, { title: 'A' }, { title: 'B' } ], -> Article.where( { sort: '-title' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.containEql 'ABC' done() ) it 'can find articles added to multiple fairs', (done) -> fabricate 'articles', [ { title: 'C', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'A', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'B', fair_ids: [ObjectId('4dc98d149a96300001003032')] } ], -> Article.where( { fair_ids: ['4dc98d149a96300001003033', '4dc98d149a96300001003032'] } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'ABC' done() ) it 'can find articles by a fair', (done) -> fabricate 'articles', [ { title: 'C', fair_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'A', fair_ids: [ObjectId('4dc98d149a96300001003033')] } ], -> Article.where( { fair_id: '4dc98d149a96300001003033' } (err, {results}) -> _.pluck(results, 'title').sort().join('').should.equal 'AC' done() ) it 'can return articles by a fair programming id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' fair_programming_ids: [ ObjectId('52617c6c8b3b81f094000013') ] }, -> Article.where { fair_programming_id: '52617c6c8b3b81f094000013', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' done() it 'can return articles by a fair artsy id', (done) -> fabricate 'articles', { author_id: aid = ObjectId '4d8cd73191a5c50ce220002a' title: 'PI:NAME:<NAME>END_PI' fair_artsy_ids: [ ObjectId('53da550a726169083c0a0700') ] }, -> Article.where { fair_artsy_id: '53da550a726169083c0a0700', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' done() it 'can return articles by a fair about id', (done) -> fabricate 'articles', { author_id: aid = ObjectId 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' title: 'PI:NAME:<NAME>END_PI' fair_about_ids: [ ObjectId('53da550a726169083c0a0700') ] }, -> Article.where { fair_about_id: '53da550a726169083c0a0700', count: true }, (err, res) -> { total, count, results } = res total.should.equal 11 count.should.equal 1 results[0].title.should.equal 'Hello PI:NAME:<NAME>END_PI' done() it 'can find articles added to a partner', (done) -> fabricate 'articles', [ { title: 'Foo', partner_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Bar', partner_ids: [ObjectId('4dc98d149a96300001003033')] } { title: 'Baz', partner_ids: [ObjectId('4dc98d149a96300001003031')] } ], -> Article.where( { partner_id: '4dc98d149a96300001003033' } (err, { results }) -> _.pluck(results, 'title').sort().join('').should.equal 'BarFoo' done() ) it 'can find articles by query', (done) -> fabricate 'articles', [ { thumbnail_title: 'Foo' } { thumbnail_title: 'Bar' } { thumbnail_title: 'Baz' } ], -> Article.where( { q: 'fo' } (err, {results}) -> results[0].thumbnail_title.should.equal 'Foo' done() ) it 'can find articles by all_by_author', (done) -> fabricate 'articles', [ { author_id: ObjectId 'PI:PASSWORD:<KEY>END_PI' contributing_authors: [ {id: ObjectId 'PI:PASSWORD:<PASSWORD>END_PI'}] title: 'Hello Wurld' } { author_id: ObjectId 'PI:PASSWORD:<PASSWORD>END_PI' title: 'Hello WPI:NAME:<NAME>END_PI' } ], -> Article.where { all_by_author: 'PI:PASSWORD:<PASSWORD>END_PI', count: true }, (err, res) -> { total, count, results } = res total.should.equal 12 count.should.equal 2 results[0].title.should.equal 'Hello Waaarld' results[1].title.should.equal 'Hello Wurld' done() it 'can find articles by super article', (done) -> fabricate 'articles', [ { author_id: ObjectId 'PI:PASSWORD:<KEY>END_PI' title: 'Hello PI:NAME:<NAME>END_PI' is_super_article: false } { author_id: ObjectId 'PI:PASSWORD:<PASSWORD>END_PI' title: 'PI:NAME:<NAME>END_PI' is_super_article: true } { author_id: ObjectId 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' title: 'Hello PI:NAME:<NAME>END_PI' } ], -> Article.where { is_super_article: true, count: true }, (err, res) -> { total, count, results } = res total.should.equal 13 count.should.equal 1 results[0].title.should.equal 'Hello WaaarldPI:NAME:<NAME>END_PI' done() it 'can find super article by article (opposite of the above test!)', (done) -> superArticleId = ObjectId '4d7ab73191a5c50ce220001c' childArticleId = ObjectId '4d8cd73191a5c50ce111111a' fabricate 'articles', [ { _id: childArticleId author_id: ObjectId '4PI:PASSWORD:<PASSWORD>END_PI' title: 'Child Article' is_super_article: false } { _id: superArticleId author_id: ObjectId '4dPI:PASSWORD:<PASSWORD>END_PI' title: 'Super Article' is_super_article: true super_article: related_articles: [childArticleId] } ], -> Article.where { super_article_for: childArticleId.toString(), count: true }, (err, res) -> { total, count, results } = res total.should.equal 12 count.should.equal 1 results[0].title.should.equal 'Super Article' done() it 'can find articles by tags', (done) -> fabricate 'articles', [ { author_id: ObjectId 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' tags: [ 'pickle', 'samosa' ] title: 'Hello Wuuuurld - Food' } { author_id: ObjectId 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI0002b' tags: [ 'pickle', 'muffin' ] title: 'Hello Waaarld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002c' tags: [ 'muffin', 'lentils' ] title: 'Hello Weeeerld - Food' } { author_id: ObjectId '4d8cd73191a5c50ce220002e' tags: [ 'radio', 'pixels' ] title: 'Hello I am Weiiird - Electronics' } ], -> Article.where { tags: ['pickle', 'muffin'], count: true }, (err, res) -> { total, count, results } = res total.should.equal 14 count.should.equal 3 results[0].title.should.equal 'Hello Weeeerld - Food' results[1].title.should.equal 'Hello Waaarld - Food' results[2].title.should.equal 'Hello Wuuuurld - Food' done() it 'can find articles by tracking_tags', (done) -> fabricate 'articles', [ { author_id: ObjectId '4d8cd73191a5c50ce220002a' tracking_tags: [ 'video', 'evergreen' ] title: 'The Shanghai Art Project That’s Working to Save Us from a Dystopian Future' } { author_id: ObjectId '4PI:PASSWORD:<PASSWORD>END_PI' tracking_tags: [ 'video', 'evergreen' ] title: '$448 Million Christie’s Post-War and Contemporary Sale Led by Bacon and Twombly' } { author_id: ObjectId 'PI:PASSWORD:<PASSWORD>END_PI' tracking_tags: [ 'podcast', 'evergreen' ] title: '8 Works to Collect at ARCOlisboa' } { author_id: ObjectId '4d8cd73191a5c50ce220002e' tracking_tags: [ 'op-eds', 'explainers' ] title: 'NYC Releases Data That Will Help Shape the City’s Cultural Future' } ], -> Article.where { tracking_tags: ['video', 'evergreen'], count: true }, (err, res) -> { total, count, results } = res total.should.equal 14 count.should.equal 3 results[0].title.should.equal '8 Works to Collect at ARCOlisboa' results[1].title.should.equal '$448 Million Christie’s Post-War and Contemporary Sale Led by Bacon and Twombly' results[2].title.should.equal 'The Shanghai Art Project That’s Working to Save Us from a Dystopian Future' done() it 'can find articles by artist biography', (done) -> fabricate 'articles', [ { title: 'PI:NAME:<NAME>END_PI' published: true biography_for_artist_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true biography_for_artist_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello PI:NAME:<NAME>END_PI' done() it 'can find articles by channel_id', (done) -> fabricate 'articles', [ { title: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' published: true channel_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true channel_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello WPI:NAME:<NAME>END_PI' done() it 'can find articles by partner_channel_id', (done) -> fabricate 'articles', [ { title: 'PI:NAME:<NAME>END_PI' published: true partner_channel_id: ObjectId '5086df098523e60002000016' } ], -> Article.where { published: true channel_id: '5086df098523e60002000016' count: true }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello PI:NAME:<NAME>END_PI' done() it 'can find articles by scheduled', (done) -> fabricate 'articles', [ { title: 'PI:NAME:<NAME>END_PI' published: false scheduled_publish_at: '555' } ], -> Article.where { scheduled: true count: true published: false }, (err, res) -> { total, count, results } = res count.should.equal 1 results[0].title.should.equal 'Hello PI:NAME:<NAME>END_PI' done() it 'can return articles by indexable', (done) -> fabricate 'articles', _.times(3, -> { indexable: false, title: 'Moo baz' }), -> Article.where { indexable: true, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 10 results[0].title.should.not.equal 'Moo baz' done() it 'can return articles by not indexable', (done) -> fabricate 'articles', _.times(3, -> { indexable: false, title: 'Moo baz' }), -> Article.where { indexable: false, count: true }, (err, { total, count, results }) -> total.should.equal 13 count.should.equal 3 results[0].title.should.equal 'Moo baz' done() it 'can omit articles', (done) -> fabricate 'articles', [ { title: 'PI:NAME:<NAME>END_PI' _id: ObjectId('5086df098523e60002000018') published: true } ], -> Article.where { omit: ['5086df098523e60002000018'], count: true }, (err, { total, count, results }) -> total.should.equal 11 count.should.equal 10 done() describe '#find', -> it 'finds an article by an id string', (done) -> fabricate 'articles', { _id: ObjectId('5086df098523e60002000018') }, -> Article.find '5086df098523e60002000018', (err, article) -> article._id.toString().should.equal '5086df098523e60002000018' done() it 'can lookup an article by slug', (done) -> fabricate 'articles', { _id: ObjectId('5086df098523e60002000018') slugs: ['foo-bar'] }, -> Article.find 'foo-bar', (err, article) -> article._id.toString().should.equal '5086df098523e60002000018' done()
[ { "context": "derstood\n# MUST be ignored. See Sections 3.1.3.6, 3.3.2.11, 5.1, and 7.4 for additional\n# Claims defined by ", "end": 6410, "score": 0.992071270942688, "start": 6402, "tag": "IP_ADDRESS", "value": "3.3.2.11" } ]
test/unit/models/idTokenSpec.coffee
LorianeE/connect
331
# Test dependencies cwd = process.cwd() path = require 'path' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect # Assertions chai.use sinonChai chai.should() # Code under test IDToken = require path.join cwd, 'models/IDToken' JWT = require 'anvil-connect-jwt' base64url = require 'base64url' # OpenID Connect Core 1.0 # # http://openid.net/specs/openid-connect-core-1_0.html#IDToken # # 2. ID Token # # The primary extension that OpenID Connect makes to OAuth 2.0 to enable # End-Users to be Authenticated is the ID Token data structure. The ID Token is a # security token that contains Claims about the Authentication of an End-User by # an Authorization Server when using a Client, and potentially other requested # Claims. The ID Token is represented as a JSON Web Token (JWT) [JWT]. # # The following Claims are used within the ID Token for all OAuth 2.0 flows # used by OpenID Connect: # # iss # REQUIRED. Issuer Identifier for the Issuer of the response. The iss # value is a case sensitive URL using the https scheme that contains scheme, # host, and optionally, port number and path components and no query or # fragment components. # sub # REQUIRED. Subject Identifier. A locally unique and never reassigned # identifier within the Issuer for the End-User, which is intended to be # consumed by the Client, e.g., 24400320 or # AItOawmwtWwcT0k51BayewNvutrJUqsvl6qs7A4. It MUST NOT exceed 255 ASCII # characters in length. The sub value is a case sensitive string. # aud # REQUIRED. Audience(s) that this ID Token is intended for. It MUST # contain the OAuth 2.0 client_id of the Relying Party as an audience value. # It MAY also contain identifiers for other audiences. In the general # case, the aud value is an array of case sensitive strings. In the # common special case when there is one audience, the aud value MAY be a # single case sensitive string. # exp # REQUIRED. Expiration time on or after which the ID Token MUST NOT be # accepted for processing. The processing of this parameter requires that # the current date/time MUST be before the expiration date/time listed in # the value. Implementers MAY provide for some small leeway, usually no more # than a few minutes, to account for clock skew. Its value is a JSON number # representing the number of seconds from 1970-01-01T0:0:0Z as measured in # UTC until the date/time. See RFC 3339 [RFC3339] for details regarding # date/times in general and UTC in particular. # iat # REQUIRED. Time at which the JWT was issued. Its value is a JSON number # representing the number of seconds from 1970-01-01T0:0:0Z as measured in # UTC until the date/time. # auth_time # Time when the End-User authentication occurred. Its value is a JSON # number representing the number of seconds from 1970-01-01T0:0:0Z as # measured in UTC until the date/time. When a max_age request is made or # when auth_time is requested as an Essential Claim, then this Claim is # REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim # semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time # response parameter.) # nonce # String value used to associate a Client session with an ID Token, and # to mitigate replay attacks. The value is passed through unmodified from # the Authentication Request to the ID Token. If present in the ID Token, # Clients MUST verify that the nonce Claim Value is equal to the value of # the nonce parameter sent in the Authentication Request. If present in the # Authentication Request, Authorization Servers MUST include a nonce Claim # in the ID Token with the Claim Value being the nonce value sent in the # Authentication Request. Authorization Servers SHOULD perform no other # processing on nonce values used. The nonce value is a case sensitive # string. # acr # OPTIONAL. Authentication Context Class Reference. String specifying an # Authentication Context Class Reference value that identifies the # Authentication Context Class that the authentication performed satisfied. # The value "0" indicates the End-User authentication did not meet the # requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a # long-lived browser cookie, for instance, is one example where the use of # "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used # to authorize access to any resource of any monetary value. (This # corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An # absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as # the acr value; registered names MUST NOT be used with a different meaning # than that which is registered. Parties using this claim will need to agree # upon the meanings of the values used, which may be context-specific. The # acr value is a case sensitive string. # amr # OPTIONAL. Authentication Methods References. JSON array of strings that # are identifiers for authentication methods used in the authentication. For # instance, values might indicate that both password and OTP authentication # methods were used. The definition of particular values to be used in the # amr Claim is beyond the scope of this specification. Parties using this # claim will need to agree upon the meanings of the values used, which may be # context-specific. The amr value is an array of case sensitive strings. # azp # OPTIONAL. Authorized party - the party to which the ID Token was # issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. # This Claim is only needed when the ID Token has a single audience value # and that audience is different than the authorized party. It MAY be # included even when the authorized party is the same as the sole audience. # The azp value is a case sensitive string containing a StringOrURI value. # # ID Tokens MAY contain other Claims. Any Claims used that are not understood # MUST be ignored. See Sections 3.1.3.6, 3.3.2.11, 5.1, and 7.4 for additional # Claims defined by this specification. # # ID Tokens MUST be signed using JWS [JWS] and optionally both signed and then # encrypted using JWS [JWS] and JWE [JWE] respectively, thereby providing # authentication, integrity, non-repudiation, and optionally, confidentiality, # per Section 16.14. If the ID Token is encrypted, it MUST be signed then # encrypted, with the result being a Nested JWT, as defined in [JWT]. ID Tokens # MUST NOT use none as the alg value unless the Response Type used returns no ID # Token from the Authorization Endpoint (such as when using the Authorization # Code Flow) and the Client explicitly requested the use of none at Registration # time. # # ID Tokens SHOULD NOT use the JWS or JWE x5u, x5c, jku, or jwk header # parameter fields. Instead, references to keys used are communicated in advance # using Discovery and Registration parameters, per Section 10. # # The following is a non-normative example of the set of Claims (the JWT Claims # Set) in an ID Token: # # { # "iss": "https://server.example.com", # "sub": "24400320", # "aud": "s6BhdRkqt3", # "nonce": "n-0S6_WzA2Mj", # "exp": 1311281970, # "iat": 1311280970, # "auth_time": 1311280969, # "acr": "urn:mace:incommon:iap:silver" # } describe 'ID Token', -> it 'should be a subclass of JWT', -> IDToken.super.should.equal JWT describe 'header', -> it 'must not use "none" as "alg" value', -> expect(-> new IDToken({}, { alg: 'none'})).to.throw Error it 'should not use "x5u", "x5c", "jku", or "jwk" header parameter fields', -> header = alg: 'RS256' x5u: 'x5u' x5c: 'x5c' jku: 'jku' jwk: 'jwk' payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' exp: Date.now() iat: Date.now() token = new IDToken payload, header expect(token.header.x5u).to.be.undefined expect(token.header.x5c).to.be.undefined expect(token.header.jku).to.be.undefined expect(token.header.jwk).to.be.undefined describe 'claims', -> it 'should require "iss" Issuer Identifier', -> IDToken.registeredClaims.iss.required.should.be.true it 'should require "sub" Subject Identifier', -> IDToken.registeredClaims.sub.required.should.be.true it 'should require "aud" Audience array or string' it 'should require "exp" Expiration time', -> IDToken.registeredClaims.exp.required.should.be.true it 'should default "exp" to 24 hours', -> payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' token = new IDToken payload token.payload.exp.should.be.a('number') new Date(token.payload.exp * 1000).getDay().should.not.equal new Date().getDay() it 'should require "iat" Issued time', -> IDToken.registeredClaims.iat.required.should.be.true it 'should default "iat" to now', -> payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' exp: Date.now() token = new IDToken payload token.payload.iat.should.be.a('number') it 'should conditionally require "auth_time"' it 'should include "nonce"', -> IDToken.registeredClaims.nonce.should.not.be.undefined it 'should optionally include "acr"', -> IDToken.registeredClaims.acr.should.not.be.undefined it 'should optionally include "amr"', -> IDToken.registeredClaims.amr.should.not.be.undefined it 'should optionally include "azp"' it 'should optionally include other claims defined by the specification' describe 'JWT encoded representation', -> it 'must be signed using JWS' describe 'encrypted representation', -> it 'must be a nested JWT' it 'must be signed using JWS' describe 'persistence', -> describe 'logging', -> describe 'issuance', ->
9163
# Test dependencies cwd = process.cwd() path = require 'path' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect # Assertions chai.use sinonChai chai.should() # Code under test IDToken = require path.join cwd, 'models/IDToken' JWT = require 'anvil-connect-jwt' base64url = require 'base64url' # OpenID Connect Core 1.0 # # http://openid.net/specs/openid-connect-core-1_0.html#IDToken # # 2. ID Token # # The primary extension that OpenID Connect makes to OAuth 2.0 to enable # End-Users to be Authenticated is the ID Token data structure. The ID Token is a # security token that contains Claims about the Authentication of an End-User by # an Authorization Server when using a Client, and potentially other requested # Claims. The ID Token is represented as a JSON Web Token (JWT) [JWT]. # # The following Claims are used within the ID Token for all OAuth 2.0 flows # used by OpenID Connect: # # iss # REQUIRED. Issuer Identifier for the Issuer of the response. The iss # value is a case sensitive URL using the https scheme that contains scheme, # host, and optionally, port number and path components and no query or # fragment components. # sub # REQUIRED. Subject Identifier. A locally unique and never reassigned # identifier within the Issuer for the End-User, which is intended to be # consumed by the Client, e.g., 24400320 or # AItOawmwtWwcT0k51BayewNvutrJUqsvl6qs7A4. It MUST NOT exceed 255 ASCII # characters in length. The sub value is a case sensitive string. # aud # REQUIRED. Audience(s) that this ID Token is intended for. It MUST # contain the OAuth 2.0 client_id of the Relying Party as an audience value. # It MAY also contain identifiers for other audiences. In the general # case, the aud value is an array of case sensitive strings. In the # common special case when there is one audience, the aud value MAY be a # single case sensitive string. # exp # REQUIRED. Expiration time on or after which the ID Token MUST NOT be # accepted for processing. The processing of this parameter requires that # the current date/time MUST be before the expiration date/time listed in # the value. Implementers MAY provide for some small leeway, usually no more # than a few minutes, to account for clock skew. Its value is a JSON number # representing the number of seconds from 1970-01-01T0:0:0Z as measured in # UTC until the date/time. See RFC 3339 [RFC3339] for details regarding # date/times in general and UTC in particular. # iat # REQUIRED. Time at which the JWT was issued. Its value is a JSON number # representing the number of seconds from 1970-01-01T0:0:0Z as measured in # UTC until the date/time. # auth_time # Time when the End-User authentication occurred. Its value is a JSON # number representing the number of seconds from 1970-01-01T0:0:0Z as # measured in UTC until the date/time. When a max_age request is made or # when auth_time is requested as an Essential Claim, then this Claim is # REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim # semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time # response parameter.) # nonce # String value used to associate a Client session with an ID Token, and # to mitigate replay attacks. The value is passed through unmodified from # the Authentication Request to the ID Token. If present in the ID Token, # Clients MUST verify that the nonce Claim Value is equal to the value of # the nonce parameter sent in the Authentication Request. If present in the # Authentication Request, Authorization Servers MUST include a nonce Claim # in the ID Token with the Claim Value being the nonce value sent in the # Authentication Request. Authorization Servers SHOULD perform no other # processing on nonce values used. The nonce value is a case sensitive # string. # acr # OPTIONAL. Authentication Context Class Reference. String specifying an # Authentication Context Class Reference value that identifies the # Authentication Context Class that the authentication performed satisfied. # The value "0" indicates the End-User authentication did not meet the # requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a # long-lived browser cookie, for instance, is one example where the use of # "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used # to authorize access to any resource of any monetary value. (This # corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An # absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as # the acr value; registered names MUST NOT be used with a different meaning # than that which is registered. Parties using this claim will need to agree # upon the meanings of the values used, which may be context-specific. The # acr value is a case sensitive string. # amr # OPTIONAL. Authentication Methods References. JSON array of strings that # are identifiers for authentication methods used in the authentication. For # instance, values might indicate that both password and OTP authentication # methods were used. The definition of particular values to be used in the # amr Claim is beyond the scope of this specification. Parties using this # claim will need to agree upon the meanings of the values used, which may be # context-specific. The amr value is an array of case sensitive strings. # azp # OPTIONAL. Authorized party - the party to which the ID Token was # issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. # This Claim is only needed when the ID Token has a single audience value # and that audience is different than the authorized party. It MAY be # included even when the authorized party is the same as the sole audience. # The azp value is a case sensitive string containing a StringOrURI value. # # ID Tokens MAY contain other Claims. Any Claims used that are not understood # MUST be ignored. See Sections 3.1.3.6, 172.16.58.3, 5.1, and 7.4 for additional # Claims defined by this specification. # # ID Tokens MUST be signed using JWS [JWS] and optionally both signed and then # encrypted using JWS [JWS] and JWE [JWE] respectively, thereby providing # authentication, integrity, non-repudiation, and optionally, confidentiality, # per Section 16.14. If the ID Token is encrypted, it MUST be signed then # encrypted, with the result being a Nested JWT, as defined in [JWT]. ID Tokens # MUST NOT use none as the alg value unless the Response Type used returns no ID # Token from the Authorization Endpoint (such as when using the Authorization # Code Flow) and the Client explicitly requested the use of none at Registration # time. # # ID Tokens SHOULD NOT use the JWS or JWE x5u, x5c, jku, or jwk header # parameter fields. Instead, references to keys used are communicated in advance # using Discovery and Registration parameters, per Section 10. # # The following is a non-normative example of the set of Claims (the JWT Claims # Set) in an ID Token: # # { # "iss": "https://server.example.com", # "sub": "24400320", # "aud": "s6BhdRkqt3", # "nonce": "n-0S6_WzA2Mj", # "exp": 1311281970, # "iat": 1311280970, # "auth_time": 1311280969, # "acr": "urn:mace:incommon:iap:silver" # } describe 'ID Token', -> it 'should be a subclass of JWT', -> IDToken.super.should.equal JWT describe 'header', -> it 'must not use "none" as "alg" value', -> expect(-> new IDToken({}, { alg: 'none'})).to.throw Error it 'should not use "x5u", "x5c", "jku", or "jwk" header parameter fields', -> header = alg: 'RS256' x5u: 'x5u' x5c: 'x5c' jku: 'jku' jwk: 'jwk' payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' exp: Date.now() iat: Date.now() token = new IDToken payload, header expect(token.header.x5u).to.be.undefined expect(token.header.x5c).to.be.undefined expect(token.header.jku).to.be.undefined expect(token.header.jwk).to.be.undefined describe 'claims', -> it 'should require "iss" Issuer Identifier', -> IDToken.registeredClaims.iss.required.should.be.true it 'should require "sub" Subject Identifier', -> IDToken.registeredClaims.sub.required.should.be.true it 'should require "aud" Audience array or string' it 'should require "exp" Expiration time', -> IDToken.registeredClaims.exp.required.should.be.true it 'should default "exp" to 24 hours', -> payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' token = new IDToken payload token.payload.exp.should.be.a('number') new Date(token.payload.exp * 1000).getDay().should.not.equal new Date().getDay() it 'should require "iat" Issued time', -> IDToken.registeredClaims.iat.required.should.be.true it 'should default "iat" to now', -> payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' exp: Date.now() token = new IDToken payload token.payload.iat.should.be.a('number') it 'should conditionally require "auth_time"' it 'should include "nonce"', -> IDToken.registeredClaims.nonce.should.not.be.undefined it 'should optionally include "acr"', -> IDToken.registeredClaims.acr.should.not.be.undefined it 'should optionally include "amr"', -> IDToken.registeredClaims.amr.should.not.be.undefined it 'should optionally include "azp"' it 'should optionally include other claims defined by the specification' describe 'JWT encoded representation', -> it 'must be signed using JWS' describe 'encrypted representation', -> it 'must be a nested JWT' it 'must be signed using JWS' describe 'persistence', -> describe 'logging', -> describe 'issuance', ->
true
# Test dependencies cwd = process.cwd() path = require 'path' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect # Assertions chai.use sinonChai chai.should() # Code under test IDToken = require path.join cwd, 'models/IDToken' JWT = require 'anvil-connect-jwt' base64url = require 'base64url' # OpenID Connect Core 1.0 # # http://openid.net/specs/openid-connect-core-1_0.html#IDToken # # 2. ID Token # # The primary extension that OpenID Connect makes to OAuth 2.0 to enable # End-Users to be Authenticated is the ID Token data structure. The ID Token is a # security token that contains Claims about the Authentication of an End-User by # an Authorization Server when using a Client, and potentially other requested # Claims. The ID Token is represented as a JSON Web Token (JWT) [JWT]. # # The following Claims are used within the ID Token for all OAuth 2.0 flows # used by OpenID Connect: # # iss # REQUIRED. Issuer Identifier for the Issuer of the response. The iss # value is a case sensitive URL using the https scheme that contains scheme, # host, and optionally, port number and path components and no query or # fragment components. # sub # REQUIRED. Subject Identifier. A locally unique and never reassigned # identifier within the Issuer for the End-User, which is intended to be # consumed by the Client, e.g., 24400320 or # AItOawmwtWwcT0k51BayewNvutrJUqsvl6qs7A4. It MUST NOT exceed 255 ASCII # characters in length. The sub value is a case sensitive string. # aud # REQUIRED. Audience(s) that this ID Token is intended for. It MUST # contain the OAuth 2.0 client_id of the Relying Party as an audience value. # It MAY also contain identifiers for other audiences. In the general # case, the aud value is an array of case sensitive strings. In the # common special case when there is one audience, the aud value MAY be a # single case sensitive string. # exp # REQUIRED. Expiration time on or after which the ID Token MUST NOT be # accepted for processing. The processing of this parameter requires that # the current date/time MUST be before the expiration date/time listed in # the value. Implementers MAY provide for some small leeway, usually no more # than a few minutes, to account for clock skew. Its value is a JSON number # representing the number of seconds from 1970-01-01T0:0:0Z as measured in # UTC until the date/time. See RFC 3339 [RFC3339] for details regarding # date/times in general and UTC in particular. # iat # REQUIRED. Time at which the JWT was issued. Its value is a JSON number # representing the number of seconds from 1970-01-01T0:0:0Z as measured in # UTC until the date/time. # auth_time # Time when the End-User authentication occurred. Its value is a JSON # number representing the number of seconds from 1970-01-01T0:0:0Z as # measured in UTC until the date/time. When a max_age request is made or # when auth_time is requested as an Essential Claim, then this Claim is # REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim # semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time # response parameter.) # nonce # String value used to associate a Client session with an ID Token, and # to mitigate replay attacks. The value is passed through unmodified from # the Authentication Request to the ID Token. If present in the ID Token, # Clients MUST verify that the nonce Claim Value is equal to the value of # the nonce parameter sent in the Authentication Request. If present in the # Authentication Request, Authorization Servers MUST include a nonce Claim # in the ID Token with the Claim Value being the nonce value sent in the # Authentication Request. Authorization Servers SHOULD perform no other # processing on nonce values used. The nonce value is a case sensitive # string. # acr # OPTIONAL. Authentication Context Class Reference. String specifying an # Authentication Context Class Reference value that identifies the # Authentication Context Class that the authentication performed satisfied. # The value "0" indicates the End-User authentication did not meet the # requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a # long-lived browser cookie, for instance, is one example where the use of # "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used # to authorize access to any resource of any monetary value. (This # corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An # absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as # the acr value; registered names MUST NOT be used with a different meaning # than that which is registered. Parties using this claim will need to agree # upon the meanings of the values used, which may be context-specific. The # acr value is a case sensitive string. # amr # OPTIONAL. Authentication Methods References. JSON array of strings that # are identifiers for authentication methods used in the authentication. For # instance, values might indicate that both password and OTP authentication # methods were used. The definition of particular values to be used in the # amr Claim is beyond the scope of this specification. Parties using this # claim will need to agree upon the meanings of the values used, which may be # context-specific. The amr value is an array of case sensitive strings. # azp # OPTIONAL. Authorized party - the party to which the ID Token was # issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. # This Claim is only needed when the ID Token has a single audience value # and that audience is different than the authorized party. It MAY be # included even when the authorized party is the same as the sole audience. # The azp value is a case sensitive string containing a StringOrURI value. # # ID Tokens MAY contain other Claims. Any Claims used that are not understood # MUST be ignored. See Sections 3.1.3.6, PI:IP_ADDRESS:172.16.58.3END_PI, 5.1, and 7.4 for additional # Claims defined by this specification. # # ID Tokens MUST be signed using JWS [JWS] and optionally both signed and then # encrypted using JWS [JWS] and JWE [JWE] respectively, thereby providing # authentication, integrity, non-repudiation, and optionally, confidentiality, # per Section 16.14. If the ID Token is encrypted, it MUST be signed then # encrypted, with the result being a Nested JWT, as defined in [JWT]. ID Tokens # MUST NOT use none as the alg value unless the Response Type used returns no ID # Token from the Authorization Endpoint (such as when using the Authorization # Code Flow) and the Client explicitly requested the use of none at Registration # time. # # ID Tokens SHOULD NOT use the JWS or JWE x5u, x5c, jku, or jwk header # parameter fields. Instead, references to keys used are communicated in advance # using Discovery and Registration parameters, per Section 10. # # The following is a non-normative example of the set of Claims (the JWT Claims # Set) in an ID Token: # # { # "iss": "https://server.example.com", # "sub": "24400320", # "aud": "s6BhdRkqt3", # "nonce": "n-0S6_WzA2Mj", # "exp": 1311281970, # "iat": 1311280970, # "auth_time": 1311280969, # "acr": "urn:mace:incommon:iap:silver" # } describe 'ID Token', -> it 'should be a subclass of JWT', -> IDToken.super.should.equal JWT describe 'header', -> it 'must not use "none" as "alg" value', -> expect(-> new IDToken({}, { alg: 'none'})).to.throw Error it 'should not use "x5u", "x5c", "jku", or "jwk" header parameter fields', -> header = alg: 'RS256' x5u: 'x5u' x5c: 'x5c' jku: 'jku' jwk: 'jwk' payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' exp: Date.now() iat: Date.now() token = new IDToken payload, header expect(token.header.x5u).to.be.undefined expect(token.header.x5c).to.be.undefined expect(token.header.jku).to.be.undefined expect(token.header.jwk).to.be.undefined describe 'claims', -> it 'should require "iss" Issuer Identifier', -> IDToken.registeredClaims.iss.required.should.be.true it 'should require "sub" Subject Identifier', -> IDToken.registeredClaims.sub.required.should.be.true it 'should require "aud" Audience array or string' it 'should require "exp" Expiration time', -> IDToken.registeredClaims.exp.required.should.be.true it 'should default "exp" to 24 hours', -> payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' token = new IDToken payload token.payload.exp.should.be.a('number') new Date(token.payload.exp * 1000).getDay().should.not.equal new Date().getDay() it 'should require "iat" Issued time', -> IDToken.registeredClaims.iat.required.should.be.true it 'should default "iat" to now', -> payload = iss: 'http://anvil.io' sub: 'uuid' aud: 'uuid' exp: Date.now() token = new IDToken payload token.payload.iat.should.be.a('number') it 'should conditionally require "auth_time"' it 'should include "nonce"', -> IDToken.registeredClaims.nonce.should.not.be.undefined it 'should optionally include "acr"', -> IDToken.registeredClaims.acr.should.not.be.undefined it 'should optionally include "amr"', -> IDToken.registeredClaims.amr.should.not.be.undefined it 'should optionally include "azp"' it 'should optionally include other claims defined by the specification' describe 'JWT encoded representation', -> it 'must be signed using JWS' describe 'encrypted representation', -> it 'must be a nested JWT' it 'must be signed using JWS' describe 'persistence', -> describe 'logging', -> describe 'issuance', ->
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992150664329529, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "lines to HTTP/1.0 clients.\n#\n# https://github.com/joyent/node/issues/1234\n#\n(->\n handler...
test/simple/test-http-1.0.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. test = (handler, request_generator, response_validator) -> cleanup = -> server.close() response_validator server_response, client_got_eof, true return port = common_port++ server = http.createServer(handler) client_got_eof = false server_response = data: "" chunks: [] timer = setTimeout(cleanup, 1000) process.on "exit", cleanup server.listen port server.on "listening", -> c = net.createConnection(port) c.setEncoding "utf8" c.on "connect", -> c.write request_generator() return c.on "data", (chunk) -> server_response.data += chunk server_response.chunks.push chunk return c.on "end", -> client_got_eof = true c.end() server.close() clearTimeout timer process.removeListener "exit", cleanup response_validator server_response, client_got_eof, false return return return common = require("../common") assert = require("assert") net = require("net") http = require("http") body = "hello world\n" common_port = common.PORT (-> handler = (req, res) -> assert.equal "1.0", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 0, req.httpVersionMinor res.writeHead 200, "Content-Type": "text/plain" res.end body return request_generator = -> "GET / HTTP/1.0\r\n\r\n" response_validator = (server_response, client_got_eof, timed_out) -> m = server_response.data.split("\r\n\r\n") assert.equal m[1], body assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )() # # Don't send HTTP/1.1 status lines to HTTP/1.0 clients. # # https://github.com/joyent/node/issues/1234 # (-> handler = (req, res) -> assert.equal "1.0", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 0, req.httpVersionMinor res.sendDate = false res.writeHead 200, "Content-Type": "text/plain" res.write "Hello, " res._send "" res.write "world!" res._send "" res.end() return request_generator = -> "GET / HTTP/1.0\r\n" + "User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 " + "OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n" + "Host: 127.0.0.1:1337\r\n" + "Accept: */*\r\n" + "\r\n" response_validator = (server_response, client_got_eof, timed_out) -> expected_response = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "\r\n" + "Hello, world!") assert.equal expected_response, server_response.data assert.equal 1, server_response.chunks.length assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )() (-> handler = (req, res) -> assert.equal "1.1", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 1, req.httpVersionMinor res.sendDate = false res.writeHead 200, "Content-Type": "text/plain" res.write "Hello, " res._send "" res.write "world!" res._send "" res.end() return request_generator = -> "GET / HTTP/1.1\r\n" + "User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 " + "OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n" + "Connection: close\r\n" + "Host: 127.0.0.1:1337\r\n" + "Accept: */*\r\n" + "\r\n" response_validator = (server_response, client_got_eof, timed_out) -> expected_response = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "7\r\n" + "Hello, \r\n" + "6\r\n" + "world!\r\n" + "0\r\n" + "\r\n") assert.equal expected_response, server_response.data assert.equal 1, server_response.chunks.length assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )()
137223
# 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 = (handler, request_generator, response_validator) -> cleanup = -> server.close() response_validator server_response, client_got_eof, true return port = common_port++ server = http.createServer(handler) client_got_eof = false server_response = data: "" chunks: [] timer = setTimeout(cleanup, 1000) process.on "exit", cleanup server.listen port server.on "listening", -> c = net.createConnection(port) c.setEncoding "utf8" c.on "connect", -> c.write request_generator() return c.on "data", (chunk) -> server_response.data += chunk server_response.chunks.push chunk return c.on "end", -> client_got_eof = true c.end() server.close() clearTimeout timer process.removeListener "exit", cleanup response_validator server_response, client_got_eof, false return return return common = require("../common") assert = require("assert") net = require("net") http = require("http") body = "hello world\n" common_port = common.PORT (-> handler = (req, res) -> assert.equal "1.0", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 0, req.httpVersionMinor res.writeHead 200, "Content-Type": "text/plain" res.end body return request_generator = -> "GET / HTTP/1.0\r\n\r\n" response_validator = (server_response, client_got_eof, timed_out) -> m = server_response.data.split("\r\n\r\n") assert.equal m[1], body assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )() # # Don't send HTTP/1.1 status lines to HTTP/1.0 clients. # # https://github.com/joyent/node/issues/1234 # (-> handler = (req, res) -> assert.equal "1.0", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 0, req.httpVersionMinor res.sendDate = false res.writeHead 200, "Content-Type": "text/plain" res.write "Hello, " res._send "" res.write "world!" res._send "" res.end() return request_generator = -> "GET / HTTP/1.0\r\n" + "User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 " + "OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n" + "Host: 127.0.0.1:1337\r\n" + "Accept: */*\r\n" + "\r\n" response_validator = (server_response, client_got_eof, timed_out) -> expected_response = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "\r\n" + "Hello, world!") assert.equal expected_response, server_response.data assert.equal 1, server_response.chunks.length assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )() (-> handler = (req, res) -> assert.equal "1.1", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 1, req.httpVersionMinor res.sendDate = false res.writeHead 200, "Content-Type": "text/plain" res.write "Hello, " res._send "" res.write "world!" res._send "" res.end() return request_generator = -> "GET / HTTP/1.1\r\n" + "User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 " + "OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n" + "Connection: close\r\n" + "Host: 127.0.0.1:1337\r\n" + "Accept: */*\r\n" + "\r\n" response_validator = (server_response, client_got_eof, timed_out) -> expected_response = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "7\r\n" + "Hello, \r\n" + "6\r\n" + "world!\r\n" + "0\r\n" + "\r\n") assert.equal expected_response, server_response.data assert.equal 1, server_response.chunks.length assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator 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. test = (handler, request_generator, response_validator) -> cleanup = -> server.close() response_validator server_response, client_got_eof, true return port = common_port++ server = http.createServer(handler) client_got_eof = false server_response = data: "" chunks: [] timer = setTimeout(cleanup, 1000) process.on "exit", cleanup server.listen port server.on "listening", -> c = net.createConnection(port) c.setEncoding "utf8" c.on "connect", -> c.write request_generator() return c.on "data", (chunk) -> server_response.data += chunk server_response.chunks.push chunk return c.on "end", -> client_got_eof = true c.end() server.close() clearTimeout timer process.removeListener "exit", cleanup response_validator server_response, client_got_eof, false return return return common = require("../common") assert = require("assert") net = require("net") http = require("http") body = "hello world\n" common_port = common.PORT (-> handler = (req, res) -> assert.equal "1.0", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 0, req.httpVersionMinor res.writeHead 200, "Content-Type": "text/plain" res.end body return request_generator = -> "GET / HTTP/1.0\r\n\r\n" response_validator = (server_response, client_got_eof, timed_out) -> m = server_response.data.split("\r\n\r\n") assert.equal m[1], body assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )() # # Don't send HTTP/1.1 status lines to HTTP/1.0 clients. # # https://github.com/joyent/node/issues/1234 # (-> handler = (req, res) -> assert.equal "1.0", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 0, req.httpVersionMinor res.sendDate = false res.writeHead 200, "Content-Type": "text/plain" res.write "Hello, " res._send "" res.write "world!" res._send "" res.end() return request_generator = -> "GET / HTTP/1.0\r\n" + "User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 " + "OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n" + "Host: 127.0.0.1:1337\r\n" + "Accept: */*\r\n" + "\r\n" response_validator = (server_response, client_got_eof, timed_out) -> expected_response = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "\r\n" + "Hello, world!") assert.equal expected_response, server_response.data assert.equal 1, server_response.chunks.length assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )() (-> handler = (req, res) -> assert.equal "1.1", req.httpVersion assert.equal 1, req.httpVersionMajor assert.equal 1, req.httpVersionMinor res.sendDate = false res.writeHead 200, "Content-Type": "text/plain" res.write "Hello, " res._send "" res.write "world!" res._send "" res.end() return request_generator = -> "GET / HTTP/1.1\r\n" + "User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 " + "OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n" + "Connection: close\r\n" + "Host: 127.0.0.1:1337\r\n" + "Accept: */*\r\n" + "\r\n" response_validator = (server_response, client_got_eof, timed_out) -> expected_response = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "7\r\n" + "Hello, \r\n" + "6\r\n" + "world!\r\n" + "0\r\n" + "\r\n") assert.equal expected_response, server_response.data assert.equal 1, server_response.chunks.length assert.equal true, client_got_eof assert.equal false, timed_out return test handler, request_generator, response_validator return )()
[ { "context": "panelContrast: true\n \"circle-ci\":\n apiToken: \"CIRCLE_CI_API_TOKEN\"\n core:\n closeDeletedFileTabs", "end": 306, "score": 0.7431240677833557, "start": 303, "tag": "KEY", "value": "CIR" }, { "context": " emmet: {}\n \"exception-reporting\":\n userId: \"...
init/config.cson
kuatsure/dotfiles
2
"*": "advanced-new-file": createFileInstantly: true suggestCurrentFilePath: true "atom-material-ui": depth: true fonts: {} panelContrast: true tabs: compactTabs: true treeView: compactList: true ui: panelContrast: true "circle-ci": apiToken: "CIRCLE_CI_API_TOKEN" core: closeDeletedFileTabs: true disabledPackages: [ "svg-preview" "relative-numbers" "vim-surround" "vim-mode" ] openEmptyEditorOnStart: false telemetryConsent: "no" themes: [ "dracula-ui" "dracula-theme" ] docblockr: deep_indent: true editor: fontFamily: "SourceCodePro-Light" invisibles: {} preferredLineLength: 1000 showIndentGuide: true showInvisibles: true useShadowDOM: true emmet: {} "exception-reporting": userId: "user_id" "file-watcher": promptWhenFileHasChangedOnDisk: false "fuzzy-finder": ignoredNames: [ "migrate" ] "isotope-ui": backgroundColor: "false" fontFamily: "Source Sans Pro" lowContrastTooltip: true spaciousMode: true linter: {} "linter-eslint": disableFSCache: true fixOnSave: true "linter-jshint": disableWhenNoJshintrcFileInPath: true "linter-sass-lint": noConfigDisable: true "linter-scss-lint": disableWhenNoConfigFileInPath: true executablePath: "path_to_linter" "linter-stylelint": {} "linter-ui-default": showPanel: true showTooltip: false useBusySignal: false pigments: groupPaletteColors: "by file" markerType: "dot" mergeColorDuplicates: true sortPaletteColors: "by color" traverseIntoSymlinkDirectories: true "split-diff": diffWords: true ignoreWhitespace: true leftEditorColor: "red" rightEditorColor: "green" scrollSyncType: "Vertical + Horizontal" "travis-ci-status": {} "tree-view": focusOnReveal: false hideIgnoredNames: true showOnRightSide: true squashDirectoryNames: true "vim-mode": useClipboardAsDefaultRegister: false "vim-mode-plus": automaticallyEscapeInsertModeOnActivePaneItemChange: true highlightSearch: true welcome: showOnStartup: false whitespace: ignoreWhitespaceOnCurrentLine: false ".ansi.text": editor: preferredLineLength: 1000 ".hack.html.text": editor: preferredLineLength: 1000 ".hackfragment.source": editor: preferredLineLength: 1000 ".haml.text": editor: preferredLineLength: 1000 ".hamlc.text": editor: preferredLineLength: 1000 ".html.mustache.text": editor: preferredLineLength: 1000 ".ini.source": editor: preferredLineLength: 1000 ".mustache.source.sql": editor: preferredLineLength: 1000
55435
"*": "advanced-new-file": createFileInstantly: true suggestCurrentFilePath: true "atom-material-ui": depth: true fonts: {} panelContrast: true tabs: compactTabs: true treeView: compactList: true ui: panelContrast: true "circle-ci": apiToken: "<KEY>CLE_CI_API_TOKEN" core: closeDeletedFileTabs: true disabledPackages: [ "svg-preview" "relative-numbers" "vim-surround" "vim-mode" ] openEmptyEditorOnStart: false telemetryConsent: "no" themes: [ "dracula-ui" "dracula-theme" ] docblockr: deep_indent: true editor: fontFamily: "SourceCodePro-Light" invisibles: {} preferredLineLength: 1000 showIndentGuide: true showInvisibles: true useShadowDOM: true emmet: {} "exception-reporting": userId: "user_id" "file-watcher": promptWhenFileHasChangedOnDisk: false "fuzzy-finder": ignoredNames: [ "migrate" ] "isotope-ui": backgroundColor: "false" fontFamily: "Source Sans Pro" lowContrastTooltip: true spaciousMode: true linter: {} "linter-eslint": disableFSCache: true fixOnSave: true "linter-jshint": disableWhenNoJshintrcFileInPath: true "linter-sass-lint": noConfigDisable: true "linter-scss-lint": disableWhenNoConfigFileInPath: true executablePath: "path_to_linter" "linter-stylelint": {} "linter-ui-default": showPanel: true showTooltip: false useBusySignal: false pigments: groupPaletteColors: "by file" markerType: "dot" mergeColorDuplicates: true sortPaletteColors: "by color" traverseIntoSymlinkDirectories: true "split-diff": diffWords: true ignoreWhitespace: true leftEditorColor: "red" rightEditorColor: "green" scrollSyncType: "Vertical + Horizontal" "travis-ci-status": {} "tree-view": focusOnReveal: false hideIgnoredNames: true showOnRightSide: true squashDirectoryNames: true "vim-mode": useClipboardAsDefaultRegister: false "vim-mode-plus": automaticallyEscapeInsertModeOnActivePaneItemChange: true highlightSearch: true welcome: showOnStartup: false whitespace: ignoreWhitespaceOnCurrentLine: false ".ansi.text": editor: preferredLineLength: 1000 ".hack.html.text": editor: preferredLineLength: 1000 ".hackfragment.source": editor: preferredLineLength: 1000 ".haml.text": editor: preferredLineLength: 1000 ".hamlc.text": editor: preferredLineLength: 1000 ".html.mustache.text": editor: preferredLineLength: 1000 ".ini.source": editor: preferredLineLength: 1000 ".mustache.source.sql": editor: preferredLineLength: 1000
true
"*": "advanced-new-file": createFileInstantly: true suggestCurrentFilePath: true "atom-material-ui": depth: true fonts: {} panelContrast: true tabs: compactTabs: true treeView: compactList: true ui: panelContrast: true "circle-ci": apiToken: "PI:KEY:<KEY>END_PICLE_CI_API_TOKEN" core: closeDeletedFileTabs: true disabledPackages: [ "svg-preview" "relative-numbers" "vim-surround" "vim-mode" ] openEmptyEditorOnStart: false telemetryConsent: "no" themes: [ "dracula-ui" "dracula-theme" ] docblockr: deep_indent: true editor: fontFamily: "SourceCodePro-Light" invisibles: {} preferredLineLength: 1000 showIndentGuide: true showInvisibles: true useShadowDOM: true emmet: {} "exception-reporting": userId: "user_id" "file-watcher": promptWhenFileHasChangedOnDisk: false "fuzzy-finder": ignoredNames: [ "migrate" ] "isotope-ui": backgroundColor: "false" fontFamily: "Source Sans Pro" lowContrastTooltip: true spaciousMode: true linter: {} "linter-eslint": disableFSCache: true fixOnSave: true "linter-jshint": disableWhenNoJshintrcFileInPath: true "linter-sass-lint": noConfigDisable: true "linter-scss-lint": disableWhenNoConfigFileInPath: true executablePath: "path_to_linter" "linter-stylelint": {} "linter-ui-default": showPanel: true showTooltip: false useBusySignal: false pigments: groupPaletteColors: "by file" markerType: "dot" mergeColorDuplicates: true sortPaletteColors: "by color" traverseIntoSymlinkDirectories: true "split-diff": diffWords: true ignoreWhitespace: true leftEditorColor: "red" rightEditorColor: "green" scrollSyncType: "Vertical + Horizontal" "travis-ci-status": {} "tree-view": focusOnReveal: false hideIgnoredNames: true showOnRightSide: true squashDirectoryNames: true "vim-mode": useClipboardAsDefaultRegister: false "vim-mode-plus": automaticallyEscapeInsertModeOnActivePaneItemChange: true highlightSearch: true welcome: showOnStartup: false whitespace: ignoreWhitespaceOnCurrentLine: false ".ansi.text": editor: preferredLineLength: 1000 ".hack.html.text": editor: preferredLineLength: 1000 ".hackfragment.source": editor: preferredLineLength: 1000 ".haml.text": editor: preferredLineLength: 1000 ".hamlc.text": editor: preferredLineLength: 1000 ".html.mustache.text": editor: preferredLineLength: 1000 ".ini.source": editor: preferredLineLength: 1000 ".mustache.source.sql": editor: preferredLineLength: 1000
[ { "context": "vices, anywhere,\n anytime.\n '''\n,\n name: 'Blitz'\n image: 'blitz.png'\n url: 'http://blitz.io/'", "end": 535, "score": 0.8859333992004395, "start": 530, "tag": "NAME", "value": "Blitz" }, { "context": "formance and\n scalability.\n '''\n,\n name: ...
models/sponsor.coffee
nko2/website
4
module.exports = [ name: 'Adobe' image: 'adobe.png' url: 'http://www.adobe.com/' description: ''' We help our customers create, deliver, and optimize compelling content and applications — improving the impact of their communications, enhancing their brands and productivity, and ultimately bringing them greater business success. Together, we're turning ordinary interactions into more valuable digital experiences every day, across media and devices, anywhere, anytime. ''' , name: 'Blitz' image: 'blitz.png' url: 'http://blitz.io/' description: ''' Blitz, powered by Mu Dynamics, is a self-service cloud based performance testing platform. Built for API, cloud, web and mobile app developers, Blitz quickly and inexpensively helps you ensure performance and scalability. ''' , name: 'Bislr' image: 'bislr.png' url: 'http://www.bislr.com/' description: ''' [Bislr][1] (pronounced Biz-ler) allows anyone to create an online business. Manage your website, blog, contacts and online marketing on the world’s first online business platform. Bislr uses Node.js at it's core and is proud to be supporting Node.js Knockout. [1]: http://www.bislr.com/ ''' , name: 'Cloud9' image: 'cloud9.png' url: 'http://cloud9ide.com/' description: ''' Cloud9 IDE is the first-ever cloud-based integrated development environment (IDE) for JavaScript developers, built on top of Node.js. Cloud9 enables Web developers to access, edit and share projects anywhere, anytime. ''' , name: 'Cloud Foundry' image: 'cloudfoundry.png' url: 'http://www.cloudfoundry.com/' description: ''' [Cloud Foundry&trade;][1] is the industry’s first open platform as a service and Micro Cloud Foundry&trade; is the industry’s first downloadable PaaS for your computer. Initiated by VMware, Cloud Foundry delivers access to modern frameworks including Spring for Java, Ruby for Rails and Sinatra, node.js, Grails, Scala on Lift and more. It provides application services including RabbitMQ and MySQL, MongoDB, Redis and more from third parties and the open source community. Cloud Foundry is downloadable and dramatically enhances developers’ abilities to build, test and deploy their applications with symmetry between private, public and hybrid clouds. [1]: http://www.cloudfoundry.com/ ''' , name: 'Couchbase' image: 'couchbase.png' url: 'http://www.couchbase.com/' description: ''' Apache [CouchDB][1] is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution. [1]: http://www.couchbase.com/ ''' , name: 'Dropbox' image: 'dropbox.png' url: 'http://www.dropbox.com/' description: ''' Today, more than 25 million people across every continent use [Dropbox][1] to always have their stuff at hand, share with family and friends, and work on team projects. We're looking for more great people to join us, so if you're excited to help simplify life for millions of people, check out our [jobs][2]. [1]: http://www.dropbox.com/ [2]: http://www.dropbox.com/jobs ''' , name: 'Geekli.st' image: 'geeklist.png' url: 'http://geekli.st/' description: ''' [Get early access to our private beta][1] by requesting an invite and reserving your username. [1]: http://geekli.st/beta ''' , name: 'GitHub', image: 'github.png' url: 'https://github.com/' description: ''' Code is about the people writing it. We focus on lowering the barriers of collaboration by building powerful [features][1] into our products that make it easier to contribute. The tools we create help individuals and companies, public and private, to write better code, faster. [Ship it!][2] [1]: https://github.com/features/projects [2]: http://shipitsquirrel.github.com/ ''' , name: 'Heroku' image: 'heroku.png' url: 'http://www.heroku.com/' description: ''' Agile deployment for Ruby, Node.js and Clojure. Get up and running in minutes, and deploy instantly with git. Focus 100% on your code, and never think about servers, instances, or VMs again. ''' , name: 'Joyent' image: 'joyent.png' url: 'http://www.joyent.com/' description: ''' Joyent is a global cloud computing software and service provider that offers an integrated technology suite designed for service providers, enterprises, and developers. Joyent Cloud delivers public cloud services to some of the most innovative companies in the world, including LinkedIn, Gilt Groupe and Kabam. Joyent offerings also include Platform-as-a-Service based on Node.js, the open source server-side JavaScript development environment. For more information, visit <http://www.joyentcloud.com/> and <http://www.joyent.com/>. ''' , name: 'Linode' image: 'linode.png' url: 'http://www.linode.com/index.cfm' description: ''' Deploy and Manage Linux Virtual Servers in the [Linode][1] Cloud. Get a server running in minutes with your choice of Linux distro, resources, and node location. [1]: http://www.linode.com/index.cfm ''' , name: 'MaxCDN' image: 'maxcdn.png' url: 'http://maxcdn.com/' description: ''' Simply put, [MaxCDN][1] gives you the most powerful control panel and CDN product in the industry – at a price you can afford. [1]: http://maxcdn.com/ ''' , name: 'Meebo' image: 'meebo.png' url: 'http://www.meebo.com/' description: ''' [Meebo][1] gives you the easiest, most open and most "right there where you want it" way to share on the web. [1]: http://www.meebo.com/ ''' , name: 'MongoHQ' image: 'mongohq.png' url: 'https://mongohq.com/home' description: ''' [MongoHQ][1] is the hosted database solution for getting your applications up and running on MongoDB, fast. From our free shared plans to custom dedicated solutions, we can handle all the different levels of your data layer. [1]: https://mongohq.com/home ''' , name: 'Mozilla' image: 'mozilla.png' url: 'http://www.mozilla.org/' description: ''' Mozilla, a non-profit organization and creator of Firefox whose [mission][1] is to promote openness, innovation and opportunity on the Web. [1]: http://www.mozilla.org/about/mission.html ''' , name: 'ngmoco' image: 'ngmoco.png' url: 'http://blog.ngmoco.com/' description: ''' In 2011 there will be more iOS/Android devices shipped than PCs/notebooks. We at [ngmoco:)][1] see a once-in-a-generation opportunity to build a Social Entertainment Network to serve this new audience. We provide Mobage, a powerful social framework for developers to build & amplify social in their games. We make the best social games, powered by ngCore, a technology framework to publish on multiple platforms from a single codebase. [1]: http://blog.ngmoco.com/ ''' , name: 'nodejitsu' image: 'nodejitsu.png' url: 'http://www.nodejitsu.com/' description: ''' Enterprise-class cloud hosting for node.js applications and websites. We're in __private beta__! [Signup for our beta session][1] and we'll send you an email. Also, [come hack with us during node.js knockout][2]. [1]: http://www.nodejitsu.com/ [2]: http://nodeknockout.com/locations#nyc ''' , name: 'nodeSocket' image: 'nodesocket.png' url: 'http://www.nodesocket.com/' description: ''' [NodeSocket][1] is a simple, scalable, and powerful node.js hosting platform and community for developers. NodeSocket provides a complete suite of developer focused tools and add-ons to assist developers build, deploy, scale, and monitor their node.js applications. __Request a [beta invitation][2] today.__ [1]: http://www.nodesocket.com/ [2]: http://beta.nodesocket.com/ ''' , name: 'PostageApp' image: 'postageapp.png' url: 'http://postageapp.com/' description: ''' [PostageApp][1] is a service that makes it easier to manage, deliver, and track emails from your web apps. HTML/CSS templates that make it easy to design, edit, and preview emails; a developer friendly API; rock-solid deliverability; and detailed, real-time reporting that gives you a pulse on the lifeblood of your web app. [1]: http://postageapp.com/ ''' , name: 'PubNub' image: 'pubnub.png' url: 'http://www.pubnub.com/' description: ''' Real-time, publish and subscribe communication cloud offered as a web-service API. Our customers are building cool new real-time mobile, web and social apps using data push communication and mass broadcasting that run on Mobile, Tablet and Web. ''' , name: 'Pusher' image: 'pusher.png' url: 'http://pusher.com/' description: ''' Supercharge your app with __realtime__ events [Pusher][1] is a hosted __API__ for __quickly__, __easily__ and __securely__ adding __scalable__ realtime functionality via WebSockets to web and mobile apps. [1]: http://pusher.com/ ''' , name: 'Scopely' image: 'scopely.png' url: 'http://jobs.scopely.com/' description: ''' The hottest new consumer web startup in Los Angeles, [Scopely][1] is in stealth mode preparing to disrupt a segment of the social web that is ripe for innovation. The Scopely team includes 12 senior engineers and product managers from companies including Playdom, MindJolt, Warner Brothers, and Saatchi and Saatchi. Current investors include David Tisch, Greycroft Partners, David Cohen, Windsor Media, Lerer Ventures, The Collaborative Fund, Howard Lindzon, Gil Elbaz, and Evan Rifkin. [1]: http://jobs.scopely.com/ ''' , name: 'Sleepless' image: 'sleepless.gif' url: 'http://sleepless.com/' description: ''' No sleeping, no waiting, no blocking... [Sleepless][1] is a software and Internet development company specializing in custom Node.js development and highly scalable, cloud-based, server-side infrastructure. We provide development, consulting, and analysis for projects large and small. Our teams are very highly skilled and possess a breadth and depth of experience rarely found. If you have a project or would like to work on one, find us at Sleepless.com. [1]: http://sleepless.com/ ''' , name: 'Sequoia Capital' image: 'sequoiacap.png' url: 'http://www.sequoiacap.com/' description: ''' Sequoia Capital provides [venture capital funding][1] to founders of startups who want to turn [business ideas][2] into enduring companies. As the "Entrepreneurs Behind the Entrepreneurs", Sequoia Capital's Partners have worked with innovators such as Steve Jobs of Apple Computer, Larry Ellison of Oracle, Bob Swanson of Linear Technology, Sandy Lerner and Len Bozack of Cisco Systems, Dan Warmenhoven of NetApp, Jerry Yang and David Filo of Yahoo!, Jen-Hsun Huang of NVIDIA, Michael Marks of Flextronics, Larry Page and Sergey Brin of Google, Chad Hurley and Steve Chen of YouTube, Dominic Orr and Keerti Melkote of Aruba Networks, Tony Hsieh of Zappos, Omar Hamoui of Admob, Steve Streit of Green Dot and Reid Hoffman and Jeff Weiner of LinkedIn. To learn more about Sequoia Capital visit [www.sequoiacap.com/us][3]. [1]: http://www.sequoiacap.com/us [2]: http://www.sequoiacap.com/ideas [3]: http://www.sequoiacap.com/us ''' , name: 'Spreecast' image: 'spreecast.png' url: 'http://spreecast.com/' description: ''' Compelling conversations. Democratized media. Join the discussion. Get involved. [Join our invite list][1]. [1]: http://spreecast.com/ ''' , name: 'NodeConf SummerCamp' image: 'summercamp.gif' url: 'http://www.nodeconf.com/summercamp.html' description: ''' [NodeConf SummerCamp][1] is an unconference held at the Walker Creek Ranch in California. Developers of all skill levels are invited to discuss, learn, and build a stronger community. [1]: http://www.nodeconf.com/summercamp.html ''' , name: 'SunGard' image: 'sungard.png' url: 'http://sungard.com/' description: ''' SunGard Global Services combines business consulting, technology and professional services for financial services firms, energy companies and corporations. Leveraging SunGard’s global delivery model, more than 5,000 employees worldwide help customers manage their complex data needs, optimize end-to-end business processes and assist with systems integration, while providing full application development, maintenance, testing and support services. ''' , name: 'Tapjoy' image: 'tapjoy.png' url: 'https://www.tapjoy.com/' description: ''' [Tapjoy][1] is the success engine for mobile application distribution, engagement and revenue. The company’s turnkey in-app advertising platform helps developers acquire cost-effective, high-value new users, drive engagement within their applications, and create incremental income by providing an ad-funded payment method. The Tapjoy network spans over 9,000 applications and 200 million global consumers on iOS, Android and emerging mobile platforms, delivering more than 1.5 million advertising completions per day to applications developers and advertisers. Tapjoy is backed by top-tier investors including J.P.Morgan Asset Management, Rho Ventures, North Bridge Venture Partners, InterWest Partners and D.E. Shaw Ventures. Headquartered in San Francisco, the company also has offices in New York, London and Tokyo. For more information, please visit [www.tapjoy.com][1]. [1]: https://www.tapjoy.com/ ''' , name: 'TradeKing' image: 'tradeking.png' url: 'http://www.tradeking.com/' description: ''' [TradeKing][1] is a nationally licensed online broker dealer offering simple, low flat fees with no hidden fees or account minimums. A pioneer in integrating new social media as part of its innovative online trading platform, TradeKing recently launched a trading and market data API available at [developers.tradeking.com][2]. [1]: http://www.tradeking.com [2]: http://developers.tradeking.com ''' , name: 'Tropo' image: 'tropo.png' url: 'https://www.tropo.com/home.jsp' description: ''' [Tropo][1] makes it simple to build phone, SMS and Instant Messaging (IM) applications. You use the web technologies you already know and Tropo's powerful cloud API to bring real-time communications to your apps. Tropo empowers developers to build sophisticated, multi-channel communication applications with easy to use cloud-based components. Tropo is committed to fostering and supporting open source, open standards and open communications. [1]: https://www.tropo.com/home.jsp ''' , name: 'Twilio' image: 'twilio.png' url: 'http://www.twilio.com/' description: ''' [Twilio][1] is a cloud communications company that offers simple HTTP APIs for sending and receiving phone calls and text messages. [1]: http://www.twilio.com/ ''' ]
156054
module.exports = [ name: 'Adobe' image: 'adobe.png' url: 'http://www.adobe.com/' description: ''' We help our customers create, deliver, and optimize compelling content and applications — improving the impact of their communications, enhancing their brands and productivity, and ultimately bringing them greater business success. Together, we're turning ordinary interactions into more valuable digital experiences every day, across media and devices, anywhere, anytime. ''' , name: '<NAME>' image: 'blitz.png' url: 'http://blitz.io/' description: ''' Blitz, powered by Mu Dynamics, is a self-service cloud based performance testing platform. Built for API, cloud, web and mobile app developers, Blitz quickly and inexpensively helps you ensure performance and scalability. ''' , name: '<NAME>' image: 'bislr.png' url: 'http://www.bislr.com/' description: ''' [Bislr][1] (pronounced Biz-ler) allows anyone to create an online business. Manage your website, blog, contacts and online marketing on the world’s first online business platform. Bislr uses Node.js at it's core and is proud to be supporting Node.js Knockout. [1]: http://www.bislr.com/ ''' , name: 'Cloud9' image: 'cloud9.png' url: 'http://cloud9ide.com/' description: ''' Cloud9 IDE is the first-ever cloud-based integrated development environment (IDE) for JavaScript developers, built on top of Node.js. Cloud9 enables Web developers to access, edit and share projects anywhere, anytime. ''' , name: 'Cloud Foundry' image: 'cloudfoundry.png' url: 'http://www.cloudfoundry.com/' description: ''' [Cloud Foundry&trade;][1] is the industry’s first open platform as a service and Micro Cloud Foundry&trade; is the industry’s first downloadable PaaS for your computer. Initiated by VMware, Cloud Foundry delivers access to modern frameworks including Spring for Java, Ruby for Rails and Sinatra, node.js, Grails, Scala on Lift and more. It provides application services including RabbitMQ and MySQL, MongoDB, Redis and more from third parties and the open source community. Cloud Foundry is downloadable and dramatically enhances developers’ abilities to build, test and deploy their applications with symmetry between private, public and hybrid clouds. [1]: http://www.cloudfoundry.com/ ''' , name: 'Couchbase' image: 'couchbase.png' url: 'http://www.couchbase.com/' description: ''' Apache [CouchDB][1] is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution. [1]: http://www.couchbase.com/ ''' , name: 'Dropbox' image: 'dropbox.png' url: 'http://www.dropbox.com/' description: ''' Today, more than 25 million people across every continent use [Dropbox][1] to always have their stuff at hand, share with family and friends, and work on team projects. We're looking for more great people to join us, so if you're excited to help simplify life for millions of people, check out our [jobs][2]. [1]: http://www.dropbox.com/ [2]: http://www.dropbox.com/jobs ''' , name: 'G<NAME>' image: 'geeklist.png' url: 'http://geekli.st/' description: ''' [Get early access to our private beta][1] by requesting an invite and reserving your username. [1]: http://geekli.st/beta ''' , name: 'GitHub', image: 'github.png' url: 'https://github.com/' description: ''' Code is about the people writing it. We focus on lowering the barriers of collaboration by building powerful [features][1] into our products that make it easier to contribute. The tools we create help individuals and companies, public and private, to write better code, faster. [Ship it!][2] [1]: https://github.com/features/projects [2]: http://shipitsquirrel.github.com/ ''' , name: '<NAME>' image: 'heroku.png' url: 'http://www.heroku.com/' description: ''' Agile deployment for Ruby, Node.js and Clojure. Get up and running in minutes, and deploy instantly with git. Focus 100% on your code, and never think about servers, instances, or VMs again. ''' , name: '<NAME>' image: 'joyent.png' url: 'http://www.joyent.com/' description: ''' Joyent is a global cloud computing software and service provider that offers an integrated technology suite designed for service providers, enterprises, and developers. Joyent Cloud delivers public cloud services to some of the most innovative companies in the world, including LinkedIn, Gilt Groupe and Kabam. Joyent offerings also include Platform-as-a-Service based on Node.js, the open source server-side JavaScript development environment. For more information, visit <http://www.joyentcloud.com/> and <http://www.joyent.com/>. ''' , name: 'Lin<NAME>' image: 'linode.png' url: 'http://www.linode.com/index.cfm' description: ''' Deploy and Manage Linux Virtual Servers in the [Linode][1] Cloud. Get a server running in minutes with your choice of Linux distro, resources, and node location. [1]: http://www.linode.com/index.cfm ''' , name: 'MaxCDN' image: 'maxcdn.png' url: 'http://maxcdn.com/' description: ''' Simply put, [MaxCDN][1] gives you the most powerful control panel and CDN product in the industry – at a price you can afford. [1]: http://maxcdn.com/ ''' , name: 'Meebo' image: 'meebo.png' url: 'http://www.meebo.com/' description: ''' [Meebo][1] gives you the easiest, most open and most "right there where you want it" way to share on the web. [1]: http://www.meebo.com/ ''' , name: 'MongoHQ' image: 'mongohq.png' url: 'https://mongohq.com/home' description: ''' [MongoHQ][1] is the hosted database solution for getting your applications up and running on MongoDB, fast. From our free shared plans to custom dedicated solutions, we can handle all the different levels of your data layer. [1]: https://mongohq.com/home ''' , name: 'Mozilla' image: 'mozilla.png' url: 'http://www.mozilla.org/' description: ''' Mozilla, a non-profit organization and creator of Firefox whose [mission][1] is to promote openness, innovation and opportunity on the Web. [1]: http://www.mozilla.org/about/mission.html ''' , name: 'ngmoco' image: 'ngmoco.png' url: 'http://blog.ngmoco.com/' description: ''' In 2011 there will be more iOS/Android devices shipped than PCs/notebooks. We at [ngmoco:)][1] see a once-in-a-generation opportunity to build a Social Entertainment Network to serve this new audience. We provide Mobage, a powerful social framework for developers to build & amplify social in their games. We make the best social games, powered by ngCore, a technology framework to publish on multiple platforms from a single codebase. [1]: http://blog.ngmoco.com/ ''' , name: 'nodejitsu' image: 'nodejitsu.png' url: 'http://www.nodejitsu.com/' description: ''' Enterprise-class cloud hosting for node.js applications and websites. We're in __private beta__! [Signup for our beta session][1] and we'll send you an email. Also, [come hack with us during node.js knockout][2]. [1]: http://www.nodejitsu.com/ [2]: http://nodeknockout.com/locations#nyc ''' , name: 'nodeSocket' image: 'nodesocket.png' url: 'http://www.nodesocket.com/' description: ''' [NodeSocket][1] is a simple, scalable, and powerful node.js hosting platform and community for developers. NodeSocket provides a complete suite of developer focused tools and add-ons to assist developers build, deploy, scale, and monitor their node.js applications. __Request a [beta invitation][2] today.__ [1]: http://www.nodesocket.com/ [2]: http://beta.nodesocket.com/ ''' , name: 'PostageApp' image: 'postageapp.png' url: 'http://postageapp.com/' description: ''' [PostageApp][1] is a service that makes it easier to manage, deliver, and track emails from your web apps. HTML/CSS templates that make it easy to design, edit, and preview emails; a developer friendly API; rock-solid deliverability; and detailed, real-time reporting that gives you a pulse on the lifeblood of your web app. [1]: http://postageapp.com/ ''' , name: 'PubNub' image: 'pubnub.png' url: 'http://www.pubnub.com/' description: ''' Real-time, publish and subscribe communication cloud offered as a web-service API. Our customers are building cool new real-time mobile, web and social apps using data push communication and mass broadcasting that run on Mobile, Tablet and Web. ''' , name: 'Pusher' image: 'pusher.png' url: 'http://pusher.com/' description: ''' Supercharge your app with __realtime__ events [Pusher][1] is a hosted __API__ for __quickly__, __easily__ and __securely__ adding __scalable__ realtime functionality via WebSockets to web and mobile apps. [1]: http://pusher.com/ ''' , name: '<NAME>' image: 'scopely.png' url: 'http://jobs.scopely.com/' description: ''' The hottest new consumer web startup in Los Angeles, [Scopely][1] is in stealth mode preparing to disrupt a segment of the social web that is ripe for innovation. The Scopely team includes 12 senior engineers and product managers from companies including <NAME>, <NAME>, <NAME>, and Saatchi and Saatchi. Current investors include <NAME>, G<NAME>yc<NAME>ft Partners, <NAME>, Windsor Media, <NAME>ures, The Collaborative Fund, <NAME>, <NAME>, and <NAME>. [1]: http://jobs.scopely.com/ ''' , name: 'Sleep<NAME>' image: 'sleepless.gif' url: 'http://sleepless.com/' description: ''' No sleeping, no waiting, no blocking... [Sleepless][1] is a software and Internet development company specializing in custom Node.js development and highly scalable, cloud-based, server-side infrastructure. We provide development, consulting, and analysis for projects large and small. Our teams are very highly skilled and possess a breadth and depth of experience rarely found. If you have a project or would like to work on one, find us at Sleepless.com. [1]: http://sleepless.com/ ''' , name: 'Sequoia Capital' image: 'sequoiacap.png' url: 'http://www.sequoiacap.com/' description: ''' Sequoia Capital provides [venture capital funding][1] to founders of startups who want to turn [business ideas][2] into enduring companies. As the "Entrepreneurs Behind the Entrepreneurs", Sequoia Capital's Partners have worked with innovators such as <NAME> of Apple Computer, <NAME> <NAME> of Oracle, <NAME>on of Linear Technology, <NAME> and <NAME> of Cisco Systems, <NAME> of NetApp, <NAME> and <NAME> of Yahoo!, <NAME> of NVIDIA, <NAME> of Flextronics, <NAME> and <NAME> of Google, <NAME> and <NAME> of YouTube, <NAME> and <NAME> of Aruba Networks, <NAME> of Zappos, <NAME> of Admob, <NAME> of Green Dot and <NAME> and <NAME> of LinkedIn. To learn more about Sequoia Capital visit [www.sequoiacap.com/us][3]. [1]: http://www.sequoiacap.com/us [2]: http://www.sequoiacap.com/ideas [3]: http://www.sequoiacap.com/us ''' , name: 'S<NAME>ast' image: 'spreecast.png' url: 'http://spreecast.com/' description: ''' Compelling conversations. Democratized media. Join the discussion. Get involved. [Join our invite list][1]. [1]: http://spreecast.com/ ''' , name: 'NodeConf SummerCamp' image: 'summercamp.gif' url: 'http://www.nodeconf.com/summercamp.html' description: ''' [NodeConf SummerCamp][1] is an unconference held at the Walker Creek Ranch in California. Developers of all skill levels are invited to discuss, learn, and build a stronger community. [1]: http://www.nodeconf.com/summercamp.html ''' , name: '<NAME>' image: 'sungard.png' url: 'http://sungard.com/' description: ''' SunGard Global Services combines business consulting, technology and professional services for financial services firms, energy companies and corporations. Leveraging SunGard’s global delivery model, more than 5,000 employees worldwide help customers manage their complex data needs, optimize end-to-end business processes and assist with systems integration, while providing full application development, maintenance, testing and support services. ''' , name: '<NAME>' image: 'tapjoy.png' url: 'https://www.tapjoy.com/' description: ''' [Tapjoy][1] is the success engine for mobile application distribution, engagement and revenue. The company’s turnkey in-app advertising platform helps developers acquire cost-effective, high-value new users, drive engagement within their applications, and create incremental income by providing an ad-funded payment method. The Tapjoy network spans over 9,000 applications and 200 million global consumers on iOS, Android and emerging mobile platforms, delivering more than 1.5 million advertising completions per day to applications developers and advertisers. Tapjoy is backed by top-tier investors including J.P.Morgan Asset Management, Rho Ventures, North Bridge Venture Partners, InterWest Partners and D.E<NAME>. Shaw Ventures. Headquartered in San Francisco, the company also has offices in New York, London and Tokyo. For more information, please visit [www.tapjoy.com][1]. [1]: https://www.tapjoy.com/ ''' , name: '<NAME>' image: 'tradeking.png' url: 'http://www.tradeking.com/' description: ''' [TradeKing][1] is a nationally licensed online broker dealer offering simple, low flat fees with no hidden fees or account minimums. A pioneer in integrating new social media as part of its innovative online trading platform, TradeKing recently launched a trading and market data API available at [developers.tradeking.com][2]. [1]: http://www.tradeking.com [2]: http://developers.tradeking.com ''' , name: 'Tropo' image: 'tropo.png' url: 'https://www.tropo.com/home.jsp' description: ''' [Tropo][1] makes it simple to build phone, SMS and Instant Messaging (IM) applications. You use the web technologies you already know and Tropo's powerful cloud API to bring real-time communications to your apps. Tropo empowers developers to build sophisticated, multi-channel communication applications with easy to use cloud-based components. Tropo is committed to fostering and supporting open source, open standards and open communications. [1]: https://www.tropo.com/home.jsp ''' , name: '<NAME>' image: 'twilio.png' url: 'http://www.twilio.com/' description: ''' [Twilio][1] is a cloud communications company that offers simple HTTP APIs for sending and receiving phone calls and text messages. [1]: http://www.twilio.com/ ''' ]
true
module.exports = [ name: 'Adobe' image: 'adobe.png' url: 'http://www.adobe.com/' description: ''' We help our customers create, deliver, and optimize compelling content and applications — improving the impact of their communications, enhancing their brands and productivity, and ultimately bringing them greater business success. Together, we're turning ordinary interactions into more valuable digital experiences every day, across media and devices, anywhere, anytime. ''' , name: 'PI:NAME:<NAME>END_PI' image: 'blitz.png' url: 'http://blitz.io/' description: ''' Blitz, powered by Mu Dynamics, is a self-service cloud based performance testing platform. Built for API, cloud, web and mobile app developers, Blitz quickly and inexpensively helps you ensure performance and scalability. ''' , name: 'PI:NAME:<NAME>END_PI' image: 'bislr.png' url: 'http://www.bislr.com/' description: ''' [Bislr][1] (pronounced Biz-ler) allows anyone to create an online business. Manage your website, blog, contacts and online marketing on the world’s first online business platform. Bislr uses Node.js at it's core and is proud to be supporting Node.js Knockout. [1]: http://www.bislr.com/ ''' , name: 'Cloud9' image: 'cloud9.png' url: 'http://cloud9ide.com/' description: ''' Cloud9 IDE is the first-ever cloud-based integrated development environment (IDE) for JavaScript developers, built on top of Node.js. Cloud9 enables Web developers to access, edit and share projects anywhere, anytime. ''' , name: 'Cloud Foundry' image: 'cloudfoundry.png' url: 'http://www.cloudfoundry.com/' description: ''' [Cloud Foundry&trade;][1] is the industry’s first open platform as a service and Micro Cloud Foundry&trade; is the industry’s first downloadable PaaS for your computer. Initiated by VMware, Cloud Foundry delivers access to modern frameworks including Spring for Java, Ruby for Rails and Sinatra, node.js, Grails, Scala on Lift and more. It provides application services including RabbitMQ and MySQL, MongoDB, Redis and more from third parties and the open source community. Cloud Foundry is downloadable and dramatically enhances developers’ abilities to build, test and deploy their applications with symmetry between private, public and hybrid clouds. [1]: http://www.cloudfoundry.com/ ''' , name: 'Couchbase' image: 'couchbase.png' url: 'http://www.couchbase.com/' description: ''' Apache [CouchDB][1] is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution. [1]: http://www.couchbase.com/ ''' , name: 'Dropbox' image: 'dropbox.png' url: 'http://www.dropbox.com/' description: ''' Today, more than 25 million people across every continent use [Dropbox][1] to always have their stuff at hand, share with family and friends, and work on team projects. We're looking for more great people to join us, so if you're excited to help simplify life for millions of people, check out our [jobs][2]. [1]: http://www.dropbox.com/ [2]: http://www.dropbox.com/jobs ''' , name: 'GPI:NAME:<NAME>END_PI' image: 'geeklist.png' url: 'http://geekli.st/' description: ''' [Get early access to our private beta][1] by requesting an invite and reserving your username. [1]: http://geekli.st/beta ''' , name: 'GitHub', image: 'github.png' url: 'https://github.com/' description: ''' Code is about the people writing it. We focus on lowering the barriers of collaboration by building powerful [features][1] into our products that make it easier to contribute. The tools we create help individuals and companies, public and private, to write better code, faster. [Ship it!][2] [1]: https://github.com/features/projects [2]: http://shipitsquirrel.github.com/ ''' , name: 'PI:NAME:<NAME>END_PI' image: 'heroku.png' url: 'http://www.heroku.com/' description: ''' Agile deployment for Ruby, Node.js and Clojure. Get up and running in minutes, and deploy instantly with git. Focus 100% on your code, and never think about servers, instances, or VMs again. ''' , name: 'PI:NAME:<NAME>END_PI' image: 'joyent.png' url: 'http://www.joyent.com/' description: ''' Joyent is a global cloud computing software and service provider that offers an integrated technology suite designed for service providers, enterprises, and developers. Joyent Cloud delivers public cloud services to some of the most innovative companies in the world, including LinkedIn, Gilt Groupe and Kabam. Joyent offerings also include Platform-as-a-Service based on Node.js, the open source server-side JavaScript development environment. For more information, visit <http://www.joyentcloud.com/> and <http://www.joyent.com/>. ''' , name: 'LinPI:NAME:<NAME>END_PI' image: 'linode.png' url: 'http://www.linode.com/index.cfm' description: ''' Deploy and Manage Linux Virtual Servers in the [Linode][1] Cloud. Get a server running in minutes with your choice of Linux distro, resources, and node location. [1]: http://www.linode.com/index.cfm ''' , name: 'MaxCDN' image: 'maxcdn.png' url: 'http://maxcdn.com/' description: ''' Simply put, [MaxCDN][1] gives you the most powerful control panel and CDN product in the industry – at a price you can afford. [1]: http://maxcdn.com/ ''' , name: 'Meebo' image: 'meebo.png' url: 'http://www.meebo.com/' description: ''' [Meebo][1] gives you the easiest, most open and most "right there where you want it" way to share on the web. [1]: http://www.meebo.com/ ''' , name: 'MongoHQ' image: 'mongohq.png' url: 'https://mongohq.com/home' description: ''' [MongoHQ][1] is the hosted database solution for getting your applications up and running on MongoDB, fast. From our free shared plans to custom dedicated solutions, we can handle all the different levels of your data layer. [1]: https://mongohq.com/home ''' , name: 'Mozilla' image: 'mozilla.png' url: 'http://www.mozilla.org/' description: ''' Mozilla, a non-profit organization and creator of Firefox whose [mission][1] is to promote openness, innovation and opportunity on the Web. [1]: http://www.mozilla.org/about/mission.html ''' , name: 'ngmoco' image: 'ngmoco.png' url: 'http://blog.ngmoco.com/' description: ''' In 2011 there will be more iOS/Android devices shipped than PCs/notebooks. We at [ngmoco:)][1] see a once-in-a-generation opportunity to build a Social Entertainment Network to serve this new audience. We provide Mobage, a powerful social framework for developers to build & amplify social in their games. We make the best social games, powered by ngCore, a technology framework to publish on multiple platforms from a single codebase. [1]: http://blog.ngmoco.com/ ''' , name: 'nodejitsu' image: 'nodejitsu.png' url: 'http://www.nodejitsu.com/' description: ''' Enterprise-class cloud hosting for node.js applications and websites. We're in __private beta__! [Signup for our beta session][1] and we'll send you an email. Also, [come hack with us during node.js knockout][2]. [1]: http://www.nodejitsu.com/ [2]: http://nodeknockout.com/locations#nyc ''' , name: 'nodeSocket' image: 'nodesocket.png' url: 'http://www.nodesocket.com/' description: ''' [NodeSocket][1] is a simple, scalable, and powerful node.js hosting platform and community for developers. NodeSocket provides a complete suite of developer focused tools and add-ons to assist developers build, deploy, scale, and monitor their node.js applications. __Request a [beta invitation][2] today.__ [1]: http://www.nodesocket.com/ [2]: http://beta.nodesocket.com/ ''' , name: 'PostageApp' image: 'postageapp.png' url: 'http://postageapp.com/' description: ''' [PostageApp][1] is a service that makes it easier to manage, deliver, and track emails from your web apps. HTML/CSS templates that make it easy to design, edit, and preview emails; a developer friendly API; rock-solid deliverability; and detailed, real-time reporting that gives you a pulse on the lifeblood of your web app. [1]: http://postageapp.com/ ''' , name: 'PubNub' image: 'pubnub.png' url: 'http://www.pubnub.com/' description: ''' Real-time, publish and subscribe communication cloud offered as a web-service API. Our customers are building cool new real-time mobile, web and social apps using data push communication and mass broadcasting that run on Mobile, Tablet and Web. ''' , name: 'Pusher' image: 'pusher.png' url: 'http://pusher.com/' description: ''' Supercharge your app with __realtime__ events [Pusher][1] is a hosted __API__ for __quickly__, __easily__ and __securely__ adding __scalable__ realtime functionality via WebSockets to web and mobile apps. [1]: http://pusher.com/ ''' , name: 'PI:NAME:<NAME>END_PI' image: 'scopely.png' url: 'http://jobs.scopely.com/' description: ''' The hottest new consumer web startup in Los Angeles, [Scopely][1] is in stealth mode preparing to disrupt a segment of the social web that is ripe for innovation. The Scopely team includes 12 senior engineers and product managers from companies including PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and Saatchi and Saatchi. Current investors include PI:NAME:<NAME>END_PI, GPI:NAME:<NAME>END_PIycPI:NAME:<NAME>END_PIft Partners, PI:NAME:<NAME>END_PI, Windsor Media, PI:NAME:<NAME>END_PIures, The Collaborative Fund, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI. [1]: http://jobs.scopely.com/ ''' , name: 'SleepPI:NAME:<NAME>END_PI' image: 'sleepless.gif' url: 'http://sleepless.com/' description: ''' No sleeping, no waiting, no blocking... [Sleepless][1] is a software and Internet development company specializing in custom Node.js development and highly scalable, cloud-based, server-side infrastructure. We provide development, consulting, and analysis for projects large and small. Our teams are very highly skilled and possess a breadth and depth of experience rarely found. If you have a project or would like to work on one, find us at Sleepless.com. [1]: http://sleepless.com/ ''' , name: 'Sequoia Capital' image: 'sequoiacap.png' url: 'http://www.sequoiacap.com/' description: ''' Sequoia Capital provides [venture capital funding][1] to founders of startups who want to turn [business ideas][2] into enduring companies. As the "Entrepreneurs Behind the Entrepreneurs", Sequoia Capital's Partners have worked with innovators such as PI:NAME:<NAME>END_PI of Apple Computer, PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI of Oracle, PI:NAME:<NAME>END_PIon of Linear Technology, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI of Cisco Systems, PI:NAME:<NAME>END_PI of NetApp, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI of Yahoo!, PI:NAME:<NAME>END_PI of NVIDIA, PI:NAME:<NAME>END_PI of Flextronics, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI of Google, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI of YouTube, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI of Aruba Networks, PI:NAME:<NAME>END_PI of Zappos, PI:NAME:<NAME>END_PI of Admob, PI:NAME:<NAME>END_PI of Green Dot and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI of LinkedIn. To learn more about Sequoia Capital visit [www.sequoiacap.com/us][3]. [1]: http://www.sequoiacap.com/us [2]: http://www.sequoiacap.com/ideas [3]: http://www.sequoiacap.com/us ''' , name: 'SPI:NAME:<NAME>END_PIast' image: 'spreecast.png' url: 'http://spreecast.com/' description: ''' Compelling conversations. Democratized media. Join the discussion. Get involved. [Join our invite list][1]. [1]: http://spreecast.com/ ''' , name: 'NodeConf SummerCamp' image: 'summercamp.gif' url: 'http://www.nodeconf.com/summercamp.html' description: ''' [NodeConf SummerCamp][1] is an unconference held at the Walker Creek Ranch in California. Developers of all skill levels are invited to discuss, learn, and build a stronger community. [1]: http://www.nodeconf.com/summercamp.html ''' , name: 'PI:NAME:<NAME>END_PI' image: 'sungard.png' url: 'http://sungard.com/' description: ''' SunGard Global Services combines business consulting, technology and professional services for financial services firms, energy companies and corporations. Leveraging SunGard’s global delivery model, more than 5,000 employees worldwide help customers manage their complex data needs, optimize end-to-end business processes and assist with systems integration, while providing full application development, maintenance, testing and support services. ''' , name: 'PI:NAME:<NAME>END_PI' image: 'tapjoy.png' url: 'https://www.tapjoy.com/' description: ''' [Tapjoy][1] is the success engine for mobile application distribution, engagement and revenue. The company’s turnkey in-app advertising platform helps developers acquire cost-effective, high-value new users, drive engagement within their applications, and create incremental income by providing an ad-funded payment method. The Tapjoy network spans over 9,000 applications and 200 million global consumers on iOS, Android and emerging mobile platforms, delivering more than 1.5 million advertising completions per day to applications developers and advertisers. Tapjoy is backed by top-tier investors including J.P.Morgan Asset Management, Rho Ventures, North Bridge Venture Partners, InterWest Partners and D.EPI:NAME:<NAME>END_PI. Shaw Ventures. Headquartered in San Francisco, the company also has offices in New York, London and Tokyo. For more information, please visit [www.tapjoy.com][1]. [1]: https://www.tapjoy.com/ ''' , name: 'PI:NAME:<NAME>END_PI' image: 'tradeking.png' url: 'http://www.tradeking.com/' description: ''' [TradeKing][1] is a nationally licensed online broker dealer offering simple, low flat fees with no hidden fees or account minimums. A pioneer in integrating new social media as part of its innovative online trading platform, TradeKing recently launched a trading and market data API available at [developers.tradeking.com][2]. [1]: http://www.tradeking.com [2]: http://developers.tradeking.com ''' , name: 'Tropo' image: 'tropo.png' url: 'https://www.tropo.com/home.jsp' description: ''' [Tropo][1] makes it simple to build phone, SMS and Instant Messaging (IM) applications. You use the web technologies you already know and Tropo's powerful cloud API to bring real-time communications to your apps. Tropo empowers developers to build sophisticated, multi-channel communication applications with easy to use cloud-based components. Tropo is committed to fostering and supporting open source, open standards and open communications. [1]: https://www.tropo.com/home.jsp ''' , name: 'PI:NAME:<NAME>END_PI' image: 'twilio.png' url: 'http://www.twilio.com/' description: ''' [Twilio][1] is a cloud communications company that offers simple HTTP APIs for sending and receiving phone calls and text messages. [1]: http://www.twilio.com/ ''' ]
[ { "context": "er.\n# https://docs.google.com/spreadsheet/ccc?key=0AlwCBXG5ae-wdGo5b3hRcnU1RDZsYlV2YVpjMWtNU0E\n\n# The order of these values must match the order", "end": 296, "score": 0.9996085166931152, "start": 252, "tag": "KEY", "value": "0AlwCBXG5ae-wdGo5b3hRcnU1RDZsYlV2YVpjMWtNU0E" }...
app/lib/animals.coffee
zooniverse/Serengeti
8
FilteringSet = require 'models/filtering_set' Animal = require 'models/animal' translate = require 't7e' # The master list of animals is generated from this spreadsheet that the science team put together. # https://docs.google.com/spreadsheet/ccc?key=0AlwCBXG5ae-wdGo5b3hRcnU1RDZsYlV2YVpjMWtNU0E # The order of these values must match the order in the spreadsheet. values = [ 'likeCatDog', 'likeCowHorse', 'likeAntelopeDeer', 'likeBird', 'likeOther', 'likeWeasel' 'patternVerticalStripe', 'patternHorizontalStripe', 'patternSpots', 'patternSolid' 'coatTanYellow', 'coatRedBrown', 'coatBrownBlack', 'coatWhite', 'coatGray', 'coatBlack' 'hornsNone', 'hornsStraight', 'hornsSimpleCurve', 'hornsLyrate', 'hornsCurly' 'tailBushy', 'tailSmooth', 'tailTufted', 'tailLong', 'tailShort' 'buildStocky', 'buildLanky', 'buildTall', 'buildSmall', 'buildLowSlung', 'buildSloped' ] # The order of characteristics is derived from the list of values. characteristics = ['like', 'pattern', 'coat', 'horns', 'tail', 'build'] # The animal names and "grid" values are from the spreadsheet. # Order matches the values. 1 means it describes that animal, 0 means it does not. # If you want to re-label an animal, do it in the translation file. animalCharacteristics = [ {aardvark: [0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0]} {aardwolf: [1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1]} {baboon: [1,0,0,0,1,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0]} {bat: [0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {batEaredFox: [1,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0]} {otherBird: [0,0,0,1,0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0]} {buffalo: [0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,0,0,0]} {bushbuck: [0,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,1,0,0,0,0]} {cattle: [0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0]} {caracal: [1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0]} {cheetah: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0]} {civet: [1,0,0,0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0]} {dikDik: [0,0,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0]} {duiker: [0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {eland: [0,1,1,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,0,0]} {elephant: [0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,0]} {gazelleGrants: [0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,0,1,0,1,0,0,0,0]} {gazelleThomsons: [0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0,0,1,0,1,0,1,0,0]} {genet: [1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0]} {giraffe: [0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,0,0,1]} {guineaFowl: [0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]} {hare: [0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {hartebeest: [0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1]} {hippopotamus: [0,0,0,0,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0]} {honeyBadger: [1,0,0,0,0,1,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,1,1,0]} {hyenaSpotted: [1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1]} {hyenaStriped: [1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1]} {impala: [0,0,1,0,0,0,0,1,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,0,0]} {insectSpider: [0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {jackal: [1,0,0,0,0,0,0,1,0,1,1,1,1,0,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,1,0,0]} {koriBustard: [0,0,0,1,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0]} {leopard: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,0,0,0,0]} {lionFemale: [1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0]} {lionMale: [1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0]} {mongoose: [0,0,0,0,1,1,1,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0]} {ostrich: [0,0,0,1,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0]} {porcupine: [0,0,0,0,1,0,0,0,1,1,0,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,1,0,0,1,1,0]} {reedbuck: [0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0]} {reptiles: [0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0]} {rhinoceros: [0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0]} {rodents: [0,0,0,0,1,0,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,0,1,0,0]} {secretaryBird: [0,0,0,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0]} {serval: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0]} {steenbok: [0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {topi: [0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,1]} {vervetMonkey: [0,0,0,0,1,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0]} {vulture: [0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {warthog: [0,0,0,0,1,0,0,0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0]} {waterbuck: [0,1,1,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0]} {wildcat: [1,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0]} {wildebeest: [0,1,1,0,0,0,0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0,1]} {zebra: [0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0]} {zorilla: [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0]} {human: [0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0]} ] dashedFromId = (id) -> id.replace /[A-Z]/g, (cap) -> "-#{cap.toLowerCase()}" imagesFromId = (id) -> [ "images/animals/#{dashedFromId id}-1.jpg" "images/animals/#{dashedFromId id}-2.jpg" "images/animals/#{dashedFromId id}-3.jpg" ] animals = new FilteringSet searchProperties: ['label', 'description'] items: for item in animalCharacteristics for id, grid of item animal = new Animal id: id label: translate('span', "animals.#{id}.label") description: translate('span', "animals.#{id}.description") images: imagesFromId id for char in characteristics animal[char] = (value for value, i in values when value[0...char.length] is char and grid[i] is 1) animal[char] = animal[char][0] if animal[char].length is 1 delete animal[char] if animal[char].length is 0 animal.save() animal module.exports = animals
155367
FilteringSet = require 'models/filtering_set' Animal = require 'models/animal' translate = require 't7e' # The master list of animals is generated from this spreadsheet that the science team put together. # https://docs.google.com/spreadsheet/ccc?key=<KEY> # The order of these values must match the order in the spreadsheet. values = [ 'likeCatDog', 'likeCowHorse', 'likeAntelopeDeer', 'likeBird', 'likeOther', 'likeWeasel' 'patternVerticalStripe', 'patternHorizontalStripe', 'patternSpots', 'patternSolid' 'coatTanYellow', 'coatRedBrown', 'coatBrownBlack', 'coatWhite', 'coatGray', 'coatBlack' 'hornsNone', 'hornsStraight', 'hornsSimpleCurve', 'hornsLyrate', 'hornsCurly' 'tailBushy', 'tailSmooth', 'tailTufted', 'tailLong', 'tailShort' 'buildStocky', 'buildLanky', 'buildTall', 'buildSmall', 'buildLowSlung', 'buildSloped' ] # The order of characteristics is derived from the list of values. characteristics = ['like', 'pattern', 'coat', 'horns', 'tail', 'build'] # The animal names and "grid" values are from the spreadsheet. # Order matches the values. 1 means it describes that animal, 0 means it does not. # If you want to re-label an animal, do it in the translation file. animalCharacteristics = [ {aardvark: [0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0]} {aardwolf: [1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1]} {baboon: [1,0,0,0,1,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0]} {bat: [0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {batEaredFox: [1,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0]} {otherBird: [0,0,0,1,0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0]} {buffalo: [0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,0,0,0]} {bushbuck: [0,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,1,0,0,0,0]} {cattle: [0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0]} {caracal: [1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0]} {cheetah: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0]} {civet: [1,0,0,0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0]} {dikDik: [0,0,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0]} {duiker: [0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {eland: [0,1,1,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,0,0]} {elephant: [0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,0]} {gazelleGrants: [0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,0,1,0,1,0,0,0,0]} {gazelleThomsons: [0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0,0,1,0,1,0,1,0,0]} {genet: [1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0]} {giraffe: [0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,0,0,1]} {guineaFowl: [0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]} {hare: [0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {hartebeest: [0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1]} {hippopotamus: [0,0,0,0,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0]} {honeyBadger: [1,0,0,0,0,1,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,1,1,0]} {hyenaSpotted: [1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1]} {hyenaStriped: [1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1]} {impala: [0,0,1,0,0,0,0,1,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,0,0]} {insectSpider: [0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {jackal: [1,0,0,0,0,0,0,1,0,1,1,1,1,0,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,1,0,0]} {koriBustard: [0,0,0,1,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0]} {leopard: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,0,0,0,0]} {lionFemale: [1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0]} {lionMale: [1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0]} {mongoose: [0,0,0,0,1,1,1,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0]} {ostrich: [0,0,0,1,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0]} {porcupine: [0,0,0,0,1,0,0,0,1,1,0,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,1,0,0,1,1,0]} {reedbuck: [0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0]} {reptiles: [0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0]} {rhinoceros: [0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0]} {rodents: [0,0,0,0,1,0,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,0,1,0,0]} {secretaryBird: [0,0,0,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0]} {serval: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0]} {steenbok: [0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {topi: [0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,1]} {vervetMonkey: [0,0,0,0,1,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0]} {vulture: [0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {warthog: [0,0,0,0,1,0,0,0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0]} {waterbuck: [0,1,1,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0]} {wildcat: [1,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0]} {wildebeest: [0,1,1,0,0,0,0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0,1]} {zebra: [0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0]} {zorilla: [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0]} {human: [0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0]} ] dashedFromId = (id) -> id.replace /[A-Z]/g, (cap) -> "-#{cap.toLowerCase()}" imagesFromId = (id) -> [ "images/animals/#{dashedFromId id}-1.jpg" "images/animals/#{dashedFromId id}-2.jpg" "images/animals/#{dashedFromId id}-3.jpg" ] animals = new FilteringSet searchProperties: ['label', 'description'] items: for item in animalCharacteristics for id, grid of item animal = new Animal id: id label: translate('span', "animals.#{id}.label") description: translate('span', "animals.#{id}.description") images: imagesFromId id for char in characteristics animal[char] = (value for value, i in values when value[0...char.length] is char and grid[i] is 1) animal[char] = animal[char][0] if animal[char].length is 1 delete animal[char] if animal[char].length is 0 animal.save() animal module.exports = animals
true
FilteringSet = require 'models/filtering_set' Animal = require 'models/animal' translate = require 't7e' # The master list of animals is generated from this spreadsheet that the science team put together. # https://docs.google.com/spreadsheet/ccc?key=PI:KEY:<KEY>END_PI # The order of these values must match the order in the spreadsheet. values = [ 'likeCatDog', 'likeCowHorse', 'likeAntelopeDeer', 'likeBird', 'likeOther', 'likeWeasel' 'patternVerticalStripe', 'patternHorizontalStripe', 'patternSpots', 'patternSolid' 'coatTanYellow', 'coatRedBrown', 'coatBrownBlack', 'coatWhite', 'coatGray', 'coatBlack' 'hornsNone', 'hornsStraight', 'hornsSimpleCurve', 'hornsLyrate', 'hornsCurly' 'tailBushy', 'tailSmooth', 'tailTufted', 'tailLong', 'tailShort' 'buildStocky', 'buildLanky', 'buildTall', 'buildSmall', 'buildLowSlung', 'buildSloped' ] # The order of characteristics is derived from the list of values. characteristics = ['like', 'pattern', 'coat', 'horns', 'tail', 'build'] # The animal names and "grid" values are from the spreadsheet. # Order matches the values. 1 means it describes that animal, 0 means it does not. # If you want to re-label an animal, do it in the translation file. animalCharacteristics = [ {aardvark: [0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0]} {aardwolf: [1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1]} {baboon: [1,0,0,0,1,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0]} {bat: [0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {batEaredFox: [1,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0]} {otherBird: [0,0,0,1,0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0]} {buffalo: [0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,0,0,0]} {bushbuck: [0,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,1,0,0,0,0]} {cattle: [0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0]} {caracal: [1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0]} {cheetah: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0]} {civet: [1,0,0,0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0]} {dikDik: [0,0,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0]} {duiker: [0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {eland: [0,1,1,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,0,0]} {elephant: [0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,0]} {gazelleGrants: [0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,0,1,0,1,0,0,0,0]} {gazelleThomsons: [0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0,0,1,0,1,0,1,0,0]} {genet: [1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0]} {giraffe: [0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,0,0,1]} {guineaFowl: [0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]} {hare: [0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {hartebeest: [0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1]} {hippopotamus: [0,0,0,0,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0]} {honeyBadger: [1,0,0,0,0,1,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,1,1,0]} {hyenaSpotted: [1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1]} {hyenaStriped: [1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1]} {impala: [0,0,1,0,0,0,0,1,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,0,0]} {insectSpider: [0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {jackal: [1,0,0,0,0,0,0,1,0,1,1,1,1,0,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,1,0,0]} {koriBustard: [0,0,0,1,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0]} {leopard: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,0,0,0,0]} {lionFemale: [1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0]} {lionMale: [1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0]} {mongoose: [0,0,0,0,1,1,1,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0]} {ostrich: [0,0,0,1,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0]} {porcupine: [0,0,0,0,1,0,0,0,1,1,0,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,1,0,0,1,1,0]} {reedbuck: [0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0]} {reptiles: [0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0]} {rhinoceros: [0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0]} {rodents: [0,0,0,0,1,0,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,0,1,0,0]} {secretaryBird: [0,0,0,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0]} {serval: [1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0]} {steenbok: [0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0]} {topi: [0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,1]} {vervetMonkey: [0,0,0,0,1,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0]} {vulture: [0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} {warthog: [0,0,0,0,1,0,0,0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0]} {waterbuck: [0,1,1,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0]} {wildcat: [1,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0]} {wildebeest: [0,1,1,0,0,0,0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0,1]} {zebra: [0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0]} {zorilla: [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0]} {human: [0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0]} ] dashedFromId = (id) -> id.replace /[A-Z]/g, (cap) -> "-#{cap.toLowerCase()}" imagesFromId = (id) -> [ "images/animals/#{dashedFromId id}-1.jpg" "images/animals/#{dashedFromId id}-2.jpg" "images/animals/#{dashedFromId id}-3.jpg" ] animals = new FilteringSet searchProperties: ['label', 'description'] items: for item in animalCharacteristics for id, grid of item animal = new Animal id: id label: translate('span', "animals.#{id}.label") description: translate('span', "animals.#{id}.description") images: imagesFromId id for char in characteristics animal[char] = (value for value, i in values when value[0...char.length] is char and grid[i] is 1) animal[char] = animal[char][0] if animal[char].length is 1 delete animal[char] if animal[char].length is 0 animal.save() animal module.exports = animals
[ { "context": ", '.ajax-form', ( ->\n data = user:\n \"email\": 'a@maildrop.cc'\n \"password\": 'password'\n \"remember_me\": 1\n", "end": 361, "score": 0.9999048709869385, "start": 348, "tag": "EMAIL", "value": "a@maildrop.cc" }, { "context": "er:\n \"email\": 'a@maildro...
app/assets/javascripts/home.coffee
mreigen/AQ-Test
12
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on 'ready page:load', -> Prism.highlightAll() $(document).on('click', '.ajax-form', ( -> data = user: "email": 'a@maildrop.cc' "password": 'password' "remember_me": 1 getData "/users/sign_in", data )); getData = (url, data) -> console.log(data) $.ajax url: url type: "POST" data: data dataType: "json", encoding: 'UTF-8' beforeSend: ajaxStart success: ajaxSuccess error: ajaxError complete: ajaxComplete xhrFields: withCredentials: true return ajaxStart = (xhrInstance) -> #A. Clear Any Previously Written HTML #B. Show Preloader csrf_token = $('meta[name="csrf-token"]').attr('content') xhrInstance.setRequestHeader('X-CSRF-Token', csrf_token); console.log 'ajaxStart:', csrf_token return ajaxError = (xhrInstance, message, optional) -> console.log 'ajaxError:', message, optional return ajaxComplete = (xhrInstance, status) -> #A. Remove any preloaders console.log 'ajaxComplete:' return ajaxSuccess = (data, status) -> #Write your Parse XML Function parseData data return parseData = (data) -> #console.log 'parseData:', data $('.ajax-response code').text JSON.stringify(data, null, '\t') return
48571
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on 'ready page:load', -> Prism.highlightAll() $(document).on('click', '.ajax-form', ( -> data = user: "email": '<EMAIL>' "password": '<PASSWORD>' "remember_me": 1 getData "/users/sign_in", data )); getData = (url, data) -> console.log(data) $.ajax url: url type: "POST" data: data dataType: "json", encoding: 'UTF-8' beforeSend: ajaxStart success: ajaxSuccess error: ajaxError complete: ajaxComplete xhrFields: withCredentials: true return ajaxStart = (xhrInstance) -> #A. Clear Any Previously Written HTML #B. Show Preloader csrf_token = $('meta[name="csrf-token"]').attr('content') xhrInstance.setRequestHeader('X-CSRF-Token', csrf_token); console.log 'ajaxStart:', csrf_token return ajaxError = (xhrInstance, message, optional) -> console.log 'ajaxError:', message, optional return ajaxComplete = (xhrInstance, status) -> #A. Remove any preloaders console.log 'ajaxComplete:' return ajaxSuccess = (data, status) -> #Write your Parse XML Function parseData data return parseData = (data) -> #console.log 'parseData:', data $('.ajax-response code').text JSON.stringify(data, null, '\t') return
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on 'ready page:load', -> Prism.highlightAll() $(document).on('click', '.ajax-form', ( -> data = user: "email": 'PI:EMAIL:<EMAIL>END_PI' "password": 'PI:PASSWORD:<PASSWORD>END_PI' "remember_me": 1 getData "/users/sign_in", data )); getData = (url, data) -> console.log(data) $.ajax url: url type: "POST" data: data dataType: "json", encoding: 'UTF-8' beforeSend: ajaxStart success: ajaxSuccess error: ajaxError complete: ajaxComplete xhrFields: withCredentials: true return ajaxStart = (xhrInstance) -> #A. Clear Any Previously Written HTML #B. Show Preloader csrf_token = $('meta[name="csrf-token"]').attr('content') xhrInstance.setRequestHeader('X-CSRF-Token', csrf_token); console.log 'ajaxStart:', csrf_token return ajaxError = (xhrInstance, message, optional) -> console.log 'ajaxError:', message, optional return ajaxComplete = (xhrInstance, status) -> #A. Remove any preloaders console.log 'ajaxComplete:' return ajaxSuccess = (data, status) -> #Write your Parse XML Function parseData data return parseData = (data) -> #console.log 'parseData:', data $('.ajax-response code').text JSON.stringify(data, null, '\t') return
[ { "context": "scope: scope })\n expect(scope.data.name).toBe('Gulangco Plate')", "end": 263, "score": 0.9995566010475159, "start": 249, "tag": "NAME", "value": "Gulangco Plate" } ]
src/app/main/mainCtrl.spec.coffee
SteefTheBeef/ng-gulp
0
describe 'MainCtrl Test', () -> beforeEach -> module 'mainCtrl' it 'should validate on true', inject ($rootScope, $controller) -> scope = $rootScope.$new() $controller('mainCtrl', {$scope: scope }) expect(scope.data.name).toBe('Gulangco Plate')
201759
describe 'MainCtrl Test', () -> beforeEach -> module 'mainCtrl' it 'should validate on true', inject ($rootScope, $controller) -> scope = $rootScope.$new() $controller('mainCtrl', {$scope: scope }) expect(scope.data.name).toBe('<NAME>')
true
describe 'MainCtrl Test', () -> beforeEach -> module 'mainCtrl' it 'should validate on true', inject ($rootScope, $controller) -> scope = $rootScope.$new() $controller('mainCtrl', {$scope: scope }) expect(scope.data.name).toBe('PI:NAME:<NAME>END_PI')
[ { "context": "amount_in_cents: 999\n\t\taccount:\n\t\t\taccount_code: \"user-123\"\n\n\n\tbeforeEach ->\n\t\t@user =\n\t\t\temail:\"tom@yahoo.c", "end": 453, "score": 0.8106220364570618, "start": 445, "tag": "KEY", "value": "user-123" }, { "context": ": \"user-123\"\n\n\n\tbeforeEach...
test/unit/coffee/Subscription/SubscriptionViewModelBuilderTests.coffee
dtu-compute/web-sharelatex
0
SandboxedModule = require('sandboxed-module') sinon = require 'sinon' should = require("chai").should() modulePath = '../../../../app/js/Features/Subscription/SubscriptionViewModelBuilder' describe 'SubscriptionViewModelBuilder', -> mockSubscription = uuid: "subscription-123-active" plan: name: "Gold" plan_code: "gold" current_period_ends_at: new Date() state: "active" unit_amount_in_cents: 999 account: account_code: "user-123" beforeEach -> @user = email:"tom@yahoo.com", _id: 'one', signUpDate: new Date('2000-10-01') @plan = name: "test plan" @SubscriptionFormatters = formatDate: sinon.stub().returns("Formatted date") formatPrice: sinon.stub().returns("Formatted price") @RecurlyWrapper = sign: sinon.stub().callsArgWith(1, null, "something") getSubscription: sinon.stub().callsArgWith 2, null, account: hosted_login_token: "hosted_login_token" @builder = SandboxedModule.require modulePath, requires: "settings-sharelatex": { apis: { recurly: { subdomain: "example.com" }}} "./RecurlyWrapper": @RecurlyWrapper "./PlansLocator": @PlansLocator = {} "./SubscriptionLocator": @SubscriptionLocator = {} "./SubscriptionFormatters": @SubscriptionFormatters "./LimitationsManager": {} "logger-sharelatex": log:-> warn:-> "underscore": {} @PlansLocator.findLocalPlanInSettings = sinon.stub().returns(@plan) @SubscriptionLocator.getUsersSubscription = sinon.stub().callsArgWith(1, null, mockSubscription) @SubscriptionLocator.getMemberSubscriptions = sinon.stub().callsArgWith(1, null, null) it 'builds the user view model', -> callback = (error, subscription, memberSubscriptions, billingDetailsLink) => @error = error @subscription = subscription @memberSubscriptions = memberSubscriptions @billingDetailsLink = billingDetailsLink @builder.buildUsersSubscriptionViewModel(@user, callback) @subscription.name.should.eq 'test plan' @subscription.nextPaymentDueAt.should.eq 'Formatted date' @subscription.price.should.eq 'Formatted price' @billingDetailsLink.should.eq "https://example.com.recurly.com/account/billing_info/edit?ht=hosted_login_token"
142203
SandboxedModule = require('sandboxed-module') sinon = require 'sinon' should = require("chai").should() modulePath = '../../../../app/js/Features/Subscription/SubscriptionViewModelBuilder' describe 'SubscriptionViewModelBuilder', -> mockSubscription = uuid: "subscription-123-active" plan: name: "Gold" plan_code: "gold" current_period_ends_at: new Date() state: "active" unit_amount_in_cents: 999 account: account_code: "<KEY>" beforeEach -> @user = email:"<EMAIL>", _id: 'one', signUpDate: new Date('2000-10-01') @plan = name: "test plan" @SubscriptionFormatters = formatDate: sinon.stub().returns("Formatted date") formatPrice: sinon.stub().returns("Formatted price") @RecurlyWrapper = sign: sinon.stub().callsArgWith(1, null, "something") getSubscription: sinon.stub().callsArgWith 2, null, account: hosted_login_token: "hosted_login_token" @builder = SandboxedModule.require modulePath, requires: "settings-sharelatex": { apis: { recurly: { subdomain: "example.com" }}} "./RecurlyWrapper": @RecurlyWrapper "./PlansLocator": @PlansLocator = {} "./SubscriptionLocator": @SubscriptionLocator = {} "./SubscriptionFormatters": @SubscriptionFormatters "./LimitationsManager": {} "logger-sharelatex": log:-> warn:-> "underscore": {} @PlansLocator.findLocalPlanInSettings = sinon.stub().returns(@plan) @SubscriptionLocator.getUsersSubscription = sinon.stub().callsArgWith(1, null, mockSubscription) @SubscriptionLocator.getMemberSubscriptions = sinon.stub().callsArgWith(1, null, null) it 'builds the user view model', -> callback = (error, subscription, memberSubscriptions, billingDetailsLink) => @error = error @subscription = subscription @memberSubscriptions = memberSubscriptions @billingDetailsLink = billingDetailsLink @builder.buildUsersSubscriptionViewModel(@user, callback) @subscription.name.should.eq 'test plan' @subscription.nextPaymentDueAt.should.eq 'Formatted date' @subscription.price.should.eq 'Formatted price' @billingDetailsLink.should.eq "https://example.com.recurly.com/account/billing_info/edit?ht=hosted_login_token"
true
SandboxedModule = require('sandboxed-module') sinon = require 'sinon' should = require("chai").should() modulePath = '../../../../app/js/Features/Subscription/SubscriptionViewModelBuilder' describe 'SubscriptionViewModelBuilder', -> mockSubscription = uuid: "subscription-123-active" plan: name: "Gold" plan_code: "gold" current_period_ends_at: new Date() state: "active" unit_amount_in_cents: 999 account: account_code: "PI:KEY:<KEY>END_PI" beforeEach -> @user = email:"PI:EMAIL:<EMAIL>END_PI", _id: 'one', signUpDate: new Date('2000-10-01') @plan = name: "test plan" @SubscriptionFormatters = formatDate: sinon.stub().returns("Formatted date") formatPrice: sinon.stub().returns("Formatted price") @RecurlyWrapper = sign: sinon.stub().callsArgWith(1, null, "something") getSubscription: sinon.stub().callsArgWith 2, null, account: hosted_login_token: "hosted_login_token" @builder = SandboxedModule.require modulePath, requires: "settings-sharelatex": { apis: { recurly: { subdomain: "example.com" }}} "./RecurlyWrapper": @RecurlyWrapper "./PlansLocator": @PlansLocator = {} "./SubscriptionLocator": @SubscriptionLocator = {} "./SubscriptionFormatters": @SubscriptionFormatters "./LimitationsManager": {} "logger-sharelatex": log:-> warn:-> "underscore": {} @PlansLocator.findLocalPlanInSettings = sinon.stub().returns(@plan) @SubscriptionLocator.getUsersSubscription = sinon.stub().callsArgWith(1, null, mockSubscription) @SubscriptionLocator.getMemberSubscriptions = sinon.stub().callsArgWith(1, null, null) it 'builds the user view model', -> callback = (error, subscription, memberSubscriptions, billingDetailsLink) => @error = error @subscription = subscription @memberSubscriptions = memberSubscriptions @billingDetailsLink = billingDetailsLink @builder.buildUsersSubscriptionViewModel(@user, callback) @subscription.name.should.eq 'test plan' @subscription.nextPaymentDueAt.should.eq 'Formatted date' @subscription.price.should.eq 'Formatted price' @billingDetailsLink.should.eq "https://example.com.recurly.com/account/billing_info/edit?ht=hosted_login_token"
[ { "context": "\": @fullHref()\n \"author\": {\n \"name\": \"Artsy Editorial\"\n }\n \"publisher\": {\n \"name\": \"Ar", "end": 9701, "score": 0.9996680021286011, "start": 9686, "tag": "NAME", "value": "Artsy Editorial" }, { "context": "al\"\n }\n ...
src/desktop/models/article.coffee
fossabot/force
0
_ = require 'underscore' _s = require 'underscore.string' Q = require 'bluebird-q' Backbone = require 'backbone' moment = require 'moment' momentTimezone = require 'moment-timezone' { POSITRON_URL, APP_URL, ARTSY_EDITORIAL_CHANNEL } = sd = require('sharify').data request = require 'superagent' Artwork = require '../models/artwork.coffee' Artworks = require '../collections/artworks.coffee' Partner = require '../models/partner.coffee' Channel = require '../models/channel.coffee' { crop, resize } = require '../components/resizer/index.coffee' Relations = require './mixins/relations/article.coffee' { stripTags } = require 'underscore.string' { compactObject } = require './mixins/compact_object.coffee' cheerio = require 'cheerio' module.exports = class Article extends Backbone.Model _.extend @prototype, Relations urlRoot: "#{POSITRON_URL}/api/articles" defaults: sections: [{ type: 'text', body: '' }] fetchWithRelated: (options = {}) -> # Deferred require Articles = require '../collections/articles.coffee' superArticles = new Articles Q.allSettled([ @fetch( error: options.error headers: 'X-Access-Token': options.accessToken or '' cache: true ) superArticles.fetch( error: options.error cache: true headers: 'X-Access-Token': options.accessToken or '' data: is_super_article: true ) ]).then => slideshowArtworks = new Artworks superArticle = null superSubArticles = new Articles calloutArticles = new Articles dfds = [] # Get slideshow artworks to render server-side carousel if @get('sections')?.length and (slideshow = _.first(@get 'sections')).type is 'slideshow' for item in slideshow.items when item.type is 'artwork' dfds.push new Artwork(id: item.id).fetch cache: true data: access_token: options.accessToken success: (artwork) -> slideshowArtworks.add(artwork) # Check if the article is a super article if @get('is_super_article') superArticle = this else # Check if the article is IN a super article dfds.push new Articles().fetch error: options.error cache: true headers: 'X-Access-Token': options.accessToken or '' data: super_article_for: @get('id') success: (articles) -> superArticle = articles?.models[0] # Partner Channel + Team Channels if @get('partner_channel_id') dfds.push (partner = new Partner(id: @get('partner_channel_id'))).fetch(cache: true) else if @get('channel_id') dfds.push (channel = new Channel(id: @get('channel_id'))).fetch(cache: true) # Callouts if @get('sections')?.length for item in @get('sections') when item.type is 'callout' and item.article dfds.push new Article(id: item.article).fetch cache: true data: access_token: options.accessToken success: (article) -> calloutArticles.add(article) Q.allSettled(dfds).then => superArticleDefferreds = if superArticle then superArticle.fetchSuperSubArticles(superSubArticles, options.accessToken) else [] Q.allSettled(superArticleDefferreds) .then => # Super Sub Article Ids superSubArticleIds = [] if superArticles.length for article in superArticles.models superSubArticleIds = superSubArticleIds.concat(article.get('super_article')?.related_articles) superSubArticles.orderByIds(superArticle.get('super_article').related_articles) if superArticle and superSubArticles?.length @set('channel', channel) if channel @set('partner', partner) if partner options.success?( article: this slideshowArtworks: slideshowArtworks superArticle: superArticle superSubArticles: superSubArticles superSubArticleIds: superSubArticleIds partner: partner if partner channel: channel if channel calloutArticles: calloutArticles ) isTopTier: -> @get('tier') is 1 href: -> "/article/#{@get('slug')}" fullHref: -> "#{APP_URL}/article/#{@get('slug')}" ampHref: -> "#{APP_URL}/article/#{@get('slug')}/amp" authorHref: -> if @get('author') then "/#{@get('author').profile_handle}" else @href() cropUrlFor: (attr, args...) -> crop @get(attr), args... date: (attr) -> if @get('channel_id') is ARTSY_EDITORIAL_CHANNEL momentTimezone(@get(attr)).tz('America/New_York') else moment(@get(attr)).local() formatDate: -> currentYear = moment().year() publishedYear = @date('published_at').year() year = if currentYear != publishedYear then " #{publishedYear}" else "" @date('published_at').format('MMMM Do') + year strip: (attr) -> stripTags(@get attr) byline: -> return _s.toSentence(_.pluck(@get('authors'), 'name')) if @hasAuthors() return _s.toSentence(_.pluck(@get('contributing_authors'), 'name')) if @hasContributingAuthors() return @get('author').name if @get('author') '' contributingByline: -> return _s.toSentence(_.pluck(@get('contributing_authors'), 'name')) if @hasContributingAuthors() '' hasContributingAuthors: -> @get('contributing_authors')?.length > 0 hasAuthors: -> @get('authors')?.length > 0 getAuthorArray: -> creator = [] creator.push @get('author').name if @get('author') creator = _.union(creator, _.pluck(@get('contributing_authors'), 'name')) if @get('contributing_authors')?.length creator getVideoUrls: -> urls = [] @get('sections').map (section) -> if section.type is 'video' urls.push section.url if @get('hero_section')?.type is 'video' urls.push @get('hero_section').url urls = _.flatten urls getBodyClass: (data) -> bodyClass = "body-article body-article-#{@get('layout')}" if @get('hero_section') and @get('hero_section').type == 'fullscreen' bodyClass += ' body-no-margins body-transparent-header body-transparent-header-white body-fullscreen-article' if @get('is_super_article') or data.superArticle bodyClass += ' body-no-header' if @isEOYSubArticle(data.superSubArticleIds, data.superArticle) bodyClass += ' body-eoy-2016' if @get('channel')?.isTeam() bodyClass += ' body-no-header is-sticky' bodyClass isEOYSubArticle: (subArticles = [], superArticle) -> subArticles.length > 0 and not @get('is_super_article') and superArticle?.id is sd.EOY_2016_ARTICLE prepForAMP: -> sections = _.map @get('sections'), (section) -> if section.type is 'text' $ = cheerio.load(section.body) $('a:empty').remove() $('p').each -> $(this).removeAttr 'isrender' section.body = $.html() section else if section.type in ['image_set', 'image_collection'] section.images = _.map section.images, (image) -> if image.type is 'image' and image.caption $ = cheerio.load(image.caption) $('p, i').each -> $(this).removeAttr 'isrender' $(this).removeAttr 'style' image.caption = $.html() image else image section else section @set 'sections', sections hasAMP: -> # AMP requires that images provide a width and height # Articles that have been converted to ImageCollections will have this info for section in @get('sections') return false if section.type in ['artworks', 'image'] return true if @get('layout') is 'news' and @get('published') return @get('featured') and @get('published') and @get('layout') in ['standard', 'feature'] fetchSuperSubArticles: (superSubArticles, accessToken = '') -> for id in @get('super_article').related_articles new Article(id: id).fetch cache: true headers: 'X-Access-Token': accessToken success: (article) => superSubArticles.add article getParselySection: -> if @get('channel_id') is ARTSY_EDITORIAL_CHANNEL 'Editorial' else if @get('channel_id') @get('channel')?.get('name') else if @get('partner_channel_id') 'Partner' else 'Other' # article metadata tag for parse.ly toJSONLD: -> tags = @get('tags') tags = tags.concat @get('layout') if @get('layout') tags = tags.concat @get('vertical').name if @get('vertical') tags = tags.concat @get('tracking_tags') if @get('tracking_tags') compactObject { "@context": "http://schema.org" "@type": "NewsArticle" "headline": @get('thumbnail_title') "url": @fullHref() "thumbnailUrl": @get('thumbnail_image') "datePublished": @get('published_at') "dateCreated": @get('published_at') "articleSection": @getParselySection() "creator": @getAuthorArray() "keywords": tags } toJSONLDAmp: -> compactObject { "@context": "http://schema.org" "@type": "NewsArticle" "headline": @get('thumbnail_title') "url": @fullHref() "thumbnailUrl": @get('thumbnail_image') "datePublished": @get('published_at') "dateCreated": @get('published_at') "dateModified": @get('updated_at') "articleSection": @getParselySection() "creator": @getAuthorArray() "keywords": @get('tags') "mainEntityOfPage": @fullHref() "author": { "name": "Artsy Editorial" } "publisher": { "name": "Artsy" "logo": { "url": sd.APP_URL + "/images/full_logo.png" "height": 103 "width": 300 } } "image": { "url": crop(@get('thumbnail_image'), width: 800, height: 600) "width": 800 "height": 600 } }
153848
_ = require 'underscore' _s = require 'underscore.string' Q = require 'bluebird-q' Backbone = require 'backbone' moment = require 'moment' momentTimezone = require 'moment-timezone' { POSITRON_URL, APP_URL, ARTSY_EDITORIAL_CHANNEL } = sd = require('sharify').data request = require 'superagent' Artwork = require '../models/artwork.coffee' Artworks = require '../collections/artworks.coffee' Partner = require '../models/partner.coffee' Channel = require '../models/channel.coffee' { crop, resize } = require '../components/resizer/index.coffee' Relations = require './mixins/relations/article.coffee' { stripTags } = require 'underscore.string' { compactObject } = require './mixins/compact_object.coffee' cheerio = require 'cheerio' module.exports = class Article extends Backbone.Model _.extend @prototype, Relations urlRoot: "#{POSITRON_URL}/api/articles" defaults: sections: [{ type: 'text', body: '' }] fetchWithRelated: (options = {}) -> # Deferred require Articles = require '../collections/articles.coffee' superArticles = new Articles Q.allSettled([ @fetch( error: options.error headers: 'X-Access-Token': options.accessToken or '' cache: true ) superArticles.fetch( error: options.error cache: true headers: 'X-Access-Token': options.accessToken or '' data: is_super_article: true ) ]).then => slideshowArtworks = new Artworks superArticle = null superSubArticles = new Articles calloutArticles = new Articles dfds = [] # Get slideshow artworks to render server-side carousel if @get('sections')?.length and (slideshow = _.first(@get 'sections')).type is 'slideshow' for item in slideshow.items when item.type is 'artwork' dfds.push new Artwork(id: item.id).fetch cache: true data: access_token: options.accessToken success: (artwork) -> slideshowArtworks.add(artwork) # Check if the article is a super article if @get('is_super_article') superArticle = this else # Check if the article is IN a super article dfds.push new Articles().fetch error: options.error cache: true headers: 'X-Access-Token': options.accessToken or '' data: super_article_for: @get('id') success: (articles) -> superArticle = articles?.models[0] # Partner Channel + Team Channels if @get('partner_channel_id') dfds.push (partner = new Partner(id: @get('partner_channel_id'))).fetch(cache: true) else if @get('channel_id') dfds.push (channel = new Channel(id: @get('channel_id'))).fetch(cache: true) # Callouts if @get('sections')?.length for item in @get('sections') when item.type is 'callout' and item.article dfds.push new Article(id: item.article).fetch cache: true data: access_token: options.accessToken success: (article) -> calloutArticles.add(article) Q.allSettled(dfds).then => superArticleDefferreds = if superArticle then superArticle.fetchSuperSubArticles(superSubArticles, options.accessToken) else [] Q.allSettled(superArticleDefferreds) .then => # Super Sub Article Ids superSubArticleIds = [] if superArticles.length for article in superArticles.models superSubArticleIds = superSubArticleIds.concat(article.get('super_article')?.related_articles) superSubArticles.orderByIds(superArticle.get('super_article').related_articles) if superArticle and superSubArticles?.length @set('channel', channel) if channel @set('partner', partner) if partner options.success?( article: this slideshowArtworks: slideshowArtworks superArticle: superArticle superSubArticles: superSubArticles superSubArticleIds: superSubArticleIds partner: partner if partner channel: channel if channel calloutArticles: calloutArticles ) isTopTier: -> @get('tier') is 1 href: -> "/article/#{@get('slug')}" fullHref: -> "#{APP_URL}/article/#{@get('slug')}" ampHref: -> "#{APP_URL}/article/#{@get('slug')}/amp" authorHref: -> if @get('author') then "/#{@get('author').profile_handle}" else @href() cropUrlFor: (attr, args...) -> crop @get(attr), args... date: (attr) -> if @get('channel_id') is ARTSY_EDITORIAL_CHANNEL momentTimezone(@get(attr)).tz('America/New_York') else moment(@get(attr)).local() formatDate: -> currentYear = moment().year() publishedYear = @date('published_at').year() year = if currentYear != publishedYear then " #{publishedYear}" else "" @date('published_at').format('MMMM Do') + year strip: (attr) -> stripTags(@get attr) byline: -> return _s.toSentence(_.pluck(@get('authors'), 'name')) if @hasAuthors() return _s.toSentence(_.pluck(@get('contributing_authors'), 'name')) if @hasContributingAuthors() return @get('author').name if @get('author') '' contributingByline: -> return _s.toSentence(_.pluck(@get('contributing_authors'), 'name')) if @hasContributingAuthors() '' hasContributingAuthors: -> @get('contributing_authors')?.length > 0 hasAuthors: -> @get('authors')?.length > 0 getAuthorArray: -> creator = [] creator.push @get('author').name if @get('author') creator = _.union(creator, _.pluck(@get('contributing_authors'), 'name')) if @get('contributing_authors')?.length creator getVideoUrls: -> urls = [] @get('sections').map (section) -> if section.type is 'video' urls.push section.url if @get('hero_section')?.type is 'video' urls.push @get('hero_section').url urls = _.flatten urls getBodyClass: (data) -> bodyClass = "body-article body-article-#{@get('layout')}" if @get('hero_section') and @get('hero_section').type == 'fullscreen' bodyClass += ' body-no-margins body-transparent-header body-transparent-header-white body-fullscreen-article' if @get('is_super_article') or data.superArticle bodyClass += ' body-no-header' if @isEOYSubArticle(data.superSubArticleIds, data.superArticle) bodyClass += ' body-eoy-2016' if @get('channel')?.isTeam() bodyClass += ' body-no-header is-sticky' bodyClass isEOYSubArticle: (subArticles = [], superArticle) -> subArticles.length > 0 and not @get('is_super_article') and superArticle?.id is sd.EOY_2016_ARTICLE prepForAMP: -> sections = _.map @get('sections'), (section) -> if section.type is 'text' $ = cheerio.load(section.body) $('a:empty').remove() $('p').each -> $(this).removeAttr 'isrender' section.body = $.html() section else if section.type in ['image_set', 'image_collection'] section.images = _.map section.images, (image) -> if image.type is 'image' and image.caption $ = cheerio.load(image.caption) $('p, i').each -> $(this).removeAttr 'isrender' $(this).removeAttr 'style' image.caption = $.html() image else image section else section @set 'sections', sections hasAMP: -> # AMP requires that images provide a width and height # Articles that have been converted to ImageCollections will have this info for section in @get('sections') return false if section.type in ['artworks', 'image'] return true if @get('layout') is 'news' and @get('published') return @get('featured') and @get('published') and @get('layout') in ['standard', 'feature'] fetchSuperSubArticles: (superSubArticles, accessToken = '') -> for id in @get('super_article').related_articles new Article(id: id).fetch cache: true headers: 'X-Access-Token': accessToken success: (article) => superSubArticles.add article getParselySection: -> if @get('channel_id') is ARTSY_EDITORIAL_CHANNEL 'Editorial' else if @get('channel_id') @get('channel')?.get('name') else if @get('partner_channel_id') 'Partner' else 'Other' # article metadata tag for parse.ly toJSONLD: -> tags = @get('tags') tags = tags.concat @get('layout') if @get('layout') tags = tags.concat @get('vertical').name if @get('vertical') tags = tags.concat @get('tracking_tags') if @get('tracking_tags') compactObject { "@context": "http://schema.org" "@type": "NewsArticle" "headline": @get('thumbnail_title') "url": @fullHref() "thumbnailUrl": @get('thumbnail_image') "datePublished": @get('published_at') "dateCreated": @get('published_at') "articleSection": @getParselySection() "creator": @getAuthorArray() "keywords": tags } toJSONLDAmp: -> compactObject { "@context": "http://schema.org" "@type": "NewsArticle" "headline": @get('thumbnail_title') "url": @fullHref() "thumbnailUrl": @get('thumbnail_image') "datePublished": @get('published_at') "dateCreated": @get('published_at') "dateModified": @get('updated_at') "articleSection": @getParselySection() "creator": @getAuthorArray() "keywords": @get('tags') "mainEntityOfPage": @fullHref() "author": { "name": "<NAME>" } "publisher": { "name": "<NAME>" "logo": { "url": sd.APP_URL + "/images/full_logo.png" "height": 103 "width": 300 } } "image": { "url": crop(@get('thumbnail_image'), width: 800, height: 600) "width": 800 "height": 600 } }
true
_ = require 'underscore' _s = require 'underscore.string' Q = require 'bluebird-q' Backbone = require 'backbone' moment = require 'moment' momentTimezone = require 'moment-timezone' { POSITRON_URL, APP_URL, ARTSY_EDITORIAL_CHANNEL } = sd = require('sharify').data request = require 'superagent' Artwork = require '../models/artwork.coffee' Artworks = require '../collections/artworks.coffee' Partner = require '../models/partner.coffee' Channel = require '../models/channel.coffee' { crop, resize } = require '../components/resizer/index.coffee' Relations = require './mixins/relations/article.coffee' { stripTags } = require 'underscore.string' { compactObject } = require './mixins/compact_object.coffee' cheerio = require 'cheerio' module.exports = class Article extends Backbone.Model _.extend @prototype, Relations urlRoot: "#{POSITRON_URL}/api/articles" defaults: sections: [{ type: 'text', body: '' }] fetchWithRelated: (options = {}) -> # Deferred require Articles = require '../collections/articles.coffee' superArticles = new Articles Q.allSettled([ @fetch( error: options.error headers: 'X-Access-Token': options.accessToken or '' cache: true ) superArticles.fetch( error: options.error cache: true headers: 'X-Access-Token': options.accessToken or '' data: is_super_article: true ) ]).then => slideshowArtworks = new Artworks superArticle = null superSubArticles = new Articles calloutArticles = new Articles dfds = [] # Get slideshow artworks to render server-side carousel if @get('sections')?.length and (slideshow = _.first(@get 'sections')).type is 'slideshow' for item in slideshow.items when item.type is 'artwork' dfds.push new Artwork(id: item.id).fetch cache: true data: access_token: options.accessToken success: (artwork) -> slideshowArtworks.add(artwork) # Check if the article is a super article if @get('is_super_article') superArticle = this else # Check if the article is IN a super article dfds.push new Articles().fetch error: options.error cache: true headers: 'X-Access-Token': options.accessToken or '' data: super_article_for: @get('id') success: (articles) -> superArticle = articles?.models[0] # Partner Channel + Team Channels if @get('partner_channel_id') dfds.push (partner = new Partner(id: @get('partner_channel_id'))).fetch(cache: true) else if @get('channel_id') dfds.push (channel = new Channel(id: @get('channel_id'))).fetch(cache: true) # Callouts if @get('sections')?.length for item in @get('sections') when item.type is 'callout' and item.article dfds.push new Article(id: item.article).fetch cache: true data: access_token: options.accessToken success: (article) -> calloutArticles.add(article) Q.allSettled(dfds).then => superArticleDefferreds = if superArticle then superArticle.fetchSuperSubArticles(superSubArticles, options.accessToken) else [] Q.allSettled(superArticleDefferreds) .then => # Super Sub Article Ids superSubArticleIds = [] if superArticles.length for article in superArticles.models superSubArticleIds = superSubArticleIds.concat(article.get('super_article')?.related_articles) superSubArticles.orderByIds(superArticle.get('super_article').related_articles) if superArticle and superSubArticles?.length @set('channel', channel) if channel @set('partner', partner) if partner options.success?( article: this slideshowArtworks: slideshowArtworks superArticle: superArticle superSubArticles: superSubArticles superSubArticleIds: superSubArticleIds partner: partner if partner channel: channel if channel calloutArticles: calloutArticles ) isTopTier: -> @get('tier') is 1 href: -> "/article/#{@get('slug')}" fullHref: -> "#{APP_URL}/article/#{@get('slug')}" ampHref: -> "#{APP_URL}/article/#{@get('slug')}/amp" authorHref: -> if @get('author') then "/#{@get('author').profile_handle}" else @href() cropUrlFor: (attr, args...) -> crop @get(attr), args... date: (attr) -> if @get('channel_id') is ARTSY_EDITORIAL_CHANNEL momentTimezone(@get(attr)).tz('America/New_York') else moment(@get(attr)).local() formatDate: -> currentYear = moment().year() publishedYear = @date('published_at').year() year = if currentYear != publishedYear then " #{publishedYear}" else "" @date('published_at').format('MMMM Do') + year strip: (attr) -> stripTags(@get attr) byline: -> return _s.toSentence(_.pluck(@get('authors'), 'name')) if @hasAuthors() return _s.toSentence(_.pluck(@get('contributing_authors'), 'name')) if @hasContributingAuthors() return @get('author').name if @get('author') '' contributingByline: -> return _s.toSentence(_.pluck(@get('contributing_authors'), 'name')) if @hasContributingAuthors() '' hasContributingAuthors: -> @get('contributing_authors')?.length > 0 hasAuthors: -> @get('authors')?.length > 0 getAuthorArray: -> creator = [] creator.push @get('author').name if @get('author') creator = _.union(creator, _.pluck(@get('contributing_authors'), 'name')) if @get('contributing_authors')?.length creator getVideoUrls: -> urls = [] @get('sections').map (section) -> if section.type is 'video' urls.push section.url if @get('hero_section')?.type is 'video' urls.push @get('hero_section').url urls = _.flatten urls getBodyClass: (data) -> bodyClass = "body-article body-article-#{@get('layout')}" if @get('hero_section') and @get('hero_section').type == 'fullscreen' bodyClass += ' body-no-margins body-transparent-header body-transparent-header-white body-fullscreen-article' if @get('is_super_article') or data.superArticle bodyClass += ' body-no-header' if @isEOYSubArticle(data.superSubArticleIds, data.superArticle) bodyClass += ' body-eoy-2016' if @get('channel')?.isTeam() bodyClass += ' body-no-header is-sticky' bodyClass isEOYSubArticle: (subArticles = [], superArticle) -> subArticles.length > 0 and not @get('is_super_article') and superArticle?.id is sd.EOY_2016_ARTICLE prepForAMP: -> sections = _.map @get('sections'), (section) -> if section.type is 'text' $ = cheerio.load(section.body) $('a:empty').remove() $('p').each -> $(this).removeAttr 'isrender' section.body = $.html() section else if section.type in ['image_set', 'image_collection'] section.images = _.map section.images, (image) -> if image.type is 'image' and image.caption $ = cheerio.load(image.caption) $('p, i').each -> $(this).removeAttr 'isrender' $(this).removeAttr 'style' image.caption = $.html() image else image section else section @set 'sections', sections hasAMP: -> # AMP requires that images provide a width and height # Articles that have been converted to ImageCollections will have this info for section in @get('sections') return false if section.type in ['artworks', 'image'] return true if @get('layout') is 'news' and @get('published') return @get('featured') and @get('published') and @get('layout') in ['standard', 'feature'] fetchSuperSubArticles: (superSubArticles, accessToken = '') -> for id in @get('super_article').related_articles new Article(id: id).fetch cache: true headers: 'X-Access-Token': accessToken success: (article) => superSubArticles.add article getParselySection: -> if @get('channel_id') is ARTSY_EDITORIAL_CHANNEL 'Editorial' else if @get('channel_id') @get('channel')?.get('name') else if @get('partner_channel_id') 'Partner' else 'Other' # article metadata tag for parse.ly toJSONLD: -> tags = @get('tags') tags = tags.concat @get('layout') if @get('layout') tags = tags.concat @get('vertical').name if @get('vertical') tags = tags.concat @get('tracking_tags') if @get('tracking_tags') compactObject { "@context": "http://schema.org" "@type": "NewsArticle" "headline": @get('thumbnail_title') "url": @fullHref() "thumbnailUrl": @get('thumbnail_image') "datePublished": @get('published_at') "dateCreated": @get('published_at') "articleSection": @getParselySection() "creator": @getAuthorArray() "keywords": tags } toJSONLDAmp: -> compactObject { "@context": "http://schema.org" "@type": "NewsArticle" "headline": @get('thumbnail_title') "url": @fullHref() "thumbnailUrl": @get('thumbnail_image') "datePublished": @get('published_at') "dateCreated": @get('published_at') "dateModified": @get('updated_at') "articleSection": @getParselySection() "creator": @getAuthorArray() "keywords": @get('tags') "mainEntityOfPage": @fullHref() "author": { "name": "PI:NAME:<NAME>END_PI" } "publisher": { "name": "PI:NAME:<NAME>END_PI" "logo": { "url": sd.APP_URL + "/images/full_logo.png" "height": 103 "width": 300 } } "image": { "url": crop(@get('thumbnail_image'), width: 800, height: 600) "width": 800 "height": 600 } }
[ { "context": "###\n X-Wing Card Browser\n Geordan Rosario <geordan@gmail.com>\n https://github.com/georda", "end": 47, "score": 0.9998932480812073, "start": 32, "tag": "NAME", "value": "Geordan Rosario" }, { "context": "###\n X-Wing Card Browser\n Geordan Rosario <geor...
coffeescripts/browser.coffee
jpkelm/xwing
0
### X-Wing Card Browser Geordan Rosario <geordan@gmail.com> https://github.com/geordanr/xwing ### exportObj = exports ? this # Assumes cards.js has been loaded TYPES = [ 'pilots', 'upgrades' ] byName = (a, b) -> if a.display_name a_name = a.display_name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') else a_name = a.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') if b.display_name b_name = b.display_name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') else b_name = b.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') if a_name < b_name -1 else if b_name < a_name 1 else 0 byPoints = (a, b) -> if a.data.points < b.data.points -1 else if b.data.points < a.data.points 1 else byName a, b String::capitalize = -> this.charAt(0).toUpperCase() + this.slice(1) class exportObj.CardBrowser constructor: (args) -> # args @container = $ args.container # internals @currently_selected = null @language = 'English' @prepareData() @setupUI() @setupHandlers() @sort_selector.change() setupUI: () -> @container.append $.trim """ <div class="container-fluid xwing-card-browser"> <div class="row-fluid"> <div class="span12"> <span class="translate sort-cards-by">Sort cards by</span>: <select class="sort-by"> <option value="name">Name</option> <option value="source">Source</option> <option value="type-by-points">Type (by Points)</option> <option value="type-by-name" selected="1">Type (by Name)</option> </select> </div> </div> <div class="row-fluid"> <div class="span4 card-selector-container"> </div> <div class="span8"> <div class="well card-search-container"> <input type="search" placeholder="Search for name, text or ship" class = "card-search-text">"""+ #TODO: Add more search input options here. """ <button class="btn btn-primary show-advanced-search"> Advanced Search </button> <div class="advanced-search-container"> <div class= "advanced-search-faction-selection-container"> <strong>Faction:</strong> <label class = "toggle-rebel-search advanced-search-label"> <input type="checkbox" class="rebel-checkbox advanced-search-checkbox" checked="checked" /> Rebel </label> <label class = "toggle-imperial-search advanced-search-label"> <input type="checkbox" class="imperial-checkbox advanced-search-checkbox" checked="checked" /> Imperial </label> <label class = "toggle-scum-search advanced-search-label"> <input type="checkbox" class="scum-checkbox advanced-search-checkbox" checked="checked" /> Scum </label> <label class = "toggle-fo-search advanced-search-label"> <input type="checkbox" class="fo-checkbox advanced-search-checkbox" checked="checked" /> First Order </label> <label class = "toggle-resistance-search advanced-search-label"> <input type="checkbox" class="resistance-checkbox advanced-search-checkbox" checked="checked" /> Resistance </label> <label class = "toggle-separatist-search advanced-search-label"> <input type="checkbox" class="separatist-checkbox advanced-search-checkbox" checked="checked" /> Separatist </label> <label class = "toggle-republic-search advanced-search-label"> <input type="checkbox" class="republic-checkbox advanced-search-checkbox" checked="checked" /> Republic </label> <label class = "toggle-factionless-search advanced-search-label"> <input type="checkbox" class="factionless-checkbox advanced-search-checkbox" checked="checked" /> Factionless <span class="advanced-search-tooltip" tooltip="A card is considered factionless, if it can be used by more than one faction."> &#9432 </span> </label> </div> <div class = "advanced-search-point-selection-container"> <strong>Point costs:</strong> <label class = "advanced-search-label set-minimum-points"> from <input type="number" class="minimum-point-cost advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-points"> to <input type="number" class="maximum-point-cost advanced-search-number-input" value="200" /> </label> <label class = "advanced-search-label toggle-variable-cost-search"> <input type="checkbox" class="variable-point-cost-checkbox advanced-search-checkbox" checked="checked" /> Variable point cost </label> </div> <div class = "advanced-search-collection-container"> <strong>Owned copies:</strong> <label class = "advanced-search-label set-minimum-owned-copies"> from <input type="number" class="minimum-owned-copies advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-owened-copies"> to <input type="number" class="maximum-owned-copies advanced-search-number-input" value="100" /> </label> </div> <div class = "advanced-search-slot-available-container"> <label class = "advanced-search-label select-available-slots"> <strong>Available slots: </strong> <select class="advanced-search-selection slot-available-selection" multiple="1" data-placeholder="No slots selected"></select> <span class="advanced-search-tooltip" tooltip="Search for pilots having all selected slots available."> &#9432 </span> </label> </div> <div class = "advanced-search-slot-used-container"> <label class = "advanced-search-label select-used-slots"> <strong>Used slot: </strong> <select class="advanced-search-selection slot-used-selection" multiple="1" data-placeholder="No slots selected"></select> <span class="advanced-search-tooltip" tooltip="Search for upgrades using any of the selected slots."> &#9432 </span> </label> </div> <div class = "advanced-search-charge-container"> <strong>Charges:</strong> <label class = "advanced-search-label set-minimum-charge"> from <input type="number" class="minimum-charge advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-charge"> to <input type="number" class="maximum-charge advanced-search-number-input" value="5" /> </label> <label class = "advanced-search-label has-recurring-charge"> <input type="checkbox" class="advanced-search-checkbox has-recurring-charge-checkbox" checked="checked"/> recurring </label> <label class = "advanced-search-label has-not-recurring-charge"> <input type="checkbox" class="advanced-search-checkbox has-not-recurring-charge-checkbox" checked="checked"/> not recurring </label> </div> <div class = "advanced-search-misc-container"> <strong>Misc:</strong> <label class = "advanced-search-label toggle-unique"> <input type="checkbox" class="unique-checkbox advanced-search-checkbox" /> Is unique </label> <label class = "advanced-search-label toggle-second-edition"> <input type="checkbox" class="second-edition-checkbox advanced-search-checkbox" /> Second-Edition only <span class="advanced-search-tooltip" tooltip="Check to exclude cards only obtainable from conversion kits."> &#9432 </span> </label> </div> </div> </div> <div class="well card-viewer-placeholder info-well"> <p class="translate select-a-card">Select a card from the list at the left.</p> </div> <div class="well card-viewer-container info-well"> <span class="info-name"></span> <br /> <span class="info-type"></span> <br /> <span class="info-sources"></span> <br /> <span class="info-collection"></span> <table> <tbody> <tr class="info-skill"> <td class="info-header">Skill</td> <td class="info-data info-skill"></td> </tr> <tr class="info-energy"> <td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td> <td class="info-data info-energy"></td> </tr> <tr class="info-attack"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-fullfront"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-bullseye"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-back"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-turret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-doubleturret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-agility"> <td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td> <td class="info-data info-agility"></td> </tr> <tr class="info-hull"> <td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td> <td class="info-data info-hull"></td> </tr> <tr class="info-shields"> <td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td> <td class="info-data info-shields"></td> </tr> <tr class="info-force"> <td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td> <td class="info-data info-force"></td> </tr> <tr class="info-charge"> <td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td> <td class="info-data info-charge"></td> </tr> <tr class="info-range"> <td class="info-header">Range</td> <td class="info-data info-range"></td> </tr> <tr class="info-actions"> <td class="info-header">Actions</td> <td class="info-data"></td> </tr> <tr class="info-actions-red"> <td></td> <td class="info-data-red"></td> </tr> <tr class="info-upgrades"> <td class="info-header">Upgrades</td> <td class="info-data"></td> </tr> </tbody> </table> <p class="info-text" /> </div> </div> </div> </div> """ @card_selector_container = $ @container.find('.xwing-card-browser .card-selector-container') @card_viewer_container = $ @container.find('.xwing-card-browser .card-viewer-container') @card_viewer_container.hide() @card_viewer_placeholder = $ @container.find('.xwing-card-browser .card-viewer-placeholder') @advanced_search_button = ($ @container.find('.xwing-card-browser .show-advanced-search'))[0] @advanced_search_container = $ @container.find('.xwing-card-browser .advanced-search-container') @advanced_search_container.hide() @advanced_search_active = false @sort_selector = $ @container.find('select.sort-by') @sort_selector.select2 minimumResultsForSearch: -1 # TODO: Make added inputs easy accessible @card_search_text = ($ @container.find('.xwing-card-browser .card-search-text'))[0] @faction_selectors = {} @faction_selectors["Rebel Alliance"] = ($ @container.find('.xwing-card-browser .rebel-checkbox'))[0] @faction_selectors["Scum and Villainy"] = ($ @container.find('.xwing-card-browser .scum-checkbox'))[0] @faction_selectors["Galactic Empire"] = ($ @container.find('.xwing-card-browser .imperial-checkbox'))[0] @faction_selectors["Resistance"] = ($ @container.find('.xwing-card-browser .resistance-checkbox'))[0] @faction_selectors["First Order"] = ($ @container.find('.xwing-card-browser .fo-checkbox'))[0] @faction_selectors["Separatist Alliance"] = ($ @container.find('.xwing-card-browser .separatist-checkbox'))[0] @faction_selectors["Galactic Republic"] = ($ @container.find('.xwing-card-browser .republic-checkbox'))[0] @faction_selectors[undefined] = ($ @container.find('.xwing-card-browser .factionless-checkbox'))[0] @minimum_point_costs = ($ @container.find('.xwing-card-browser .minimum-point-cost'))[0] @maximum_point_costs = ($ @container.find('.xwing-card-browser .maximum-point-cost'))[0] @variable_point_costs = ($ @container.find('.xwing-card-browser .variable-point-cost-checkbox'))[0] @second_edition_checkbox = ($ @container.find('.xwing-card-browser .second-edition-checkbox'))[0] @unique_checkbox = ($ @container.find('.xwing-card-browser .unique-checkbox'))[0] @slot_available_selection = ($ @container.find('.xwing-card-browser select.slot-available-selection')) for slot of exportObj.upgradesBySlotCanonicalName opt = $ document.createElement('OPTION') opt.text slot @slot_available_selection.append opt @slot_available_selection.select2 minimumResultsForSearch: if $.isMobile() then -1 else 0 @slot_used_selection = ($ @container.find('.xwing-card-browser select.slot-used-selection')) for slot of exportObj.upgradesBySlotCanonicalName opt = $ document.createElement('OPTION') opt.text slot @slot_used_selection.append opt @slot_used_selection.select2 minimumResultsForSearch: if $.isMobile() then -1 else 0 @minimum_charge = ($ @container.find('.xwing-card-browser .minimum-charge'))[0] @maximum_charge = ($ @container.find('.xwing-card-browser .maximum-charge'))[0] @recurring_charge = ($ @container.find('.xwing-card-browser .has-recurring-charge-checkbox'))[0] @not_recurring_charge = ($ @container.find('.xwing-card-browser .has-not-recurring-charge-checkbox'))[0] @minimum_owned_copies = ($ @container.find('.xwing-card-browser .minimum-owned-copies'))[0] @maximum_owned_copies = ($ @container.find('.xwing-card-browser .maximum-owned-copies'))[0] setupHandlers: () -> @sort_selector.change (e) => @renderList @sort_selector.val() $(window).on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) => @language = language @prepareData() @renderList @sort_selector.val() @card_search_text.oninput = => @renderList @sort_selector.val() # TODO: Add a call to @renderList for added inputs, to start the actual search @advanced_search_button.onclick = @toggleAdvancedSearch for faction, checkbox of @faction_selectors checkbox.onclick = => @renderList @sort_selector.val() @minimum_point_costs.oninput = => @renderList @sort_selector.val() @maximum_point_costs.oninput = => @renderList @sort_selector.val() @variable_point_costs.onclick = => @renderList @sort_selector.val() @second_edition_checkbox.onclick = => @renderList @sort_selector.val() @unique_checkbox.onclick = => @renderList @sort_selector.val() @slot_available_selection[0].onchange = => @renderList @sort_selector.val() @slot_used_selection[0].onchange = => @renderList @sort_selector.val() @recurring_charge.onclick = => @renderList @sort_selector.val() @not_recurring_charge.onclick = => @renderList @sort_selector.val() @minimum_charge.oninput = => @renderList @sort_selector.val() @maximum_charge.oninput = => @renderList @sort_selector.val() @minimum_owned_copies.oninput = => @renderList @sort_selector.val() @maximum_owned_copies.oninput = => @renderList @sort_selector.val() toggleAdvancedSearch: () => if @advanced_search_active @advanced_search_container.hide() else @advanced_search_container.show() @advanced_search_active = not @advanced_search_active @renderList @sort_selector.val() prepareData: () -> @all_cards = [] for type in TYPES if type == 'upgrades' @all_cards = @all_cards.concat ( { name: card_data.name, display_name: card_data.display_name, type: exportObj.translate(@language, 'ui', 'upgradeHeader', card_data.slot), data: card_data, orig_type: card_data.slot } for card_name, card_data of exportObj[type] ) else @all_cards = @all_cards.concat ( { name: card_data.name, display_name: card_data.display_name, type: exportObj.translate(@language, 'singular', type), data: card_data, orig_type: exportObj.translate('English', 'singular', type) } for card_name, card_data of exportObj[type] ) @types = (exportObj.translate(@language, 'types', type) for type in [ 'Pilot' ]) for card_name, card_data of exportObj.upgrades upgrade_text = exportObj.translate @language, 'ui', 'upgradeHeader', card_data.slot @types.push upgrade_text if upgrade_text not in @types @all_cards.sort byName @sources = [] for card in @all_cards for source in card.data.sources @sources.push(source) if source not in @sources sorted_types = @types.sort() sorted_sources = @sources.sort() @cards_by_type_name = {} for type in sorted_types @cards_by_type_name[type] = ( card for card in @all_cards when card.type == type ).sort byName @cards_by_type_points = {} for type in sorted_types @cards_by_type_points[type] = ( card for card in @all_cards when card.type == type ).sort byPoints @cards_by_source = {} for source in sorted_sources @cards_by_source[source] = ( card for card in @all_cards when source in card.data.sources ).sort byName renderList: (sort_by='name') -> # sort_by is one of `name`, `type-by-name`, `source`, `type-by-points` # # Renders multiselect to container # Selects previously selected card if there is one @card_selector.remove() if @card_selector? @card_selector = $ document.createElement('SELECT') @card_selector.addClass 'card-selector' @card_selector.attr 'size', 25 @card_selector_container.append @card_selector switch sort_by when 'type-by-name' for type in @types optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', type card_added = false for card in @cards_by_type_name[type] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup when 'type-by-points' for type in @types optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', type card_added = false for card in @cards_by_type_points[type] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup when 'source' for source in @sources optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', source card_added = false for card in @cards_by_source[source] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup else for card in @all_cards if @checkSearchCriteria card @addCardTo @card_selector, card @card_selector.change (e) => @renderCard $(@card_selector.find(':selected')) renderCard: (card) -> # Renders card to card container display_name = card.data 'display_name' name = card.data 'name' type = card.data 'type' data = card.data 'card' orig_type = card.data 'orig_type' @card_viewer_container.find('.info-name').html """#{if data.unique then "&middot;&nbsp;" else ""}#{if display_name then display_name else name} (#{data.points})#{if data.limited? then " (#{exportObj.translate(@language, 'ui', 'limited')})" else ""}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" @card_viewer_container.find('p.info-text').html data.text ? '' @card_viewer_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') switch orig_type when 'Pilot' ship = exportObj.ships[data.ship] @card_viewer_container.find('.info-type').text "#{data.ship} Pilot (#{data.faction})" if exportObj.builders[0].collection?.counts? ship_count = exportObj.builders[0].collection.counts?.ship?[data.ship] ? 0 pilot_count = exportObj.builders[0].collection.counts?.pilot?[data.name] ? 0 @card_viewer_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection.""" else @card_viewer_container.find('.info-collection').text '' @card_viewer_container.find('tr.info-skill td.info-data').text data.skill @card_viewer_container.find('tr.info-skill').show() @card_viewer_container.find('tr.info-attack td.info-data').text(data.ship_override?.attack ? ship.attack) @card_viewer_container.find('tr.info-attack-bullseye td.info-data').text(ship.attackbull) @card_viewer_container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf) @card_viewer_container.find('tr.info-attack-back td.info-data').text(ship.attackb) @card_viewer_container.find('tr.info-attack-turret td.info-data').text(ship.attackt) @card_viewer_container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt) @card_viewer_container.find('tr.info-attack').toggle(ship.attack?) @card_viewer_container.find('tr.info-attack-bullseye').toggle(ship.attackbull?) @card_viewer_container.find('tr.info-attack-fullfront').toggle(ship.attackf?) @card_viewer_container.find('tr.info-attack-back').toggle(ship.attackb?) @card_viewer_container.find('tr.info-attack-turret').toggle(ship.attackt?) @card_viewer_container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?) for cls in @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-attack') @card_viewer_container.find('tr.info-energy td.info-data').text(data.ship_override?.energy ? ship.energy) @card_viewer_container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?) @card_viewer_container.find('tr.info-range').hide() @card_viewer_container.find('tr.info-agility td.info-data').text(data.ship_override?.agility ? ship.agility) @card_viewer_container.find('tr.info-agility').show() @card_viewer_container.find('tr.info-hull td.info-data').text(data.ship_override?.hull ? ship.hull) @card_viewer_container.find('tr.info-hull').show() @card_viewer_container.find('tr.info-shields td.info-data').text(data.ship_override?.shields ? ship.shields) @card_viewer_container.find('tr.info-shields').show() if data.force? @card_viewer_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') @card_viewer_container.find('tr.info-force td.info-header').show() @card_viewer_container.find('tr.info-force').show() else @card_viewer_container.find('tr.info-force').hide() if data.charge? if data.recurring? @card_viewer_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') else @card_viewer_container.find('tr.info-charge td.info-data').text data.charge @card_viewer_container.find('tr.info-charge').show() else @card_viewer_container.find('tr.info-charge').hide() @card_viewer_container.find('tr.info-actions td.info-data').html (((exportObj.translate(@language, 'action', action) for action in exportObj.ships[data.ship].actions).join(', ')).replace(/, <r><i class="xwing-miniatures-font xwing-miniatures-font-linked">/g,' <r><i class="xwing-miniatures-font xwing-miniatures-font-linked">')).replace(/, <i class="xwing-miniatures-font xwing-miniatures-font-linked">/g,' <i class="xwing-miniatures-font xwing-miniatures-font-linked">') #super ghetto double replace for linked actions @card_viewer_container.find('tr.info-actions').show() if ships[data.ship].actionsred? @card_viewer_container.find('tr.info-actions-red td.info-data').html (exportObj.translate(@language, 'action', action) for action in exportObj.ships[data.ship].actionsred).join(' ') @card_viewer_container.find('tr.info-actions-red').show() else @card_viewer_container.find('tr.info-actions-red').hide() @card_viewer_container.find('tr.info-upgrades').show() @card_viewer_container.find('tr.info-upgrades td.info-data').html((exportObj.translate(@language, 'sloticon', slot) for slot in data.slots).join(' ') or 'None') else @card_viewer_container.find('.info-type').text type @card_viewer_container.find('.info-type').append " &ndash; #{data.faction} only" if data.faction? if exportObj.builders[0].collection?.counts? addon_count = exportObj.builders[0].collection.counts.upgrade[data.name] ? 0 @card_viewer_container.find('.info-collection').text """You have #{addon_count} in your collection.""" else @card_viewer_container.find('.info-collection').text '' @card_viewer_container.find('tr.info-ship').hide() @card_viewer_container.find('tr.info-skill').hide() if data.energy? @card_viewer_container.find('tr.info-energy td.info-data').text data.energy @card_viewer_container.find('tr.info-energy').show() else @card_viewer_container.find('tr.info-energy').hide() if data.attack? @card_viewer_container.find('tr.info-attack td.info-data').text data.attack @card_viewer_container.find('tr.info-attack').show() else @card_viewer_container.find('tr.info-attack').hide() if data.attackbull? @card_viewer_container.find('tr.info-attack-bullseye td.info-data').text data.attackbull @card_viewer_container.find('tr.info-attack-bullseye').show() else @card_viewer_container.find('tr.info-attack-bullseye').hide() if data.attackt? @card_viewer_container.find('tr.info-attack-turret td.info-data').text data.attackt @card_viewer_container.find('tr.info-attack-turret').show() else @card_viewer_container.find('tr.info-attack-turret').hide() if data.range? @card_viewer_container.find('tr.info-range td.info-data').text data.range @card_viewer_container.find('tr.info-range').show() else @card_viewer_container.find('tr.info-range').hide() if data.force? @card_viewer_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') @card_viewer_container.find('tr.info-force td.info-header').show() @card_viewer_container.find('tr.info-force').show() else @card_viewer_container.find('tr.info-force').hide() if data.charge? if data.recurring? @card_viewer_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') else @card_viewer_container.find('tr.info-charge td.info-data').text data.charge @card_viewer_container.find('tr.info-charge').show() else @card_viewer_container.find('tr.info-charge').hide() @card_viewer_container.find('tr.info-attack-fullfront').hide() @card_viewer_container.find('tr.info-attack-back').hide() @card_viewer_container.find('tr.info-attack-doubleturret').hide() @card_viewer_container.find('tr.info-agility').hide() @card_viewer_container.find('tr.info-hull').hide() @card_viewer_container.find('tr.info-shields').hide() @card_viewer_container.find('tr.info-actions').hide() @card_viewer_container.find('tr.info-actions-red').hide() @card_viewer_container.find('tr.info-upgrades').hide() @card_viewer_container.show() @card_viewer_placeholder.hide() addCardTo: (container, card) -> option = $ document.createElement('OPTION') option.text "#{if card.display_name then card.display_name else card.name} (#{card.data.points})" option.data 'name', card.name option.data 'display_name', card.display_name option.data 'type', card.type option.data 'card', card.data option.data 'orig_type', card.orig_type if @getCollectionNumber(card) == 0 option[0].classList.add('result-not-in-collection') $(container).append option getCollectionNumber: (card) -> # returns number of copies of the given card in the collection, or -1 if no collection loaded if not (exportObj.builders[0].collection? and exportObj.builders[0].collection.counts?) return -1 owned_copies = 0 switch card.orig_type when 'Pilot' owned_copies = exportObj.builders[0].collection.counts.pilot?[card.name] ? 0 when 'Ship' owned_copies = exportObj.builders[0].collection.counts.ship?[card.name] ? 0 else # type is e.g. astromech owned_copies = exportObj.builders[0].collection.counts.upgrade?[card.name] ? 0 owned_copies checkSearchCriteria: (card) -> # check for text search search_text = @card_search_text.value.toLowerCase() text_search = card.name.toLowerCase().indexOf(search_text) > -1 or (card.data.text and card.data.text.toLowerCase().indexOf(search_text)) > -1 or (card.display_name and card.display_name.toLowerCase().indexOf(search_text) > -1) if not text_search return false unless card.data.ship ship = card.data.ship if ship instanceof Array text_in_ship = false for s in ship if s.toLowerCase().indexOf(search_text) > -1 or (exportObj.ships[s].display_name and exportObj.ships[s].display_name.toLowerCase().indexOf(search_text) > -1) text_in_ship = true break return false unless text_in_ship else return false unless ship.toLowerCase().indexOf(search_text) > -1 or (exportObj.ships[ship].display_name and exportObj.ships[ship].display_name.toLowerCase().indexOf(search_text) > -1) # prevent the three virtual hardpoint cards from beeing displayed return false unless card.data.slot != "Hardpoint" # check if advanced search is enabled return true unless @advanced_search_active # check if faction matches return false unless @faction_selectors[card.data.faction].checked # check if second-edition only matches return false unless exportObj.secondEditionCheck(card.data) or not @second_edition_checkbox.checked # check for slot requirements required_slots = @slot_available_selection.val() if required_slots for slot in required_slots return false unless card.data.slots? and slot in card.data.slots # check if point costs matches return false unless (card.data.points >= @minimum_point_costs.value and card.data.points <= @maximum_point_costs.value) or (@variable_point_costs.checked and card.data.points == "*") # check if used slot matches used_slots = @slot_used_selection.val() if used_slots return false unless card.data.slot? matches = false for slot in used_slots if card.data.slot == slot matches = true break return false unless matches # check for uniqueness return false unless not @unique_checkbox.checked or card.data.unique # check charge stuff return false unless (card.data.charge? and card.data.charge <= @maximum_charge.value and card.data.charge >= @minimum_charge.value) or (@minimum_charge.value <= 0 and not card.data.charge?) return false if card.data.recurring and not @recurring_charge.checked return false if card.data.charge and not card.data.recurring and not @not_recurring_charge.checked # check collection status if exportObj.builders[0].collection?.counts? # ignore collection stuff, if no collection available owned_copies = @getCollectionNumber(card) return false unless owned_copies >= @minimum_owned_copies.value and owned_copies <= @maximum_owned_copies.value #TODO: Add logic of addiditional search criteria here. Have a look at card.data, to see what data is available. Add search inputs at the todo marks above. return true
159488
### X-Wing Card Browser <NAME> <<EMAIL>> https://github.com/geordanr/xwing ### exportObj = exports ? this # Assumes cards.js has been loaded TYPES = [ 'pilots', 'upgrades' ] byName = (a, b) -> if a.display_name a_name = a.display_name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') else a_name = a.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') if b.display_name b_name = b.display_name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') else b_name = b.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') if a_name < b_name -1 else if b_name < a_name 1 else 0 byPoints = (a, b) -> if a.data.points < b.data.points -1 else if b.data.points < a.data.points 1 else byName a, b String::capitalize = -> this.charAt(0).toUpperCase() + this.slice(1) class exportObj.CardBrowser constructor: (args) -> # args @container = $ args.container # internals @currently_selected = null @language = 'English' @prepareData() @setupUI() @setupHandlers() @sort_selector.change() setupUI: () -> @container.append $.trim """ <div class="container-fluid xwing-card-browser"> <div class="row-fluid"> <div class="span12"> <span class="translate sort-cards-by">Sort cards by</span>: <select class="sort-by"> <option value="name">Name</option> <option value="source">Source</option> <option value="type-by-points">Type (by Points)</option> <option value="type-by-name" selected="1">Type (by Name)</option> </select> </div> </div> <div class="row-fluid"> <div class="span4 card-selector-container"> </div> <div class="span8"> <div class="well card-search-container"> <input type="search" placeholder="Search for name, text or ship" class = "card-search-text">"""+ #TODO: Add more search input options here. """ <button class="btn btn-primary show-advanced-search"> Advanced Search </button> <div class="advanced-search-container"> <div class= "advanced-search-faction-selection-container"> <strong>Faction:</strong> <label class = "toggle-rebel-search advanced-search-label"> <input type="checkbox" class="rebel-checkbox advanced-search-checkbox" checked="checked" /> Rebel </label> <label class = "toggle-imperial-search advanced-search-label"> <input type="checkbox" class="imperial-checkbox advanced-search-checkbox" checked="checked" /> Imperial </label> <label class = "toggle-scum-search advanced-search-label"> <input type="checkbox" class="scum-checkbox advanced-search-checkbox" checked="checked" /> Scum </label> <label class = "toggle-fo-search advanced-search-label"> <input type="checkbox" class="fo-checkbox advanced-search-checkbox" checked="checked" /> First Order </label> <label class = "toggle-resistance-search advanced-search-label"> <input type="checkbox" class="resistance-checkbox advanced-search-checkbox" checked="checked" /> Resistance </label> <label class = "toggle-separatist-search advanced-search-label"> <input type="checkbox" class="separatist-checkbox advanced-search-checkbox" checked="checked" /> Separatist </label> <label class = "toggle-republic-search advanced-search-label"> <input type="checkbox" class="republic-checkbox advanced-search-checkbox" checked="checked" /> Republic </label> <label class = "toggle-factionless-search advanced-search-label"> <input type="checkbox" class="factionless-checkbox advanced-search-checkbox" checked="checked" /> Factionless <span class="advanced-search-tooltip" tooltip="A card is considered factionless, if it can be used by more than one faction."> &#9432 </span> </label> </div> <div class = "advanced-search-point-selection-container"> <strong>Point costs:</strong> <label class = "advanced-search-label set-minimum-points"> from <input type="number" class="minimum-point-cost advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-points"> to <input type="number" class="maximum-point-cost advanced-search-number-input" value="200" /> </label> <label class = "advanced-search-label toggle-variable-cost-search"> <input type="checkbox" class="variable-point-cost-checkbox advanced-search-checkbox" checked="checked" /> Variable point cost </label> </div> <div class = "advanced-search-collection-container"> <strong>Owned copies:</strong> <label class = "advanced-search-label set-minimum-owned-copies"> from <input type="number" class="minimum-owned-copies advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-owened-copies"> to <input type="number" class="maximum-owned-copies advanced-search-number-input" value="100" /> </label> </div> <div class = "advanced-search-slot-available-container"> <label class = "advanced-search-label select-available-slots"> <strong>Available slots: </strong> <select class="advanced-search-selection slot-available-selection" multiple="1" data-placeholder="No slots selected"></select> <span class="advanced-search-tooltip" tooltip="Search for pilots having all selected slots available."> &#9432 </span> </label> </div> <div class = "advanced-search-slot-used-container"> <label class = "advanced-search-label select-used-slots"> <strong>Used slot: </strong> <select class="advanced-search-selection slot-used-selection" multiple="1" data-placeholder="No slots selected"></select> <span class="advanced-search-tooltip" tooltip="Search for upgrades using any of the selected slots."> &#9432 </span> </label> </div> <div class = "advanced-search-charge-container"> <strong>Charges:</strong> <label class = "advanced-search-label set-minimum-charge"> from <input type="number" class="minimum-charge advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-charge"> to <input type="number" class="maximum-charge advanced-search-number-input" value="5" /> </label> <label class = "advanced-search-label has-recurring-charge"> <input type="checkbox" class="advanced-search-checkbox has-recurring-charge-checkbox" checked="checked"/> recurring </label> <label class = "advanced-search-label has-not-recurring-charge"> <input type="checkbox" class="advanced-search-checkbox has-not-recurring-charge-checkbox" checked="checked"/> not recurring </label> </div> <div class = "advanced-search-misc-container"> <strong>Misc:</strong> <label class = "advanced-search-label toggle-unique"> <input type="checkbox" class="unique-checkbox advanced-search-checkbox" /> Is unique </label> <label class = "advanced-search-label toggle-second-edition"> <input type="checkbox" class="second-edition-checkbox advanced-search-checkbox" /> Second-Edition only <span class="advanced-search-tooltip" tooltip="Check to exclude cards only obtainable from conversion kits."> &#9432 </span> </label> </div> </div> </div> <div class="well card-viewer-placeholder info-well"> <p class="translate select-a-card">Select a card from the list at the left.</p> </div> <div class="well card-viewer-container info-well"> <span class="info-name"></span> <br /> <span class="info-type"></span> <br /> <span class="info-sources"></span> <br /> <span class="info-collection"></span> <table> <tbody> <tr class="info-skill"> <td class="info-header">Skill</td> <td class="info-data info-skill"></td> </tr> <tr class="info-energy"> <td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td> <td class="info-data info-energy"></td> </tr> <tr class="info-attack"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-fullfront"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-bullseye"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-back"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-turret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-doubleturret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-agility"> <td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td> <td class="info-data info-agility"></td> </tr> <tr class="info-hull"> <td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td> <td class="info-data info-hull"></td> </tr> <tr class="info-shields"> <td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td> <td class="info-data info-shields"></td> </tr> <tr class="info-force"> <td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td> <td class="info-data info-force"></td> </tr> <tr class="info-charge"> <td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td> <td class="info-data info-charge"></td> </tr> <tr class="info-range"> <td class="info-header">Range</td> <td class="info-data info-range"></td> </tr> <tr class="info-actions"> <td class="info-header">Actions</td> <td class="info-data"></td> </tr> <tr class="info-actions-red"> <td></td> <td class="info-data-red"></td> </tr> <tr class="info-upgrades"> <td class="info-header">Upgrades</td> <td class="info-data"></td> </tr> </tbody> </table> <p class="info-text" /> </div> </div> </div> </div> """ @card_selector_container = $ @container.find('.xwing-card-browser .card-selector-container') @card_viewer_container = $ @container.find('.xwing-card-browser .card-viewer-container') @card_viewer_container.hide() @card_viewer_placeholder = $ @container.find('.xwing-card-browser .card-viewer-placeholder') @advanced_search_button = ($ @container.find('.xwing-card-browser .show-advanced-search'))[0] @advanced_search_container = $ @container.find('.xwing-card-browser .advanced-search-container') @advanced_search_container.hide() @advanced_search_active = false @sort_selector = $ @container.find('select.sort-by') @sort_selector.select2 minimumResultsForSearch: -1 # TODO: Make added inputs easy accessible @card_search_text = ($ @container.find('.xwing-card-browser .card-search-text'))[0] @faction_selectors = {} @faction_selectors["Rebel Alliance"] = ($ @container.find('.xwing-card-browser .rebel-checkbox'))[0] @faction_selectors["Scum and Villainy"] = ($ @container.find('.xwing-card-browser .scum-checkbox'))[0] @faction_selectors["Galactic Empire"] = ($ @container.find('.xwing-card-browser .imperial-checkbox'))[0] @faction_selectors["Resistance"] = ($ @container.find('.xwing-card-browser .resistance-checkbox'))[0] @faction_selectors["First Order"] = ($ @container.find('.xwing-card-browser .fo-checkbox'))[0] @faction_selectors["Separatist Alliance"] = ($ @container.find('.xwing-card-browser .separatist-checkbox'))[0] @faction_selectors["Galactic Republic"] = ($ @container.find('.xwing-card-browser .republic-checkbox'))[0] @faction_selectors[undefined] = ($ @container.find('.xwing-card-browser .factionless-checkbox'))[0] @minimum_point_costs = ($ @container.find('.xwing-card-browser .minimum-point-cost'))[0] @maximum_point_costs = ($ @container.find('.xwing-card-browser .maximum-point-cost'))[0] @variable_point_costs = ($ @container.find('.xwing-card-browser .variable-point-cost-checkbox'))[0] @second_edition_checkbox = ($ @container.find('.xwing-card-browser .second-edition-checkbox'))[0] @unique_checkbox = ($ @container.find('.xwing-card-browser .unique-checkbox'))[0] @slot_available_selection = ($ @container.find('.xwing-card-browser select.slot-available-selection')) for slot of exportObj.upgradesBySlotCanonicalName opt = $ document.createElement('OPTION') opt.text slot @slot_available_selection.append opt @slot_available_selection.select2 minimumResultsForSearch: if $.isMobile() then -1 else 0 @slot_used_selection = ($ @container.find('.xwing-card-browser select.slot-used-selection')) for slot of exportObj.upgradesBySlotCanonicalName opt = $ document.createElement('OPTION') opt.text slot @slot_used_selection.append opt @slot_used_selection.select2 minimumResultsForSearch: if $.isMobile() then -1 else 0 @minimum_charge = ($ @container.find('.xwing-card-browser .minimum-charge'))[0] @maximum_charge = ($ @container.find('.xwing-card-browser .maximum-charge'))[0] @recurring_charge = ($ @container.find('.xwing-card-browser .has-recurring-charge-checkbox'))[0] @not_recurring_charge = ($ @container.find('.xwing-card-browser .has-not-recurring-charge-checkbox'))[0] @minimum_owned_copies = ($ @container.find('.xwing-card-browser .minimum-owned-copies'))[0] @maximum_owned_copies = ($ @container.find('.xwing-card-browser .maximum-owned-copies'))[0] setupHandlers: () -> @sort_selector.change (e) => @renderList @sort_selector.val() $(window).on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) => @language = language @prepareData() @renderList @sort_selector.val() @card_search_text.oninput = => @renderList @sort_selector.val() # TODO: Add a call to @renderList for added inputs, to start the actual search @advanced_search_button.onclick = @toggleAdvancedSearch for faction, checkbox of @faction_selectors checkbox.onclick = => @renderList @sort_selector.val() @minimum_point_costs.oninput = => @renderList @sort_selector.val() @maximum_point_costs.oninput = => @renderList @sort_selector.val() @variable_point_costs.onclick = => @renderList @sort_selector.val() @second_edition_checkbox.onclick = => @renderList @sort_selector.val() @unique_checkbox.onclick = => @renderList @sort_selector.val() @slot_available_selection[0].onchange = => @renderList @sort_selector.val() @slot_used_selection[0].onchange = => @renderList @sort_selector.val() @recurring_charge.onclick = => @renderList @sort_selector.val() @not_recurring_charge.onclick = => @renderList @sort_selector.val() @minimum_charge.oninput = => @renderList @sort_selector.val() @maximum_charge.oninput = => @renderList @sort_selector.val() @minimum_owned_copies.oninput = => @renderList @sort_selector.val() @maximum_owned_copies.oninput = => @renderList @sort_selector.val() toggleAdvancedSearch: () => if @advanced_search_active @advanced_search_container.hide() else @advanced_search_container.show() @advanced_search_active = not @advanced_search_active @renderList @sort_selector.val() prepareData: () -> @all_cards = [] for type in TYPES if type == 'upgrades' @all_cards = @all_cards.concat ( { name: card_data.name, display_name: card_data.display_name, type: exportObj.translate(@language, 'ui', 'upgradeHeader', card_data.slot), data: card_data, orig_type: card_data.slot } for card_name, card_data of exportObj[type] ) else @all_cards = @all_cards.concat ( { name: card_data.name, display_name: card_data.display_name, type: exportObj.translate(@language, 'singular', type), data: card_data, orig_type: exportObj.translate('English', 'singular', type) } for card_name, card_data of exportObj[type] ) @types = (exportObj.translate(@language, 'types', type) for type in [ 'Pilot' ]) for card_name, card_data of exportObj.upgrades upgrade_text = exportObj.translate @language, 'ui', 'upgradeHeader', card_data.slot @types.push upgrade_text if upgrade_text not in @types @all_cards.sort byName @sources = [] for card in @all_cards for source in card.data.sources @sources.push(source) if source not in @sources sorted_types = @types.sort() sorted_sources = @sources.sort() @cards_by_type_name = {} for type in sorted_types @cards_by_type_name[type] = ( card for card in @all_cards when card.type == type ).sort byName @cards_by_type_points = {} for type in sorted_types @cards_by_type_points[type] = ( card for card in @all_cards when card.type == type ).sort byPoints @cards_by_source = {} for source in sorted_sources @cards_by_source[source] = ( card for card in @all_cards when source in card.data.sources ).sort byName renderList: (sort_by='name') -> # sort_by is one of `name`, `type-by-name`, `source`, `type-by-points` # # Renders multiselect to container # Selects previously selected card if there is one @card_selector.remove() if @card_selector? @card_selector = $ document.createElement('SELECT') @card_selector.addClass 'card-selector' @card_selector.attr 'size', 25 @card_selector_container.append @card_selector switch sort_by when 'type-by-name' for type in @types optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', type card_added = false for card in @cards_by_type_name[type] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup when 'type-by-points' for type in @types optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', type card_added = false for card in @cards_by_type_points[type] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup when 'source' for source in @sources optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', source card_added = false for card in @cards_by_source[source] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup else for card in @all_cards if @checkSearchCriteria card @addCardTo @card_selector, card @card_selector.change (e) => @renderCard $(@card_selector.find(':selected')) renderCard: (card) -> # Renders card to card container display_name = card.data 'display_name' name = card.data 'name' type = card.data 'type' data = card.data 'card' orig_type = card.data 'orig_type' @card_viewer_container.find('.info-name').html """#{if data.unique then "&middot;&nbsp;" else ""}#{if display_name then display_name else name} (#{data.points})#{if data.limited? then " (#{exportObj.translate(@language, 'ui', 'limited')})" else ""}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" @card_viewer_container.find('p.info-text').html data.text ? '' @card_viewer_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') switch orig_type when 'Pilot' ship = exportObj.ships[data.ship] @card_viewer_container.find('.info-type').text "#{data.ship} Pilot (#{data.faction})" if exportObj.builders[0].collection?.counts? ship_count = exportObj.builders[0].collection.counts?.ship?[data.ship] ? 0 pilot_count = exportObj.builders[0].collection.counts?.pilot?[data.name] ? 0 @card_viewer_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection.""" else @card_viewer_container.find('.info-collection').text '' @card_viewer_container.find('tr.info-skill td.info-data').text data.skill @card_viewer_container.find('tr.info-skill').show() @card_viewer_container.find('tr.info-attack td.info-data').text(data.ship_override?.attack ? ship.attack) @card_viewer_container.find('tr.info-attack-bullseye td.info-data').text(ship.attackbull) @card_viewer_container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf) @card_viewer_container.find('tr.info-attack-back td.info-data').text(ship.attackb) @card_viewer_container.find('tr.info-attack-turret td.info-data').text(ship.attackt) @card_viewer_container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt) @card_viewer_container.find('tr.info-attack').toggle(ship.attack?) @card_viewer_container.find('tr.info-attack-bullseye').toggle(ship.attackbull?) @card_viewer_container.find('tr.info-attack-fullfront').toggle(ship.attackf?) @card_viewer_container.find('tr.info-attack-back').toggle(ship.attackb?) @card_viewer_container.find('tr.info-attack-turret').toggle(ship.attackt?) @card_viewer_container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?) for cls in @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-attack') @card_viewer_container.find('tr.info-energy td.info-data').text(data.ship_override?.energy ? ship.energy) @card_viewer_container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?) @card_viewer_container.find('tr.info-range').hide() @card_viewer_container.find('tr.info-agility td.info-data').text(data.ship_override?.agility ? ship.agility) @card_viewer_container.find('tr.info-agility').show() @card_viewer_container.find('tr.info-hull td.info-data').text(data.ship_override?.hull ? ship.hull) @card_viewer_container.find('tr.info-hull').show() @card_viewer_container.find('tr.info-shields td.info-data').text(data.ship_override?.shields ? ship.shields) @card_viewer_container.find('tr.info-shields').show() if data.force? @card_viewer_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') @card_viewer_container.find('tr.info-force td.info-header').show() @card_viewer_container.find('tr.info-force').show() else @card_viewer_container.find('tr.info-force').hide() if data.charge? if data.recurring? @card_viewer_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') else @card_viewer_container.find('tr.info-charge td.info-data').text data.charge @card_viewer_container.find('tr.info-charge').show() else @card_viewer_container.find('tr.info-charge').hide() @card_viewer_container.find('tr.info-actions td.info-data').html (((exportObj.translate(@language, 'action', action) for action in exportObj.ships[data.ship].actions).join(', ')).replace(/, <r><i class="xwing-miniatures-font xwing-miniatures-font-linked">/g,' <r><i class="xwing-miniatures-font xwing-miniatures-font-linked">')).replace(/, <i class="xwing-miniatures-font xwing-miniatures-font-linked">/g,' <i class="xwing-miniatures-font xwing-miniatures-font-linked">') #super ghetto double replace for linked actions @card_viewer_container.find('tr.info-actions').show() if ships[data.ship].actionsred? @card_viewer_container.find('tr.info-actions-red td.info-data').html (exportObj.translate(@language, 'action', action) for action in exportObj.ships[data.ship].actionsred).join(' ') @card_viewer_container.find('tr.info-actions-red').show() else @card_viewer_container.find('tr.info-actions-red').hide() @card_viewer_container.find('tr.info-upgrades').show() @card_viewer_container.find('tr.info-upgrades td.info-data').html((exportObj.translate(@language, 'sloticon', slot) for slot in data.slots).join(' ') or 'None') else @card_viewer_container.find('.info-type').text type @card_viewer_container.find('.info-type').append " &ndash; #{data.faction} only" if data.faction? if exportObj.builders[0].collection?.counts? addon_count = exportObj.builders[0].collection.counts.upgrade[data.name] ? 0 @card_viewer_container.find('.info-collection').text """You have #{addon_count} in your collection.""" else @card_viewer_container.find('.info-collection').text '' @card_viewer_container.find('tr.info-ship').hide() @card_viewer_container.find('tr.info-skill').hide() if data.energy? @card_viewer_container.find('tr.info-energy td.info-data').text data.energy @card_viewer_container.find('tr.info-energy').show() else @card_viewer_container.find('tr.info-energy').hide() if data.attack? @card_viewer_container.find('tr.info-attack td.info-data').text data.attack @card_viewer_container.find('tr.info-attack').show() else @card_viewer_container.find('tr.info-attack').hide() if data.attackbull? @card_viewer_container.find('tr.info-attack-bullseye td.info-data').text data.attackbull @card_viewer_container.find('tr.info-attack-bullseye').show() else @card_viewer_container.find('tr.info-attack-bullseye').hide() if data.attackt? @card_viewer_container.find('tr.info-attack-turret td.info-data').text data.attackt @card_viewer_container.find('tr.info-attack-turret').show() else @card_viewer_container.find('tr.info-attack-turret').hide() if data.range? @card_viewer_container.find('tr.info-range td.info-data').text data.range @card_viewer_container.find('tr.info-range').show() else @card_viewer_container.find('tr.info-range').hide() if data.force? @card_viewer_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') @card_viewer_container.find('tr.info-force td.info-header').show() @card_viewer_container.find('tr.info-force').show() else @card_viewer_container.find('tr.info-force').hide() if data.charge? if data.recurring? @card_viewer_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') else @card_viewer_container.find('tr.info-charge td.info-data').text data.charge @card_viewer_container.find('tr.info-charge').show() else @card_viewer_container.find('tr.info-charge').hide() @card_viewer_container.find('tr.info-attack-fullfront').hide() @card_viewer_container.find('tr.info-attack-back').hide() @card_viewer_container.find('tr.info-attack-doubleturret').hide() @card_viewer_container.find('tr.info-agility').hide() @card_viewer_container.find('tr.info-hull').hide() @card_viewer_container.find('tr.info-shields').hide() @card_viewer_container.find('tr.info-actions').hide() @card_viewer_container.find('tr.info-actions-red').hide() @card_viewer_container.find('tr.info-upgrades').hide() @card_viewer_container.show() @card_viewer_placeholder.hide() addCardTo: (container, card) -> option = $ document.createElement('OPTION') option.text "#{if card.display_name then card.display_name else card.name} (#{card.data.points})" option.data 'name', card.name option.data 'display_name', card.display_name option.data 'type', card.type option.data 'card', card.data option.data 'orig_type', card.orig_type if @getCollectionNumber(card) == 0 option[0].classList.add('result-not-in-collection') $(container).append option getCollectionNumber: (card) -> # returns number of copies of the given card in the collection, or -1 if no collection loaded if not (exportObj.builders[0].collection? and exportObj.builders[0].collection.counts?) return -1 owned_copies = 0 switch card.orig_type when 'Pilot' owned_copies = exportObj.builders[0].collection.counts.pilot?[card.name] ? 0 when 'Ship' owned_copies = exportObj.builders[0].collection.counts.ship?[card.name] ? 0 else # type is e.g. astromech owned_copies = exportObj.builders[0].collection.counts.upgrade?[card.name] ? 0 owned_copies checkSearchCriteria: (card) -> # check for text search search_text = @card_search_text.value.toLowerCase() text_search = card.name.toLowerCase().indexOf(search_text) > -1 or (card.data.text and card.data.text.toLowerCase().indexOf(search_text)) > -1 or (card.display_name and card.display_name.toLowerCase().indexOf(search_text) > -1) if not text_search return false unless card.data.ship ship = card.data.ship if ship instanceof Array text_in_ship = false for s in ship if s.toLowerCase().indexOf(search_text) > -1 or (exportObj.ships[s].display_name and exportObj.ships[s].display_name.toLowerCase().indexOf(search_text) > -1) text_in_ship = true break return false unless text_in_ship else return false unless ship.toLowerCase().indexOf(search_text) > -1 or (exportObj.ships[ship].display_name and exportObj.ships[ship].display_name.toLowerCase().indexOf(search_text) > -1) # prevent the three virtual hardpoint cards from beeing displayed return false unless card.data.slot != "Hardpoint" # check if advanced search is enabled return true unless @advanced_search_active # check if faction matches return false unless @faction_selectors[card.data.faction].checked # check if second-edition only matches return false unless exportObj.secondEditionCheck(card.data) or not @second_edition_checkbox.checked # check for slot requirements required_slots = @slot_available_selection.val() if required_slots for slot in required_slots return false unless card.data.slots? and slot in card.data.slots # check if point costs matches return false unless (card.data.points >= @minimum_point_costs.value and card.data.points <= @maximum_point_costs.value) or (@variable_point_costs.checked and card.data.points == "*") # check if used slot matches used_slots = @slot_used_selection.val() if used_slots return false unless card.data.slot? matches = false for slot in used_slots if card.data.slot == slot matches = true break return false unless matches # check for uniqueness return false unless not @unique_checkbox.checked or card.data.unique # check charge stuff return false unless (card.data.charge? and card.data.charge <= @maximum_charge.value and card.data.charge >= @minimum_charge.value) or (@minimum_charge.value <= 0 and not card.data.charge?) return false if card.data.recurring and not @recurring_charge.checked return false if card.data.charge and not card.data.recurring and not @not_recurring_charge.checked # check collection status if exportObj.builders[0].collection?.counts? # ignore collection stuff, if no collection available owned_copies = @getCollectionNumber(card) return false unless owned_copies >= @minimum_owned_copies.value and owned_copies <= @maximum_owned_copies.value #TODO: Add logic of addiditional search criteria here. Have a look at card.data, to see what data is available. Add search inputs at the todo marks above. return true
true
### X-Wing Card Browser PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> https://github.com/geordanr/xwing ### exportObj = exports ? this # Assumes cards.js has been loaded TYPES = [ 'pilots', 'upgrades' ] byName = (a, b) -> if a.display_name a_name = a.display_name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') else a_name = a.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') if b.display_name b_name = b.display_name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') else b_name = b.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') if a_name < b_name -1 else if b_name < a_name 1 else 0 byPoints = (a, b) -> if a.data.points < b.data.points -1 else if b.data.points < a.data.points 1 else byName a, b String::capitalize = -> this.charAt(0).toUpperCase() + this.slice(1) class exportObj.CardBrowser constructor: (args) -> # args @container = $ args.container # internals @currently_selected = null @language = 'English' @prepareData() @setupUI() @setupHandlers() @sort_selector.change() setupUI: () -> @container.append $.trim """ <div class="container-fluid xwing-card-browser"> <div class="row-fluid"> <div class="span12"> <span class="translate sort-cards-by">Sort cards by</span>: <select class="sort-by"> <option value="name">Name</option> <option value="source">Source</option> <option value="type-by-points">Type (by Points)</option> <option value="type-by-name" selected="1">Type (by Name)</option> </select> </div> </div> <div class="row-fluid"> <div class="span4 card-selector-container"> </div> <div class="span8"> <div class="well card-search-container"> <input type="search" placeholder="Search for name, text or ship" class = "card-search-text">"""+ #TODO: Add more search input options here. """ <button class="btn btn-primary show-advanced-search"> Advanced Search </button> <div class="advanced-search-container"> <div class= "advanced-search-faction-selection-container"> <strong>Faction:</strong> <label class = "toggle-rebel-search advanced-search-label"> <input type="checkbox" class="rebel-checkbox advanced-search-checkbox" checked="checked" /> Rebel </label> <label class = "toggle-imperial-search advanced-search-label"> <input type="checkbox" class="imperial-checkbox advanced-search-checkbox" checked="checked" /> Imperial </label> <label class = "toggle-scum-search advanced-search-label"> <input type="checkbox" class="scum-checkbox advanced-search-checkbox" checked="checked" /> Scum </label> <label class = "toggle-fo-search advanced-search-label"> <input type="checkbox" class="fo-checkbox advanced-search-checkbox" checked="checked" /> First Order </label> <label class = "toggle-resistance-search advanced-search-label"> <input type="checkbox" class="resistance-checkbox advanced-search-checkbox" checked="checked" /> Resistance </label> <label class = "toggle-separatist-search advanced-search-label"> <input type="checkbox" class="separatist-checkbox advanced-search-checkbox" checked="checked" /> Separatist </label> <label class = "toggle-republic-search advanced-search-label"> <input type="checkbox" class="republic-checkbox advanced-search-checkbox" checked="checked" /> Republic </label> <label class = "toggle-factionless-search advanced-search-label"> <input type="checkbox" class="factionless-checkbox advanced-search-checkbox" checked="checked" /> Factionless <span class="advanced-search-tooltip" tooltip="A card is considered factionless, if it can be used by more than one faction."> &#9432 </span> </label> </div> <div class = "advanced-search-point-selection-container"> <strong>Point costs:</strong> <label class = "advanced-search-label set-minimum-points"> from <input type="number" class="minimum-point-cost advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-points"> to <input type="number" class="maximum-point-cost advanced-search-number-input" value="200" /> </label> <label class = "advanced-search-label toggle-variable-cost-search"> <input type="checkbox" class="variable-point-cost-checkbox advanced-search-checkbox" checked="checked" /> Variable point cost </label> </div> <div class = "advanced-search-collection-container"> <strong>Owned copies:</strong> <label class = "advanced-search-label set-minimum-owned-copies"> from <input type="number" class="minimum-owned-copies advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-owened-copies"> to <input type="number" class="maximum-owned-copies advanced-search-number-input" value="100" /> </label> </div> <div class = "advanced-search-slot-available-container"> <label class = "advanced-search-label select-available-slots"> <strong>Available slots: </strong> <select class="advanced-search-selection slot-available-selection" multiple="1" data-placeholder="No slots selected"></select> <span class="advanced-search-tooltip" tooltip="Search for pilots having all selected slots available."> &#9432 </span> </label> </div> <div class = "advanced-search-slot-used-container"> <label class = "advanced-search-label select-used-slots"> <strong>Used slot: </strong> <select class="advanced-search-selection slot-used-selection" multiple="1" data-placeholder="No slots selected"></select> <span class="advanced-search-tooltip" tooltip="Search for upgrades using any of the selected slots."> &#9432 </span> </label> </div> <div class = "advanced-search-charge-container"> <strong>Charges:</strong> <label class = "advanced-search-label set-minimum-charge"> from <input type="number" class="minimum-charge advanced-search-number-input" value="0" /> </label> <label class = "advanced-search-label set-maximum-charge"> to <input type="number" class="maximum-charge advanced-search-number-input" value="5" /> </label> <label class = "advanced-search-label has-recurring-charge"> <input type="checkbox" class="advanced-search-checkbox has-recurring-charge-checkbox" checked="checked"/> recurring </label> <label class = "advanced-search-label has-not-recurring-charge"> <input type="checkbox" class="advanced-search-checkbox has-not-recurring-charge-checkbox" checked="checked"/> not recurring </label> </div> <div class = "advanced-search-misc-container"> <strong>Misc:</strong> <label class = "advanced-search-label toggle-unique"> <input type="checkbox" class="unique-checkbox advanced-search-checkbox" /> Is unique </label> <label class = "advanced-search-label toggle-second-edition"> <input type="checkbox" class="second-edition-checkbox advanced-search-checkbox" /> Second-Edition only <span class="advanced-search-tooltip" tooltip="Check to exclude cards only obtainable from conversion kits."> &#9432 </span> </label> </div> </div> </div> <div class="well card-viewer-placeholder info-well"> <p class="translate select-a-card">Select a card from the list at the left.</p> </div> <div class="well card-viewer-container info-well"> <span class="info-name"></span> <br /> <span class="info-type"></span> <br /> <span class="info-sources"></span> <br /> <span class="info-collection"></span> <table> <tbody> <tr class="info-skill"> <td class="info-header">Skill</td> <td class="info-data info-skill"></td> </tr> <tr class="info-energy"> <td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td> <td class="info-data info-energy"></td> </tr> <tr class="info-attack"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-fullfront"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-bullseye"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-back"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-turret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-attack-doubleturret"> <td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td> <td class="info-data info-attack"></td> </tr> <tr class="info-agility"> <td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td> <td class="info-data info-agility"></td> </tr> <tr class="info-hull"> <td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td> <td class="info-data info-hull"></td> </tr> <tr class="info-shields"> <td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td> <td class="info-data info-shields"></td> </tr> <tr class="info-force"> <td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td> <td class="info-data info-force"></td> </tr> <tr class="info-charge"> <td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td> <td class="info-data info-charge"></td> </tr> <tr class="info-range"> <td class="info-header">Range</td> <td class="info-data info-range"></td> </tr> <tr class="info-actions"> <td class="info-header">Actions</td> <td class="info-data"></td> </tr> <tr class="info-actions-red"> <td></td> <td class="info-data-red"></td> </tr> <tr class="info-upgrades"> <td class="info-header">Upgrades</td> <td class="info-data"></td> </tr> </tbody> </table> <p class="info-text" /> </div> </div> </div> </div> """ @card_selector_container = $ @container.find('.xwing-card-browser .card-selector-container') @card_viewer_container = $ @container.find('.xwing-card-browser .card-viewer-container') @card_viewer_container.hide() @card_viewer_placeholder = $ @container.find('.xwing-card-browser .card-viewer-placeholder') @advanced_search_button = ($ @container.find('.xwing-card-browser .show-advanced-search'))[0] @advanced_search_container = $ @container.find('.xwing-card-browser .advanced-search-container') @advanced_search_container.hide() @advanced_search_active = false @sort_selector = $ @container.find('select.sort-by') @sort_selector.select2 minimumResultsForSearch: -1 # TODO: Make added inputs easy accessible @card_search_text = ($ @container.find('.xwing-card-browser .card-search-text'))[0] @faction_selectors = {} @faction_selectors["Rebel Alliance"] = ($ @container.find('.xwing-card-browser .rebel-checkbox'))[0] @faction_selectors["Scum and Villainy"] = ($ @container.find('.xwing-card-browser .scum-checkbox'))[0] @faction_selectors["Galactic Empire"] = ($ @container.find('.xwing-card-browser .imperial-checkbox'))[0] @faction_selectors["Resistance"] = ($ @container.find('.xwing-card-browser .resistance-checkbox'))[0] @faction_selectors["First Order"] = ($ @container.find('.xwing-card-browser .fo-checkbox'))[0] @faction_selectors["Separatist Alliance"] = ($ @container.find('.xwing-card-browser .separatist-checkbox'))[0] @faction_selectors["Galactic Republic"] = ($ @container.find('.xwing-card-browser .republic-checkbox'))[0] @faction_selectors[undefined] = ($ @container.find('.xwing-card-browser .factionless-checkbox'))[0] @minimum_point_costs = ($ @container.find('.xwing-card-browser .minimum-point-cost'))[0] @maximum_point_costs = ($ @container.find('.xwing-card-browser .maximum-point-cost'))[0] @variable_point_costs = ($ @container.find('.xwing-card-browser .variable-point-cost-checkbox'))[0] @second_edition_checkbox = ($ @container.find('.xwing-card-browser .second-edition-checkbox'))[0] @unique_checkbox = ($ @container.find('.xwing-card-browser .unique-checkbox'))[0] @slot_available_selection = ($ @container.find('.xwing-card-browser select.slot-available-selection')) for slot of exportObj.upgradesBySlotCanonicalName opt = $ document.createElement('OPTION') opt.text slot @slot_available_selection.append opt @slot_available_selection.select2 minimumResultsForSearch: if $.isMobile() then -1 else 0 @slot_used_selection = ($ @container.find('.xwing-card-browser select.slot-used-selection')) for slot of exportObj.upgradesBySlotCanonicalName opt = $ document.createElement('OPTION') opt.text slot @slot_used_selection.append opt @slot_used_selection.select2 minimumResultsForSearch: if $.isMobile() then -1 else 0 @minimum_charge = ($ @container.find('.xwing-card-browser .minimum-charge'))[0] @maximum_charge = ($ @container.find('.xwing-card-browser .maximum-charge'))[0] @recurring_charge = ($ @container.find('.xwing-card-browser .has-recurring-charge-checkbox'))[0] @not_recurring_charge = ($ @container.find('.xwing-card-browser .has-not-recurring-charge-checkbox'))[0] @minimum_owned_copies = ($ @container.find('.xwing-card-browser .minimum-owned-copies'))[0] @maximum_owned_copies = ($ @container.find('.xwing-card-browser .maximum-owned-copies'))[0] setupHandlers: () -> @sort_selector.change (e) => @renderList @sort_selector.val() $(window).on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) => @language = language @prepareData() @renderList @sort_selector.val() @card_search_text.oninput = => @renderList @sort_selector.val() # TODO: Add a call to @renderList for added inputs, to start the actual search @advanced_search_button.onclick = @toggleAdvancedSearch for faction, checkbox of @faction_selectors checkbox.onclick = => @renderList @sort_selector.val() @minimum_point_costs.oninput = => @renderList @sort_selector.val() @maximum_point_costs.oninput = => @renderList @sort_selector.val() @variable_point_costs.onclick = => @renderList @sort_selector.val() @second_edition_checkbox.onclick = => @renderList @sort_selector.val() @unique_checkbox.onclick = => @renderList @sort_selector.val() @slot_available_selection[0].onchange = => @renderList @sort_selector.val() @slot_used_selection[0].onchange = => @renderList @sort_selector.val() @recurring_charge.onclick = => @renderList @sort_selector.val() @not_recurring_charge.onclick = => @renderList @sort_selector.val() @minimum_charge.oninput = => @renderList @sort_selector.val() @maximum_charge.oninput = => @renderList @sort_selector.val() @minimum_owned_copies.oninput = => @renderList @sort_selector.val() @maximum_owned_copies.oninput = => @renderList @sort_selector.val() toggleAdvancedSearch: () => if @advanced_search_active @advanced_search_container.hide() else @advanced_search_container.show() @advanced_search_active = not @advanced_search_active @renderList @sort_selector.val() prepareData: () -> @all_cards = [] for type in TYPES if type == 'upgrades' @all_cards = @all_cards.concat ( { name: card_data.name, display_name: card_data.display_name, type: exportObj.translate(@language, 'ui', 'upgradeHeader', card_data.slot), data: card_data, orig_type: card_data.slot } for card_name, card_data of exportObj[type] ) else @all_cards = @all_cards.concat ( { name: card_data.name, display_name: card_data.display_name, type: exportObj.translate(@language, 'singular', type), data: card_data, orig_type: exportObj.translate('English', 'singular', type) } for card_name, card_data of exportObj[type] ) @types = (exportObj.translate(@language, 'types', type) for type in [ 'Pilot' ]) for card_name, card_data of exportObj.upgrades upgrade_text = exportObj.translate @language, 'ui', 'upgradeHeader', card_data.slot @types.push upgrade_text if upgrade_text not in @types @all_cards.sort byName @sources = [] for card in @all_cards for source in card.data.sources @sources.push(source) if source not in @sources sorted_types = @types.sort() sorted_sources = @sources.sort() @cards_by_type_name = {} for type in sorted_types @cards_by_type_name[type] = ( card for card in @all_cards when card.type == type ).sort byName @cards_by_type_points = {} for type in sorted_types @cards_by_type_points[type] = ( card for card in @all_cards when card.type == type ).sort byPoints @cards_by_source = {} for source in sorted_sources @cards_by_source[source] = ( card for card in @all_cards when source in card.data.sources ).sort byName renderList: (sort_by='name') -> # sort_by is one of `name`, `type-by-name`, `source`, `type-by-points` # # Renders multiselect to container # Selects previously selected card if there is one @card_selector.remove() if @card_selector? @card_selector = $ document.createElement('SELECT') @card_selector.addClass 'card-selector' @card_selector.attr 'size', 25 @card_selector_container.append @card_selector switch sort_by when 'type-by-name' for type in @types optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', type card_added = false for card in @cards_by_type_name[type] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup when 'type-by-points' for type in @types optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', type card_added = false for card in @cards_by_type_points[type] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup when 'source' for source in @sources optgroup = $ document.createElement('OPTGROUP') optgroup.attr 'label', source card_added = false for card in @cards_by_source[source] if @checkSearchCriteria card @addCardTo optgroup, card card_added = true if card_added @card_selector.append optgroup else for card in @all_cards if @checkSearchCriteria card @addCardTo @card_selector, card @card_selector.change (e) => @renderCard $(@card_selector.find(':selected')) renderCard: (card) -> # Renders card to card container display_name = card.data 'display_name' name = card.data 'name' type = card.data 'type' data = card.data 'card' orig_type = card.data 'orig_type' @card_viewer_container.find('.info-name').html """#{if data.unique then "&middot;&nbsp;" else ""}#{if display_name then display_name else name} (#{data.points})#{if data.limited? then " (#{exportObj.translate(@language, 'ui', 'limited')})" else ""}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}""" @card_viewer_container.find('p.info-text').html data.text ? '' @card_viewer_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ') switch orig_type when 'Pilot' ship = exportObj.ships[data.ship] @card_viewer_container.find('.info-type').text "#{data.ship} Pilot (#{data.faction})" if exportObj.builders[0].collection?.counts? ship_count = exportObj.builders[0].collection.counts?.ship?[data.ship] ? 0 pilot_count = exportObj.builders[0].collection.counts?.pilot?[data.name] ? 0 @card_viewer_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection.""" else @card_viewer_container.find('.info-collection').text '' @card_viewer_container.find('tr.info-skill td.info-data').text data.skill @card_viewer_container.find('tr.info-skill').show() @card_viewer_container.find('tr.info-attack td.info-data').text(data.ship_override?.attack ? ship.attack) @card_viewer_container.find('tr.info-attack-bullseye td.info-data').text(ship.attackbull) @card_viewer_container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf) @card_viewer_container.find('tr.info-attack-back td.info-data').text(ship.attackb) @card_viewer_container.find('tr.info-attack-turret td.info-data').text(ship.attackt) @card_viewer_container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt) @card_viewer_container.find('tr.info-attack').toggle(ship.attack?) @card_viewer_container.find('tr.info-attack-bullseye').toggle(ship.attackbull?) @card_viewer_container.find('tr.info-attack-fullfront').toggle(ship.attackf?) @card_viewer_container.find('tr.info-attack-back').toggle(ship.attackb?) @card_viewer_container.find('tr.info-attack-turret').toggle(ship.attackt?) @card_viewer_container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?) for cls in @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack') @card_viewer_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-attack') @card_viewer_container.find('tr.info-energy td.info-data').text(data.ship_override?.energy ? ship.energy) @card_viewer_container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?) @card_viewer_container.find('tr.info-range').hide() @card_viewer_container.find('tr.info-agility td.info-data').text(data.ship_override?.agility ? ship.agility) @card_viewer_container.find('tr.info-agility').show() @card_viewer_container.find('tr.info-hull td.info-data').text(data.ship_override?.hull ? ship.hull) @card_viewer_container.find('tr.info-hull').show() @card_viewer_container.find('tr.info-shields td.info-data').text(data.ship_override?.shields ? ship.shields) @card_viewer_container.find('tr.info-shields').show() if data.force? @card_viewer_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') @card_viewer_container.find('tr.info-force td.info-header').show() @card_viewer_container.find('tr.info-force').show() else @card_viewer_container.find('tr.info-force').hide() if data.charge? if data.recurring? @card_viewer_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') else @card_viewer_container.find('tr.info-charge td.info-data').text data.charge @card_viewer_container.find('tr.info-charge').show() else @card_viewer_container.find('tr.info-charge').hide() @card_viewer_container.find('tr.info-actions td.info-data').html (((exportObj.translate(@language, 'action', action) for action in exportObj.ships[data.ship].actions).join(', ')).replace(/, <r><i class="xwing-miniatures-font xwing-miniatures-font-linked">/g,' <r><i class="xwing-miniatures-font xwing-miniatures-font-linked">')).replace(/, <i class="xwing-miniatures-font xwing-miniatures-font-linked">/g,' <i class="xwing-miniatures-font xwing-miniatures-font-linked">') #super ghetto double replace for linked actions @card_viewer_container.find('tr.info-actions').show() if ships[data.ship].actionsred? @card_viewer_container.find('tr.info-actions-red td.info-data').html (exportObj.translate(@language, 'action', action) for action in exportObj.ships[data.ship].actionsred).join(' ') @card_viewer_container.find('tr.info-actions-red').show() else @card_viewer_container.find('tr.info-actions-red').hide() @card_viewer_container.find('tr.info-upgrades').show() @card_viewer_container.find('tr.info-upgrades td.info-data').html((exportObj.translate(@language, 'sloticon', slot) for slot in data.slots).join(' ') or 'None') else @card_viewer_container.find('.info-type').text type @card_viewer_container.find('.info-type').append " &ndash; #{data.faction} only" if data.faction? if exportObj.builders[0].collection?.counts? addon_count = exportObj.builders[0].collection.counts.upgrade[data.name] ? 0 @card_viewer_container.find('.info-collection').text """You have #{addon_count} in your collection.""" else @card_viewer_container.find('.info-collection').text '' @card_viewer_container.find('tr.info-ship').hide() @card_viewer_container.find('tr.info-skill').hide() if data.energy? @card_viewer_container.find('tr.info-energy td.info-data').text data.energy @card_viewer_container.find('tr.info-energy').show() else @card_viewer_container.find('tr.info-energy').hide() if data.attack? @card_viewer_container.find('tr.info-attack td.info-data').text data.attack @card_viewer_container.find('tr.info-attack').show() else @card_viewer_container.find('tr.info-attack').hide() if data.attackbull? @card_viewer_container.find('tr.info-attack-bullseye td.info-data').text data.attackbull @card_viewer_container.find('tr.info-attack-bullseye').show() else @card_viewer_container.find('tr.info-attack-bullseye').hide() if data.attackt? @card_viewer_container.find('tr.info-attack-turret td.info-data').text data.attackt @card_viewer_container.find('tr.info-attack-turret').show() else @card_viewer_container.find('tr.info-attack-turret').hide() if data.range? @card_viewer_container.find('tr.info-range td.info-data').text data.range @card_viewer_container.find('tr.info-range').show() else @card_viewer_container.find('tr.info-range').hide() if data.force? @card_viewer_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') @card_viewer_container.find('tr.info-force td.info-header').show() @card_viewer_container.find('tr.info-force').show() else @card_viewer_container.find('tr.info-force').hide() if data.charge? if data.recurring? @card_viewer_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>') else @card_viewer_container.find('tr.info-charge td.info-data').text data.charge @card_viewer_container.find('tr.info-charge').show() else @card_viewer_container.find('tr.info-charge').hide() @card_viewer_container.find('tr.info-attack-fullfront').hide() @card_viewer_container.find('tr.info-attack-back').hide() @card_viewer_container.find('tr.info-attack-doubleturret').hide() @card_viewer_container.find('tr.info-agility').hide() @card_viewer_container.find('tr.info-hull').hide() @card_viewer_container.find('tr.info-shields').hide() @card_viewer_container.find('tr.info-actions').hide() @card_viewer_container.find('tr.info-actions-red').hide() @card_viewer_container.find('tr.info-upgrades').hide() @card_viewer_container.show() @card_viewer_placeholder.hide() addCardTo: (container, card) -> option = $ document.createElement('OPTION') option.text "#{if card.display_name then card.display_name else card.name} (#{card.data.points})" option.data 'name', card.name option.data 'display_name', card.display_name option.data 'type', card.type option.data 'card', card.data option.data 'orig_type', card.orig_type if @getCollectionNumber(card) == 0 option[0].classList.add('result-not-in-collection') $(container).append option getCollectionNumber: (card) -> # returns number of copies of the given card in the collection, or -1 if no collection loaded if not (exportObj.builders[0].collection? and exportObj.builders[0].collection.counts?) return -1 owned_copies = 0 switch card.orig_type when 'Pilot' owned_copies = exportObj.builders[0].collection.counts.pilot?[card.name] ? 0 when 'Ship' owned_copies = exportObj.builders[0].collection.counts.ship?[card.name] ? 0 else # type is e.g. astromech owned_copies = exportObj.builders[0].collection.counts.upgrade?[card.name] ? 0 owned_copies checkSearchCriteria: (card) -> # check for text search search_text = @card_search_text.value.toLowerCase() text_search = card.name.toLowerCase().indexOf(search_text) > -1 or (card.data.text and card.data.text.toLowerCase().indexOf(search_text)) > -1 or (card.display_name and card.display_name.toLowerCase().indexOf(search_text) > -1) if not text_search return false unless card.data.ship ship = card.data.ship if ship instanceof Array text_in_ship = false for s in ship if s.toLowerCase().indexOf(search_text) > -1 or (exportObj.ships[s].display_name and exportObj.ships[s].display_name.toLowerCase().indexOf(search_text) > -1) text_in_ship = true break return false unless text_in_ship else return false unless ship.toLowerCase().indexOf(search_text) > -1 or (exportObj.ships[ship].display_name and exportObj.ships[ship].display_name.toLowerCase().indexOf(search_text) > -1) # prevent the three virtual hardpoint cards from beeing displayed return false unless card.data.slot != "Hardpoint" # check if advanced search is enabled return true unless @advanced_search_active # check if faction matches return false unless @faction_selectors[card.data.faction].checked # check if second-edition only matches return false unless exportObj.secondEditionCheck(card.data) or not @second_edition_checkbox.checked # check for slot requirements required_slots = @slot_available_selection.val() if required_slots for slot in required_slots return false unless card.data.slots? and slot in card.data.slots # check if point costs matches return false unless (card.data.points >= @minimum_point_costs.value and card.data.points <= @maximum_point_costs.value) or (@variable_point_costs.checked and card.data.points == "*") # check if used slot matches used_slots = @slot_used_selection.val() if used_slots return false unless card.data.slot? matches = false for slot in used_slots if card.data.slot == slot matches = true break return false unless matches # check for uniqueness return false unless not @unique_checkbox.checked or card.data.unique # check charge stuff return false unless (card.data.charge? and card.data.charge <= @maximum_charge.value and card.data.charge >= @minimum_charge.value) or (@minimum_charge.value <= 0 and not card.data.charge?) return false if card.data.recurring and not @recurring_charge.checked return false if card.data.charge and not card.data.recurring and not @not_recurring_charge.checked # check collection status if exportObj.builders[0].collection?.counts? # ignore collection stuff, if no collection available owned_copies = @getCollectionNumber(card) return false unless owned_copies >= @minimum_owned_copies.value and owned_copies <= @maximum_owned_copies.value #TODO: Add logic of addiditional search criteria here. Have a look at card.data, to see what data is available. Add search inputs at the todo marks above. return true
[ { "context": "#\t> File Name: db.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: W", "end": 39, "score": 0.9991077780723572, "start": 37, "tag": "USERNAME", "value": "LY" }, { "context": "#\t> File Name: db.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gma...
server/db/db.coffee
wiiliamking/miac-website
0
# > File Name: db.coffee # > Author: LY # > Mail: ly.franky@gmail.com # > Created Time: Wednesday, November 19, 2014 PM03:58:31 CST mongoose = require "mongoose" UserModel = require "./models/user.coffee" config = require '../config.coffee' MessageModel = require './models/message.coffee' ArticleModel = require './models/article.coffee' DiscussionModel = require './models/discuss.coffee' AlbumModel = require './models/album.coffee' db = null ### * init database * create a administrator ### init = -> initDB -> #UserModel.createAdministrator -> #DiscussionModel.drop -> #MessageModel.drop -> #UserModel.drop -> #ArticleModel.drop -> #DiscussionModel.drop -> #AlbumModel.drop -> ### * set database URL in mongoose * connect database * @param callback: callback function that would call when function ended ### initDB = (callback)-> if process.env.NODE_ENV is "DEV" mongoose.connect config.TEST_DB_URI else mongoose.connect config.PRODUCTION_DB_URI db = mongoose.connection callback() module.exports = {db, init}
41964
# > File Name: db.coffee # > Author: LY # > Mail: <EMAIL> # > Created Time: Wednesday, November 19, 2014 PM03:58:31 CST mongoose = require "mongoose" UserModel = require "./models/user.coffee" config = require '../config.coffee' MessageModel = require './models/message.coffee' ArticleModel = require './models/article.coffee' DiscussionModel = require './models/discuss.coffee' AlbumModel = require './models/album.coffee' db = null ### * init database * create a administrator ### init = -> initDB -> #UserModel.createAdministrator -> #DiscussionModel.drop -> #MessageModel.drop -> #UserModel.drop -> #ArticleModel.drop -> #DiscussionModel.drop -> #AlbumModel.drop -> ### * set database URL in mongoose * connect database * @param callback: callback function that would call when function ended ### initDB = (callback)-> if process.env.NODE_ENV is "DEV" mongoose.connect config.TEST_DB_URI else mongoose.connect config.PRODUCTION_DB_URI db = mongoose.connection callback() module.exports = {db, init}
true
# > File Name: db.coffee # > Author: LY # > Mail: PI:EMAIL:<EMAIL>END_PI # > Created Time: Wednesday, November 19, 2014 PM03:58:31 CST mongoose = require "mongoose" UserModel = require "./models/user.coffee" config = require '../config.coffee' MessageModel = require './models/message.coffee' ArticleModel = require './models/article.coffee' DiscussionModel = require './models/discuss.coffee' AlbumModel = require './models/album.coffee' db = null ### * init database * create a administrator ### init = -> initDB -> #UserModel.createAdministrator -> #DiscussionModel.drop -> #MessageModel.drop -> #UserModel.drop -> #ArticleModel.drop -> #DiscussionModel.drop -> #AlbumModel.drop -> ### * set database URL in mongoose * connect database * @param callback: callback function that would call when function ended ### initDB = (callback)-> if process.env.NODE_ENV is "DEV" mongoose.connect config.TEST_DB_URI else mongoose.connect config.PRODUCTION_DB_URI db = mongoose.connection callback() module.exports = {db, init}
[ { "context": "stenTo @collection, 'sync', @render\n @key = 'popular'\n\n remove: ->\n $('.search-result-navbar')", "end": 312, "score": 0.9923372268676758, "start": 305, "tag": "KEY", "value": "popular" } ]
app/assets/javascripts/backbone/views/searchresultview.js.coffee
vacaybug/vacaybug
0
jQuery -> class SearchResultView extends window.Vacaybug.GenericView template: JST["backbone/templates/search-result"] className: 'row search-result' events: 'click .js-guide-item': '_openModal' initialize: (options) -> @listenTo @collection, 'sync', @render @key = 'popular' remove: -> $('.search-result-navbar').remove() super() _openModal: (e) -> guide_id = $(e.currentTarget).attr('data-id') modal = new Vacaybug.GuideModalView guide: @collection.where({id: parseInt(guide_id)})[0] modal.render() renderNavBar: -> return if @navBarRendered @navBarRendered = true html = ' <div class="navbar-sort search-result-navbar"> <div class="col-md-6 col-md-offset-3 col-xs-12"> <div class="btn-group" role="group" aria-label="..."> <button type="button" class="js-search-key btn active" data-key="popular">Popular</button> <button type="button" class="js-search-key btn" data-key="recent">Recent</button> <!-- <button type="button" class="js-search-key btn active" data-key="popular">Guides</button> <button type="button" class="js-search-key btn" data-key="recent">Places</button> --> </div> </div> </div> ' $(html).insertBefore($('#wrapper')) $('.js-search-key').on 'click', (event) => key = $(event.currentTarget).attr('data-key') @key = key $('.js-search-key').removeClass('active') $(".js-search-key[data-key=#{key}]").addClass('active') @collection.key = key @collection.fetch() render: -> return @ if !@collection.sync_status $(@el).html @template collection: @collection view = new Vacaybug.GuidesView collection: @collection where: 'search' view.setElement(@$('.guides-container')).render() @renderNavBar() @ Vacaybug = window.Vacaybug ? {} Vacaybug.SearchResultView = SearchResultView
197025
jQuery -> class SearchResultView extends window.Vacaybug.GenericView template: JST["backbone/templates/search-result"] className: 'row search-result' events: 'click .js-guide-item': '_openModal' initialize: (options) -> @listenTo @collection, 'sync', @render @key = '<KEY>' remove: -> $('.search-result-navbar').remove() super() _openModal: (e) -> guide_id = $(e.currentTarget).attr('data-id') modal = new Vacaybug.GuideModalView guide: @collection.where({id: parseInt(guide_id)})[0] modal.render() renderNavBar: -> return if @navBarRendered @navBarRendered = true html = ' <div class="navbar-sort search-result-navbar"> <div class="col-md-6 col-md-offset-3 col-xs-12"> <div class="btn-group" role="group" aria-label="..."> <button type="button" class="js-search-key btn active" data-key="popular">Popular</button> <button type="button" class="js-search-key btn" data-key="recent">Recent</button> <!-- <button type="button" class="js-search-key btn active" data-key="popular">Guides</button> <button type="button" class="js-search-key btn" data-key="recent">Places</button> --> </div> </div> </div> ' $(html).insertBefore($('#wrapper')) $('.js-search-key').on 'click', (event) => key = $(event.currentTarget).attr('data-key') @key = key $('.js-search-key').removeClass('active') $(".js-search-key[data-key=#{key}]").addClass('active') @collection.key = key @collection.fetch() render: -> return @ if !@collection.sync_status $(@el).html @template collection: @collection view = new Vacaybug.GuidesView collection: @collection where: 'search' view.setElement(@$('.guides-container')).render() @renderNavBar() @ Vacaybug = window.Vacaybug ? {} Vacaybug.SearchResultView = SearchResultView
true
jQuery -> class SearchResultView extends window.Vacaybug.GenericView template: JST["backbone/templates/search-result"] className: 'row search-result' events: 'click .js-guide-item': '_openModal' initialize: (options) -> @listenTo @collection, 'sync', @render @key = 'PI:KEY:<KEY>END_PI' remove: -> $('.search-result-navbar').remove() super() _openModal: (e) -> guide_id = $(e.currentTarget).attr('data-id') modal = new Vacaybug.GuideModalView guide: @collection.where({id: parseInt(guide_id)})[0] modal.render() renderNavBar: -> return if @navBarRendered @navBarRendered = true html = ' <div class="navbar-sort search-result-navbar"> <div class="col-md-6 col-md-offset-3 col-xs-12"> <div class="btn-group" role="group" aria-label="..."> <button type="button" class="js-search-key btn active" data-key="popular">Popular</button> <button type="button" class="js-search-key btn" data-key="recent">Recent</button> <!-- <button type="button" class="js-search-key btn active" data-key="popular">Guides</button> <button type="button" class="js-search-key btn" data-key="recent">Places</button> --> </div> </div> </div> ' $(html).insertBefore($('#wrapper')) $('.js-search-key').on 'click', (event) => key = $(event.currentTarget).attr('data-key') @key = key $('.js-search-key').removeClass('active') $(".js-search-key[data-key=#{key}]").addClass('active') @collection.key = key @collection.fetch() render: -> return @ if !@collection.sync_status $(@el).html @template collection: @collection view = new Vacaybug.GuidesView collection: @collection where: 'search' view.setElement(@$('.guides-container')).render() @renderNavBar() @ Vacaybug = window.Vacaybug ? {} Vacaybug.SearchResultView = SearchResultView
[ { "context": "ey', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['meow123'], oi: 'newobj'}])\n\n describe 'randomizer', ->\n ", "end": 28560, "score": 0.799922525882721, "start": 28555, "tag": "PASSWORD", "value": "ow123" } ]
test/json0.coffee
wheatco/json00
0
# Tests for JSON OT type. assert = require 'assert' nativetype = require '../lib/json0' fuzzer = require 'ot-fuzzer' nativetype.registerSubtype name: 'mock' transform: (a, b, side) -> return { mock: true } # Cross-transform helper function. Transform server by client and client by # server. Returns [server, client]. transformX = (type, left, right) -> [type.transform(left, right, 'left'), type.transform(right, left, 'right')] genTests = (type) -> # The random op tester above will test that the OT functions are admissable, # but debugging problems it detects is a pain. # # These tests should pick up *most* problems with a normal JSON OT # implementation. describe 'sanity', -> describe '#create()', -> it 'returns null', -> assert.deepEqual type.create(), null describe '#compose()', -> it 'od,oi --> od+oi', -> assert.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1}],[{p:['foo'],oi:2}] assert.deepEqual [{p:['foo'], od:1},{p:['bar'], oi:2}], type.compose [{p:['foo'],od:1}],[{p:['bar'],oi:2}] it 'merges od+oi, od+oi -> od+oi', -> assert.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1,oi:3}],[{p:['foo'],od:3,oi:2}] describe '#transform()', -> it 'returns sane values', -> t = (op1, op2) -> assert.deepEqual op1, type.transform op1, op2, 'left' assert.deepEqual op1, type.transform op1, op2, 'right' t [], [] t [{p:['foo'], oi:1}], [] t [{p:['foo'], oi:1}], [{p:['bar'], oi:2}] describe 'number', -> it 'Adds a number', -> assert.deepEqual 3, type.apply 1, [{p:[], na:2}] assert.deepEqual [3], type.apply [1], [{p:[0], na:2}] it 'compresses two adds together in compose', -> assert.deepEqual [{p:['a', 'b'], na:3}], type.compose [{p:['a', 'b'], na:1}], [{p:['a', 'b'], na:2}] assert.deepEqual [{p:['a'], na:1}, {p:['b'], na:2}], type.compose [{p:['a'], na:1}], [{p:['b'], na:2}] it 'doesn\'t overwrite values when it merges na in append', -> rightHas = 21 leftHas = 3 rightOp = [{"p":[],"od":0,"oi":15},{"p":[],"na":4},{"p":[],"na":1},{"p":[],"na":1}] leftOp = [{"p":[],"na":4},{"p":[],"na":-1}] [right_, left_] = transformX type, rightOp, leftOp s_c = type.apply rightHas, left_ c_s = type.apply leftHas, right_ assert.deepEqual s_c, c_s # Strings should be handled internally by the text type. We'll just do some basic sanity checks here. describe 'string', -> describe '#apply()', -> it 'works', -> assert.deepEqual 'abc', type.apply 'a', [{p:[1], si:'bc'}] assert.deepEqual 'bc', type.apply 'abc', [{p:[0], sd:'a'}] assert.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x', 1], si:'bc'}] describe '#transform()', -> it 'splits deletes', -> assert.deepEqual type.transform([{p:[0], sd:'ab'}], [{p:[1], si:'x'}], 'left'), [{p:[0], sd:'a'}, {p:[1], sd:'b'}] it 'cancels out other deletes', -> assert.deepEqual type.transform([{p:['k', 5], sd:'a'}], [{p:['k', 5], sd:'a'}], 'left'), [] it 'does not throw errors with blank inserts', -> assert.deepEqual type.transform([{p: ['k', 5], si:''}], [{p: ['k', 3], si: 'a'}], 'left'), [] describe 'string subtype', -> describe '#apply()', -> it 'works', -> assert.deepEqual 'abc', type.apply 'a', [{p:[], t:'text0', o:[{p:1, i:'bc'}]}] assert.deepEqual 'bc', type.apply 'abc', [{p:[], t:'text0', o:[{p:0, d:'a'}]}] assert.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x'], t:'text0', o:[{p:1, i:'bc'}]}] describe '#transform()', -> it 'splits deletes', -> a = [{p:[], t:'text0', o:[{p:0, d:'ab'}]}] b = [{p:[], t:'text0', o:[{p:1, i:'x'}]}] assert.deepEqual type.transform(a, b, 'left'), [{p:[], t:'text0', o:[{p:0, d:'a'}, {p:1, d:'b'}]}] it 'cancels out other deletes', -> assert.deepEqual type.transform([{p:['k'], t:'text0', o:[{p:5, d:'a'}]}], [{p:['k'], t:'text0', o:[{p:5, d:'a'}]}], 'left'), [] it 'does not throw errors with blank inserts', -> assert.deepEqual type.transform([{p:['k'], t:'text0', o:[{p:5, i:''}]}], [{p:['k'], t:'text0', o:[{p:3, i:'a'}]}], 'left'), [] describe 'subtype with non-array operation', -> describe '#transform()', -> it 'works', -> a = [{p:[], t:'mock', o:'foo'}] b = [{p:[], t:'mock', o:'bar'}] assert.deepEqual type.transform(a, b, 'left'), [{p:[], t:'mock', o:{mock:true}}] describe 'list', -> describe 'apply', -> it 'inserts', -> assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'c'], [{p:[0], li:'a'}] assert.deepEqual ['a', 'b', 'c'], type.apply ['a', 'c'], [{p:[1], li:'b'}] assert.deepEqual ['a', 'b', 'c'], type.apply ['a', 'b'], [{p:[2], li:'c'}] it 'deletes', -> assert.deepEqual ['b', 'c'], type.apply ['a', 'b', 'c'], [{p:[0], ld:'a'}] assert.deepEqual ['a', 'c'], type.apply ['a', 'b', 'c'], [{p:[1], ld:'b'}] assert.deepEqual ['a', 'b'], type.apply ['a', 'b', 'c'], [{p:[2], ld:'c'}] it 'replaces', -> assert.deepEqual ['a', 'y', 'b'], type.apply ['a', 'x', 'b'], [{p:[1], ld:'x', li:'y'}] it 'moves', -> assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[1], lm:0}] assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[0], lm:1}] ### 'null moves compose to nops', -> assert.deepEqual [], type.compose [], [{p:[3],lm:3}] assert.deepEqual [], type.compose [], [{p:[0,3],lm:3}] assert.deepEqual [], type.compose [], [{p:['x','y',0],lm:0}] ### describe '#transform()', -> it 'bumps paths when list elements are inserted or removed', -> assert.deepEqual [{p:[2, 200], si:'hi'}], type.transform [{p:[1, 200], si:'hi'}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1, 201], si:'hi'}], type.transform [{p:[0, 201], si:'hi'}], [{p:[0], li:'x'}], 'right' assert.deepEqual [{p:[0, 202], si:'hi'}], type.transform [{p:[0, 202], si:'hi'}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[2], t:'text0', o:[{p:200, i:'hi'}]}], type.transform [{p:[1], t:'text0', o:[{p:200, i:'hi'}]}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1], t:'text0', o:[{p:201, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:201, i:'hi'}]}], [{p:[0], li:'x'}], 'right' assert.deepEqual [{p:[0], t:'text0', o:[{p:202, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:202, i:'hi'}]}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[0, 203], si:'hi'}], type.transform [{p:[1, 203], si:'hi'}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [{p:[0, 204], si:'hi'}], type.transform [{p:[0, 204], si:'hi'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:['x',3], si: 'hi'}], type.transform [{p:['x',3], si:'hi'}], [{p:['x',0,'x'], li:0}], 'left' assert.deepEqual [{p:['x',3,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',5], li:0}], 'left' assert.deepEqual [{p:['x',4,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',0], li:0}], 'left' assert.deepEqual [{p:[0], t:'text0', o:[{p:203, i:'hi'}]}], type.transform [{p:[1], t:'text0', o:[{p:203, i:'hi'}]}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [{p:[0], t:'text0', o:[{p:204, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:204, i:'hi'}]}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:['x'], t:'text0', o:[{p:3,i: 'hi'}]}], type.transform [{p:['x'], t:'text0', o:[{p:3, i:'hi'}]}], [{p:['x',0,'x'], li:0}], 'left' assert.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'left' assert.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'right' it 'converts ops on deleted elements to noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[0],li:'x'}], type.transform [{p:[0],li:'x'}], [{p:[0],ld:'y'}], 'left' assert.deepEqual [], type.transform [{p:[0],na:-3}], [{p:[0],ld:48}], 'left' it 'converts ops on replaced elements to noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x', li:'y'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], ld:'x', li:'y'}], 'left' assert.deepEqual [{p:[0], li:'hi'}], type.transform [{p:[0], li:'hi'}], [{p:[0], ld:'x', li:'y'}], 'left' it 'changes deleted data to reflect edits', -> assert.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1, 1], si:'bc'}], 'left' assert.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1], t:'text0', o:[{p:1, i:'bc'}]}], 'left' it 'Puts the left op first if two inserts are simultaneous', -> assert.deepEqual [{p:[1], li:'a'}], type.transform [{p:[1], li:'a'}], [{p:[1], li:'b'}], 'left' assert.deepEqual [{p:[2], li:'b'}], type.transform [{p:[1], li:'b'}], [{p:[1], li:'a'}], 'right' it 'converts an attempt to re-delete a list element into a no-op', -> assert.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'right' describe '#compose()', -> it 'composes insert then delete into a no-op', -> assert.deepEqual [], type.compose [{p:[1], li:'abc'}], [{p:[1], ld:'abc'}] assert.deepEqual [{p:[1],ld:null,li:'x'}], type.transform [{p:[0],ld:null,li:"x"}], [{p:[0],li:"The"}], 'right' it 'doesn\'t change the original object', -> a = [{p:[0],ld:'abc',li:null}] assert.deepEqual [{p:[0],ld:'abc'}], type.compose a, [{p:[0],ld:null}] assert.deepEqual [{p:[0],ld:'abc',li:null}], a it 'composes together adjacent string ops', -> assert.deepEqual [{p:[100], si:'hi'}], type.compose [{p:[100], si:'h'}], [{p:[101], si:'i'}] assert.deepEqual [{p:[], t:'text0', o:[{p:100, i:'hi'}]}], type.compose [{p:[], t:'text0', o:[{p:100, i:'h'}]}], [{p:[], t:'text0', o:[{p:101, i:'i'}]}] it 'moves ops on a moved element with the element', -> assert.deepEqual [{p:[10], ld:'x'}], type.transform [{p:[4], ld:'x'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], si:'a'}], type.transform [{p:[4, 1], si:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10], t:'text0', o:[{p:1, i:'a'}]}], type.transform [{p:[4], t:'text0', o:[{p:1, i:'a'}]}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], li:'a'}], type.transform [{p:[4, 1], li:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], ld:'b', li:'a'}], type.transform [{p:[4, 1], ld:'b', li:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[0],li:null}], type.transform [{p:[0],li:null}], [{p:[0],lm:1}], 'left' # [_,_,_,_,5,6,7,_] # c: [_,_,_,_,5,'x',6,7,_] p:5 li:'x' # s: [_,6,_,_,_,5,7,_] p:5 lm:1 # correct: [_,6,_,_,_,5,'x',7,_] assert.deepEqual [{p:[6],li:'x'}], type.transform [{p:[5],li:'x'}], [{p:[5],lm:1}], 'left' # [_,_,_,_,5,6,7,_] # c: [_,_,_,_,5,6,7,_] p:5 ld:6 # s: [_,6,_,_,_,5,7,_] p:5 lm:1 # correct: [_,_,_,_,5,7,_] assert.deepEqual [{p:[1],ld:6}], type.transform [{p:[5],ld:6}], [{p:[5],lm:1}], 'left' #assert.deepEqual [{p:[0],li:{}}], type.transform [{p:[0],li:{}}], [{p:[0],lm:0}], 'right' assert.deepEqual [{p:[0],li:[]}], type.transform [{p:[0],li:[]}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],li:'x'}], type.transform [{p:[2],li:'x'}], [{p:[0],lm:1}], 'left' it 'moves target index on ld/li', -> assert.deepEqual [{p:[0],lm:1}], type.transform [{p:[0], lm: 2}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[1],lm:3}], type.transform [{p:[2], lm: 4}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[0],lm:3}], type.transform [{p:[0], lm: 2}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[3],lm:5}], type.transform [{p:[2], lm: 4}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0], lm: 0}], [{p:[0], li:28}], 'left' it 'tiebreaks lm vs. ld/li', -> assert.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'right' assert.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'right' it 'replacement vs. deletion', -> assert.deepEqual [{p:[0],li:'y'}], type.transform [{p:[0],ld:'x',li:'y'}], [{p:[0],ld:'x'}], 'right' it 'replacement vs. insertion', -> assert.deepEqual [{p:[1],ld:{},li:"brillig"}], type.transform [{p:[0],ld:{},li:"brillig"}], [{p:[0],li:36}], 'left' it 'replacement vs. replacement', -> assert.deepEqual [], type.transform [{p:[0],ld:null,li:[]}], [{p:[0],ld:null,li:0}], 'right' assert.deepEqual [{p:[0],ld:[],li:0}], type.transform [{p:[0],ld:null,li:0}], [{p:[0],ld:null,li:[]}], 'left' it 'composes replace with delete of replaced element results in insert', -> assert.deepEqual [{p:[2],ld:[]}], type.compose [{p:[2],ld:[],li:null}], [{p:[2],ld:null}] it 'lm vs lm', -> assert.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:2}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[4],lm:4}], type.transform [{p:[3],lm:3}], [{p:[5],lm:0}], 'left' assert.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],lm:1}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'right' assert.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[3],lm:0}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'left' assert.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left' assert.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:5}], 'right' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:1}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[1],lm:2}], type.transform [{p:[0],lm:1}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[3],lm:2}], type.transform [{p:[2],lm:1}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[2],lm:1}], type.transform [{p:[3],lm:1}], [{p:[1],lm:3}], 'left' assert.deepEqual [{p:[2],lm:3}], type.transform [{p:[1],lm:3}], [{p:[3],lm:1}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'right' assert.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:1}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:1}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:0}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],lm:3}], 'left' assert.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:1}], [{p:[3],lm:2}], 'left' assert.deepEqual [{p:[3],lm:3}], type.transform [{p:[3],lm:2}], [{p:[2],lm:1}], 'left' it 'changes indices correctly around a move', -> assert.deepEqual [{p:[1,0],li:{}}], type.transform [{p:[0,0],li:{}}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],ld:{}}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],ld:{}}], 'left' assert.deepEqual [{p:[5],lm:0}], type.transform [{p:[6],lm:0}], [{p:[2],ld:{}}], 'left' assert.deepEqual [{p:[1],lm:0}], type.transform [{p:[1],lm:0}], [{p:[2],ld:{}}], 'left' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[2],lm:1}], [{p:[1],ld:3}], 'right' assert.deepEqual [{p:[1],ld:{}}], type.transform [{p:[2],ld:{}}], [{p:[1],lm:2}], 'right' assert.deepEqual [{p:[2],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[0],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[0],ld:1,li:2}], type.transform [{p:[1],ld:1,li:2}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],ld:2,li:3}], type.transform [{p:[1],ld:2,li:3}], [{p:[0],lm:1}], 'left' assert.deepEqual [{p:[1],ld:3,li:4}], type.transform [{p:[0],ld:3,li:4}], [{p:[1],lm:0}], 'left' it 'li vs lm', -> li = (p) -> [{p:[p],li:[]}] lm = (f,t) -> [{p:[f],lm:t}] xf = type.transform assert.deepEqual (li 0), xf (li 0), (lm 1, 3), 'left' assert.deepEqual (li 1), xf (li 1), (lm 1, 3), 'left' assert.deepEqual (li 1), xf (li 2), (lm 1, 3), 'left' assert.deepEqual (li 2), xf (li 3), (lm 1, 3), 'left' assert.deepEqual (li 4), xf (li 4), (lm 1, 3), 'left' assert.deepEqual (lm 2, 4), xf (lm 1, 3), (li 0), 'right' assert.deepEqual (lm 2, 4), xf (lm 1, 3), (li 1), 'right' assert.deepEqual (lm 1, 4), xf (lm 1, 3), (li 2), 'right' assert.deepEqual (lm 1, 4), xf (lm 1, 3), (li 3), 'right' assert.deepEqual (lm 1, 3), xf (lm 1, 3), (li 4), 'right' assert.deepEqual (li 0), xf (li 0), (lm 1, 2), 'left' assert.deepEqual (li 1), xf (li 1), (lm 1, 2), 'left' assert.deepEqual (li 1), xf (li 2), (lm 1, 2), 'left' assert.deepEqual (li 3), xf (li 3), (lm 1, 2), 'left' assert.deepEqual (li 0), xf (li 0), (lm 3, 1), 'left' assert.deepEqual (li 1), xf (li 1), (lm 3, 1), 'left' assert.deepEqual (li 3), xf (li 2), (lm 3, 1), 'left' assert.deepEqual (li 4), xf (li 3), (lm 3, 1), 'left' assert.deepEqual (li 4), xf (li 4), (lm 3, 1), 'left' assert.deepEqual (lm 4, 2), xf (lm 3, 1), (li 0), 'right' assert.deepEqual (lm 4, 2), xf (lm 3, 1), (li 1), 'right' assert.deepEqual (lm 4, 1), xf (lm 3, 1), (li 2), 'right' assert.deepEqual (lm 4, 1), xf (lm 3, 1), (li 3), 'right' assert.deepEqual (lm 3, 1), xf (lm 3, 1), (li 4), 'right' assert.deepEqual (li 0), xf (li 0), (lm 2, 1), 'left' assert.deepEqual (li 1), xf (li 1), (lm 2, 1), 'left' assert.deepEqual (li 3), xf (li 2), (lm 2, 1), 'left' assert.deepEqual (li 3), xf (li 3), (lm 2, 1), 'left' describe 'object', -> it 'passes sanity checks', -> assert.deepEqual {x:'a', y:'b'}, type.apply {x:'a'}, [{p:['y'], oi:'b'}] assert.deepEqual {}, type.apply {x:'a'}, [{p:['x'], od:'a'}] assert.deepEqual {x:'b'}, type.apply {x:'a'}, [{p:['x'], od:'a', oi:'b'}] it 'Ops on deleted elements become noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:[9],si:"bite "}], [{p:[],od:"agimble s",oi:null}], 'right' assert.deepEqual [], type.transform [{p:[], t:'text0', o:[{p:9, i:"bite "}]}], [{p:[],od:"agimble s",oi:null}], 'right' it 'Ops on replaced elements become noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x', oi:'y'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], od:'x', oi:'y'}], 'left' it 'Deleted data is changed to reflect edits', -> assert.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1, 1], si:'bc'}], 'left' assert.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1], t:'text0', o:[{p:1, i:'bc'}]}], 'left' assert.deepEqual [{p:[],od:25,oi:[]}], type.transform [{p:[],od:22,oi:[]}], [{p:[],na:3}], 'left' assert.deepEqual [{p:[],od:{toves:""},oi:4}], type.transform [{p:[],od:{toves:0},oi:4}], [{p:["toves"],od:0,oi:""}], 'left' assert.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[7],sd:"d "}], 'left' assert.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[], t:'text0', o:[{p:7, d:"d "}]}], 'left' assert.deepEqual [], type.transform([{p:["bird"],na:2}], [{p:[],od:{bird:38},oi:20}], 'right') assert.deepEqual [{p:[],od:{bird:40},oi:20}], type.transform([{p:[],od:{bird:38},oi:20}], [{p:["bird"],na:2}], 'left') assert.deepEqual [{p:['He'],od:[]}], type.transform [{p:["He"],od:[]}], [{p:["The"],na:-3}], 'right' assert.deepEqual [], type.transform [{p:["He"],oi:{}}], [{p:[],od:{},oi:"the"}], 'left' it 'If two inserts are simultaneous, the lefts insert will win', -> assert.deepEqual [{p:[1], oi:'a', od:'b'}], type.transform [{p:[1], oi:'a'}], [{p:[1], oi:'b'}], 'left' assert.deepEqual [], type.transform [{p:[1], oi:'b'}], [{p:[1], oi:'a'}], 'right' it 'parallel ops on different keys miss each other', -> assert.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], oi:'z'}], 'left' assert.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], od:'z'}], 'left' assert.deepEqual [{p:["in","he"],oi:{}}], type.transform [{p:["in","he"],oi:{}}], [{p:["and"],od:{}}], 'right' assert.deepEqual [{p:['x',0],si:"his "}], type.transform [{p:['x',0],si:"his "}], [{p:['y'],od:0,oi:1}], 'right' assert.deepEqual [{p:['x'], t:'text0', o:[{p:0, i:"his "}]}], type.transform [{p:['x'],t:'text0', o:[{p:0, i:"his "}]}], [{p:['y'],od:0,oi:1}], 'right' it 'replacement vs. deletion', -> assert.deepEqual [{p:[],oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:['']}], 'right' it 'replacement vs. replacement', -> assert.deepEqual [], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'right' assert.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'left' assert.deepEqual [], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'right' assert.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'left' # test diamond property rightOps = [ {"p":[],"od":null,"oi":{}} ] leftOps = [ {"p":[],"od":null,"oi":""} ] rightHas = type.apply(null, rightOps) leftHas = type.apply(null, leftOps) [left_, right_] = transformX type, leftOps, rightOps assert.deepEqual leftHas, type.apply rightHas, left_ assert.deepEqual leftHas, type.apply leftHas, right_ it 'An attempt to re-delete a key becomes a no-op', -> assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right' describe 'transformCursor', -> describe 'string operations', -> it 'handles inserts before', -> assert.deepEqual ['key', 10, 3+4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], si: 'meow'}]) it 'handles inserts after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], si: 'meow'}]) it 'handles inserts at current point with isOwnOp', -> assert.deepEqual ['key', 10, 3+4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], si: 'meow'}], true) it 'handles inserts at current point without isOwnOp', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], si: 'meow'}]) it 'handles deletes before', -> assert.deepEqual ['key', 10, 3-2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 0], sd: '12'}]) it 'handles deletes after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], sd: '12'}]) it 'handles deletes at current point', -> assert.deepEqual ['key', 10, 1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], sd: 'meow meow'}]) it 'ignores irrelevant operations', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 9, 1], si: 'meow'}]) describe 'number operations', -> it 'ignores', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], na: 123}]) describe 'list operations', -> it 'handles inserts before', -> assert.deepEqual ['key', 10, 3+1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], li: 'meow'}]) assert.deepEqual ['key', 10+1, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10], li: 'meow'}]) it 'handles inserts after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 4], li: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 11], li: 'meow'}]) it 'handles replacements at current point', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], ld: 'meow1', li: 'meow2'}]) assert.deepEqual ['key', 10], type.transformCursor(['key', 10, 3], [{p: ['key', 10], ld: 'meow1', li: 'meow2'}]) # move cursor up tree when parent deleted it 'handles deletes before', -> assert.deepEqual ['key', 10, 3-1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], ld: 'meow'}]) assert.deepEqual ['key', 10-1, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 9], ld: 'meow'}]) it 'handles deletes after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 4], ld: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 11], ld: 'meow'}]) it 'handles deletes at current point', -> assert.deepEqual ['key', 10], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], ld: 'meow'}]) assert.deepEqual ['key'], type.transformCursor(['key', 10, 3], [{p: ['key', 10], ld: 'meow'}]) it 'handles movements of current point', -> assert.deepEqual ['key', 10, 20], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], lm: 20}]) assert.deepEqual ['key', 20, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10], lm: 20}]) it 'handles movements of other points', -> assert.deepEqual ['key', 10, 2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], lm: 20}]) assert.deepEqual ['key', 10, 4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], lm: 3}]) assert.deepEqual ['key', 10, 4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], lm: 1}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 10], lm: 20}]) assert.deepEqual ['key', 10, 2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], lm: 3}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], lm: 1}]) describe 'dict operations', -> it 'ignores irrelevant inserts and deletes', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key2'], oi: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key2'], od: 'meow'}]) it 'handles deletes at current point', -> assert.deepEqual [], type.transformCursor(['key', 0, 3], [{p: ['key'], od: ['meow123']}]) assert.deepEqual ['key', 0], type.transformCursor(['key', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['meow123']}]) it 'handles replacements at current point', -> assert.deepEqual ['key'], type.transformCursor(['key', 0, 3], [{p: ['key'], od: ['meow123'], oi: 'newobj'}]) assert.deepEqual ['key', 0, 'key2'], type.transformCursor(['key', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['meow123'], oi: 'newobj'}]) describe 'randomizer', -> @timeout 20000 @slow 6000 it 'passes', -> fuzzer type, require('./json0-generator'), 1000 it 'passes with string subtype', -> type._testStringSubtype = true # hack fuzzer type, require('./json0-generator'), 1000 delete type._testStringSubtype describe 'json', -> describe 'native type', -> genTests nativetype #exports.webclient = genTests require('../helpers/webclient').types.json
71102
# Tests for JSON OT type. assert = require 'assert' nativetype = require '../lib/json0' fuzzer = require 'ot-fuzzer' nativetype.registerSubtype name: 'mock' transform: (a, b, side) -> return { mock: true } # Cross-transform helper function. Transform server by client and client by # server. Returns [server, client]. transformX = (type, left, right) -> [type.transform(left, right, 'left'), type.transform(right, left, 'right')] genTests = (type) -> # The random op tester above will test that the OT functions are admissable, # but debugging problems it detects is a pain. # # These tests should pick up *most* problems with a normal JSON OT # implementation. describe 'sanity', -> describe '#create()', -> it 'returns null', -> assert.deepEqual type.create(), null describe '#compose()', -> it 'od,oi --> od+oi', -> assert.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1}],[{p:['foo'],oi:2}] assert.deepEqual [{p:['foo'], od:1},{p:['bar'], oi:2}], type.compose [{p:['foo'],od:1}],[{p:['bar'],oi:2}] it 'merges od+oi, od+oi -> od+oi', -> assert.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1,oi:3}],[{p:['foo'],od:3,oi:2}] describe '#transform()', -> it 'returns sane values', -> t = (op1, op2) -> assert.deepEqual op1, type.transform op1, op2, 'left' assert.deepEqual op1, type.transform op1, op2, 'right' t [], [] t [{p:['foo'], oi:1}], [] t [{p:['foo'], oi:1}], [{p:['bar'], oi:2}] describe 'number', -> it 'Adds a number', -> assert.deepEqual 3, type.apply 1, [{p:[], na:2}] assert.deepEqual [3], type.apply [1], [{p:[0], na:2}] it 'compresses two adds together in compose', -> assert.deepEqual [{p:['a', 'b'], na:3}], type.compose [{p:['a', 'b'], na:1}], [{p:['a', 'b'], na:2}] assert.deepEqual [{p:['a'], na:1}, {p:['b'], na:2}], type.compose [{p:['a'], na:1}], [{p:['b'], na:2}] it 'doesn\'t overwrite values when it merges na in append', -> rightHas = 21 leftHas = 3 rightOp = [{"p":[],"od":0,"oi":15},{"p":[],"na":4},{"p":[],"na":1},{"p":[],"na":1}] leftOp = [{"p":[],"na":4},{"p":[],"na":-1}] [right_, left_] = transformX type, rightOp, leftOp s_c = type.apply rightHas, left_ c_s = type.apply leftHas, right_ assert.deepEqual s_c, c_s # Strings should be handled internally by the text type. We'll just do some basic sanity checks here. describe 'string', -> describe '#apply()', -> it 'works', -> assert.deepEqual 'abc', type.apply 'a', [{p:[1], si:'bc'}] assert.deepEqual 'bc', type.apply 'abc', [{p:[0], sd:'a'}] assert.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x', 1], si:'bc'}] describe '#transform()', -> it 'splits deletes', -> assert.deepEqual type.transform([{p:[0], sd:'ab'}], [{p:[1], si:'x'}], 'left'), [{p:[0], sd:'a'}, {p:[1], sd:'b'}] it 'cancels out other deletes', -> assert.deepEqual type.transform([{p:['k', 5], sd:'a'}], [{p:['k', 5], sd:'a'}], 'left'), [] it 'does not throw errors with blank inserts', -> assert.deepEqual type.transform([{p: ['k', 5], si:''}], [{p: ['k', 3], si: 'a'}], 'left'), [] describe 'string subtype', -> describe '#apply()', -> it 'works', -> assert.deepEqual 'abc', type.apply 'a', [{p:[], t:'text0', o:[{p:1, i:'bc'}]}] assert.deepEqual 'bc', type.apply 'abc', [{p:[], t:'text0', o:[{p:0, d:'a'}]}] assert.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x'], t:'text0', o:[{p:1, i:'bc'}]}] describe '#transform()', -> it 'splits deletes', -> a = [{p:[], t:'text0', o:[{p:0, d:'ab'}]}] b = [{p:[], t:'text0', o:[{p:1, i:'x'}]}] assert.deepEqual type.transform(a, b, 'left'), [{p:[], t:'text0', o:[{p:0, d:'a'}, {p:1, d:'b'}]}] it 'cancels out other deletes', -> assert.deepEqual type.transform([{p:['k'], t:'text0', o:[{p:5, d:'a'}]}], [{p:['k'], t:'text0', o:[{p:5, d:'a'}]}], 'left'), [] it 'does not throw errors with blank inserts', -> assert.deepEqual type.transform([{p:['k'], t:'text0', o:[{p:5, i:''}]}], [{p:['k'], t:'text0', o:[{p:3, i:'a'}]}], 'left'), [] describe 'subtype with non-array operation', -> describe '#transform()', -> it 'works', -> a = [{p:[], t:'mock', o:'foo'}] b = [{p:[], t:'mock', o:'bar'}] assert.deepEqual type.transform(a, b, 'left'), [{p:[], t:'mock', o:{mock:true}}] describe 'list', -> describe 'apply', -> it 'inserts', -> assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'c'], [{p:[0], li:'a'}] assert.deepEqual ['a', 'b', 'c'], type.apply ['a', 'c'], [{p:[1], li:'b'}] assert.deepEqual ['a', 'b', 'c'], type.apply ['a', 'b'], [{p:[2], li:'c'}] it 'deletes', -> assert.deepEqual ['b', 'c'], type.apply ['a', 'b', 'c'], [{p:[0], ld:'a'}] assert.deepEqual ['a', 'c'], type.apply ['a', 'b', 'c'], [{p:[1], ld:'b'}] assert.deepEqual ['a', 'b'], type.apply ['a', 'b', 'c'], [{p:[2], ld:'c'}] it 'replaces', -> assert.deepEqual ['a', 'y', 'b'], type.apply ['a', 'x', 'b'], [{p:[1], ld:'x', li:'y'}] it 'moves', -> assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[1], lm:0}] assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[0], lm:1}] ### 'null moves compose to nops', -> assert.deepEqual [], type.compose [], [{p:[3],lm:3}] assert.deepEqual [], type.compose [], [{p:[0,3],lm:3}] assert.deepEqual [], type.compose [], [{p:['x','y',0],lm:0}] ### describe '#transform()', -> it 'bumps paths when list elements are inserted or removed', -> assert.deepEqual [{p:[2, 200], si:'hi'}], type.transform [{p:[1, 200], si:'hi'}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1, 201], si:'hi'}], type.transform [{p:[0, 201], si:'hi'}], [{p:[0], li:'x'}], 'right' assert.deepEqual [{p:[0, 202], si:'hi'}], type.transform [{p:[0, 202], si:'hi'}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[2], t:'text0', o:[{p:200, i:'hi'}]}], type.transform [{p:[1], t:'text0', o:[{p:200, i:'hi'}]}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1], t:'text0', o:[{p:201, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:201, i:'hi'}]}], [{p:[0], li:'x'}], 'right' assert.deepEqual [{p:[0], t:'text0', o:[{p:202, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:202, i:'hi'}]}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[0, 203], si:'hi'}], type.transform [{p:[1, 203], si:'hi'}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [{p:[0, 204], si:'hi'}], type.transform [{p:[0, 204], si:'hi'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:['x',3], si: 'hi'}], type.transform [{p:['x',3], si:'hi'}], [{p:['x',0,'x'], li:0}], 'left' assert.deepEqual [{p:['x',3,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',5], li:0}], 'left' assert.deepEqual [{p:['x',4,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',0], li:0}], 'left' assert.deepEqual [{p:[0], t:'text0', o:[{p:203, i:'hi'}]}], type.transform [{p:[1], t:'text0', o:[{p:203, i:'hi'}]}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [{p:[0], t:'text0', o:[{p:204, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:204, i:'hi'}]}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:['x'], t:'text0', o:[{p:3,i: 'hi'}]}], type.transform [{p:['x'], t:'text0', o:[{p:3, i:'hi'}]}], [{p:['x',0,'x'], li:0}], 'left' assert.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'left' assert.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'right' it 'converts ops on deleted elements to noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[0],li:'x'}], type.transform [{p:[0],li:'x'}], [{p:[0],ld:'y'}], 'left' assert.deepEqual [], type.transform [{p:[0],na:-3}], [{p:[0],ld:48}], 'left' it 'converts ops on replaced elements to noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x', li:'y'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], ld:'x', li:'y'}], 'left' assert.deepEqual [{p:[0], li:'hi'}], type.transform [{p:[0], li:'hi'}], [{p:[0], ld:'x', li:'y'}], 'left' it 'changes deleted data to reflect edits', -> assert.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1, 1], si:'bc'}], 'left' assert.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1], t:'text0', o:[{p:1, i:'bc'}]}], 'left' it 'Puts the left op first if two inserts are simultaneous', -> assert.deepEqual [{p:[1], li:'a'}], type.transform [{p:[1], li:'a'}], [{p:[1], li:'b'}], 'left' assert.deepEqual [{p:[2], li:'b'}], type.transform [{p:[1], li:'b'}], [{p:[1], li:'a'}], 'right' it 'converts an attempt to re-delete a list element into a no-op', -> assert.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'right' describe '#compose()', -> it 'composes insert then delete into a no-op', -> assert.deepEqual [], type.compose [{p:[1], li:'abc'}], [{p:[1], ld:'abc'}] assert.deepEqual [{p:[1],ld:null,li:'x'}], type.transform [{p:[0],ld:null,li:"x"}], [{p:[0],li:"The"}], 'right' it 'doesn\'t change the original object', -> a = [{p:[0],ld:'abc',li:null}] assert.deepEqual [{p:[0],ld:'abc'}], type.compose a, [{p:[0],ld:null}] assert.deepEqual [{p:[0],ld:'abc',li:null}], a it 'composes together adjacent string ops', -> assert.deepEqual [{p:[100], si:'hi'}], type.compose [{p:[100], si:'h'}], [{p:[101], si:'i'}] assert.deepEqual [{p:[], t:'text0', o:[{p:100, i:'hi'}]}], type.compose [{p:[], t:'text0', o:[{p:100, i:'h'}]}], [{p:[], t:'text0', o:[{p:101, i:'i'}]}] it 'moves ops on a moved element with the element', -> assert.deepEqual [{p:[10], ld:'x'}], type.transform [{p:[4], ld:'x'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], si:'a'}], type.transform [{p:[4, 1], si:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10], t:'text0', o:[{p:1, i:'a'}]}], type.transform [{p:[4], t:'text0', o:[{p:1, i:'a'}]}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], li:'a'}], type.transform [{p:[4, 1], li:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], ld:'b', li:'a'}], type.transform [{p:[4, 1], ld:'b', li:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[0],li:null}], type.transform [{p:[0],li:null}], [{p:[0],lm:1}], 'left' # [_,_,_,_,5,6,7,_] # c: [_,_,_,_,5,'x',6,7,_] p:5 li:'x' # s: [_,6,_,_,_,5,7,_] p:5 lm:1 # correct: [_,6,_,_,_,5,'x',7,_] assert.deepEqual [{p:[6],li:'x'}], type.transform [{p:[5],li:'x'}], [{p:[5],lm:1}], 'left' # [_,_,_,_,5,6,7,_] # c: [_,_,_,_,5,6,7,_] p:5 ld:6 # s: [_,6,_,_,_,5,7,_] p:5 lm:1 # correct: [_,_,_,_,5,7,_] assert.deepEqual [{p:[1],ld:6}], type.transform [{p:[5],ld:6}], [{p:[5],lm:1}], 'left' #assert.deepEqual [{p:[0],li:{}}], type.transform [{p:[0],li:{}}], [{p:[0],lm:0}], 'right' assert.deepEqual [{p:[0],li:[]}], type.transform [{p:[0],li:[]}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],li:'x'}], type.transform [{p:[2],li:'x'}], [{p:[0],lm:1}], 'left' it 'moves target index on ld/li', -> assert.deepEqual [{p:[0],lm:1}], type.transform [{p:[0], lm: 2}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[1],lm:3}], type.transform [{p:[2], lm: 4}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[0],lm:3}], type.transform [{p:[0], lm: 2}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[3],lm:5}], type.transform [{p:[2], lm: 4}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0], lm: 0}], [{p:[0], li:28}], 'left' it 'tiebreaks lm vs. ld/li', -> assert.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'right' assert.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'right' it 'replacement vs. deletion', -> assert.deepEqual [{p:[0],li:'y'}], type.transform [{p:[0],ld:'x',li:'y'}], [{p:[0],ld:'x'}], 'right' it 'replacement vs. insertion', -> assert.deepEqual [{p:[1],ld:{},li:"brillig"}], type.transform [{p:[0],ld:{},li:"brillig"}], [{p:[0],li:36}], 'left' it 'replacement vs. replacement', -> assert.deepEqual [], type.transform [{p:[0],ld:null,li:[]}], [{p:[0],ld:null,li:0}], 'right' assert.deepEqual [{p:[0],ld:[],li:0}], type.transform [{p:[0],ld:null,li:0}], [{p:[0],ld:null,li:[]}], 'left' it 'composes replace with delete of replaced element results in insert', -> assert.deepEqual [{p:[2],ld:[]}], type.compose [{p:[2],ld:[],li:null}], [{p:[2],ld:null}] it 'lm vs lm', -> assert.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:2}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[4],lm:4}], type.transform [{p:[3],lm:3}], [{p:[5],lm:0}], 'left' assert.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],lm:1}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'right' assert.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[3],lm:0}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'left' assert.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left' assert.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:5}], 'right' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:1}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[1],lm:2}], type.transform [{p:[0],lm:1}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[3],lm:2}], type.transform [{p:[2],lm:1}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[2],lm:1}], type.transform [{p:[3],lm:1}], [{p:[1],lm:3}], 'left' assert.deepEqual [{p:[2],lm:3}], type.transform [{p:[1],lm:3}], [{p:[3],lm:1}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'right' assert.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:1}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:1}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:0}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],lm:3}], 'left' assert.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:1}], [{p:[3],lm:2}], 'left' assert.deepEqual [{p:[3],lm:3}], type.transform [{p:[3],lm:2}], [{p:[2],lm:1}], 'left' it 'changes indices correctly around a move', -> assert.deepEqual [{p:[1,0],li:{}}], type.transform [{p:[0,0],li:{}}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],ld:{}}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],ld:{}}], 'left' assert.deepEqual [{p:[5],lm:0}], type.transform [{p:[6],lm:0}], [{p:[2],ld:{}}], 'left' assert.deepEqual [{p:[1],lm:0}], type.transform [{p:[1],lm:0}], [{p:[2],ld:{}}], 'left' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[2],lm:1}], [{p:[1],ld:3}], 'right' assert.deepEqual [{p:[1],ld:{}}], type.transform [{p:[2],ld:{}}], [{p:[1],lm:2}], 'right' assert.deepEqual [{p:[2],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[0],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[0],ld:1,li:2}], type.transform [{p:[1],ld:1,li:2}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],ld:2,li:3}], type.transform [{p:[1],ld:2,li:3}], [{p:[0],lm:1}], 'left' assert.deepEqual [{p:[1],ld:3,li:4}], type.transform [{p:[0],ld:3,li:4}], [{p:[1],lm:0}], 'left' it 'li vs lm', -> li = (p) -> [{p:[p],li:[]}] lm = (f,t) -> [{p:[f],lm:t}] xf = type.transform assert.deepEqual (li 0), xf (li 0), (lm 1, 3), 'left' assert.deepEqual (li 1), xf (li 1), (lm 1, 3), 'left' assert.deepEqual (li 1), xf (li 2), (lm 1, 3), 'left' assert.deepEqual (li 2), xf (li 3), (lm 1, 3), 'left' assert.deepEqual (li 4), xf (li 4), (lm 1, 3), 'left' assert.deepEqual (lm 2, 4), xf (lm 1, 3), (li 0), 'right' assert.deepEqual (lm 2, 4), xf (lm 1, 3), (li 1), 'right' assert.deepEqual (lm 1, 4), xf (lm 1, 3), (li 2), 'right' assert.deepEqual (lm 1, 4), xf (lm 1, 3), (li 3), 'right' assert.deepEqual (lm 1, 3), xf (lm 1, 3), (li 4), 'right' assert.deepEqual (li 0), xf (li 0), (lm 1, 2), 'left' assert.deepEqual (li 1), xf (li 1), (lm 1, 2), 'left' assert.deepEqual (li 1), xf (li 2), (lm 1, 2), 'left' assert.deepEqual (li 3), xf (li 3), (lm 1, 2), 'left' assert.deepEqual (li 0), xf (li 0), (lm 3, 1), 'left' assert.deepEqual (li 1), xf (li 1), (lm 3, 1), 'left' assert.deepEqual (li 3), xf (li 2), (lm 3, 1), 'left' assert.deepEqual (li 4), xf (li 3), (lm 3, 1), 'left' assert.deepEqual (li 4), xf (li 4), (lm 3, 1), 'left' assert.deepEqual (lm 4, 2), xf (lm 3, 1), (li 0), 'right' assert.deepEqual (lm 4, 2), xf (lm 3, 1), (li 1), 'right' assert.deepEqual (lm 4, 1), xf (lm 3, 1), (li 2), 'right' assert.deepEqual (lm 4, 1), xf (lm 3, 1), (li 3), 'right' assert.deepEqual (lm 3, 1), xf (lm 3, 1), (li 4), 'right' assert.deepEqual (li 0), xf (li 0), (lm 2, 1), 'left' assert.deepEqual (li 1), xf (li 1), (lm 2, 1), 'left' assert.deepEqual (li 3), xf (li 2), (lm 2, 1), 'left' assert.deepEqual (li 3), xf (li 3), (lm 2, 1), 'left' describe 'object', -> it 'passes sanity checks', -> assert.deepEqual {x:'a', y:'b'}, type.apply {x:'a'}, [{p:['y'], oi:'b'}] assert.deepEqual {}, type.apply {x:'a'}, [{p:['x'], od:'a'}] assert.deepEqual {x:'b'}, type.apply {x:'a'}, [{p:['x'], od:'a', oi:'b'}] it 'Ops on deleted elements become noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:[9],si:"bite "}], [{p:[],od:"agimble s",oi:null}], 'right' assert.deepEqual [], type.transform [{p:[], t:'text0', o:[{p:9, i:"bite "}]}], [{p:[],od:"agimble s",oi:null}], 'right' it 'Ops on replaced elements become noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x', oi:'y'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], od:'x', oi:'y'}], 'left' it 'Deleted data is changed to reflect edits', -> assert.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1, 1], si:'bc'}], 'left' assert.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1], t:'text0', o:[{p:1, i:'bc'}]}], 'left' assert.deepEqual [{p:[],od:25,oi:[]}], type.transform [{p:[],od:22,oi:[]}], [{p:[],na:3}], 'left' assert.deepEqual [{p:[],od:{toves:""},oi:4}], type.transform [{p:[],od:{toves:0},oi:4}], [{p:["toves"],od:0,oi:""}], 'left' assert.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[7],sd:"d "}], 'left' assert.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[], t:'text0', o:[{p:7, d:"d "}]}], 'left' assert.deepEqual [], type.transform([{p:["bird"],na:2}], [{p:[],od:{bird:38},oi:20}], 'right') assert.deepEqual [{p:[],od:{bird:40},oi:20}], type.transform([{p:[],od:{bird:38},oi:20}], [{p:["bird"],na:2}], 'left') assert.deepEqual [{p:['He'],od:[]}], type.transform [{p:["He"],od:[]}], [{p:["The"],na:-3}], 'right' assert.deepEqual [], type.transform [{p:["He"],oi:{}}], [{p:[],od:{},oi:"the"}], 'left' it 'If two inserts are simultaneous, the lefts insert will win', -> assert.deepEqual [{p:[1], oi:'a', od:'b'}], type.transform [{p:[1], oi:'a'}], [{p:[1], oi:'b'}], 'left' assert.deepEqual [], type.transform [{p:[1], oi:'b'}], [{p:[1], oi:'a'}], 'right' it 'parallel ops on different keys miss each other', -> assert.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], oi:'z'}], 'left' assert.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], od:'z'}], 'left' assert.deepEqual [{p:["in","he"],oi:{}}], type.transform [{p:["in","he"],oi:{}}], [{p:["and"],od:{}}], 'right' assert.deepEqual [{p:['x',0],si:"his "}], type.transform [{p:['x',0],si:"his "}], [{p:['y'],od:0,oi:1}], 'right' assert.deepEqual [{p:['x'], t:'text0', o:[{p:0, i:"his "}]}], type.transform [{p:['x'],t:'text0', o:[{p:0, i:"his "}]}], [{p:['y'],od:0,oi:1}], 'right' it 'replacement vs. deletion', -> assert.deepEqual [{p:[],oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:['']}], 'right' it 'replacement vs. replacement', -> assert.deepEqual [], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'right' assert.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'left' assert.deepEqual [], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'right' assert.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'left' # test diamond property rightOps = [ {"p":[],"od":null,"oi":{}} ] leftOps = [ {"p":[],"od":null,"oi":""} ] rightHas = type.apply(null, rightOps) leftHas = type.apply(null, leftOps) [left_, right_] = transformX type, leftOps, rightOps assert.deepEqual leftHas, type.apply rightHas, left_ assert.deepEqual leftHas, type.apply leftHas, right_ it 'An attempt to re-delete a key becomes a no-op', -> assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right' describe 'transformCursor', -> describe 'string operations', -> it 'handles inserts before', -> assert.deepEqual ['key', 10, 3+4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], si: 'meow'}]) it 'handles inserts after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], si: 'meow'}]) it 'handles inserts at current point with isOwnOp', -> assert.deepEqual ['key', 10, 3+4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], si: 'meow'}], true) it 'handles inserts at current point without isOwnOp', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], si: 'meow'}]) it 'handles deletes before', -> assert.deepEqual ['key', 10, 3-2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 0], sd: '12'}]) it 'handles deletes after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], sd: '12'}]) it 'handles deletes at current point', -> assert.deepEqual ['key', 10, 1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], sd: 'meow meow'}]) it 'ignores irrelevant operations', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 9, 1], si: 'meow'}]) describe 'number operations', -> it 'ignores', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], na: 123}]) describe 'list operations', -> it 'handles inserts before', -> assert.deepEqual ['key', 10, 3+1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], li: 'meow'}]) assert.deepEqual ['key', 10+1, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10], li: 'meow'}]) it 'handles inserts after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 4], li: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 11], li: 'meow'}]) it 'handles replacements at current point', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], ld: 'meow1', li: 'meow2'}]) assert.deepEqual ['key', 10], type.transformCursor(['key', 10, 3], [{p: ['key', 10], ld: 'meow1', li: 'meow2'}]) # move cursor up tree when parent deleted it 'handles deletes before', -> assert.deepEqual ['key', 10, 3-1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], ld: 'meow'}]) assert.deepEqual ['key', 10-1, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 9], ld: 'meow'}]) it 'handles deletes after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 4], ld: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 11], ld: 'meow'}]) it 'handles deletes at current point', -> assert.deepEqual ['key', 10], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], ld: 'meow'}]) assert.deepEqual ['key'], type.transformCursor(['key', 10, 3], [{p: ['key', 10], ld: 'meow'}]) it 'handles movements of current point', -> assert.deepEqual ['key', 10, 20], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], lm: 20}]) assert.deepEqual ['key', 20, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10], lm: 20}]) it 'handles movements of other points', -> assert.deepEqual ['key', 10, 2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], lm: 20}]) assert.deepEqual ['key', 10, 4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], lm: 3}]) assert.deepEqual ['key', 10, 4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], lm: 1}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 10], lm: 20}]) assert.deepEqual ['key', 10, 2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], lm: 3}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], lm: 1}]) describe 'dict operations', -> it 'ignores irrelevant inserts and deletes', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key2'], oi: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key2'], od: 'meow'}]) it 'handles deletes at current point', -> assert.deepEqual [], type.transformCursor(['key', 0, 3], [{p: ['key'], od: ['meow123']}]) assert.deepEqual ['key', 0], type.transformCursor(['key', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['meow123']}]) it 'handles replacements at current point', -> assert.deepEqual ['key'], type.transformCursor(['key', 0, 3], [{p: ['key'], od: ['meow123'], oi: 'newobj'}]) assert.deepEqual ['key', 0, 'key2'], type.transformCursor(['key', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['me<PASSWORD>'], oi: 'newobj'}]) describe 'randomizer', -> @timeout 20000 @slow 6000 it 'passes', -> fuzzer type, require('./json0-generator'), 1000 it 'passes with string subtype', -> type._testStringSubtype = true # hack fuzzer type, require('./json0-generator'), 1000 delete type._testStringSubtype describe 'json', -> describe 'native type', -> genTests nativetype #exports.webclient = genTests require('../helpers/webclient').types.json
true
# Tests for JSON OT type. assert = require 'assert' nativetype = require '../lib/json0' fuzzer = require 'ot-fuzzer' nativetype.registerSubtype name: 'mock' transform: (a, b, side) -> return { mock: true } # Cross-transform helper function. Transform server by client and client by # server. Returns [server, client]. transformX = (type, left, right) -> [type.transform(left, right, 'left'), type.transform(right, left, 'right')] genTests = (type) -> # The random op tester above will test that the OT functions are admissable, # but debugging problems it detects is a pain. # # These tests should pick up *most* problems with a normal JSON OT # implementation. describe 'sanity', -> describe '#create()', -> it 'returns null', -> assert.deepEqual type.create(), null describe '#compose()', -> it 'od,oi --> od+oi', -> assert.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1}],[{p:['foo'],oi:2}] assert.deepEqual [{p:['foo'], od:1},{p:['bar'], oi:2}], type.compose [{p:['foo'],od:1}],[{p:['bar'],oi:2}] it 'merges od+oi, od+oi -> od+oi', -> assert.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1,oi:3}],[{p:['foo'],od:3,oi:2}] describe '#transform()', -> it 'returns sane values', -> t = (op1, op2) -> assert.deepEqual op1, type.transform op1, op2, 'left' assert.deepEqual op1, type.transform op1, op2, 'right' t [], [] t [{p:['foo'], oi:1}], [] t [{p:['foo'], oi:1}], [{p:['bar'], oi:2}] describe 'number', -> it 'Adds a number', -> assert.deepEqual 3, type.apply 1, [{p:[], na:2}] assert.deepEqual [3], type.apply [1], [{p:[0], na:2}] it 'compresses two adds together in compose', -> assert.deepEqual [{p:['a', 'b'], na:3}], type.compose [{p:['a', 'b'], na:1}], [{p:['a', 'b'], na:2}] assert.deepEqual [{p:['a'], na:1}, {p:['b'], na:2}], type.compose [{p:['a'], na:1}], [{p:['b'], na:2}] it 'doesn\'t overwrite values when it merges na in append', -> rightHas = 21 leftHas = 3 rightOp = [{"p":[],"od":0,"oi":15},{"p":[],"na":4},{"p":[],"na":1},{"p":[],"na":1}] leftOp = [{"p":[],"na":4},{"p":[],"na":-1}] [right_, left_] = transformX type, rightOp, leftOp s_c = type.apply rightHas, left_ c_s = type.apply leftHas, right_ assert.deepEqual s_c, c_s # Strings should be handled internally by the text type. We'll just do some basic sanity checks here. describe 'string', -> describe '#apply()', -> it 'works', -> assert.deepEqual 'abc', type.apply 'a', [{p:[1], si:'bc'}] assert.deepEqual 'bc', type.apply 'abc', [{p:[0], sd:'a'}] assert.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x', 1], si:'bc'}] describe '#transform()', -> it 'splits deletes', -> assert.deepEqual type.transform([{p:[0], sd:'ab'}], [{p:[1], si:'x'}], 'left'), [{p:[0], sd:'a'}, {p:[1], sd:'b'}] it 'cancels out other deletes', -> assert.deepEqual type.transform([{p:['k', 5], sd:'a'}], [{p:['k', 5], sd:'a'}], 'left'), [] it 'does not throw errors with blank inserts', -> assert.deepEqual type.transform([{p: ['k', 5], si:''}], [{p: ['k', 3], si: 'a'}], 'left'), [] describe 'string subtype', -> describe '#apply()', -> it 'works', -> assert.deepEqual 'abc', type.apply 'a', [{p:[], t:'text0', o:[{p:1, i:'bc'}]}] assert.deepEqual 'bc', type.apply 'abc', [{p:[], t:'text0', o:[{p:0, d:'a'}]}] assert.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x'], t:'text0', o:[{p:1, i:'bc'}]}] describe '#transform()', -> it 'splits deletes', -> a = [{p:[], t:'text0', o:[{p:0, d:'ab'}]}] b = [{p:[], t:'text0', o:[{p:1, i:'x'}]}] assert.deepEqual type.transform(a, b, 'left'), [{p:[], t:'text0', o:[{p:0, d:'a'}, {p:1, d:'b'}]}] it 'cancels out other deletes', -> assert.deepEqual type.transform([{p:['k'], t:'text0', o:[{p:5, d:'a'}]}], [{p:['k'], t:'text0', o:[{p:5, d:'a'}]}], 'left'), [] it 'does not throw errors with blank inserts', -> assert.deepEqual type.transform([{p:['k'], t:'text0', o:[{p:5, i:''}]}], [{p:['k'], t:'text0', o:[{p:3, i:'a'}]}], 'left'), [] describe 'subtype with non-array operation', -> describe '#transform()', -> it 'works', -> a = [{p:[], t:'mock', o:'foo'}] b = [{p:[], t:'mock', o:'bar'}] assert.deepEqual type.transform(a, b, 'left'), [{p:[], t:'mock', o:{mock:true}}] describe 'list', -> describe 'apply', -> it 'inserts', -> assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'c'], [{p:[0], li:'a'}] assert.deepEqual ['a', 'b', 'c'], type.apply ['a', 'c'], [{p:[1], li:'b'}] assert.deepEqual ['a', 'b', 'c'], type.apply ['a', 'b'], [{p:[2], li:'c'}] it 'deletes', -> assert.deepEqual ['b', 'c'], type.apply ['a', 'b', 'c'], [{p:[0], ld:'a'}] assert.deepEqual ['a', 'c'], type.apply ['a', 'b', 'c'], [{p:[1], ld:'b'}] assert.deepEqual ['a', 'b'], type.apply ['a', 'b', 'c'], [{p:[2], ld:'c'}] it 'replaces', -> assert.deepEqual ['a', 'y', 'b'], type.apply ['a', 'x', 'b'], [{p:[1], ld:'x', li:'y'}] it 'moves', -> assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[1], lm:0}] assert.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[0], lm:1}] ### 'null moves compose to nops', -> assert.deepEqual [], type.compose [], [{p:[3],lm:3}] assert.deepEqual [], type.compose [], [{p:[0,3],lm:3}] assert.deepEqual [], type.compose [], [{p:['x','y',0],lm:0}] ### describe '#transform()', -> it 'bumps paths when list elements are inserted or removed', -> assert.deepEqual [{p:[2, 200], si:'hi'}], type.transform [{p:[1, 200], si:'hi'}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1, 201], si:'hi'}], type.transform [{p:[0, 201], si:'hi'}], [{p:[0], li:'x'}], 'right' assert.deepEqual [{p:[0, 202], si:'hi'}], type.transform [{p:[0, 202], si:'hi'}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[2], t:'text0', o:[{p:200, i:'hi'}]}], type.transform [{p:[1], t:'text0', o:[{p:200, i:'hi'}]}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1], t:'text0', o:[{p:201, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:201, i:'hi'}]}], [{p:[0], li:'x'}], 'right' assert.deepEqual [{p:[0], t:'text0', o:[{p:202, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:202, i:'hi'}]}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[0, 203], si:'hi'}], type.transform [{p:[1, 203], si:'hi'}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [{p:[0, 204], si:'hi'}], type.transform [{p:[0, 204], si:'hi'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:['x',3], si: 'hi'}], type.transform [{p:['x',3], si:'hi'}], [{p:['x',0,'x'], li:0}], 'left' assert.deepEqual [{p:['x',3,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',5], li:0}], 'left' assert.deepEqual [{p:['x',4,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',0], li:0}], 'left' assert.deepEqual [{p:[0], t:'text0', o:[{p:203, i:'hi'}]}], type.transform [{p:[1], t:'text0', o:[{p:203, i:'hi'}]}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [{p:[0], t:'text0', o:[{p:204, i:'hi'}]}], type.transform [{p:[0], t:'text0', o:[{p:204, i:'hi'}]}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:['x'], t:'text0', o:[{p:3,i: 'hi'}]}], type.transform [{p:['x'], t:'text0', o:[{p:3, i:'hi'}]}], [{p:['x',0,'x'], li:0}], 'left' assert.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'left' assert.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'right' it 'converts ops on deleted elements to noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[0],li:'x'}], type.transform [{p:[0],li:'x'}], [{p:[0],ld:'y'}], 'left' assert.deepEqual [], type.transform [{p:[0],na:-3}], [{p:[0],ld:48}], 'left' it 'converts ops on replaced elements to noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x', li:'y'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], ld:'x', li:'y'}], 'left' assert.deepEqual [{p:[0], li:'hi'}], type.transform [{p:[0], li:'hi'}], [{p:[0], ld:'x', li:'y'}], 'left' it 'changes deleted data to reflect edits', -> assert.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1, 1], si:'bc'}], 'left' assert.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1], t:'text0', o:[{p:1, i:'bc'}]}], 'left' it 'Puts the left op first if two inserts are simultaneous', -> assert.deepEqual [{p:[1], li:'a'}], type.transform [{p:[1], li:'a'}], [{p:[1], li:'b'}], 'left' assert.deepEqual [{p:[2], li:'b'}], type.transform [{p:[1], li:'b'}], [{p:[1], li:'a'}], 'right' it 'converts an attempt to re-delete a list element into a no-op', -> assert.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'right' describe '#compose()', -> it 'composes insert then delete into a no-op', -> assert.deepEqual [], type.compose [{p:[1], li:'abc'}], [{p:[1], ld:'abc'}] assert.deepEqual [{p:[1],ld:null,li:'x'}], type.transform [{p:[0],ld:null,li:"x"}], [{p:[0],li:"The"}], 'right' it 'doesn\'t change the original object', -> a = [{p:[0],ld:'abc',li:null}] assert.deepEqual [{p:[0],ld:'abc'}], type.compose a, [{p:[0],ld:null}] assert.deepEqual [{p:[0],ld:'abc',li:null}], a it 'composes together adjacent string ops', -> assert.deepEqual [{p:[100], si:'hi'}], type.compose [{p:[100], si:'h'}], [{p:[101], si:'i'}] assert.deepEqual [{p:[], t:'text0', o:[{p:100, i:'hi'}]}], type.compose [{p:[], t:'text0', o:[{p:100, i:'h'}]}], [{p:[], t:'text0', o:[{p:101, i:'i'}]}] it 'moves ops on a moved element with the element', -> assert.deepEqual [{p:[10], ld:'x'}], type.transform [{p:[4], ld:'x'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], si:'a'}], type.transform [{p:[4, 1], si:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10], t:'text0', o:[{p:1, i:'a'}]}], type.transform [{p:[4], t:'text0', o:[{p:1, i:'a'}]}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], li:'a'}], type.transform [{p:[4, 1], li:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[10, 1], ld:'b', li:'a'}], type.transform [{p:[4, 1], ld:'b', li:'a'}], [{p:[4], lm:10}], 'left' assert.deepEqual [{p:[0],li:null}], type.transform [{p:[0],li:null}], [{p:[0],lm:1}], 'left' # [_,_,_,_,5,6,7,_] # c: [_,_,_,_,5,'x',6,7,_] p:5 li:'x' # s: [_,6,_,_,_,5,7,_] p:5 lm:1 # correct: [_,6,_,_,_,5,'x',7,_] assert.deepEqual [{p:[6],li:'x'}], type.transform [{p:[5],li:'x'}], [{p:[5],lm:1}], 'left' # [_,_,_,_,5,6,7,_] # c: [_,_,_,_,5,6,7,_] p:5 ld:6 # s: [_,6,_,_,_,5,7,_] p:5 lm:1 # correct: [_,_,_,_,5,7,_] assert.deepEqual [{p:[1],ld:6}], type.transform [{p:[5],ld:6}], [{p:[5],lm:1}], 'left' #assert.deepEqual [{p:[0],li:{}}], type.transform [{p:[0],li:{}}], [{p:[0],lm:0}], 'right' assert.deepEqual [{p:[0],li:[]}], type.transform [{p:[0],li:[]}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],li:'x'}], type.transform [{p:[2],li:'x'}], [{p:[0],lm:1}], 'left' it 'moves target index on ld/li', -> assert.deepEqual [{p:[0],lm:1}], type.transform [{p:[0], lm: 2}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[1],lm:3}], type.transform [{p:[2], lm: 4}], [{p:[1], ld:'x'}], 'left' assert.deepEqual [{p:[0],lm:3}], type.transform [{p:[0], lm: 2}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[3],lm:5}], type.transform [{p:[2], lm: 4}], [{p:[1], li:'x'}], 'left' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0], lm: 0}], [{p:[0], li:28}], 'left' it 'tiebreaks lm vs. ld/li', -> assert.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'left' assert.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'right' assert.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'left' assert.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'right' it 'replacement vs. deletion', -> assert.deepEqual [{p:[0],li:'y'}], type.transform [{p:[0],ld:'x',li:'y'}], [{p:[0],ld:'x'}], 'right' it 'replacement vs. insertion', -> assert.deepEqual [{p:[1],ld:{},li:"brillig"}], type.transform [{p:[0],ld:{},li:"brillig"}], [{p:[0],li:36}], 'left' it 'replacement vs. replacement', -> assert.deepEqual [], type.transform [{p:[0],ld:null,li:[]}], [{p:[0],ld:null,li:0}], 'right' assert.deepEqual [{p:[0],ld:[],li:0}], type.transform [{p:[0],ld:null,li:0}], [{p:[0],ld:null,li:[]}], 'left' it 'composes replace with delete of replaced element results in insert', -> assert.deepEqual [{p:[2],ld:[]}], type.compose [{p:[2],ld:[],li:null}], [{p:[2],ld:null}] it 'lm vs lm', -> assert.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:2}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[4],lm:4}], type.transform [{p:[3],lm:3}], [{p:[5],lm:0}], 'left' assert.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],lm:1}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'right' assert.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[3],lm:0}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'left' assert.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left' assert.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:5}], 'right' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:1}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[1],lm:2}], type.transform [{p:[0],lm:1}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[3],lm:2}], type.transform [{p:[2],lm:1}], [{p:[5],lm:0}], 'right' assert.deepEqual [{p:[2],lm:1}], type.transform [{p:[3],lm:1}], [{p:[1],lm:3}], 'left' assert.deepEqual [{p:[2],lm:3}], type.transform [{p:[1],lm:3}], [{p:[3],lm:1}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'right' assert.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:1}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:1}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:0}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],lm:3}], 'left' assert.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:1}], [{p:[3],lm:2}], 'left' assert.deepEqual [{p:[3],lm:3}], type.transform [{p:[3],lm:2}], [{p:[2],lm:1}], 'left' it 'changes indices correctly around a move', -> assert.deepEqual [{p:[1,0],li:{}}], type.transform [{p:[0,0],li:{}}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],ld:{}}], 'left' assert.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],ld:{}}], 'left' assert.deepEqual [{p:[5],lm:0}], type.transform [{p:[6],lm:0}], [{p:[2],ld:{}}], 'left' assert.deepEqual [{p:[1],lm:0}], type.transform [{p:[1],lm:0}], [{p:[2],ld:{}}], 'left' assert.deepEqual [{p:[1],lm:1}], type.transform [{p:[2],lm:1}], [{p:[1],ld:3}], 'right' assert.deepEqual [{p:[1],ld:{}}], type.transform [{p:[2],ld:{}}], [{p:[1],lm:2}], 'right' assert.deepEqual [{p:[2],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[2],lm:1}], 'left' assert.deepEqual [{p:[0],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[0],lm:1}], 'right' assert.deepEqual [{p:[0],ld:1,li:2}], type.transform [{p:[1],ld:1,li:2}], [{p:[1],lm:0}], 'left' assert.deepEqual [{p:[0],ld:2,li:3}], type.transform [{p:[1],ld:2,li:3}], [{p:[0],lm:1}], 'left' assert.deepEqual [{p:[1],ld:3,li:4}], type.transform [{p:[0],ld:3,li:4}], [{p:[1],lm:0}], 'left' it 'li vs lm', -> li = (p) -> [{p:[p],li:[]}] lm = (f,t) -> [{p:[f],lm:t}] xf = type.transform assert.deepEqual (li 0), xf (li 0), (lm 1, 3), 'left' assert.deepEqual (li 1), xf (li 1), (lm 1, 3), 'left' assert.deepEqual (li 1), xf (li 2), (lm 1, 3), 'left' assert.deepEqual (li 2), xf (li 3), (lm 1, 3), 'left' assert.deepEqual (li 4), xf (li 4), (lm 1, 3), 'left' assert.deepEqual (lm 2, 4), xf (lm 1, 3), (li 0), 'right' assert.deepEqual (lm 2, 4), xf (lm 1, 3), (li 1), 'right' assert.deepEqual (lm 1, 4), xf (lm 1, 3), (li 2), 'right' assert.deepEqual (lm 1, 4), xf (lm 1, 3), (li 3), 'right' assert.deepEqual (lm 1, 3), xf (lm 1, 3), (li 4), 'right' assert.deepEqual (li 0), xf (li 0), (lm 1, 2), 'left' assert.deepEqual (li 1), xf (li 1), (lm 1, 2), 'left' assert.deepEqual (li 1), xf (li 2), (lm 1, 2), 'left' assert.deepEqual (li 3), xf (li 3), (lm 1, 2), 'left' assert.deepEqual (li 0), xf (li 0), (lm 3, 1), 'left' assert.deepEqual (li 1), xf (li 1), (lm 3, 1), 'left' assert.deepEqual (li 3), xf (li 2), (lm 3, 1), 'left' assert.deepEqual (li 4), xf (li 3), (lm 3, 1), 'left' assert.deepEqual (li 4), xf (li 4), (lm 3, 1), 'left' assert.deepEqual (lm 4, 2), xf (lm 3, 1), (li 0), 'right' assert.deepEqual (lm 4, 2), xf (lm 3, 1), (li 1), 'right' assert.deepEqual (lm 4, 1), xf (lm 3, 1), (li 2), 'right' assert.deepEqual (lm 4, 1), xf (lm 3, 1), (li 3), 'right' assert.deepEqual (lm 3, 1), xf (lm 3, 1), (li 4), 'right' assert.deepEqual (li 0), xf (li 0), (lm 2, 1), 'left' assert.deepEqual (li 1), xf (li 1), (lm 2, 1), 'left' assert.deepEqual (li 3), xf (li 2), (lm 2, 1), 'left' assert.deepEqual (li 3), xf (li 3), (lm 2, 1), 'left' describe 'object', -> it 'passes sanity checks', -> assert.deepEqual {x:'a', y:'b'}, type.apply {x:'a'}, [{p:['y'], oi:'b'}] assert.deepEqual {}, type.apply {x:'a'}, [{p:['x'], od:'a'}] assert.deepEqual {x:'b'}, type.apply {x:'a'}, [{p:['x'], od:'a', oi:'b'}] it 'Ops on deleted elements become noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:[9],si:"bite "}], [{p:[],od:"agimble s",oi:null}], 'right' assert.deepEqual [], type.transform [{p:[], t:'text0', o:[{p:9, i:"bite "}]}], [{p:[],od:"agimble s",oi:null}], 'right' it 'Ops on replaced elements become noops', -> assert.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x', oi:'y'}], 'left' assert.deepEqual [], type.transform [{p:[1], t:'text0', o:[{p:0, i:'hi'}]}], [{p:[1], od:'x', oi:'y'}], 'left' it 'Deleted data is changed to reflect edits', -> assert.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1, 1], si:'bc'}], 'left' assert.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1], t:'text0', o:[{p:1, i:'bc'}]}], 'left' assert.deepEqual [{p:[],od:25,oi:[]}], type.transform [{p:[],od:22,oi:[]}], [{p:[],na:3}], 'left' assert.deepEqual [{p:[],od:{toves:""},oi:4}], type.transform [{p:[],od:{toves:0},oi:4}], [{p:["toves"],od:0,oi:""}], 'left' assert.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[7],sd:"d "}], 'left' assert.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[], t:'text0', o:[{p:7, d:"d "}]}], 'left' assert.deepEqual [], type.transform([{p:["bird"],na:2}], [{p:[],od:{bird:38},oi:20}], 'right') assert.deepEqual [{p:[],od:{bird:40},oi:20}], type.transform([{p:[],od:{bird:38},oi:20}], [{p:["bird"],na:2}], 'left') assert.deepEqual [{p:['He'],od:[]}], type.transform [{p:["He"],od:[]}], [{p:["The"],na:-3}], 'right' assert.deepEqual [], type.transform [{p:["He"],oi:{}}], [{p:[],od:{},oi:"the"}], 'left' it 'If two inserts are simultaneous, the lefts insert will win', -> assert.deepEqual [{p:[1], oi:'a', od:'b'}], type.transform [{p:[1], oi:'a'}], [{p:[1], oi:'b'}], 'left' assert.deepEqual [], type.transform [{p:[1], oi:'b'}], [{p:[1], oi:'a'}], 'right' it 'parallel ops on different keys miss each other', -> assert.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], oi:'z'}], 'left' assert.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], od:'z'}], 'left' assert.deepEqual [{p:["in","he"],oi:{}}], type.transform [{p:["in","he"],oi:{}}], [{p:["and"],od:{}}], 'right' assert.deepEqual [{p:['x',0],si:"his "}], type.transform [{p:['x',0],si:"his "}], [{p:['y'],od:0,oi:1}], 'right' assert.deepEqual [{p:['x'], t:'text0', o:[{p:0, i:"his "}]}], type.transform [{p:['x'],t:'text0', o:[{p:0, i:"his "}]}], [{p:['y'],od:0,oi:1}], 'right' it 'replacement vs. deletion', -> assert.deepEqual [{p:[],oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:['']}], 'right' it 'replacement vs. replacement', -> assert.deepEqual [], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'right' assert.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'left' assert.deepEqual [], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'right' assert.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'left' # test diamond property rightOps = [ {"p":[],"od":null,"oi":{}} ] leftOps = [ {"p":[],"od":null,"oi":""} ] rightHas = type.apply(null, rightOps) leftHas = type.apply(null, leftOps) [left_, right_] = transformX type, leftOps, rightOps assert.deepEqual leftHas, type.apply rightHas, left_ assert.deepEqual leftHas, type.apply leftHas, right_ it 'An attempt to re-delete a key becomes a no-op', -> assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left' assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right' describe 'transformCursor', -> describe 'string operations', -> it 'handles inserts before', -> assert.deepEqual ['key', 10, 3+4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], si: 'meow'}]) it 'handles inserts after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], si: 'meow'}]) it 'handles inserts at current point with isOwnOp', -> assert.deepEqual ['key', 10, 3+4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], si: 'meow'}], true) it 'handles inserts at current point without isOwnOp', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], si: 'meow'}]) it 'handles deletes before', -> assert.deepEqual ['key', 10, 3-2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 0], sd: '12'}]) it 'handles deletes after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], sd: '12'}]) it 'handles deletes at current point', -> assert.deepEqual ['key', 10, 1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], sd: 'meow meow'}]) it 'ignores irrelevant operations', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 9, 1], si: 'meow'}]) describe 'number operations', -> it 'ignores', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], na: 123}]) describe 'list operations', -> it 'handles inserts before', -> assert.deepEqual ['key', 10, 3+1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], li: 'meow'}]) assert.deepEqual ['key', 10+1, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10], li: 'meow'}]) it 'handles inserts after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 4], li: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 11], li: 'meow'}]) it 'handles replacements at current point', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], ld: 'meow1', li: 'meow2'}]) assert.deepEqual ['key', 10], type.transformCursor(['key', 10, 3], [{p: ['key', 10], ld: 'meow1', li: 'meow2'}]) # move cursor up tree when parent deleted it 'handles deletes before', -> assert.deepEqual ['key', 10, 3-1], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], ld: 'meow'}]) assert.deepEqual ['key', 10-1, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 9], ld: 'meow'}]) it 'handles deletes after', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 4], ld: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 11], ld: 'meow'}]) it 'handles deletes at current point', -> assert.deepEqual ['key', 10], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], ld: 'meow'}]) assert.deepEqual ['key'], type.transformCursor(['key', 10, 3], [{p: ['key', 10], ld: 'meow'}]) it 'handles movements of current point', -> assert.deepEqual ['key', 10, 20], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 3], lm: 20}]) assert.deepEqual ['key', 20, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10], lm: 20}]) it 'handles movements of other points', -> assert.deepEqual ['key', 10, 2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 1], lm: 20}]) assert.deepEqual ['key', 10, 4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], lm: 3}]) assert.deepEqual ['key', 10, 4], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 5], lm: 1}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 10], lm: 20}]) assert.deepEqual ['key', 10, 2], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], lm: 3}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key', 10, 2], lm: 1}]) describe 'dict operations', -> it 'ignores irrelevant inserts and deletes', -> assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key2'], oi: 'meow'}]) assert.deepEqual ['key', 10, 3], type.transformCursor(['key', 10, 3], [{p: ['key2'], od: 'meow'}]) it 'handles deletes at current point', -> assert.deepEqual [], type.transformCursor(['key', 0, 3], [{p: ['key'], od: ['meow123']}]) assert.deepEqual ['key', 0], type.transformCursor(['key', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['meow123']}]) it 'handles replacements at current point', -> assert.deepEqual ['key'], type.transformCursor(['key', 0, 3], [{p: ['key'], od: ['meow123'], oi: 'newobj'}]) assert.deepEqual ['key', 0, 'key2'], type.transformCursor(['key', 0, 'key2'], [{p: ['key', 0, 'key2'], od: ['mePI:PASSWORD:<PASSWORD>END_PI'], oi: 'newobj'}]) describe 'randomizer', -> @timeout 20000 @slow 6000 it 'passes', -> fuzzer type, require('./json0-generator'), 1000 it 'passes with string subtype', -> type._testStringSubtype = true # hack fuzzer type, require('./json0-generator'), 1000 delete type._testStringSubtype describe 'json', -> describe 'native type', -> genTests nativetype #exports.webclient = genTests require('../helpers/webclient').types.json
[ { "context": "# Droplet Treewalker framework.\n#\n# Copyright (c) Anthony Bau (dab1998@gmail.com)\n# MIT License\nhelper = requir", "end": 61, "score": 0.9998689889907837, "start": 50, "tag": "NAME", "value": "Anthony Bau" }, { "context": "ewalker framework.\n#\n# Copyright (c) Antho...
src/treewalk.coffee
takeratta/droplet
145
# Droplet Treewalker framework. # # Copyright (c) Anthony Bau (dab1998@gmail.com) # MIT License helper = require './helper.coffee' model = require './model.coffee' parser = require './parser.coffee' exports.createTreewalkParser = (parse, config, root) -> class TreewalkParser extends parser.Parser constructor: (@text, @opts = {}) -> super @lines = @text.split '\n' isComment: (text) -> if config?.isComment? return config.isComment(text) else return false parseComment: (text) -> return config.parseComment text markRoot: (context = root) -> parseTree = parse(context, @text) # Parse @mark parseTree, '', 0 guessPrefix: (bounds) -> line = @lines[bounds.start.line + 1] return line[0...line.length - line.trimLeft().length] applyRule: (rule, node) -> if 'string' is typeof rule return {type: rule} else if rule instanceof Function return rule(node) else return rule det: (node) -> if node.type of config.RULES return @applyRule(config.RULES[node.type], node).type return 'block' detNode: (node) -> if node.blockified then 'block' else @det(node) getColor: (node, rules) -> color = config.COLOR_CALLBACK?(@opts, node) if color? return color # Apply the static rules set given in config rulesSet = {} rules.forEach (el) -> rulesSet[el] = true for colorRule in config.COLOR_RULES if colorRule[0] of rulesSet return colorRule[1] return 'comment' getShape: (node, rules) -> shape = config.SHAPE_CALLBACK?(@opts, node) if shape? return shape # Apply the static rules set given in config rulesSet = {} rules.forEach (el) -> rulesSet[el] = true for shapeRule in config.SHAPE_RULES if shapeRule[0] of rulesSet return shapeRule[1] return 'any-drop' mark: (node, prefix, depth, pass, rules, context, wrap, wrapRules) -> unless pass context = node.parent while context? and @detNode(context) in ['skip', 'parens'] context = context.parent rules ?= [] rules = rules.slice 0 rules.push node.type # Pass through to child if single-child if node.children.length is 1 and @detNode(node) isnt 'indent' @mark node.children[0], prefix, depth, true, rules, context, wrap, wrapRules else if node.children.length > 0 switch @detNode node when 'block' if wrap? bounds = wrap.bounds else bounds = node.bounds if context? and @detNode(context) is 'block' @addSocket bounds: bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) @addBlock bounds: bounds depth: depth + 1 color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) when 'parens' # Parens are assumed to wrap the only child that has children child = null; ok = true for el, i in node.children if el.children.length > 0 if child? ok = false break else child = el if ok @mark child, prefix, depth, true, rules, context, wrap ? node, wrapRules ? rules return else node.blockified = true if wrap? bounds = wrap.bounds else bounds = node.bounds if context? and @detNode(context) is 'block' @addSocket bounds: bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) @addBlock bounds: bounds depth: depth + 1 color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) when 'indent' # A lone indent needs to be wrapped in a block. if @det(context) isnt 'block' @addBlock bounds: node.bounds depth: depth color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) depth += 1 start = origin = node.children[0].bounds.start for child, i in node.children if child.children.length > 0 break else unless helper.clipLines(@lines, origin, child.bounds.end).trim().length is 0 or i is node.children.length - 1 start = child.bounds.end end = node.children[node.children.length - 1].bounds.end for child, i in node.children by -1 if child.children.length > 0 end = child.bounds.end break else unless i is 0 end = child.bounds.start if @lines[end.line][...end.column].trim().length is 0 end.line -= 1 end.column = @lines[end.line].length bounds = { start: start end: end } oldPrefix = prefix prefix = @guessPrefix bounds @addIndent bounds: bounds depth: depth prefix: prefix[oldPrefix.length...prefix.length] classes: padRules(wrapRules ? rules) parseContext: @applyRule(config.RULES[node.type], node).indentContext for child in node.children @mark child, prefix, depth + 2, false else if context? and @detNode(context) is 'block' if @det(node) is 'socket' and ((not config.SHOULD_SOCKET?) or config.SHOULD_SOCKET(@opts, node)) @addSocket bounds: node.bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) if config.empty? and not @opts.preserveEmpty and helper.clipLines(@lines, node.bounds.start, node.bounds.end) is config.empty @flagToRemove node.bounds, depth + 1 TreewalkParser.drop = (block, context, pred) -> if context.type is 'socket' if '__comment__' in block.classes return helper.DISCOURAGE for c in parseClasses(context) if c in parseClasses(block) return helper.ENCOURAGE # Check to see if we could paren-wrap this if config.PAREN_RULES? and c of config.PAREN_RULES for m in parseClasses(block) if m of config.PAREN_RULES[c] return helper.ENCOURAGE return helper.DISCOURAGE else if context.type is 'indent' if '__comment__' in block.classes return helper.ENCOURAGE if context.parseContext in parseClasses(block) return helper.ENCOURAGE # Check to see if we could paren-wrap this if config.PAREN_RULES? and context.parseContext of config.PAREN_RULES for m in parseClasses(block) if m of config.PAREN_RULES[context.parseContext] return helper.ENCOURAGE return helper.DISCOURAGE else if context.type is 'document' if '__comment__' in block.classes return helper.ENCOURAGE if context.parseContext in parseClasses(block) return helper.ENCOURAGE return helper.DISCOURAGE return helper.DISCOURAGE # Doesn't yet deal with parens TreewalkParser.parens = (leading, trailing, node, context)-> # If we're moving to null, remove parens (where possible) unless context? if config.unParenWrap? return config.unParenWrap leading, trailing, node, context else return # If we already match types, we're fine for c in parseClasses(context) if c in parseClasses(node) return # Otherwise, wrap according to the provided rule for c in parseClasses(context) when c of config.PAREN_RULES for m in parseClasses(node) when m of config.PAREN_RULES[c] return config.PAREN_RULES[c][m] leading, trailing, node, context TreewalkParser.stringFixer = config.stringFixer TreewalkParser.getDefaultSelectionRange = config.getDefaultSelectionRange TreewalkParser.empty = config.empty TreewalkParser.rootContext = root return TreewalkParser PARSE_PREFIX = "__parse__" padRules = (rules) -> rules.map (x) -> "#{PARSE_PREFIX}#{x}" parseClasses = (node) -> node.classes.filter((x) -> x[...PARSE_PREFIX.length] is PARSE_PREFIX).map((x) -> x[PARSE_PREFIX.length..]).concat(node.parseContext)
179882
# Droplet Treewalker framework. # # Copyright (c) <NAME> (<EMAIL>) # MIT License helper = require './helper.coffee' model = require './model.coffee' parser = require './parser.coffee' exports.createTreewalkParser = (parse, config, root) -> class TreewalkParser extends parser.Parser constructor: (@text, @opts = {}) -> super @lines = @text.split '\n' isComment: (text) -> if config?.isComment? return config.isComment(text) else return false parseComment: (text) -> return config.parseComment text markRoot: (context = root) -> parseTree = parse(context, @text) # Parse @mark parseTree, '', 0 guessPrefix: (bounds) -> line = @lines[bounds.start.line + 1] return line[0...line.length - line.trimLeft().length] applyRule: (rule, node) -> if 'string' is typeof rule return {type: rule} else if rule instanceof Function return rule(node) else return rule det: (node) -> if node.type of config.RULES return @applyRule(config.RULES[node.type], node).type return 'block' detNode: (node) -> if node.blockified then 'block' else @det(node) getColor: (node, rules) -> color = config.COLOR_CALLBACK?(@opts, node) if color? return color # Apply the static rules set given in config rulesSet = {} rules.forEach (el) -> rulesSet[el] = true for colorRule in config.COLOR_RULES if colorRule[0] of rulesSet return colorRule[1] return 'comment' getShape: (node, rules) -> shape = config.SHAPE_CALLBACK?(@opts, node) if shape? return shape # Apply the static rules set given in config rulesSet = {} rules.forEach (el) -> rulesSet[el] = true for shapeRule in config.SHAPE_RULES if shapeRule[0] of rulesSet return shapeRule[1] return 'any-drop' mark: (node, prefix, depth, pass, rules, context, wrap, wrapRules) -> unless pass context = node.parent while context? and @detNode(context) in ['skip', 'parens'] context = context.parent rules ?= [] rules = rules.slice 0 rules.push node.type # Pass through to child if single-child if node.children.length is 1 and @detNode(node) isnt 'indent' @mark node.children[0], prefix, depth, true, rules, context, wrap, wrapRules else if node.children.length > 0 switch @detNode node when 'block' if wrap? bounds = wrap.bounds else bounds = node.bounds if context? and @detNode(context) is 'block' @addSocket bounds: bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) @addBlock bounds: bounds depth: depth + 1 color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) when 'parens' # Parens are assumed to wrap the only child that has children child = null; ok = true for el, i in node.children if el.children.length > 0 if child? ok = false break else child = el if ok @mark child, prefix, depth, true, rules, context, wrap ? node, wrapRules ? rules return else node.blockified = true if wrap? bounds = wrap.bounds else bounds = node.bounds if context? and @detNode(context) is 'block' @addSocket bounds: bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) @addBlock bounds: bounds depth: depth + 1 color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) when 'indent' # A lone indent needs to be wrapped in a block. if @det(context) isnt 'block' @addBlock bounds: node.bounds depth: depth color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) depth += 1 start = origin = node.children[0].bounds.start for child, i in node.children if child.children.length > 0 break else unless helper.clipLines(@lines, origin, child.bounds.end).trim().length is 0 or i is node.children.length - 1 start = child.bounds.end end = node.children[node.children.length - 1].bounds.end for child, i in node.children by -1 if child.children.length > 0 end = child.bounds.end break else unless i is 0 end = child.bounds.start if @lines[end.line][...end.column].trim().length is 0 end.line -= 1 end.column = @lines[end.line].length bounds = { start: start end: end } oldPrefix = prefix prefix = @guessPrefix bounds @addIndent bounds: bounds depth: depth prefix: prefix[oldPrefix.length...prefix.length] classes: padRules(wrapRules ? rules) parseContext: @applyRule(config.RULES[node.type], node).indentContext for child in node.children @mark child, prefix, depth + 2, false else if context? and @detNode(context) is 'block' if @det(node) is 'socket' and ((not config.SHOULD_SOCKET?) or config.SHOULD_SOCKET(@opts, node)) @addSocket bounds: node.bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) if config.empty? and not @opts.preserveEmpty and helper.clipLines(@lines, node.bounds.start, node.bounds.end) is config.empty @flagToRemove node.bounds, depth + 1 TreewalkParser.drop = (block, context, pred) -> if context.type is 'socket' if '__comment__' in block.classes return helper.DISCOURAGE for c in parseClasses(context) if c in parseClasses(block) return helper.ENCOURAGE # Check to see if we could paren-wrap this if config.PAREN_RULES? and c of config.PAREN_RULES for m in parseClasses(block) if m of config.PAREN_RULES[c] return helper.ENCOURAGE return helper.DISCOURAGE else if context.type is 'indent' if '__comment__' in block.classes return helper.ENCOURAGE if context.parseContext in parseClasses(block) return helper.ENCOURAGE # Check to see if we could paren-wrap this if config.PAREN_RULES? and context.parseContext of config.PAREN_RULES for m in parseClasses(block) if m of config.PAREN_RULES[context.parseContext] return helper.ENCOURAGE return helper.DISCOURAGE else if context.type is 'document' if '__comment__' in block.classes return helper.ENCOURAGE if context.parseContext in parseClasses(block) return helper.ENCOURAGE return helper.DISCOURAGE return helper.DISCOURAGE # Doesn't yet deal with parens TreewalkParser.parens = (leading, trailing, node, context)-> # If we're moving to null, remove parens (where possible) unless context? if config.unParenWrap? return config.unParenWrap leading, trailing, node, context else return # If we already match types, we're fine for c in parseClasses(context) if c in parseClasses(node) return # Otherwise, wrap according to the provided rule for c in parseClasses(context) when c of config.PAREN_RULES for m in parseClasses(node) when m of config.PAREN_RULES[c] return config.PAREN_RULES[c][m] leading, trailing, node, context TreewalkParser.stringFixer = config.stringFixer TreewalkParser.getDefaultSelectionRange = config.getDefaultSelectionRange TreewalkParser.empty = config.empty TreewalkParser.rootContext = root return TreewalkParser PARSE_PREFIX = "__parse__" padRules = (rules) -> rules.map (x) -> "#{PARSE_PREFIX}#{x}" parseClasses = (node) -> node.classes.filter((x) -> x[...PARSE_PREFIX.length] is PARSE_PREFIX).map((x) -> x[PARSE_PREFIX.length..]).concat(node.parseContext)
true
# Droplet Treewalker framework. # # Copyright (c) PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # MIT License helper = require './helper.coffee' model = require './model.coffee' parser = require './parser.coffee' exports.createTreewalkParser = (parse, config, root) -> class TreewalkParser extends parser.Parser constructor: (@text, @opts = {}) -> super @lines = @text.split '\n' isComment: (text) -> if config?.isComment? return config.isComment(text) else return false parseComment: (text) -> return config.parseComment text markRoot: (context = root) -> parseTree = parse(context, @text) # Parse @mark parseTree, '', 0 guessPrefix: (bounds) -> line = @lines[bounds.start.line + 1] return line[0...line.length - line.trimLeft().length] applyRule: (rule, node) -> if 'string' is typeof rule return {type: rule} else if rule instanceof Function return rule(node) else return rule det: (node) -> if node.type of config.RULES return @applyRule(config.RULES[node.type], node).type return 'block' detNode: (node) -> if node.blockified then 'block' else @det(node) getColor: (node, rules) -> color = config.COLOR_CALLBACK?(@opts, node) if color? return color # Apply the static rules set given in config rulesSet = {} rules.forEach (el) -> rulesSet[el] = true for colorRule in config.COLOR_RULES if colorRule[0] of rulesSet return colorRule[1] return 'comment' getShape: (node, rules) -> shape = config.SHAPE_CALLBACK?(@opts, node) if shape? return shape # Apply the static rules set given in config rulesSet = {} rules.forEach (el) -> rulesSet[el] = true for shapeRule in config.SHAPE_RULES if shapeRule[0] of rulesSet return shapeRule[1] return 'any-drop' mark: (node, prefix, depth, pass, rules, context, wrap, wrapRules) -> unless pass context = node.parent while context? and @detNode(context) in ['skip', 'parens'] context = context.parent rules ?= [] rules = rules.slice 0 rules.push node.type # Pass through to child if single-child if node.children.length is 1 and @detNode(node) isnt 'indent' @mark node.children[0], prefix, depth, true, rules, context, wrap, wrapRules else if node.children.length > 0 switch @detNode node when 'block' if wrap? bounds = wrap.bounds else bounds = node.bounds if context? and @detNode(context) is 'block' @addSocket bounds: bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) @addBlock bounds: bounds depth: depth + 1 color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) when 'parens' # Parens are assumed to wrap the only child that has children child = null; ok = true for el, i in node.children if el.children.length > 0 if child? ok = false break else child = el if ok @mark child, prefix, depth, true, rules, context, wrap ? node, wrapRules ? rules return else node.blockified = true if wrap? bounds = wrap.bounds else bounds = node.bounds if context? and @detNode(context) is 'block' @addSocket bounds: bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) @addBlock bounds: bounds depth: depth + 1 color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) when 'indent' # A lone indent needs to be wrapped in a block. if @det(context) isnt 'block' @addBlock bounds: node.bounds depth: depth color: @getColor node, rules classes: padRules(wrapRules ? rules).concat(@getShape(node, rules)) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) depth += 1 start = origin = node.children[0].bounds.start for child, i in node.children if child.children.length > 0 break else unless helper.clipLines(@lines, origin, child.bounds.end).trim().length is 0 or i is node.children.length - 1 start = child.bounds.end end = node.children[node.children.length - 1].bounds.end for child, i in node.children by -1 if child.children.length > 0 end = child.bounds.end break else unless i is 0 end = child.bounds.start if @lines[end.line][...end.column].trim().length is 0 end.line -= 1 end.column = @lines[end.line].length bounds = { start: start end: end } oldPrefix = prefix prefix = @guessPrefix bounds @addIndent bounds: bounds depth: depth prefix: prefix[oldPrefix.length...prefix.length] classes: padRules(wrapRules ? rules) parseContext: @applyRule(config.RULES[node.type], node).indentContext for child in node.children @mark child, prefix, depth + 2, false else if context? and @detNode(context) is 'block' if @det(node) is 'socket' and ((not config.SHOULD_SOCKET?) or config.SHOULD_SOCKET(@opts, node)) @addSocket bounds: node.bounds depth: depth classes: padRules(wrapRules ? rules) parseContext: rules[0] #(if wrap? then wrap.type else rules[0]) if config.empty? and not @opts.preserveEmpty and helper.clipLines(@lines, node.bounds.start, node.bounds.end) is config.empty @flagToRemove node.bounds, depth + 1 TreewalkParser.drop = (block, context, pred) -> if context.type is 'socket' if '__comment__' in block.classes return helper.DISCOURAGE for c in parseClasses(context) if c in parseClasses(block) return helper.ENCOURAGE # Check to see if we could paren-wrap this if config.PAREN_RULES? and c of config.PAREN_RULES for m in parseClasses(block) if m of config.PAREN_RULES[c] return helper.ENCOURAGE return helper.DISCOURAGE else if context.type is 'indent' if '__comment__' in block.classes return helper.ENCOURAGE if context.parseContext in parseClasses(block) return helper.ENCOURAGE # Check to see if we could paren-wrap this if config.PAREN_RULES? and context.parseContext of config.PAREN_RULES for m in parseClasses(block) if m of config.PAREN_RULES[context.parseContext] return helper.ENCOURAGE return helper.DISCOURAGE else if context.type is 'document' if '__comment__' in block.classes return helper.ENCOURAGE if context.parseContext in parseClasses(block) return helper.ENCOURAGE return helper.DISCOURAGE return helper.DISCOURAGE # Doesn't yet deal with parens TreewalkParser.parens = (leading, trailing, node, context)-> # If we're moving to null, remove parens (where possible) unless context? if config.unParenWrap? return config.unParenWrap leading, trailing, node, context else return # If we already match types, we're fine for c in parseClasses(context) if c in parseClasses(node) return # Otherwise, wrap according to the provided rule for c in parseClasses(context) when c of config.PAREN_RULES for m in parseClasses(node) when m of config.PAREN_RULES[c] return config.PAREN_RULES[c][m] leading, trailing, node, context TreewalkParser.stringFixer = config.stringFixer TreewalkParser.getDefaultSelectionRange = config.getDefaultSelectionRange TreewalkParser.empty = config.empty TreewalkParser.rootContext = root return TreewalkParser PARSE_PREFIX = "__parse__" padRules = (rules) -> rules.map (x) -> "#{PARSE_PREFIX}#{x}" parseClasses = (node) -> node.classes.filter((x) -> x[...PARSE_PREFIX.length] is PARSE_PREFIX).map((x) -> x[PARSE_PREFIX.length..]).concat(node.parseContext)
[ { "context": "h module 'ui.gravatar'\n element = {}\n\n email = 'sebastian.wallin@gmail.com'\n emailmd5 = '46ab5c60ced85b09c35fd31a510206ef'\n", "end": 139, "score": 0.999932587146759, "start": 113, "tag": "EMAIL", "value": "sebastian.wallin@gmail.com" }, { "context": "($rootScope...
node_modules/angular-gravatar/spec/tests.coffee
timlevett/timlevett.github.io
1
'use strict' describe 'Directive: gravatarSrc', -> beforeEach module 'ui.gravatar' element = {} email = 'sebastian.wallin@gmail.com' emailmd5 = '46ab5c60ced85b09c35fd31a510206ef' $compile = {} gravatarService = {} beforeEach inject (_gravatarService_, _$compile_) -> gravatarService = _gravatarService_ $compile = _$compile_ createElement = (html, scope) -> element = angular.element(html) element = $compile(element) scope scope.$apply() element it 'sets the src attribute with Gravatar URL', inject ($rootScope, $compile) -> $rootScope.email = "test@example.com" element = createElement '<img gravatar-src="email">', $rootScope expect(element.attr('src')).toBeTruthy() it 'sets the src attribute from static src', inject ($rootScope, $compile) -> element = createElement '<img gravatar-src="\'sebastian.wallin@gmail.com\'">', $rootScope expect(element.attr('src')).toContain('46ab5c60ced85b09c35fd31a510206ef') it 'generates a gravatar image for empty src', inject ($rootScope, $compile) -> $rootScope.email = null element = createElement '<img gravatar-src="email">', $rootScope expect(element.attr('src')).toContain('gravatar') it 'does not include the directive name in the gravatar url', inject ($rootScope) -> $rootScope.email = email element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).not.toContain 'src' describe 'when gravatar-src-once is used', -> it 'does not change src when email is changed', inject ($rootScope) -> $rootScope.email = 'diaper.dynamo@example.com' element = createElement('<img gravatar-src-once="email">', $rootScope) srcBefore = element.attr('src') $rootScope.email = 'something.else@example.com' $rootScope.$apply() expect(element.attr('src')).toBe srcBefore it 'does not lock on null', inject ($rootScope) -> element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).toBeUndefined(); $rootScope.email = email $rootScope.$apply() expect(element.attr('src')).toContain(emailmd5) $rootScope.email = 'something.else@example.com' $rootScope.$apply() expect(element.attr('src')).toContain(emailmd5) it 'does not include the directive name in the gravatar url', inject ($rootScope) -> $rootScope.email = email element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).not.toContain 'once' describe 'Service: gravatarService', -> beforeEach module 'ui.gravatar' gravatarService = {} beforeEach inject (_gravatarService_) -> gravatarService = _gravatarService_ email = 'sebastian.wallin@gmail.com' emailmd5 = '46ab5c60ced85b09c35fd31a510206ef' describe '#url:', -> it 'generates an url without parameters to gravatar avatar endpoint', -> url = gravatarService.url(email) expect(url).toBe '//www.gravatar.com/avatar/' + emailmd5 it 'generates an url with provided parameters', -> opts = size: 100 default: 'mm' url = gravatarService.url(email, opts) for k, v of opts expect(url).toContain("#{k}=#{v}") it 'URL encodes options in final URL', -> url = 'http://placekitten.com/100/100' urlEscaped = encodeURIComponent('http://placekitten.com/100/100') opts = default: url expect(gravatarService.url(email, opts)).toMatch(urlEscaped) it 'does not re-encode the source if it is already a lowercase MD5 hash', -> expect(gravatarService.url(emailmd5)).toMatch(emailmd5) it 'does not re-encode the source if it is already an uppercase MD5 hash', -> src = emailmd5.toUpperCase() expect(gravatarService.url(src)).toMatch(src) it 'does not overwrite default options', -> opts = size: 100 url = gravatarService.url(email, opts) url = gravatarService.url(email) expect(url).not.toContain('size')
5941
'use strict' describe 'Directive: gravatarSrc', -> beforeEach module 'ui.gravatar' element = {} email = '<EMAIL>' emailmd5 = '46ab5c60ced85b09c35fd31a510206ef' $compile = {} gravatarService = {} beforeEach inject (_gravatarService_, _$compile_) -> gravatarService = _gravatarService_ $compile = _$compile_ createElement = (html, scope) -> element = angular.element(html) element = $compile(element) scope scope.$apply() element it 'sets the src attribute with Gravatar URL', inject ($rootScope, $compile) -> $rootScope.email = "<EMAIL>" element = createElement '<img gravatar-src="email">', $rootScope expect(element.attr('src')).toBeTruthy() it 'sets the src attribute from static src', inject ($rootScope, $compile) -> element = createElement '<img gravatar-src="\'<EMAIL>\'">', $rootScope expect(element.attr('src')).toContain('46ab5c60ced85b09c35fd31a510206ef') it 'generates a gravatar image for empty src', inject ($rootScope, $compile) -> $rootScope.email = null element = createElement '<img gravatar-src="email">', $rootScope expect(element.attr('src')).toContain('gravatar') it 'does not include the directive name in the gravatar url', inject ($rootScope) -> $rootScope.email = email element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).not.toContain 'src' describe 'when gravatar-src-once is used', -> it 'does not change src when email is changed', inject ($rootScope) -> $rootScope.email = '<EMAIL>' element = createElement('<img gravatar-src-once="email">', $rootScope) srcBefore = element.attr('src') $rootScope.email = '<EMAIL>' $rootScope.$apply() expect(element.attr('src')).toBe srcBefore it 'does not lock on null', inject ($rootScope) -> element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).toBeUndefined(); $rootScope.email = email $rootScope.$apply() expect(element.attr('src')).toContain(emailmd5) $rootScope.email = '<EMAIL>' $rootScope.$apply() expect(element.attr('src')).toContain(emailmd5) it 'does not include the directive name in the gravatar url', inject ($rootScope) -> $rootScope.email = email element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).not.toContain 'once' describe 'Service: gravatarService', -> beforeEach module 'ui.gravatar' gravatarService = {} beforeEach inject (_gravatarService_) -> gravatarService = _gravatarService_ email = '<EMAIL>' emailmd5 = '46ab5c60ced85b09c35fd31a510206ef' describe '#url:', -> it 'generates an url without parameters to gravatar avatar endpoint', -> url = gravatarService.url(email) expect(url).toBe '//www.gravatar.com/avatar/' + emailmd5 it 'generates an url with provided parameters', -> opts = size: 100 default: 'mm' url = gravatarService.url(email, opts) for k, v of opts expect(url).toContain("#{k}=#{v}") it 'URL encodes options in final URL', -> url = 'http://placekitten.com/100/100' urlEscaped = encodeURIComponent('http://placekitten.com/100/100') opts = default: url expect(gravatarService.url(email, opts)).toMatch(urlEscaped) it 'does not re-encode the source if it is already a lowercase MD5 hash', -> expect(gravatarService.url(emailmd5)).toMatch(emailmd5) it 'does not re-encode the source if it is already an uppercase MD5 hash', -> src = emailmd5.toUpperCase() expect(gravatarService.url(src)).toMatch(src) it 'does not overwrite default options', -> opts = size: 100 url = gravatarService.url(email, opts) url = gravatarService.url(email) expect(url).not.toContain('size')
true
'use strict' describe 'Directive: gravatarSrc', -> beforeEach module 'ui.gravatar' element = {} email = 'PI:EMAIL:<EMAIL>END_PI' emailmd5 = '46ab5c60ced85b09c35fd31a510206ef' $compile = {} gravatarService = {} beforeEach inject (_gravatarService_, _$compile_) -> gravatarService = _gravatarService_ $compile = _$compile_ createElement = (html, scope) -> element = angular.element(html) element = $compile(element) scope scope.$apply() element it 'sets the src attribute with Gravatar URL', inject ($rootScope, $compile) -> $rootScope.email = "PI:EMAIL:<EMAIL>END_PI" element = createElement '<img gravatar-src="email">', $rootScope expect(element.attr('src')).toBeTruthy() it 'sets the src attribute from static src', inject ($rootScope, $compile) -> element = createElement '<img gravatar-src="\'PI:EMAIL:<EMAIL>END_PI\'">', $rootScope expect(element.attr('src')).toContain('46ab5c60ced85b09c35fd31a510206ef') it 'generates a gravatar image for empty src', inject ($rootScope, $compile) -> $rootScope.email = null element = createElement '<img gravatar-src="email">', $rootScope expect(element.attr('src')).toContain('gravatar') it 'does not include the directive name in the gravatar url', inject ($rootScope) -> $rootScope.email = email element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).not.toContain 'src' describe 'when gravatar-src-once is used', -> it 'does not change src when email is changed', inject ($rootScope) -> $rootScope.email = 'PI:EMAIL:<EMAIL>END_PI' element = createElement('<img gravatar-src-once="email">', $rootScope) srcBefore = element.attr('src') $rootScope.email = 'PI:EMAIL:<EMAIL>END_PI' $rootScope.$apply() expect(element.attr('src')).toBe srcBefore it 'does not lock on null', inject ($rootScope) -> element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).toBeUndefined(); $rootScope.email = email $rootScope.$apply() expect(element.attr('src')).toContain(emailmd5) $rootScope.email = 'PI:EMAIL:<EMAIL>END_PI' $rootScope.$apply() expect(element.attr('src')).toContain(emailmd5) it 'does not include the directive name in the gravatar url', inject ($rootScope) -> $rootScope.email = email element = createElement('<img gravatar-src-once="email">', $rootScope) expect(element.attr('src')).not.toContain 'once' describe 'Service: gravatarService', -> beforeEach module 'ui.gravatar' gravatarService = {} beforeEach inject (_gravatarService_) -> gravatarService = _gravatarService_ email = 'PI:EMAIL:<EMAIL>END_PI' emailmd5 = '46ab5c60ced85b09c35fd31a510206ef' describe '#url:', -> it 'generates an url without parameters to gravatar avatar endpoint', -> url = gravatarService.url(email) expect(url).toBe '//www.gravatar.com/avatar/' + emailmd5 it 'generates an url with provided parameters', -> opts = size: 100 default: 'mm' url = gravatarService.url(email, opts) for k, v of opts expect(url).toContain("#{k}=#{v}") it 'URL encodes options in final URL', -> url = 'http://placekitten.com/100/100' urlEscaped = encodeURIComponent('http://placekitten.com/100/100') opts = default: url expect(gravatarService.url(email, opts)).toMatch(urlEscaped) it 'does not re-encode the source if it is already a lowercase MD5 hash', -> expect(gravatarService.url(emailmd5)).toMatch(emailmd5) it 'does not re-encode the source if it is already an uppercase MD5 hash', -> src = emailmd5.toUpperCase() expect(gravatarService.url(src)).toMatch(src) it 'does not overwrite default options', -> opts = size: 100 url = gravatarService.url(email, opts) url = gravatarService.url(email) expect(url).not.toContain('size')
[ { "context": "# Copyright (c) 2016-2017 Bennet Carstensen\n#\n# Permission is hereby granted, free of charge,", "end": 43, "score": 0.9998495578765869, "start": 26, "tag": "NAME", "value": "Bennet Carstensen" } ]
spec/linter-opencl-spec.coffee
BenSolus/linter-clcc
0
# Copyright (c) 2016-2017 Bennet Carstensen # # 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. 'use babel' lint = require('../lib/linter-opencl.coffee').provideLinter().lint describe 'The OpenCL build provider for Atom Linter', -> linter = require('../lib/linter-opencl.coffee').provideLinter().lint beforeEach -> waitsForPromise -> atom.config.set('linter-opencl.openCL.platformIndex', 0) # atom.config.set('linter-opencl.openCL.platformIndex', 1) atom.config.set('linter-opencl.debug', true) atom.packages.activatePackage('language-opencl') atom.packages.activatePackage('linter-opencl') return atom.packages.activatePackage("linter-opencl") it 'should be in the packages list', -> expect(atom.packages.isPackageLoaded('linter-opencl')).toBe(true) it 'should be an active package', -> expect(atom.packages.isPackageActive('linter-opencl')).toBe(true) it 'find an catastrophic error in error.cl', -> waitsForPromise -> file = __dirname + '/files/fatal-error.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length).toEqual(1) expect(messages[0].severity).toEqual('error') expect(messages[0].excerpt).toEqual('cannot open source file') it 'find errors and warnings in error.cl', -> waitsForPromise -> atom.config.set('linter-opencl.includePaths', [__dirname + '/spec/files']) file = __dirname + '/files/error.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length) expect(messages.length).toEqual(2) expect(messages[0].severity).toEqual('error') expect(messages[0].excerpt).toEqual('expected a ";"') expect(messages[1].severity).toEqual('warning') expect(messages[1].excerpt).toEqual('variable "a" was declared but ' + 'never') it 'find no error in correct.cl', -> waitsForPromise -> file = __dirname + '/files/correct.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length).toEqual(0)
152107
# Copyright (c) 2016-2017 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'use babel' lint = require('../lib/linter-opencl.coffee').provideLinter().lint describe 'The OpenCL build provider for Atom Linter', -> linter = require('../lib/linter-opencl.coffee').provideLinter().lint beforeEach -> waitsForPromise -> atom.config.set('linter-opencl.openCL.platformIndex', 0) # atom.config.set('linter-opencl.openCL.platformIndex', 1) atom.config.set('linter-opencl.debug', true) atom.packages.activatePackage('language-opencl') atom.packages.activatePackage('linter-opencl') return atom.packages.activatePackage("linter-opencl") it 'should be in the packages list', -> expect(atom.packages.isPackageLoaded('linter-opencl')).toBe(true) it 'should be an active package', -> expect(atom.packages.isPackageActive('linter-opencl')).toBe(true) it 'find an catastrophic error in error.cl', -> waitsForPromise -> file = __dirname + '/files/fatal-error.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length).toEqual(1) expect(messages[0].severity).toEqual('error') expect(messages[0].excerpt).toEqual('cannot open source file') it 'find errors and warnings in error.cl', -> waitsForPromise -> atom.config.set('linter-opencl.includePaths', [__dirname + '/spec/files']) file = __dirname + '/files/error.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length) expect(messages.length).toEqual(2) expect(messages[0].severity).toEqual('error') expect(messages[0].excerpt).toEqual('expected a ";"') expect(messages[1].severity).toEqual('warning') expect(messages[1].excerpt).toEqual('variable "a" was declared but ' + 'never') it 'find no error in correct.cl', -> waitsForPromise -> file = __dirname + '/files/correct.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length).toEqual(0)
true
# Copyright (c) 2016-2017 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'use babel' lint = require('../lib/linter-opencl.coffee').provideLinter().lint describe 'The OpenCL build provider for Atom Linter', -> linter = require('../lib/linter-opencl.coffee').provideLinter().lint beforeEach -> waitsForPromise -> atom.config.set('linter-opencl.openCL.platformIndex', 0) # atom.config.set('linter-opencl.openCL.platformIndex', 1) atom.config.set('linter-opencl.debug', true) atom.packages.activatePackage('language-opencl') atom.packages.activatePackage('linter-opencl') return atom.packages.activatePackage("linter-opencl") it 'should be in the packages list', -> expect(atom.packages.isPackageLoaded('linter-opencl')).toBe(true) it 'should be an active package', -> expect(atom.packages.isPackageActive('linter-opencl')).toBe(true) it 'find an catastrophic error in error.cl', -> waitsForPromise -> file = __dirname + '/files/fatal-error.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length).toEqual(1) expect(messages[0].severity).toEqual('error') expect(messages[0].excerpt).toEqual('cannot open source file') it 'find errors and warnings in error.cl', -> waitsForPromise -> atom.config.set('linter-opencl.includePaths', [__dirname + '/spec/files']) file = __dirname + '/files/error.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length) expect(messages.length).toEqual(2) expect(messages[0].severity).toEqual('error') expect(messages[0].excerpt).toEqual('expected a ";"') expect(messages[1].severity).toEqual('warning') expect(messages[1].excerpt).toEqual('variable "a" was declared but ' + 'never') it 'find no error in correct.cl', -> waitsForPromise -> file = __dirname + '/files/correct.cl' expect(file).toExistOnDisk() atom.workspace.open(file).then((editor) -> lint(editor)).then (messages) -> expect(messages.length).toEqual(0)
[ { "context": "class CreateImage\r\n @name = \"CreateImage\"\r\n\r\n constructor: () ->\r\n # BITMAP", "end": 38, "score": 0.7626983523368835, "start": 32, "tag": "NAME", "value": "Create" } ]
src/CreateImg.coffee
tanaikech/CreateImg
2
class CreateImage @name = "CreateImage" constructor: () -> # BITMAPFILEHEADER @bfType = iniAr2f.call @ @bfSize = iniAr4f.call @ @bfReserved1 = iniAr2f.call @ @bfReserved2 = iniAr2f.call @ @bfOffBits = iniAr4f.call @ # BITMAPINFOHEADER @bcSize = iniAr4f.call @ @bcWidth = iniAr4f.call @ @bcHeight = iniAr4f.call @ @bcPlanes = iniAr2f.call @ @bcBitCount = iniAr2f.call @ @biCompression = iniAr4f.call @ @biSizeImage = iniAr4f.call @ @biXPelsPerMeter = iniAr4f.call @ @biYPelsPerMeter = iniAr4f.call @ @biClrUsed = iniAr4f.call @ @biClrImportant = iniAr4f.call @ # RGBQUAD @colorpallets = [] # DATA @data = [] Do: (data, colors, wsize, hsize, filename, ext) -> return createImage.call @, @makeData(data, colors, wsize, hsize), filename, if ext == "bmp" then "image/bmp" else if ext == "gif" then "image/gif" else if ext == "jpg" then "image/jpeg" else if ext == "png" then "image/png" else "image/png" makeData: (data, colors, wsize, hsize) -> @bfType = [66, 77] @bcSize = convByteSlice.call @, 40, 4 @bcWidth = convByteSlice.call @, wsize, 4 @bcHeight = convByteSlice.call @, hsize, 4 @bcPlanes = convByteSlice.call @, 1, 2 @bcBitCount = convByteSlice.call @, 8, 2 @biXPelsPerMeter = convByteSlice.call @, 1, 4 @biYPelsPerMeter = convByteSlice.call @, 1, 4 for e in colors @colorpallets.push([ (convByteSlice.call @, e[2], 1)[0], (convByteSlice.call @, e[1], 1)[0], (convByteSlice.call @, e[0], 1)[0], 0 ]) addData.call @, data size_headers = 54 + @colorpallets.length * 4 size_image = data.length @bfOffBits = convByteSlice.call @, size_headers, 4 @biSizeImage = convByteSlice.call @, size_image, 4 @bfSize = convByteSlice.call @, size_headers + size_image, 4 BITMAPFILEHEADER = [this.bfType, this.bfSize, this.bfReserved1, this.bfReserved2, this.bfOffBits] BITMAPINFOHEADER = [this.bcSize, this.bcWidth, this.bcHeight, this.bcPlanes, this.bcBitCount, this.biCompression, this.biSizeImage, this.biXPelsPerMeter, this.biYPelsPerMeter, this.biClrUsed, this.biClrImportant] RGBQUAD = this.colorpallets ar = BITMAPFILEHEADER.concat(BITMAPINFOHEADER).concat(RGBQUAD).concat(this.data) return Array.prototype.concat.apply([], ar) createImage = (bytear, filename, mimetype) -> blob = Utilities.newBlob(bytear, "image/bmp", filename).getAs(mimetype) try id = DriveApp.createFile(blob).getId() catch e throw new Error "Error: Couldn't create image file. I'm sorry. Please check your data again." return id addData = (d) -> this.data.push((convByteSlice.call @, e, 1)[0] for e in d) convByteSlice = (number, b) -> ar1 = [] ar2 = [] ar1 = parseInt(number, 10).toString(16) if ar1.length % 2 isnt 0 ar1 = "0" + ar1 for i in [0..ar1.length - 1] by 2 t1 = (Array(2).join('0') + ar1.substr(i, 2)).slice(-2) ta1 = t1.slice(0,1) ta2 = t1.slice(1,2) tb1 = (Array(4).join('0') + parseInt(ta1, 16).toString(2)).slice(-4) tb2 = (Array(4).join('0') + parseInt(ta2, 16).toString(2)).slice(-4) ar2.push(tb1 + tb2) for i, e of ar2 if parseInt(e.slice(0,1)) == 1 temp = "" for j in [0..e.length - 1] tempn = 0 if parseInt(e.substr(j, 1)) == 0 tempn = 1 temp += tempn res = -1 * parseInt(parseInt((Array(8).join('0') + parseInt(parseInt(parseInt(temp, 2).toString(10), 10) + 1, 10).toString(2)).slice(-8), 2).toString(10), 10) else res = parseInt(parseInt(e, 2).toString(10), 10) ar2[i] = res try res = ar2.reverse().concat(Array.apply(null, Array(b - ar2.length)).map(-> return 0)) catch e throw new Error "Error: Value is over 255. Value has to be less than 255 which is the colow index. Please check again." return res iniAr2f = () -> return new Array(0,0) iniAr4f = () -> return new Array(0,0,0,0) mandelbrot = (size) -> if size % 4 isnt 0 size = size + 4 - (size % 4) r = sh: 3.0, sw: 2.0, sa: 20, size: size results = [] for j in [0..r.size - 1] for i in [0..r.size - 1] xx = 0.0 yy = 0.0 d = true for k in [0..r.sa - 1] xx1 = (Math.pow(xx, 2) - Math.pow(yy, 2)) - r.sh / 2 + (2.0 / r.size * i) yy1 = (2 * xx * yy) - r.sw / 2 + (2.0 / r.size * j) xx = xx1 yy = yy1 if Math.pow(xx, 2) + Math.pow(yy, 2) > 4 d = false break results.push(if d then 1 else 0) return results
42287
class CreateImage @name = "<NAME>Image" constructor: () -> # BITMAPFILEHEADER @bfType = iniAr2f.call @ @bfSize = iniAr4f.call @ @bfReserved1 = iniAr2f.call @ @bfReserved2 = iniAr2f.call @ @bfOffBits = iniAr4f.call @ # BITMAPINFOHEADER @bcSize = iniAr4f.call @ @bcWidth = iniAr4f.call @ @bcHeight = iniAr4f.call @ @bcPlanes = iniAr2f.call @ @bcBitCount = iniAr2f.call @ @biCompression = iniAr4f.call @ @biSizeImage = iniAr4f.call @ @biXPelsPerMeter = iniAr4f.call @ @biYPelsPerMeter = iniAr4f.call @ @biClrUsed = iniAr4f.call @ @biClrImportant = iniAr4f.call @ # RGBQUAD @colorpallets = [] # DATA @data = [] Do: (data, colors, wsize, hsize, filename, ext) -> return createImage.call @, @makeData(data, colors, wsize, hsize), filename, if ext == "bmp" then "image/bmp" else if ext == "gif" then "image/gif" else if ext == "jpg" then "image/jpeg" else if ext == "png" then "image/png" else "image/png" makeData: (data, colors, wsize, hsize) -> @bfType = [66, 77] @bcSize = convByteSlice.call @, 40, 4 @bcWidth = convByteSlice.call @, wsize, 4 @bcHeight = convByteSlice.call @, hsize, 4 @bcPlanes = convByteSlice.call @, 1, 2 @bcBitCount = convByteSlice.call @, 8, 2 @biXPelsPerMeter = convByteSlice.call @, 1, 4 @biYPelsPerMeter = convByteSlice.call @, 1, 4 for e in colors @colorpallets.push([ (convByteSlice.call @, e[2], 1)[0], (convByteSlice.call @, e[1], 1)[0], (convByteSlice.call @, e[0], 1)[0], 0 ]) addData.call @, data size_headers = 54 + @colorpallets.length * 4 size_image = data.length @bfOffBits = convByteSlice.call @, size_headers, 4 @biSizeImage = convByteSlice.call @, size_image, 4 @bfSize = convByteSlice.call @, size_headers + size_image, 4 BITMAPFILEHEADER = [this.bfType, this.bfSize, this.bfReserved1, this.bfReserved2, this.bfOffBits] BITMAPINFOHEADER = [this.bcSize, this.bcWidth, this.bcHeight, this.bcPlanes, this.bcBitCount, this.biCompression, this.biSizeImage, this.biXPelsPerMeter, this.biYPelsPerMeter, this.biClrUsed, this.biClrImportant] RGBQUAD = this.colorpallets ar = BITMAPFILEHEADER.concat(BITMAPINFOHEADER).concat(RGBQUAD).concat(this.data) return Array.prototype.concat.apply([], ar) createImage = (bytear, filename, mimetype) -> blob = Utilities.newBlob(bytear, "image/bmp", filename).getAs(mimetype) try id = DriveApp.createFile(blob).getId() catch e throw new Error "Error: Couldn't create image file. I'm sorry. Please check your data again." return id addData = (d) -> this.data.push((convByteSlice.call @, e, 1)[0] for e in d) convByteSlice = (number, b) -> ar1 = [] ar2 = [] ar1 = parseInt(number, 10).toString(16) if ar1.length % 2 isnt 0 ar1 = "0" + ar1 for i in [0..ar1.length - 1] by 2 t1 = (Array(2).join('0') + ar1.substr(i, 2)).slice(-2) ta1 = t1.slice(0,1) ta2 = t1.slice(1,2) tb1 = (Array(4).join('0') + parseInt(ta1, 16).toString(2)).slice(-4) tb2 = (Array(4).join('0') + parseInt(ta2, 16).toString(2)).slice(-4) ar2.push(tb1 + tb2) for i, e of ar2 if parseInt(e.slice(0,1)) == 1 temp = "" for j in [0..e.length - 1] tempn = 0 if parseInt(e.substr(j, 1)) == 0 tempn = 1 temp += tempn res = -1 * parseInt(parseInt((Array(8).join('0') + parseInt(parseInt(parseInt(temp, 2).toString(10), 10) + 1, 10).toString(2)).slice(-8), 2).toString(10), 10) else res = parseInt(parseInt(e, 2).toString(10), 10) ar2[i] = res try res = ar2.reverse().concat(Array.apply(null, Array(b - ar2.length)).map(-> return 0)) catch e throw new Error "Error: Value is over 255. Value has to be less than 255 which is the colow index. Please check again." return res iniAr2f = () -> return new Array(0,0) iniAr4f = () -> return new Array(0,0,0,0) mandelbrot = (size) -> if size % 4 isnt 0 size = size + 4 - (size % 4) r = sh: 3.0, sw: 2.0, sa: 20, size: size results = [] for j in [0..r.size - 1] for i in [0..r.size - 1] xx = 0.0 yy = 0.0 d = true for k in [0..r.sa - 1] xx1 = (Math.pow(xx, 2) - Math.pow(yy, 2)) - r.sh / 2 + (2.0 / r.size * i) yy1 = (2 * xx * yy) - r.sw / 2 + (2.0 / r.size * j) xx = xx1 yy = yy1 if Math.pow(xx, 2) + Math.pow(yy, 2) > 4 d = false break results.push(if d then 1 else 0) return results
true
class CreateImage @name = "PI:NAME:<NAME>END_PIImage" constructor: () -> # BITMAPFILEHEADER @bfType = iniAr2f.call @ @bfSize = iniAr4f.call @ @bfReserved1 = iniAr2f.call @ @bfReserved2 = iniAr2f.call @ @bfOffBits = iniAr4f.call @ # BITMAPINFOHEADER @bcSize = iniAr4f.call @ @bcWidth = iniAr4f.call @ @bcHeight = iniAr4f.call @ @bcPlanes = iniAr2f.call @ @bcBitCount = iniAr2f.call @ @biCompression = iniAr4f.call @ @biSizeImage = iniAr4f.call @ @biXPelsPerMeter = iniAr4f.call @ @biYPelsPerMeter = iniAr4f.call @ @biClrUsed = iniAr4f.call @ @biClrImportant = iniAr4f.call @ # RGBQUAD @colorpallets = [] # DATA @data = [] Do: (data, colors, wsize, hsize, filename, ext) -> return createImage.call @, @makeData(data, colors, wsize, hsize), filename, if ext == "bmp" then "image/bmp" else if ext == "gif" then "image/gif" else if ext == "jpg" then "image/jpeg" else if ext == "png" then "image/png" else "image/png" makeData: (data, colors, wsize, hsize) -> @bfType = [66, 77] @bcSize = convByteSlice.call @, 40, 4 @bcWidth = convByteSlice.call @, wsize, 4 @bcHeight = convByteSlice.call @, hsize, 4 @bcPlanes = convByteSlice.call @, 1, 2 @bcBitCount = convByteSlice.call @, 8, 2 @biXPelsPerMeter = convByteSlice.call @, 1, 4 @biYPelsPerMeter = convByteSlice.call @, 1, 4 for e in colors @colorpallets.push([ (convByteSlice.call @, e[2], 1)[0], (convByteSlice.call @, e[1], 1)[0], (convByteSlice.call @, e[0], 1)[0], 0 ]) addData.call @, data size_headers = 54 + @colorpallets.length * 4 size_image = data.length @bfOffBits = convByteSlice.call @, size_headers, 4 @biSizeImage = convByteSlice.call @, size_image, 4 @bfSize = convByteSlice.call @, size_headers + size_image, 4 BITMAPFILEHEADER = [this.bfType, this.bfSize, this.bfReserved1, this.bfReserved2, this.bfOffBits] BITMAPINFOHEADER = [this.bcSize, this.bcWidth, this.bcHeight, this.bcPlanes, this.bcBitCount, this.biCompression, this.biSizeImage, this.biXPelsPerMeter, this.biYPelsPerMeter, this.biClrUsed, this.biClrImportant] RGBQUAD = this.colorpallets ar = BITMAPFILEHEADER.concat(BITMAPINFOHEADER).concat(RGBQUAD).concat(this.data) return Array.prototype.concat.apply([], ar) createImage = (bytear, filename, mimetype) -> blob = Utilities.newBlob(bytear, "image/bmp", filename).getAs(mimetype) try id = DriveApp.createFile(blob).getId() catch e throw new Error "Error: Couldn't create image file. I'm sorry. Please check your data again." return id addData = (d) -> this.data.push((convByteSlice.call @, e, 1)[0] for e in d) convByteSlice = (number, b) -> ar1 = [] ar2 = [] ar1 = parseInt(number, 10).toString(16) if ar1.length % 2 isnt 0 ar1 = "0" + ar1 for i in [0..ar1.length - 1] by 2 t1 = (Array(2).join('0') + ar1.substr(i, 2)).slice(-2) ta1 = t1.slice(0,1) ta2 = t1.slice(1,2) tb1 = (Array(4).join('0') + parseInt(ta1, 16).toString(2)).slice(-4) tb2 = (Array(4).join('0') + parseInt(ta2, 16).toString(2)).slice(-4) ar2.push(tb1 + tb2) for i, e of ar2 if parseInt(e.slice(0,1)) == 1 temp = "" for j in [0..e.length - 1] tempn = 0 if parseInt(e.substr(j, 1)) == 0 tempn = 1 temp += tempn res = -1 * parseInt(parseInt((Array(8).join('0') + parseInt(parseInt(parseInt(temp, 2).toString(10), 10) + 1, 10).toString(2)).slice(-8), 2).toString(10), 10) else res = parseInt(parseInt(e, 2).toString(10), 10) ar2[i] = res try res = ar2.reverse().concat(Array.apply(null, Array(b - ar2.length)).map(-> return 0)) catch e throw new Error "Error: Value is over 255. Value has to be less than 255 which is the colow index. Please check again." return res iniAr2f = () -> return new Array(0,0) iniAr4f = () -> return new Array(0,0,0,0) mandelbrot = (size) -> if size % 4 isnt 0 size = size + 4 - (size % 4) r = sh: 3.0, sw: 2.0, sa: 20, size: size results = [] for j in [0..r.size - 1] for i in [0..r.size - 1] xx = 0.0 yy = 0.0 d = true for k in [0..r.sa - 1] xx1 = (Math.pow(xx, 2) - Math.pow(yy, 2)) - r.sh / 2 + (2.0 / r.size * i) yy1 = (2 * xx * yy) - r.sw / 2 + (2.0 / r.size * j) xx = xx1 yy = yy1 if Math.pow(xx, 2) + Math.pow(yy, 2) > 4 d = false break results.push(if d then 1 else 0) return results
[ { "context": "es[\"names\"])\n expect(items).toContain({\"name\":\"Jacob\"})\n expect(items).toContain({\"name\":\"Isabella\"", "end": 521, "score": 0.9985795021057129, "start": 516, "tag": "NAME", "value": "Jacob" }, { "context": "e\":\"Jacob\"})\n expect(items).toContain({...
spec/javascripts/default_callbacks.spec.coffee
GerHobbelt/At.js
0
$inputor = null app = null describe "default callbacks", -> callbacks = null text = null beforeEach -> loadFixtures("inputors.html") $inputor = $("#inputor").atwho at: "@", data: fixtures["names"] app = getAppOf $inputor beforeEach -> text = $.trim $inputor.text() callbacks = $.fn.atwho.default.callbacks app = $inputor.data("atwho") it "refactor the data before save", -> items = callbacks.before_save.call(app, fixtures["names"]) expect(items).toContain({"name":"Jacob"}) expect(items).toContain({"name":"Isabella"}) it "should match the key word following @", -> query = callbacks.matcher.call(app, "@", text) expect(query).toBe("Jobs") it "can filter data", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.filter.call(app, "jo", names, "name") expect(names).toContain name: "Joshua" it "request data from remote by ajax if set remote_filter", -> remote_call = jasmine.createSpy("remote_call") $inputor.atwho at: "@" data: null, callbacks: remote_filter: remote_call simulateTypingIn $inputor expect(remote_call).toHaveBeenCalled() it "can sort the data", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.sorter.call(app, "e", names, "name") expect(names[0].name).toBe 'Ethan' it "don't sort the data without a query", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.sorter.call(app, "", names, "name") expect(names[0]).toEqual({ name : 'Jacob' }) it "can eval temple", -> map = {name: "username", nick: "nick_name"} tpl = '<li data-value="${name}">${nick}</li>' html = '<li data-value="username">nick_name</li>' result = callbacks.tpl_eval.call(app, tpl, map) expect(result).toBe(html) it "can highlight the query", -> html = '<li data-value="username">Ethan</li>' highlighted = callbacks.highlighter.call(app, html, "e") result = '<li data-value="username"> <strong>E</strong>than </li>' expect(highlighted).toBe(result) it "can insert the text which be choosed", -> spyOn(callbacks, "before_insert").and.callThrough() triggerAtwhoAt $inputor expect(callbacks.before_insert).toHaveBeenCalled() it "can adjust offset before reposition", -> before_reposition = jasmine.createSpy("before_reposition") $inputor.atwho at: "@" data: null, callbacks: remote_filter: before_reposition simulateTypingIn $inputor expect(before_reposition).toHaveBeenCalled()
625
$inputor = null app = null describe "default callbacks", -> callbacks = null text = null beforeEach -> loadFixtures("inputors.html") $inputor = $("#inputor").atwho at: "@", data: fixtures["names"] app = getAppOf $inputor beforeEach -> text = $.trim $inputor.text() callbacks = $.fn.atwho.default.callbacks app = $inputor.data("atwho") it "refactor the data before save", -> items = callbacks.before_save.call(app, fixtures["names"]) expect(items).toContain({"name":"<NAME>"}) expect(items).toContain({"name":"<NAME>"}) it "should match the key word following @", -> query = callbacks.matcher.call(app, "@", text) expect(query).toBe("Jobs") it "can filter data", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.filter.call(app, "jo", names, "name") expect(names).toContain name: "<NAME>" it "request data from remote by ajax if set remote_filter", -> remote_call = jasmine.createSpy("remote_call") $inputor.atwho at: "@" data: null, callbacks: remote_filter: remote_call simulateTypingIn $inputor expect(remote_call).toHaveBeenCalled() it "can sort the data", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.sorter.call(app, "e", names, "name") expect(names[0].name).toBe '<NAME>' it "don't sort the data without a query", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.sorter.call(app, "", names, "name") expect(names[0]).toEqual({ name : '<NAME>' }) it "can eval temple", -> map = {name: "username", nick: "nick_name"} tpl = '<li data-value="${name}">${nick}</li>' html = '<li data-value="username">nick_name</li>' result = callbacks.tpl_eval.call(app, tpl, map) expect(result).toBe(html) it "can highlight the query", -> html = '<li data-value="username"><NAME></li>' highlighted = callbacks.highlighter.call(app, html, "e") result = '<li data-value="username"> <strong><NAME></strong><NAME> </li>' expect(highlighted).toBe(result) it "can insert the text which be choosed", -> spyOn(callbacks, "before_insert").and.callThrough() triggerAtwhoAt $inputor expect(callbacks.before_insert).toHaveBeenCalled() it "can adjust offset before reposition", -> before_reposition = jasmine.createSpy("before_reposition") $inputor.atwho at: "@" data: null, callbacks: remote_filter: before_reposition simulateTypingIn $inputor expect(before_reposition).toHaveBeenCalled()
true
$inputor = null app = null describe "default callbacks", -> callbacks = null text = null beforeEach -> loadFixtures("inputors.html") $inputor = $("#inputor").atwho at: "@", data: fixtures["names"] app = getAppOf $inputor beforeEach -> text = $.trim $inputor.text() callbacks = $.fn.atwho.default.callbacks app = $inputor.data("atwho") it "refactor the data before save", -> items = callbacks.before_save.call(app, fixtures["names"]) expect(items).toContain({"name":"PI:NAME:<NAME>END_PI"}) expect(items).toContain({"name":"PI:NAME:<NAME>END_PI"}) it "should match the key word following @", -> query = callbacks.matcher.call(app, "@", text) expect(query).toBe("Jobs") it "can filter data", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.filter.call(app, "jo", names, "name") expect(names).toContain name: "PI:NAME:<NAME>END_PI" it "request data from remote by ajax if set remote_filter", -> remote_call = jasmine.createSpy("remote_call") $inputor.atwho at: "@" data: null, callbacks: remote_filter: remote_call simulateTypingIn $inputor expect(remote_call).toHaveBeenCalled() it "can sort the data", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.sorter.call(app, "e", names, "name") expect(names[0].name).toBe 'PI:NAME:<NAME>END_PI' it "don't sort the data without a query", -> names = callbacks.before_save.call(app, fixtures["names"]) names = callbacks.sorter.call(app, "", names, "name") expect(names[0]).toEqual({ name : 'PI:NAME:<NAME>END_PI' }) it "can eval temple", -> map = {name: "username", nick: "nick_name"} tpl = '<li data-value="${name}">${nick}</li>' html = '<li data-value="username">nick_name</li>' result = callbacks.tpl_eval.call(app, tpl, map) expect(result).toBe(html) it "can highlight the query", -> html = '<li data-value="username">PI:NAME:<NAME>END_PI</li>' highlighted = callbacks.highlighter.call(app, html, "e") result = '<li data-value="username"> <strong>PI:NAME:<NAME>END_PI</strong>PI:NAME:<NAME>END_PI </li>' expect(highlighted).toBe(result) it "can insert the text which be choosed", -> spyOn(callbacks, "before_insert").and.callThrough() triggerAtwhoAt $inputor expect(callbacks.before_insert).toHaveBeenCalled() it "can adjust offset before reposition", -> before_reposition = jasmine.createSpy("before_reposition") $inputor.atwho at: "@" data: null, callbacks: remote_filter: before_reposition simulateTypingIn $inputor expect(before_reposition).toHaveBeenCalled()
[ { "context": "addTo(@map).bringToBack()\n if boundaryName is \"Shehias\"\n @$(\"#shehiaOptions\").show()\n if @sheh", "end": 11017, "score": 0.9914600253105164, "start": 11010, "tag": "NAME", "value": "Shehias" }, { "context": " \"\n div\n\n legend.addTo(@map)\n...
_attachments/app/views/MapView.coffee
jongoz/coconut-analytice
3
_ = require "underscore" $ = require "jquery" Backbone = require "backbone" Case = require '../models/Case' DateSelectorView = require '../views/DateSelectorView' Backbone.$ = $ require('leaflet') global.CenterOfPolygon = require 'polylabel' #require('leaflet.heat') HTMLHelpers = require '../HTMLHelpers' dasherize = require 'underscore.string/dasherize' class MapView extends Backbone.View events: => "change .changeBoundary":"changeBoundary" "change #showLabels":"showLabels" "change .changeTileSet":"changeTiles" "change #showSprayedShehias":"showSprayedShehias" "change #showFociClassifications":"toggleFociClassifications" "click #zoomPemba":"zoomPemba" "click #zoomUnguja":"zoomUnguja" zoom: (target) => target = target.toUpperCase() @map.fitBounds switch target when "UNGUJA" [ [-6.489983,39.130554] [-5.714380,39.633179] ] when "PEMBA" [ [-5.506640,39.549065] [-4.858022,39.889984] ] zoomPemba: => @zoom "PEMBA" zoomUnguja: => @zoom "UNGUJA" showSprayedShehias: => if @$('#showSprayedShehias').is(":checked") @$(".sprayed-shehia").css("fill","lightgreen") else @$(".sprayed-shehia").css("fill","") toggleFociClassifications: => if @$('#showFociClassifications').is(":checked") @showFociClassifications() else @$(".sprayed-shehia").css("fill","") showFociClassifications: => @$(".shehia-cleared").css("fill","green") @$(".shehia-residual-non-active").css("fill","yellow") @$(".shehia-active").css("fill","red") changeTiles: => @showTileSet @$('input[name=tileSet]:checked').val() changeBoundary: => @showBoundary @$('input[name=boundary]:checked').val() showLabels: => if @$('#showLabels').is(":checked") @addLabels @$('input[name=boundary]:checked').val() else @removeLabels() render: => @initialBoundary or= "Districts" @initialTileSet or= "None" @$el.html " <style> .map-marker-labels{ white-space:nowrap; color: black; font-size: 1em; } .labels-District{ font-size: 2em; } .boundary{ color: black; fill: white; stroke-width: 0.5; stroke: black; fill-opacity: 1; } .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .legend { line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; } .legend .circle { border-radius: 50%; width: 10px; height: 10px; margin-top: 3.6px; border: 0.3px black solid; } #mapElement{ width: 100%; height: 95%; position: relative; background-color: #e6ffff; } .label{ font-size: 1em } .leaflet-control-scale-line{ border-color:#b0b0b0; color:#b0b0b0; } .controls .controlBox{ padding-top: 15px; padding-bottom: 10px; border: 1px solid black; } </style> <div class='mdl-grid' style='height:100%'> <div class='mdl-cell mdl-cell--12-col' style='height:100%'> <div class='controls' style='float:right'> <span class='controlBox' id='shehiaOptions' style='display:none;'> <input class='showSprayedShehias' id='showSprayedShehias' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showSprayedShehias' class='label'>Sprayed Shehias</label> <div id='showFociClassificationsOptions'> <input class='showFociClassifications' id='showFociClassifications' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showFociClassifications' class='label'>Foci Classifications</label> </div> </span> <span class='controlBox'> #{ (for boundary in [ "Districts", "Shehias", "Villages"] " <input class='changeBoundary' id='select-boundary-#{boundary}' style='display:none; margin-left:10px' type='radio' value='#{boundary}' name='boundary' #{if boundary is @initialBoundary then 'checked' else ''}></input> <span id='loading-boundary-#{boundary}'>Loading...</span> <label for='select-boundary-#{boundary}' class='label'>#{boundary}</label> " ).join("") } </span> <span class='controlBox'> #{ (for tileSet in [ "None", "RoadsBuildings", "Satellite"] " <input class='changeTileSet' id='select-tileSet-#{tileSet}' style='margin-left:10px' type='radio' value='#{tileSet}' name='tileSet' #{if tileSet is @initialTileSet then 'checked' else ''}></input> <label for='select-tileSet-#{tileSet}' class='label'>#{tileSet}</label> " ).join("") } </span> <span class='controlBox labels' style='padding-right: 10px'> <input id='showLabels' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showLabels' class='label'>Labels</label> </span> </div> <div id='date-selector'></div> <div id='mapElement'></div> </div> </div> " @map = L.map @$('#mapElement')[0], zoomSnap: 0.2 .fitBounds [ [-4.8587000, 39.8772333], [-6.4917667, 39.0945000] ] unless @dontShowCases @createMapLegend() if @casesWithKeyIndicators @addCasesToMap(@casesWithKeyIndicators) else @getCases() @createZoomUngujaPemba() promiseWhenBoundariesAreLoaded = @getBoundariesAndLabels load: @initialBoundary @initializeTileSets() L.control.scale().addTo(@map) promiseWhenBoundariesAreLoaded initializeTileSets: => @tilesets = None: null RoadsBuildings: layer: openStreetMapDefault = L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' Satellite: layer: satellite = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }) #streets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'] }) #outdoors = L.tileLayer('https://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', { maxZoom: 20,subdomains:['mt0','mt1','mt2','mt3'] }) showTileSet: (tileSetName) => if @activeTileSet @activeTileSet.removeFrom(@map) if tileSetName is "None" @activeTileSet = null @$(".boundary").css("fill-opacity", 1) else @activeTileSet = @tilesets[tileSetName].layer @activeTileSet.addTo(@map).bringToBack() @$(".boundary").css("fill-opacity", 0) getBoundariesAndLabels: (options) => @boundaries = Districts: labelsDocName: 'DistrictsCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "District_N" Villages: labelsDocName: 'VillageCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "Vil_Mtaa_N" Shehias: labelsDocName: 'ShehiaCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "Shehia_Nam" for boundaryName, properties of @boundaries loadFeatureData = (feature, layer) => if boundaryName is "Shehias" shehiaNameFromBoundary = feature.properties["Shehia_Nam"].toUpperCase() # Creating this so that we can compare DHIS2 shehias with the GIS boundaries @shehiasWithBoundaries or= [] @shehiasWithBoundaries.push shehiaNameFromBoundary if _(@sprayedShehias).contains shehiaNameFromBoundary layer.setStyle className: "boundary sprayed-shehia" if @shehiaClassifications for classification in [ "Cleared" "Residual non-active" "Active" ] if _(@shehiaClassifications[classification]).contains shehiaNameFromBoundary layer.setStyle className: "boundary shehia#{dasherize(classification)}" # Would be better to find the one with the largest area, but most vertices is close enough, easy and fast # Would also be better to save these into the geoJSON as a feature property but it seems fast enough polygonWithTheMostVertices = _(layer.feature.geometry.coordinates).max (polygon) => polygon.length #console.log polygonWithTheMostVertices labelPosition = CenterOfPolygon(polygonWithTheMostVertices).reverse() #console.log shehiaNameFromBoundary #console.log labelPosition unless isNaN(labelPosition[0]) @boundaries[boundaryName].labelLayer.addLayer L.marker(labelPosition, icon: L.divIcon className: 'map-marker-labels labels-#{boundaryName}' html: feature.properties[@boundaries[boundaryName].featureName] ) # Cache the maps data locally since the files are big - also kick off a replication to keep them up to date await Coconut.cachingDatabase.get "#{boundaryName}Adjusted" .catch (error) => new Promise (resolve, reject) => Coconut.cachingDatabase.replicate.from Coconut.database, doc_ids: ["#{boundaryName}Adjusted"] .on "complete", => resolve(Coconut.cachingDatabase.get "#{boundaryName}Adjusted" .catch (error) => console.log error ) .then (data) => @boundaries[boundaryName].boundary = L.geoJSON data, className: "boundary" onEachFeature: loadFeatureData @$("#select-boundary-#{boundaryName}").show() @$("#loading-boundary-#{boundaryName}").hide() @showBoundary(boundaryName) if options.load is boundaryName # Wait 5 seconds then check for updated to the maps _.delay => Coconut.cachingDatabase.replicate.from Coconut.database, doc_ids: _(@boundaries).chain().keys().map( (boundaryName) => "#{boundaryName}Adjusted").value() .on "complete", => console.log "Map data updated" , 1000 * 5 showBoundary: (boundaryName) => if @activeBoundary @activeBoundary.removeFrom(@map) @activeBoundary = @boundaries[boundaryName].boundary if @activeLabels @removeLabels() @addLabels(boundaryName) @activeBoundary.addTo(@map).bringToBack() if boundaryName is "Shehias" @$("#shehiaOptions").show() if @shehiaClassifications @$("#showFociClassificationsOptions").show() else @$("#shehiaOptions").hide() @$("#showFociClassificationsOptions").hide() @$('#showSprayedShehias').prop('checked', false); addLabels: (boundaryName) => @removeLabels() if @activeLabels console.log boundaryName console.log @boundaries @activeLabels = @boundaries[boundaryName].labelLayer @activeLabels.addTo(@map).bringToBack() removeLabels: => @activeLabels?.removeFrom(@map) @activeLabels = null colorByClassification = { Indigenous: "red" Imported: "blue" Introduced: "darkgreen" Induced: "purple" Relapsing: "orange" } addCasesToMap: (rowsWithKeyIndicators) => for row in rowsWithKeyIndicators unless row.value.latLong? console.warn "#{row.value} missing latLong, not mapping" continue unless (row.value.latLong?[0] and row.value.latLong?[1]) console.warn "#{row.value} missing latLong, not mapping" continue caseId = row.id[4..].replace(/_.*/,"") L.circleMarker row.value.latLong, color: '#000000' weight: 0.3 radius: 12 fill: true fillOpacity: 0.8 fillColor: if row.value.classification colorByClassification[row.value.classification] else "red" .addTo(@map) .bringToFront() .bindPopup "<a href='#show/case/#{caseId}'>#{caseId}</a>" getCases: => Coconut.individualIndexDatabase.query 'keyIndicatorsByDate', startkey: Coconut.router.reportViewOptions.startDate endkey: Coconut.router.reportViewOptions.endDate .then (result) => @addCasesToMap(result.rows) createMapLegend: => legend = L.control(position: 'bottomright') legend.onAdd = (map) => div = L.DomUtil.create('div', 'info legend') for classification in Coconut.CaseClassifications div.innerHTML += " <i class='circle' style='background:#{colorByClassification[classification]}'></i> #{classification}<br/> " div legend.addTo(@map) createZoomUngujaPemba: => legend = L.control({ position: 'topleft' }) legend.onAdd = (map) => div = L.DomUtil.create('div', 'zoom') div.innerHTML += " <button style='background-color:white' class='zoom' id='zoomUnguja'>Unguja</button><br/><br/> <button style='background-color:white' class='zoom' id='zoomPemba'>Pemba</button> " div legend.addTo(@map) @sprayedShehias= """ Mfenesini Mihogoni Mkokotoni Mto wa Pwani Mwakaje Fuoni Kibondeni Tondooni Dole Bumbwisudi Shakani Kiembesamaki Chukwani Fukuchani Ndagoni Fumba Bweleo Dimani Kombeni Nungwi Mgelema Magogoni Pwani Mchangani Gamba Mtoni Kidatu Moga Fuoni Kijito Upele Kinyasini Kandwi Mbuzini Kisauni Kinuni Nyamanzi Kigomani Misufini Makombeni Makoba Makoongwe Mangapwani Fujoni Kiomba Mvua Donge Mchangani Michenzani Chokocho Zingwe Zingwe Kitope Mahonda Kinduni Mizingani Donge Mbiji Donge Kipange Upenja Kiwengwa Mbuyuni Muwanda Matetema Kidanzini Mbaleni Mafufuni Machui Miwani Kiboje Mkwajuni Ghana Koani Mgeni Haji Uzini Mitakawani Tunduni Bambi Pagali Mtambwe Kaskazini Umbuji Fundo Mchangani Dunga Kiembeni Ndijani Mseweni Jendele Chwaka Marumbi Uroa Piki Jumbi Tunguu Gando Ukunjwi Cheju Bungi Unguja Ukuu Kaepwani Kikungwi Mtambwe Kusini Uzi Charawe Michamvi Mpapa Unguja Ukuu Kaebona Junguni Kiungoni Jambiani Kikadini Kizimkazi Dimbani Kinowe Kizimkazi Mkunguni Muyuni A Tumbe Mashariki Muyuni B Muyuni C Shumba Viamboni Pete Paje Jambiani Kibigija Makangale Bwejuu Kitogani Wingwi Njuguni Mwera Chimba Bububu Tumbe Magharibi """.toUpperCase().split("\n") module.exports = MapView
108043
_ = require "underscore" $ = require "jquery" Backbone = require "backbone" Case = require '../models/Case' DateSelectorView = require '../views/DateSelectorView' Backbone.$ = $ require('leaflet') global.CenterOfPolygon = require 'polylabel' #require('leaflet.heat') HTMLHelpers = require '../HTMLHelpers' dasherize = require 'underscore.string/dasherize' class MapView extends Backbone.View events: => "change .changeBoundary":"changeBoundary" "change #showLabels":"showLabels" "change .changeTileSet":"changeTiles" "change #showSprayedShehias":"showSprayedShehias" "change #showFociClassifications":"toggleFociClassifications" "click #zoomPemba":"zoomPemba" "click #zoomUnguja":"zoomUnguja" zoom: (target) => target = target.toUpperCase() @map.fitBounds switch target when "UNGUJA" [ [-6.489983,39.130554] [-5.714380,39.633179] ] when "PEMBA" [ [-5.506640,39.549065] [-4.858022,39.889984] ] zoomPemba: => @zoom "PEMBA" zoomUnguja: => @zoom "UNGUJA" showSprayedShehias: => if @$('#showSprayedShehias').is(":checked") @$(".sprayed-shehia").css("fill","lightgreen") else @$(".sprayed-shehia").css("fill","") toggleFociClassifications: => if @$('#showFociClassifications').is(":checked") @showFociClassifications() else @$(".sprayed-shehia").css("fill","") showFociClassifications: => @$(".shehia-cleared").css("fill","green") @$(".shehia-residual-non-active").css("fill","yellow") @$(".shehia-active").css("fill","red") changeTiles: => @showTileSet @$('input[name=tileSet]:checked').val() changeBoundary: => @showBoundary @$('input[name=boundary]:checked').val() showLabels: => if @$('#showLabels').is(":checked") @addLabels @$('input[name=boundary]:checked').val() else @removeLabels() render: => @initialBoundary or= "Districts" @initialTileSet or= "None" @$el.html " <style> .map-marker-labels{ white-space:nowrap; color: black; font-size: 1em; } .labels-District{ font-size: 2em; } .boundary{ color: black; fill: white; stroke-width: 0.5; stroke: black; fill-opacity: 1; } .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .legend { line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; } .legend .circle { border-radius: 50%; width: 10px; height: 10px; margin-top: 3.6px; border: 0.3px black solid; } #mapElement{ width: 100%; height: 95%; position: relative; background-color: #e6ffff; } .label{ font-size: 1em } .leaflet-control-scale-line{ border-color:#b0b0b0; color:#b0b0b0; } .controls .controlBox{ padding-top: 15px; padding-bottom: 10px; border: 1px solid black; } </style> <div class='mdl-grid' style='height:100%'> <div class='mdl-cell mdl-cell--12-col' style='height:100%'> <div class='controls' style='float:right'> <span class='controlBox' id='shehiaOptions' style='display:none;'> <input class='showSprayedShehias' id='showSprayedShehias' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showSprayedShehias' class='label'>Sprayed Shehias</label> <div id='showFociClassificationsOptions'> <input class='showFociClassifications' id='showFociClassifications' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showFociClassifications' class='label'>Foci Classifications</label> </div> </span> <span class='controlBox'> #{ (for boundary in [ "Districts", "Shehias", "Villages"] " <input class='changeBoundary' id='select-boundary-#{boundary}' style='display:none; margin-left:10px' type='radio' value='#{boundary}' name='boundary' #{if boundary is @initialBoundary then 'checked' else ''}></input> <span id='loading-boundary-#{boundary}'>Loading...</span> <label for='select-boundary-#{boundary}' class='label'>#{boundary}</label> " ).join("") } </span> <span class='controlBox'> #{ (for tileSet in [ "None", "RoadsBuildings", "Satellite"] " <input class='changeTileSet' id='select-tileSet-#{tileSet}' style='margin-left:10px' type='radio' value='#{tileSet}' name='tileSet' #{if tileSet is @initialTileSet then 'checked' else ''}></input> <label for='select-tileSet-#{tileSet}' class='label'>#{tileSet}</label> " ).join("") } </span> <span class='controlBox labels' style='padding-right: 10px'> <input id='showLabels' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showLabels' class='label'>Labels</label> </span> </div> <div id='date-selector'></div> <div id='mapElement'></div> </div> </div> " @map = L.map @$('#mapElement')[0], zoomSnap: 0.2 .fitBounds [ [-4.8587000, 39.8772333], [-6.4917667, 39.0945000] ] unless @dontShowCases @createMapLegend() if @casesWithKeyIndicators @addCasesToMap(@casesWithKeyIndicators) else @getCases() @createZoomUngujaPemba() promiseWhenBoundariesAreLoaded = @getBoundariesAndLabels load: @initialBoundary @initializeTileSets() L.control.scale().addTo(@map) promiseWhenBoundariesAreLoaded initializeTileSets: => @tilesets = None: null RoadsBuildings: layer: openStreetMapDefault = L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' Satellite: layer: satellite = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }) #streets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'] }) #outdoors = L.tileLayer('https://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', { maxZoom: 20,subdomains:['mt0','mt1','mt2','mt3'] }) showTileSet: (tileSetName) => if @activeTileSet @activeTileSet.removeFrom(@map) if tileSetName is "None" @activeTileSet = null @$(".boundary").css("fill-opacity", 1) else @activeTileSet = @tilesets[tileSetName].layer @activeTileSet.addTo(@map).bringToBack() @$(".boundary").css("fill-opacity", 0) getBoundariesAndLabels: (options) => @boundaries = Districts: labelsDocName: 'DistrictsCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "District_N" Villages: labelsDocName: 'VillageCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "Vil_Mtaa_N" Shehias: labelsDocName: 'ShehiaCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "Shehia_Nam" for boundaryName, properties of @boundaries loadFeatureData = (feature, layer) => if boundaryName is "Shehias" shehiaNameFromBoundary = feature.properties["Shehia_Nam"].toUpperCase() # Creating this so that we can compare DHIS2 shehias with the GIS boundaries @shehiasWithBoundaries or= [] @shehiasWithBoundaries.push shehiaNameFromBoundary if _(@sprayedShehias).contains shehiaNameFromBoundary layer.setStyle className: "boundary sprayed-shehia" if @shehiaClassifications for classification in [ "Cleared" "Residual non-active" "Active" ] if _(@shehiaClassifications[classification]).contains shehiaNameFromBoundary layer.setStyle className: "boundary shehia#{dasherize(classification)}" # Would be better to find the one with the largest area, but most vertices is close enough, easy and fast # Would also be better to save these into the geoJSON as a feature property but it seems fast enough polygonWithTheMostVertices = _(layer.feature.geometry.coordinates).max (polygon) => polygon.length #console.log polygonWithTheMostVertices labelPosition = CenterOfPolygon(polygonWithTheMostVertices).reverse() #console.log shehiaNameFromBoundary #console.log labelPosition unless isNaN(labelPosition[0]) @boundaries[boundaryName].labelLayer.addLayer L.marker(labelPosition, icon: L.divIcon className: 'map-marker-labels labels-#{boundaryName}' html: feature.properties[@boundaries[boundaryName].featureName] ) # Cache the maps data locally since the files are big - also kick off a replication to keep them up to date await Coconut.cachingDatabase.get "#{boundaryName}Adjusted" .catch (error) => new Promise (resolve, reject) => Coconut.cachingDatabase.replicate.from Coconut.database, doc_ids: ["#{boundaryName}Adjusted"] .on "complete", => resolve(Coconut.cachingDatabase.get "#{boundaryName}Adjusted" .catch (error) => console.log error ) .then (data) => @boundaries[boundaryName].boundary = L.geoJSON data, className: "boundary" onEachFeature: loadFeatureData @$("#select-boundary-#{boundaryName}").show() @$("#loading-boundary-#{boundaryName}").hide() @showBoundary(boundaryName) if options.load is boundaryName # Wait 5 seconds then check for updated to the maps _.delay => Coconut.cachingDatabase.replicate.from Coconut.database, doc_ids: _(@boundaries).chain().keys().map( (boundaryName) => "#{boundaryName}Adjusted").value() .on "complete", => console.log "Map data updated" , 1000 * 5 showBoundary: (boundaryName) => if @activeBoundary @activeBoundary.removeFrom(@map) @activeBoundary = @boundaries[boundaryName].boundary if @activeLabels @removeLabels() @addLabels(boundaryName) @activeBoundary.addTo(@map).bringToBack() if boundaryName is "<NAME>" @$("#shehiaOptions").show() if @shehiaClassifications @$("#showFociClassificationsOptions").show() else @$("#shehiaOptions").hide() @$("#showFociClassificationsOptions").hide() @$('#showSprayedShehias').prop('checked', false); addLabels: (boundaryName) => @removeLabels() if @activeLabels console.log boundaryName console.log @boundaries @activeLabels = @boundaries[boundaryName].labelLayer @activeLabels.addTo(@map).bringToBack() removeLabels: => @activeLabels?.removeFrom(@map) @activeLabels = null colorByClassification = { Indigenous: "red" Imported: "blue" Introduced: "darkgreen" Induced: "purple" Relapsing: "orange" } addCasesToMap: (rowsWithKeyIndicators) => for row in rowsWithKeyIndicators unless row.value.latLong? console.warn "#{row.value} missing latLong, not mapping" continue unless (row.value.latLong?[0] and row.value.latLong?[1]) console.warn "#{row.value} missing latLong, not mapping" continue caseId = row.id[4..].replace(/_.*/,"") L.circleMarker row.value.latLong, color: '#000000' weight: 0.3 radius: 12 fill: true fillOpacity: 0.8 fillColor: if row.value.classification colorByClassification[row.value.classification] else "red" .addTo(@map) .bringToFront() .bindPopup "<a href='#show/case/#{caseId}'>#{caseId}</a>" getCases: => Coconut.individualIndexDatabase.query 'keyIndicatorsByDate', startkey: Coconut.router.reportViewOptions.startDate endkey: Coconut.router.reportViewOptions.endDate .then (result) => @addCasesToMap(result.rows) createMapLegend: => legend = L.control(position: 'bottomright') legend.onAdd = (map) => div = L.DomUtil.create('div', 'info legend') for classification in Coconut.CaseClassifications div.innerHTML += " <i class='circle' style='background:#{colorByClassification[classification]}'></i> #{classification}<br/> " div legend.addTo(@map) createZoomUngujaPemba: => legend = L.control({ position: 'topleft' }) legend.onAdd = (map) => div = L.DomUtil.create('div', 'zoom') div.innerHTML += " <button style='background-color:white' class='zoom' id='zoomUnguja'>Unguja</button><br/><br/> <button style='background-color:white' class='zoom' id='zoomPemba'>Pemba</button> " div legend.addTo(@map) @sprayedShehias= """ Mf<NAME>ini <NAME>ihogoni Mkokotoni Mto wa Pwani Mwakaje Fuoni Kibondeni Tondooni Dole Bumbwisudi Shakani Kiembesamaki Chukwani Fukuchani Ndagoni Fumba Bweleo Dimani Kombeni Nungwi Mgelema Magogoni Pwani Mchangani Gamba Mtoni Kidatu Moga Fuoni Kijito Upele Kinyasini Kandwi Mbuzini Kisauni Kinuni Nyamanzi Kigomani Misufini Makombeni Makoba Makoongwe Mangapwani Fujoni Kiomba Mvua Donge Mchangani Michenzani Chokocho Zingwe Zingwe Kitope Mahonda Kinduni Mizingani Donge Mbiji Donge Kipange Upenja Kiwengwa Mbuyuni Muwanda Matetema Kidanzini Mbaleni Mafufuni Machui Miwani Kiboje Mkwajuni Ghana Koani Mgeni Haji Uzini Mitakawani Tunduni Bambi Pagali Mtambwe Kaskazini Umbuji Fundo Mchangani Dunga Kiembeni Ndijani Mseweni Jendele Chwaka Marumbi Uroa Piki Jumbi Tunguu Gando Ukunjwi Cheju Bungi Unguja Ukuu Kaepwani Kikungwi Mtambwe Kusini Uzi Charawe Michamvi Mpapa Unguja Ukuu Kaebona Junguni Kiungoni Jambiani Kikadini Kizimkazi Dimbani Kinowe Kizimkazi Mkunguni Muyuni A Tumbe Mashariki Muyuni B Muyuni C Shumba Viamboni Pete Paje Jambiani Kibigija Makangale Bwejuu Kitogani Wingwi Njuguni Mwera Chimba Bububu Tumbe Magharibi """.toUpperCase().split("\n") module.exports = MapView
true
_ = require "underscore" $ = require "jquery" Backbone = require "backbone" Case = require '../models/Case' DateSelectorView = require '../views/DateSelectorView' Backbone.$ = $ require('leaflet') global.CenterOfPolygon = require 'polylabel' #require('leaflet.heat') HTMLHelpers = require '../HTMLHelpers' dasherize = require 'underscore.string/dasherize' class MapView extends Backbone.View events: => "change .changeBoundary":"changeBoundary" "change #showLabels":"showLabels" "change .changeTileSet":"changeTiles" "change #showSprayedShehias":"showSprayedShehias" "change #showFociClassifications":"toggleFociClassifications" "click #zoomPemba":"zoomPemba" "click #zoomUnguja":"zoomUnguja" zoom: (target) => target = target.toUpperCase() @map.fitBounds switch target when "UNGUJA" [ [-6.489983,39.130554] [-5.714380,39.633179] ] when "PEMBA" [ [-5.506640,39.549065] [-4.858022,39.889984] ] zoomPemba: => @zoom "PEMBA" zoomUnguja: => @zoom "UNGUJA" showSprayedShehias: => if @$('#showSprayedShehias').is(":checked") @$(".sprayed-shehia").css("fill","lightgreen") else @$(".sprayed-shehia").css("fill","") toggleFociClassifications: => if @$('#showFociClassifications').is(":checked") @showFociClassifications() else @$(".sprayed-shehia").css("fill","") showFociClassifications: => @$(".shehia-cleared").css("fill","green") @$(".shehia-residual-non-active").css("fill","yellow") @$(".shehia-active").css("fill","red") changeTiles: => @showTileSet @$('input[name=tileSet]:checked').val() changeBoundary: => @showBoundary @$('input[name=boundary]:checked').val() showLabels: => if @$('#showLabels').is(":checked") @addLabels @$('input[name=boundary]:checked').val() else @removeLabels() render: => @initialBoundary or= "Districts" @initialTileSet or= "None" @$el.html " <style> .map-marker-labels{ white-space:nowrap; color: black; font-size: 1em; } .labels-District{ font-size: 2em; } .boundary{ color: black; fill: white; stroke-width: 0.5; stroke: black; fill-opacity: 1; } .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .legend { line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; } .legend .circle { border-radius: 50%; width: 10px; height: 10px; margin-top: 3.6px; border: 0.3px black solid; } #mapElement{ width: 100%; height: 95%; position: relative; background-color: #e6ffff; } .label{ font-size: 1em } .leaflet-control-scale-line{ border-color:#b0b0b0; color:#b0b0b0; } .controls .controlBox{ padding-top: 15px; padding-bottom: 10px; border: 1px solid black; } </style> <div class='mdl-grid' style='height:100%'> <div class='mdl-cell mdl-cell--12-col' style='height:100%'> <div class='controls' style='float:right'> <span class='controlBox' id='shehiaOptions' style='display:none;'> <input class='showSprayedShehias' id='showSprayedShehias' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showSprayedShehias' class='label'>Sprayed Shehias</label> <div id='showFociClassificationsOptions'> <input class='showFociClassifications' id='showFociClassifications' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showFociClassifications' class='label'>Foci Classifications</label> </div> </span> <span class='controlBox'> #{ (for boundary in [ "Districts", "Shehias", "Villages"] " <input class='changeBoundary' id='select-boundary-#{boundary}' style='display:none; margin-left:10px' type='radio' value='#{boundary}' name='boundary' #{if boundary is @initialBoundary then 'checked' else ''}></input> <span id='loading-boundary-#{boundary}'>Loading...</span> <label for='select-boundary-#{boundary}' class='label'>#{boundary}</label> " ).join("") } </span> <span class='controlBox'> #{ (for tileSet in [ "None", "RoadsBuildings", "Satellite"] " <input class='changeTileSet' id='select-tileSet-#{tileSet}' style='margin-left:10px' type='radio' value='#{tileSet}' name='tileSet' #{if tileSet is @initialTileSet then 'checked' else ''}></input> <label for='select-tileSet-#{tileSet}' class='label'>#{tileSet}</label> " ).join("") } </span> <span class='controlBox labels' style='padding-right: 10px'> <input id='showLabels' type='checkbox' style='margin-left:10px; margin-rght:10px;'></input> <label for='showLabels' class='label'>Labels</label> </span> </div> <div id='date-selector'></div> <div id='mapElement'></div> </div> </div> " @map = L.map @$('#mapElement')[0], zoomSnap: 0.2 .fitBounds [ [-4.8587000, 39.8772333], [-6.4917667, 39.0945000] ] unless @dontShowCases @createMapLegend() if @casesWithKeyIndicators @addCasesToMap(@casesWithKeyIndicators) else @getCases() @createZoomUngujaPemba() promiseWhenBoundariesAreLoaded = @getBoundariesAndLabels load: @initialBoundary @initializeTileSets() L.control.scale().addTo(@map) promiseWhenBoundariesAreLoaded initializeTileSets: => @tilesets = None: null RoadsBuildings: layer: openStreetMapDefault = L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' Satellite: layer: satellite = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }) #streets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'] }) #outdoors = L.tileLayer('https://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', { maxZoom: 20,subdomains:['mt0','mt1','mt2','mt3'] }) showTileSet: (tileSetName) => if @activeTileSet @activeTileSet.removeFrom(@map) if tileSetName is "None" @activeTileSet = null @$(".boundary").css("fill-opacity", 1) else @activeTileSet = @tilesets[tileSetName].layer @activeTileSet.addTo(@map).bringToBack() @$(".boundary").css("fill-opacity", 0) getBoundariesAndLabels: (options) => @boundaries = Districts: labelsDocName: 'DistrictsCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "District_N" Villages: labelsDocName: 'VillageCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "Vil_Mtaa_N" Shehias: labelsDocName: 'ShehiaCntrPtsWGS84' labelLayer: L.featureGroup() featureName: "Shehia_Nam" for boundaryName, properties of @boundaries loadFeatureData = (feature, layer) => if boundaryName is "Shehias" shehiaNameFromBoundary = feature.properties["Shehia_Nam"].toUpperCase() # Creating this so that we can compare DHIS2 shehias with the GIS boundaries @shehiasWithBoundaries or= [] @shehiasWithBoundaries.push shehiaNameFromBoundary if _(@sprayedShehias).contains shehiaNameFromBoundary layer.setStyle className: "boundary sprayed-shehia" if @shehiaClassifications for classification in [ "Cleared" "Residual non-active" "Active" ] if _(@shehiaClassifications[classification]).contains shehiaNameFromBoundary layer.setStyle className: "boundary shehia#{dasherize(classification)}" # Would be better to find the one with the largest area, but most vertices is close enough, easy and fast # Would also be better to save these into the geoJSON as a feature property but it seems fast enough polygonWithTheMostVertices = _(layer.feature.geometry.coordinates).max (polygon) => polygon.length #console.log polygonWithTheMostVertices labelPosition = CenterOfPolygon(polygonWithTheMostVertices).reverse() #console.log shehiaNameFromBoundary #console.log labelPosition unless isNaN(labelPosition[0]) @boundaries[boundaryName].labelLayer.addLayer L.marker(labelPosition, icon: L.divIcon className: 'map-marker-labels labels-#{boundaryName}' html: feature.properties[@boundaries[boundaryName].featureName] ) # Cache the maps data locally since the files are big - also kick off a replication to keep them up to date await Coconut.cachingDatabase.get "#{boundaryName}Adjusted" .catch (error) => new Promise (resolve, reject) => Coconut.cachingDatabase.replicate.from Coconut.database, doc_ids: ["#{boundaryName}Adjusted"] .on "complete", => resolve(Coconut.cachingDatabase.get "#{boundaryName}Adjusted" .catch (error) => console.log error ) .then (data) => @boundaries[boundaryName].boundary = L.geoJSON data, className: "boundary" onEachFeature: loadFeatureData @$("#select-boundary-#{boundaryName}").show() @$("#loading-boundary-#{boundaryName}").hide() @showBoundary(boundaryName) if options.load is boundaryName # Wait 5 seconds then check for updated to the maps _.delay => Coconut.cachingDatabase.replicate.from Coconut.database, doc_ids: _(@boundaries).chain().keys().map( (boundaryName) => "#{boundaryName}Adjusted").value() .on "complete", => console.log "Map data updated" , 1000 * 5 showBoundary: (boundaryName) => if @activeBoundary @activeBoundary.removeFrom(@map) @activeBoundary = @boundaries[boundaryName].boundary if @activeLabels @removeLabels() @addLabels(boundaryName) @activeBoundary.addTo(@map).bringToBack() if boundaryName is "PI:NAME:<NAME>END_PI" @$("#shehiaOptions").show() if @shehiaClassifications @$("#showFociClassificationsOptions").show() else @$("#shehiaOptions").hide() @$("#showFociClassificationsOptions").hide() @$('#showSprayedShehias').prop('checked', false); addLabels: (boundaryName) => @removeLabels() if @activeLabels console.log boundaryName console.log @boundaries @activeLabels = @boundaries[boundaryName].labelLayer @activeLabels.addTo(@map).bringToBack() removeLabels: => @activeLabels?.removeFrom(@map) @activeLabels = null colorByClassification = { Indigenous: "red" Imported: "blue" Introduced: "darkgreen" Induced: "purple" Relapsing: "orange" } addCasesToMap: (rowsWithKeyIndicators) => for row in rowsWithKeyIndicators unless row.value.latLong? console.warn "#{row.value} missing latLong, not mapping" continue unless (row.value.latLong?[0] and row.value.latLong?[1]) console.warn "#{row.value} missing latLong, not mapping" continue caseId = row.id[4..].replace(/_.*/,"") L.circleMarker row.value.latLong, color: '#000000' weight: 0.3 radius: 12 fill: true fillOpacity: 0.8 fillColor: if row.value.classification colorByClassification[row.value.classification] else "red" .addTo(@map) .bringToFront() .bindPopup "<a href='#show/case/#{caseId}'>#{caseId}</a>" getCases: => Coconut.individualIndexDatabase.query 'keyIndicatorsByDate', startkey: Coconut.router.reportViewOptions.startDate endkey: Coconut.router.reportViewOptions.endDate .then (result) => @addCasesToMap(result.rows) createMapLegend: => legend = L.control(position: 'bottomright') legend.onAdd = (map) => div = L.DomUtil.create('div', 'info legend') for classification in Coconut.CaseClassifications div.innerHTML += " <i class='circle' style='background:#{colorByClassification[classification]}'></i> #{classification}<br/> " div legend.addTo(@map) createZoomUngujaPemba: => legend = L.control({ position: 'topleft' }) legend.onAdd = (map) => div = L.DomUtil.create('div', 'zoom') div.innerHTML += " <button style='background-color:white' class='zoom' id='zoomUnguja'>Unguja</button><br/><br/> <button style='background-color:white' class='zoom' id='zoomPemba'>Pemba</button> " div legend.addTo(@map) @sprayedShehias= """ MfPI:NAME:<NAME>END_PIini PI:NAME:<NAME>END_PIihogoni Mkokotoni Mto wa Pwani Mwakaje Fuoni Kibondeni Tondooni Dole Bumbwisudi Shakani Kiembesamaki Chukwani Fukuchani Ndagoni Fumba Bweleo Dimani Kombeni Nungwi Mgelema Magogoni Pwani Mchangani Gamba Mtoni Kidatu Moga Fuoni Kijito Upele Kinyasini Kandwi Mbuzini Kisauni Kinuni Nyamanzi Kigomani Misufini Makombeni Makoba Makoongwe Mangapwani Fujoni Kiomba Mvua Donge Mchangani Michenzani Chokocho Zingwe Zingwe Kitope Mahonda Kinduni Mizingani Donge Mbiji Donge Kipange Upenja Kiwengwa Mbuyuni Muwanda Matetema Kidanzini Mbaleni Mafufuni Machui Miwani Kiboje Mkwajuni Ghana Koani Mgeni Haji Uzini Mitakawani Tunduni Bambi Pagali Mtambwe Kaskazini Umbuji Fundo Mchangani Dunga Kiembeni Ndijani Mseweni Jendele Chwaka Marumbi Uroa Piki Jumbi Tunguu Gando Ukunjwi Cheju Bungi Unguja Ukuu Kaepwani Kikungwi Mtambwe Kusini Uzi Charawe Michamvi Mpapa Unguja Ukuu Kaebona Junguni Kiungoni Jambiani Kikadini Kizimkazi Dimbani Kinowe Kizimkazi Mkunguni Muyuni A Tumbe Mashariki Muyuni B Muyuni C Shumba Viamboni Pete Paje Jambiani Kibigija Makangale Bwejuu Kitogani Wingwi Njuguni Mwera Chimba Bububu Tumbe Magharibi """.toUpperCase().split("\n") module.exports = MapView
[ { "context": "apAsync(f)(args...)\n\nclass IrcClient\n\tconstructor: (@loginReq) ->\n\t\t@user = @loginReq.user\n\t\tircClientMap[@user", "end": 709, "score": 0.9934280514717102, "start": 699, "tag": "USERNAME", "value": "(@loginReq" }, { "context": ")\n\nclass IrcClient\n\tconstruct...
packages/rocketchat-irc/server/server.coffee
claysaad/Rocket.Chat
0
# # # # Assign values # # Package availability IRC_AVAILABILITY = RocketChat.settings.get('IRC_Enabled'); # Cache prep net = Npm.require('net') Lru = Npm.require('lru-cache') MESSAGE_CACHE_SIZE = RocketChat.settings.get('IRC_Message_Cache_Size'); ircReceiveMessageCache = Lru MESSAGE_CACHE_SIZE ircSendMessageCache = Lru MESSAGE_CACHE_SIZE # IRC server IRC_PORT = RocketChat.settings.get('IRC_Port'); IRC_HOST = RocketChat.settings.get('IRC_Host'); ircClientMap = {} # # # # Core functionality # bind = (f) -> g = Meteor.bindEnvironment (self, args...) -> f.apply(self, args) (args...) -> g @, args... async = (f, args...) -> Meteor.wrapAsync(f)(args...) class IrcClient constructor: (@loginReq) -> @user = @loginReq.user ircClientMap[@user._id] = this @ircPort = IRC_PORT @ircHost = IRC_HOST @msgBuf = [] @isConnected = false @isDistroyed = false @socket = new net.Socket @socket.setNoDelay @socket.setEncoding 'utf-8' @socket.setKeepAlive true @onConnect = bind @onConnect @onClose = bind @onClose @onTimeout = bind @onTimeout @onError = bind @onError @onReceiveRawMessage = bind @onReceiveRawMessage @socket.on 'data', @onReceiveRawMessage @socket.on 'close', @onClose @socket.on 'timeout', @onTimeout @socket.on 'error', @onError @isJoiningRoom = false @receiveMemberListBuf = {} @pendingJoinRoomBuf = [] @successLoginMessageRegex = /RocketChat.settings.get('IRC_RegEx_successLogin');/ @failedLoginMessageRegex = /RocketChat.settings.get('IRC_RegEx_failedLogin');/ @receiveMessageRegex = /RocketChat.settings.get('IRC_RegEx_receiveMessage');/ @receiveMemberListRegex = /RocketChat.settings.get('IRC_RegEx_receiveMemberList');/ @endMemberListRegex = /RocketChat.settings.get('IRC_RegEx_endMemberList');/ @addMemberToRoomRegex = /RocketChat.settings.get('IRC_RegEx_addMemberToRoom');/ @removeMemberFromRoomRegex = /RocketChat.settings.get('IRC_RegEx_removeMemberFromRoom');/ @quitMemberRegex = /RocketChat.settings.get('IRC_RegEx_quitMember');/ connect: (@loginCb) => @socket.connect @ircPort, @ircHost, @onConnect @initRoomList() disconnect: () -> @isDistroyed = true @socket.destroy() onConnect: () => console.log '[irc] onConnect -> '.yellow, @user.username, 'connect success.' @socket.write "NICK #{@user.username}\r\n" @socket.write "USER #{@user.username} 0 * :#{@user.name}\r\n" # message order could not make sure here @isConnected = true @socket.write msg for msg in @msgBuf onClose: (data) => console.log '[irc] onClose -> '.yellow, @user.username, 'connection close.' @isConnected = false if @isDistroyed delete ircClientMap[@user._id] else @connect() onTimeout: () => console.log '[irc] onTimeout -> '.yellow, @user.username, 'connection timeout.', arguments onError: () => console.log '[irc] onError -> '.yellow, @user.username, 'connection error.', arguments onReceiveRawMessage: (data) => data = data.toString().split('\n') for line in data line = line.trim() console.log "[#{@ircHost}:#{@ircPort}]:", line # Send heartbeat package to irc server if line.indexOf('PING') == 0 @socket.write line.replace('PING :', 'PONG ') continue matchResult = @receiveMessageRegex.exec line if matchResult @onReceiveMessage matchResult[1], matchResult[2], matchResult[3] continue matchResult = @receiveMemberListRegex.exec line if matchResult @onReceiveMemberList matchResult[1], matchResult[2].split ' ' continue matchResult = @endMemberListRegex.exec line if matchResult @onEndMemberList matchResult[1] continue matchResult = @addMemberToRoomRegex.exec line if matchResult @onAddMemberToRoom matchResult[1], matchResult[2] continue matchResult = @removeMemberFromRoomRegex.exec line if matchResult @onRemoveMemberFromRoom matchResult[1], matchResult[2] continue matchResult = @quitMemberRegex.exec line if matchResult @onQuitMember matchResult[1] continue matchResult = @successLoginMessageRegex.exec line if matchResult @onSuccessLoginMessage() continue matchResult = @failedLoginMessageRegex.exec line if matchResult @onFailedLoginMessage() continue onSuccessLoginMessage: () -> console.log '[irc] onSuccessLoginMessage -> '.yellow if @loginCb @loginCb null, @loginReq onFailedLoginMessage: () -> console.log '[irc] onFailedLoginMessage -> '.yellow @loginReq.allowed = false @disconnect() if @loginCb @loginCb null, @loginReq onReceiveMessage: (source, target, content) -> now = new Date timestamp = now.getTime() cacheKey = [source, target, content].join ',' console.log '[irc] ircSendMessageCache.get -> '.yellow, 'key:', cacheKey, 'value:', ircSendMessageCache.get(cacheKey), 'ts:', (timestamp - 1000) if ircSendMessageCache.get(cacheKey) > (timestamp - 1000) return else ircSendMessageCache.set cacheKey, timestamp console.log '[irc] onReceiveMessage -> '.yellow, 'source:', source, 'target:', target, 'content:', content source = @createUserWhenNotExist source if target[0] == '#' room = RocketChat.models.Rooms.findOneByName target.substring(1) else room = @createDirectRoomWhenNotExist(source, @user) message = msg: content ts: now cacheKey = "#{source.username}#{timestamp}" ircReceiveMessageCache.set cacheKey, true console.log '[irc] ircReceiveMessageCache.set -> '.yellow, 'key:', cacheKey RocketChat.sendMessage source, message, room onReceiveMemberList: (roomName, members) -> @receiveMemberListBuf[roomName] = @receiveMemberListBuf[roomName].concat members onEndMemberList: (roomName) -> newMembers = @receiveMemberListBuf[roomName] console.log '[irc] onEndMemberList -> '.yellow, 'room:', roomName, 'members:', newMembers.join ',' room = RocketChat.models.Rooms.findOneByNameAndType roomName, 'c' unless room return oldMembers = room.usernames appendMembers = _.difference newMembers, oldMembers removeMembers = _.difference oldMembers, newMembers for member in appendMembers @createUserWhenNotExist member RocketChat.models.Rooms.removeUsernamesById room._id, removeMembers RocketChat.models.Rooms.addUsernamesById room._id, appendMembers @isJoiningRoom = false roomName = @pendingJoinRoomBuf.shift() if roomName @joinRoom t: 'c' name: roomName sendRawMessage: (msg) -> console.log '[irc] sendRawMessage -> '.yellow, msg.slice(0, -2) if @isConnected @socket.write msg else @msgBuf.push msg sendMessage: (room, message) -> console.log '[irc] sendMessage -> '.yellow, 'userName:', message.u.username target = '' if room.t == 'c' target = "##{room.name}" else if room.t == 'd' for name in room.usernames if message.u.username != name target = name break cacheKey = [@user.username, target, message.msg].join ',' console.log '[irc] ircSendMessageCache.set -> '.yellow, 'key:', cacheKey, 'ts:', message.ts.getTime() ircSendMessageCache.set cacheKey, message.ts.getTime() msg = "PRIVMSG #{target} :#{message.msg}\r\n" @sendRawMessage msg initRoomList: -> roomsCursor = RocketChat.models.Rooms.findByTypeContainigUsername 'c', @user.username, fields: name: 1 t: 1 rooms = roomsCursor.fetch() for room in rooms @joinRoom(room) joinRoom: (room) -> if room.t isnt 'c' or room.name == 'general' return if @isJoiningRoom @pendingJoinRoomBuf.push room.name else console.log '[irc] joinRoom -> '.yellow, 'roomName:', room.name, 'pendingJoinRoomBuf:', @pendingJoinRoomBuf.join ',' msg = "JOIN ##{room.name}\r\n" @receiveMemberListBuf[room.name] = [] @sendRawMessage msg @isJoiningRoom = true leaveRoom: (room) -> if room.t isnt 'c' return msg = "PART ##{room.name}\r\n" @sendRawMessage msg getMemberList: (room) -> if room.t isnt 'c' return msg = "NAMES ##{room.name}\r\n" @receiveMemberListBuf[room.name] = [] @sendRawMessage msg onAddMemberToRoom: (member, roomName) -> if @user.username == member return console.log '[irc] onAddMemberToRoom -> '.yellow, 'roomName:', roomName, 'member:', member @createUserWhenNotExist member RocketChat.models.Rooms.addUsernameByName roomName, member onRemoveMemberFromRoom: (member, roomName)-> console.log '[irc] onRemoveMemberFromRoom -> '.yellow, 'roomName:', roomName, 'member:', member RocketChat.models.Rooms.removeUsernameByName roomName, member onQuitMember: (member) -> console.log '[irc] onQuitMember ->'.yellow, 'username:', member RocketChat.models.Rooms.removeUsernameFromAll member Meteor.users.update {name: member}, $set: status: 'offline' createUserWhenNotExist: (name) -> user = Meteor.users.findOne {name: name} unless user console.log '[irc] createNotExistUser ->'.yellow, 'userName:', name Meteor.call 'registerUser', email: "#{name}@rocketchat.org" pass: 'rocketchat' name: name Meteor.users.update {name: name}, $set: status: 'online' username: name user = Meteor.users.findOne {name: name} return user createDirectRoomWhenNotExist: (source, target) -> console.log '[irc] createDirectRoomWhenNotExist -> '.yellow, 'source:', source, 'target:', target rid = [source._id, target._id].sort().join('') now = new Date() RocketChat.models.Rooms.upsert _id: rid , $set: usernames: [source.username, target.username] $setOnInsert: t: 'd' msgs: 0 ts: now RocketChat.models.Subscriptions.upsert rid: rid $and: [{'u._id': target._id}] , $setOnInsert: name: source.username t: 'd' open: false alert: false unread: 0 u: _id: target._id username: target.username return { t: 'd' _id: rid } IrcClient.getByUid = (uid) -> return ircClientMap[uid] IrcClient.create = (login) -> unless login.user? return login unless login.user._id of ircClientMap ircClient = new IrcClient login return async ircClient.connect return login class IrcLoginer constructor: (login) -> console.log '[irc] validateLogin -> '.yellow, login return IrcClient.create login class IrcSender constructor: (message) -> name = message.u.username timestamp = message.ts.getTime() cacheKey = "#{name}#{timestamp}" if ircReceiveMessageCache.get cacheKey return message room = RocketChat.models.Rooms.findOneById message.rid, { fields: { name: 1, usernames: 1, t: 1 } } ircClient = IrcClient.getByUid message.u._id ircClient.sendMessage room, message return message class IrcRoomJoiner constructor: (user, room) -> ircClient = IrcClient.getByUid user._id ircClient.joinRoom room return room class IrcRoomLeaver constructor: (user, room) -> ircClient = IrcClient.getByUid user._id ircClient.leaveRoom room return room class IrcLogoutCleanUper constructor: (user) -> ircClient = IrcClient.getByUid user._id ircClient.disconnect() return user # # # # Make magic happen # # Only proceed if the package has been enabled if IRC_AVAILABILITY == true RocketChat.callbacks.add 'beforeValidateLogin', IrcLoginer, RocketChat.callbacks.priority.LOW, 'irc-loginer' RocketChat.callbacks.add 'beforeSaveMessage', IrcSender, RocketChat.callbacks.priority.LOW, 'irc-sender' RocketChat.callbacks.add 'beforeJoinRoom', IrcRoomJoiner, RocketChat.callbacks.priority.LOW, 'irc-room-joiner' RocketChat.callbacks.add 'beforeCreateChannel', IrcRoomJoiner, RocketChat.callbacks.priority.LOW, 'irc-room-joiner-create-channel' RocketChat.callbacks.add 'beforeLeaveRoom', IrcRoomLeaver, RocketChat.callbacks.priority.LOW, 'irc-room-leaver' RocketChat.callbacks.add 'afterLogoutCleanUp', IrcLogoutCleanUper, RocketChat.callbacks.priority.LOW, 'irc-clean-up' else return
18212
# # # # Assign values # # Package availability IRC_AVAILABILITY = RocketChat.settings.get('IRC_Enabled'); # Cache prep net = Npm.require('net') Lru = Npm.require('lru-cache') MESSAGE_CACHE_SIZE = RocketChat.settings.get('IRC_Message_Cache_Size'); ircReceiveMessageCache = Lru MESSAGE_CACHE_SIZE ircSendMessageCache = Lru MESSAGE_CACHE_SIZE # IRC server IRC_PORT = RocketChat.settings.get('IRC_Port'); IRC_HOST = RocketChat.settings.get('IRC_Host'); ircClientMap = {} # # # # Core functionality # bind = (f) -> g = Meteor.bindEnvironment (self, args...) -> f.apply(self, args) (args...) -> g @, args... async = (f, args...) -> Meteor.wrapAsync(f)(args...) class IrcClient constructor: (@loginReq) -> @user = @loginReq.user ircClientMap[@user._id] = this @ircPort = IRC_PORT @ircHost = IRC_HOST @msgBuf = [] @isConnected = false @isDistroyed = false @socket = new net.Socket @socket.setNoDelay @socket.setEncoding 'utf-8' @socket.setKeepAlive true @onConnect = bind @onConnect @onClose = bind @onClose @onTimeout = bind @onTimeout @onError = bind @onError @onReceiveRawMessage = bind @onReceiveRawMessage @socket.on 'data', @onReceiveRawMessage @socket.on 'close', @onClose @socket.on 'timeout', @onTimeout @socket.on 'error', @onError @isJoiningRoom = false @receiveMemberListBuf = {} @pendingJoinRoomBuf = [] @successLoginMessageRegex = /RocketChat.settings.get('IRC_RegEx_successLogin');/ @failedLoginMessageRegex = /RocketChat.settings.get('IRC_RegEx_failedLogin');/ @receiveMessageRegex = /RocketChat.settings.get('IRC_RegEx_receiveMessage');/ @receiveMemberListRegex = /RocketChat.settings.get('IRC_RegEx_receiveMemberList');/ @endMemberListRegex = /RocketChat.settings.get('IRC_RegEx_endMemberList');/ @addMemberToRoomRegex = /RocketChat.settings.get('IRC_RegEx_addMemberToRoom');/ @removeMemberFromRoomRegex = /RocketChat.settings.get('IRC_RegEx_removeMemberFromRoom');/ @quitMemberRegex = /RocketChat.settings.get('IRC_RegEx_quitMember');/ connect: (@loginCb) => @socket.connect @ircPort, @ircHost, @onConnect @initRoomList() disconnect: () -> @isDistroyed = true @socket.destroy() onConnect: () => console.log '[irc] onConnect -> '.yellow, @user.username, 'connect success.' @socket.write "NICK #{@user.username}\r\n" @socket.write "USER #{@user.username} 0 * :#{@user.name}\r\n" # message order could not make sure here @isConnected = true @socket.write msg for msg in @msgBuf onClose: (data) => console.log '[irc] onClose -> '.yellow, @user.username, 'connection close.' @isConnected = false if @isDistroyed delete ircClientMap[@user._id] else @connect() onTimeout: () => console.log '[irc] onTimeout -> '.yellow, @user.username, 'connection timeout.', arguments onError: () => console.log '[irc] onError -> '.yellow, @user.username, 'connection error.', arguments onReceiveRawMessage: (data) => data = data.toString().split('\n') for line in data line = line.trim() console.log "[#{@ircHost}:#{@ircPort}]:", line # Send heartbeat package to irc server if line.indexOf('PING') == 0 @socket.write line.replace('PING :', 'PONG ') continue matchResult = @receiveMessageRegex.exec line if matchResult @onReceiveMessage matchResult[1], matchResult[2], matchResult[3] continue matchResult = @receiveMemberListRegex.exec line if matchResult @onReceiveMemberList matchResult[1], matchResult[2].split ' ' continue matchResult = @endMemberListRegex.exec line if matchResult @onEndMemberList matchResult[1] continue matchResult = @addMemberToRoomRegex.exec line if matchResult @onAddMemberToRoom matchResult[1], matchResult[2] continue matchResult = @removeMemberFromRoomRegex.exec line if matchResult @onRemoveMemberFromRoom matchResult[1], matchResult[2] continue matchResult = @quitMemberRegex.exec line if matchResult @onQuitMember matchResult[1] continue matchResult = @successLoginMessageRegex.exec line if matchResult @onSuccessLoginMessage() continue matchResult = @failedLoginMessageRegex.exec line if matchResult @onFailedLoginMessage() continue onSuccessLoginMessage: () -> console.log '[irc] onSuccessLoginMessage -> '.yellow if @loginCb @loginCb null, @loginReq onFailedLoginMessage: () -> console.log '[irc] onFailedLoginMessage -> '.yellow @loginReq.allowed = false @disconnect() if @loginCb @loginCb null, @loginReq onReceiveMessage: (source, target, content) -> now = new Date timestamp = now.getTime() cacheKey = [source, target, content].join ',' console.log '[irc] ircSendMessageCache.get -> '.yellow, 'key:', cacheKey, 'value:', ircSendMessageCache.get(cacheKey), 'ts:', (timestamp - 1000) if ircSendMessageCache.get(cacheKey) > (timestamp - 1000) return else ircSendMessageCache.set cacheKey, timestamp console.log '[irc] onReceiveMessage -> '.yellow, 'source:', source, 'target:', target, 'content:', content source = @createUserWhenNotExist source if target[0] == '#' room = RocketChat.models.Rooms.findOneByName target.substring(1) else room = @createDirectRoomWhenNotExist(source, @user) message = msg: content ts: now cacheKey = "#{source.username}#{timestamp}" ircReceiveMessageCache.set cacheKey, true console.log '[irc] ircReceiveMessageCache.set -> '.yellow, 'key:', cacheKey RocketChat.sendMessage source, message, room onReceiveMemberList: (roomName, members) -> @receiveMemberListBuf[roomName] = @receiveMemberListBuf[roomName].concat members onEndMemberList: (roomName) -> newMembers = @receiveMemberListBuf[roomName] console.log '[irc] onEndMemberList -> '.yellow, 'room:', roomName, 'members:', newMembers.join ',' room = RocketChat.models.Rooms.findOneByNameAndType roomName, 'c' unless room return oldMembers = room.usernames appendMembers = _.difference newMembers, oldMembers removeMembers = _.difference oldMembers, newMembers for member in appendMembers @createUserWhenNotExist member RocketChat.models.Rooms.removeUsernamesById room._id, removeMembers RocketChat.models.Rooms.addUsernamesById room._id, appendMembers @isJoiningRoom = false roomName = @pendingJoinRoomBuf.shift() if roomName @joinRoom t: 'c' name: roomName sendRawMessage: (msg) -> console.log '[irc] sendRawMessage -> '.yellow, msg.slice(0, -2) if @isConnected @socket.write msg else @msgBuf.push msg sendMessage: (room, message) -> console.log '[irc] sendMessage -> '.yellow, 'userName:', message.u.username target = '' if room.t == 'c' target = "##{room.name}" else if room.t == 'd' for name in room.usernames if message.u.username != name target = name break cacheKey = [@user.username, target, message.msg].join ',' console.log '[irc] ircSendMessageCache.set -> '.yellow, 'key:', cacheKey, 'ts:', message.ts.getTime() ircSendMessageCache.set cacheKey, message.ts.getTime() msg = "PRIVMSG #{target} :#{message.msg}\r\n" @sendRawMessage msg initRoomList: -> roomsCursor = RocketChat.models.Rooms.findByTypeContainigUsername 'c', @user.username, fields: name: 1 t: 1 rooms = roomsCursor.fetch() for room in rooms @joinRoom(room) joinRoom: (room) -> if room.t isnt 'c' or room.name == 'general' return if @isJoiningRoom @pendingJoinRoomBuf.push room.name else console.log '[irc] joinRoom -> '.yellow, 'roomName:', room.name, 'pendingJoinRoomBuf:', @pendingJoinRoomBuf.join ',' msg = "JOIN ##{room.name}\r\n" @receiveMemberListBuf[room.name] = [] @sendRawMessage msg @isJoiningRoom = true leaveRoom: (room) -> if room.t isnt 'c' return msg = "PART ##{room.name}\r\n" @sendRawMessage msg getMemberList: (room) -> if room.t isnt 'c' return msg = "NAMES ##{room.name}\r\n" @receiveMemberListBuf[room.name] = [] @sendRawMessage msg onAddMemberToRoom: (member, roomName) -> if @user.username == member return console.log '[irc] onAddMemberToRoom -> '.yellow, 'roomName:', roomName, 'member:', member @createUserWhenNotExist member RocketChat.models.Rooms.addUsernameByName roomName, member onRemoveMemberFromRoom: (member, roomName)-> console.log '[irc] onRemoveMemberFromRoom -> '.yellow, 'roomName:', roomName, 'member:', member RocketChat.models.Rooms.removeUsernameByName roomName, member onQuitMember: (member) -> console.log '[irc] onQuitMember ->'.yellow, 'username:', member RocketChat.models.Rooms.removeUsernameFromAll member Meteor.users.update {name: member}, $set: status: 'offline' createUserWhenNotExist: (name) -> user = Meteor.users.findOne {name: name} unless user console.log '[irc] createNotExistUser ->'.yellow, 'userName:', name Meteor.call 'registerUser', email: <EMAIL>" pass: '<PASSWORD>' name: name Meteor.users.update {name: name}, $set: status: 'online' username: name user = Meteor.users.findOne {name: name} return user createDirectRoomWhenNotExist: (source, target) -> console.log '[irc] createDirectRoomWhenNotExist -> '.yellow, 'source:', source, 'target:', target rid = [source._id, target._id].sort().join('') now = new Date() RocketChat.models.Rooms.upsert _id: rid , $set: usernames: [source.username, target.username] $setOnInsert: t: 'd' msgs: 0 ts: now RocketChat.models.Subscriptions.upsert rid: rid $and: [{'u._id': target._id}] , $setOnInsert: name: source.username t: 'd' open: false alert: false unread: 0 u: _id: target._id username: target.username return { t: 'd' _id: rid } IrcClient.getByUid = (uid) -> return ircClientMap[uid] IrcClient.create = (login) -> unless login.user? return login unless login.user._id of ircClientMap ircClient = new IrcClient login return async ircClient.connect return login class IrcLoginer constructor: (login) -> console.log '[irc] validateLogin -> '.yellow, login return IrcClient.create login class IrcSender constructor: (message) -> name = message.u.username timestamp = message.ts.getTime() cacheKey = "#{name}#{timestamp}" if ircReceiveMessageCache.get cacheKey return message room = RocketChat.models.Rooms.findOneById message.rid, { fields: { name: 1, usernames: 1, t: 1 } } ircClient = IrcClient.getByUid message.u._id ircClient.sendMessage room, message return message class IrcRoomJoiner constructor: (user, room) -> ircClient = IrcClient.getByUid user._id ircClient.joinRoom room return room class IrcRoomLeaver constructor: (user, room) -> ircClient = IrcClient.getByUid user._id ircClient.leaveRoom room return room class IrcLogoutCleanUper constructor: (user) -> ircClient = IrcClient.getByUid user._id ircClient.disconnect() return user # # # # Make magic happen # # Only proceed if the package has been enabled if IRC_AVAILABILITY == true RocketChat.callbacks.add 'beforeValidateLogin', IrcLoginer, RocketChat.callbacks.priority.LOW, 'irc-loginer' RocketChat.callbacks.add 'beforeSaveMessage', IrcSender, RocketChat.callbacks.priority.LOW, 'irc-sender' RocketChat.callbacks.add 'beforeJoinRoom', IrcRoomJoiner, RocketChat.callbacks.priority.LOW, 'irc-room-joiner' RocketChat.callbacks.add 'beforeCreateChannel', IrcRoomJoiner, RocketChat.callbacks.priority.LOW, 'irc-room-joiner-create-channel' RocketChat.callbacks.add 'beforeLeaveRoom', IrcRoomLeaver, RocketChat.callbacks.priority.LOW, 'irc-room-leaver' RocketChat.callbacks.add 'afterLogoutCleanUp', IrcLogoutCleanUper, RocketChat.callbacks.priority.LOW, 'irc-clean-up' else return
true
# # # # Assign values # # Package availability IRC_AVAILABILITY = RocketChat.settings.get('IRC_Enabled'); # Cache prep net = Npm.require('net') Lru = Npm.require('lru-cache') MESSAGE_CACHE_SIZE = RocketChat.settings.get('IRC_Message_Cache_Size'); ircReceiveMessageCache = Lru MESSAGE_CACHE_SIZE ircSendMessageCache = Lru MESSAGE_CACHE_SIZE # IRC server IRC_PORT = RocketChat.settings.get('IRC_Port'); IRC_HOST = RocketChat.settings.get('IRC_Host'); ircClientMap = {} # # # # Core functionality # bind = (f) -> g = Meteor.bindEnvironment (self, args...) -> f.apply(self, args) (args...) -> g @, args... async = (f, args...) -> Meteor.wrapAsync(f)(args...) class IrcClient constructor: (@loginReq) -> @user = @loginReq.user ircClientMap[@user._id] = this @ircPort = IRC_PORT @ircHost = IRC_HOST @msgBuf = [] @isConnected = false @isDistroyed = false @socket = new net.Socket @socket.setNoDelay @socket.setEncoding 'utf-8' @socket.setKeepAlive true @onConnect = bind @onConnect @onClose = bind @onClose @onTimeout = bind @onTimeout @onError = bind @onError @onReceiveRawMessage = bind @onReceiveRawMessage @socket.on 'data', @onReceiveRawMessage @socket.on 'close', @onClose @socket.on 'timeout', @onTimeout @socket.on 'error', @onError @isJoiningRoom = false @receiveMemberListBuf = {} @pendingJoinRoomBuf = [] @successLoginMessageRegex = /RocketChat.settings.get('IRC_RegEx_successLogin');/ @failedLoginMessageRegex = /RocketChat.settings.get('IRC_RegEx_failedLogin');/ @receiveMessageRegex = /RocketChat.settings.get('IRC_RegEx_receiveMessage');/ @receiveMemberListRegex = /RocketChat.settings.get('IRC_RegEx_receiveMemberList');/ @endMemberListRegex = /RocketChat.settings.get('IRC_RegEx_endMemberList');/ @addMemberToRoomRegex = /RocketChat.settings.get('IRC_RegEx_addMemberToRoom');/ @removeMemberFromRoomRegex = /RocketChat.settings.get('IRC_RegEx_removeMemberFromRoom');/ @quitMemberRegex = /RocketChat.settings.get('IRC_RegEx_quitMember');/ connect: (@loginCb) => @socket.connect @ircPort, @ircHost, @onConnect @initRoomList() disconnect: () -> @isDistroyed = true @socket.destroy() onConnect: () => console.log '[irc] onConnect -> '.yellow, @user.username, 'connect success.' @socket.write "NICK #{@user.username}\r\n" @socket.write "USER #{@user.username} 0 * :#{@user.name}\r\n" # message order could not make sure here @isConnected = true @socket.write msg for msg in @msgBuf onClose: (data) => console.log '[irc] onClose -> '.yellow, @user.username, 'connection close.' @isConnected = false if @isDistroyed delete ircClientMap[@user._id] else @connect() onTimeout: () => console.log '[irc] onTimeout -> '.yellow, @user.username, 'connection timeout.', arguments onError: () => console.log '[irc] onError -> '.yellow, @user.username, 'connection error.', arguments onReceiveRawMessage: (data) => data = data.toString().split('\n') for line in data line = line.trim() console.log "[#{@ircHost}:#{@ircPort}]:", line # Send heartbeat package to irc server if line.indexOf('PING') == 0 @socket.write line.replace('PING :', 'PONG ') continue matchResult = @receiveMessageRegex.exec line if matchResult @onReceiveMessage matchResult[1], matchResult[2], matchResult[3] continue matchResult = @receiveMemberListRegex.exec line if matchResult @onReceiveMemberList matchResult[1], matchResult[2].split ' ' continue matchResult = @endMemberListRegex.exec line if matchResult @onEndMemberList matchResult[1] continue matchResult = @addMemberToRoomRegex.exec line if matchResult @onAddMemberToRoom matchResult[1], matchResult[2] continue matchResult = @removeMemberFromRoomRegex.exec line if matchResult @onRemoveMemberFromRoom matchResult[1], matchResult[2] continue matchResult = @quitMemberRegex.exec line if matchResult @onQuitMember matchResult[1] continue matchResult = @successLoginMessageRegex.exec line if matchResult @onSuccessLoginMessage() continue matchResult = @failedLoginMessageRegex.exec line if matchResult @onFailedLoginMessage() continue onSuccessLoginMessage: () -> console.log '[irc] onSuccessLoginMessage -> '.yellow if @loginCb @loginCb null, @loginReq onFailedLoginMessage: () -> console.log '[irc] onFailedLoginMessage -> '.yellow @loginReq.allowed = false @disconnect() if @loginCb @loginCb null, @loginReq onReceiveMessage: (source, target, content) -> now = new Date timestamp = now.getTime() cacheKey = [source, target, content].join ',' console.log '[irc] ircSendMessageCache.get -> '.yellow, 'key:', cacheKey, 'value:', ircSendMessageCache.get(cacheKey), 'ts:', (timestamp - 1000) if ircSendMessageCache.get(cacheKey) > (timestamp - 1000) return else ircSendMessageCache.set cacheKey, timestamp console.log '[irc] onReceiveMessage -> '.yellow, 'source:', source, 'target:', target, 'content:', content source = @createUserWhenNotExist source if target[0] == '#' room = RocketChat.models.Rooms.findOneByName target.substring(1) else room = @createDirectRoomWhenNotExist(source, @user) message = msg: content ts: now cacheKey = "#{source.username}#{timestamp}" ircReceiveMessageCache.set cacheKey, true console.log '[irc] ircReceiveMessageCache.set -> '.yellow, 'key:', cacheKey RocketChat.sendMessage source, message, room onReceiveMemberList: (roomName, members) -> @receiveMemberListBuf[roomName] = @receiveMemberListBuf[roomName].concat members onEndMemberList: (roomName) -> newMembers = @receiveMemberListBuf[roomName] console.log '[irc] onEndMemberList -> '.yellow, 'room:', roomName, 'members:', newMembers.join ',' room = RocketChat.models.Rooms.findOneByNameAndType roomName, 'c' unless room return oldMembers = room.usernames appendMembers = _.difference newMembers, oldMembers removeMembers = _.difference oldMembers, newMembers for member in appendMembers @createUserWhenNotExist member RocketChat.models.Rooms.removeUsernamesById room._id, removeMembers RocketChat.models.Rooms.addUsernamesById room._id, appendMembers @isJoiningRoom = false roomName = @pendingJoinRoomBuf.shift() if roomName @joinRoom t: 'c' name: roomName sendRawMessage: (msg) -> console.log '[irc] sendRawMessage -> '.yellow, msg.slice(0, -2) if @isConnected @socket.write msg else @msgBuf.push msg sendMessage: (room, message) -> console.log '[irc] sendMessage -> '.yellow, 'userName:', message.u.username target = '' if room.t == 'c' target = "##{room.name}" else if room.t == 'd' for name in room.usernames if message.u.username != name target = name break cacheKey = [@user.username, target, message.msg].join ',' console.log '[irc] ircSendMessageCache.set -> '.yellow, 'key:', cacheKey, 'ts:', message.ts.getTime() ircSendMessageCache.set cacheKey, message.ts.getTime() msg = "PRIVMSG #{target} :#{message.msg}\r\n" @sendRawMessage msg initRoomList: -> roomsCursor = RocketChat.models.Rooms.findByTypeContainigUsername 'c', @user.username, fields: name: 1 t: 1 rooms = roomsCursor.fetch() for room in rooms @joinRoom(room) joinRoom: (room) -> if room.t isnt 'c' or room.name == 'general' return if @isJoiningRoom @pendingJoinRoomBuf.push room.name else console.log '[irc] joinRoom -> '.yellow, 'roomName:', room.name, 'pendingJoinRoomBuf:', @pendingJoinRoomBuf.join ',' msg = "JOIN ##{room.name}\r\n" @receiveMemberListBuf[room.name] = [] @sendRawMessage msg @isJoiningRoom = true leaveRoom: (room) -> if room.t isnt 'c' return msg = "PART ##{room.name}\r\n" @sendRawMessage msg getMemberList: (room) -> if room.t isnt 'c' return msg = "NAMES ##{room.name}\r\n" @receiveMemberListBuf[room.name] = [] @sendRawMessage msg onAddMemberToRoom: (member, roomName) -> if @user.username == member return console.log '[irc] onAddMemberToRoom -> '.yellow, 'roomName:', roomName, 'member:', member @createUserWhenNotExist member RocketChat.models.Rooms.addUsernameByName roomName, member onRemoveMemberFromRoom: (member, roomName)-> console.log '[irc] onRemoveMemberFromRoom -> '.yellow, 'roomName:', roomName, 'member:', member RocketChat.models.Rooms.removeUsernameByName roomName, member onQuitMember: (member) -> console.log '[irc] onQuitMember ->'.yellow, 'username:', member RocketChat.models.Rooms.removeUsernameFromAll member Meteor.users.update {name: member}, $set: status: 'offline' createUserWhenNotExist: (name) -> user = Meteor.users.findOne {name: name} unless user console.log '[irc] createNotExistUser ->'.yellow, 'userName:', name Meteor.call 'registerUser', email: PI:EMAIL:<EMAIL>END_PI" pass: 'PI:PASSWORD:<PASSWORD>END_PI' name: name Meteor.users.update {name: name}, $set: status: 'online' username: name user = Meteor.users.findOne {name: name} return user createDirectRoomWhenNotExist: (source, target) -> console.log '[irc] createDirectRoomWhenNotExist -> '.yellow, 'source:', source, 'target:', target rid = [source._id, target._id].sort().join('') now = new Date() RocketChat.models.Rooms.upsert _id: rid , $set: usernames: [source.username, target.username] $setOnInsert: t: 'd' msgs: 0 ts: now RocketChat.models.Subscriptions.upsert rid: rid $and: [{'u._id': target._id}] , $setOnInsert: name: source.username t: 'd' open: false alert: false unread: 0 u: _id: target._id username: target.username return { t: 'd' _id: rid } IrcClient.getByUid = (uid) -> return ircClientMap[uid] IrcClient.create = (login) -> unless login.user? return login unless login.user._id of ircClientMap ircClient = new IrcClient login return async ircClient.connect return login class IrcLoginer constructor: (login) -> console.log '[irc] validateLogin -> '.yellow, login return IrcClient.create login class IrcSender constructor: (message) -> name = message.u.username timestamp = message.ts.getTime() cacheKey = "#{name}#{timestamp}" if ircReceiveMessageCache.get cacheKey return message room = RocketChat.models.Rooms.findOneById message.rid, { fields: { name: 1, usernames: 1, t: 1 } } ircClient = IrcClient.getByUid message.u._id ircClient.sendMessage room, message return message class IrcRoomJoiner constructor: (user, room) -> ircClient = IrcClient.getByUid user._id ircClient.joinRoom room return room class IrcRoomLeaver constructor: (user, room) -> ircClient = IrcClient.getByUid user._id ircClient.leaveRoom room return room class IrcLogoutCleanUper constructor: (user) -> ircClient = IrcClient.getByUid user._id ircClient.disconnect() return user # # # # Make magic happen # # Only proceed if the package has been enabled if IRC_AVAILABILITY == true RocketChat.callbacks.add 'beforeValidateLogin', IrcLoginer, RocketChat.callbacks.priority.LOW, 'irc-loginer' RocketChat.callbacks.add 'beforeSaveMessage', IrcSender, RocketChat.callbacks.priority.LOW, 'irc-sender' RocketChat.callbacks.add 'beforeJoinRoom', IrcRoomJoiner, RocketChat.callbacks.priority.LOW, 'irc-room-joiner' RocketChat.callbacks.add 'beforeCreateChannel', IrcRoomJoiner, RocketChat.callbacks.priority.LOW, 'irc-room-joiner-create-channel' RocketChat.callbacks.add 'beforeLeaveRoom', IrcRoomLeaver, RocketChat.callbacks.priority.LOW, 'irc-room-leaver' RocketChat.callbacks.add 'afterLogoutCleanUp', IrcLogoutCleanUper, RocketChat.callbacks.priority.LOW, 'irc-clean-up' else return
[ { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n#", "end": 21, "score": 0.9978118538856506, "start": 14, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n# Last Update ...
node_modules/node-find-folder/gulp/clean.for.test.coffee
long-grass/mikey
0
### # Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() del = require 'del' ff = require '../index' order = ['childs_need_to_be_deteled'] cln_prefix = 'clean-' order.forEach (the) -> gulp.task cln_prefix + the, -> $.util.log 'The results of the folder to be find found: ', new ff the, nottraversal: ['.git', 'node_modules', 'backup'] ff_result = new ff the, nottraversal: ['.git', 'node_modules', 'backup'] ff_result.forEach (_item, _index, _array) -> del _item + '/*' return return return gulp.task 'clean', order.map (the) -> cln_prefix + the
72531
### # Author: iTonyYo <<EMAIL>> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <<EMAIL>> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() del = require 'del' ff = require '../index' order = ['childs_need_to_be_deteled'] cln_prefix = 'clean-' order.forEach (the) -> gulp.task cln_prefix + the, -> $.util.log 'The results of the folder to be find found: ', new ff the, nottraversal: ['.git', 'node_modules', 'backup'] ff_result = new ff the, nottraversal: ['.git', 'node_modules', 'backup'] ff_result.forEach (_item, _index, _array) -> del _item + '/*' return return return gulp.task 'clean', order.map (the) -> cln_prefix + the
true
### # Author: iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() del = require 'del' ff = require '../index' order = ['childs_need_to_be_deteled'] cln_prefix = 'clean-' order.forEach (the) -> gulp.task cln_prefix + the, -> $.util.log 'The results of the folder to be find found: ', new ff the, nottraversal: ['.git', 'node_modules', 'backup'] ff_result = new ff the, nottraversal: ['.git', 'node_modules', 'backup'] ff_result.forEach (_item, _index, _array) -> del _item + '/*' return return return gulp.task 'clean', order.map (the) -> cln_prefix + the
[ { "context": "{username:process.env.HUBOT_JENKINS_USER,password:process.env.HUBOT_JENKINS_PASSWORD},headers:{}};\n\t\t\tif crumbv", "end": 1878, "score": 0.549887478351593, "start": 1867, "tag": "PASSWORD", "value": "process.env" }, { "context": "nkins-Crumb\"] = crumbvalue\n\t\t\t\t...
scripts/jenkins/scripts-hipchat/statuscheck.coffee
akash1233/OnBot_Demo
4
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- #Description: # checks the status of jenkins job which are currently being built and notifies user once # build is finished. Job status is checked from jenkins job queue. # Main working function:checkbuildstatus # Arguments passed: chat application id of user # run_queue_list -> gets the job queue of jenkins which has the status of the jobs being built # run_job_status -> checks if build is completed. If completed then notifies user # #Configuration: # HUBOT_JENKINS_URL # HUBOT_JENKINS_USER # HUBOT_JENKINS_PASSWORD # HUBOT_JENKINS_API_TOKEN # #COMMANDS: # none # #Dependencies: # "request": "2.81.0" # "elasticSearch": "^0.9.2" # #Note: # Invoked from build.coffee and buildwithparam.coffee request = require('request') index = require('./index') jenkins_url=process.env.HUBOT_JENKINS_URL module.exports = (robot) -> module.exports.checkbuildstatus = (recipientid,jobname,crumbvalue) -> dt = '' run_job_status = () -> options = { url: jenkins_url+'/job/'+jobname+'/lastBuild/api/json', method: 'GET', auth:{username:process.env.HUBOT_JENKINS_USER,password:process.env.HUBOT_JENKINS_PASSWORD},headers:{}}; if crumbvalue!='' options.headers["Jenkins-Crumb"] = crumbvalue options.auth.pass = process.env.HUBOT_JENKINS_API_TOKEN request.get options, (error, response, body) -> body = JSON.parse(body); if body.result != "FAILURE" dt = "Build finished\n"+"Job name: "+body.fullDisplayName+"\nStatus: SUCCESS\nBuild Completion Time: "+new Date(body.timestamp) index.passData dt if !body.building robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status else if body.result == "FAILURE" dt = "Build finished\n"+"Job name: "+body.fullDisplayName+"\nStatus: "+body.result+"\nBuild Completion Time: "+new Date(body.timestamp) index.passData dt if !body.building robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status else console.log error dt = "Couldn't fetch last build status of "+jobname robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status intervalid_run_job_status = setInterval(run_job_status, 7000)
30397
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- #Description: # checks the status of jenkins job which are currently being built and notifies user once # build is finished. Job status is checked from jenkins job queue. # Main working function:checkbuildstatus # Arguments passed: chat application id of user # run_queue_list -> gets the job queue of jenkins which has the status of the jobs being built # run_job_status -> checks if build is completed. If completed then notifies user # #Configuration: # HUBOT_JENKINS_URL # HUBOT_JENKINS_USER # HUBOT_JENKINS_PASSWORD # HUBOT_JENKINS_API_TOKEN # #COMMANDS: # none # #Dependencies: # "request": "2.81.0" # "elasticSearch": "^0.9.2" # #Note: # Invoked from build.coffee and buildwithparam.coffee request = require('request') index = require('./index') jenkins_url=process.env.HUBOT_JENKINS_URL module.exports = (robot) -> module.exports.checkbuildstatus = (recipientid,jobname,crumbvalue) -> dt = '' run_job_status = () -> options = { url: jenkins_url+'/job/'+jobname+'/lastBuild/api/json', method: 'GET', auth:{username:process.env.HUBOT_JENKINS_USER,password:<PASSWORD>.HUBOT_JENKINS_PASSWORD},headers:{}}; if crumbvalue!='' options.headers["Jenkins-Crumb"] = crumbvalue options.auth.pass = <PASSWORD>.HUBOT_JENKINS_API_TOKEN request.get options, (error, response, body) -> body = JSON.parse(body); if body.result != "FAILURE" dt = "Build finished\n"+"Job name: "+body.fullDisplayName+"\nStatus: SUCCESS\nBuild Completion Time: "+new Date(body.timestamp) index.passData dt if !body.building robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status else if body.result == "FAILURE" dt = "Build finished\n"+"Job name: "+body.fullDisplayName+"\nStatus: "+body.result+"\nBuild Completion Time: "+new Date(body.timestamp) index.passData dt if !body.building robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status else console.log error dt = "Couldn't fetch last build status of "+jobname robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status intervalid_run_job_status = setInterval(run_job_status, 7000)
true
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- #Description: # checks the status of jenkins job which are currently being built and notifies user once # build is finished. Job status is checked from jenkins job queue. # Main working function:checkbuildstatus # Arguments passed: chat application id of user # run_queue_list -> gets the job queue of jenkins which has the status of the jobs being built # run_job_status -> checks if build is completed. If completed then notifies user # #Configuration: # HUBOT_JENKINS_URL # HUBOT_JENKINS_USER # HUBOT_JENKINS_PASSWORD # HUBOT_JENKINS_API_TOKEN # #COMMANDS: # none # #Dependencies: # "request": "2.81.0" # "elasticSearch": "^0.9.2" # #Note: # Invoked from build.coffee and buildwithparam.coffee request = require('request') index = require('./index') jenkins_url=process.env.HUBOT_JENKINS_URL module.exports = (robot) -> module.exports.checkbuildstatus = (recipientid,jobname,crumbvalue) -> dt = '' run_job_status = () -> options = { url: jenkins_url+'/job/'+jobname+'/lastBuild/api/json', method: 'GET', auth:{username:process.env.HUBOT_JENKINS_USER,password:PI:PASSWORD:<PASSWORD>END_PI.HUBOT_JENKINS_PASSWORD},headers:{}}; if crumbvalue!='' options.headers["Jenkins-Crumb"] = crumbvalue options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI.HUBOT_JENKINS_API_TOKEN request.get options, (error, response, body) -> body = JSON.parse(body); if body.result != "FAILURE" dt = "Build finished\n"+"Job name: "+body.fullDisplayName+"\nStatus: SUCCESS\nBuild Completion Time: "+new Date(body.timestamp) index.passData dt if !body.building robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status else if body.result == "FAILURE" dt = "Build finished\n"+"Job name: "+body.fullDisplayName+"\nStatus: "+body.result+"\nBuild Completion Time: "+new Date(body.timestamp) index.passData dt if !body.building robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status else console.log error dt = "Couldn't fetch last build status of "+jobname robot.messageRoom recipientid,dt clearInterval intervalid_run_job_status intervalid_run_job_status = setInterval(run_job_status, 7000)
[ { "context": "= new metrics.Timer(\"lock.#{namespace}\")\n\t\tkey = \"lock:web:#{namespace}:#{id}\"\n\t\tLockManager._getLock key, namespace, (error, lo", "end": 1617, "score": 0.9259598255157471, "start": 1589, "tag": "KEY", "value": "lock:web:#{namespace}:#{id}\"" } ]
app/coffee/infrastructure/LockManager.coffee
shyoshyo/web-sharelatex
1
metrics = require('metrics-sharelatex') Settings = require('settings-sharelatex') RedisWrapper = require("./RedisWrapper") rclient = RedisWrapper.client("lock") logger = require "logger-sharelatex" os = require "os" crypto = require "crypto" async = require "async" HOST = os.hostname() PID = process.pid RND = crypto.randomBytes(4).toString('hex') COUNT = 0 LOCK_QUEUES = new Map() # queue lock requests for each name/id so they get the lock on a first-come first-served basis module.exports = LockManager = LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock MAX_TEST_INTERVAL: 1000 # back off to 1s between each test of the lock MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log # Use a signed lock value as described in # http://redis.io/topics/distlock#correct-implementation-with-a-single-instance # to prevent accidental unlocking by multiple processes randomLock : () -> time = Date.now() return "locked:host=#{HOST}:pid=#{PID}:random=#{RND}:time=#{time}:count=#{COUNT++}" unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end' runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) -> # This error is defined here so we get a useful stacktrace slowExecutionError = new Error "slow execution during lock" timer = new metrics.Timer("lock.#{namespace}") key = "lock:web:#{namespace}:#{id}" LockManager._getLock key, namespace, (error, lockValue) -> return callback(error) if error? # The lock can expire in redis but the process carry on. This setTimout call # is designed to log if this happens. countIfExceededLockTimeout = () -> metrics.inc "lock.#{namespace}.exceeded_lock_timeout" logger.log "exceeded lock timeout", { namespace, id, slowExecutionError } exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 runner (error1, values...) -> LockManager._releaseLock key, lockValue, (error2) -> clearTimeout exceededLockTimeout timeTaken = new Date - timer.start if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError } timer.done() error = error1 or error2 return callback(error) if error? callback null, values... _tryLock : (key, namespace, callback = (err, isFree, lockValue)->)-> lockValue = LockManager.randomLock() rclient.set key, lockValue, "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)-> return callback(err) if err? if gotLock == "OK" metrics.inc "lock.#{namespace}.try.success" callback err, true, lockValue else metrics.inc "lock.#{namespace}.try.failed" logger.log key: key, redis_response: gotLock, "lock is locked" callback err, false # it's sufficient to serialize within a process because that is where the parallel operations occur _getLock: (key, namespace, callback = (error, lockValue) ->) -> # this is what we need to do for each lock we want to request task = (next) -> LockManager._getLockByPolling key, namespace, (error, lockValue) -> # tell the queue to start trying to get the next lock (if any) next() # we have got a lock result, so we can continue with our own execution callback(error, lockValue) # create a queue for this key if needed queueName = "#{key}:#{namespace}" queue = LOCK_QUEUES.get queueName if !queue? handler = (fn, cb) -> fn(cb) # execute any function as our task # set up a new queue for this key queue = async.queue handler, 1 queue.push task # remove the queue object when queue is empty queue.drain = () -> LOCK_QUEUES.delete queueName # store the queue in our global map LOCK_QUEUES.set queueName, queue else # queue the request to get the lock queue.push task _getLockByPolling: (key, namespace, callback = (error, lockValue) ->) -> startTime = Date.now() testInterval = LockManager.LOCK_TEST_INTERVAL attempts = 0 do attempt = () -> if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME metrics.inc "lock.#{namespace}.get.failed" return callback(new Error("Timeout")) attempts += 1 LockManager._tryLock key, namespace, (error, gotLock, lockValue) -> return callback(error) if error? if gotLock metrics.gauge "lock.#{namespace}.get.success.tries", attempts callback(null, lockValue) else setTimeout attempt, testInterval _releaseLock: (key, lockValue, callback)-> rclient.eval LockManager.unlockScript, 1, key, lockValue, (err, result) -> if err? return callback(err) else if result? and result isnt 1 # successful unlock should release exactly one key logger.error {key:key, lockValue:lockValue, redis_err:err, redis_result:result}, "unlocking error" metrics.inc "unlock-error" return callback(new Error("tried to release timed out lock")) else callback(null,result)
176902
metrics = require('metrics-sharelatex') Settings = require('settings-sharelatex') RedisWrapper = require("./RedisWrapper") rclient = RedisWrapper.client("lock") logger = require "logger-sharelatex" os = require "os" crypto = require "crypto" async = require "async" HOST = os.hostname() PID = process.pid RND = crypto.randomBytes(4).toString('hex') COUNT = 0 LOCK_QUEUES = new Map() # queue lock requests for each name/id so they get the lock on a first-come first-served basis module.exports = LockManager = LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock MAX_TEST_INTERVAL: 1000 # back off to 1s between each test of the lock MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log # Use a signed lock value as described in # http://redis.io/topics/distlock#correct-implementation-with-a-single-instance # to prevent accidental unlocking by multiple processes randomLock : () -> time = Date.now() return "locked:host=#{HOST}:pid=#{PID}:random=#{RND}:time=#{time}:count=#{COUNT++}" unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end' runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) -> # This error is defined here so we get a useful stacktrace slowExecutionError = new Error "slow execution during lock" timer = new metrics.Timer("lock.#{namespace}") key = "<KEY> LockManager._getLock key, namespace, (error, lockValue) -> return callback(error) if error? # The lock can expire in redis but the process carry on. This setTimout call # is designed to log if this happens. countIfExceededLockTimeout = () -> metrics.inc "lock.#{namespace}.exceeded_lock_timeout" logger.log "exceeded lock timeout", { namespace, id, slowExecutionError } exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 runner (error1, values...) -> LockManager._releaseLock key, lockValue, (error2) -> clearTimeout exceededLockTimeout timeTaken = new Date - timer.start if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError } timer.done() error = error1 or error2 return callback(error) if error? callback null, values... _tryLock : (key, namespace, callback = (err, isFree, lockValue)->)-> lockValue = LockManager.randomLock() rclient.set key, lockValue, "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)-> return callback(err) if err? if gotLock == "OK" metrics.inc "lock.#{namespace}.try.success" callback err, true, lockValue else metrics.inc "lock.#{namespace}.try.failed" logger.log key: key, redis_response: gotLock, "lock is locked" callback err, false # it's sufficient to serialize within a process because that is where the parallel operations occur _getLock: (key, namespace, callback = (error, lockValue) ->) -> # this is what we need to do for each lock we want to request task = (next) -> LockManager._getLockByPolling key, namespace, (error, lockValue) -> # tell the queue to start trying to get the next lock (if any) next() # we have got a lock result, so we can continue with our own execution callback(error, lockValue) # create a queue for this key if needed queueName = "#{key}:#{namespace}" queue = LOCK_QUEUES.get queueName if !queue? handler = (fn, cb) -> fn(cb) # execute any function as our task # set up a new queue for this key queue = async.queue handler, 1 queue.push task # remove the queue object when queue is empty queue.drain = () -> LOCK_QUEUES.delete queueName # store the queue in our global map LOCK_QUEUES.set queueName, queue else # queue the request to get the lock queue.push task _getLockByPolling: (key, namespace, callback = (error, lockValue) ->) -> startTime = Date.now() testInterval = LockManager.LOCK_TEST_INTERVAL attempts = 0 do attempt = () -> if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME metrics.inc "lock.#{namespace}.get.failed" return callback(new Error("Timeout")) attempts += 1 LockManager._tryLock key, namespace, (error, gotLock, lockValue) -> return callback(error) if error? if gotLock metrics.gauge "lock.#{namespace}.get.success.tries", attempts callback(null, lockValue) else setTimeout attempt, testInterval _releaseLock: (key, lockValue, callback)-> rclient.eval LockManager.unlockScript, 1, key, lockValue, (err, result) -> if err? return callback(err) else if result? and result isnt 1 # successful unlock should release exactly one key logger.error {key:key, lockValue:lockValue, redis_err:err, redis_result:result}, "unlocking error" metrics.inc "unlock-error" return callback(new Error("tried to release timed out lock")) else callback(null,result)
true
metrics = require('metrics-sharelatex') Settings = require('settings-sharelatex') RedisWrapper = require("./RedisWrapper") rclient = RedisWrapper.client("lock") logger = require "logger-sharelatex" os = require "os" crypto = require "crypto" async = require "async" HOST = os.hostname() PID = process.pid RND = crypto.randomBytes(4).toString('hex') COUNT = 0 LOCK_QUEUES = new Map() # queue lock requests for each name/id so they get the lock on a first-come first-served basis module.exports = LockManager = LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock MAX_TEST_INTERVAL: 1000 # back off to 1s between each test of the lock MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log # Use a signed lock value as described in # http://redis.io/topics/distlock#correct-implementation-with-a-single-instance # to prevent accidental unlocking by multiple processes randomLock : () -> time = Date.now() return "locked:host=#{HOST}:pid=#{PID}:random=#{RND}:time=#{time}:count=#{COUNT++}" unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end' runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) -> # This error is defined here so we get a useful stacktrace slowExecutionError = new Error "slow execution during lock" timer = new metrics.Timer("lock.#{namespace}") key = "PI:KEY:<KEY>END_PI LockManager._getLock key, namespace, (error, lockValue) -> return callback(error) if error? # The lock can expire in redis but the process carry on. This setTimout call # is designed to log if this happens. countIfExceededLockTimeout = () -> metrics.inc "lock.#{namespace}.exceeded_lock_timeout" logger.log "exceeded lock timeout", { namespace, id, slowExecutionError } exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 runner (error1, values...) -> LockManager._releaseLock key, lockValue, (error2) -> clearTimeout exceededLockTimeout timeTaken = new Date - timer.start if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError } timer.done() error = error1 or error2 return callback(error) if error? callback null, values... _tryLock : (key, namespace, callback = (err, isFree, lockValue)->)-> lockValue = LockManager.randomLock() rclient.set key, lockValue, "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)-> return callback(err) if err? if gotLock == "OK" metrics.inc "lock.#{namespace}.try.success" callback err, true, lockValue else metrics.inc "lock.#{namespace}.try.failed" logger.log key: key, redis_response: gotLock, "lock is locked" callback err, false # it's sufficient to serialize within a process because that is where the parallel operations occur _getLock: (key, namespace, callback = (error, lockValue) ->) -> # this is what we need to do for each lock we want to request task = (next) -> LockManager._getLockByPolling key, namespace, (error, lockValue) -> # tell the queue to start trying to get the next lock (if any) next() # we have got a lock result, so we can continue with our own execution callback(error, lockValue) # create a queue for this key if needed queueName = "#{key}:#{namespace}" queue = LOCK_QUEUES.get queueName if !queue? handler = (fn, cb) -> fn(cb) # execute any function as our task # set up a new queue for this key queue = async.queue handler, 1 queue.push task # remove the queue object when queue is empty queue.drain = () -> LOCK_QUEUES.delete queueName # store the queue in our global map LOCK_QUEUES.set queueName, queue else # queue the request to get the lock queue.push task _getLockByPolling: (key, namespace, callback = (error, lockValue) ->) -> startTime = Date.now() testInterval = LockManager.LOCK_TEST_INTERVAL attempts = 0 do attempt = () -> if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME metrics.inc "lock.#{namespace}.get.failed" return callback(new Error("Timeout")) attempts += 1 LockManager._tryLock key, namespace, (error, gotLock, lockValue) -> return callback(error) if error? if gotLock metrics.gauge "lock.#{namespace}.get.success.tries", attempts callback(null, lockValue) else setTimeout attempt, testInterval _releaseLock: (key, lockValue, callback)-> rclient.eval LockManager.unlockScript, 1, key, lockValue, (err, result) -> if err? return callback(err) else if result? and result isnt 1 # successful unlock should release exactly one key logger.error {key:key, lockValue:lockValue, redis_err:err, redis_result:result}, "unlocking error" metrics.inc "unlock-error" return callback(new Error("tried to release timed out lock")) else callback(null,result)
[ { "context": "gramming for microcontrollers\n# Copyright (c) 2014 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely dist", "end": 90, "score": 0.9997788071632385, "start": 80, "tag": "NAME", "value": "Jon Nordby" }, { "context": "microcontrollers\n# Copyright (c) 2014 Jon Nord...
lib/serial.coffee
microflo/microflo
136
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2014 Jon Nordby <jononor@gmail.com> # MicroFlo may be freely distributed under the MIT license ### util = require './util' if util.isBrowser() # Requires Chrome APIs and permissions if 'chrome' in window and 'serial' in window.chrome serial = window.chrome.serial else SerialPort = require 'serialport' isLikelyArduinoSerial = (e) -> e.comName.indexOf('usbserial') != -1 or e.comName.indexOf('usbmodem') != -1 guessSerialPort = (wantedPortName, callback) -> SerialPort.list (err, ports) -> if err callback err return else if ports.length == 0 return callback null, null, [] p = undefined ports.forEach (port) -> if wantedPortName and wantedPortName != 'auto' and wantedPortName == port.comName p = port.comName return if p callback err, p, ports return else if wantedPortName and wantedPortName != 'auto' console.log 'WARN: unable to find serial port: ', wantedPortName preferred = ports.filter(isLikelyArduinoSerial) p = if preferred.length > 0 then preferred[0].comName else ports[0].comName callback err, p, ports return return getSerial = (serialPortToUse, baudRate, cb) -> if not cb cb = (err) -> console.error 'Warning: Missing callback for getSerial()' console.log 'Using serial baudrate with ' + serialPortToUse, baudRate serial = null guessSerialPort serialPortToUse, (err, portName, ports) -> if serialPortToUse.indexOf('.microflo') != -1 portName = serialPortToUse if err console.log 'Error detecting serial port: ', err return cb err, null else if not portName return cb new Error "No serial port found" if err ports = ports.map (item) -> item.comName console.log 'Using port: ' + portName console.log 'Available serial ports: ', JSON.stringify(ports, null, null) serial = new SerialPort portName, { baudRate: baudRate }, (err) -> return cb err, serial serial.getTransportType = -> 'Serial' return -> serial listChromeSerial = (callback) -> f = (ports) -> devices = [] i = 0 while i < ports.length port = ports[i] if port.path.search('/dev/ttyS') != -1 i++ continue devices.push port.path i++ callback devices chrome.serial.getDevices f return listNodeSerial = (callback) -> throw new Error('listNodeSerial: Not implemented') return getChromeSerial = (serialPortToUse, baudRate, readyCallback) -> # Hacky API compat with node-serialport subset that we use transport = {} transport.connectionId = null transport.listeners = 'data': null transport.write = (data, callback) -> #console.log("Trying to send: ", data); data = util.bufferToArrayBuffer(data) #console.log("Sending", util.arrayBufferToString(data)); chrome.serial.send transport.connectionId, data, (sendinfo, error) -> #console.log("Attempted send: ", sendinfo, error); if typeof callback != 'undefined' callback error, sendinfo return return transport.close = (callback) -> if !transport.connectionId return chrome.serial.disconnect transport.connectionId, callback return transport.removeAllListeners = (event) -> transport.listeners[event] = null return transport.on = (event, callback) -> transport.listeners[event] = callback return transport.emit = (event, arg) -> cb = transport.listeners[event] if cb cb arg return transport.getTransportType = -> 'Serial' onConnect = (connectionInfo) -> if connectionInfo transport.connectionId = connectionInfo.connectionId readyCallback null, transport else e = new Error('Could not connect to serialport') readyCallback e, null onReceiveCallback = (info) -> if info.connectionId == connectionId and info.data data = util.arrayBufferToBuffer(info.data) #console.log("received", data); transport.emit 'data', data return chrome.serial.onReceive.addListener onReceiveCallback chrome.serial.connect serialPortToUse, { 'bitrate': baudRate }, onConnect -> transport isSupported = -> util.isBrowser() and 'chrome' in window and 'serial' in window.chrome or !util.isBrowser() if util.isBrowser() module.exports.listDevices = listChromeSerial module.exports.openTransport = getChromeSerial else module.exports.listDevices = listNodeSerial module.exports.openTransport = getSerial module.exports.isSupported = isSupported
78898
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2014 <NAME> <<EMAIL>> # MicroFlo may be freely distributed under the MIT license ### util = require './util' if util.isBrowser() # Requires Chrome APIs and permissions if 'chrome' in window and 'serial' in window.chrome serial = window.chrome.serial else SerialPort = require 'serialport' isLikelyArduinoSerial = (e) -> e.comName.indexOf('usbserial') != -1 or e.comName.indexOf('usbmodem') != -1 guessSerialPort = (wantedPortName, callback) -> SerialPort.list (err, ports) -> if err callback err return else if ports.length == 0 return callback null, null, [] p = undefined ports.forEach (port) -> if wantedPortName and wantedPortName != 'auto' and wantedPortName == port.comName p = port.comName return if p callback err, p, ports return else if wantedPortName and wantedPortName != 'auto' console.log 'WARN: unable to find serial port: ', wantedPortName preferred = ports.filter(isLikelyArduinoSerial) p = if preferred.length > 0 then preferred[0].comName else ports[0].comName callback err, p, ports return return getSerial = (serialPortToUse, baudRate, cb) -> if not cb cb = (err) -> console.error 'Warning: Missing callback for getSerial()' console.log 'Using serial baudrate with ' + serialPortToUse, baudRate serial = null guessSerialPort serialPortToUse, (err, portName, ports) -> if serialPortToUse.indexOf('.microflo') != -1 portName = serialPortToUse if err console.log 'Error detecting serial port: ', err return cb err, null else if not portName return cb new Error "No serial port found" if err ports = ports.map (item) -> item.comName console.log 'Using port: ' + portName console.log 'Available serial ports: ', JSON.stringify(ports, null, null) serial = new SerialPort portName, { baudRate: baudRate }, (err) -> return cb err, serial serial.getTransportType = -> 'Serial' return -> serial listChromeSerial = (callback) -> f = (ports) -> devices = [] i = 0 while i < ports.length port = ports[i] if port.path.search('/dev/ttyS') != -1 i++ continue devices.push port.path i++ callback devices chrome.serial.getDevices f return listNodeSerial = (callback) -> throw new Error('listNodeSerial: Not implemented') return getChromeSerial = (serialPortToUse, baudRate, readyCallback) -> # Hacky API compat with node-serialport subset that we use transport = {} transport.connectionId = null transport.listeners = 'data': null transport.write = (data, callback) -> #console.log("Trying to send: ", data); data = util.bufferToArrayBuffer(data) #console.log("Sending", util.arrayBufferToString(data)); chrome.serial.send transport.connectionId, data, (sendinfo, error) -> #console.log("Attempted send: ", sendinfo, error); if typeof callback != 'undefined' callback error, sendinfo return return transport.close = (callback) -> if !transport.connectionId return chrome.serial.disconnect transport.connectionId, callback return transport.removeAllListeners = (event) -> transport.listeners[event] = null return transport.on = (event, callback) -> transport.listeners[event] = callback return transport.emit = (event, arg) -> cb = transport.listeners[event] if cb cb arg return transport.getTransportType = -> 'Serial' onConnect = (connectionInfo) -> if connectionInfo transport.connectionId = connectionInfo.connectionId readyCallback null, transport else e = new Error('Could not connect to serialport') readyCallback e, null onReceiveCallback = (info) -> if info.connectionId == connectionId and info.data data = util.arrayBufferToBuffer(info.data) #console.log("received", data); transport.emit 'data', data return chrome.serial.onReceive.addListener onReceiveCallback chrome.serial.connect serialPortToUse, { 'bitrate': baudRate }, onConnect -> transport isSupported = -> util.isBrowser() and 'chrome' in window and 'serial' in window.chrome or !util.isBrowser() if util.isBrowser() module.exports.listDevices = listChromeSerial module.exports.openTransport = getChromeSerial else module.exports.listDevices = listNodeSerial module.exports.openTransport = getSerial module.exports.isSupported = isSupported
true
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # MicroFlo may be freely distributed under the MIT license ### util = require './util' if util.isBrowser() # Requires Chrome APIs and permissions if 'chrome' in window and 'serial' in window.chrome serial = window.chrome.serial else SerialPort = require 'serialport' isLikelyArduinoSerial = (e) -> e.comName.indexOf('usbserial') != -1 or e.comName.indexOf('usbmodem') != -1 guessSerialPort = (wantedPortName, callback) -> SerialPort.list (err, ports) -> if err callback err return else if ports.length == 0 return callback null, null, [] p = undefined ports.forEach (port) -> if wantedPortName and wantedPortName != 'auto' and wantedPortName == port.comName p = port.comName return if p callback err, p, ports return else if wantedPortName and wantedPortName != 'auto' console.log 'WARN: unable to find serial port: ', wantedPortName preferred = ports.filter(isLikelyArduinoSerial) p = if preferred.length > 0 then preferred[0].comName else ports[0].comName callback err, p, ports return return getSerial = (serialPortToUse, baudRate, cb) -> if not cb cb = (err) -> console.error 'Warning: Missing callback for getSerial()' console.log 'Using serial baudrate with ' + serialPortToUse, baudRate serial = null guessSerialPort serialPortToUse, (err, portName, ports) -> if serialPortToUse.indexOf('.microflo') != -1 portName = serialPortToUse if err console.log 'Error detecting serial port: ', err return cb err, null else if not portName return cb new Error "No serial port found" if err ports = ports.map (item) -> item.comName console.log 'Using port: ' + portName console.log 'Available serial ports: ', JSON.stringify(ports, null, null) serial = new SerialPort portName, { baudRate: baudRate }, (err) -> return cb err, serial serial.getTransportType = -> 'Serial' return -> serial listChromeSerial = (callback) -> f = (ports) -> devices = [] i = 0 while i < ports.length port = ports[i] if port.path.search('/dev/ttyS') != -1 i++ continue devices.push port.path i++ callback devices chrome.serial.getDevices f return listNodeSerial = (callback) -> throw new Error('listNodeSerial: Not implemented') return getChromeSerial = (serialPortToUse, baudRate, readyCallback) -> # Hacky API compat with node-serialport subset that we use transport = {} transport.connectionId = null transport.listeners = 'data': null transport.write = (data, callback) -> #console.log("Trying to send: ", data); data = util.bufferToArrayBuffer(data) #console.log("Sending", util.arrayBufferToString(data)); chrome.serial.send transport.connectionId, data, (sendinfo, error) -> #console.log("Attempted send: ", sendinfo, error); if typeof callback != 'undefined' callback error, sendinfo return return transport.close = (callback) -> if !transport.connectionId return chrome.serial.disconnect transport.connectionId, callback return transport.removeAllListeners = (event) -> transport.listeners[event] = null return transport.on = (event, callback) -> transport.listeners[event] = callback return transport.emit = (event, arg) -> cb = transport.listeners[event] if cb cb arg return transport.getTransportType = -> 'Serial' onConnect = (connectionInfo) -> if connectionInfo transport.connectionId = connectionInfo.connectionId readyCallback null, transport else e = new Error('Could not connect to serialport') readyCallback e, null onReceiveCallback = (info) -> if info.connectionId == connectionId and info.data data = util.arrayBufferToBuffer(info.data) #console.log("received", data); transport.emit 'data', data return chrome.serial.onReceive.addListener onReceiveCallback chrome.serial.connect serialPortToUse, { 'bitrate': baudRate }, onConnect -> transport isSupported = -> util.isBrowser() and 'chrome' in window and 'serial' in window.chrome or !util.isBrowser() if util.isBrowser() module.exports.listDevices = listChromeSerial module.exports.openTransport = getChromeSerial else module.exports.listDevices = listNodeSerial module.exports.openTransport = getSerial module.exports.isSupported = isSupported
[ { "context": "=\n brand: 'Rainbow'\n name: 'Lisa Doe' # those which uses i18n directive can not be rep", "end": 259, "score": 0.9998858571052551, "start": 251, "tag": "NAME", "value": "Lisa Doe" } ]
rainbow-v1.2/rainbow/client/scripts/shared/main.coffee
DigitalWant/K11
0
'use strict'; angular.module('app.controllers', []) # overall control .controller('AppCtrl', [ '$scope', '$rootScope' ($scope, $rootScope) -> $window = $(window) $scope.main = brand: 'Rainbow' name: 'Lisa Doe' # those which uses i18n directive can not be replaced for now. $scope.pageTransitionOpts = [ name: 'Scale up' class: 'ainmate-scale-up' , name: 'Fade up' class: 'animate-fade-up' , name: 'Slide in from right' class: 'ainmate-slide-in-right' , name: 'Flip Y' class: 'animate-flip-y' ] $scope.admin = layout: 'wide' # 'boxed', 'wide' menu: 'vertical' # 'horizontal', 'vertical' fixedHeader: true # true, false fixedSidebar: false # true, false pageTransition: $scope.pageTransitionOpts[0] # unlimited, check out "_animation.scss" $scope.$watch('admin', (newVal, oldVal) -> # manually trigger resize event to force morris charts to resize, a significant performance impact, enable for demo purpose only # if newVal.menu isnt oldVal.menu || newVal.layout isnt oldVal.layout # $window.trigger('resize') if newVal.menu is 'horizontal' && oldVal.menu is 'vertical' $rootScope.$broadcast('nav:reset') return if newVal.fixedHeader is false && newVal.fixedSidebar is true if oldVal.fixedHeader is false && oldVal.fixedSidebar is false $scope.admin.fixedHeader = true $scope.admin.fixedSidebar = true if oldVal.fixedHeader is true && oldVal.fixedSidebar is true $scope.admin.fixedHeader = false $scope.admin.fixedSidebar = false return if newVal.fixedSidebar is true $scope.admin.fixedHeader = true if newVal.fixedHeader is false $scope.admin.fixedSidebar = false return , true) $scope.color = primary: '#248AAF' success: '#3CBC8D' info: '#29B7D3' infoAlt: '#666699' warning: '#FAC552' danger: '#E9422E' ]) .controller('HeaderCtrl', [ '$scope' ($scope) -> ]) .controller('NavContainerCtrl', [ '$scope' ($scope) -> ]) .controller('NavCtrl', [ '$scope', 'taskStorage', 'filterFilter' ($scope, taskStorage, filterFilter) -> # init tasks = $scope.tasks = taskStorage.get() $scope.taskRemainingCount = filterFilter(tasks, {completed: false}).length $scope.$on('taskRemaining:changed', (event, count) -> $scope.taskRemainingCount = count ) ]) .controller('DashboardCtrl', [ '$scope' ($scope) -> ])
154537
'use strict'; angular.module('app.controllers', []) # overall control .controller('AppCtrl', [ '$scope', '$rootScope' ($scope, $rootScope) -> $window = $(window) $scope.main = brand: 'Rainbow' name: '<NAME>' # those which uses i18n directive can not be replaced for now. $scope.pageTransitionOpts = [ name: 'Scale up' class: 'ainmate-scale-up' , name: 'Fade up' class: 'animate-fade-up' , name: 'Slide in from right' class: 'ainmate-slide-in-right' , name: 'Flip Y' class: 'animate-flip-y' ] $scope.admin = layout: 'wide' # 'boxed', 'wide' menu: 'vertical' # 'horizontal', 'vertical' fixedHeader: true # true, false fixedSidebar: false # true, false pageTransition: $scope.pageTransitionOpts[0] # unlimited, check out "_animation.scss" $scope.$watch('admin', (newVal, oldVal) -> # manually trigger resize event to force morris charts to resize, a significant performance impact, enable for demo purpose only # if newVal.menu isnt oldVal.menu || newVal.layout isnt oldVal.layout # $window.trigger('resize') if newVal.menu is 'horizontal' && oldVal.menu is 'vertical' $rootScope.$broadcast('nav:reset') return if newVal.fixedHeader is false && newVal.fixedSidebar is true if oldVal.fixedHeader is false && oldVal.fixedSidebar is false $scope.admin.fixedHeader = true $scope.admin.fixedSidebar = true if oldVal.fixedHeader is true && oldVal.fixedSidebar is true $scope.admin.fixedHeader = false $scope.admin.fixedSidebar = false return if newVal.fixedSidebar is true $scope.admin.fixedHeader = true if newVal.fixedHeader is false $scope.admin.fixedSidebar = false return , true) $scope.color = primary: '#248AAF' success: '#3CBC8D' info: '#29B7D3' infoAlt: '#666699' warning: '#FAC552' danger: '#E9422E' ]) .controller('HeaderCtrl', [ '$scope' ($scope) -> ]) .controller('NavContainerCtrl', [ '$scope' ($scope) -> ]) .controller('NavCtrl', [ '$scope', 'taskStorage', 'filterFilter' ($scope, taskStorage, filterFilter) -> # init tasks = $scope.tasks = taskStorage.get() $scope.taskRemainingCount = filterFilter(tasks, {completed: false}).length $scope.$on('taskRemaining:changed', (event, count) -> $scope.taskRemainingCount = count ) ]) .controller('DashboardCtrl', [ '$scope' ($scope) -> ])
true
'use strict'; angular.module('app.controllers', []) # overall control .controller('AppCtrl', [ '$scope', '$rootScope' ($scope, $rootScope) -> $window = $(window) $scope.main = brand: 'Rainbow' name: 'PI:NAME:<NAME>END_PI' # those which uses i18n directive can not be replaced for now. $scope.pageTransitionOpts = [ name: 'Scale up' class: 'ainmate-scale-up' , name: 'Fade up' class: 'animate-fade-up' , name: 'Slide in from right' class: 'ainmate-slide-in-right' , name: 'Flip Y' class: 'animate-flip-y' ] $scope.admin = layout: 'wide' # 'boxed', 'wide' menu: 'vertical' # 'horizontal', 'vertical' fixedHeader: true # true, false fixedSidebar: false # true, false pageTransition: $scope.pageTransitionOpts[0] # unlimited, check out "_animation.scss" $scope.$watch('admin', (newVal, oldVal) -> # manually trigger resize event to force morris charts to resize, a significant performance impact, enable for demo purpose only # if newVal.menu isnt oldVal.menu || newVal.layout isnt oldVal.layout # $window.trigger('resize') if newVal.menu is 'horizontal' && oldVal.menu is 'vertical' $rootScope.$broadcast('nav:reset') return if newVal.fixedHeader is false && newVal.fixedSidebar is true if oldVal.fixedHeader is false && oldVal.fixedSidebar is false $scope.admin.fixedHeader = true $scope.admin.fixedSidebar = true if oldVal.fixedHeader is true && oldVal.fixedSidebar is true $scope.admin.fixedHeader = false $scope.admin.fixedSidebar = false return if newVal.fixedSidebar is true $scope.admin.fixedHeader = true if newVal.fixedHeader is false $scope.admin.fixedSidebar = false return , true) $scope.color = primary: '#248AAF' success: '#3CBC8D' info: '#29B7D3' infoAlt: '#666699' warning: '#FAC552' danger: '#E9422E' ]) .controller('HeaderCtrl', [ '$scope' ($scope) -> ]) .controller('NavContainerCtrl', [ '$scope' ($scope) -> ]) .controller('NavCtrl', [ '$scope', 'taskStorage', 'filterFilter' ($scope, taskStorage, filterFilter) -> # init tasks = $scope.tasks = taskStorage.get() $scope.taskRemainingCount = filterFilter(tasks, {completed: false}).length $scope.$on('taskRemaining:changed', (event, count) -> $scope.taskRemainingCount = count ) ]) .controller('DashboardCtrl', [ '$scope' ($scope) -> ])
[ { "context": "key: 'pandoc'\npatterns: [\n\n # grid_tables extension\n {\n n", "end": 12, "score": 0.9987005591392517, "start": 6, "tag": "KEY", "value": "pandoc" } ]
grammars/repositories/flavors/pandoc.cson
doc22940/language-markdown
138
key: 'pandoc' patterns: [ # grid_tables extension { name: 'table.storage.md' match: '^(\\+-+)+\\+$' captures: 0: name: 'punctuation.md' } # grid_tables extension: head/body separator { name: 'table.storage.md' match: '^(\\+=+)+\\+$' captures: 0: name: 'punctuation.md' } ]
160261
key: '<KEY>' patterns: [ # grid_tables extension { name: 'table.storage.md' match: '^(\\+-+)+\\+$' captures: 0: name: 'punctuation.md' } # grid_tables extension: head/body separator { name: 'table.storage.md' match: '^(\\+=+)+\\+$' captures: 0: name: 'punctuation.md' } ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ # grid_tables extension { name: 'table.storage.md' match: '^(\\+-+)+\\+$' captures: 0: name: 'punctuation.md' } # grid_tables extension: head/body separator { name: 'table.storage.md' match: '^(\\+=+)+\\+$' captures: 0: name: 'punctuation.md' } ]
[ { "context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ", "end": 33, "score": 0.9998700022697449, "start": 21, "tag": "NAME", "value": "John Judnich" } ]
source/NearMapGenerator.coffee
anandprabhakar0507/Kosmos
46
# Copyright (C) 2013 John Judnich # Released under The MIT License - see "LICENSE" file for details. root = exports ? this class root.NearMapGenerator constructor: (mapResolution) -> # load shaders @heightGenShader = [] for i in [0 .. kosmosShaderHeightFunctions.length-1] @heightGenShader[i] = xgl.loadProgram("nearMapGenerator" + i) @heightGenShader[i].uniforms = xgl.getProgramUniforms(@heightGenShader[i], ["verticalViewport", "randomSeed"]) @heightGenShader[i].attribs = xgl.getProgramAttribs(@heightGenShader[i], ["aUV", "aPos", "aTangent", "aBinormal"]) @normalGenShader = xgl.loadProgram("normalMapGenerator") @normalGenShader.uniforms = xgl.getProgramUniforms(@normalGenShader, ["verticalViewport", "sampler"]) @normalGenShader.attribs = xgl.getProgramAttribs(@normalGenShader, ["aUV", "aPos", "aTangent", "aBinormal"]) # initialize FBO @fbo = gl.createFramebuffer() gl.bindFramebuffer(gl.FRAMEBUFFER, @fbo) @fbo.width = mapResolution @fbo.height = mapResolution console.log("Initialized high resolution planet map generator FBO at #{@fbo.width} x #{@fbo.height}") gl.bindFramebuffer(gl.FRAMEBUFFER, null) # create fullscreen quad vertices buff = new Float32Array(6*6*11) i = 0 tangent = [0, 0, 0] binormal = [0, 0, 0] for faceIndex in [0..5] for uv in [[0,0], [1,0], [0,1], [1,0], [1,1], [0,1]] pos = mapPlaneToCube(uv[0], uv[1], faceIndex) buff[i++] = uv[0]; buff[i++] = uv[1] buff[i++] = pos[0]; buff[i++] = pos[1]; buff[i++] = pos[2] posU = mapPlaneToCube(uv[0]+1, uv[1], faceIndex) posV = mapPlaneToCube(uv[0], uv[1]+1, faceIndex) binormal = [posU[0]-pos[0], posU[1]-pos[1], posU[2]-pos[2]] tangent = [posV[0]-pos[0], posV[1]-pos[1], posV[2]-pos[2]] buff[i++] = binormal[0]; buff[i++] = binormal[1]; buff[i++] = binormal[2] buff[i++] = tangent[0]; buff[i++] = tangent[1]; buff[i++] = tangent[2] @quadVerts = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts); gl.bufferData(gl.ARRAY_BUFFER, buff, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, null) @quadVerts.itemSize = 11 @quadVerts.numItems = buff.length / @quadVerts.itemSize # call this before making call(s) to generateSubMap start: -> gl.disable(gl.DEPTH_TEST) gl.depthMask(false) gl.bindFramebuffer(gl.FRAMEBUFFER, @fbo) gl.viewport(0, 0, @fbo.width, @fbo.height) gl.enableVertexAttribArray(@normalGenShader.attribs.aUV) gl.enableVertexAttribArray(@normalGenShader.attribs.aPos) gl.enableVertexAttribArray(@normalGenShader.attribs.aBinormal) gl.enableVertexAttribArray(@normalGenShader.attribs.aTangent) gl.enable(gl.SCISSOR_TEST) # call this after making call(s) to generateSubMap finish: -> gl.disable(gl.SCISSOR_TEST) gl.disableVertexAttribArray(@normalGenShader.attribs.aUV) gl.disableVertexAttribArray(@normalGenShader.attribs.aPos) gl.disableVertexAttribArray(@normalGenShader.attribs.aBinormal) gl.disableVertexAttribArray(@normalGenShader.attribs.aTangent) gl.bindBuffer(gl.ARRAY_BUFFER, null) gl.bindFramebuffer(gl.FRAMEBUFFER, null) gl.useProgram(null) gl.depthMask(true) gl.enable(gl.DEPTH_TEST) # Creates and returns a list of SEVEN opengl textures: six for each face of the planet cube, and one # for temporary heightmap storage before normal maps are generated for the finalized map. createMaps: -> maps = [] for face in [0..6] maps[face] = gl.createTexture() gl.bindTexture(gl.TEXTURE_2D, maps[face]) if face < 6 #gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) else gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, @fbo.width, @fbo.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null) gl.bindTexture(gl.TEXTURE_2D, null) return maps # Takes the heightmap generated at maps[6] and outputs the final data map containing # normals/color/height/etc. to maps[faceIndex]. This assumes generateSubMap() has finished # generating all of the heightmap for the SAME faceIndex (so generate only one face at a time # between the two function). Partial generation is allowed via start/endFraction ranging [0,1] generateSubFinalMap: (maps, seed, faceIndex, startFraction, endFraction) -> # select the normal map generation program gl.useProgram(@normalGenShader) gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts) gl.vertexAttribPointer(@normalGenShader.attribs.aUV, 2, gl.FLOAT, false, @quadVerts.itemSize*4, 0) gl.vertexAttribPointer(@normalGenShader.attribs.aPos, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *2) gl.vertexAttribPointer(@normalGenShader.attribs.aBinormal, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *5) gl.vertexAttribPointer(@normalGenShader.attribs.aTangent, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *8) # bind the heightmap input gl.activeTexture(gl.TEXTURE0) gl.bindTexture(gl.TEXTURE_2D, maps[6]) gl.uniform1i(@normalGenShader.uniforms.sampler, 0); # bind the appropriate face map texture dataMap = maps[faceIndex] gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataMap, 0) # select the subset of the viewport to generate gl.viewport(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.scissor(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.uniform2f(@normalGenShader.uniforms.verticalViewport, startFraction, endFraction - startFraction); # run the generation shader indicesPerFace = @quadVerts.numItems / 6 gl.drawArrays(gl.TRIANGLES, indicesPerFace * faceIndex, indicesPerFace); gl.bindTexture(gl.TEXTURE_2D, null) # generates a heightmap output to maps[6], for later processing by generateSubFinalMap # for face faceIndex. partial generation is allowed via start/endFraction ranging [0,1] generateSubMap: (maps, seed, faceIndex, startFraction, endFraction) -> # setup seed values rndStr = new RandomStream(seed) seeds = [rndStr.unit(), rndStr.unit(), rndStr.unit()] shaderIndex = rndStr.intRange(0, kosmosShaderHeightFunctions.length-1) # set shader from seed gl.useProgram(@heightGenShader[shaderIndex]) gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aUV, 2, gl.FLOAT, false, @quadVerts.itemSize*4, 0) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aPos, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *2) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aBinormal, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *5) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aTangent, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *8) gl.uniform3fv(@heightGenShader[shaderIndex].uniforms.randomSeed, seeds) # bind the appropriate face map texture dataMap = maps[6] gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataMap, 0) # select the subset of the viewport to generate gl.viewport(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.scissor(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.uniform2f(@heightGenShader[shaderIndex].uniforms.verticalViewport, startFraction, endFraction - startFraction); # run the generation shader indicesPerFace = @quadVerts.numItems / 6 gl.drawArrays(gl.TRIANGLES, indicesPerFace * faceIndex, indicesPerFace); # call this to finalize map generation finalizeMaps: (maps) -> # note: it seems generating mipmaps leads to some glitches either in intel HD 4000 or webgl, # causing MAJOR permanent lag for the remainder of the program, and this occurs RANDOMLY. # impossible to know when, and impossible to predict. so I've disabled this. FORTUNATELY, # it turns out for whatever reason, disabling mipmaps entirely looks great with no visible pixel # shimmer on my retina macbook at least, most likely because the high res maps are used only # when you're near the planet anyway, thus effectively being a sort of manual objectwide mipmap anyway. #for i in [0..5] # gl.bindTexture(gl.TEXTURE_2D, maps[i]) # gl.generateMipmap(gl.TEXTURE_2D) #gl.bindTexture(gl.TEXTURE_2D, null) delete maps[6]
83821
# Copyright (C) 2013 <NAME> # Released under The MIT License - see "LICENSE" file for details. root = exports ? this class root.NearMapGenerator constructor: (mapResolution) -> # load shaders @heightGenShader = [] for i in [0 .. kosmosShaderHeightFunctions.length-1] @heightGenShader[i] = xgl.loadProgram("nearMapGenerator" + i) @heightGenShader[i].uniforms = xgl.getProgramUniforms(@heightGenShader[i], ["verticalViewport", "randomSeed"]) @heightGenShader[i].attribs = xgl.getProgramAttribs(@heightGenShader[i], ["aUV", "aPos", "aTangent", "aBinormal"]) @normalGenShader = xgl.loadProgram("normalMapGenerator") @normalGenShader.uniforms = xgl.getProgramUniforms(@normalGenShader, ["verticalViewport", "sampler"]) @normalGenShader.attribs = xgl.getProgramAttribs(@normalGenShader, ["aUV", "aPos", "aTangent", "aBinormal"]) # initialize FBO @fbo = gl.createFramebuffer() gl.bindFramebuffer(gl.FRAMEBUFFER, @fbo) @fbo.width = mapResolution @fbo.height = mapResolution console.log("Initialized high resolution planet map generator FBO at #{@fbo.width} x #{@fbo.height}") gl.bindFramebuffer(gl.FRAMEBUFFER, null) # create fullscreen quad vertices buff = new Float32Array(6*6*11) i = 0 tangent = [0, 0, 0] binormal = [0, 0, 0] for faceIndex in [0..5] for uv in [[0,0], [1,0], [0,1], [1,0], [1,1], [0,1]] pos = mapPlaneToCube(uv[0], uv[1], faceIndex) buff[i++] = uv[0]; buff[i++] = uv[1] buff[i++] = pos[0]; buff[i++] = pos[1]; buff[i++] = pos[2] posU = mapPlaneToCube(uv[0]+1, uv[1], faceIndex) posV = mapPlaneToCube(uv[0], uv[1]+1, faceIndex) binormal = [posU[0]-pos[0], posU[1]-pos[1], posU[2]-pos[2]] tangent = [posV[0]-pos[0], posV[1]-pos[1], posV[2]-pos[2]] buff[i++] = binormal[0]; buff[i++] = binormal[1]; buff[i++] = binormal[2] buff[i++] = tangent[0]; buff[i++] = tangent[1]; buff[i++] = tangent[2] @quadVerts = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts); gl.bufferData(gl.ARRAY_BUFFER, buff, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, null) @quadVerts.itemSize = 11 @quadVerts.numItems = buff.length / @quadVerts.itemSize # call this before making call(s) to generateSubMap start: -> gl.disable(gl.DEPTH_TEST) gl.depthMask(false) gl.bindFramebuffer(gl.FRAMEBUFFER, @fbo) gl.viewport(0, 0, @fbo.width, @fbo.height) gl.enableVertexAttribArray(@normalGenShader.attribs.aUV) gl.enableVertexAttribArray(@normalGenShader.attribs.aPos) gl.enableVertexAttribArray(@normalGenShader.attribs.aBinormal) gl.enableVertexAttribArray(@normalGenShader.attribs.aTangent) gl.enable(gl.SCISSOR_TEST) # call this after making call(s) to generateSubMap finish: -> gl.disable(gl.SCISSOR_TEST) gl.disableVertexAttribArray(@normalGenShader.attribs.aUV) gl.disableVertexAttribArray(@normalGenShader.attribs.aPos) gl.disableVertexAttribArray(@normalGenShader.attribs.aBinormal) gl.disableVertexAttribArray(@normalGenShader.attribs.aTangent) gl.bindBuffer(gl.ARRAY_BUFFER, null) gl.bindFramebuffer(gl.FRAMEBUFFER, null) gl.useProgram(null) gl.depthMask(true) gl.enable(gl.DEPTH_TEST) # Creates and returns a list of SEVEN opengl textures: six for each face of the planet cube, and one # for temporary heightmap storage before normal maps are generated for the finalized map. createMaps: -> maps = [] for face in [0..6] maps[face] = gl.createTexture() gl.bindTexture(gl.TEXTURE_2D, maps[face]) if face < 6 #gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) else gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, @fbo.width, @fbo.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null) gl.bindTexture(gl.TEXTURE_2D, null) return maps # Takes the heightmap generated at maps[6] and outputs the final data map containing # normals/color/height/etc. to maps[faceIndex]. This assumes generateSubMap() has finished # generating all of the heightmap for the SAME faceIndex (so generate only one face at a time # between the two function). Partial generation is allowed via start/endFraction ranging [0,1] generateSubFinalMap: (maps, seed, faceIndex, startFraction, endFraction) -> # select the normal map generation program gl.useProgram(@normalGenShader) gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts) gl.vertexAttribPointer(@normalGenShader.attribs.aUV, 2, gl.FLOAT, false, @quadVerts.itemSize*4, 0) gl.vertexAttribPointer(@normalGenShader.attribs.aPos, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *2) gl.vertexAttribPointer(@normalGenShader.attribs.aBinormal, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *5) gl.vertexAttribPointer(@normalGenShader.attribs.aTangent, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *8) # bind the heightmap input gl.activeTexture(gl.TEXTURE0) gl.bindTexture(gl.TEXTURE_2D, maps[6]) gl.uniform1i(@normalGenShader.uniforms.sampler, 0); # bind the appropriate face map texture dataMap = maps[faceIndex] gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataMap, 0) # select the subset of the viewport to generate gl.viewport(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.scissor(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.uniform2f(@normalGenShader.uniforms.verticalViewport, startFraction, endFraction - startFraction); # run the generation shader indicesPerFace = @quadVerts.numItems / 6 gl.drawArrays(gl.TRIANGLES, indicesPerFace * faceIndex, indicesPerFace); gl.bindTexture(gl.TEXTURE_2D, null) # generates a heightmap output to maps[6], for later processing by generateSubFinalMap # for face faceIndex. partial generation is allowed via start/endFraction ranging [0,1] generateSubMap: (maps, seed, faceIndex, startFraction, endFraction) -> # setup seed values rndStr = new RandomStream(seed) seeds = [rndStr.unit(), rndStr.unit(), rndStr.unit()] shaderIndex = rndStr.intRange(0, kosmosShaderHeightFunctions.length-1) # set shader from seed gl.useProgram(@heightGenShader[shaderIndex]) gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aUV, 2, gl.FLOAT, false, @quadVerts.itemSize*4, 0) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aPos, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *2) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aBinormal, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *5) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aTangent, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *8) gl.uniform3fv(@heightGenShader[shaderIndex].uniforms.randomSeed, seeds) # bind the appropriate face map texture dataMap = maps[6] gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataMap, 0) # select the subset of the viewport to generate gl.viewport(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.scissor(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.uniform2f(@heightGenShader[shaderIndex].uniforms.verticalViewport, startFraction, endFraction - startFraction); # run the generation shader indicesPerFace = @quadVerts.numItems / 6 gl.drawArrays(gl.TRIANGLES, indicesPerFace * faceIndex, indicesPerFace); # call this to finalize map generation finalizeMaps: (maps) -> # note: it seems generating mipmaps leads to some glitches either in intel HD 4000 or webgl, # causing MAJOR permanent lag for the remainder of the program, and this occurs RANDOMLY. # impossible to know when, and impossible to predict. so I've disabled this. FORTUNATELY, # it turns out for whatever reason, disabling mipmaps entirely looks great with no visible pixel # shimmer on my retina macbook at least, most likely because the high res maps are used only # when you're near the planet anyway, thus effectively being a sort of manual objectwide mipmap anyway. #for i in [0..5] # gl.bindTexture(gl.TEXTURE_2D, maps[i]) # gl.generateMipmap(gl.TEXTURE_2D) #gl.bindTexture(gl.TEXTURE_2D, null) delete maps[6]
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI # Released under The MIT License - see "LICENSE" file for details. root = exports ? this class root.NearMapGenerator constructor: (mapResolution) -> # load shaders @heightGenShader = [] for i in [0 .. kosmosShaderHeightFunctions.length-1] @heightGenShader[i] = xgl.loadProgram("nearMapGenerator" + i) @heightGenShader[i].uniforms = xgl.getProgramUniforms(@heightGenShader[i], ["verticalViewport", "randomSeed"]) @heightGenShader[i].attribs = xgl.getProgramAttribs(@heightGenShader[i], ["aUV", "aPos", "aTangent", "aBinormal"]) @normalGenShader = xgl.loadProgram("normalMapGenerator") @normalGenShader.uniforms = xgl.getProgramUniforms(@normalGenShader, ["verticalViewport", "sampler"]) @normalGenShader.attribs = xgl.getProgramAttribs(@normalGenShader, ["aUV", "aPos", "aTangent", "aBinormal"]) # initialize FBO @fbo = gl.createFramebuffer() gl.bindFramebuffer(gl.FRAMEBUFFER, @fbo) @fbo.width = mapResolution @fbo.height = mapResolution console.log("Initialized high resolution planet map generator FBO at #{@fbo.width} x #{@fbo.height}") gl.bindFramebuffer(gl.FRAMEBUFFER, null) # create fullscreen quad vertices buff = new Float32Array(6*6*11) i = 0 tangent = [0, 0, 0] binormal = [0, 0, 0] for faceIndex in [0..5] for uv in [[0,0], [1,0], [0,1], [1,0], [1,1], [0,1]] pos = mapPlaneToCube(uv[0], uv[1], faceIndex) buff[i++] = uv[0]; buff[i++] = uv[1] buff[i++] = pos[0]; buff[i++] = pos[1]; buff[i++] = pos[2] posU = mapPlaneToCube(uv[0]+1, uv[1], faceIndex) posV = mapPlaneToCube(uv[0], uv[1]+1, faceIndex) binormal = [posU[0]-pos[0], posU[1]-pos[1], posU[2]-pos[2]] tangent = [posV[0]-pos[0], posV[1]-pos[1], posV[2]-pos[2]] buff[i++] = binormal[0]; buff[i++] = binormal[1]; buff[i++] = binormal[2] buff[i++] = tangent[0]; buff[i++] = tangent[1]; buff[i++] = tangent[2] @quadVerts = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts); gl.bufferData(gl.ARRAY_BUFFER, buff, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, null) @quadVerts.itemSize = 11 @quadVerts.numItems = buff.length / @quadVerts.itemSize # call this before making call(s) to generateSubMap start: -> gl.disable(gl.DEPTH_TEST) gl.depthMask(false) gl.bindFramebuffer(gl.FRAMEBUFFER, @fbo) gl.viewport(0, 0, @fbo.width, @fbo.height) gl.enableVertexAttribArray(@normalGenShader.attribs.aUV) gl.enableVertexAttribArray(@normalGenShader.attribs.aPos) gl.enableVertexAttribArray(@normalGenShader.attribs.aBinormal) gl.enableVertexAttribArray(@normalGenShader.attribs.aTangent) gl.enable(gl.SCISSOR_TEST) # call this after making call(s) to generateSubMap finish: -> gl.disable(gl.SCISSOR_TEST) gl.disableVertexAttribArray(@normalGenShader.attribs.aUV) gl.disableVertexAttribArray(@normalGenShader.attribs.aPos) gl.disableVertexAttribArray(@normalGenShader.attribs.aBinormal) gl.disableVertexAttribArray(@normalGenShader.attribs.aTangent) gl.bindBuffer(gl.ARRAY_BUFFER, null) gl.bindFramebuffer(gl.FRAMEBUFFER, null) gl.useProgram(null) gl.depthMask(true) gl.enable(gl.DEPTH_TEST) # Creates and returns a list of SEVEN opengl textures: six for each face of the planet cube, and one # for temporary heightmap storage before normal maps are generated for the finalized map. createMaps: -> maps = [] for face in [0..6] maps[face] = gl.createTexture() gl.bindTexture(gl.TEXTURE_2D, maps[face]) if face < 6 #gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) else gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, @fbo.width, @fbo.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null) gl.bindTexture(gl.TEXTURE_2D, null) return maps # Takes the heightmap generated at maps[6] and outputs the final data map containing # normals/color/height/etc. to maps[faceIndex]. This assumes generateSubMap() has finished # generating all of the heightmap for the SAME faceIndex (so generate only one face at a time # between the two function). Partial generation is allowed via start/endFraction ranging [0,1] generateSubFinalMap: (maps, seed, faceIndex, startFraction, endFraction) -> # select the normal map generation program gl.useProgram(@normalGenShader) gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts) gl.vertexAttribPointer(@normalGenShader.attribs.aUV, 2, gl.FLOAT, false, @quadVerts.itemSize*4, 0) gl.vertexAttribPointer(@normalGenShader.attribs.aPos, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *2) gl.vertexAttribPointer(@normalGenShader.attribs.aBinormal, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *5) gl.vertexAttribPointer(@normalGenShader.attribs.aTangent, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *8) # bind the heightmap input gl.activeTexture(gl.TEXTURE0) gl.bindTexture(gl.TEXTURE_2D, maps[6]) gl.uniform1i(@normalGenShader.uniforms.sampler, 0); # bind the appropriate face map texture dataMap = maps[faceIndex] gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataMap, 0) # select the subset of the viewport to generate gl.viewport(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.scissor(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.uniform2f(@normalGenShader.uniforms.verticalViewport, startFraction, endFraction - startFraction); # run the generation shader indicesPerFace = @quadVerts.numItems / 6 gl.drawArrays(gl.TRIANGLES, indicesPerFace * faceIndex, indicesPerFace); gl.bindTexture(gl.TEXTURE_2D, null) # generates a heightmap output to maps[6], for later processing by generateSubFinalMap # for face faceIndex. partial generation is allowed via start/endFraction ranging [0,1] generateSubMap: (maps, seed, faceIndex, startFraction, endFraction) -> # setup seed values rndStr = new RandomStream(seed) seeds = [rndStr.unit(), rndStr.unit(), rndStr.unit()] shaderIndex = rndStr.intRange(0, kosmosShaderHeightFunctions.length-1) # set shader from seed gl.useProgram(@heightGenShader[shaderIndex]) gl.bindBuffer(gl.ARRAY_BUFFER, @quadVerts) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aUV, 2, gl.FLOAT, false, @quadVerts.itemSize*4, 0) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aPos, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *2) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aBinormal, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *5) gl.vertexAttribPointer(@heightGenShader[shaderIndex].attribs.aTangent, 3, gl.FLOAT, false, @quadVerts.itemSize*4, 4 *8) gl.uniform3fv(@heightGenShader[shaderIndex].uniforms.randomSeed, seeds) # bind the appropriate face map texture dataMap = maps[6] gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataMap, 0) # select the subset of the viewport to generate gl.viewport(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.scissor(0, @fbo.height * startFraction, @fbo.width, @fbo.height * (endFraction - startFraction)) gl.uniform2f(@heightGenShader[shaderIndex].uniforms.verticalViewport, startFraction, endFraction - startFraction); # run the generation shader indicesPerFace = @quadVerts.numItems / 6 gl.drawArrays(gl.TRIANGLES, indicesPerFace * faceIndex, indicesPerFace); # call this to finalize map generation finalizeMaps: (maps) -> # note: it seems generating mipmaps leads to some glitches either in intel HD 4000 or webgl, # causing MAJOR permanent lag for the remainder of the program, and this occurs RANDOMLY. # impossible to know when, and impossible to predict. so I've disabled this. FORTUNATELY, # it turns out for whatever reason, disabling mipmaps entirely looks great with no visible pixel # shimmer on my retina macbook at least, most likely because the high res maps are used only # when you're near the planet anyway, thus effectively being a sort of manual objectwide mipmap anyway. #for i in [0..5] # gl.bindTexture(gl.TEXTURE_2D, maps[i]) # gl.generateMipmap(gl.TEXTURE_2D) #gl.bindTexture(gl.TEXTURE_2D, null) delete maps[6]
[ { "context": "------------\ncustomers = [\n { id: 1, firstName: \"justin\", balance: 10 },\n { id: 2, firstName: \"sissel\", ", "end": 815, "score": 0.9996803998947144, "start": 809, "tag": "NAME", "value": "justin" }, { "context": ": \"justin\", balance: 10 },\n { id: 2, firstNam...
dev/snippets/src/push-and-pull-queries.coffee
loveencounterflow/hengist
0
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'PUSH&PULL' debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge info = CND.get_logger 'info', badge urge = CND.get_logger 'urge', badge help = CND.get_logger 'help', badge whisper = CND.get_logger 'whisper', badge echo = CND.echo.bind CND #----------------------------------------------------------------------------------------------------------- customers = [ { id: 1, firstName: "justin", balance: 10 }, { id: 2, firstName: "sissel", balance: 0 }, { id: 3, firstName: "justin", balance: -3 }, { id: 4, firstName: "smudge", balance: 2 }, { id: 5, firstName: "smudge", balance: 0 }, ] #=========================================================================================================== pull_query = -> #--------------------------------------------------------------------------------------------------------- Scan = ( collection ) -> for x from collection yield x return null #--------------------------------------------------------------------------------------------------------- Select = ( filter, iterator ) -> for x from iterator continue unless filter x yield x return null #--------------------------------------------------------------------------------------------------------- Map = ( f, iterator ) -> for x from iterator yield f x return null #--------------------------------------------------------------------------------------------------------- Distinct = ( iterator ) -> seen = new Set() for x from iterator continue if seen.has x seen.add x yield x return null #--------------------------------------------------------------------------------------------------------- ### SELECT DISTINCT customer_first_name FROM customers WHERE customer_balance > 0 ### info [ ( Distinct \ ( Map \ ( ( c ) => c.firstName ), ( Select ( ( c ) => c.balance > 0 ), ( Scan customers ) ) ) \ )... ] #--------------------------------------------------------------------------------------------------------- return null #=========================================================================================================== push_query = -> #--------------------------------------------------------------------------------------------------------- Scan = ( relation, send ) -> for r from relation send r return null #--------------------------------------------------------------------------------------------------------- Select = ( test, send ) -> ( x ) => send x if test x #--------------------------------------------------------------------------------------------------------- Map = ( f, send ) -> ( x ) => send f x #--------------------------------------------------------------------------------------------------------- Distinct = ( send ) -> seen = new Set() return ( x ) => return null if seen.has x seen.add x send x return null #--------------------------------------------------------------------------------------------------------- result = [] ( Scan \ customers, ( Select \ ( ( c ) => c.balance > 0 ), Map( ( ( c ) => c.firstName ), ( Distinct ( ( r ) => result.push(r) ) ) ) ) ) help result #--------------------------------------------------------------------------------------------------------- return null ############################################################################################################ if module is require.main then do => pull_query() push_query()
137682
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'PUSH&PULL' debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge info = CND.get_logger 'info', badge urge = CND.get_logger 'urge', badge help = CND.get_logger 'help', badge whisper = CND.get_logger 'whisper', badge echo = CND.echo.bind CND #----------------------------------------------------------------------------------------------------------- customers = [ { id: 1, firstName: "<NAME>", balance: 10 }, { id: 2, firstName: "<NAME>", balance: 0 }, { id: 3, firstName: "<NAME>", balance: -3 }, { id: 4, firstName: "<NAME>", balance: 2 }, { id: 5, firstName: "<NAME>", balance: 0 }, ] #=========================================================================================================== pull_query = -> #--------------------------------------------------------------------------------------------------------- Scan = ( collection ) -> for x from collection yield x return null #--------------------------------------------------------------------------------------------------------- Select = ( filter, iterator ) -> for x from iterator continue unless filter x yield x return null #--------------------------------------------------------------------------------------------------------- Map = ( f, iterator ) -> for x from iterator yield f x return null #--------------------------------------------------------------------------------------------------------- Distinct = ( iterator ) -> seen = new Set() for x from iterator continue if seen.has x seen.add x yield x return null #--------------------------------------------------------------------------------------------------------- ### SELECT DISTINCT customer_first_name FROM customers WHERE customer_balance > 0 ### info [ ( Distinct \ ( Map \ ( ( c ) => c.firstName ), ( Select ( ( c ) => c.balance > 0 ), ( Scan customers ) ) ) \ )... ] #--------------------------------------------------------------------------------------------------------- return null #=========================================================================================================== push_query = -> #--------------------------------------------------------------------------------------------------------- Scan = ( relation, send ) -> for r from relation send r return null #--------------------------------------------------------------------------------------------------------- Select = ( test, send ) -> ( x ) => send x if test x #--------------------------------------------------------------------------------------------------------- Map = ( f, send ) -> ( x ) => send f x #--------------------------------------------------------------------------------------------------------- Distinct = ( send ) -> seen = new Set() return ( x ) => return null if seen.has x seen.add x send x return null #--------------------------------------------------------------------------------------------------------- result = [] ( Scan \ customers, ( Select \ ( ( c ) => c.balance > 0 ), Map( ( ( c ) => c.firstName ), ( Distinct ( ( r ) => result.push(r) ) ) ) ) ) help result #--------------------------------------------------------------------------------------------------------- return null ############################################################################################################ if module is require.main then do => pull_query() push_query()
true
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'PUSH&PULL' debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge info = CND.get_logger 'info', badge urge = CND.get_logger 'urge', badge help = CND.get_logger 'help', badge whisper = CND.get_logger 'whisper', badge echo = CND.echo.bind CND #----------------------------------------------------------------------------------------------------------- customers = [ { id: 1, firstName: "PI:NAME:<NAME>END_PI", balance: 10 }, { id: 2, firstName: "PI:NAME:<NAME>END_PI", balance: 0 }, { id: 3, firstName: "PI:NAME:<NAME>END_PI", balance: -3 }, { id: 4, firstName: "PI:NAME:<NAME>END_PI", balance: 2 }, { id: 5, firstName: "PI:NAME:<NAME>END_PI", balance: 0 }, ] #=========================================================================================================== pull_query = -> #--------------------------------------------------------------------------------------------------------- Scan = ( collection ) -> for x from collection yield x return null #--------------------------------------------------------------------------------------------------------- Select = ( filter, iterator ) -> for x from iterator continue unless filter x yield x return null #--------------------------------------------------------------------------------------------------------- Map = ( f, iterator ) -> for x from iterator yield f x return null #--------------------------------------------------------------------------------------------------------- Distinct = ( iterator ) -> seen = new Set() for x from iterator continue if seen.has x seen.add x yield x return null #--------------------------------------------------------------------------------------------------------- ### SELECT DISTINCT customer_first_name FROM customers WHERE customer_balance > 0 ### info [ ( Distinct \ ( Map \ ( ( c ) => c.firstName ), ( Select ( ( c ) => c.balance > 0 ), ( Scan customers ) ) ) \ )... ] #--------------------------------------------------------------------------------------------------------- return null #=========================================================================================================== push_query = -> #--------------------------------------------------------------------------------------------------------- Scan = ( relation, send ) -> for r from relation send r return null #--------------------------------------------------------------------------------------------------------- Select = ( test, send ) -> ( x ) => send x if test x #--------------------------------------------------------------------------------------------------------- Map = ( f, send ) -> ( x ) => send f x #--------------------------------------------------------------------------------------------------------- Distinct = ( send ) -> seen = new Set() return ( x ) => return null if seen.has x seen.add x send x return null #--------------------------------------------------------------------------------------------------------- result = [] ( Scan \ customers, ( Select \ ( ( c ) => c.balance > 0 ), Map( ( ( c ) => c.firstName ), ( Distinct ( ( r ) => result.push(r) ) ) ) ) ) help result #--------------------------------------------------------------------------------------------------------- return null ############################################################################################################ if module is require.main then do => pull_query() push_query()
[ { "context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"John\"]\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book}", "end": 17785, "score": 0.9728336930274963, "start": 17781, "tag": "NAME", "value": "John" }, { "context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)/...
src/ta/regexps.coffee
phillipb/Bible-Passage-Reference-Parser
149
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | title (?! [a-z] ) #could be followed by a number | அதிகாரம் | மற்றும் | verse | அதி | ff | to | [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* title | \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 = "(?:முதலாவது|Mutal[āa]vatu|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:இரண்டாம|இரண்டாவது|Ira[ṇn][ṭt][āa]vatu|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:முன்றாம்|மூன்றாவது|M[ūu][ṉn][ṛr][āa]vatu|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|மற்றும்|to)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|to)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஆதியாகமம்)|(?:[AĀ]tiy[aā]kamam|Gen|ஆதி|தொ(?:டக்க[\s\xa0]*நூல்|நூ)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யாத்திராகமம்)|(?:Y[aā]ttir[aā]kamam|Exod|யாத்|வி(?:டுதலைப்[\s\xa0]*பயணம்|ப)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பேல்(?:[\s\xa0]*தெய்வமும்[\s\xa0]*அரக்கப்பாம்பும்(?:[\s\xa0]*என்பவையாகும்)?)?|Bel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:ev(?:iyar[aā]kamam)?|ēviyar[aā]kamam)|லேவி(?:யர(?:ாகமம)?்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எண்(?:ண(?:ாகமம்|ிக்கை))?|Num|E[nṇ][nṇ][aā]kamam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சீ(?:ராக்(?:கின்[\s\xa0]*ஞான|[\s\xa0]*ஆகம)ம்|ஞா)|Sir) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சா(?:லமோனின்[\s\xa0]*ஞானம்|ஞா)|ஞானாகமம்|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:புலம்பல்)|(?:புலம்)|(?:எரேமியாவின்[\s\xa0]*புலம்பல்|Pulampal|Lam|புல) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எரேமியாவின்[\s\xa0]*கடிதம்|EpJer|எரேமியாவின்[\s\xa0]*மடல்|அவை[\s\xa0]*இளைஞர்[\s\xa0]*மூவரின்[\s\xa0]*பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:வெளிப்படுத்தின[\s\xa0]*விசேடங்கள்)|(?:Ve[lḷ]ippa[tṭ]utti[nṉ]a[\s\xa0]*Vic[eē][tṭ]a[nṅ]ka[lḷ]|தி(?:ருவெளிப்பாடு|வெ)|வெளி|Rev|யோவானுக்கு[\s\xa0]*வெளிப்படுத்தின[\s\xa0]*விசேஷம்)|(?:Ve[lḷ]ippa[tṭ]utti[nṉ]a) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:PrMan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உபாகமம்)|(?:Up[aā]kamam|Deut|உபா|இ(?:ணைச்[\s\xa0]*சட்டம்|ச)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோசு(?:வா(?:வின்[\s\xa0]*புத்தகம்)?)?|Y[oō]cuv[aā]|Josh) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ந(?:ியா(?:யாதிபதிகள(?:ின்[\s\xa0]*புத்தகம்|்(?:[\s\xa0]*ஆகமம்)?))?|ீத(?:ி(?:த்[\s\xa0]*தலைவர்|பதி)கள்)?)|Niy[aā]y[aā]tipatika[lḷ]|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ரூத்(?:த(?:ின்[\s\xa0]*சரித்திரம்|ு))?|R(?:uth|ūt|ut)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*எஸ்திராஸ்|Esd)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*எஸ்திராஸ்|Esd)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஏசா(?:யா(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|Ec[aā]y[aā]|எசாயா|Isa|எசா) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*சாமுவேல்)|(?:2(?:[\s\xa0]*(?:C[aā]muv[eē]l|சாமு)|Sam|[\s\xa0]*அரசுகள்)|சாமுவேலின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*சாமுவேல்)|(?:1(?:[\s\xa0]*(?:C[aā]muv[eē]l|சாமு)|Sam|[\s\xa0]*அரசுகள்)|சாமுவேலின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*(?:இராஜாக|அரசர)்கள்)|(?:2(?:[\s\xa0]*(?:Ir[aā]j[aā]kka[lḷ]|இராஜா|அர)|Kgs|[\s\xa0]*இரா)|4[\s\xa0]*அரசுகள்|இராஜாக்களின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*(?:இராஜாக|அரசர)்கள்)|(?:1(?:[\s\xa0]*(?:Ir[aā]j[aā]kka[lḷ]|இராஜா|அர)|Kgs|[\s\xa0]*இரா)|3[\s\xa0]*அரசுகள்|இராஜாக்களின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*நாளாகமம்)|(?:2(?:[\s\xa0]*(?:N[aā][lḷ][aā]kamam|நாளா|குறிப்பேடு)|Chr|[\s\xa0]*குறி)|நாளாகமத்தின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*நாளாகமம்)|(?:1(?:[\s\xa0]*(?:N[aā][lḷ][aā]kamam|நாளா|குறிப்பேடு)|Chr|[\s\xa0]*குறி)|நாளாகமத்தின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:றா(?:வின்[\s\xa0]*புத்தகம்)?|ரா)|E(?:s[rṛ][aā]|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:நெகே(?:மியா(?:வின்[\s\xa0]*புத்தகம்)?)?|Ne(?:k[eē]miy[aā]|h)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:தர்[\s\xa0]*\(கி(?:ரேக்கம்)?|[\s\xa0]*\(கி)\)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:தர(?:ின்[\s\xa0]*சரித்திரம)?்)?|Est(?:ar|h)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோபு(?:டைய[\s\xa0]*சரித்திரம்)?|Y[oō]pu|Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:இளைஞர்[\s\xa0]*மூவரின்[\s\xa0]*பாடல்|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உன்னத[\s\xa0]*பாட்டு)|(?:U[nṉ][nṉ]atapp[aā][tṭ][tṭ]u|Song|உன்னத[\s\xa0]*சங்கீதம்|இ(?:னிமைமிகு[\s\xa0]*பாடல்|பா)|உன்ன|சாலொமோனின்[\s\xa0]*உன்னதப்பாட்டு)|(?:உன்னதப்பாட்டு|பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:திருப்பாடல்கள்)|(?:சங(?:்(?:கீ(?:த(?:[\s\xa0]*புத்தகம|ங்கள|ம)்)?)?|கீதம்)|Ca[nṅ]k[iī]tam|Ps|திபா|திருப்பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:PrAzar|அசரியா) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:நீதிமொழிகள்)|(?:N[iī]timo[lḻ]ika[lḷ]|நீ(?:தி|மொ)|Prov|பழமொழி[\s\xa0]*ஆகமம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ச(?:ங்கத்[\s\xa0]*திருவுரை[\s\xa0]*ஆகமம்|பை[\s\xa0]*உரையாளர்|உ)|பிரசங்கி|Eccl|Piraca[nṅ]ki|பிரச) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எரே(?:மியா(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|Er[eē]miy[aā]|ஏரேமியா|Jer|ஏரே) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எசே(?:க்கியேல்(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|E(?:c[eē]kkiy[eē]l|zek)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:தானி(?:யேல(?:ின்[\s\xa0]*புத்தகம)?்)?|T[aā][nṉ]iy[eē]l|Dan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஓச[ிே]யா|Hos|ஒசேயா|ஓச[ிே]|[OŌ]ciy[aā]) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:Y[oō]v[eē]|Joe)l|யோவே(?:ல்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]m[oō]s|ஆமோ(?:ஸ்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:O(?:patiy[aā]|bad)|ஒப(?:தியா|தி)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Y[oō][nṉ][aā]|யோனா|Jonah) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:i(?:k[aā]|c)|īk[aā])|மீக(?:்(?:கா)?|ா)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:N(?:a(?:k[uū]m|h)|āk[uū]m)|நாகூ(?:ம்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]pak[uū]k|ஆபகூக்|Hab|ஆப|அப(?:க்கூக்கு)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:செப்பனியா|Zeph|செப்|Ceppa[nṉ]iy[aā]) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]k[aā]y|Hag|ஆகா(?:ய்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ச(?:ெக்(?:கரியா)?|கரி(?:யா)?)|Cakariy[aā]|Zech) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:மல(?:ாக்கி|்கியா)|Malkiy[aā]|மல(?:்கி|ா)|Mal|எபிரேயம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:மத்(?:தேயு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?|Matt(?:[eē]yu[\s\xa0]*Na[rṛ]ceyti|[eē]yu)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:(?:a(?:ṛku[\s\xa0]*Na[rṛ]|rku[\s\xa0]*Na[rṛ])|ā[rṛ]ku[\s\xa0]*Na[rṛ])ceyti|a(?:rku?|ṛku)|ā[rṛ]ku)|மாற்(?:கு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:uk(?:k[aā][\s\xa0]*Na[rṛ]ceyti|e)|ūkk[aā][\s\xa0]*Na[rṛ]ceyti|ūkk[aā]|ukk[aā])|லூ(?:க்(?:கா(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:(?:முதலாவது|1\.)[\s\xa0]*யோவான|1[\s\xa0]*(?:அருளப்பர|யோவான)|Mutal[aā]vatu[\s\xa0]*யோவான)்|1(?:[\s\xa0]*Y[oō]va[nṉ]|John)|யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*முதல(?:்[\s\xa0]*திருமுக|ாம்[\s\xa0]*கடித)|முதல்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*முதலாவது[\s\xa0]*நிருப)ம்|1[\s\xa0]*யோ(?:வா)?|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*(?:திருமுக|கடித)|இரண்டாம்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாவது[\s\xa0]*நிருப)ம்|2(?:[\s\xa0]*(?:அருளப்பர|யோவான)்|[\s\xa0]*Y[oō]va[nṉ]|John)|2[\s\xa0]*யோ(?:வா)?|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:(?:ம(?:ூன்றாவது|ுன்றாம்)|3\.)[\s\xa0]*யோவான|3[\s\xa0]*(?:அருளப்பர|யோவான)|M[uū][nṉ][rṛ][aā]vatu[\s\xa0]*யோவான)்|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*M[uū][nṉ][rṛ][aā]vatu[\s\xa0]*Nirupam|3(?:[\s\xa0]*Y[oō]va[nṉ]|John)|3[\s\xa0]*யோ(?:வா)?|யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*ம(?:ுன்றாம்[\s\xa0]*திருமுக|ூன்றாம்[\s\xa0]*கடித)|மூன்றாம்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*மூன்றாவது[\s\xa0]*நிருப)ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோவா(?:ன்[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?|Y[oō]v[aā][nṉ][\s\xa0]*Na[rṛ]ceyti|John|அருளப்பர்[\s\xa0]*நற்செய்தி)|(?:Y[oō]v[aā][nṉ]|யோவான்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:pp[oō]stalar[\s\xa0]*Pa[nṇ]i|cts)|திப|திருத்தூதர்[\s\xa0]*பணிகள்|அப்(?:போ(?:ஸ்தலர(?:ுடைய[\s\xa0]*நடபடிகள்|்(?:[\s\xa0]*பணி)?))?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உரோம(?:ையருக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுக|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*நிருப)ம்)|(?:உரோமையர்)|(?:Ur[oō]marukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Rom|உரோ|Ur[oō]marukku|ரோம(?:ாபுரியாருக்கு[\s\xa0]*எழுதிய[\s\xa0]*கடிதம|ர)்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*கொரிந்தியர்)|(?:Korintiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam|2(?:[\s\xa0]*(?:Korintiyarukku|கொரி)|Cor)|2[\s\xa0]*கொ|கொரிந்தியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது[\s\xa0]*(?:திருமுக|நிருப)|ம்[\s\xa0]*(?:திருமுக|கடித))ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:கொரிந்தியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல(?:ா(?:வது[\s\xa0]*(?:திருமுக|நிருப))?|்[\s\xa0]*திருமுக)ம்|1(?:[\s\xa0]*Korintiyarukku|Cor|[\s\xa0]*கொரிந்தியர்)|1[\s\xa0]*கொ(?:ரி)?|Korintiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:கலா(?:த்(?:தியர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|Kal[aā]ttiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Gal|Kal[aā]ttiyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எபே(?:சி(?:யர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|Ep(?:[eē]ciyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|h|[eē]ciyarukku)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பிலி(?:ப்(?:பியர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|P(?:ilippiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|hil|ilippiyarukku)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:கொலோ(?:ச(?:ெயர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித)ம)?|ையர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம)?)்)?|Kol[oō]ceyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Col|Kol[oō]ceyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:தெசலோனிக்க(?:ியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாவது[\s\xa0]*நிருப|ேயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*கடித|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது|ம்)[\s\xa0]*திருமுக)ம்|2(?:[\s\xa0]*Tecal[oō][nṉ]ikkiyarukku|Thess|[\s\xa0]*தெசலோனிக்க(?:ேய)?ர்)|2[\s\xa0]*தெச(?:லோ)?|Tecal[oō][nṉ]ikkiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:தெசலோனிக்க(?:ேயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலாம்[\s\xa0]*கடித|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல்[\s\xa0]*திருமுக|ியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலாவது[\s\xa0]*நிருப)ம்|1(?:[\s\xa0]*Tecal[oō][nṉ]ikkiyarukku|Thess|[\s\xa0]*தெசலோனிக்க(?:ேய)?ர்)|1[\s\xa0]*தெச(?:லோ)?|Tecal[oō][nṉ]ikkiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:T[iī]m[oō]tt[eē]yuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam|2(?:[\s\xa0]*(?:T[iī]m[oō]tt[eē]yuvukku|த(?:ிமொ|ீமோ)த்தேயு)|Tim)|2[\s\xa0]*த(?:ீமோத்|ிமொ)|த(?:ீமோத்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|ிம[ொோ]த்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*திருமுக)ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:த(?:ீமோத்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|ிம[ொோ]த்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல்[\s\xa0]*திருமுக)ம்|1[\s\xa0]*(?:T[iī]m[oō]tt[eē]yuvukku|த(?:ிமொ|ீமோ)த்தேயு)|1[\s\xa0]*த(?:ீமோத்|ிமொ)|1Tim|T[iī]m[oō]tt[eē]yuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:it(?:tuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|us)|īttuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|[iī]ttuvukku)|தீத்(?:து(?:வுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம்|க்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம்)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பில(?:ேமோனுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித)ம்|ேமோன்|ே|மோன(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம)?்)?|P(?:il[eē]m[oō][nṉ]ukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupa|hl)m)|(?:Pil[eē]m[oō][nṉ]ukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எபி(?:ர(?:ே(?:யர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:திருமுக|கடித)ம)?்)?|ெயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*நிருபம்))?|Epireyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Heb|Epireyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யாக(?:்(?:கோபு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)|திருமுக)ம்)?)?|ப்பர்[\s\xa0]*திருமுகம்)|Y[aā]kk[oō]pu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Jas|Y[aā]kk[oō]pu) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:பேதுரு[\s\xa0]*(?:எழுதிய[\s\xa0]*இரண்டா(?:ம்[\s\xa0]*(?:திருமுக|கடித)|வது[\s\xa0]*நிருப)|இரண்டாம்[\s\xa0]*திருமுக)ம்|2(?:[\s\xa0]*(?:P[eē]turu|பேதுரு)|Pet|[\s\xa0]*இராயப்பர்)|2[\s\xa0]*பேது|P[eē]turu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:பேதுரு[\s\xa0]*(?:எழுதிய[\s\xa0]*முதல(?:ா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|்[\s\xa0]*திருமுக)|முதல்[\s\xa0]*திருமுக)ம்|1(?:[\s\xa0]*(?:P[eē]turu|பேதுரு)|Pet|[\s\xa0]*இராயப்பர்)|1[\s\xa0]*பேது|P[eē]turu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யூதா[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:நிருப|கடித)|திருமுக)ம்|Jude|யூதா|Y[uū]t[aā](?:[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:த(?:ொபியாசு[\s\xa0]*ஆகமம்|ோபி(?:த்து)?)|Tob) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யூதி(?:த்து)?|Jdt) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பாரூ(?:க்கு)?|Bar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சூசன்னா|Sus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John", "Josh", "Joel", "Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோ) )(?:(?=[\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"
86285
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] | title (?! [a-z] ) #could be followed by a number | அதிகாரம் | மற்றும் | verse | அதி | ff | to | [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* title | \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 = "(?:முதலாவது|Mutal[āa]vatu|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:இரண்டாம|இரண்டாவது|Ira[ṇn][ṭt][āa]vatu|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:முன்றாம்|மூன்றாவது|M[ūu][ṉn][ṛr][āa]vatu|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|மற்றும்|to)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|to)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஆதியாகமம்)|(?:[AĀ]tiy[aā]kamam|Gen|ஆதி|தொ(?:டக்க[\s\xa0]*நூல்|நூ)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யாத்திராகமம்)|(?:Y[aā]ttir[aā]kamam|Exod|யாத்|வி(?:டுதலைப்[\s\xa0]*பயணம்|ப)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பேல்(?:[\s\xa0]*தெய்வமும்[\s\xa0]*அரக்கப்பாம்பும்(?:[\s\xa0]*என்பவையாகும்)?)?|Bel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:ev(?:iyar[aā]kamam)?|ēviyar[aā]kamam)|லேவி(?:யர(?:ாகமம)?்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எண்(?:ண(?:ாகமம்|ிக்கை))?|Num|E[nṇ][nṇ][aā]kamam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சீ(?:ராக்(?:கின்[\s\xa0]*ஞான|[\s\xa0]*ஆகம)ம்|ஞா)|Sir) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சா(?:லமோனின்[\s\xa0]*ஞானம்|ஞா)|ஞானாகமம்|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:புலம்பல்)|(?:புலம்)|(?:எரேமியாவின்[\s\xa0]*புலம்பல்|Pulampal|Lam|புல) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எரேமியாவின்[\s\xa0]*கடிதம்|EpJer|எரேமியாவின்[\s\xa0]*மடல்|அவை[\s\xa0]*இளைஞர்[\s\xa0]*மூவரின்[\s\xa0]*பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:வெளிப்படுத்தின[\s\xa0]*விசேடங்கள்)|(?:Ve[lḷ]ippa[tṭ]utti[nṉ]a[\s\xa0]*Vic[eē][tṭ]a[nṅ]ka[lḷ]|தி(?:ருவெளிப்பாடு|வெ)|வெளி|Rev|யோவானுக்கு[\s\xa0]*வெளிப்படுத்தின[\s\xa0]*விசேஷம்)|(?:Ve[lḷ]ippa[tṭ]utti[nṉ]a) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:PrMan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உபாகமம்)|(?:Up[aā]kamam|Deut|உபா|இ(?:ணைச்[\s\xa0]*சட்டம்|ச)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோசு(?:வா(?:வின்[\s\xa0]*புத்தகம்)?)?|Y[oō]cuv[aā]|Josh) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ந(?:ியா(?:யாதிபதிகள(?:ின்[\s\xa0]*புத்தகம்|்(?:[\s\xa0]*ஆகமம்)?))?|ீத(?:ி(?:த்[\s\xa0]*தலைவர்|பதி)கள்)?)|Niy[aā]y[aā]tipatika[lḷ]|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ரூத்(?:த(?:ின்[\s\xa0]*சரித்திரம்|ு))?|R(?:uth|ūt|ut)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*எஸ்திராஸ்|Esd)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*எஸ்திராஸ்|Esd)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஏசா(?:யா(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|Ec[aā]y[aā]|எசாயா|Isa|எசா) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*சாமுவேல்)|(?:2(?:[\s\xa0]*(?:C[aā]muv[eē]l|சாமு)|Sam|[\s\xa0]*அரசுகள்)|சாமுவேலின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*சாமுவேல்)|(?:1(?:[\s\xa0]*(?:C[aā]muv[eē]l|சாமு)|Sam|[\s\xa0]*அரசுகள்)|சாமுவேலின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*(?:இராஜாக|அரசர)்கள்)|(?:2(?:[\s\xa0]*(?:Ir[aā]j[aā]kka[lḷ]|இராஜா|அர)|Kgs|[\s\xa0]*இரா)|4[\s\xa0]*அரசுகள்|இராஜாக்களின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*(?:இராஜாக|அரசர)்கள்)|(?:1(?:[\s\xa0]*(?:Ir[aā]j[aā]kka[lḷ]|இராஜா|அர)|Kgs|[\s\xa0]*இரா)|3[\s\xa0]*அரசுகள்|இராஜாக்களின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*நாளாகமம்)|(?:2(?:[\s\xa0]*(?:N[aā][lḷ][aā]kamam|நாளா|குறிப்பேடு)|Chr|[\s\xa0]*குறி)|நாளாகமத்தின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*நாளாகமம்)|(?:1(?:[\s\xa0]*(?:N[aā][lḷ][aā]kamam|நாளா|குறிப்பேடு)|Chr|[\s\xa0]*குறி)|நாளாகமத்தின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:றா(?:வின்[\s\xa0]*புத்தகம்)?|ரா)|E(?:s[rṛ][aā]|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:நெகே(?:மியா(?:வின்[\s\xa0]*புத்தகம்)?)?|Ne(?:k[eē]miy[aā]|h)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:தர்[\s\xa0]*\(கி(?:ரேக்கம்)?|[\s\xa0]*\(கி)\)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:தர(?:ின்[\s\xa0]*சரித்திரம)?்)?|Est(?:ar|h)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோபு(?:டைய[\s\xa0]*சரித்திரம்)?|Y[oō]pu|Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:இளைஞர்[\s\xa0]*மூவரின்[\s\xa0]*பாடல்|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உன்னத[\s\xa0]*பாட்டு)|(?:U[nṉ][nṉ]atapp[aā][tṭ][tṭ]u|Song|உன்னத[\s\xa0]*சங்கீதம்|இ(?:னிமைமிகு[\s\xa0]*பாடல்|பா)|உன்ன|சாலொமோனின்[\s\xa0]*உன்னதப்பாட்டு)|(?:உன்னதப்பாட்டு|பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:திருப்பாடல்கள்)|(?:சங(?:்(?:கீ(?:த(?:[\s\xa0]*புத்தகம|ங்கள|ம)்)?)?|கீதம்)|Ca[nṅ]k[iī]tam|Ps|திபா|திருப்பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:PrAzar|அசரியா) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:நீதிமொழிகள்)|(?:N[iī]timo[lḻ]ika[lḷ]|நீ(?:தி|மொ)|Prov|பழமொழி[\s\xa0]*ஆகமம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ச(?:ங்கத்[\s\xa0]*திருவுரை[\s\xa0]*ஆகமம்|பை[\s\xa0]*உரையாளர்|உ)|பிரசங்கி|Eccl|Piraca[nṅ]ki|பிரச) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எரே(?:மியா(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|Er[eē]miy[aā]|ஏரேமியா|Jer|ஏரே) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எசே(?:க்கியேல்(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|E(?:c[eē]kkiy[eē]l|zek)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:தானி(?:யேல(?:ின்[\s\xa0]*புத்தகம)?்)?|T[aā][nṉ]iy[eē]l|Dan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஓச[ிே]யா|Hos|ஒசேயா|ஓச[ிே]|[OŌ]ciy[aā]) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:Y[oō]v[eē]|Joe)l|யோவே(?:ல்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]m[oō]s|ஆமோ(?:ஸ்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:O(?:patiy[aā]|bad)|ஒப(?:தியா|தி)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Y[oō][nṉ][aā]|யோனா|Jonah) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:i(?:k[aā]|c)|īk[aā])|மீக(?:்(?:கா)?|ா)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:N(?:a(?:k[uū]m|h)|āk[uū]m)|நாகூ(?:ம்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]pak[uū]k|ஆபகூக்|Hab|ஆப|அப(?:க்கூக்கு)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:செப்பனியா|Zeph|செப்|Ceppa[nṉ]iy[aā]) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]k[aā]y|Hag|ஆகா(?:ய்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ச(?:ெக்(?:கரியா)?|கரி(?:யா)?)|Cakariy[aā]|Zech) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:மல(?:ாக்கி|்கியா)|Malkiy[aā]|மல(?:்கி|ா)|Mal|எபிரேயம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:மத்(?:தேயு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?|Matt(?:[eē]yu[\s\xa0]*Na[rṛ]ceyti|[eē]yu)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:(?:a(?:ṛku[\s\xa0]*Na[rṛ]|rku[\s\xa0]*Na[rṛ])|ā[rṛ]ku[\s\xa0]*Na[rṛ])ceyti|a(?:rku?|ṛku)|ā[rṛ]ku)|மாற்(?:கு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:uk(?:k[aā][\s\xa0]*Na[rṛ]ceyti|e)|ūkk[aā][\s\xa0]*Na[rṛ]ceyti|ūkk[aā]|ukk[aā])|லூ(?:க்(?:கா(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:(?:முதலாவது|1\.)[\s\xa0]*யோவான|1[\s\xa0]*(?:அருளப்பர|யோவான)|Mutal[aā]vatu[\s\xa0]*யோவான)்|1(?:[\s\xa0]*Y[oō]va[nṉ]|John)|யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*முதல(?:்[\s\xa0]*திருமுக|ாம்[\s\xa0]*கடித)|முதல்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*முதலாவது[\s\xa0]*நிருப)ம்|1[\s\xa0]*யோ(?:வா)?|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*(?:திருமுக|கடித)|இரண்டாம்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாவது[\s\xa0]*நிருப)ம்|2(?:[\s\xa0]*(?:அருளப்பர|யோவான)்|[\s\xa0]*Y[oō]va[nṉ]|John)|2[\s\xa0]*யோ(?:வா)?|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:(?:ம(?:ூன்றாவது|ுன்றாம்)|3\.)[\s\xa0]*யோவான|3[\s\xa0]*(?:அருளப்பர|யோவான)|M[uū][nṉ][rṛ][aā]vatu[\s\xa0]*யோவான)்|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*M[uū][nṉ][rṛ][aā]vatu[\s\xa0]*Nirupam|3(?:[\s\xa0]*Y[oō]va[nṉ]|John)|3[\s\xa0]*யோ(?:வா)?|யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*ம(?:ுன்றாம்[\s\xa0]*திருமுக|ூன்றாம்[\s\xa0]*கடித)|மூன்றாம்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*மூன்றாவது[\s\xa0]*நிருப)ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["<NAME>"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோவா(?:ன்[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?|Y[oō]v[aā][nṉ][\s\xa0]*Na[rṛ]ceyti|John|அருளப்பர்[\s\xa0]*நற்செய்தி)|(?:Y[oō]v[aā][nṉ]|யோவான்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:pp[oō]stalar[\s\xa0]*Pa[nṇ]i|cts)|திப|திருத்தூதர்[\s\xa0]*பணிகள்|அப்(?:போ(?:ஸ்தலர(?:ுடைய[\s\xa0]*நடபடிகள்|்(?:[\s\xa0]*பணி)?))?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உரோம(?:ையருக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுக|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*நிருப)ம்)|(?:உரோமையர்)|(?:Ur[oō]marukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Rom|உரோ|Ur[oō]marukku|ரோம(?:ாபுரியாருக்கு[\s\xa0]*எழுதிய[\s\xa0]*கடிதம|ர)்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*கொரிந்தியர்)|(?:Korintiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam|2(?:[\s\xa0]*(?:Korintiyarukku|கொரி)|Cor)|2[\s\xa0]*கொ|கொரிந்தியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது[\s\xa0]*(?:திருமுக|நிருப)|ம்[\s\xa0]*(?:திருமுக|கடித))ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:கொரிந்தியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல(?:ா(?:வது[\s\xa0]*(?:திருமுக|நிருப))?|்[\s\xa0]*திருமுக)ம்|1(?:[\s\xa0]*Korintiyarukku|Cor|[\s\xa0]*கொரிந்தியர்)|1[\s\xa0]*கொ(?:ரி)?|Korintiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:கலா(?:த்(?:தியர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|Kal[aā]ttiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Gal|Kal[aā]ttiyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எபே(?:சி(?:யர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|Ep(?:[eē]ciyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|h|[eē]ciyarukku)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பிலி(?:ப்(?:பியர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|P(?:ilippiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|hil|ilippiyarukku)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:கொலோ(?:ச(?:ெயர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித)ம)?|ையர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம)?)்)?|Kol[oō]ceyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Col|Kol[oō]ceyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:தெசலோனிக்க(?:ியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாவது[\s\xa0]*நிருப|ேயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*கடித|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது|ம்)[\s\xa0]*திருமுக)ம்|2(?:[\s\xa0]*Tecal[oō][nṉ]ikkiyarukku|Thess|[\s\xa0]*தெசலோனிக்க(?:ேய)?ர்)|2[\s\xa0]*தெச(?:லோ)?|Tecal[oō][nṉ]ikkiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:தெசலோனிக்க(?:ேயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலாம்[\s\xa0]*கடித|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல்[\s\xa0]*திருமுக|ியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலாவது[\s\xa0]*நிருப)ம்|1(?:[\s\xa0]*Tecal[oō][nṉ]ikkiyarukku|Thess|[\s\xa0]*தெசலோனிக்க(?:ேய)?ர்)|1[\s\xa0]*தெச(?:லோ)?|Tecal[oō][nṉ]ikkiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:T[iī]m[oō]tt[eē]yuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam|2(?:[\s\xa0]*(?:T[iī]m[oō]tt[eē]yuvukku|த(?:ிமொ|ீமோ)த்தேயு)|Tim)|2[\s\xa0]*த(?:ீமோத்|ிமொ)|த(?:ீமோத்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|ிம[ொோ]த்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*திருமுக)ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:த(?:ீமோத்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|ிம[ொோ]த்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல்[\s\xa0]*திருமுக)ம்|1[\s\xa0]*(?:T[iī]m[oō]tt[eē]yuvukku|த(?:ிமொ|ீமோ)த்தேயு)|1[\s\xa0]*த(?:ீமோத்|ிமொ)|1Tim|T[iī]m[oō]tt[eē]yuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:it(?:tuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|us)|īttuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|[iī]ttuvukku)|தீத்(?:து(?:வுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம்|க்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம்)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பில(?:ேமோனுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித)ம்|ேமோன்|ே|மோன(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம)?்)?|P(?:il[eē]m[oō][nṉ]ukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupa|hl)m)|(?:Pil[eē]m[oō][nṉ]ukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எபி(?:ர(?:ே(?:யர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:திருமுக|கடித)ம)?்)?|ெயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*நிருபம்))?|Epireyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Heb|Epireyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யாக(?:்(?:கோபு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)|திருமுக)ம்)?)?|ப்பர்[\s\xa0]*திருமுகம்)|Y[aā]kk[oō]pu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Jas|Y[aā]kk[oō]pu) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:பேதுரு[\s\xa0]*(?:எழுதிய[\s\xa0]*இரண்டா(?:ம்[\s\xa0]*(?:திருமுக|கடித)|வது[\s\xa0]*நிருப)|இரண்டாம்[\s\xa0]*திருமுக)ம்|2(?:[\s\xa0]*(?:P[eē]turu|பேதுரு)|Pet|[\s\xa0]*இராயப்பர்)|2[\s\xa0]*பேது|P[eē]turu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:பேதுரு[\s\xa0]*(?:எழுதிய[\s\xa0]*முதல(?:ா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|்[\s\xa0]*திருமுக)|முதல்[\s\xa0]*திருமுக)ம்|1(?:[\s\xa0]*(?:P[eē]turu|பேதுரு)|Pet|[\s\xa0]*இராயப்பர்)|1[\s\xa0]*பேது|P[eē]turu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யூதா[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:நிருப|கடித)|திருமுக)ம்|Jude|யூதா|Y[uū]t[aā](?:[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:த(?:ொபியாசு[\s\xa0]*ஆகமம்|ோபி(?:த்து)?)|Tob) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யூதி(?:த்து)?|Jdt) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பாரூ(?:க்கு)?|Bar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சூசன்னா|Sus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோ) )(?:(?=[\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] | title (?! [a-z] ) #could be followed by a number | அதிகாரம் | மற்றும் | verse | அதி | ff | to | [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* title | \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 = "(?:முதலாவது|Mutal[āa]vatu|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:இரண்டாம|இரண்டாவது|Ira[ṇn][ṭt][āa]vatu|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:முன்றாம்|மூன்றாவது|M[ūu][ṉn][ṛr][āa]vatu|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|மற்றும்|to)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|to)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஆதியாகமம்)|(?:[AĀ]tiy[aā]kamam|Gen|ஆதி|தொ(?:டக்க[\s\xa0]*நூல்|நூ)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யாத்திராகமம்)|(?:Y[aā]ttir[aā]kamam|Exod|யாத்|வி(?:டுதலைப்[\s\xa0]*பயணம்|ப)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பேல்(?:[\s\xa0]*தெய்வமும்[\s\xa0]*அரக்கப்பாம்பும்(?:[\s\xa0]*என்பவையாகும்)?)?|Bel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:ev(?:iyar[aā]kamam)?|ēviyar[aā]kamam)|லேவி(?:யர(?:ாகமம)?்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எண்(?:ண(?:ாகமம்|ிக்கை))?|Num|E[nṇ][nṇ][aā]kamam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சீ(?:ராக்(?:கின்[\s\xa0]*ஞான|[\s\xa0]*ஆகம)ம்|ஞா)|Sir) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சா(?:லமோனின்[\s\xa0]*ஞானம்|ஞா)|ஞானாகமம்|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:புலம்பல்)|(?:புலம்)|(?:எரேமியாவின்[\s\xa0]*புலம்பல்|Pulampal|Lam|புல) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எரேமியாவின்[\s\xa0]*கடிதம்|EpJer|எரேமியாவின்[\s\xa0]*மடல்|அவை[\s\xa0]*இளைஞர்[\s\xa0]*மூவரின்[\s\xa0]*பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:வெளிப்படுத்தின[\s\xa0]*விசேடங்கள்)|(?:Ve[lḷ]ippa[tṭ]utti[nṉ]a[\s\xa0]*Vic[eē][tṭ]a[nṅ]ka[lḷ]|தி(?:ருவெளிப்பாடு|வெ)|வெளி|Rev|யோவானுக்கு[\s\xa0]*வெளிப்படுத்தின[\s\xa0]*விசேஷம்)|(?:Ve[lḷ]ippa[tṭ]utti[nṉ]a) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:PrMan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உபாகமம்)|(?:Up[aā]kamam|Deut|உபா|இ(?:ணைச்[\s\xa0]*சட்டம்|ச)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோசு(?:வா(?:வின்[\s\xa0]*புத்தகம்)?)?|Y[oō]cuv[aā]|Josh) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ந(?:ியா(?:யாதிபதிகள(?:ின்[\s\xa0]*புத்தகம்|்(?:[\s\xa0]*ஆகமம்)?))?|ீத(?:ி(?:த்[\s\xa0]*தலைவர்|பதி)கள்)?)|Niy[aā]y[aā]tipatika[lḷ]|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ரூத்(?:த(?:ின்[\s\xa0]*சரித்திரம்|ு))?|R(?:uth|ūt|ut)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*எஸ்திராஸ்|Esd)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*எஸ்திராஸ்|Esd)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஏசா(?:யா(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|Ec[aā]y[aā]|எசாயா|Isa|எசா) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*சாமுவேல்)|(?:2(?:[\s\xa0]*(?:C[aā]muv[eē]l|சாமு)|Sam|[\s\xa0]*அரசுகள்)|சாமுவேலின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*சாமுவேல்)|(?:1(?:[\s\xa0]*(?:C[aā]muv[eē]l|சாமு)|Sam|[\s\xa0]*அரசுகள்)|சாமுவேலின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*(?:இராஜாக|அரசர)்கள்)|(?:2(?:[\s\xa0]*(?:Ir[aā]j[aā]kka[lḷ]|இராஜா|அர)|Kgs|[\s\xa0]*இரா)|4[\s\xa0]*அரசுகள்|இராஜாக்களின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*(?:இராஜாக|அரசர)்கள்)|(?:1(?:[\s\xa0]*(?:Ir[aā]j[aā]kka[lḷ]|இராஜா|அர)|Kgs|[\s\xa0]*இரா)|3[\s\xa0]*அரசுகள்|இராஜாக்களின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*நாளாகமம்)|(?:2(?:[\s\xa0]*(?:N[aā][lḷ][aā]kamam|நாளா|குறிப்பேடு)|Chr|[\s\xa0]*குறி)|நாளாகமத்தின்[\s\xa0]*இரண்டாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*நாளாகமம்)|(?:1(?:[\s\xa0]*(?:N[aā][lḷ][aā]kamam|நாளா|குறிப்பேடு)|Chr|[\s\xa0]*குறி)|நாளாகமத்தின்[\s\xa0]*முதலாம்[\s\xa0]*புத்தகம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:றா(?:வின்[\s\xa0]*புத்தகம்)?|ரா)|E(?:s[rṛ][aā]|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:நெகே(?:மியா(?:வின்[\s\xa0]*புத்தகம்)?)?|Ne(?:k[eē]miy[aā]|h)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:தர்[\s\xa0]*\(கி(?:ரேக்கம்)?|[\s\xa0]*\(கி)\)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எஸ்(?:தர(?:ின்[\s\xa0]*சரித்திரம)?்)?|Est(?:ar|h)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோபு(?:டைய[\s\xa0]*சரித்திரம்)?|Y[oō]pu|Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:இளைஞர்[\s\xa0]*மூவரின்[\s\xa0]*பாடல்|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உன்னத[\s\xa0]*பாட்டு)|(?:U[nṉ][nṉ]atapp[aā][tṭ][tṭ]u|Song|உன்னத[\s\xa0]*சங்கீதம்|இ(?:னிமைமிகு[\s\xa0]*பாடல்|பா)|உன்ன|சாலொமோனின்[\s\xa0]*உன்னதப்பாட்டு)|(?:உன்னதப்பாட்டு|பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:திருப்பாடல்கள்)|(?:சங(?:்(?:கீ(?:த(?:[\s\xa0]*புத்தகம|ங்கள|ம)்)?)?|கீதம்)|Ca[nṅ]k[iī]tam|Ps|திபா|திருப்பாடல்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:PrAzar|அசரியா) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:நீதிமொழிகள்)|(?:N[iī]timo[lḻ]ika[lḷ]|நீ(?:தி|மொ)|Prov|பழமொழி[\s\xa0]*ஆகமம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ச(?:ங்கத்[\s\xa0]*திருவுரை[\s\xa0]*ஆகமம்|பை[\s\xa0]*உரையாளர்|உ)|பிரசங்கி|Eccl|Piraca[nṅ]ki|பிரச) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எரே(?:மியா(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|Er[eē]miy[aā]|ஏரேமியா|Jer|ஏரே) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எசே(?:க்கியேல்(?:[\s\xa0]*தீர்க்கதரிசியின்[\s\xa0]*புத்தகம்)?)?|E(?:c[eē]kkiy[eē]l|zek)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:தானி(?:யேல(?:ின்[\s\xa0]*புத்தகம)?்)?|T[aā][nṉ]iy[eē]l|Dan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ஓச[ிே]யா|Hos|ஒசேயா|ஓச[ிே]|[OŌ]ciy[aā]) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:Y[oō]v[eē]|Joe)l|யோவே(?:ல்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]m[oō]s|ஆமோ(?:ஸ்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:O(?:patiy[aā]|bad)|ஒப(?:தியா|தி)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Y[oō][nṉ][aā]|யோனா|Jonah) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:i(?:k[aā]|c)|īk[aā])|மீக(?:்(?:கா)?|ா)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:N(?:a(?:k[uū]m|h)|āk[uū]m)|நாகூ(?:ம்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]pak[uū]k|ஆபகூக்|Hab|ஆப|அப(?:க்கூக்கு)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:செப்பனியா|Zeph|செப்|Ceppa[nṉ]iy[aā]) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[AĀ]k[aā]y|Hag|ஆகா(?:ய்)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:ச(?:ெக்(?:கரியா)?|கரி(?:யா)?)|Cakariy[aā]|Zech) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:மல(?:ாக்கி|்கியா)|Malkiy[aā]|மல(?:்கி|ா)|Mal|எபிரேயம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:மத்(?:தேயு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?|Matt(?:[eē]yu[\s\xa0]*Na[rṛ]ceyti|[eē]yu)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:(?:a(?:ṛku[\s\xa0]*Na[rṛ]|rku[\s\xa0]*Na[rṛ])|ā[rṛ]ku[\s\xa0]*Na[rṛ])ceyti|a(?:rku?|ṛku)|ā[rṛ]ku)|மாற்(?:கு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:uk(?:k[aā][\s\xa0]*Na[rṛ]ceyti|e)|ūkk[aā][\s\xa0]*Na[rṛ]ceyti|ūkk[aā]|ukk[aā])|லூ(?:க்(?:கா(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:(?:முதலாவது|1\.)[\s\xa0]*யோவான|1[\s\xa0]*(?:அருளப்பர|யோவான)|Mutal[aā]vatu[\s\xa0]*யோவான)்|1(?:[\s\xa0]*Y[oō]va[nṉ]|John)|யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*முதல(?:்[\s\xa0]*திருமுக|ாம்[\s\xa0]*கடித)|முதல்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*முதலாவது[\s\xa0]*நிருப)ம்|1[\s\xa0]*யோ(?:வா)?|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*(?:திருமுக|கடித)|இரண்டாம்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாவது[\s\xa0]*நிருப)ம்|2(?:[\s\xa0]*(?:அருளப்பர|யோவான)்|[\s\xa0]*Y[oō]va[nṉ]|John)|2[\s\xa0]*யோ(?:வா)?|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:(?:ம(?:ூன்றாவது|ுன்றாம்)|3\.)[\s\xa0]*யோவான|3[\s\xa0]*(?:அருளப்பர|யோவான)|M[uū][nṉ][rṛ][aā]vatu[\s\xa0]*யோவான)்|Y[oō]va[nṉ][\s\xa0]*E[lḻ]utiya[\s\xa0]*M[uū][nṉ][rṛ][aā]vatu[\s\xa0]*Nirupam|3(?:[\s\xa0]*Y[oō]va[nṉ]|John)|3[\s\xa0]*யோ(?:வா)?|யோவ(?:ான்[\s\xa0]*(?:எழுதிய[\s\xa0]*ம(?:ுன்றாம்[\s\xa0]*திருமுக|ூன்றாம்[\s\xa0]*கடித)|மூன்றாம்[\s\xa0]*திருமுக)|ன்[\s\xa0]*எழுதிய[\s\xa0]*மூன்றாவது[\s\xa0]*நிருப)ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PI:NAME:<NAME>END_PI"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோவா(?:ன்[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:சுவிசேஷம்|நற்செய்தி)|நற்செய்தி))?|Y[oō]v[aā][nṉ][\s\xa0]*Na[rṛ]ceyti|John|அருளப்பர்[\s\xa0]*நற்செய்தி)|(?:Y[oō]v[aā][nṉ]|யோவான்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:pp[oō]stalar[\s\xa0]*Pa[nṇ]i|cts)|திப|திருத்தூதர்[\s\xa0]*பணிகள்|அப்(?:போ(?:ஸ்தலர(?:ுடைய[\s\xa0]*நடபடிகள்|்(?:[\s\xa0]*பணி)?))?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:உரோம(?:ையருக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுக|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*நிருப)ம்)|(?:உரோமையர்)|(?:Ur[oō]marukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Rom|உரோ|Ur[oō]marukku|ரோம(?:ாபுரியாருக்கு[\s\xa0]*எழுதிய[\s\xa0]*கடிதம|ர)்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*கொரிந்தியர்)|(?:Korintiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam|2(?:[\s\xa0]*(?:Korintiyarukku|கொரி)|Cor)|2[\s\xa0]*கொ|கொரிந்தியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது[\s\xa0]*(?:திருமுக|நிருப)|ம்[\s\xa0]*(?:திருமுக|கடித))ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:கொரிந்தியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல(?:ா(?:வது[\s\xa0]*(?:திருமுக|நிருப))?|்[\s\xa0]*திருமுக)ம்|1(?:[\s\xa0]*Korintiyarukku|Cor|[\s\xa0]*கொரிந்தியர்)|1[\s\xa0]*கொ(?:ரி)?|Korintiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:கலா(?:த்(?:தியர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|Kal[aā]ttiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Gal|Kal[aā]ttiyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எபே(?:சி(?:யர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|Ep(?:[eē]ciyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|h|[eē]ciyarukku)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பிலி(?:ப்(?:பியர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம)?்)?)?|P(?:ilippiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|hil|ilippiyarukku)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:கொலோ(?:ச(?:ெயர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித)ம)?|ையர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம)?)்)?|Kol[oō]ceyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Col|Kol[oō]ceyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:தெசலோனிக்க(?:ியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாவது[\s\xa0]*நிருப|ேயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*கடித|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது|ம்)[\s\xa0]*திருமுக)ம்|2(?:[\s\xa0]*Tecal[oō][nṉ]ikkiyarukku|Thess|[\s\xa0]*தெசலோனிக்க(?:ேய)?ர்)|2[\s\xa0]*தெச(?:லோ)?|Tecal[oō][nṉ]ikkiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:தெசலோனிக்க(?:ேயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலாம்[\s\xa0]*கடித|ருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல்[\s\xa0]*திருமுக|ியருக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலாவது[\s\xa0]*நிருப)ம்|1(?:[\s\xa0]*Tecal[oō][nṉ]ikkiyarukku|Thess|[\s\xa0]*தெசலோனிக்க(?:ேய)?ர்)|1[\s\xa0]*தெச(?:லோ)?|Tecal[oō][nṉ]ikkiyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:T[iī]m[oō]tt[eē]yuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam|2(?:[\s\xa0]*(?:T[iī]m[oō]tt[eē]yuvukku|த(?:ிமொ|ீமோ)த்தேயு)|Tim)|2[\s\xa0]*த(?:ீமோத்|ிமொ)|த(?:ீமோத்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|ிம[ொோ]த்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*இரண்டாம்[\s\xa0]*திருமுக)ம்) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:த(?:ீமோத்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதலா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|ிம[ொோ]த்தேயுவுக்கு[\s\xa0]*எழுதிய[\s\xa0]*முதல்[\s\xa0]*திருமுக)ம்|1[\s\xa0]*(?:T[iī]m[oō]tt[eē]yuvukku|த(?:ிமொ|ீமோ)த்தேயு)|1[\s\xa0]*த(?:ீமோத்|ிமொ)|1Tim|T[iī]m[oō]tt[eē]yuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:it(?:tuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|us)|īttuvukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|[iī]ttuvukku)|தீத்(?:து(?:வுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)ம்|க்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம்)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பில(?:ேமோனுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:நிருப|கடித)ம்|ேமோன்|ே|மோன(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*திருமுகம)?்)?|P(?:il[eē]m[oō][nṉ]ukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupa|hl)m)|(?:Pil[eē]m[oō][nṉ]ukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:எபி(?:ர(?:ே(?:யர(?:ுக்கு[\s\xa0]*எழுதிய[\s\xa0]*(?:திருமுக|கடித)ம)?்)?|ெயருக்கு[\s\xa0]*எழுதிய[\s\xa0]*நிருபம்))?|Epireyarukku[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Heb|Epireyarukku) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யாக(?:்(?:கோபு(?:[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:நிருப|கடித|திருமுக)|திருமுக)ம்)?)?|ப்பர்[\s\xa0]*திருமுகம்)|Y[aā]kk[oō]pu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam|Jas|Y[aā]kk[oō]pu) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:பேதுரு[\s\xa0]*(?:எழுதிய[\s\xa0]*இரண்டா(?:ம்[\s\xa0]*(?:திருமுக|கடித)|வது[\s\xa0]*நிருப)|இரண்டாம்[\s\xa0]*திருமுக)ம்|2(?:[\s\xa0]*(?:P[eē]turu|பேதுரு)|Pet|[\s\xa0]*இராயப்பர்)|2[\s\xa0]*பேது|P[eē]turu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Ira[nṇ][tṭ][aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:பேதுரு[\s\xa0]*(?:எழுதிய[\s\xa0]*முதல(?:ா(?:வது[\s\xa0]*நிருப|ம்[\s\xa0]*கடித)|்[\s\xa0]*திருமுக)|முதல்[\s\xa0]*திருமுக)ம்|1(?:[\s\xa0]*(?:P[eē]turu|பேதுரு)|Pet|[\s\xa0]*இராயப்பர்)|1[\s\xa0]*பேது|P[eē]turu[\s\xa0]*E[lḻ]utiya[\s\xa0]*Mutal[aā]vatu[\s\xa0]*Nirupam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யூதா[\s\xa0]*(?:எழுதிய[\s\xa0]*(?:நிருப|கடித)|திருமுக)ம்|Jude|யூதா|Y[uū]t[aā](?:[\s\xa0]*E[lḻ]utiya[\s\xa0]*Nirupam)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:த(?:ொபியாசு[\s\xa0]*ஆகமம்|ோபி(?:த்து)?)|Tob) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யூதி(?:த்து)?|Jdt) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:பாரூ(?:க்கு)?|Bar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:சூசன்னா|Sus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏஂ-ஃஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-ஹீ்ௐḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*மக்(?:கபேயர்)?|Macc)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:யோ) )(?:(?=[\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": "ter_combo(\n keys : \"a b c\"\n is_exclusive : true\n ", "end": 23738, "score": 0.584638237953186, "start": 23737, "tag": "KEY", "value": "a" }, { "context": "ter_combo(\n keys : \"a b c\"...
public/plugins/Keypress-development/test/tests.coffee
20181180/Sist_ventas
1,423
describe "Keypress:", -> SHIFT = false listener = null beforeEach -> listener = new window.keypress.Listener() convert_readable_key_to_keycode = (keyname) -> for keycode, name of window.keypress._keycode_dictionary return keycode if name is keyname return event_for_key = (key) -> event = {} event.preventDefault = -> return event.shiftKey = SHIFT spyOn event, "preventDefault" key_code = convert_readable_key_to_keycode key event.keyCode = key_code return event on_keydown = (key) -> if key is "shift" SHIFT = true event = event_for_key key event.metaKey = "meta" in listener._keys_down or listener.get_meta_key() in listener._keys_down listener._receive_input event, true listener._bug_catcher event return event on_keyup = (key) -> if key is "shift" SHIFT = false event = event_for_key key listener._receive_input event, false return event press_key = (key) -> on_keydown key on_keyup key describe "A simple single key basic combo", -> afterEach -> listener.reset() it "just works", -> foo = 0 listener.simple_combo ["a"], -> foo = 1 press_key "a" expect(foo).toEqual(1) it "defaults to not preventing default", -> listener.simple_combo "a", null event = on_keydown "a" on_keyup "a" expect(event.preventDefault).not.toHaveBeenCalled() it "will prevent default keydown if we have an on_keydown function that doesn't return true", -> listener.simple_combo "a", -> return event = on_keydown "a" on_keyup "a" expect(event.preventDefault).toHaveBeenCalled() it "will not prevent default keydown if we have an on_keydown function that does return true", -> listener.simple_combo "a", -> return true event = on_keydown "a" on_keyup "a" expect(event.preventDefault).not.toHaveBeenCalled() it "will only prevent for the final event by default if we don't return true", -> listener.simple_combo "a b", -> return event = on_keydown "a" expect(event.preventDefault).not.toHaveBeenCalled() event = on_keydown "b" expect(event.preventDefault).toHaveBeenCalled() on_keyup "a" on_keyup "b" describe "Shift key helpers", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "evaluates keys as shifted to match combos", -> listener.simple_combo "!", key_handler on_keydown "shift" on_keydown "1" expect(key_handler).toHaveBeenCalled() on_keyup "shift" on_keyup "1" it "still fires the correct keyup even if you let off shift first", -> listener.register_combo( keys : "a !" on_keydown : key_handler on_keyup : key_handler ) on_keydown "shift" on_keydown "a" on_keydown "1" expect(key_handler).toHaveBeenCalled() on_keyup "shift" expect(key_handler.calls.length).toEqual(1) on_keyup "1" on_keyup "a" expect(key_handler.calls.length).toEqual(2) describe "Bug catcher", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "forces keyup on keys when cmd is held down", -> listener.register_combo( keys : "cmd v" on_keydown : key_handler on_keyup : key_handler ) on_keydown "cmd" on_keydown "v" expect(key_handler.calls.length).toEqual(2) on_keyup "v" on_keyup "cmd" describe "Keyup events with no relevant keydown event", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "won't fire the keyup when we alt-tab/cmd-tab in", -> listener.register_combo( keys : "cmd" on_keyup : key_handler ) listener.register_combo( keys : "alt" on_keyup : key_handler ) on_keyup "cmd" expect(key_handler).not.toHaveBeenCalled() on_keyup "alt" expect(key_handler).not.toHaveBeenCalled() describe "Explicit combo options", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() describe "keys", -> it "can take an array", -> listener.register_combo( keys : ["a"] on_keydown : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() it "can take a string", -> listener.register_combo( keys : "a" on_keydown : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() describe "on_keydown", -> it "receives the event and combo count as arguments", -> received_event = null listener.simple_combo "a", (event, count) -> expect(count).toEqual(0) received_event = event down_event = on_keydown "a" on_keyup "a" expect(received_event).toEqual(down_event) it "only fires when all of the keys have been pressed", -> listener.simple_combo "a b c", key_handler on_keydown "a" expect(key_handler).not.toHaveBeenCalled() on_keydown "b" expect(key_handler).not.toHaveBeenCalled() on_keydown "c" expect(key_handler).toHaveBeenCalled() on_keyup "a" on_keyup "b" on_keyup "c" it "will fire each time the final key is pressed", -> foo = 0 listener.simple_combo "a b", -> foo += 1 on_keydown "a" on_keydown "b" on_keyup "b" on_keydown "b" expect(foo).toEqual(2) on_keyup "b" on_keyup "a" it "properly receives is_autorepeat", -> did_repeat = false listener.simple_combo "a", (event, count, is_autorepeat) -> did_repeat = is_autorepeat on_keydown "a" expect(did_repeat).toBe(false) on_keydown "a" expect(did_repeat).toBe(true) on_keydown "a" expect(did_repeat).toBe(true) on_keyup "a" describe "on_keyup", -> it "fires properly", -> listener.register_combo( keys : "a" on_keyup : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() it "receives the event as its argument", -> received_event = null listener.register_combo( keys : "a" on_keyup : (event) -> received_event = event ) on_keydown "a" up_event = on_keyup "a" expect(received_event).toEqual(up_event) it "fires only after all keys are down and the first has been released", -> listener.register_combo( keys : "a b c" on_keyup : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "b" expect(key_handler).toHaveBeenCalled() on_keyup "c" expect(key_handler.calls.length).toEqual(1) on_keyup "a" expect(key_handler.calls.length).toEqual(1) describe "on_release", -> it "only fires after all of the keys have been released", -> listener.register_combo( keys : "a b c" on_release : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "b" expect(key_handler).not.toHaveBeenCalled() on_keyup "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "a" expect(key_handler).toHaveBeenCalled() describe "this keyword", -> it "defaults to window", -> listener.simple_combo "a", -> expect(this).toEqual(window) press_key "a" it "can be set to any arbitrary scope", -> my_scope = {} listener.register_combo( keys : "a" this : my_scope on_keydown : -> expect(this).toEqual(my_scope) ) press_key "a" describe "prevent_default", -> it "manual: only prevents on the key that activated the handler", -> listener.register_combo( keys : "a b c" on_keydown : (event) -> event.preventDefault() on_keyup : (event) -> event.preventDefault() on_release : (event) -> event.preventDefault() ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).not.toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() a_up_event = on_keyup "a" expect(a_up_event.preventDefault).toHaveBeenCalled() b_up_event = on_keyup "b" expect(b_up_event.preventDefault).not.toHaveBeenCalled() c_up_event = on_keyup "c" expect(c_up_event.preventDefault).toHaveBeenCalled() it "return any non-true value: only prevents the key that activated the handler", -> listener.register_combo( keys : "a b c" on_keydown : (event) -> return false on_keyup : (event) -> return false on_release : (event) -> return false ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).not.toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() # on_keydown a_up_event = on_keyup "a" expect(a_up_event.preventDefault).toHaveBeenCalled() # on_keyup b_up_event = on_keyup "b" expect(b_up_event.preventDefault).not.toHaveBeenCalled() c_up_event = on_keyup "c" expect(c_up_event.preventDefault).toHaveBeenCalled() # on_release it "property: prevents on all events related and only those related", -> listener.register_combo( keys : "a b c" prevent_default : true on_keydown : -> on_keyup : -> on_release : -> ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).toHaveBeenCalled() x_down_event = on_keydown "x" expect(x_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() a_up_event = on_keyup "a" x_up_event = on_keyup "x" b_up_event = on_keyup "b" c_up_event = on_keyup "c" expect(a_up_event.preventDefault).toHaveBeenCalled() expect(x_up_event.preventDefault).not.toHaveBeenCalled() expect(b_up_event.preventDefault).toHaveBeenCalled() expect(c_up_event.preventDefault).toHaveBeenCalled() describe "prevent_repeat", -> it "allows multiple firings of the keydown event by default", -> listener.simple_combo "a", key_handler on_keydown "a" on_keydown "a" expect(key_handler.calls.length).toEqual(2) on_keyup "a" it "only fires the first time it is pressed down when true", -> listener.register_combo( keys : "a" on_keydown : key_handler prevent_repeat : true ) on_keydown "a" on_keydown "a" expect(key_handler.calls.length).toEqual(1) on_keyup "a" describe "is_unordered", -> it "forces the order described by default", -> listener.register_combo( keys : "a b" on_keydown : key_handler ) on_keydown "b" on_keydown "a" on_keyup "b" on_keyup "a" expect(key_handler).not.toHaveBeenCalled() on_keydown "a" on_keydown "b" on_keyup "a" on_keyup "b" expect(key_handler).toHaveBeenCalled() it "allows a user to press the keys in any order when is_unordered", -> listener.register_combo( keys : "a b" on_keydown : key_handler is_unordered : true ) on_keydown "b" on_keydown "a" on_keyup "b" on_keyup "a" expect(key_handler).toHaveBeenCalled() describe "is_counting", -> it "calls the keydown handler with the count", -> last_count = 0 listener.register_combo( keys : "tab x space" is_counting : true on_keydown : (event, count) -> last_count = count ) on_keydown "tab" on_keydown "x" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" on_keydown "space" expect(last_count).toEqual(2) on_keyup "space" on_keyup "x" on_keyup "tab" it "does not increment count on keyup if we have keydown handler", -> last_count = 0 listener.register_combo( keys : "tab space" is_counting : true on_keydown : (event, count) -> last_count = count on_keyup : (event, count) -> last_count = count ) on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" expect(last_count).toEqual(1) on_keyup "tab" it "resets the count even if the combo gets dropped", -> last_count = 0 listener.register_combo( keys : "tab space" is_counting : true on_keydown : (event, count) -> last_count = count ) listener.register_combo( keys : "tab space a" on_keydown : key_handler ) on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keydown "a" expect(key_handler).toHaveBeenCalled() on_keyup "a" on_keyup "space" on_keyup "tab" on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" on_keyup "tab" describe "is_sequence", -> it "properly registers a sequence", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" expect(key_handler).toHaveBeenCalled() it "only calls the keydown handler after the last key has been pressed", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).toHaveBeenCalled() it "only calls the keyup handler after the last key has been released", -> listener.register_combo( keys : "h i" is_sequence : true on_keyup : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).toHaveBeenCalled() it "completely ignores the on_release block", -> listener.register_combo( keys : "h i" is_sequence : true on_release : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).not.toHaveBeenCalled() it "works with the prevent_default property", -> listener.register_combo( keys : "h i t" is_sequence : true prevent_default : true on_keydown : key_handler ) h_keydown = on_keydown "h" on_keyup "h" i_keydown = on_keydown "i" on_keyup "i" t_keydown = on_keydown "t" on_keyup "t" expect(key_handler).toHaveBeenCalled() expect(h_keydown.preventDefault).toHaveBeenCalled() expect(i_keydown.preventDefault).toHaveBeenCalled() expect(t_keydown.preventDefault).toHaveBeenCalled() it "will trigger overlapping sequences which are not exclusive", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) listener.register_combo( keys : "h i t" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" press_key "t" expect(key_handler.calls.length).toEqual(2) it "will not trigger overlapping exclusive sequences", -> listener.register_combo( keys : "h i" is_sequence : true is_exclusive : true on_keydown : key_handler ) listener.register_combo( keys : "h i t" is_sequence : true is_exclusive : true on_keydown : key_handler ) press_key "h" press_key "i" press_key "t" expect(key_handler.calls.length).toEqual(1) it "clears out sequence keys after matching an exclusive combo", -> listener.register_combo( keys : "h i" is_sequence : true is_exclusive : true on_keydown : key_handler ) press_key "h" press_key "i" expect(listener._sequence.length).toEqual(0) it "does not clears out sequence keys for non-exclusives", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" expect(listener._sequence.length).toEqual(2) it "will default sequences to exclusive", -> combo = listener.sequence_combo("h i") expect(combo.is_exclusive).toBe(true) describe "is_exclusive", -> it "will fire all combos by default", -> listener.register_combo( keys : "a b" on_keydown : key_handler ) listener.register_combo( keys : "a b c" on_keydown : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler.calls.length).toEqual(2) on_keyup "a" on_keyup "b" on_keyup "c" it "will not fire keydown for a less specific combo", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keydown : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "a b c" is_exclusive : true on_keydown : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("bigger") on_keyup "a" on_keyup "b" on_keyup "c" it "will not fire keyup for a less specific combo", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keyup : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "a b c" is_exclusive : true on_keyup : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keydown "c" on_keyup "c" on_keyup "b" on_keyup "a" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("bigger") it "will fire a less specific combo if the bigger did NOT fire", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keyup : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "a b c" is_exclusive : true on_keyup : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keyup "b" on_keyup "a" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("smaller") describe "is_solitary", -> it "will not fire the combo if additional keys are pressed", -> listener.register_combo( keys : "a b" is_solitary : true on_keydown : key_handler on_keyup : key_handler on_release : key_handler ) on_keydown "a" on_keydown "x" on_keydown "b" on_keyup "a" on_keyup "x" on_keyup "b" expect(key_handler).not.toHaveBeenCalled() it "will not fire up if down was not fired", -> listener.register_combo( keys : "a b" is_solitary : true on_keydown : key_handler on_keyup : key_handler on_release : key_handler ) on_keydown "a" on_keydown "x" on_keydown "b" on_keyup "x" on_keyup "a" on_keyup "b" expect(key_handler).not.toHaveBeenCalled() describe "Keyboard Shortcuts", -> afterEach -> listener.reset() describe "Escape", -> it "works with 'escape' and 'esc'", -> count = 0 handler = -> count += 1 listener.register_combo( keys : "escape" on_keydown : handler ) on_keydown "esc" expect(count).toEqual(1) listener.unregister_combo("esc") expect(listener.get_registered_combos().length).toEqual(0) listener.register_combo( keys : "esc" on_keydown : handler ) on_keydown "esc" expect(count).toEqual(2) describe "Keypress Functional components:", -> listener = null beforeEach -> listener = new window.keypress.Listener() afterEach -> listener.reset() describe "_is_array_in_array_sorted", -> it "case 1", -> result = window.keypress._is_array_in_array_sorted ["a", "b"], ["a", "b", "c"] expect(result).toBe(true) it "case 2", -> result = window.keypress._is_array_in_array_sorted ["a", "b", "c"], ["a", "b"] expect(result).toBe(false) it "case 3", -> result = window.keypress._is_array_in_array_sorted ["a", "b"], ["a", "x", "b"] expect(result).toBe(true) it "case 4", -> result = window.keypress._is_array_in_array_sorted ["b", "a"], ["a", "x", "b"] expect(result).toBe(false) describe "_fuzzy_match_combo_arrays", -> it "properly matches even with something else in the array", -> listener.register_combo( keys : "a b" ) foo = 0 listener._fuzzy_match_combo_arrays ["a", "x", "b"], -> foo += 1 expect(foo).toEqual(1) it "won't match a sorted combo that isn't in the same order", -> listener.register_combo( keys : "a b" is_unordered : false ) foo = 0 listener._fuzzy_match_combo_arrays ["b", "x", "a"], -> foo += 1 expect(foo).toEqual(0) it "will match a sorted combo that is in the correct order", -> listener.register_combo( keys : "a b" is_unordered : false ) foo = 0 listener._fuzzy_match_combo_arrays ["a", "x", "b"], -> foo += 1 expect(foo).toEqual(1) describe "APIs behave as expected:", -> listener = null beforeEach -> listener = new window.keypress.Listener() afterEach -> listener.reset() describe "unregister_many", -> it "unregisters the combos registered by register_many", () -> combos1 = [ { keys : "shift s", }, { keys : "shift r", }] combos2 = [ { keys : "alt s" }, { keys : "alt r" }] registered1 = listener.register_many(combos1) registered2 = listener.register_many(combos2) expect(listener.get_registered_combos().length).toEqual(4) listener.unregister_many(registered2) expect(listener.get_registered_combos().length).toEqual(2) expect(listener.get_registered_combos()[0].keys).toEqual(["shift", "s"]) expect(listener.get_registered_combos()[1].keys).toEqual(["shift", "r"]) describe "unregister_combo", -> it "unregisters string", -> listener.register_combo( keys : "shift s" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("shift s") count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters array", -> listener.register_combo( keys : "shift s" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(["shift", "s"]) count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters array out of order", -> listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(["s", "shift"]) count = listener.get_registered_combos().length expect(count).toEqual(0) it "does not unregister if the combo is ordered and not unregistered with the same ordering", -> listener.register_combo( keys : "shift s" is_unordered : false ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("s shift") count = listener.get_registered_combos().length expect(count).toEqual(1) it "unregisters if the combo is unordered and not unregistered with the same ordering", -> listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("shift s") count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters a combo passed in directly", -> combo = listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(combo) count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters a meta combo from a string", -> listener.register_combo( keys: "meta c" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("meta c") count = listener.get_registered_combos().length expect(count).toEqual(0)
57916
describe "Keypress:", -> SHIFT = false listener = null beforeEach -> listener = new window.keypress.Listener() convert_readable_key_to_keycode = (keyname) -> for keycode, name of window.keypress._keycode_dictionary return keycode if name is keyname return event_for_key = (key) -> event = {} event.preventDefault = -> return event.shiftKey = SHIFT spyOn event, "preventDefault" key_code = convert_readable_key_to_keycode key event.keyCode = key_code return event on_keydown = (key) -> if key is "shift" SHIFT = true event = event_for_key key event.metaKey = "meta" in listener._keys_down or listener.get_meta_key() in listener._keys_down listener._receive_input event, true listener._bug_catcher event return event on_keyup = (key) -> if key is "shift" SHIFT = false event = event_for_key key listener._receive_input event, false return event press_key = (key) -> on_keydown key on_keyup key describe "A simple single key basic combo", -> afterEach -> listener.reset() it "just works", -> foo = 0 listener.simple_combo ["a"], -> foo = 1 press_key "a" expect(foo).toEqual(1) it "defaults to not preventing default", -> listener.simple_combo "a", null event = on_keydown "a" on_keyup "a" expect(event.preventDefault).not.toHaveBeenCalled() it "will prevent default keydown if we have an on_keydown function that doesn't return true", -> listener.simple_combo "a", -> return event = on_keydown "a" on_keyup "a" expect(event.preventDefault).toHaveBeenCalled() it "will not prevent default keydown if we have an on_keydown function that does return true", -> listener.simple_combo "a", -> return true event = on_keydown "a" on_keyup "a" expect(event.preventDefault).not.toHaveBeenCalled() it "will only prevent for the final event by default if we don't return true", -> listener.simple_combo "a b", -> return event = on_keydown "a" expect(event.preventDefault).not.toHaveBeenCalled() event = on_keydown "b" expect(event.preventDefault).toHaveBeenCalled() on_keyup "a" on_keyup "b" describe "Shift key helpers", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "evaluates keys as shifted to match combos", -> listener.simple_combo "!", key_handler on_keydown "shift" on_keydown "1" expect(key_handler).toHaveBeenCalled() on_keyup "shift" on_keyup "1" it "still fires the correct keyup even if you let off shift first", -> listener.register_combo( keys : "a !" on_keydown : key_handler on_keyup : key_handler ) on_keydown "shift" on_keydown "a" on_keydown "1" expect(key_handler).toHaveBeenCalled() on_keyup "shift" expect(key_handler.calls.length).toEqual(1) on_keyup "1" on_keyup "a" expect(key_handler.calls.length).toEqual(2) describe "Bug catcher", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "forces keyup on keys when cmd is held down", -> listener.register_combo( keys : "cmd v" on_keydown : key_handler on_keyup : key_handler ) on_keydown "cmd" on_keydown "v" expect(key_handler.calls.length).toEqual(2) on_keyup "v" on_keyup "cmd" describe "Keyup events with no relevant keydown event", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "won't fire the keyup when we alt-tab/cmd-tab in", -> listener.register_combo( keys : "cmd" on_keyup : key_handler ) listener.register_combo( keys : "alt" on_keyup : key_handler ) on_keyup "cmd" expect(key_handler).not.toHaveBeenCalled() on_keyup "alt" expect(key_handler).not.toHaveBeenCalled() describe "Explicit combo options", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() describe "keys", -> it "can take an array", -> listener.register_combo( keys : ["a"] on_keydown : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() it "can take a string", -> listener.register_combo( keys : "a" on_keydown : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() describe "on_keydown", -> it "receives the event and combo count as arguments", -> received_event = null listener.simple_combo "a", (event, count) -> expect(count).toEqual(0) received_event = event down_event = on_keydown "a" on_keyup "a" expect(received_event).toEqual(down_event) it "only fires when all of the keys have been pressed", -> listener.simple_combo "a b c", key_handler on_keydown "a" expect(key_handler).not.toHaveBeenCalled() on_keydown "b" expect(key_handler).not.toHaveBeenCalled() on_keydown "c" expect(key_handler).toHaveBeenCalled() on_keyup "a" on_keyup "b" on_keyup "c" it "will fire each time the final key is pressed", -> foo = 0 listener.simple_combo "a b", -> foo += 1 on_keydown "a" on_keydown "b" on_keyup "b" on_keydown "b" expect(foo).toEqual(2) on_keyup "b" on_keyup "a" it "properly receives is_autorepeat", -> did_repeat = false listener.simple_combo "a", (event, count, is_autorepeat) -> did_repeat = is_autorepeat on_keydown "a" expect(did_repeat).toBe(false) on_keydown "a" expect(did_repeat).toBe(true) on_keydown "a" expect(did_repeat).toBe(true) on_keyup "a" describe "on_keyup", -> it "fires properly", -> listener.register_combo( keys : "a" on_keyup : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() it "receives the event as its argument", -> received_event = null listener.register_combo( keys : "a" on_keyup : (event) -> received_event = event ) on_keydown "a" up_event = on_keyup "a" expect(received_event).toEqual(up_event) it "fires only after all keys are down and the first has been released", -> listener.register_combo( keys : "a b c" on_keyup : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "b" expect(key_handler).toHaveBeenCalled() on_keyup "c" expect(key_handler.calls.length).toEqual(1) on_keyup "a" expect(key_handler.calls.length).toEqual(1) describe "on_release", -> it "only fires after all of the keys have been released", -> listener.register_combo( keys : "a b c" on_release : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "b" expect(key_handler).not.toHaveBeenCalled() on_keyup "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "a" expect(key_handler).toHaveBeenCalled() describe "this keyword", -> it "defaults to window", -> listener.simple_combo "a", -> expect(this).toEqual(window) press_key "a" it "can be set to any arbitrary scope", -> my_scope = {} listener.register_combo( keys : "a" this : my_scope on_keydown : -> expect(this).toEqual(my_scope) ) press_key "a" describe "prevent_default", -> it "manual: only prevents on the key that activated the handler", -> listener.register_combo( keys : "a b c" on_keydown : (event) -> event.preventDefault() on_keyup : (event) -> event.preventDefault() on_release : (event) -> event.preventDefault() ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).not.toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() a_up_event = on_keyup "a" expect(a_up_event.preventDefault).toHaveBeenCalled() b_up_event = on_keyup "b" expect(b_up_event.preventDefault).not.toHaveBeenCalled() c_up_event = on_keyup "c" expect(c_up_event.preventDefault).toHaveBeenCalled() it "return any non-true value: only prevents the key that activated the handler", -> listener.register_combo( keys : "a b c" on_keydown : (event) -> return false on_keyup : (event) -> return false on_release : (event) -> return false ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).not.toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() # on_keydown a_up_event = on_keyup "a" expect(a_up_event.preventDefault).toHaveBeenCalled() # on_keyup b_up_event = on_keyup "b" expect(b_up_event.preventDefault).not.toHaveBeenCalled() c_up_event = on_keyup "c" expect(c_up_event.preventDefault).toHaveBeenCalled() # on_release it "property: prevents on all events related and only those related", -> listener.register_combo( keys : "a b c" prevent_default : true on_keydown : -> on_keyup : -> on_release : -> ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).toHaveBeenCalled() x_down_event = on_keydown "x" expect(x_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() a_up_event = on_keyup "a" x_up_event = on_keyup "x" b_up_event = on_keyup "b" c_up_event = on_keyup "c" expect(a_up_event.preventDefault).toHaveBeenCalled() expect(x_up_event.preventDefault).not.toHaveBeenCalled() expect(b_up_event.preventDefault).toHaveBeenCalled() expect(c_up_event.preventDefault).toHaveBeenCalled() describe "prevent_repeat", -> it "allows multiple firings of the keydown event by default", -> listener.simple_combo "a", key_handler on_keydown "a" on_keydown "a" expect(key_handler.calls.length).toEqual(2) on_keyup "a" it "only fires the first time it is pressed down when true", -> listener.register_combo( keys : "a" on_keydown : key_handler prevent_repeat : true ) on_keydown "a" on_keydown "a" expect(key_handler.calls.length).toEqual(1) on_keyup "a" describe "is_unordered", -> it "forces the order described by default", -> listener.register_combo( keys : "a b" on_keydown : key_handler ) on_keydown "b" on_keydown "a" on_keyup "b" on_keyup "a" expect(key_handler).not.toHaveBeenCalled() on_keydown "a" on_keydown "b" on_keyup "a" on_keyup "b" expect(key_handler).toHaveBeenCalled() it "allows a user to press the keys in any order when is_unordered", -> listener.register_combo( keys : "a b" on_keydown : key_handler is_unordered : true ) on_keydown "b" on_keydown "a" on_keyup "b" on_keyup "a" expect(key_handler).toHaveBeenCalled() describe "is_counting", -> it "calls the keydown handler with the count", -> last_count = 0 listener.register_combo( keys : "tab x space" is_counting : true on_keydown : (event, count) -> last_count = count ) on_keydown "tab" on_keydown "x" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" on_keydown "space" expect(last_count).toEqual(2) on_keyup "space" on_keyup "x" on_keyup "tab" it "does not increment count on keyup if we have keydown handler", -> last_count = 0 listener.register_combo( keys : "tab space" is_counting : true on_keydown : (event, count) -> last_count = count on_keyup : (event, count) -> last_count = count ) on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" expect(last_count).toEqual(1) on_keyup "tab" it "resets the count even if the combo gets dropped", -> last_count = 0 listener.register_combo( keys : "tab space" is_counting : true on_keydown : (event, count) -> last_count = count ) listener.register_combo( keys : "tab space a" on_keydown : key_handler ) on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keydown "a" expect(key_handler).toHaveBeenCalled() on_keyup "a" on_keyup "space" on_keyup "tab" on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" on_keyup "tab" describe "is_sequence", -> it "properly registers a sequence", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" expect(key_handler).toHaveBeenCalled() it "only calls the keydown handler after the last key has been pressed", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).toHaveBeenCalled() it "only calls the keyup handler after the last key has been released", -> listener.register_combo( keys : "h i" is_sequence : true on_keyup : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).toHaveBeenCalled() it "completely ignores the on_release block", -> listener.register_combo( keys : "h i" is_sequence : true on_release : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).not.toHaveBeenCalled() it "works with the prevent_default property", -> listener.register_combo( keys : "h i t" is_sequence : true prevent_default : true on_keydown : key_handler ) h_keydown = on_keydown "h" on_keyup "h" i_keydown = on_keydown "i" on_keyup "i" t_keydown = on_keydown "t" on_keyup "t" expect(key_handler).toHaveBeenCalled() expect(h_keydown.preventDefault).toHaveBeenCalled() expect(i_keydown.preventDefault).toHaveBeenCalled() expect(t_keydown.preventDefault).toHaveBeenCalled() it "will trigger overlapping sequences which are not exclusive", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) listener.register_combo( keys : "h i t" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" press_key "t" expect(key_handler.calls.length).toEqual(2) it "will not trigger overlapping exclusive sequences", -> listener.register_combo( keys : "h i" is_sequence : true is_exclusive : true on_keydown : key_handler ) listener.register_combo( keys : "h i t" is_sequence : true is_exclusive : true on_keydown : key_handler ) press_key "h" press_key "i" press_key "t" expect(key_handler.calls.length).toEqual(1) it "clears out sequence keys after matching an exclusive combo", -> listener.register_combo( keys : "h i" is_sequence : true is_exclusive : true on_keydown : key_handler ) press_key "h" press_key "i" expect(listener._sequence.length).toEqual(0) it "does not clears out sequence keys for non-exclusives", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" expect(listener._sequence.length).toEqual(2) it "will default sequences to exclusive", -> combo = listener.sequence_combo("h i") expect(combo.is_exclusive).toBe(true) describe "is_exclusive", -> it "will fire all combos by default", -> listener.register_combo( keys : "a b" on_keydown : key_handler ) listener.register_combo( keys : "a b c" on_keydown : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler.calls.length).toEqual(2) on_keyup "a" on_keyup "b" on_keyup "c" it "will not fire keydown for a less specific combo", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keydown : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "<KEY> b c" is_exclusive : true on_keydown : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("bigger") on_keyup "a" on_keyup "b" on_keyup "c" it "will not fire keyup for a less specific combo", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keyup : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "<KEY>" is_exclusive : true on_keyup : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keydown "c" on_keyup "c" on_keyup "b" on_keyup "a" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("bigger") it "will fire a less specific combo if the bigger did NOT fire", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keyup : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "a b c" is_exclusive : true on_keyup : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keyup "b" on_keyup "a" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("smaller") describe "is_solitary", -> it "will not fire the combo if additional keys are pressed", -> listener.register_combo( keys : "a b" is_solitary : true on_keydown : key_handler on_keyup : key_handler on_release : key_handler ) on_keydown "a" on_keydown "x" on_keydown "b" on_keyup "a" on_keyup "x" on_keyup "b" expect(key_handler).not.toHaveBeenCalled() it "will not fire up if down was not fired", -> listener.register_combo( keys : "a b" is_solitary : true on_keydown : key_handler on_keyup : key_handler on_release : key_handler ) on_keydown "a" on_keydown "x" on_keydown "b" on_keyup "x" on_keyup "a" on_keyup "b" expect(key_handler).not.toHaveBeenCalled() describe "Keyboard Shortcuts", -> afterEach -> listener.reset() describe "Escape", -> it "works with 'escape' and 'esc'", -> count = 0 handler = -> count += 1 listener.register_combo( keys : "escape" on_keydown : handler ) on_keydown "esc" expect(count).toEqual(1) listener.unregister_combo("esc") expect(listener.get_registered_combos().length).toEqual(0) listener.register_combo( keys : "esc" on_keydown : handler ) on_keydown "esc" expect(count).toEqual(2) describe "Keypress Functional components:", -> listener = null beforeEach -> listener = new window.keypress.Listener() afterEach -> listener.reset() describe "_is_array_in_array_sorted", -> it "case 1", -> result = window.keypress._is_array_in_array_sorted ["a", "b"], ["a", "b", "c"] expect(result).toBe(true) it "case 2", -> result = window.keypress._is_array_in_array_sorted ["a", "b", "c"], ["a", "b"] expect(result).toBe(false) it "case 3", -> result = window.keypress._is_array_in_array_sorted ["a", "b"], ["a", "x", "b"] expect(result).toBe(true) it "case 4", -> result = window.keypress._is_array_in_array_sorted ["b", "a"], ["a", "x", "b"] expect(result).toBe(false) describe "_fuzzy_match_combo_arrays", -> it "properly matches even with something else in the array", -> listener.register_combo( keys : "a b" ) foo = 0 listener._fuzzy_match_combo_arrays ["a", "x", "b"], -> foo += 1 expect(foo).toEqual(1) it "won't match a sorted combo that isn't in the same order", -> listener.register_combo( keys : "a b" is_unordered : false ) foo = 0 listener._fuzzy_match_combo_arrays ["b", "x", "a"], -> foo += 1 expect(foo).toEqual(0) it "will match a sorted combo that is in the correct order", -> listener.register_combo( keys : "a b" is_unordered : false ) foo = 0 listener._fuzzy_match_combo_arrays ["a", "x", "b"], -> foo += 1 expect(foo).toEqual(1) describe "APIs behave as expected:", -> listener = null beforeEach -> listener = new window.keypress.Listener() afterEach -> listener.reset() describe "unregister_many", -> it "unregisters the combos registered by register_many", () -> combos1 = [ { keys : "shift s", }, { keys : "shift r", }] combos2 = [ { keys : "alt s" }, { keys : "alt r" }] registered1 = listener.register_many(combos1) registered2 = listener.register_many(combos2) expect(listener.get_registered_combos().length).toEqual(4) listener.unregister_many(registered2) expect(listener.get_registered_combos().length).toEqual(2) expect(listener.get_registered_combos()[0].keys).toEqual(["shift", "s"]) expect(listener.get_registered_combos()[1].keys).toEqual(["shift", "r"]) describe "unregister_combo", -> it "unregisters string", -> listener.register_combo( keys : "shift s" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("shift s") count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters array", -> listener.register_combo( keys : "shift s" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(["shift", "s"]) count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters array out of order", -> listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(["s", "shift"]) count = listener.get_registered_combos().length expect(count).toEqual(0) it "does not unregister if the combo is ordered and not unregistered with the same ordering", -> listener.register_combo( keys : "shift s" is_unordered : false ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("s shift") count = listener.get_registered_combos().length expect(count).toEqual(1) it "unregisters if the combo is unordered and not unregistered with the same ordering", -> listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("shift s") count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters a combo passed in directly", -> combo = listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(combo) count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters a meta combo from a string", -> listener.register_combo( keys: "meta c" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("meta c") count = listener.get_registered_combos().length expect(count).toEqual(0)
true
describe "Keypress:", -> SHIFT = false listener = null beforeEach -> listener = new window.keypress.Listener() convert_readable_key_to_keycode = (keyname) -> for keycode, name of window.keypress._keycode_dictionary return keycode if name is keyname return event_for_key = (key) -> event = {} event.preventDefault = -> return event.shiftKey = SHIFT spyOn event, "preventDefault" key_code = convert_readable_key_to_keycode key event.keyCode = key_code return event on_keydown = (key) -> if key is "shift" SHIFT = true event = event_for_key key event.metaKey = "meta" in listener._keys_down or listener.get_meta_key() in listener._keys_down listener._receive_input event, true listener._bug_catcher event return event on_keyup = (key) -> if key is "shift" SHIFT = false event = event_for_key key listener._receive_input event, false return event press_key = (key) -> on_keydown key on_keyup key describe "A simple single key basic combo", -> afterEach -> listener.reset() it "just works", -> foo = 0 listener.simple_combo ["a"], -> foo = 1 press_key "a" expect(foo).toEqual(1) it "defaults to not preventing default", -> listener.simple_combo "a", null event = on_keydown "a" on_keyup "a" expect(event.preventDefault).not.toHaveBeenCalled() it "will prevent default keydown if we have an on_keydown function that doesn't return true", -> listener.simple_combo "a", -> return event = on_keydown "a" on_keyup "a" expect(event.preventDefault).toHaveBeenCalled() it "will not prevent default keydown if we have an on_keydown function that does return true", -> listener.simple_combo "a", -> return true event = on_keydown "a" on_keyup "a" expect(event.preventDefault).not.toHaveBeenCalled() it "will only prevent for the final event by default if we don't return true", -> listener.simple_combo "a b", -> return event = on_keydown "a" expect(event.preventDefault).not.toHaveBeenCalled() event = on_keydown "b" expect(event.preventDefault).toHaveBeenCalled() on_keyup "a" on_keyup "b" describe "Shift key helpers", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "evaluates keys as shifted to match combos", -> listener.simple_combo "!", key_handler on_keydown "shift" on_keydown "1" expect(key_handler).toHaveBeenCalled() on_keyup "shift" on_keyup "1" it "still fires the correct keyup even if you let off shift first", -> listener.register_combo( keys : "a !" on_keydown : key_handler on_keyup : key_handler ) on_keydown "shift" on_keydown "a" on_keydown "1" expect(key_handler).toHaveBeenCalled() on_keyup "shift" expect(key_handler.calls.length).toEqual(1) on_keyup "1" on_keyup "a" expect(key_handler.calls.length).toEqual(2) describe "Bug catcher", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "forces keyup on keys when cmd is held down", -> listener.register_combo( keys : "cmd v" on_keydown : key_handler on_keyup : key_handler ) on_keydown "cmd" on_keydown "v" expect(key_handler.calls.length).toEqual(2) on_keyup "v" on_keyup "cmd" describe "Keyup events with no relevant keydown event", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() it "won't fire the keyup when we alt-tab/cmd-tab in", -> listener.register_combo( keys : "cmd" on_keyup : key_handler ) listener.register_combo( keys : "alt" on_keyup : key_handler ) on_keyup "cmd" expect(key_handler).not.toHaveBeenCalled() on_keyup "alt" expect(key_handler).not.toHaveBeenCalled() describe "Explicit combo options", -> key_handler = null beforeEach -> key_handler = jasmine.createSpy() afterEach -> listener.reset() describe "keys", -> it "can take an array", -> listener.register_combo( keys : ["a"] on_keydown : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() it "can take a string", -> listener.register_combo( keys : "a" on_keydown : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() describe "on_keydown", -> it "receives the event and combo count as arguments", -> received_event = null listener.simple_combo "a", (event, count) -> expect(count).toEqual(0) received_event = event down_event = on_keydown "a" on_keyup "a" expect(received_event).toEqual(down_event) it "only fires when all of the keys have been pressed", -> listener.simple_combo "a b c", key_handler on_keydown "a" expect(key_handler).not.toHaveBeenCalled() on_keydown "b" expect(key_handler).not.toHaveBeenCalled() on_keydown "c" expect(key_handler).toHaveBeenCalled() on_keyup "a" on_keyup "b" on_keyup "c" it "will fire each time the final key is pressed", -> foo = 0 listener.simple_combo "a b", -> foo += 1 on_keydown "a" on_keydown "b" on_keyup "b" on_keydown "b" expect(foo).toEqual(2) on_keyup "b" on_keyup "a" it "properly receives is_autorepeat", -> did_repeat = false listener.simple_combo "a", (event, count, is_autorepeat) -> did_repeat = is_autorepeat on_keydown "a" expect(did_repeat).toBe(false) on_keydown "a" expect(did_repeat).toBe(true) on_keydown "a" expect(did_repeat).toBe(true) on_keyup "a" describe "on_keyup", -> it "fires properly", -> listener.register_combo( keys : "a" on_keyup : key_handler ) press_key "a" expect(key_handler).toHaveBeenCalled() it "receives the event as its argument", -> received_event = null listener.register_combo( keys : "a" on_keyup : (event) -> received_event = event ) on_keydown "a" up_event = on_keyup "a" expect(received_event).toEqual(up_event) it "fires only after all keys are down and the first has been released", -> listener.register_combo( keys : "a b c" on_keyup : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "b" expect(key_handler).toHaveBeenCalled() on_keyup "c" expect(key_handler.calls.length).toEqual(1) on_keyup "a" expect(key_handler.calls.length).toEqual(1) describe "on_release", -> it "only fires after all of the keys have been released", -> listener.register_combo( keys : "a b c" on_release : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "b" expect(key_handler).not.toHaveBeenCalled() on_keyup "c" expect(key_handler).not.toHaveBeenCalled() on_keyup "a" expect(key_handler).toHaveBeenCalled() describe "this keyword", -> it "defaults to window", -> listener.simple_combo "a", -> expect(this).toEqual(window) press_key "a" it "can be set to any arbitrary scope", -> my_scope = {} listener.register_combo( keys : "a" this : my_scope on_keydown : -> expect(this).toEqual(my_scope) ) press_key "a" describe "prevent_default", -> it "manual: only prevents on the key that activated the handler", -> listener.register_combo( keys : "a b c" on_keydown : (event) -> event.preventDefault() on_keyup : (event) -> event.preventDefault() on_release : (event) -> event.preventDefault() ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).not.toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() a_up_event = on_keyup "a" expect(a_up_event.preventDefault).toHaveBeenCalled() b_up_event = on_keyup "b" expect(b_up_event.preventDefault).not.toHaveBeenCalled() c_up_event = on_keyup "c" expect(c_up_event.preventDefault).toHaveBeenCalled() it "return any non-true value: only prevents the key that activated the handler", -> listener.register_combo( keys : "a b c" on_keydown : (event) -> return false on_keyup : (event) -> return false on_release : (event) -> return false ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).not.toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() # on_keydown a_up_event = on_keyup "a" expect(a_up_event.preventDefault).toHaveBeenCalled() # on_keyup b_up_event = on_keyup "b" expect(b_up_event.preventDefault).not.toHaveBeenCalled() c_up_event = on_keyup "c" expect(c_up_event.preventDefault).toHaveBeenCalled() # on_release it "property: prevents on all events related and only those related", -> listener.register_combo( keys : "a b c" prevent_default : true on_keydown : -> on_keyup : -> on_release : -> ) a_down_event = on_keydown "a" expect(a_down_event.preventDefault).toHaveBeenCalled() b_down_event = on_keydown "b" expect(b_down_event.preventDefault).toHaveBeenCalled() x_down_event = on_keydown "x" expect(x_down_event.preventDefault).not.toHaveBeenCalled() c_down_event = on_keydown "c" expect(c_down_event.preventDefault).toHaveBeenCalled() a_up_event = on_keyup "a" x_up_event = on_keyup "x" b_up_event = on_keyup "b" c_up_event = on_keyup "c" expect(a_up_event.preventDefault).toHaveBeenCalled() expect(x_up_event.preventDefault).not.toHaveBeenCalled() expect(b_up_event.preventDefault).toHaveBeenCalled() expect(c_up_event.preventDefault).toHaveBeenCalled() describe "prevent_repeat", -> it "allows multiple firings of the keydown event by default", -> listener.simple_combo "a", key_handler on_keydown "a" on_keydown "a" expect(key_handler.calls.length).toEqual(2) on_keyup "a" it "only fires the first time it is pressed down when true", -> listener.register_combo( keys : "a" on_keydown : key_handler prevent_repeat : true ) on_keydown "a" on_keydown "a" expect(key_handler.calls.length).toEqual(1) on_keyup "a" describe "is_unordered", -> it "forces the order described by default", -> listener.register_combo( keys : "a b" on_keydown : key_handler ) on_keydown "b" on_keydown "a" on_keyup "b" on_keyup "a" expect(key_handler).not.toHaveBeenCalled() on_keydown "a" on_keydown "b" on_keyup "a" on_keyup "b" expect(key_handler).toHaveBeenCalled() it "allows a user to press the keys in any order when is_unordered", -> listener.register_combo( keys : "a b" on_keydown : key_handler is_unordered : true ) on_keydown "b" on_keydown "a" on_keyup "b" on_keyup "a" expect(key_handler).toHaveBeenCalled() describe "is_counting", -> it "calls the keydown handler with the count", -> last_count = 0 listener.register_combo( keys : "tab x space" is_counting : true on_keydown : (event, count) -> last_count = count ) on_keydown "tab" on_keydown "x" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" on_keydown "space" expect(last_count).toEqual(2) on_keyup "space" on_keyup "x" on_keyup "tab" it "does not increment count on keyup if we have keydown handler", -> last_count = 0 listener.register_combo( keys : "tab space" is_counting : true on_keydown : (event, count) -> last_count = count on_keyup : (event, count) -> last_count = count ) on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" expect(last_count).toEqual(1) on_keyup "tab" it "resets the count even if the combo gets dropped", -> last_count = 0 listener.register_combo( keys : "tab space" is_counting : true on_keydown : (event, count) -> last_count = count ) listener.register_combo( keys : "tab space a" on_keydown : key_handler ) on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keydown "a" expect(key_handler).toHaveBeenCalled() on_keyup "a" on_keyup "space" on_keyup "tab" on_keydown "tab" on_keydown "space" expect(last_count).toEqual(1) on_keyup "space" on_keyup "tab" describe "is_sequence", -> it "properly registers a sequence", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" expect(key_handler).toHaveBeenCalled() it "only calls the keydown handler after the last key has been pressed", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).toHaveBeenCalled() it "only calls the keyup handler after the last key has been released", -> listener.register_combo( keys : "h i" is_sequence : true on_keyup : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).toHaveBeenCalled() it "completely ignores the on_release block", -> listener.register_combo( keys : "h i" is_sequence : true on_release : key_handler ) press_key "h" expect(key_handler).not.toHaveBeenCalled() press_key "i" expect(key_handler).not.toHaveBeenCalled() it "works with the prevent_default property", -> listener.register_combo( keys : "h i t" is_sequence : true prevent_default : true on_keydown : key_handler ) h_keydown = on_keydown "h" on_keyup "h" i_keydown = on_keydown "i" on_keyup "i" t_keydown = on_keydown "t" on_keyup "t" expect(key_handler).toHaveBeenCalled() expect(h_keydown.preventDefault).toHaveBeenCalled() expect(i_keydown.preventDefault).toHaveBeenCalled() expect(t_keydown.preventDefault).toHaveBeenCalled() it "will trigger overlapping sequences which are not exclusive", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) listener.register_combo( keys : "h i t" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" press_key "t" expect(key_handler.calls.length).toEqual(2) it "will not trigger overlapping exclusive sequences", -> listener.register_combo( keys : "h i" is_sequence : true is_exclusive : true on_keydown : key_handler ) listener.register_combo( keys : "h i t" is_sequence : true is_exclusive : true on_keydown : key_handler ) press_key "h" press_key "i" press_key "t" expect(key_handler.calls.length).toEqual(1) it "clears out sequence keys after matching an exclusive combo", -> listener.register_combo( keys : "h i" is_sequence : true is_exclusive : true on_keydown : key_handler ) press_key "h" press_key "i" expect(listener._sequence.length).toEqual(0) it "does not clears out sequence keys for non-exclusives", -> listener.register_combo( keys : "h i" is_sequence : true on_keydown : key_handler ) press_key "h" press_key "i" expect(listener._sequence.length).toEqual(2) it "will default sequences to exclusive", -> combo = listener.sequence_combo("h i") expect(combo.is_exclusive).toBe(true) describe "is_exclusive", -> it "will fire all combos by default", -> listener.register_combo( keys : "a b" on_keydown : key_handler ) listener.register_combo( keys : "a b c" on_keydown : key_handler ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler.calls.length).toEqual(2) on_keyup "a" on_keyup "b" on_keyup "c" it "will not fire keydown for a less specific combo", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keydown : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "PI:KEY:<KEY>END_PI b c" is_exclusive : true on_keydown : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keydown "c" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("bigger") on_keyup "a" on_keyup "b" on_keyup "c" it "will not fire keyup for a less specific combo", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keyup : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "PI:KEY:<KEY>END_PI" is_exclusive : true on_keyup : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keydown "c" on_keyup "c" on_keyup "b" on_keyup "a" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("bigger") it "will fire a less specific combo if the bigger did NOT fire", -> fired = null listener.register_combo( keys : "a b" is_exclusive : true on_keyup : -> fired = "smaller" key_handler() ) listener.register_combo( keys : "a b c" is_exclusive : true on_keyup : -> fired = "bigger" key_handler() ) on_keydown "a" on_keydown "b" on_keyup "b" on_keyup "a" expect(key_handler.calls.length).toEqual(1) expect(fired).toEqual("smaller") describe "is_solitary", -> it "will not fire the combo if additional keys are pressed", -> listener.register_combo( keys : "a b" is_solitary : true on_keydown : key_handler on_keyup : key_handler on_release : key_handler ) on_keydown "a" on_keydown "x" on_keydown "b" on_keyup "a" on_keyup "x" on_keyup "b" expect(key_handler).not.toHaveBeenCalled() it "will not fire up if down was not fired", -> listener.register_combo( keys : "a b" is_solitary : true on_keydown : key_handler on_keyup : key_handler on_release : key_handler ) on_keydown "a" on_keydown "x" on_keydown "b" on_keyup "x" on_keyup "a" on_keyup "b" expect(key_handler).not.toHaveBeenCalled() describe "Keyboard Shortcuts", -> afterEach -> listener.reset() describe "Escape", -> it "works with 'escape' and 'esc'", -> count = 0 handler = -> count += 1 listener.register_combo( keys : "escape" on_keydown : handler ) on_keydown "esc" expect(count).toEqual(1) listener.unregister_combo("esc") expect(listener.get_registered_combos().length).toEqual(0) listener.register_combo( keys : "esc" on_keydown : handler ) on_keydown "esc" expect(count).toEqual(2) describe "Keypress Functional components:", -> listener = null beforeEach -> listener = new window.keypress.Listener() afterEach -> listener.reset() describe "_is_array_in_array_sorted", -> it "case 1", -> result = window.keypress._is_array_in_array_sorted ["a", "b"], ["a", "b", "c"] expect(result).toBe(true) it "case 2", -> result = window.keypress._is_array_in_array_sorted ["a", "b", "c"], ["a", "b"] expect(result).toBe(false) it "case 3", -> result = window.keypress._is_array_in_array_sorted ["a", "b"], ["a", "x", "b"] expect(result).toBe(true) it "case 4", -> result = window.keypress._is_array_in_array_sorted ["b", "a"], ["a", "x", "b"] expect(result).toBe(false) describe "_fuzzy_match_combo_arrays", -> it "properly matches even with something else in the array", -> listener.register_combo( keys : "a b" ) foo = 0 listener._fuzzy_match_combo_arrays ["a", "x", "b"], -> foo += 1 expect(foo).toEqual(1) it "won't match a sorted combo that isn't in the same order", -> listener.register_combo( keys : "a b" is_unordered : false ) foo = 0 listener._fuzzy_match_combo_arrays ["b", "x", "a"], -> foo += 1 expect(foo).toEqual(0) it "will match a sorted combo that is in the correct order", -> listener.register_combo( keys : "a b" is_unordered : false ) foo = 0 listener._fuzzy_match_combo_arrays ["a", "x", "b"], -> foo += 1 expect(foo).toEqual(1) describe "APIs behave as expected:", -> listener = null beforeEach -> listener = new window.keypress.Listener() afterEach -> listener.reset() describe "unregister_many", -> it "unregisters the combos registered by register_many", () -> combos1 = [ { keys : "shift s", }, { keys : "shift r", }] combos2 = [ { keys : "alt s" }, { keys : "alt r" }] registered1 = listener.register_many(combos1) registered2 = listener.register_many(combos2) expect(listener.get_registered_combos().length).toEqual(4) listener.unregister_many(registered2) expect(listener.get_registered_combos().length).toEqual(2) expect(listener.get_registered_combos()[0].keys).toEqual(["shift", "s"]) expect(listener.get_registered_combos()[1].keys).toEqual(["shift", "r"]) describe "unregister_combo", -> it "unregisters string", -> listener.register_combo( keys : "shift s" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("shift s") count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters array", -> listener.register_combo( keys : "shift s" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(["shift", "s"]) count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters array out of order", -> listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(["s", "shift"]) count = listener.get_registered_combos().length expect(count).toEqual(0) it "does not unregister if the combo is ordered and not unregistered with the same ordering", -> listener.register_combo( keys : "shift s" is_unordered : false ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("s shift") count = listener.get_registered_combos().length expect(count).toEqual(1) it "unregisters if the combo is unordered and not unregistered with the same ordering", -> listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("shift s") count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters a combo passed in directly", -> combo = listener.register_combo( keys : "shift s" is_unordered : true ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo(combo) count = listener.get_registered_combos().length expect(count).toEqual(0) it "unregisters a meta combo from a string", -> listener.register_combo( keys: "meta c" ) count = listener.get_registered_combos().length expect(count).toEqual(1) listener.unregister_combo("meta c") count = listener.get_registered_combos().length expect(count).toEqual(0)
[ { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 1088, "score": 0.9387900233268738, "start": 1081, "tag": "NAME", "value": "Patient" }, { "context": " \"localId\" : \"5\",\n ...
test/elm/logical/data.coffee
luis1van/cql-execution-1
0
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.cql to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### And library TestSnippet version '1' using QUICK context Patient define TT: true and true define TF: true and false define TN: true and null define FF: false and false define FT: false and true define FN: false and null define NN: null and null define NT: null and true define NF: null and false ### module.exports['And'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "TT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "And", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "TF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "And", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "TN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "And", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "FF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "And", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "FT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "And", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "FN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "And", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "NN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "NT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "NF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### Or library TestSnippet version '1' using QUICK context Patient define TT: true or true define TF: true or false define TN: true or null define FF: false or false define FT: false or true define FN: false or null define NN: null or null define NT: null or true define NF: null or false ### module.exports['Or'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "TT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "Or", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "TF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "Or", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "TN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "Or", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "FF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "Or", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "FT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "Or", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "FN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "Or", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "NN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "NT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "NF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### XOr library TestSnippet version '1' using QUICK context Patient define TT: true xor true define TF: true xor false define TN: true xor null define FF: false xor false define FT: false xor true define FN: false xor null define NN: null xor null define NT: null xor true define NF: null xor false ### module.exports['XOr'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "TT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "Xor", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "TF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "Xor", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "TN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "Xor", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "FF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "Xor", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "FT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "Xor", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "FN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "Xor", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "NN", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "NT", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "NF", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### Not library TestSnippet version '1' using QUICK context Patient define NotTrue: not true define NotFalse: not false define NotNull: not null ### module.exports['Not'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "NotTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","NotTrue",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "not ","true" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "Not", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "NotFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","NotFalse",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "not ","false" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "Not", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NotNull", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NotNull",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "not ","null" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "Not", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } } ### IsTrue library TestSnippet version '1' using QUICK context Patient define TrueIsTrue: true is true define FalseIsTrue: false is true define NullIsTrue: null is true ### module.exports['IsTrue'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "TrueIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","TrueIsTrue",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "true"," is true" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "IsTrue", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "FalseIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","FalseIsTrue",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "false"," is true" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "IsTrue", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NullIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NullIsTrue",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "null"," is true" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "IsTrue", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } } ### IsFalse library TestSnippet version '1' using QUICK context Patient define TrueIsFalse: true is false define FalseIsFalse: false is false define NullIsFalse: null is false ### module.exports['IsFalse'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "TrueIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","TrueIsFalse",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "true"," is false" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "IsFalse", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "FalseIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","FalseIsFalse",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "false"," is false" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "IsFalse", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NullIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NullIsFalse",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "null"," is false" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "IsFalse", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } }
119579
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.cql to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### And library TestSnippet version '1' using QUICK context Patient define TT: true and true define TF: true and false define TN: true and null define FF: false and false define FT: false and true define FN: false and null define NN: null and null define NT: null and true define NF: null and false ### module.exports['And'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "And", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "And", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "And", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "And", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "And", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "And", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### Or library TestSnippet version '1' using QUICK context Patient define TT: true or true define TF: true or false define TN: true or null define FF: false or false define FT: false or true define FN: false or null define NN: null or null define NT: null or true define NF: null or false ### module.exports['Or'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "Or", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "Or", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "Or", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "Or", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "Or", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "Or", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### XOr library TestSnippet version '1' using QUICK context Patient define TT: true xor true define TF: true xor false define TN: true xor null define FF: false xor false define FT: false xor true define FN: false xor null define NN: null xor null define NT: null xor true define NF: null xor false ### module.exports['XOr'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "Xor", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "Xor", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "Xor", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "Xor", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "Xor", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "Xor", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### Not library TestSnippet version '1' using QUICK context Patient define NotTrue: not true define NotFalse: not false define NotNull: not null ### module.exports['Not'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","NotTrue",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "not ","true" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "Not", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "<NAME>False", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","NotFalse",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "not ","false" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "Not", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NotNull",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "not ","null" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "Not", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } } ### IsTrue library TestSnippet version '1' using QUICK context Patient define TrueIsTrue: true is true define FalseIsTrue: false is true define NullIsTrue: null is true ### module.exports['IsTrue'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "TrueIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","TrueIsTrue",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "true"," is true" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "IsTrue", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "FalseIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","FalseIsTrue",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "false"," is true" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "IsTrue", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NullIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NullIsTrue",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "null"," is true" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "IsTrue", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } } ### IsFalse library TestSnippet version '1' using QUICK context Patient define TrueIsFalse: true is false define FalseIsFalse: false is false define NullIsFalse: null is false ### module.exports['IsFalse'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "TrueIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","TrueIsFalse",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "true"," is false" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "IsFalse", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "FalseIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","FalseIsFalse",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "false"," is false" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "IsFalse", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NullIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NullIsFalse",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "null"," is false" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "IsFalse", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } }
true
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.cql to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### And library TestSnippet version '1' using QUICK context Patient define TT: true and true define TF: true and false define TN: true and null define FF: false and false define FT: false and true define FN: false and null define NN: null and null define NT: null and true define NF: null and false ### module.exports['And'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "And", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "And", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "And", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "And", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "And", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "And", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," and ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," and ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," and ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "And", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### Or library TestSnippet version '1' using QUICK context Patient define TT: true or true define TF: true or false define TN: true or null define FF: false or false define FT: false or true define FN: false or null define NN: null or null define NT: null or true define NF: null or false ### module.exports['Or'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "Or", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "Or", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "Or", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "Or", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "Or", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "Or", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," or ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," or ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," or ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "Or", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### XOr library TestSnippet version '1' using QUICK context Patient define TT: true xor true define TF: true xor false define TN: true xor null define FF: false xor false define FT: false xor true define FN: false xor null define NN: null xor null define NT: null xor true define NF: null xor false ### module.exports['XOr'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "5", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "5", "s" : [ { "value" : [ "define ","TT",": " ] }, { "r" : "4", "s" : [ { "r" : "2", "value" : [ "true"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "4", "type" : "Xor", "operand" : [ { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "3", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "9", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "9", "s" : [ { "value" : [ "define ","TF",": " ] }, { "r" : "8", "s" : [ { "r" : "6", "value" : [ "true"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "8", "type" : "Xor", "operand" : [ { "localId" : "6", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "localId" : "7", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "13", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "13", "s" : [ { "value" : [ "define ","TN",": " ] }, { "r" : "12", "s" : [ { "r" : "10", "value" : [ "true"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "12", "type" : "Xor", "operand" : [ { "localId" : "10", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "11", "type" : "Null" } } ] } }, { "localId" : "17", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "17", "s" : [ { "value" : [ "define ","FF",": " ] }, { "r" : "16", "s" : [ { "r" : "14", "value" : [ "false"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "16", "type" : "Xor", "operand" : [ { "localId" : "14", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "15", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } }, { "localId" : "21", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "21", "s" : [ { "value" : [ "define ","FT",": " ] }, { "r" : "20", "s" : [ { "r" : "18", "value" : [ "false"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "20", "type" : "Xor", "operand" : [ { "localId" : "18", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "localId" : "19", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "25", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "25", "s" : [ { "value" : [ "define ","FN",": " ] }, { "r" : "24", "s" : [ { "r" : "22", "value" : [ "false"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "24", "type" : "Xor", "operand" : [ { "localId" : "22", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "23", "type" : "Null" } } ] } }, { "localId" : "29", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "29", "s" : [ { "value" : [ "define ","NN",": " ] }, { "r" : "28", "s" : [ { "r" : "26", "value" : [ "null"," xor ","null" ] } ] } ] } } ], "expression" : { "localId" : "28", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "26", "type" : "Null" } }, { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "27", "type" : "Null" } } ] } }, { "localId" : "33", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "33", "s" : [ { "value" : [ "define ","NT",": " ] }, { "r" : "32", "s" : [ { "r" : "30", "value" : [ "null"," xor ","true" ] } ] } ] } } ], "expression" : { "localId" : "32", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "30", "type" : "Null" } }, { "localId" : "31", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } ] } }, { "localId" : "37", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "37", "s" : [ { "value" : [ "define ","NF",": " ] }, { "r" : "36", "s" : [ { "r" : "34", "value" : [ "null"," xor ","false" ] } ] } ] } } ], "expression" : { "localId" : "36", "type" : "Xor", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "34", "type" : "Null" } }, { "localId" : "35", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } ] } } ] } } } ### Not library TestSnippet version '1' using QUICK context Patient define NotTrue: not true define NotFalse: not false define NotNull: not null ### module.exports['Not'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","NotTrue",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "not ","true" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "Not", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "PI:NAME:<NAME>END_PIFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","NotFalse",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "not ","false" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "Not", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NotNull",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "not ","null" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "Not", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } } ### IsTrue library TestSnippet version '1' using QUICK context Patient define TrueIsTrue: true is true define FalseIsTrue: false is true define NullIsTrue: null is true ### module.exports['IsTrue'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "TrueIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","TrueIsTrue",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "true"," is true" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "IsTrue", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "FalseIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","FalseIsTrue",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "false"," is true" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "IsTrue", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NullIsTrue", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NullIsTrue",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "null"," is true" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "IsTrue", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } } ### IsFalse library TestSnippet version '1' using QUICK context Patient define TrueIsFalse: true is false define FalseIsFalse: false is false define NullIsFalse: null is false ### module.exports['IsFalse'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localId" : "1", "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "localId" : "4", "name" : "TrueIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "4", "s" : [ { "value" : [ "define ","TrueIsFalse",": " ] }, { "r" : "3", "s" : [ { "r" : "2", "value" : [ "true"," is false" ] } ] } ] } } ], "expression" : { "localId" : "3", "type" : "IsFalse", "operand" : { "localId" : "2", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "true", "type" : "Literal" } } }, { "localId" : "7", "name" : "FalseIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "7", "s" : [ { "value" : [ "define ","FalseIsFalse",": " ] }, { "r" : "6", "s" : [ { "r" : "5", "value" : [ "false"," is false" ] } ] } ] } } ], "expression" : { "localId" : "6", "type" : "IsFalse", "operand" : { "localId" : "5", "valueType" : "{urn:hl7-org:elm-types:r1}Boolean", "value" : "false", "type" : "Literal" } } }, { "localId" : "10", "name" : "NullIsFalse", "context" : "Patient", "accessLevel" : "Public", "annotation" : [ { "type" : "Annotation", "s" : { "r" : "10", "s" : [ { "value" : [ "define ","NullIsFalse",": " ] }, { "r" : "9", "s" : [ { "r" : "8", "value" : [ "null"," is false" ] } ] } ] } } ], "expression" : { "localId" : "9", "type" : "IsFalse", "operand" : { "asType" : "{urn:hl7-org:elm-types:r1}Boolean", "type" : "As", "operand" : { "localId" : "8", "type" : "Null" } } } } ] } } }
[ { "context": "',\n IS_MOBILE: true\n CURRENT_USER: 'John'\n view = new @EditorialSignupView el: @$el\n ", "end": 2230, "score": 0.9980307221412659, "start": 2226, "tag": "NAME", "value": "John" }, { "context": "',\n IS_MOBILE: true\n CURRENT_USER: 'Jo...
src/desktop/components/email/test/editorial_signup.coffee
kanaabe/force
0
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' { stubChildClasses } = require '../../../test/helpers/stubs' describe 'EditorialSignupView', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') $.fn.waypoint = sinon.stub() sinon.stub($, 'ajax') Backbone.$ = $ @clock = sinon.useFakeTimers() @$el = $(' <div> <div id="modal-container"></div> <div id="main-layout-container"></div> <div class="article-es-header"></div> </div>') @EditorialSignupView = benv.requireWithJadeify resolve(__dirname, '../client/editorial_signup'), ['editorialCTABannerTemplate'] stubChildClasses @EditorialSignupView, this, ['CTABarView'] ['previouslyDismissed', 'render', 'logDismissal', 'transitionIn', 'transitionOut', 'close'] @CTABarView::render.returns @$el @CTABarView::previouslyDismissed.returns false @EditorialSignupView.__set__ 'mediator', trigger: @mediatorTrigger = sinon.stub(), on: @mediatorOn = sinon.stub() @EditorialSignupView.__set__ 'analyticsHooks', trigger: @trigger = sinon.stub() done() afterEach -> $.ajax.restore() @clock.restore() benv.teardown() describe '#initialize', -> beforeEach -> @EditorialSignupView::setupMobileCTA = sinon.spy() @EditorialSignupView::setupDesktopCTA = sinon.spy() it 'returns if the CTA bar was previously dismissed', -> @CTABarView::previouslyDismissed.returns true view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 0 it 'returns if the user is coming from Sailthru', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_source: 'sailthru' view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 0 it 'sets up CTA for mobile users', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'John' view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 1 it 'sets up CTA for desktop users', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 1 view.setupMobileCTA.callCount.should.equal 0 describe '#setupMobileCTA', -> beforeEach -> @EditorialSignupView::showCTA = sinon.spy() @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'John' @view = new @EditorialSignupView el: @$el it 'adds the CTA banner to the page', -> $(@view.el).find('#modal-container').html().should.containEql 'articles-es-cta--banner modal' it 'shows the CTA banner', -> @view.showCTA.callCount.should.equal 1 describe '#setupDesktopCTA', -> beforeEach -> @EditorialSignupView::showCTA = sinon.spy() @EditorialSignupView::setDismissCookie = sinon.spy() @EditorialSignupView.__set__ 'sd', IS_MOBILE: false @view = new @EditorialSignupView el: @$el it 'sets the cookie when the user modal is closed or if the user has signed up', -> @mediatorOn.args.length.should.equal 2 @mediatorOn.args[0][0].should.equal 'modal:closed' @mediatorOn.args[1][0].should.equal 'auth:sign_up:success' it 'shows the user modal', -> @view.showCTA.callCount.should.equal 1 it 'returns early if the user is logged in', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false, CURRENT_USER: { name: 'Joe' } @EditorialSignupView::showCTA = sinon.spy() view = new @EditorialSignupView el: @$el view.showCTA.callCount.should.equal 0 describe '#fromSailthru', -> it 'checks if the utm_source is sailthru', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_source: 'sailthru' view = new @EditorialSignupView el: @$el view.fromSailthru().should.be.true() it 'checks if the utm_content starts with st-', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_content: 'st-lala' view = new @EditorialSignupView el: @$el view.fromSailthru().should.be.true() describe '#showCTA && #revealArticlePopup', -> it 'reveals the banner after 2000 ms on mobile', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'John' view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) @trigger.args[0][0].should.equal 'view:editorial-signup' view.$el.find('.articles-es-cta--banner').css('opacity').should.equal '1' it 'reveals the user modal after 2000 ms on desktop', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) @mediatorTrigger.args[0][0].should.equal 'open:auth' describe '#onSubscribe', -> beforeEach -> @view = new @EditorialSignupView el: @$el it 'removes the form when successful', -> $.ajax.yieldsTo('success') @view.ctaBarView = { close: sinon.stub() logDismissal: sinon.stub() } @view.onSubscribe({currentTarget: $('<div></div>')}) @view.$el.find('.articles-es-cta--banner').length.should.equal 0 @view.ctaBarView.logDismissal.callCount.should.equal 1 it 'removes the loading spinner if there is an error', -> $.ajax.yieldsTo('error') $subscribe = $('<div></div>') @view.onSubscribe({currentTarget: $subscribe}) $($subscribe).hasClass('loading-spinner').should.be.false() describe 'Dismisses modals and logs cookies', -> beforeEach -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'John' @view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) it 'sets a dismiss cookie and tracks analytics', -> @view.$el.find('.cta-bar-defer').click() @trigger.args[1][0].should.equal 'dismiss:editorial-signup'
119775
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' { stubChildClasses } = require '../../../test/helpers/stubs' describe 'EditorialSignupView', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') $.fn.waypoint = sinon.stub() sinon.stub($, 'ajax') Backbone.$ = $ @clock = sinon.useFakeTimers() @$el = $(' <div> <div id="modal-container"></div> <div id="main-layout-container"></div> <div class="article-es-header"></div> </div>') @EditorialSignupView = benv.requireWithJadeify resolve(__dirname, '../client/editorial_signup'), ['editorialCTABannerTemplate'] stubChildClasses @EditorialSignupView, this, ['CTABarView'] ['previouslyDismissed', 'render', 'logDismissal', 'transitionIn', 'transitionOut', 'close'] @CTABarView::render.returns @$el @CTABarView::previouslyDismissed.returns false @EditorialSignupView.__set__ 'mediator', trigger: @mediatorTrigger = sinon.stub(), on: @mediatorOn = sinon.stub() @EditorialSignupView.__set__ 'analyticsHooks', trigger: @trigger = sinon.stub() done() afterEach -> $.ajax.restore() @clock.restore() benv.teardown() describe '#initialize', -> beforeEach -> @EditorialSignupView::setupMobileCTA = sinon.spy() @EditorialSignupView::setupDesktopCTA = sinon.spy() it 'returns if the CTA bar was previously dismissed', -> @CTABarView::previouslyDismissed.returns true view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 0 it 'returns if the user is coming from Sailthru', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_source: 'sailthru' view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 0 it 'sets up CTA for mobile users', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: '<NAME>' view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 1 it 'sets up CTA for desktop users', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 1 view.setupMobileCTA.callCount.should.equal 0 describe '#setupMobileCTA', -> beforeEach -> @EditorialSignupView::showCTA = sinon.spy() @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: '<NAME>' @view = new @EditorialSignupView el: @$el it 'adds the CTA banner to the page', -> $(@view.el).find('#modal-container').html().should.containEql 'articles-es-cta--banner modal' it 'shows the CTA banner', -> @view.showCTA.callCount.should.equal 1 describe '#setupDesktopCTA', -> beforeEach -> @EditorialSignupView::showCTA = sinon.spy() @EditorialSignupView::setDismissCookie = sinon.spy() @EditorialSignupView.__set__ 'sd', IS_MOBILE: false @view = new @EditorialSignupView el: @$el it 'sets the cookie when the user modal is closed or if the user has signed up', -> @mediatorOn.args.length.should.equal 2 @mediatorOn.args[0][0].should.equal 'modal:closed' @mediatorOn.args[1][0].should.equal 'auth:sign_up:success' it 'shows the user modal', -> @view.showCTA.callCount.should.equal 1 it 'returns early if the user is logged in', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false, CURRENT_USER: { name: '<NAME>' } @EditorialSignupView::showCTA = sinon.spy() view = new @EditorialSignupView el: @$el view.showCTA.callCount.should.equal 0 describe '#fromSailthru', -> it 'checks if the utm_source is sailthru', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_source: 'sailthru' view = new @EditorialSignupView el: @$el view.fromSailthru().should.be.true() it 'checks if the utm_content starts with st-', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_content: 'st-lala' view = new @EditorialSignupView el: @$el view.fromSailthru().should.be.true() describe '#showCTA && #revealArticlePopup', -> it 'reveals the banner after 2000 ms on mobile', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: '<NAME>' view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) @trigger.args[0][0].should.equal 'view:editorial-signup' view.$el.find('.articles-es-cta--banner').css('opacity').should.equal '1' it 'reveals the user modal after 2000 ms on desktop', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) @mediatorTrigger.args[0][0].should.equal 'open:auth' describe '#onSubscribe', -> beforeEach -> @view = new @EditorialSignupView el: @$el it 'removes the form when successful', -> $.ajax.yieldsTo('success') @view.ctaBarView = { close: sinon.stub() logDismissal: sinon.stub() } @view.onSubscribe({currentTarget: $('<div></div>')}) @view.$el.find('.articles-es-cta--banner').length.should.equal 0 @view.ctaBarView.logDismissal.callCount.should.equal 1 it 'removes the loading spinner if there is an error', -> $.ajax.yieldsTo('error') $subscribe = $('<div></div>') @view.onSubscribe({currentTarget: $subscribe}) $($subscribe).hasClass('loading-spinner').should.be.false() describe 'Dismisses modals and logs cookies', -> beforeEach -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: '<NAME>' @view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) it 'sets a dismiss cookie and tracks analytics', -> @view.$el.find('.cta-bar-defer').click() @trigger.args[1][0].should.equal 'dismiss:editorial-signup'
true
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' { stubChildClasses } = require '../../../test/helpers/stubs' describe 'EditorialSignupView', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') $.fn.waypoint = sinon.stub() sinon.stub($, 'ajax') Backbone.$ = $ @clock = sinon.useFakeTimers() @$el = $(' <div> <div id="modal-container"></div> <div id="main-layout-container"></div> <div class="article-es-header"></div> </div>') @EditorialSignupView = benv.requireWithJadeify resolve(__dirname, '../client/editorial_signup'), ['editorialCTABannerTemplate'] stubChildClasses @EditorialSignupView, this, ['CTABarView'] ['previouslyDismissed', 'render', 'logDismissal', 'transitionIn', 'transitionOut', 'close'] @CTABarView::render.returns @$el @CTABarView::previouslyDismissed.returns false @EditorialSignupView.__set__ 'mediator', trigger: @mediatorTrigger = sinon.stub(), on: @mediatorOn = sinon.stub() @EditorialSignupView.__set__ 'analyticsHooks', trigger: @trigger = sinon.stub() done() afterEach -> $.ajax.restore() @clock.restore() benv.teardown() describe '#initialize', -> beforeEach -> @EditorialSignupView::setupMobileCTA = sinon.spy() @EditorialSignupView::setupDesktopCTA = sinon.spy() it 'returns if the CTA bar was previously dismissed', -> @CTABarView::previouslyDismissed.returns true view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 0 it 'returns if the user is coming from Sailthru', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_source: 'sailthru' view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 0 it 'sets up CTA for mobile users', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'PI:NAME:<NAME>END_PI' view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 0 view.setupMobileCTA.callCount.should.equal 1 it 'sets up CTA for desktop users', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false view = new @EditorialSignupView el: @$el view.setupDesktopCTA.callCount.should.equal 1 view.setupMobileCTA.callCount.should.equal 0 describe '#setupMobileCTA', -> beforeEach -> @EditorialSignupView::showCTA = sinon.spy() @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'PI:NAME:<NAME>END_PI' @view = new @EditorialSignupView el: @$el it 'adds the CTA banner to the page', -> $(@view.el).find('#modal-container').html().should.containEql 'articles-es-cta--banner modal' it 'shows the CTA banner', -> @view.showCTA.callCount.should.equal 1 describe '#setupDesktopCTA', -> beforeEach -> @EditorialSignupView::showCTA = sinon.spy() @EditorialSignupView::setDismissCookie = sinon.spy() @EditorialSignupView.__set__ 'sd', IS_MOBILE: false @view = new @EditorialSignupView el: @$el it 'sets the cookie when the user modal is closed or if the user has signed up', -> @mediatorOn.args.length.should.equal 2 @mediatorOn.args[0][0].should.equal 'modal:closed' @mediatorOn.args[1][0].should.equal 'auth:sign_up:success' it 'shows the user modal', -> @view.showCTA.callCount.should.equal 1 it 'returns early if the user is logged in', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false, CURRENT_USER: { name: 'PI:NAME:<NAME>END_PI' } @EditorialSignupView::showCTA = sinon.spy() view = new @EditorialSignupView el: @$el view.showCTA.callCount.should.equal 0 describe '#fromSailthru', -> it 'checks if the utm_source is sailthru', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_source: 'sailthru' view = new @EditorialSignupView el: @$el view.fromSailthru().should.be.true() it 'checks if the utm_content starts with st-', -> @EditorialSignupView.__set__ 'qs', parse: sinon.stub().returns utm_content: 'st-lala' view = new @EditorialSignupView el: @$el view.fromSailthru().should.be.true() describe '#showCTA && #revealArticlePopup', -> it 'reveals the banner after 2000 ms on mobile', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'PI:NAME:<NAME>END_PI' view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) @trigger.args[0][0].should.equal 'view:editorial-signup' view.$el.find('.articles-es-cta--banner').css('opacity').should.equal '1' it 'reveals the user modal after 2000 ms on desktop', -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: false view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) @mediatorTrigger.args[0][0].should.equal 'open:auth' describe '#onSubscribe', -> beforeEach -> @view = new @EditorialSignupView el: @$el it 'removes the form when successful', -> $.ajax.yieldsTo('success') @view.ctaBarView = { close: sinon.stub() logDismissal: sinon.stub() } @view.onSubscribe({currentTarget: $('<div></div>')}) @view.$el.find('.articles-es-cta--banner').length.should.equal 0 @view.ctaBarView.logDismissal.callCount.should.equal 1 it 'removes the loading spinner if there is an error', -> $.ajax.yieldsTo('error') $subscribe = $('<div></div>') @view.onSubscribe({currentTarget: $subscribe}) $($subscribe).hasClass('loading-spinner').should.be.false() describe 'Dismisses modals and logs cookies', -> beforeEach -> @EditorialSignupView.__set__ 'sd', IS_MOBILE: true CURRENT_USER: 'PI:NAME:<NAME>END_PI' @view = new @EditorialSignupView el: @$el $(window).scroll() @clock.tick(2000) it 'sets a dismiss cookie and tracks analytics', -> @view.$el.find('.cta-bar-defer').click() @trigger.args[1][0].should.equal 'dismiss:editorial-signup'
[ { "context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan", "end": 18, "score": 0.9998876452445984, "start": 10, "tag": "NAME", "value": "Tim Knip" }, { "context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new...
source/javascripts/new_src/loaders/collada/instance_controller.coffee
andrew-aladev/three.js
0
# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com # @author aladjev.andrew@gmail.com #= require new_src/loaders/collada/instance_material class InstanceController constructor: (loader) -> @url = "" @skeleton = [] @instance_material = [] @loader = loader parse: (element) -> @url = element.getAttribute("url").replace /^#/, "" @skeleton = [] @instance_material = [] length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "skeleton" @skeleton.push child.textContent.replace(/^#/, "") when "bind_material" instances = @loader.COLLADA.evaluate ".//dae:instance_material", child, THREE.ColladaLoader._nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null if instances instance = instances.iterateNext() while instance @instance_material.push new THREE.Collada.InstanceMaterial().parse(instance) instance = instances.iterateNext() this namespace "THREE.Collada", (exports) -> exports.InstanceController = InstanceController
139627
# @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com # @author <EMAIL> #= require new_src/loaders/collada/instance_material class InstanceController constructor: (loader) -> @url = "" @skeleton = [] @instance_material = [] @loader = loader parse: (element) -> @url = element.getAttribute("url").replace /^#/, "" @skeleton = [] @instance_material = [] length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "skeleton" @skeleton.push child.textContent.replace(/^#/, "") when "bind_material" instances = @loader.COLLADA.evaluate ".//dae:instance_material", child, THREE.ColladaLoader._nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null if instances instance = instances.iterateNext() while instance @instance_material.push new THREE.Collada.InstanceMaterial().parse(instance) instance = instances.iterateNext() this namespace "THREE.Collada", (exports) -> exports.InstanceController = InstanceController
true
# @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com # @author PI:EMAIL:<EMAIL>END_PI #= require new_src/loaders/collada/instance_material class InstanceController constructor: (loader) -> @url = "" @skeleton = [] @instance_material = [] @loader = loader parse: (element) -> @url = element.getAttribute("url").replace /^#/, "" @skeleton = [] @instance_material = [] length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "skeleton" @skeleton.push child.textContent.replace(/^#/, "") when "bind_material" instances = @loader.COLLADA.evaluate ".//dae:instance_material", child, THREE.ColladaLoader._nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null if instances instance = instances.iterateNext() while instance @instance_material.push new THREE.Collada.InstanceMaterial().parse(instance) instance = instances.iterateNext() this namespace "THREE.Collada", (exports) -> exports.InstanceController = InstanceController
[ { "context": "e.exports = class Eraser extends Pencil\n\n name: 'Eraser'\n iconName: 'eraser'\n optionsStyle: 'stroke-thi", "end": 132, "score": 0.9897934794425964, "start": 126, "tag": "NAME", "value": "Eraser" } ]
src/tools/Eraser.coffee
entrylabs/literallycanvas
4
Pencil = require './Pencil' {createShape} = require '../core/shapes' module.exports = class Eraser extends Pencil name: 'Eraser' iconName: 'eraser' optionsStyle: 'stroke-thickness' makePoint: (x, y, lc) -> createShape('Point', {x, y, size: @strokeWidth, color: '#000'}) makeShape: -> createShape('ErasedLinePath') createCursor: () -> createShape('Ellipse', { x: 0, y: 0, strokeWidth: 1, strokeColor: "#000", fillColor: 'transparent'}) updateCursor: (x, y, lc) -> @cursorShape.setUpperLeft({ x: x - @strokeWidth / 2, y: y - @strokeWidth / 2 }) @cursorShape.width = @strokeWidth + 1; @cursorShape.height = @strokeWidth + 1; convertToPoint: (x, y, lc) -> if (!@currentShape) return @currentShape = null
136127
Pencil = require './Pencil' {createShape} = require '../core/shapes' module.exports = class Eraser extends Pencil name: '<NAME>' iconName: 'eraser' optionsStyle: 'stroke-thickness' makePoint: (x, y, lc) -> createShape('Point', {x, y, size: @strokeWidth, color: '#000'}) makeShape: -> createShape('ErasedLinePath') createCursor: () -> createShape('Ellipse', { x: 0, y: 0, strokeWidth: 1, strokeColor: "#000", fillColor: 'transparent'}) updateCursor: (x, y, lc) -> @cursorShape.setUpperLeft({ x: x - @strokeWidth / 2, y: y - @strokeWidth / 2 }) @cursorShape.width = @strokeWidth + 1; @cursorShape.height = @strokeWidth + 1; convertToPoint: (x, y, lc) -> if (!@currentShape) return @currentShape = null
true
Pencil = require './Pencil' {createShape} = require '../core/shapes' module.exports = class Eraser extends Pencil name: 'PI:NAME:<NAME>END_PI' iconName: 'eraser' optionsStyle: 'stroke-thickness' makePoint: (x, y, lc) -> createShape('Point', {x, y, size: @strokeWidth, color: '#000'}) makeShape: -> createShape('ErasedLinePath') createCursor: () -> createShape('Ellipse', { x: 0, y: 0, strokeWidth: 1, strokeColor: "#000", fillColor: 'transparent'}) updateCursor: (x, y, lc) -> @cursorShape.setUpperLeft({ x: x - @strokeWidth / 2, y: y - @strokeWidth / 2 }) @cursorShape.width = @strokeWidth + 1; @cursorShape.height = @strokeWidth + 1; convertToPoint: (x, y, lc) -> if (!@currentShape) return @currentShape = null
[ { "context": "ffeescript.\n#\n# MIT License\n#\n# Copyright (c) 2015 Dennis Raymondo van der Sluis\n#\n# Permission is hereby granted, free of charge,", "end": 143, "score": 0.9998777508735657, "start": 114, "tag": "NAME", "value": "Dennis Raymondo van der Sluis" } ]
custom-log.coffee
phazelift/custom-log
0
# custom-log.coffee - A tiny console.log wrapper, written in Coffeescript. # # MIT License # # Copyright (c) 2015 Dennis Raymondo van der Sluis # # 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. # "use strict" CUSTOM_LOG = 'custom-log: ' # taken from types.js intoArray = ( args ) -> if args.length < 2 if typeof args[ 0 ] is 'string' args= args.join( '' ).replace( /^\s+|\s+$/g, '' ).replace( /\s+/g, ' ' ).split ' ' else if (typeof args[ 0 ] is 'object') and (args[ 0 ] instanceof Array) args= args[ 0 ] return args instanceOf = ( type, value ) -> value instanceof type forceObject = ( value ) -> return if (typeof value is 'object') and (value isnt null) and not instanceOf(Boolean, value) and not instanceOf(Number, value) and not instanceOf(Array, value) and not instanceOf(RegExp, value) and not instanceOf(Date, value) value else {} # # # # prefixes is primarily for creating log.anyPrefix methods # customLog= ( prefixes, settings ) -> # prefixes as string is for a only single log function with prefix prefixMsg = prefixes if typeof prefixes is 'string' prefixes = forceObject prefixes settings = forceObject settings class Log constructor: ( level, prefix ) -> @enabled = true @level = level or 'log' @prefix = prefix or '' @log = (args...) => if @enabled prefix = if (typeof @prefix is 'function') then (@prefix args...) else @prefix message = if @prefix then ([ prefix ].concat args...) else args console.log.apply console, message for own prop, value of @ if (prop isnt 'log') then @log[ prop ]= value disable: => @enabled= false if not settings.silentDisable console.log CUSTOM_LOG+ '.'+ @level+ ' is disabled' enable: => @enabled= true if not settings.silentEnable console.log CUSTOM_LOG+ '.'+ @level+ ' is enabled' # # end of Log # # create a default log right away logInstance = new Log 'log', prefixMsg log = logInstance.log # abstract function for enable and disable enact= ( method, levels... ) -> levels= intoArray levels for level in levels if level is 'log' logInstance[ method ]() else if log[ level ]? log[ level ][ method ]() log.enable = (args...) -> enact 'enable', args... log.disable = (args...) -> enact 'disable', args... # create log levels/instances from prefixes object for level, prefix of prefixes then do (level, prefix) -> switch level # allow the default log to have a prefix when 'log' then logInstance.prefix= prefix else log[ level ]= new Log( level, prefix ).log return log # # end of customLog # if define? and ( 'function' is typeof define ) and define.amd define 'customLog', [], -> customLog else if typeof module isnt 'undefined' module.exports= customLog else if typeof window isnt 'undefined' window.customLog= customLog
154133
# custom-log.coffee - A tiny console.log wrapper, written in Coffeescript. # # MIT License # # Copyright (c) 2015 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # "use strict" CUSTOM_LOG = 'custom-log: ' # taken from types.js intoArray = ( args ) -> if args.length < 2 if typeof args[ 0 ] is 'string' args= args.join( '' ).replace( /^\s+|\s+$/g, '' ).replace( /\s+/g, ' ' ).split ' ' else if (typeof args[ 0 ] is 'object') and (args[ 0 ] instanceof Array) args= args[ 0 ] return args instanceOf = ( type, value ) -> value instanceof type forceObject = ( value ) -> return if (typeof value is 'object') and (value isnt null) and not instanceOf(Boolean, value) and not instanceOf(Number, value) and not instanceOf(Array, value) and not instanceOf(RegExp, value) and not instanceOf(Date, value) value else {} # # # # prefixes is primarily for creating log.anyPrefix methods # customLog= ( prefixes, settings ) -> # prefixes as string is for a only single log function with prefix prefixMsg = prefixes if typeof prefixes is 'string' prefixes = forceObject prefixes settings = forceObject settings class Log constructor: ( level, prefix ) -> @enabled = true @level = level or 'log' @prefix = prefix or '' @log = (args...) => if @enabled prefix = if (typeof @prefix is 'function') then (@prefix args...) else @prefix message = if @prefix then ([ prefix ].concat args...) else args console.log.apply console, message for own prop, value of @ if (prop isnt 'log') then @log[ prop ]= value disable: => @enabled= false if not settings.silentDisable console.log CUSTOM_LOG+ '.'+ @level+ ' is disabled' enable: => @enabled= true if not settings.silentEnable console.log CUSTOM_LOG+ '.'+ @level+ ' is enabled' # # end of Log # # create a default log right away logInstance = new Log 'log', prefixMsg log = logInstance.log # abstract function for enable and disable enact= ( method, levels... ) -> levels= intoArray levels for level in levels if level is 'log' logInstance[ method ]() else if log[ level ]? log[ level ][ method ]() log.enable = (args...) -> enact 'enable', args... log.disable = (args...) -> enact 'disable', args... # create log levels/instances from prefixes object for level, prefix of prefixes then do (level, prefix) -> switch level # allow the default log to have a prefix when 'log' then logInstance.prefix= prefix else log[ level ]= new Log( level, prefix ).log return log # # end of customLog # if define? and ( 'function' is typeof define ) and define.amd define 'customLog', [], -> customLog else if typeof module isnt 'undefined' module.exports= customLog else if typeof window isnt 'undefined' window.customLog= customLog
true
# custom-log.coffee - A tiny console.log wrapper, written in Coffeescript. # # MIT License # # Copyright (c) 2015 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # "use strict" CUSTOM_LOG = 'custom-log: ' # taken from types.js intoArray = ( args ) -> if args.length < 2 if typeof args[ 0 ] is 'string' args= args.join( '' ).replace( /^\s+|\s+$/g, '' ).replace( /\s+/g, ' ' ).split ' ' else if (typeof args[ 0 ] is 'object') and (args[ 0 ] instanceof Array) args= args[ 0 ] return args instanceOf = ( type, value ) -> value instanceof type forceObject = ( value ) -> return if (typeof value is 'object') and (value isnt null) and not instanceOf(Boolean, value) and not instanceOf(Number, value) and not instanceOf(Array, value) and not instanceOf(RegExp, value) and not instanceOf(Date, value) value else {} # # # # prefixes is primarily for creating log.anyPrefix methods # customLog= ( prefixes, settings ) -> # prefixes as string is for a only single log function with prefix prefixMsg = prefixes if typeof prefixes is 'string' prefixes = forceObject prefixes settings = forceObject settings class Log constructor: ( level, prefix ) -> @enabled = true @level = level or 'log' @prefix = prefix or '' @log = (args...) => if @enabled prefix = if (typeof @prefix is 'function') then (@prefix args...) else @prefix message = if @prefix then ([ prefix ].concat args...) else args console.log.apply console, message for own prop, value of @ if (prop isnt 'log') then @log[ prop ]= value disable: => @enabled= false if not settings.silentDisable console.log CUSTOM_LOG+ '.'+ @level+ ' is disabled' enable: => @enabled= true if not settings.silentEnable console.log CUSTOM_LOG+ '.'+ @level+ ' is enabled' # # end of Log # # create a default log right away logInstance = new Log 'log', prefixMsg log = logInstance.log # abstract function for enable and disable enact= ( method, levels... ) -> levels= intoArray levels for level in levels if level is 'log' logInstance[ method ]() else if log[ level ]? log[ level ][ method ]() log.enable = (args...) -> enact 'enable', args... log.disable = (args...) -> enact 'disable', args... # create log levels/instances from prefixes object for level, prefix of prefixes then do (level, prefix) -> switch level # allow the default log to have a prefix when 'log' then logInstance.prefix= prefix else log[ level ]= new Log( level, prefix ).log return log # # end of customLog # if define? and ( 'function' is typeof define ) and define.amd define 'customLog', [], -> customLog else if typeof module isnt 'undefined' module.exports= customLog else if typeof window isnt 'undefined' window.customLog= customLog
[ { "context": " type: \"string\"\n username:\n title: \"XenServer username\"\n type: \"string\"\n password:\n t", "end": 250, "score": 0.9953545331954956, "start": 232, "tag": "USERNAME", "value": "XenServer username" }, { "context": " type: \"string...
configs/default/config.cson
ratokeshi/meshblu-connector-xenserver
0
title: "Default Configuration" type: "object" properties: options: title: "Options" type: "object" properties: serveraddress: title: "XenServer URL" type: "string" username: title: "XenServer username" type: "string" password: title: "XenServer password" type: "string" required: [ "serveraddress", "username", "password" ]
140680
title: "Default Configuration" type: "object" properties: options: title: "Options" type: "object" properties: serveraddress: title: "XenServer URL" type: "string" username: title: "XenServer username" type: "string" password: title: "<PASSWORD>" type: "string" required: [ "serveraddress", "username", "password" ]
true
title: "Default Configuration" type: "object" properties: options: title: "Options" type: "object" properties: serveraddress: title: "XenServer URL" type: "string" username: title: "XenServer username" type: "string" password: title: "PI:PASSWORD:<PASSWORD>END_PI" type: "string" required: [ "serveraddress", "username", "password" ]
[ { "context": "{\\\"closeButton\\\":false};toastr.warning('My name is Inigo Montoya&period; You killed my father&comma; prepare to di", "end": 1319, "score": 0.9998456835746765, "start": 1306, "tag": "NAME", "value": "Inigo Montoya" } ]
test/example.coffee
kamaln7/express-toastr
4
should = require 'should' assert = require 'assert' request = require 'supertest' app = require '../example/index.js' server = port = 4000 url = "http://localhost:#{port}" Cookies = describe 'express-toastr', -> before (done) -> server = app.listen port, (err) -> if err done err else done() after (done) -> server.close() done() it 'should exist', (done) -> should.exist app done() it 'should be listening on localhost:4000', (done) -> request url .get '/ping' .expect 200 .end (err, res) -> if err then throw err should(res.text).equal 'pong' done() it 'should set toasts properly (1/2)', (done) -> request url .get '/set' .expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' Cookies = res.headers['set-cookie'].pop().split(';')[0]; done() it 'should set toasts properly (2/2)', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal "<script type=\"text/javascript\">toastr.options={\"closeButton\":true};toastr.info('Are you the 6 fingered man&quest;');toastr.options={\"closeButton\":false};toastr.warning('My name is Inigo Montoya&period; You killed my father&comma; prepare to die&excl;');toastr.options={\"closeButton\":true};toastr.success('Have fun storming the castle&excl;','Miracle Max Says');toastr.error('I do not think that word means what you think it means&period;','Inconceivable&excl;');</script>" done() it 'should clear toasts that were viewed', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' done() it 'should clear toasts when .clear() is called (1/2)', (done) -> req = request url .get '/clear' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' done() it 'should clear toasts when .clear() is called (2/2)', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal "<script type=\"text/javascript\">toastr.options={\"closeButton\":true};toastr.info('The previous toasts were cleared&period;');</script>" done()
20315
should = require 'should' assert = require 'assert' request = require 'supertest' app = require '../example/index.js' server = port = 4000 url = "http://localhost:#{port}" Cookies = describe 'express-toastr', -> before (done) -> server = app.listen port, (err) -> if err done err else done() after (done) -> server.close() done() it 'should exist', (done) -> should.exist app done() it 'should be listening on localhost:4000', (done) -> request url .get '/ping' .expect 200 .end (err, res) -> if err then throw err should(res.text).equal 'pong' done() it 'should set toasts properly (1/2)', (done) -> request url .get '/set' .expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' Cookies = res.headers['set-cookie'].pop().split(';')[0]; done() it 'should set toasts properly (2/2)', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal "<script type=\"text/javascript\">toastr.options={\"closeButton\":true};toastr.info('Are you the 6 fingered man&quest;');toastr.options={\"closeButton\":false};toastr.warning('My name is <NAME>&period; You killed my father&comma; prepare to die&excl;');toastr.options={\"closeButton\":true};toastr.success('Have fun storming the castle&excl;','Miracle Max Says');toastr.error('I do not think that word means what you think it means&period;','Inconceivable&excl;');</script>" done() it 'should clear toasts that were viewed', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' done() it 'should clear toasts when .clear() is called (1/2)', (done) -> req = request url .get '/clear' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' done() it 'should clear toasts when .clear() is called (2/2)', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal "<script type=\"text/javascript\">toastr.options={\"closeButton\":true};toastr.info('The previous toasts were cleared&period;');</script>" done()
true
should = require 'should' assert = require 'assert' request = require 'supertest' app = require '../example/index.js' server = port = 4000 url = "http://localhost:#{port}" Cookies = describe 'express-toastr', -> before (done) -> server = app.listen port, (err) -> if err done err else done() after (done) -> server.close() done() it 'should exist', (done) -> should.exist app done() it 'should be listening on localhost:4000', (done) -> request url .get '/ping' .expect 200 .end (err, res) -> if err then throw err should(res.text).equal 'pong' done() it 'should set toasts properly (1/2)', (done) -> request url .get '/set' .expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' Cookies = res.headers['set-cookie'].pop().split(';')[0]; done() it 'should set toasts properly (2/2)', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal "<script type=\"text/javascript\">toastr.options={\"closeButton\":true};toastr.info('Are you the 6 fingered man&quest;');toastr.options={\"closeButton\":false};toastr.warning('My name is PI:NAME:<NAME>END_PI&period; You killed my father&comma; prepare to die&excl;');toastr.options={\"closeButton\":true};toastr.success('Have fun storming the castle&excl;','Miracle Max Says');toastr.error('I do not think that word means what you think it means&period;','Inconceivable&excl;');</script>" done() it 'should clear toasts that were viewed', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' done() it 'should clear toasts when .clear() is called (1/2)', (done) -> req = request url .get '/clear' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal '' done() it 'should clear toasts when .clear() is called (2/2)', (done) -> req = request url .get '/' req.cookies = Cookies req.expect 200 .end (err, res) -> if err then throw err should(res.text).equal "<script type=\"text/javascript\">toastr.options={\"closeButton\":true};toastr.info('The previous toasts were cleared&period;');</script>" done()
[ { "context": "D}', (SELECT NutzerID FROM Nutzer WHERE Name = '#{Nutzername}'))\", (err, row) ->\n\t\t\tif err\n\t\t\t\tbot.logger.erro", "end": 4124, "score": 0.9301008582115173, "start": 4114, "tag": "USERNAME", "value": "Nutzername" }, { "context": "onn.query 'select id from termin...
docker/hubot/scripts/termine.coffee
ohli/steckerbot
0
mysql = require 'mysql' module.exports = (bot) -> conversation={} url = process.env.MYSQL_URL bot.logger.info "MySQL URl: " + url conn = mysql.createConnection(url) conn.connect (err) -> if err? bot.logger.info "Error\n#{err}" else bot.logger.info "connected to mysql" ################ Text Listener bot.hear /wie bedient man den bot/i, (res) -> hilfe res #res.send "es gibt noch keine hilfe" bot.hear /^\s*hilfe\s*/i, (res) -> hilfe res #res.reply "du bist verloren" bot.hear /erstelle\s+sitzung\s+(.+)\s+am\s+(.+)\s+um\s+(\d\d:\d\d)\s+bis(\d\d:\d\d)/i, (res) -> erstellesitzung res.match[2],res.match[3],res.match[4],res.match[1],(r) -> if r bot.reply "Die Sitzung wurde angelegt" bot.reply "#{res.match[1]} #{res.match[2]} #{res.match[3]}" else bot.reply "Fehler: der Termin konnte nicht erstellt werden" bot.logger.info res.match[1],res.match[2],res.match[3] # bot.hear /wer nimmt alles an termin (.*) teil/i, (res) -> # bot.logger.info "noch nicht implementiert" bot.hear /\s*Wann\s*ist\s*die\s*nächste\s*Schicht\s*\?/i, (res) -> nutzer=res.envelope.user.id conn.query "SELECT TerminTyp.Name, ADDTIME(Termin.Datum, Schicht.Beginn) as genauertermin FROM (SELECT terminschichtid from TerminSchicht) as ts left join TerminSchicht on TerminSchicht.terminschichtid = ts.terminschichtid left join Schicht on TerminSchicht.SchichtID = Schicht.SchichtID left join Termin on Termin.terminid = TerminSchicht.terminid left join TerminTyp on TerminTyp.TerminTypID = Termin.TerminTypID where ADDTIME(Termin.Datum, Schicht.Beginn) >= NOW() order by genauertermin ASC LIMIT 1", (err, rows) -> if err bot.reply "Ich konnte die nächste Schicht nicht finden." + err else conversation.vorher="nächsterTermin" conversation.nutzer=nutzer name=rows[0].Name genauertermin=rows[0].genauertermin conversation.schichtname=name conversation.genauertermin=genauertermin res.reply "Die nächste Schicht ist: #{name} #{genauertermin}" bot.hear /\s*trage?\s*mich\s*ein/i, (res) -> nutzer=res.envelope.user.id genauertermin=conversation.genauertermin name=conversation.schichtname #bot.logger.info "ich habe dich gehört" if conversation.nutzer == nutzer && conversation.vorher == "nächsterTermin" #bot.logger.info "insert into NutzerSchicht (terminschichtid, nutzerid) values ((select terminschichtid from TerminSchicht where schichtid = (select schichtid from Schicht where beginn = TIME('#{genauertermin}')) and terminid = (select terminid from Termin where termintypid = (select termintypid from TerminTyp where name = '#{name}') and datum = DATE('#{genauertermin}'))), (select nutzerid from SlackNutzer where slacknutzerid = '#{nutzer}'));" conn.query "insert into NutzerSchicht (terminschichtid, nutzerid) values ((select terminschichtid from TerminSchicht where schichtid = (select schichtid from Schicht where beginn = TIME('#{genauertermin}')) and terminid = (select terminid from Termin where termintypid = (select termintypid from TerminTyp where name = '#{name}') and datum = DATE('#{genauertermin}'))), (select nutzerid from SlackNutzer where slacknutzerid = '#{nutzer}'));", (err, rows) -> if err res.reply "Das hat nicht geklappt." bot.logger.info err else bot.logger.info "#{nutzer} wurde in eine Schicht eingetragen" res.reply "Ich habe dich in die Schicht eingetragen." bot.hear /\s*danke\s*/i, (res) -> nutzer=res.envelope.user.id if conversation.nutzer == nutzer conversation={} res.reply "Gern geschehen." bot.hear /\s*egal bei welchem Wetter\s*/i, (res) -> res.reply "Wir saufen heut' im Stecker :beer:" ################ Command Listener # ANLEGE-BEFEHLE bot.respond /füge mich der Datenbank hinzu als (.*)/i, (res) -> SlackNutzerID = res.envelope.user.id Nutzername = res.match[1] bot.logger.info res.envelope.user.real_name + " wird zur DB hinzugefügt" conn.query "INSERT INTO SlackNutzer (SlackNutzerID, NutzerID) VALUES ('#{SlackNutzerID}', (SELECT NutzerID FROM Nutzer WHERE Name = '#{Nutzername}'))", (err, row) -> if err bot.logger.error "ERROR " + err res.reply "Es ist etwas schief gelaufen :(" #res.reply err if row bot.logger.info row res.reply res.envelope.user.real_name + " wurde in die Datenbank als " + Nutzername + " eingefügt" bot.respond /erstelle termintyp (.*)/i, (msg) -> termintyp = msg.match[1] conn.query "insert into TerminTyp (Name) VALUES ('#{termintyp}')", (err, row) -> if err msg.reply "Der Termintyp konnte nicht angelegt werden. " + err else msg.reply "Der Termintyp wurde angelegt." # ANZEIGE-BEFEHLE bot.respond /zeige Schicht/i, (res) -> Slacknutzer = res.envelope.user.id conn.query "SELECT TerminTyp.Name, ADDTIME(Termin.Datum, Schicht.Beginn) as genauertermin FROM ( SELECT terminschichtid from NutzerSchicht where NutzerID = (SELECT nutzerid from SlackNutzer where SlackNutzerID = '#{Slacknutzer}') ) as ns left join TerminSchicht on TerminSchicht.terminschichtid = ns.terminschichtid left join Schicht on TerminSchicht.SchichtID = Schicht.SchichtID left join Termin on Termin.terminid = TerminSchicht.terminid left join TerminTyp on TerminTyp.TerminTypID = Termin.TerminTypID where ADDTIME(Termin.Datum, Schicht.Beginn) >= NOW() order by genauertermin ASC LIMIT 1", (err, rows) -> if err or rows.length == 0 bot.logger.info "Datenbankabfrage schlug fehl." res.reply "Das hat nicht geklappt." else if rows.length > 1 res.reply "Es dürfte nur die nächste Schicht zurückkommen." else name=rows[0].Name genauertermin=rows[0].genauertermin res.reply "Als nächstes steht für dich folgendes an: #{name} #{genauertermin}" bot.respond /hilfe/i, (res) -> hilfe res erstellesitzung = (datum, zeit, ende, name, callback) -> conn.query 'select id from termintyp where name = "Sitzung"', (err, response) -> if err bot.logger.info "ERROR bei Abfrage des Termintyps Sitzung" bot.logger.info err else if response.length > 1 bot.logger.info "ERROR mehr als eine Sitzung gefunden" else bot.logger.info response[0] bot.logger.info "Die TermintypID ist #{response[0].id}" id = response[0].id conn.query "INSERT INTO termine (name, datum, typ) VALUES ('#{name}', STR_TO_DATE('#{datum}', '%d.%m.%Y'), '#{id}')", (err, response) -> bot.logger.info "INSERT für Sitzung" if err bot.logger.info "ERROR" bot.logger.info err callback false if response bot.logger.info response bot.logger.info "Termin erstellt für #{datum} #{name} #{id}" callback true hilfe = (res) -> res.reply "Hallo, aktuell verstehe ich folgende Kommandos:\n \ ping :\t testet Verbindung des Bots \n \ Füge mich der Datenbank hinzu als <Name> :\t fügt Nutzer initial mit dem Namen <Name> der DB hinzu \n \ Wann ist die nächste Schicht? :\t zeigt nächste verfügbare Schicht an \n \ Trag mich ein :\t trägt Nutzer in zuvor angezeigte Schicht ein \n \ Danke :\t beendet die Konversation im aktuellen Kontext \n \ ...es gibt noch weitere Befehle, entdecke die Möglichkeiten"
177681
mysql = require 'mysql' module.exports = (bot) -> conversation={} url = process.env.MYSQL_URL bot.logger.info "MySQL URl: " + url conn = mysql.createConnection(url) conn.connect (err) -> if err? bot.logger.info "Error\n#{err}" else bot.logger.info "connected to mysql" ################ Text Listener bot.hear /wie bedient man den bot/i, (res) -> hilfe res #res.send "es gibt noch keine hilfe" bot.hear /^\s*hilfe\s*/i, (res) -> hilfe res #res.reply "du bist verloren" bot.hear /erstelle\s+sitzung\s+(.+)\s+am\s+(.+)\s+um\s+(\d\d:\d\d)\s+bis(\d\d:\d\d)/i, (res) -> erstellesitzung res.match[2],res.match[3],res.match[4],res.match[1],(r) -> if r bot.reply "Die Sitzung wurde angelegt" bot.reply "#{res.match[1]} #{res.match[2]} #{res.match[3]}" else bot.reply "Fehler: der Termin konnte nicht erstellt werden" bot.logger.info res.match[1],res.match[2],res.match[3] # bot.hear /wer nimmt alles an termin (.*) teil/i, (res) -> # bot.logger.info "noch nicht implementiert" bot.hear /\s*Wann\s*ist\s*die\s*nächste\s*Schicht\s*\?/i, (res) -> nutzer=res.envelope.user.id conn.query "SELECT TerminTyp.Name, ADDTIME(Termin.Datum, Schicht.Beginn) as genauertermin FROM (SELECT terminschichtid from TerminSchicht) as ts left join TerminSchicht on TerminSchicht.terminschichtid = ts.terminschichtid left join Schicht on TerminSchicht.SchichtID = Schicht.SchichtID left join Termin on Termin.terminid = TerminSchicht.terminid left join TerminTyp on TerminTyp.TerminTypID = Termin.TerminTypID where ADDTIME(Termin.Datum, Schicht.Beginn) >= NOW() order by genauertermin ASC LIMIT 1", (err, rows) -> if err bot.reply "Ich konnte die nächste Schicht nicht finden." + err else conversation.vorher="nächsterTermin" conversation.nutzer=nutzer name=rows[0].Name genauertermin=rows[0].genauertermin conversation.schichtname=name conversation.genauertermin=genauertermin res.reply "Die nächste Schicht ist: #{name} #{genauertermin}" bot.hear /\s*trage?\s*mich\s*ein/i, (res) -> nutzer=res.envelope.user.id genauertermin=conversation.genauertermin name=conversation.schichtname #bot.logger.info "ich habe dich gehört" if conversation.nutzer == nutzer && conversation.vorher == "nächsterTermin" #bot.logger.info "insert into NutzerSchicht (terminschichtid, nutzerid) values ((select terminschichtid from TerminSchicht where schichtid = (select schichtid from Schicht where beginn = TIME('#{genauertermin}')) and terminid = (select terminid from Termin where termintypid = (select termintypid from TerminTyp where name = '#{name}') and datum = DATE('#{genauertermin}'))), (select nutzerid from SlackNutzer where slacknutzerid = '#{nutzer}'));" conn.query "insert into NutzerSchicht (terminschichtid, nutzerid) values ((select terminschichtid from TerminSchicht where schichtid = (select schichtid from Schicht where beginn = TIME('#{genauertermin}')) and terminid = (select terminid from Termin where termintypid = (select termintypid from TerminTyp where name = '#{name}') and datum = DATE('#{genauertermin}'))), (select nutzerid from SlackNutzer where slacknutzerid = '#{nutzer}'));", (err, rows) -> if err res.reply "Das hat nicht geklappt." bot.logger.info err else bot.logger.info "#{nutzer} wurde in eine Schicht eingetragen" res.reply "Ich habe dich in die Schicht eingetragen." bot.hear /\s*danke\s*/i, (res) -> nutzer=res.envelope.user.id if conversation.nutzer == nutzer conversation={} res.reply "Gern geschehen." bot.hear /\s*egal bei welchem Wetter\s*/i, (res) -> res.reply "Wir saufen heut' im Stecker :beer:" ################ Command Listener # ANLEGE-BEFEHLE bot.respond /füge mich der Datenbank hinzu als (.*)/i, (res) -> SlackNutzerID = res.envelope.user.id Nutzername = res.match[1] bot.logger.info res.envelope.user.real_name + " wird zur DB hinzugefügt" conn.query "INSERT INTO SlackNutzer (SlackNutzerID, NutzerID) VALUES ('#{SlackNutzerID}', (SELECT NutzerID FROM Nutzer WHERE Name = '#{Nutzername}'))", (err, row) -> if err bot.logger.error "ERROR " + err res.reply "Es ist etwas schief gelaufen :(" #res.reply err if row bot.logger.info row res.reply res.envelope.user.real_name + " wurde in die Datenbank als " + Nutzername + " eingefügt" bot.respond /erstelle termintyp (.*)/i, (msg) -> termintyp = msg.match[1] conn.query "insert into TerminTyp (Name) VALUES ('#{termintyp}')", (err, row) -> if err msg.reply "Der Termintyp konnte nicht angelegt werden. " + err else msg.reply "Der Termintyp wurde angelegt." # ANZEIGE-BEFEHLE bot.respond /zeige Schicht/i, (res) -> Slacknutzer = res.envelope.user.id conn.query "SELECT TerminTyp.Name, ADDTIME(Termin.Datum, Schicht.Beginn) as genauertermin FROM ( SELECT terminschichtid from NutzerSchicht where NutzerID = (SELECT nutzerid from SlackNutzer where SlackNutzerID = '#{Slacknutzer}') ) as ns left join TerminSchicht on TerminSchicht.terminschichtid = ns.terminschichtid left join Schicht on TerminSchicht.SchichtID = Schicht.SchichtID left join Termin on Termin.terminid = TerminSchicht.terminid left join TerminTyp on TerminTyp.TerminTypID = Termin.TerminTypID where ADDTIME(Termin.Datum, Schicht.Beginn) >= NOW() order by genauertermin ASC LIMIT 1", (err, rows) -> if err or rows.length == 0 bot.logger.info "Datenbankabfrage schlug fehl." res.reply "Das hat nicht geklappt." else if rows.length > 1 res.reply "Es dürfte nur die nächste Schicht zurückkommen." else name=rows[0].Name genauertermin=rows[0].genauertermin res.reply "Als nächstes steht für dich folgendes an: #{name} #{genauertermin}" bot.respond /hilfe/i, (res) -> hilfe res erstellesitzung = (datum, zeit, ende, name, callback) -> conn.query 'select id from termintyp where name = "<NAME>"', (err, response) -> if err bot.logger.info "ERROR bei Abfrage des Termintyps Sitzung" bot.logger.info err else if response.length > 1 bot.logger.info "ERROR mehr als eine Sitzung gefunden" else bot.logger.info response[0] bot.logger.info "Die TermintypID ist #{response[0].id}" id = response[0].id conn.query "INSERT INTO termine (name, datum, typ) VALUES ('#{name}', STR_TO_DATE('#{datum}', '%d.%m.%Y'), '#{id}')", (err, response) -> bot.logger.info "INSERT für Sitzung" if err bot.logger.info "ERROR" bot.logger.info err callback false if response bot.logger.info response bot.logger.info "Termin erstellt für #{datum} #{name} #{id}" callback true hilfe = (res) -> res.reply "Hallo, aktuell verstehe ich folgende Kommandos:\n \ ping :\t testet Verbindung des Bots \n \ Füge mich der Datenbank hinzu als <Name> :\t fügt Nutzer initial mit dem Namen <Name> der DB hinzu \n \ Wann ist die nächste Schicht? :\t zeigt nächste verfügbare Schicht an \n \ Trag mich ein :\t trägt Nutzer in zuvor angezeigte Schicht ein \n \ Danke :\t beendet die Konversation im aktuellen Kontext \n \ ...es gibt noch weitere Befehle, entdecke die Möglichkeiten"
true
mysql = require 'mysql' module.exports = (bot) -> conversation={} url = process.env.MYSQL_URL bot.logger.info "MySQL URl: " + url conn = mysql.createConnection(url) conn.connect (err) -> if err? bot.logger.info "Error\n#{err}" else bot.logger.info "connected to mysql" ################ Text Listener bot.hear /wie bedient man den bot/i, (res) -> hilfe res #res.send "es gibt noch keine hilfe" bot.hear /^\s*hilfe\s*/i, (res) -> hilfe res #res.reply "du bist verloren" bot.hear /erstelle\s+sitzung\s+(.+)\s+am\s+(.+)\s+um\s+(\d\d:\d\d)\s+bis(\d\d:\d\d)/i, (res) -> erstellesitzung res.match[2],res.match[3],res.match[4],res.match[1],(r) -> if r bot.reply "Die Sitzung wurde angelegt" bot.reply "#{res.match[1]} #{res.match[2]} #{res.match[3]}" else bot.reply "Fehler: der Termin konnte nicht erstellt werden" bot.logger.info res.match[1],res.match[2],res.match[3] # bot.hear /wer nimmt alles an termin (.*) teil/i, (res) -> # bot.logger.info "noch nicht implementiert" bot.hear /\s*Wann\s*ist\s*die\s*nächste\s*Schicht\s*\?/i, (res) -> nutzer=res.envelope.user.id conn.query "SELECT TerminTyp.Name, ADDTIME(Termin.Datum, Schicht.Beginn) as genauertermin FROM (SELECT terminschichtid from TerminSchicht) as ts left join TerminSchicht on TerminSchicht.terminschichtid = ts.terminschichtid left join Schicht on TerminSchicht.SchichtID = Schicht.SchichtID left join Termin on Termin.terminid = TerminSchicht.terminid left join TerminTyp on TerminTyp.TerminTypID = Termin.TerminTypID where ADDTIME(Termin.Datum, Schicht.Beginn) >= NOW() order by genauertermin ASC LIMIT 1", (err, rows) -> if err bot.reply "Ich konnte die nächste Schicht nicht finden." + err else conversation.vorher="nächsterTermin" conversation.nutzer=nutzer name=rows[0].Name genauertermin=rows[0].genauertermin conversation.schichtname=name conversation.genauertermin=genauertermin res.reply "Die nächste Schicht ist: #{name} #{genauertermin}" bot.hear /\s*trage?\s*mich\s*ein/i, (res) -> nutzer=res.envelope.user.id genauertermin=conversation.genauertermin name=conversation.schichtname #bot.logger.info "ich habe dich gehört" if conversation.nutzer == nutzer && conversation.vorher == "nächsterTermin" #bot.logger.info "insert into NutzerSchicht (terminschichtid, nutzerid) values ((select terminschichtid from TerminSchicht where schichtid = (select schichtid from Schicht where beginn = TIME('#{genauertermin}')) and terminid = (select terminid from Termin where termintypid = (select termintypid from TerminTyp where name = '#{name}') and datum = DATE('#{genauertermin}'))), (select nutzerid from SlackNutzer where slacknutzerid = '#{nutzer}'));" conn.query "insert into NutzerSchicht (terminschichtid, nutzerid) values ((select terminschichtid from TerminSchicht where schichtid = (select schichtid from Schicht where beginn = TIME('#{genauertermin}')) and terminid = (select terminid from Termin where termintypid = (select termintypid from TerminTyp where name = '#{name}') and datum = DATE('#{genauertermin}'))), (select nutzerid from SlackNutzer where slacknutzerid = '#{nutzer}'));", (err, rows) -> if err res.reply "Das hat nicht geklappt." bot.logger.info err else bot.logger.info "#{nutzer} wurde in eine Schicht eingetragen" res.reply "Ich habe dich in die Schicht eingetragen." bot.hear /\s*danke\s*/i, (res) -> nutzer=res.envelope.user.id if conversation.nutzer == nutzer conversation={} res.reply "Gern geschehen." bot.hear /\s*egal bei welchem Wetter\s*/i, (res) -> res.reply "Wir saufen heut' im Stecker :beer:" ################ Command Listener # ANLEGE-BEFEHLE bot.respond /füge mich der Datenbank hinzu als (.*)/i, (res) -> SlackNutzerID = res.envelope.user.id Nutzername = res.match[1] bot.logger.info res.envelope.user.real_name + " wird zur DB hinzugefügt" conn.query "INSERT INTO SlackNutzer (SlackNutzerID, NutzerID) VALUES ('#{SlackNutzerID}', (SELECT NutzerID FROM Nutzer WHERE Name = '#{Nutzername}'))", (err, row) -> if err bot.logger.error "ERROR " + err res.reply "Es ist etwas schief gelaufen :(" #res.reply err if row bot.logger.info row res.reply res.envelope.user.real_name + " wurde in die Datenbank als " + Nutzername + " eingefügt" bot.respond /erstelle termintyp (.*)/i, (msg) -> termintyp = msg.match[1] conn.query "insert into TerminTyp (Name) VALUES ('#{termintyp}')", (err, row) -> if err msg.reply "Der Termintyp konnte nicht angelegt werden. " + err else msg.reply "Der Termintyp wurde angelegt." # ANZEIGE-BEFEHLE bot.respond /zeige Schicht/i, (res) -> Slacknutzer = res.envelope.user.id conn.query "SELECT TerminTyp.Name, ADDTIME(Termin.Datum, Schicht.Beginn) as genauertermin FROM ( SELECT terminschichtid from NutzerSchicht where NutzerID = (SELECT nutzerid from SlackNutzer where SlackNutzerID = '#{Slacknutzer}') ) as ns left join TerminSchicht on TerminSchicht.terminschichtid = ns.terminschichtid left join Schicht on TerminSchicht.SchichtID = Schicht.SchichtID left join Termin on Termin.terminid = TerminSchicht.terminid left join TerminTyp on TerminTyp.TerminTypID = Termin.TerminTypID where ADDTIME(Termin.Datum, Schicht.Beginn) >= NOW() order by genauertermin ASC LIMIT 1", (err, rows) -> if err or rows.length == 0 bot.logger.info "Datenbankabfrage schlug fehl." res.reply "Das hat nicht geklappt." else if rows.length > 1 res.reply "Es dürfte nur die nächste Schicht zurückkommen." else name=rows[0].Name genauertermin=rows[0].genauertermin res.reply "Als nächstes steht für dich folgendes an: #{name} #{genauertermin}" bot.respond /hilfe/i, (res) -> hilfe res erstellesitzung = (datum, zeit, ende, name, callback) -> conn.query 'select id from termintyp where name = "PI:NAME:<NAME>END_PI"', (err, response) -> if err bot.logger.info "ERROR bei Abfrage des Termintyps Sitzung" bot.logger.info err else if response.length > 1 bot.logger.info "ERROR mehr als eine Sitzung gefunden" else bot.logger.info response[0] bot.logger.info "Die TermintypID ist #{response[0].id}" id = response[0].id conn.query "INSERT INTO termine (name, datum, typ) VALUES ('#{name}', STR_TO_DATE('#{datum}', '%d.%m.%Y'), '#{id}')", (err, response) -> bot.logger.info "INSERT für Sitzung" if err bot.logger.info "ERROR" bot.logger.info err callback false if response bot.logger.info response bot.logger.info "Termin erstellt für #{datum} #{name} #{id}" callback true hilfe = (res) -> res.reply "Hallo, aktuell verstehe ich folgende Kommandos:\n \ ping :\t testet Verbindung des Bots \n \ Füge mich der Datenbank hinzu als <Name> :\t fügt Nutzer initial mit dem Namen <Name> der DB hinzu \n \ Wann ist die nächste Schicht? :\t zeigt nächste verfügbare Schicht an \n \ Trag mich ein :\t trägt Nutzer in zuvor angezeigte Schicht ein \n \ Danke :\t beendet die Konversation im aktuellen Kontext \n \ ...es gibt noch weitere Befehle, entdecke die Möglichkeiten"
[ { "context": ">\n evt = _registerEvent\n name: nameA\n callBack: callBackA\n\n expec", "end": 1444, "score": 0.8282486200332642, "start": 1440, "tag": "NAME", "value": "name" }, { "context": ">\n evt = _registerEvent\n name:...
test/EventService.coffee
marc-ed-raffalli/EventService
2
# global require 'use strict' EventService = require '../src/EventService.js' Event = require '../src/Event.js' testEvtArr = [] nameA = 'nameA' channelA = 'channelA' evtService = undefined callBackA = undefined priorityDefault = 1 priorityA = 2 _registerEvent = (evtArgs) -> evt = evtService.on evtArgs testEvtArr.push evt return evt cleanAllEvts = -> testEvtArr.forEach (evt)-> evtService.off evt testEvtArr = [] eventServiceTestRunner = -> # ------------------------------------------------------ describe 'EventService', -> # ---------------------------------------- describe 'Class definition', -> it 'EventService API should be defined', -> expect(EventService).not.to.be.undefined expect(EventService.prototype.on).not.to.be.undefined expect(EventService.prototype.off).not.to.be.undefined expect(EventService.prototype.trigger).not.to.be.undefined # ---------------------------------------- # ---------------------------------------- describe 'API', -> beforeEach -> callBackA = sinon.spy() evtService = new EventService() afterEach -> cleanAllEvts() evtService = undefined describe 'EventService on()', -> # ------------------------------------------------------- it 'should accept minimum arguments / event name and callback', -> evt = _registerEvent name: nameA callBack: callBackA expect(evt).not.to.be.undefined expect(evt instanceof Event).to.be.true expect(evt.name).to.equal nameA expect(evt.callBack).to.equal callBackA expect(evt.callBack.callCount).to.equal 0 # default values expect(evt.priority).to.equal priorityDefault expect(evt.channel).to.equal undefined # ------------------------------------------------------- it 'should accept full arguments / event name, callback, channel and priority', -> evt = _registerEvent name: nameA channel: channelA callBack: callBackA priority: priorityA expect(evt).not.to.be.undefined expect(evt instanceof Event).to.be.true expect(evt.name).to.equal nameA expect(evt.channel).to.equal channelA expect(evt.callBack).to.equal callBackA expect(evt.callBack.callCount).to.equal 0 expect(evt.priority).to.equal priorityA # ------------------------------------------------------- it 'should throw if name is not string', -> fn = -> evtService.on name: 1 expect(fn).to.throw # ------------------------------------------------------- it 'should throw if name or callback are missing', -> missingNameClbkFunc = -> evtService.on() missingNameFunc = -> evtService.on callBack: -> missingClbkFunc = -> evtService.on name: nameA expect(missingNameClbkFunc).to.throw expect(missingNameFunc).to.throw expect(missingClbkFunc).to.throw # ------------------------------------------------------- # ------------------------------------------------------- describe 'EventService off()', -> # ------------------------------------------------------- it 'should remove event from default channel', -> params = name: nameA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params # triggers 3 times evtService.trigger name: nameA callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off evt2 # triggers 2 times evtService.trigger name: nameA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from default channel based on selector filter', -> params = priority: 1 name: nameA callBack: callBackA _registerEvent params #priority 1 params.priority = 2 _registerEvent params #priority 2 _registerEvent params #priority 2 evtService.trigger name: nameA # triggers 3 times callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 2 events evtService.off selector: (e)-> return e.priority == 2 # triggers 1 event evtService.trigger name: nameA expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- it 'should remove event from default channel based on event name', -> params = name: nameA callBack: callBackA _registerEvent params #priority 1 _registerEvent params #priority 1 params.name = 'anotherEventName' _registerEvent params #priority 1 evtService.trigger name: nameA callCount = callBackA.callCount expect(callCount).to.equal 2 evtService.off name: nameA evtService.trigger name: nameA # check the event registered under nameA are cleared # the callCount should be unchanged expect(callBackA.callCount).to.equal callCount # only the other event should be left evtService.trigger selector: (e)-> return e.priority == 1 # check the other event registered are left expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- it 'should remove event from defined channel', -> params = name: nameA channel: channelA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params # triggers 3 times evtService.trigger name: nameA channel: channelA callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off evt2 # triggers 2 times evtService.trigger name: nameA channel: channelA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from defined channel based on priority filter', -> params = priority: 2 name: nameA callBack: callBackA _registerEvent params #priority 2 params.priority = 3 _registerEvent params #priority 3 _registerEvent params #priority 3 # triggers 3 times evtService.trigger name: nameA callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off selector: (e)-> return e.priority == 2 # triggers 2 times evtService.trigger name: nameA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from defined channel based on event name', -> params = name: nameA channel: channelA callBack: callBackA _registerEvent params #priority default _registerEvent params #priority default params.name = 'anotherEventName' _registerEvent params #priority default # triggers 2 events evtService.trigger name: nameA channel: channelA callCount = callBackA.callCount expect(callCount).to.equal 2 # removes 2 evtService.off name: nameA channel: channelA # triggers 0 evtService.trigger name: nameA channel: channelA # check the event registered under nameA are cleared # the callCount should be unchanged expect(callBackA.callCount).to.equal callCount evtService.trigger channel: channelA prioritySelector: (e)-> return e.priority == priorityDefault # check the other event registered are left expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- # ------------------------------------------------------- describe 'EventService trigger()', -> # ------------------------------------------------------- it 'should trigger event registered on default channel', (done) -> _registerEvent name: nameA callBack: -> done() evtService.trigger name: nameA # ------------------------------------------------------- it 'should trigger event registered on defined channel', (done) -> _registerEvent name: nameA channel: channelA callBack: -> done() evtService.trigger name: nameA channel: channelA # ------------------------------------------------------- it 'should trigger events based on priority', (done) -> ctr = 0 # last _registerEvent # priority 1 default name: nameA callBack: -> expect(ctr).to.equal 11 done() # second _registerEvent name: nameA priority: 2 callBack: -> expect(ctr).to.equal 1 ctr += 10 # first _registerEvent name: nameA priority: 3 callBack: -> expect(ctr).to.equal 0 ctr++ evtService.trigger name: nameA # ------------------------------------------------------- it 'should trigger events filtered on selector', -> ctr = 0 # fourth / last _registerEvent name: nameA callBack: -> ctr++ # second _registerEvent name: nameA priority: 2 callBack: -> ctr += 10 # first _registerEvent name: nameA priority: 3 callBack: -> ctr += 100 _registerEvent name: 'anotherEventName' priority: 3 callBack: -> ctr += 1000 # should trigger all events nameA evtService.trigger selector: (e)-> return e.name == nameA expect(ctr).to.equal 111 ctr = 0 # should trigger only one evtService.trigger name: nameA selector: (e)-> return e.priority == 3 expect(ctr).to.equal 100 ctr = 0 # should trigger two evtService.trigger name: nameA selector: (e)-> return e.priority >= 2 expect(ctr).to.equal 110 ctr = 0 # should trigger all but the first evtService.trigger selector: (e)-> return e.priority >= 2 expect(ctr).to.equal 1110 # ------------------------------------------------------- it 'should trigger event passing parameters on default channel', -> evt = _registerEvent name: nameA callBack: callBackA evtService.trigger name: nameA , 1, 2, 3 expect(evt.callBack.firstCall.calledWith(1, 2, 3)).to.be.true; # ------------------------------------------------------- it 'should trigger event passing parameters on defined channel', -> evt = _registerEvent name: nameA channel: channelA callBack: callBackA evtService.trigger name: nameA channel: channelA , 1, 2, 3 expect(evt.callBack.firstCall.calledWith(1, 2, 3)).to.be.true; # ------------------------------------------------------- it 'should trigger event as many times as registered', -> params = name: nameA channel: channelA callBack: callBackA _registerEvent params _registerEvent params _registerEvent params evtService.trigger name: nameA channel: channelA expect(callBackA.callCount).to.equal 3 # ------------------------------------------------------- it 'should not trigger if the event is paused', -> params = name: nameA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.pause() evtService.trigger name: nameA expect(callBackA.callCount).to.equal 2 # ------------------------------------------------------- it 'should trigger if the event is resumed', -> params = name: nameA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.pause() evtService.trigger name: nameA callCount = callBackA.callCount expect(callCount).to.equal 2 evt2.resume() evtService.trigger name: nameA expect(callBackA.callCount).to.equal (callCount + 3) # ------------------------------------------------------- it 'should not trigger if the event is stopped', -> ctr = 0 params = name: nameA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.stop() evtService.trigger name: nameA expect(callBackA.callCount).to.equal 2 #------------------------------------------------------------ #------------------------------------------------------------ module.exports = eventServiceTestRunner;
11820
# global require 'use strict' EventService = require '../src/EventService.js' Event = require '../src/Event.js' testEvtArr = [] nameA = 'nameA' channelA = 'channelA' evtService = undefined callBackA = undefined priorityDefault = 1 priorityA = 2 _registerEvent = (evtArgs) -> evt = evtService.on evtArgs testEvtArr.push evt return evt cleanAllEvts = -> testEvtArr.forEach (evt)-> evtService.off evt testEvtArr = [] eventServiceTestRunner = -> # ------------------------------------------------------ describe 'EventService', -> # ---------------------------------------- describe 'Class definition', -> it 'EventService API should be defined', -> expect(EventService).not.to.be.undefined expect(EventService.prototype.on).not.to.be.undefined expect(EventService.prototype.off).not.to.be.undefined expect(EventService.prototype.trigger).not.to.be.undefined # ---------------------------------------- # ---------------------------------------- describe 'API', -> beforeEach -> callBackA = sinon.spy() evtService = new EventService() afterEach -> cleanAllEvts() evtService = undefined describe 'EventService on()', -> # ------------------------------------------------------- it 'should accept minimum arguments / event name and callback', -> evt = _registerEvent name: <NAME>A callBack: callBackA expect(evt).not.to.be.undefined expect(evt instanceof Event).to.be.true expect(evt.name).to.equal nameA expect(evt.callBack).to.equal callBackA expect(evt.callBack.callCount).to.equal 0 # default values expect(evt.priority).to.equal priorityDefault expect(evt.channel).to.equal undefined # ------------------------------------------------------- it 'should accept full arguments / event name, callback, channel and priority', -> evt = _registerEvent name: <NAME>A channel: channelA callBack: callBackA priority: priorityA expect(evt).not.to.be.undefined expect(evt instanceof Event).to.be.true expect(evt.name).to.equal nameA expect(evt.channel).to.equal channelA expect(evt.callBack).to.equal callBackA expect(evt.callBack.callCount).to.equal 0 expect(evt.priority).to.equal priorityA # ------------------------------------------------------- it 'should throw if name is not string', -> fn = -> evtService.on name: 1 expect(fn).to.throw # ------------------------------------------------------- it 'should throw if name or callback are missing', -> missingNameClbkFunc = -> evtService.on() missingNameFunc = -> evtService.on callBack: -> missingClbkFunc = -> evtService.on name: nameA expect(missingNameClbkFunc).to.throw expect(missingNameFunc).to.throw expect(missingClbkFunc).to.throw # ------------------------------------------------------- # ------------------------------------------------------- describe 'EventService off()', -> # ------------------------------------------------------- it 'should remove event from default channel', -> params = name: <NAME> callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params # triggers 3 times evtService.trigger name: <NAME> callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off evt2 # triggers 2 times evtService.trigger name: <NAME>A expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from default channel based on selector filter', -> params = priority: 1 name: <NAME> callBack: callBackA _registerEvent params #priority 1 params.priority = 2 _registerEvent params #priority 2 _registerEvent params #priority 2 evtService.trigger name: <NAME>A # triggers 3 times callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 2 events evtService.off selector: (e)-> return e.priority == 2 # triggers 1 event evtService.trigger name: <NAME>A expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- it 'should remove event from default channel based on event name', -> params = name: <NAME>A callBack: callBackA _registerEvent params #priority 1 _registerEvent params #priority 1 params.name = 'anotherEventName' _registerEvent params #priority 1 evtService.trigger name: <NAME>A callCount = callBackA.callCount expect(callCount).to.equal 2 evtService.off name: nameA evtService.trigger name: nameA # check the event registered under nameA are cleared # the callCount should be unchanged expect(callBackA.callCount).to.equal callCount # only the other event should be left evtService.trigger selector: (e)-> return e.priority == 1 # check the other event registered are left expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- it 'should remove event from defined channel', -> params = name: <NAME>A channel: channelA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params # triggers 3 times evtService.trigger name: <NAME>A channel: channelA callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off evt2 # triggers 2 times evtService.trigger name: <NAME>A channel: channelA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from defined channel based on priority filter', -> params = priority: 2 name: <NAME>A callBack: callBackA _registerEvent params #priority 2 params.priority = 3 _registerEvent params #priority 3 _registerEvent params #priority 3 # triggers 3 times evtService.trigger name: <NAME>A callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off selector: (e)-> return e.priority == 2 # triggers 2 times evtService.trigger name: <NAME>A expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from defined channel based on event name', -> params = name: <NAME>A channel: channelA callBack: callBackA _registerEvent params #priority default _registerEvent params #priority default params.name = 'anotherEventName' _registerEvent params #priority default # triggers 2 events evtService.trigger name: <NAME>A channel: channelA callCount = callBackA.callCount expect(callCount).to.equal 2 # removes 2 evtService.off name: <NAME>A channel: channelA # triggers 0 evtService.trigger name: <NAME>A channel: channelA # check the event registered under nameA are cleared # the callCount should be unchanged expect(callBackA.callCount).to.equal callCount evtService.trigger channel: channelA prioritySelector: (e)-> return e.priority == priorityDefault # check the other event registered are left expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- # ------------------------------------------------------- describe 'EventService trigger()', -> # ------------------------------------------------------- it 'should trigger event registered on default channel', (done) -> _registerEvent name: <NAME>A callBack: -> done() evtService.trigger name: <NAME>A # ------------------------------------------------------- it 'should trigger event registered on defined channel', (done) -> _registerEvent name: <NAME>A channel: channelA callBack: -> done() evtService.trigger name: <NAME>A channel: channelA # ------------------------------------------------------- it 'should trigger events based on priority', (done) -> ctr = 0 # last _registerEvent # priority 1 default name: <NAME>A callBack: -> expect(ctr).to.equal 11 done() # second _registerEvent name: <NAME>A priority: 2 callBack: -> expect(ctr).to.equal 1 ctr += 10 # first _registerEvent name: <NAME>A priority: 3 callBack: -> expect(ctr).to.equal 0 ctr++ evtService.trigger name: <NAME>A # ------------------------------------------------------- it 'should trigger events filtered on selector', -> ctr = 0 # fourth / last _registerEvent name: <NAME>A callBack: -> ctr++ # second _registerEvent name: <NAME>A priority: 2 callBack: -> ctr += 10 # first _registerEvent name: <NAME>A priority: 3 callBack: -> ctr += 100 _registerEvent name: 'anotherEventName' priority: 3 callBack: -> ctr += 1000 # should trigger all events nameA evtService.trigger selector: (e)-> return e.name == <NAME>A expect(ctr).to.equal 111 ctr = 0 # should trigger only one evtService.trigger name: <NAME>A selector: (e)-> return e.priority == 3 expect(ctr).to.equal 100 ctr = 0 # should trigger two evtService.trigger name: <NAME>A selector: (e)-> return e.priority >= 2 expect(ctr).to.equal 110 ctr = 0 # should trigger all but the first evtService.trigger selector: (e)-> return e.priority >= 2 expect(ctr).to.equal 1110 # ------------------------------------------------------- it 'should trigger event passing parameters on default channel', -> evt = _registerEvent name: <NAME>A callBack: callBackA evtService.trigger name: <NAME>A , 1, 2, 3 expect(evt.callBack.firstCall.calledWith(1, 2, 3)).to.be.true; # ------------------------------------------------------- it 'should trigger event passing parameters on defined channel', -> evt = _registerEvent name: <NAME>A channel: channelA callBack: callBackA evtService.trigger name: <NAME>A channel: channelA , 1, 2, 3 expect(evt.callBack.firstCall.calledWith(1, 2, 3)).to.be.true; # ------------------------------------------------------- it 'should trigger event as many times as registered', -> params = name: nameA channel: channelA callBack: callBackA _registerEvent params _registerEvent params _registerEvent params evtService.trigger name: <NAME>A channel: channelA expect(callBackA.callCount).to.equal 3 # ------------------------------------------------------- it 'should not trigger if the event is paused', -> params = name: <NAME>A callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.pause() evtService.trigger name: <NAME>A expect(callBackA.callCount).to.equal 2 # ------------------------------------------------------- it 'should trigger if the event is resumed', -> params = name: <NAME> callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.pause() evtService.trigger name: <NAME>A callCount = callBackA.callCount expect(callCount).to.equal 2 evt2.resume() evtService.trigger name: <NAME>A expect(callBackA.callCount).to.equal (callCount + 3) # ------------------------------------------------------- it 'should not trigger if the event is stopped', -> ctr = 0 params = name: <NAME> callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.stop() evtService.trigger name: <NAME>A expect(callBackA.callCount).to.equal 2 #------------------------------------------------------------ #------------------------------------------------------------ module.exports = eventServiceTestRunner;
true
# global require 'use strict' EventService = require '../src/EventService.js' Event = require '../src/Event.js' testEvtArr = [] nameA = 'nameA' channelA = 'channelA' evtService = undefined callBackA = undefined priorityDefault = 1 priorityA = 2 _registerEvent = (evtArgs) -> evt = evtService.on evtArgs testEvtArr.push evt return evt cleanAllEvts = -> testEvtArr.forEach (evt)-> evtService.off evt testEvtArr = [] eventServiceTestRunner = -> # ------------------------------------------------------ describe 'EventService', -> # ---------------------------------------- describe 'Class definition', -> it 'EventService API should be defined', -> expect(EventService).not.to.be.undefined expect(EventService.prototype.on).not.to.be.undefined expect(EventService.prototype.off).not.to.be.undefined expect(EventService.prototype.trigger).not.to.be.undefined # ---------------------------------------- # ---------------------------------------- describe 'API', -> beforeEach -> callBackA = sinon.spy() evtService = new EventService() afterEach -> cleanAllEvts() evtService = undefined describe 'EventService on()', -> # ------------------------------------------------------- it 'should accept minimum arguments / event name and callback', -> evt = _registerEvent name: PI:NAME:<NAME>END_PIA callBack: callBackA expect(evt).not.to.be.undefined expect(evt instanceof Event).to.be.true expect(evt.name).to.equal nameA expect(evt.callBack).to.equal callBackA expect(evt.callBack.callCount).to.equal 0 # default values expect(evt.priority).to.equal priorityDefault expect(evt.channel).to.equal undefined # ------------------------------------------------------- it 'should accept full arguments / event name, callback, channel and priority', -> evt = _registerEvent name: PI:NAME:<NAME>END_PIA channel: channelA callBack: callBackA priority: priorityA expect(evt).not.to.be.undefined expect(evt instanceof Event).to.be.true expect(evt.name).to.equal nameA expect(evt.channel).to.equal channelA expect(evt.callBack).to.equal callBackA expect(evt.callBack.callCount).to.equal 0 expect(evt.priority).to.equal priorityA # ------------------------------------------------------- it 'should throw if name is not string', -> fn = -> evtService.on name: 1 expect(fn).to.throw # ------------------------------------------------------- it 'should throw if name or callback are missing', -> missingNameClbkFunc = -> evtService.on() missingNameFunc = -> evtService.on callBack: -> missingClbkFunc = -> evtService.on name: nameA expect(missingNameClbkFunc).to.throw expect(missingNameFunc).to.throw expect(missingClbkFunc).to.throw # ------------------------------------------------------- # ------------------------------------------------------- describe 'EventService off()', -> # ------------------------------------------------------- it 'should remove event from default channel', -> params = name: PI:NAME:<NAME>END_PI callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params # triggers 3 times evtService.trigger name: PI:NAME:<NAME>END_PI callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off evt2 # triggers 2 times evtService.trigger name: PI:NAME:<NAME>END_PIA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from default channel based on selector filter', -> params = priority: 1 name: PI:NAME:<NAME>END_PI callBack: callBackA _registerEvent params #priority 1 params.priority = 2 _registerEvent params #priority 2 _registerEvent params #priority 2 evtService.trigger name: PI:NAME:<NAME>END_PIA # triggers 3 times callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 2 events evtService.off selector: (e)-> return e.priority == 2 # triggers 1 event evtService.trigger name: PI:NAME:<NAME>END_PIA expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- it 'should remove event from default channel based on event name', -> params = name: PI:NAME:<NAME>END_PIA callBack: callBackA _registerEvent params #priority 1 _registerEvent params #priority 1 params.name = 'anotherEventName' _registerEvent params #priority 1 evtService.trigger name: PI:NAME:<NAME>END_PIA callCount = callBackA.callCount expect(callCount).to.equal 2 evtService.off name: nameA evtService.trigger name: nameA # check the event registered under nameA are cleared # the callCount should be unchanged expect(callBackA.callCount).to.equal callCount # only the other event should be left evtService.trigger selector: (e)-> return e.priority == 1 # check the other event registered are left expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- it 'should remove event from defined channel', -> params = name: PI:NAME:<NAME>END_PIA channel: channelA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params # triggers 3 times evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off evt2 # triggers 2 times evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from defined channel based on priority filter', -> params = priority: 2 name: PI:NAME:<NAME>END_PIA callBack: callBackA _registerEvent params #priority 2 params.priority = 3 _registerEvent params #priority 3 _registerEvent params #priority 3 # triggers 3 times evtService.trigger name: PI:NAME:<NAME>END_PIA callCount = callBackA.callCount expect(callCount).to.equal 3 # removes 1 event evtService.off selector: (e)-> return e.priority == 2 # triggers 2 times evtService.trigger name: PI:NAME:<NAME>END_PIA expect(callBackA.callCount).to.equal (callCount + 2) # ------------------------------------------------------- it 'should remove event from defined channel based on event name', -> params = name: PI:NAME:<NAME>END_PIA channel: channelA callBack: callBackA _registerEvent params #priority default _registerEvent params #priority default params.name = 'anotherEventName' _registerEvent params #priority default # triggers 2 events evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA callCount = callBackA.callCount expect(callCount).to.equal 2 # removes 2 evtService.off name: PI:NAME:<NAME>END_PIA channel: channelA # triggers 0 evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA # check the event registered under nameA are cleared # the callCount should be unchanged expect(callBackA.callCount).to.equal callCount evtService.trigger channel: channelA prioritySelector: (e)-> return e.priority == priorityDefault # check the other event registered are left expect(callBackA.callCount).to.equal (callCount + 1) # ------------------------------------------------------- # ------------------------------------------------------- describe 'EventService trigger()', -> # ------------------------------------------------------- it 'should trigger event registered on default channel', (done) -> _registerEvent name: PI:NAME:<NAME>END_PIA callBack: -> done() evtService.trigger name: PI:NAME:<NAME>END_PIA # ------------------------------------------------------- it 'should trigger event registered on defined channel', (done) -> _registerEvent name: PI:NAME:<NAME>END_PIA channel: channelA callBack: -> done() evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA # ------------------------------------------------------- it 'should trigger events based on priority', (done) -> ctr = 0 # last _registerEvent # priority 1 default name: PI:NAME:<NAME>END_PIA callBack: -> expect(ctr).to.equal 11 done() # second _registerEvent name: PI:NAME:<NAME>END_PIA priority: 2 callBack: -> expect(ctr).to.equal 1 ctr += 10 # first _registerEvent name: PI:NAME:<NAME>END_PIA priority: 3 callBack: -> expect(ctr).to.equal 0 ctr++ evtService.trigger name: PI:NAME:<NAME>END_PIA # ------------------------------------------------------- it 'should trigger events filtered on selector', -> ctr = 0 # fourth / last _registerEvent name: PI:NAME:<NAME>END_PIA callBack: -> ctr++ # second _registerEvent name: PI:NAME:<NAME>END_PIA priority: 2 callBack: -> ctr += 10 # first _registerEvent name: PI:NAME:<NAME>END_PIA priority: 3 callBack: -> ctr += 100 _registerEvent name: 'anotherEventName' priority: 3 callBack: -> ctr += 1000 # should trigger all events nameA evtService.trigger selector: (e)-> return e.name == PI:NAME:<NAME>END_PIA expect(ctr).to.equal 111 ctr = 0 # should trigger only one evtService.trigger name: PI:NAME:<NAME>END_PIA selector: (e)-> return e.priority == 3 expect(ctr).to.equal 100 ctr = 0 # should trigger two evtService.trigger name: PI:NAME:<NAME>END_PIA selector: (e)-> return e.priority >= 2 expect(ctr).to.equal 110 ctr = 0 # should trigger all but the first evtService.trigger selector: (e)-> return e.priority >= 2 expect(ctr).to.equal 1110 # ------------------------------------------------------- it 'should trigger event passing parameters on default channel', -> evt = _registerEvent name: PI:NAME:<NAME>END_PIA callBack: callBackA evtService.trigger name: PI:NAME:<NAME>END_PIA , 1, 2, 3 expect(evt.callBack.firstCall.calledWith(1, 2, 3)).to.be.true; # ------------------------------------------------------- it 'should trigger event passing parameters on defined channel', -> evt = _registerEvent name: PI:NAME:<NAME>END_PIA channel: channelA callBack: callBackA evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA , 1, 2, 3 expect(evt.callBack.firstCall.calledWith(1, 2, 3)).to.be.true; # ------------------------------------------------------- it 'should trigger event as many times as registered', -> params = name: nameA channel: channelA callBack: callBackA _registerEvent params _registerEvent params _registerEvent params evtService.trigger name: PI:NAME:<NAME>END_PIA channel: channelA expect(callBackA.callCount).to.equal 3 # ------------------------------------------------------- it 'should not trigger if the event is paused', -> params = name: PI:NAME:<NAME>END_PIA callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.pause() evtService.trigger name: PI:NAME:<NAME>END_PIA expect(callBackA.callCount).to.equal 2 # ------------------------------------------------------- it 'should trigger if the event is resumed', -> params = name: PI:NAME:<NAME>END_PI callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.pause() evtService.trigger name: PI:NAME:<NAME>END_PIA callCount = callBackA.callCount expect(callCount).to.equal 2 evt2.resume() evtService.trigger name: PI:NAME:<NAME>END_PIA expect(callBackA.callCount).to.equal (callCount + 3) # ------------------------------------------------------- it 'should not trigger if the event is stopped', -> ctr = 0 params = name: PI:NAME:<NAME>END_PI callBack: callBackA _registerEvent params evt2 = _registerEvent params _registerEvent params evt2.stop() evtService.trigger name: PI:NAME:<NAME>END_PIA expect(callBackA.callCount).to.equal 2 #------------------------------------------------------------ #------------------------------------------------------------ module.exports = eventServiceTestRunner;
[ { "context": "vices/authenticator-service'\n\nSESSION_SECRET='some-secret-that-does-not-really-matter'\n\nclass Server\n", "end": 562, "score": 0.6510350108146667, "start": 562, "tag": "KEY", "value": "" }, { "context": "uthenticator-service'\n\nSESSION_SECRET='some-secret-that-does-...
src/server.coffee
octoblu/meshblu-authenticator-azure-ad
0
session = require 'cookie-session' cookieParser = require 'cookie-parser' octobluExpress = require 'express-octoblu' http = require 'http' passport = require 'passport' AzureAdOAuth2Strategy = require 'passport-azure-ad-oauth2' enableDestroy = require 'server-destroy' AuthenticatorController = require './controllers/authenticator-controller' Router = require './router' AuthenticatorService = require './services/authenticator-service' SESSION_SECRET='some-secret-that-does-not-really-matter' class Server constructor: ({ clientID, clientSecret, callbackURL, disableLogging, logFn, meshbluConfig, namespace, @port, privateKey, resource, tenant }) -> throw new Error 'Missing required parameter: clientID' unless clientID? throw new Error 'Missing required parameter: clientSecret' unless clientSecret? throw new Error 'Missing required parameter: callbackURL' unless callbackURL? throw new Error 'Missing required parameter: meshbluConfig' unless meshbluConfig? throw new Error 'Missing required parameter: namespace' unless namespace? throw new Error 'Missing required parameter: privateKey' unless privateKey? throw new Error 'Missing required parameter: resource' unless resource? throw new Error 'Missing required parameter: tenant' unless tenant? authenticatorService = new AuthenticatorService { meshbluConfig, namespace, privateKey } authenticatorController = new AuthenticatorController { authenticatorService } passport.serializeUser (user, callback) => callback null, user passport.deserializeUser (user, callback) => callback null, user passport.use new AzureAdOAuth2Strategy({ clientID, clientSecret, callbackURL, resource, tenant }, authenticatorService.authenticate) app = octobluExpress { logFn, disableLogging } app.use cookieParser() app.use session @_sessionOptions() app.use passport.initialize() app.use passport.session() router = new Router { authenticatorController } router.route app @server = http.createServer app enableDestroy @server address: => @server.address() run: (callback) => @server.listen @port, callback _sessionOptions: => return { secret: SESSION_SECRET resave: false saveUninitialized: true secure: process.env.NODE_ENV == 'production' maxAge: 60 * 60 * 1000 } module.exports = Server
81029
session = require 'cookie-session' cookieParser = require 'cookie-parser' octobluExpress = require 'express-octoblu' http = require 'http' passport = require 'passport' AzureAdOAuth2Strategy = require 'passport-azure-ad-oauth2' enableDestroy = require 'server-destroy' AuthenticatorController = require './controllers/authenticator-controller' Router = require './router' AuthenticatorService = require './services/authenticator-service' SESSION_SECRET='some<KEY>-secret<KEY>-that<KEY>-does<KEY>-not<KEY>-really<KEY>-matter' class Server constructor: ({ clientID, clientSecret, callbackURL, disableLogging, logFn, meshbluConfig, namespace, @port, privateKey, resource, tenant }) -> throw new Error 'Missing required parameter: clientID' unless clientID? throw new Error 'Missing required parameter: clientSecret' unless clientSecret? throw new Error 'Missing required parameter: callbackURL' unless callbackURL? throw new Error 'Missing required parameter: meshbluConfig' unless meshbluConfig? throw new Error 'Missing required parameter: namespace' unless namespace? throw new Error 'Missing required parameter: privateKey' unless privateKey? throw new Error 'Missing required parameter: resource' unless resource? throw new Error 'Missing required parameter: tenant' unless tenant? authenticatorService = new AuthenticatorService { meshbluConfig, namespace, privateKey } authenticatorController = new AuthenticatorController { authenticatorService } passport.serializeUser (user, callback) => callback null, user passport.deserializeUser (user, callback) => callback null, user passport.use new AzureAdOAuth2Strategy({ clientID, clientSecret, callbackURL, resource, tenant }, authenticatorService.authenticate) app = octobluExpress { logFn, disableLogging } app.use cookieParser() app.use session @_sessionOptions() app.use passport.initialize() app.use passport.session() router = new Router { authenticatorController } router.route app @server = http.createServer app enableDestroy @server address: => @server.address() run: (callback) => @server.listen @port, callback _sessionOptions: => return { secret: SESSION_SECRET resave: false saveUninitialized: true secure: process.env.NODE_ENV == 'production' maxAge: 60 * 60 * 1000 } module.exports = Server
true
session = require 'cookie-session' cookieParser = require 'cookie-parser' octobluExpress = require 'express-octoblu' http = require 'http' passport = require 'passport' AzureAdOAuth2Strategy = require 'passport-azure-ad-oauth2' enableDestroy = require 'server-destroy' AuthenticatorController = require './controllers/authenticator-controller' Router = require './router' AuthenticatorService = require './services/authenticator-service' SESSION_SECRET='somePI:KEY:<KEY>END_PI-secretPI:KEY:<KEY>END_PI-thatPI:KEY:<KEY>END_PI-doesPI:KEY:<KEY>END_PI-notPI:KEY:<KEY>END_PI-reallyPI:KEY:<KEY>END_PI-matter' class Server constructor: ({ clientID, clientSecret, callbackURL, disableLogging, logFn, meshbluConfig, namespace, @port, privateKey, resource, tenant }) -> throw new Error 'Missing required parameter: clientID' unless clientID? throw new Error 'Missing required parameter: clientSecret' unless clientSecret? throw new Error 'Missing required parameter: callbackURL' unless callbackURL? throw new Error 'Missing required parameter: meshbluConfig' unless meshbluConfig? throw new Error 'Missing required parameter: namespace' unless namespace? throw new Error 'Missing required parameter: privateKey' unless privateKey? throw new Error 'Missing required parameter: resource' unless resource? throw new Error 'Missing required parameter: tenant' unless tenant? authenticatorService = new AuthenticatorService { meshbluConfig, namespace, privateKey } authenticatorController = new AuthenticatorController { authenticatorService } passport.serializeUser (user, callback) => callback null, user passport.deserializeUser (user, callback) => callback null, user passport.use new AzureAdOAuth2Strategy({ clientID, clientSecret, callbackURL, resource, tenant }, authenticatorService.authenticate) app = octobluExpress { logFn, disableLogging } app.use cookieParser() app.use session @_sessionOptions() app.use passport.initialize() app.use passport.session() router = new Router { authenticatorController } router.route app @server = http.createServer app enableDestroy @server address: => @server.address() run: (callback) => @server.listen @port, callback _sessionOptions: => return { secret: SESSION_SECRET resave: false saveUninitialized: true secure: process.env.NODE_ENV == 'production' maxAge: 60 * 60 * 1000 } module.exports = Server
[ { "context": " currently it supports only Slack.\n#\n# Author:\n# Nikolaos Anastopoulos <ebababi@ebababi.net>\n\nmoment = require 'moment-t", "end": 405, "score": 0.999855101108551, "start": 384, "tag": "NAME", "value": "Nikolaos Anastopoulos" }, { "context": "nly Slack.\n#\n# Auth...
src/timezone-converter.coffee
ebababi/hubot-timezone-converter
1
# Description # Enable hubot to convert times in user time zones during discussion. # # Configuration: # HUBOT_TIMEZONE_CONVERTER_FORMAT - Moment.js compatible format of response. # # Commands: # <time expression> - Sends the time converted to all room users time zones. # # Notes: # It requires a time zone aware adapter and currently it supports only Slack. # # Author: # Nikolaos Anastopoulos <ebababi@ebababi.net> moment = require 'moment-timezone' chrono = require 'chrono-node' HUBOT_TIMEZONE_CONVERTER_REGEX = /(?:(?:[1-9]|1[0-2])\s*[ap]m|(?:1?\d|2[0-3])\:[0-5]\d)/i HUBOT_TIMEZONE_CONVERTER_FORMAT = process.env.HUBOT_TIMEZONE_CONVERTER_FORMAT or "HH:mm [({tz_label})][\n]" # Custom Chrono instance, enriched with time zone offset assignment refiner. chrono.custom = do -> custom = new chrono.Chrono() # Chrono refiner that will imply time zone offset set by options. # # This requires `chrono-node` version 1.3.7 and it doesn't have any effect in # lesser versions. implyTimeZoneOffsetRefiner = new chrono.Refiner() implyTimeZoneOffsetRefiner.refine = (text, results, opt) -> return results unless opt['timezoneOffset']? results.forEach (result) -> result.start.imply 'timezoneOffset', opt['timezoneOffset'] result.end.imply 'timezoneOffset', opt['timezoneOffset'] if result.end? results # Converts chrono parsed components to a moment date object with time zone. parsedComponentsToMoment = (parsedComponents, zoneName) -> dateMoment = moment.tz zoneName dateMoment.set 'year', parsedComponents.get('year') dateMoment.set 'month', parsedComponents.get('month') - 1 dateMoment.set 'date', parsedComponents.get('day') dateMoment.set 'hour', parsedComponents.get('hour') dateMoment.set 'minute', parsedComponents.get('minute') dateMoment.set 'second', parsedComponents.get('second') dateMoment.set 'millisecond', parsedComponents.get('millisecond') dateMoment # Chrono refiner that will apply time zone offset implied by options. # # Time zone offset should be assigned instead of implied because system time # zone takes precedence to implied time zone in `chrono-node` versions 1.3.6 # or less. Moreover, assignTimeZoneOffsetRefiner = new chrono.Refiner() assignTimeZoneOffsetRefiner.refine = (text, results, opt) -> return results unless opt['timezoneName']? results.forEach (result) -> unless result.start.isCertain('timezoneOffset') utcOffset = parsedComponentsToMoment(result.start, opt['timezoneName']).utcOffset() result.start.assign 'timezoneOffset', utcOffset if result.end? and not result.end.isCertain('timezoneOffset') utcOffset = parsedComponentsToMoment(result.end, opt['timezoneName']).utcOffset() result.end.assign 'timezoneOffset', utcOffset results custom.refiners.push implyTimeZoneOffsetRefiner custom.refiners.push assignTimeZoneOffsetRefiner custom module.exports = (robot) -> # Requires a time zone aware adapter and currently it supports only Slack. return unless robot.adapterName is 'slack' # Get a time zone hash object given a User object. # # Returns a time zone hash for the specified user. userTimeZoneForUser = (user) -> return unless user?.slack?.tz and user.slack.is_bot isnt true { tz: user.slack.tz, tz_label: user.slack.tz_label, tz_offset: user.slack.tz_offset } if user?.slack?.tz # Get a time zone hash object given a unique user identifier. # # Returns a time zone hash for the specified user. userTimeZoneForID = (id) -> userTimeZoneForUser robot.brain.users()[id] # Extract an array of unique time zone hash objects of member users given a # Channel object. # # Returns an array of time zone hashes for the specified channel. channelTimeZonesForChannel = (channel) -> return unless channel?.members or channel?.user (channel.members or [channel.user]) .map (id) -> userTimeZoneForID id .filter (o) -> o? .sort (a, b) -> a.tz_offset - b.tz_offset .reduce \ (uniq, tz) -> uniq.push tz unless tz.tz_label in uniq.map (tz) -> tz.tz_label uniq , [] # Command: <time expression> - Sends the time converted to all room users time zones. robot.hear HUBOT_TIMEZONE_CONVERTER_REGEX, (res) -> return if res.message.subtype? userTimeZone = userTimeZoneForUser res.message.user referenceDate = moment.tz userTimeZone?.tz referenceZone = moment.tz.zone userTimeZone?.tz messageDate = chrono.custom.parseDate res.message.text, referenceDate, timezoneOffset: referenceDate.utcOffset(), timezoneName: referenceZone?.name if messageDate robot.adapter.client.fetchConversation(res.message.room) .then (channel) -> roomTimeZones = channelTimeZonesForChannel channel if roomTimeZones.length > 1 or channel.is_im memberDates = for roomTimeZone in roomTimeZones moment.tz(messageDate, roomTimeZone.tz) .format HUBOT_TIMEZONE_CONVERTER_FORMAT.replace /\{(\w+)\}/g, (match, property) -> roomTimeZone[property] or match res.send memberDates.join ''
23673
# Description # Enable hubot to convert times in user time zones during discussion. # # Configuration: # HUBOT_TIMEZONE_CONVERTER_FORMAT - Moment.js compatible format of response. # # Commands: # <time expression> - Sends the time converted to all room users time zones. # # Notes: # It requires a time zone aware adapter and currently it supports only Slack. # # Author: # <NAME> <<EMAIL>> moment = require 'moment-timezone' chrono = require 'chrono-node' HUBOT_TIMEZONE_CONVERTER_REGEX = /(?:(?:[1-9]|1[0-2])\s*[ap]m|(?:1?\d|2[0-3])\:[0-5]\d)/i HUBOT_TIMEZONE_CONVERTER_FORMAT = process.env.HUBOT_TIMEZONE_CONVERTER_FORMAT or "HH:mm [({tz_label})][\n]" # Custom Chrono instance, enriched with time zone offset assignment refiner. chrono.custom = do -> custom = new chrono.Chrono() # Chrono refiner that will imply time zone offset set by options. # # This requires `chrono-node` version 1.3.7 and it doesn't have any effect in # lesser versions. implyTimeZoneOffsetRefiner = new chrono.Refiner() implyTimeZoneOffsetRefiner.refine = (text, results, opt) -> return results unless opt['timezoneOffset']? results.forEach (result) -> result.start.imply 'timezoneOffset', opt['timezoneOffset'] result.end.imply 'timezoneOffset', opt['timezoneOffset'] if result.end? results # Converts chrono parsed components to a moment date object with time zone. parsedComponentsToMoment = (parsedComponents, zoneName) -> dateMoment = moment.tz zoneName dateMoment.set 'year', parsedComponents.get('year') dateMoment.set 'month', parsedComponents.get('month') - 1 dateMoment.set 'date', parsedComponents.get('day') dateMoment.set 'hour', parsedComponents.get('hour') dateMoment.set 'minute', parsedComponents.get('minute') dateMoment.set 'second', parsedComponents.get('second') dateMoment.set 'millisecond', parsedComponents.get('millisecond') dateMoment # Chrono refiner that will apply time zone offset implied by options. # # Time zone offset should be assigned instead of implied because system time # zone takes precedence to implied time zone in `chrono-node` versions 1.3.6 # or less. Moreover, assignTimeZoneOffsetRefiner = new chrono.Refiner() assignTimeZoneOffsetRefiner.refine = (text, results, opt) -> return results unless opt['timezoneName']? results.forEach (result) -> unless result.start.isCertain('timezoneOffset') utcOffset = parsedComponentsToMoment(result.start, opt['timezoneName']).utcOffset() result.start.assign 'timezoneOffset', utcOffset if result.end? and not result.end.isCertain('timezoneOffset') utcOffset = parsedComponentsToMoment(result.end, opt['timezoneName']).utcOffset() result.end.assign 'timezoneOffset', utcOffset results custom.refiners.push implyTimeZoneOffsetRefiner custom.refiners.push assignTimeZoneOffsetRefiner custom module.exports = (robot) -> # Requires a time zone aware adapter and currently it supports only Slack. return unless robot.adapterName is 'slack' # Get a time zone hash object given a User object. # # Returns a time zone hash for the specified user. userTimeZoneForUser = (user) -> return unless user?.slack?.tz and user.slack.is_bot isnt true { tz: user.slack.tz, tz_label: user.slack.tz_label, tz_offset: user.slack.tz_offset } if user?.slack?.tz # Get a time zone hash object given a unique user identifier. # # Returns a time zone hash for the specified user. userTimeZoneForID = (id) -> userTimeZoneForUser robot.brain.users()[id] # Extract an array of unique time zone hash objects of member users given a # Channel object. # # Returns an array of time zone hashes for the specified channel. channelTimeZonesForChannel = (channel) -> return unless channel?.members or channel?.user (channel.members or [channel.user]) .map (id) -> userTimeZoneForID id .filter (o) -> o? .sort (a, b) -> a.tz_offset - b.tz_offset .reduce \ (uniq, tz) -> uniq.push tz unless tz.tz_label in uniq.map (tz) -> tz.tz_label uniq , [] # Command: <time expression> - Sends the time converted to all room users time zones. robot.hear HUBOT_TIMEZONE_CONVERTER_REGEX, (res) -> return if res.message.subtype? userTimeZone = userTimeZoneForUser res.message.user referenceDate = moment.tz userTimeZone?.tz referenceZone = moment.tz.zone userTimeZone?.tz messageDate = chrono.custom.parseDate res.message.text, referenceDate, timezoneOffset: referenceDate.utcOffset(), timezoneName: referenceZone?.name if messageDate robot.adapter.client.fetchConversation(res.message.room) .then (channel) -> roomTimeZones = channelTimeZonesForChannel channel if roomTimeZones.length > 1 or channel.is_im memberDates = for roomTimeZone in roomTimeZones moment.tz(messageDate, roomTimeZone.tz) .format HUBOT_TIMEZONE_CONVERTER_FORMAT.replace /\{(\w+)\}/g, (match, property) -> roomTimeZone[property] or match res.send memberDates.join ''
true
# Description # Enable hubot to convert times in user time zones during discussion. # # Configuration: # HUBOT_TIMEZONE_CONVERTER_FORMAT - Moment.js compatible format of response. # # Commands: # <time expression> - Sends the time converted to all room users time zones. # # Notes: # It requires a time zone aware adapter and currently it supports only Slack. # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> moment = require 'moment-timezone' chrono = require 'chrono-node' HUBOT_TIMEZONE_CONVERTER_REGEX = /(?:(?:[1-9]|1[0-2])\s*[ap]m|(?:1?\d|2[0-3])\:[0-5]\d)/i HUBOT_TIMEZONE_CONVERTER_FORMAT = process.env.HUBOT_TIMEZONE_CONVERTER_FORMAT or "HH:mm [({tz_label})][\n]" # Custom Chrono instance, enriched with time zone offset assignment refiner. chrono.custom = do -> custom = new chrono.Chrono() # Chrono refiner that will imply time zone offset set by options. # # This requires `chrono-node` version 1.3.7 and it doesn't have any effect in # lesser versions. implyTimeZoneOffsetRefiner = new chrono.Refiner() implyTimeZoneOffsetRefiner.refine = (text, results, opt) -> return results unless opt['timezoneOffset']? results.forEach (result) -> result.start.imply 'timezoneOffset', opt['timezoneOffset'] result.end.imply 'timezoneOffset', opt['timezoneOffset'] if result.end? results # Converts chrono parsed components to a moment date object with time zone. parsedComponentsToMoment = (parsedComponents, zoneName) -> dateMoment = moment.tz zoneName dateMoment.set 'year', parsedComponents.get('year') dateMoment.set 'month', parsedComponents.get('month') - 1 dateMoment.set 'date', parsedComponents.get('day') dateMoment.set 'hour', parsedComponents.get('hour') dateMoment.set 'minute', parsedComponents.get('minute') dateMoment.set 'second', parsedComponents.get('second') dateMoment.set 'millisecond', parsedComponents.get('millisecond') dateMoment # Chrono refiner that will apply time zone offset implied by options. # # Time zone offset should be assigned instead of implied because system time # zone takes precedence to implied time zone in `chrono-node` versions 1.3.6 # or less. Moreover, assignTimeZoneOffsetRefiner = new chrono.Refiner() assignTimeZoneOffsetRefiner.refine = (text, results, opt) -> return results unless opt['timezoneName']? results.forEach (result) -> unless result.start.isCertain('timezoneOffset') utcOffset = parsedComponentsToMoment(result.start, opt['timezoneName']).utcOffset() result.start.assign 'timezoneOffset', utcOffset if result.end? and not result.end.isCertain('timezoneOffset') utcOffset = parsedComponentsToMoment(result.end, opt['timezoneName']).utcOffset() result.end.assign 'timezoneOffset', utcOffset results custom.refiners.push implyTimeZoneOffsetRefiner custom.refiners.push assignTimeZoneOffsetRefiner custom module.exports = (robot) -> # Requires a time zone aware adapter and currently it supports only Slack. return unless robot.adapterName is 'slack' # Get a time zone hash object given a User object. # # Returns a time zone hash for the specified user. userTimeZoneForUser = (user) -> return unless user?.slack?.tz and user.slack.is_bot isnt true { tz: user.slack.tz, tz_label: user.slack.tz_label, tz_offset: user.slack.tz_offset } if user?.slack?.tz # Get a time zone hash object given a unique user identifier. # # Returns a time zone hash for the specified user. userTimeZoneForID = (id) -> userTimeZoneForUser robot.brain.users()[id] # Extract an array of unique time zone hash objects of member users given a # Channel object. # # Returns an array of time zone hashes for the specified channel. channelTimeZonesForChannel = (channel) -> return unless channel?.members or channel?.user (channel.members or [channel.user]) .map (id) -> userTimeZoneForID id .filter (o) -> o? .sort (a, b) -> a.tz_offset - b.tz_offset .reduce \ (uniq, tz) -> uniq.push tz unless tz.tz_label in uniq.map (tz) -> tz.tz_label uniq , [] # Command: <time expression> - Sends the time converted to all room users time zones. robot.hear HUBOT_TIMEZONE_CONVERTER_REGEX, (res) -> return if res.message.subtype? userTimeZone = userTimeZoneForUser res.message.user referenceDate = moment.tz userTimeZone?.tz referenceZone = moment.tz.zone userTimeZone?.tz messageDate = chrono.custom.parseDate res.message.text, referenceDate, timezoneOffset: referenceDate.utcOffset(), timezoneName: referenceZone?.name if messageDate robot.adapter.client.fetchConversation(res.message.room) .then (channel) -> roomTimeZones = channelTimeZonesForChannel channel if roomTimeZones.length > 1 or channel.is_im memberDates = for roomTimeZone in roomTimeZones moment.tz(messageDate, roomTimeZone.tz) .format HUBOT_TIMEZONE_CONVERTER_FORMAT.replace /\{(\w+)\}/g, (match, property) -> roomTimeZone[property] or match res.send memberDates.join ''
[ { "context": "ee: Github organization class\n#\n# Copyright © 2011 Pavan Kumar Sunkara. All rights reserved\n#\n\n# Requiring modules\n\n# In", "end": 82, "score": 0.9998356699943542, "start": 63, "tag": "NAME", "value": "Pavan Kumar Sunkara" }, { "context": "rganization's member.\n ...
src/octonode/org.coffee
noscripter/octonode
0
# # org.coffee: Github organization class # # Copyright © 2011 Pavan Kumar Sunkara. All rights reserved # # Requiring modules # Initiate class class Org constructor: (@name, @client) -> # Get an organization # '/orgs/flatiron' GET info: (cb) -> @client.get "/orgs/#{@name}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org info error')) else cb null, b, h # Edit an organization # '/orgs/flatiron' POST update: (info, cb) -> @client.post "/orgs/#{@name}", info, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org update error')) else cb null, b, h # Get repository instance for client repo: (nameOrRepo, cb) -> if typeof cb is 'function' and typeof nameOrRepo is 'object' @createRepo nameOrRepo, cb else @client.repo "#{@name}/#{nameOrRepo}" # List organization repositories # '/orgs/flatiron/repos' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] repos: (params..., cb) -> @client.get "/orgs/#{@name}/repos", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org repos error')) else cb null, b, h # Create an organisation repository # '/orgs/flatiron/repos' POST createRepo: (repo, cb) -> @client.post "/orgs/#{@name}/repos", repo, (err, s, b, h) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createRepo error')) else cb null, b, h # Get an organization's teams. # '/orgs/flatiron/teams' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] teams: (params..., cb) -> @client.get "/orgs/#{@name}/teams", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org teams error')) else cb null, b, h # Get an organization's members. # '/orgs/flatiron/members' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] members: (params..., cb) -> @client.get "/orgs/#{@name}/members", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org members error')) else cb null, b, h # Check membership for a user in the org. # '/orgs/flatiron/memberships/pksunkara' GET membership: (user, cb) -> @client.getOptions "/orgs/#{@name}/memberships/#{user}", { headers: { Accept: 'application/vnd.github.moondragon+json'} },(err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org memberships error')) else cb null, b, h # Check an organization's member. # '/orgs/flatiron/members/pksunkara' GET member: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/members/#{user}", (err, s, b, h) -> return cb(err) if err cb null, s is 204, h # Check an organization's public member. # '/orgs/flatiron/public_members/pksunkara' GET publicMember: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/public_members/#{user}", (err, s, b, h) -> return cb(err) if err cb null, s is 204, h # Publicize the authenticated user's membership in an organization. # '/orgs/flatiron/public_members/pksunkara' PUT publicizeMembership: (user, cb) -> @client.put "/orgs/#{@name}/public_members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb new Error("Org publicizeMembership error") else cb null, b, h # Conceal public membership of the authenticated user in the organization. # '/orgs/flatiron/public_members/pksunkara' DELETE concealMembership: (user, cb) -> @client.del "/orgs/#{@name}/public_members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org concealMembership error")) else cb null, b, h # Add a user to an organization # '/orgs/flatiron/members/pksunkara' PUT addMember: (user, options, cb) -> @client.put "/orgs/#{@name}/memberships/#{user}", options, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org addMember error")) else cb null, b, h # Remove a user from an organization and all of its teams # '/orgs/flatiron/members/pksunkara' DELETE removeMember: (user, cb) -> @client.del "/orgs/#{@name}/members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org removeMember error")) else cb null, b, h # Create an organisation team # '/orgs/flatiron/teams' POST createTeam: (options, cb) -> @client.post "/orgs/#{@name}/teams", options, (err, s, b, h) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createTeam error')) else cb null, b, h # Add an organisation team repository # '/teams/37/repos/flatiron/hub' PUT addTeamRepo: (team, repo, cbOrOptions, cb) -> if !cb? and cbOrOptions cb = cbOrOptions param = {} options = 'Content-Type': 'application/json' else if typeof cbOrOptions is 'object' param = cbOrOptions options = 'Content-Type': 'application/json' 'Accept': 'application/vnd.github.ironman-preview+json' @client.put "/teams/#{team}/repos/#{@name}/#{repo}", param, options, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error('Org addTeamRepo error')) else cb null, b, h # Export module module.exports = Org
211596
# # org.coffee: Github organization class # # Copyright © 2011 <NAME>. All rights reserved # # Requiring modules # Initiate class class Org constructor: (@name, @client) -> # Get an organization # '/orgs/flatiron' GET info: (cb) -> @client.get "/orgs/#{@name}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org info error')) else cb null, b, h # Edit an organization # '/orgs/flatiron' POST update: (info, cb) -> @client.post "/orgs/#{@name}", info, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org update error')) else cb null, b, h # Get repository instance for client repo: (nameOrRepo, cb) -> if typeof cb is 'function' and typeof nameOrRepo is 'object' @createRepo nameOrRepo, cb else @client.repo "#{@name}/#{nameOrRepo}" # List organization repositories # '/orgs/flatiron/repos' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] repos: (params..., cb) -> @client.get "/orgs/#{@name}/repos", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org repos error')) else cb null, b, h # Create an organisation repository # '/orgs/flatiron/repos' POST createRepo: (repo, cb) -> @client.post "/orgs/#{@name}/repos", repo, (err, s, b, h) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createRepo error')) else cb null, b, h # Get an organization's teams. # '/orgs/flatiron/teams' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] teams: (params..., cb) -> @client.get "/orgs/#{@name}/teams", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org teams error')) else cb null, b, h # Get an organization's members. # '/orgs/flatiron/members' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] members: (params..., cb) -> @client.get "/orgs/#{@name}/members", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org members error')) else cb null, b, h # Check membership for a user in the org. # '/orgs/flatiron/memberships/pksunkara' GET membership: (user, cb) -> @client.getOptions "/orgs/#{@name}/memberships/#{user}", { headers: { Accept: 'application/vnd.github.moondragon+json'} },(err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org memberships error')) else cb null, b, h # Check an organization's member. # '/orgs/flatiron/members/pksunkara' GET member: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/members/#{user}", (err, s, b, h) -> return cb(err) if err cb null, s is 204, h # Check an organization's public member. # '/orgs/flatiron/public_members/pksunkara' GET publicMember: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/public_members/#{user}", (err, s, b, h) -> return cb(err) if err cb null, s is 204, h # Publicize the authenticated user's membership in an organization. # '/orgs/flatiron/public_members/pksunkara' PUT publicizeMembership: (user, cb) -> @client.put "/orgs/#{@name}/public_members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb new Error("Org publicizeMembership error") else cb null, b, h # Conceal public membership of the authenticated user in the organization. # '/orgs/flatiron/public_members/pksunkara' DELETE concealMembership: (user, cb) -> @client.del "/orgs/#{@name}/public_members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org concealMembership error")) else cb null, b, h # Add a user to an organization # '/orgs/flatiron/members/pksunkara' PUT addMember: (user, options, cb) -> @client.put "/orgs/#{@name}/memberships/#{user}", options, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org addMember error")) else cb null, b, h # Remove a user from an organization and all of its teams # '/orgs/flatiron/members/pksunkara' DELETE removeMember: (user, cb) -> @client.del "/orgs/#{@name}/members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org removeMember error")) else cb null, b, h # Create an organisation team # '/orgs/flatiron/teams' POST createTeam: (options, cb) -> @client.post "/orgs/#{@name}/teams", options, (err, s, b, h) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createTeam error')) else cb null, b, h # Add an organisation team repository # '/teams/37/repos/flatiron/hub' PUT addTeamRepo: (team, repo, cbOrOptions, cb) -> if !cb? and cbOrOptions cb = cbOrOptions param = {} options = 'Content-Type': 'application/json' else if typeof cbOrOptions is 'object' param = cbOrOptions options = 'Content-Type': 'application/json' 'Accept': 'application/vnd.github.ironman-preview+json' @client.put "/teams/#{team}/repos/#{@name}/#{repo}", param, options, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error('Org addTeamRepo error')) else cb null, b, h # Export module module.exports = Org
true
# # org.coffee: Github organization class # # Copyright © 2011 PI:NAME:<NAME>END_PI. All rights reserved # # Requiring modules # Initiate class class Org constructor: (@name, @client) -> # Get an organization # '/orgs/flatiron' GET info: (cb) -> @client.get "/orgs/#{@name}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org info error')) else cb null, b, h # Edit an organization # '/orgs/flatiron' POST update: (info, cb) -> @client.post "/orgs/#{@name}", info, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org update error')) else cb null, b, h # Get repository instance for client repo: (nameOrRepo, cb) -> if typeof cb is 'function' and typeof nameOrRepo is 'object' @createRepo nameOrRepo, cb else @client.repo "#{@name}/#{nameOrRepo}" # List organization repositories # '/orgs/flatiron/repos' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] repos: (params..., cb) -> @client.get "/orgs/#{@name}/repos", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org repos error')) else cb null, b, h # Create an organisation repository # '/orgs/flatiron/repos' POST createRepo: (repo, cb) -> @client.post "/orgs/#{@name}/repos", repo, (err, s, b, h) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createRepo error')) else cb null, b, h # Get an organization's teams. # '/orgs/flatiron/teams' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] teams: (params..., cb) -> @client.get "/orgs/#{@name}/teams", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org teams error')) else cb null, b, h # Get an organization's members. # '/orgs/flatiron/members' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] members: (params..., cb) -> @client.get "/orgs/#{@name}/members", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org members error')) else cb null, b, h # Check membership for a user in the org. # '/orgs/flatiron/memberships/pksunkara' GET membership: (user, cb) -> @client.getOptions "/orgs/#{@name}/memberships/#{user}", { headers: { Accept: 'application/vnd.github.moondragon+json'} },(err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('Org memberships error')) else cb null, b, h # Check an organization's member. # '/orgs/flatiron/members/pksunkara' GET member: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/members/#{user}", (err, s, b, h) -> return cb(err) if err cb null, s is 204, h # Check an organization's public member. # '/orgs/flatiron/public_members/pksunkara' GET publicMember: (user, cb) -> @client.getNoFollow "/orgs/#{@name}/public_members/#{user}", (err, s, b, h) -> return cb(err) if err cb null, s is 204, h # Publicize the authenticated user's membership in an organization. # '/orgs/flatiron/public_members/pksunkara' PUT publicizeMembership: (user, cb) -> @client.put "/orgs/#{@name}/public_members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb new Error("Org publicizeMembership error") else cb null, b, h # Conceal public membership of the authenticated user in the organization. # '/orgs/flatiron/public_members/pksunkara' DELETE concealMembership: (user, cb) -> @client.del "/orgs/#{@name}/public_members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org concealMembership error")) else cb null, b, h # Add a user to an organization # '/orgs/flatiron/members/pksunkara' PUT addMember: (user, options, cb) -> @client.put "/orgs/#{@name}/memberships/#{user}", options, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org addMember error")) else cb null, b, h # Remove a user from an organization and all of its teams # '/orgs/flatiron/members/pksunkara' DELETE removeMember: (user, cb) -> @client.del "/orgs/#{@name}/members/#{user}", null, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error("Org removeMember error")) else cb null, b, h # Create an organisation team # '/orgs/flatiron/teams' POST createTeam: (options, cb) -> @client.post "/orgs/#{@name}/teams", options, (err, s, b, h) -> return cb(err) if err if s isnt 201 then cb(new Error('Org createTeam error')) else cb null, b, h # Add an organisation team repository # '/teams/37/repos/flatiron/hub' PUT addTeamRepo: (team, repo, cbOrOptions, cb) -> if !cb? and cbOrOptions cb = cbOrOptions param = {} options = 'Content-Type': 'application/json' else if typeof cbOrOptions is 'object' param = cbOrOptions options = 'Content-Type': 'application/json' 'Accept': 'application/vnd.github.ironman-preview+json' @client.put "/teams/#{team}/repos/#{@name}/#{repo}", param, options, (err, s, b, h) -> return cb(err) if err if s isnt 204 then cb(new Error('Org addTeamRepo error')) else cb null, b, h # Export module module.exports = Org
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998940229415894, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/database/migrations/2021032400011-create-sale-attachments.coffee
AbdelhakimRafik/Pharmalogy-API
0
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Mar 2021 ### ### Create sale attachments table migration ### module.exports = up: (queryInterface, Sequelize) -> queryInterface.createTable 'Sale-attachments', id: allowNull: false autoIncrement: true primaryKey: true type: Sequelize.INTEGER sale: allowNull: false type: Sequelize.INTEGER references: model: 'sales' key: 'id' file: allowNull: false type: Sequelize.INTEGER references: model: 'files' key: 'id' createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE down: (queryInterface, Sequelize) -> queryInterface.dropTable 'Sale-attachments'
67304
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date Mar 2021 ### ### Create sale attachments table migration ### module.exports = up: (queryInterface, Sequelize) -> queryInterface.createTable 'Sale-attachments', id: allowNull: false autoIncrement: true primaryKey: true type: Sequelize.INTEGER sale: allowNull: false type: Sequelize.INTEGER references: model: 'sales' key: '<KEY>' file: allowNull: false type: Sequelize.INTEGER references: model: 'files' key: '<KEY>' createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE down: (queryInterface, Sequelize) -> queryInterface.dropTable 'Sale-attachments'
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 ### ### Create sale attachments table migration ### module.exports = up: (queryInterface, Sequelize) -> queryInterface.createTable 'Sale-attachments', id: allowNull: false autoIncrement: true primaryKey: true type: Sequelize.INTEGER sale: allowNull: false type: Sequelize.INTEGER references: model: 'sales' key: 'PI:KEY:<KEY>END_PI' file: allowNull: false type: Sequelize.INTEGER references: model: 'files' key: 'PI:KEY:<KEY>END_PI' createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE down: (queryInterface, Sequelize) -> queryInterface.dropTable 'Sale-attachments'
[ { "context": "h1 = document.createElement 'h1'\nh1.innerText = 'Hello World'\n\ndocument.body.appendChild h1\n", "end": 60, "score": 0.7246079444885254, "start": 49, "tag": "NAME", "value": "Hello World" } ]
src/renderer/main.coffee
carsmie/electron-starter
212
h1 = document.createElement 'h1' h1.innerText = 'Hello World' document.body.appendChild h1
190967
h1 = document.createElement 'h1' h1.innerText = '<NAME>' document.body.appendChild h1
true
h1 = document.createElement 'h1' h1.innerText = 'PI:NAME:<NAME>END_PI' document.body.appendChild h1
[ { "context": "ver = second\n rest = others\n\ncontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"", "end": 164, "score": 0.9998334050178528, "start": 150, "tag": "NAME", "value": "Michael Phelps" }, { "context": " = others\n\ncontende...
public/node_modules/coffee-register/benchmarks/samples/small2.coffee
nandartika/bibe
1
gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" "Roman Sebrle" "Guo Jingjing" "Tyson Gay" "Asafa Powell" "Usain Bolt" ] awardMedals contenders... a = "Gold: " + gold b = "Silver: " + silver c = "The Field: " + rest
198717
gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" ] awardMedals contenders... a = "Gold: " + gold b = "Silver: " + silver c = "The Field: " + rest
true
gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ] awardMedals contenders... a = "Gold: " + gold b = "Silver: " + silver c = "The Field: " + rest
[ { "context": "text onto HTML canvas elements\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under ", "end": 106, "score": 0.9998904466629028, "start": 95, "tag": "NAME", "value": "Karl Naylor" }, { "context": " canvas elements\n\nWritten in 2013 by Kar...
src/content/coffee/handywriteOnCanvas/handywriteOnCanvas.coffee
karlorg/phonetify
1
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by Karl Naylor <kpn103@yahoo.com> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define ['./all_graphemes', './boxes'], (allGraphemes, boxes) -> 'use strict' hoc = {} hoc.DocumentRenderer = class DocumentRenderer constructor: (@doc) -> # the length of an 'l' curve in pixels elLength: 30 setElLength: (@elLength) -> createCanvas: (phonemes, titleText=null) -> cRenderer = new CanvasRenderer(this, phonemes, titleText) return cRenderer.canvas class CanvasRenderer constructor: (@docRenderer, @phonemes, titleText=null) -> doc = @docRenderer.doc @canvas = doc.createElement('canvas') if titleText then @canvas.setAttribute('title', titleText) @ctx = @canvas.getContext('2d') @render() render: -> graphemes = [] last = null for phoneme in @phonemes if allGraphemes.classes[phoneme]? newGrapheme = new allGraphemes.classes[phoneme] last.setRightNeighbour(newGrapheme) if last newGrapheme.setLeftNeighbour(last) if last graphemes.push(newGrapheme) last = newGrapheme for grapheme in graphemes grapheme.decide() bbox = boundsOfGraphemes(graphemes) @canvas.width = (bbox.right() - bbox.left()) * @docRenderer.elLength + 10 @canvas.height = (bbox.bottom() - bbox.top()) * @docRenderer.elLength + 10 @ctx.save() @ctx.scale(@docRenderer.elLength, @docRenderer.elLength) # scale down the line width manually, otherwise it will be scaled # along with the rest of the context @ctx.lineWidth /= @docRenderer.elLength @ctx.translate( - bbox.left() + @ctx.lineWidth, - bbox.top() + @ctx.lineWidth) for grapheme in graphemes grapheme.render(@ctx) endPoint = grapheme.getFinishPoint() @ctx.translate(endPoint.x, endPoint.y) @ctx.restore() # returns the overall bounding box of the given graphemes (which should # already have been `decide`d). Origin is the starting point of the first # grapheme, and 1 unit is the width of an l-curve. boundsOfGraphemes = (graphemes) -> boundingBoxes = [] x = y = 0 for g in graphemes boundingBoxes.push(g.getBoundingBox().translate(x, y)) { x: dx, y: dy } = g.getFinishPoint() x += dx y += dy return boxes.combineBoundingBoxes(boundingBoxes) return hoc
161954
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by <NAME> <<EMAIL>> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define ['./all_graphemes', './boxes'], (allGraphemes, boxes) -> 'use strict' hoc = {} hoc.DocumentRenderer = class DocumentRenderer constructor: (@doc) -> # the length of an 'l' curve in pixels elLength: 30 setElLength: (@elLength) -> createCanvas: (phonemes, titleText=null) -> cRenderer = new CanvasRenderer(this, phonemes, titleText) return cRenderer.canvas class CanvasRenderer constructor: (@docRenderer, @phonemes, titleText=null) -> doc = @docRenderer.doc @canvas = doc.createElement('canvas') if titleText then @canvas.setAttribute('title', titleText) @ctx = @canvas.getContext('2d') @render() render: -> graphemes = [] last = null for phoneme in @phonemes if allGraphemes.classes[phoneme]? newGrapheme = new allGraphemes.classes[phoneme] last.setRightNeighbour(newGrapheme) if last newGrapheme.setLeftNeighbour(last) if last graphemes.push(newGrapheme) last = newGrapheme for grapheme in graphemes grapheme.decide() bbox = boundsOfGraphemes(graphemes) @canvas.width = (bbox.right() - bbox.left()) * @docRenderer.elLength + 10 @canvas.height = (bbox.bottom() - bbox.top()) * @docRenderer.elLength + 10 @ctx.save() @ctx.scale(@docRenderer.elLength, @docRenderer.elLength) # scale down the line width manually, otherwise it will be scaled # along with the rest of the context @ctx.lineWidth /= @docRenderer.elLength @ctx.translate( - bbox.left() + @ctx.lineWidth, - bbox.top() + @ctx.lineWidth) for grapheme in graphemes grapheme.render(@ctx) endPoint = grapheme.getFinishPoint() @ctx.translate(endPoint.x, endPoint.y) @ctx.restore() # returns the overall bounding box of the given graphemes (which should # already have been `decide`d). Origin is the starting point of the first # grapheme, and 1 unit is the width of an l-curve. boundsOfGraphemes = (graphemes) -> boundingBoxes = [] x = y = 0 for g in graphemes boundingBoxes.push(g.getBoundingBox().translate(x, y)) { x: dx, y: dy } = g.getFinishPoint() x += dx y += dy return boxes.combineBoundingBoxes(boundingBoxes) return hoc
true
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define ['./all_graphemes', './boxes'], (allGraphemes, boxes) -> 'use strict' hoc = {} hoc.DocumentRenderer = class DocumentRenderer constructor: (@doc) -> # the length of an 'l' curve in pixels elLength: 30 setElLength: (@elLength) -> createCanvas: (phonemes, titleText=null) -> cRenderer = new CanvasRenderer(this, phonemes, titleText) return cRenderer.canvas class CanvasRenderer constructor: (@docRenderer, @phonemes, titleText=null) -> doc = @docRenderer.doc @canvas = doc.createElement('canvas') if titleText then @canvas.setAttribute('title', titleText) @ctx = @canvas.getContext('2d') @render() render: -> graphemes = [] last = null for phoneme in @phonemes if allGraphemes.classes[phoneme]? newGrapheme = new allGraphemes.classes[phoneme] last.setRightNeighbour(newGrapheme) if last newGrapheme.setLeftNeighbour(last) if last graphemes.push(newGrapheme) last = newGrapheme for grapheme in graphemes grapheme.decide() bbox = boundsOfGraphemes(graphemes) @canvas.width = (bbox.right() - bbox.left()) * @docRenderer.elLength + 10 @canvas.height = (bbox.bottom() - bbox.top()) * @docRenderer.elLength + 10 @ctx.save() @ctx.scale(@docRenderer.elLength, @docRenderer.elLength) # scale down the line width manually, otherwise it will be scaled # along with the rest of the context @ctx.lineWidth /= @docRenderer.elLength @ctx.translate( - bbox.left() + @ctx.lineWidth, - bbox.top() + @ctx.lineWidth) for grapheme in graphemes grapheme.render(@ctx) endPoint = grapheme.getFinishPoint() @ctx.translate(endPoint.x, endPoint.y) @ctx.restore() # returns the overall bounding box of the given graphemes (which should # already have been `decide`d). Origin is the starting point of the first # grapheme, and 1 unit is the width of an l-curve. boundsOfGraphemes = (graphemes) -> boundingBoxes = [] x = y = 0 for g in graphemes boundingBoxes.push(g.getBoundingBox().translate(x, y)) { x: dx, y: dy } = g.getFinishPoint() x += dx y += dy return boxes.combineBoundingBoxes(boundingBoxes) return hoc
[ { "context": "############\n##\n## Copyright 2018 M. Hoppe & N. Justus\n##\n## Licensed under the Apache Licen", "end": 42, "score": 0.9998529553413391, "start": 34, "tag": "NAME", "value": "M. Hoppe" }, { "context": "############\n##\n## Copyright 2018 M. Hoppe & N. Justus\n##\n## L...
app/assets/javascripts/dotiw/time_hash.coffee
LiScI-Lab/Guardian-of-Times
3
############ ## ## Copyright 2018 M. Hoppe & N. Justus ## ## 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. ## ############ window.dotiw || (window.dotiw = {}) class TimeHash @MINUTE = 60 @HOUR = @MINUTE * 60 @DAY = @HOUR * 24 @WEEK = @DAY * 7 @FOURWEEKS = @WEEK * 4 @TIME_FRACTIONS = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'] constructor: (distance, from_time = null, to_time = null, options = {}) -> @output = {} @options = options @distance = distance @from_time = new Date(from_time || Date.now()) if(to_time?) @to_time = new Date(to_time) @to_time_not_given = false else if @distance instanceof Date @to_time = new Date(@from_time + @distance) @distance = Math.floor(@distance / 1000) else @to_time = new Date(@from_time.getTime() + @distance * 1000) @to_time_not_given = true @smallest = new Date(Math.min(@from_time, @to_time)) @largest = new Date(Math.max(@from_time, @to_time)) @distance ||= (@largest - @smallest) / 1000 @build_time_hash() to_hash: () -> @output build_time_hash: () -> if @options['accumulate_on']? or @options['accumulateOn']? accumulate_on = @options['accumulate_on'] || @options['accumulateOn'] delete @options['accumulate_on'] delete @options['accumulateOn'] if accumulate_on == 'years' return @build_time_hash() start = TimeHash.TIME_FRACTIONS.indexOf(accumulate_on) for i in [start, 0] @["build_#{TimeHash.TIME_FRACTIONS[i]}"]() else while @distance > 0 if @distance < TimeHash.MINUTE @build_seconds() else if @distance < TimeHash.HOUR @build_minutes() else if @distance < TimeHash.DAY @build_hours() else if @distance < TimeHash.WEEK @build_days() else if @distance < TimeHash.FOURWEEKS @build_weeks() else @build_years_months_weeks_days() @output build_seconds: () -> @output['seconds'] = Math.floor @distance @distance = 0 build_minutes: () -> @output['minutes'] = Math.floor(@distance / TimeHash.MINUTE) @distance = @distance % TimeHash.MINUTE build_hours: () -> @output['hours'] = Math.floor(@distance / TimeHash.HOUR) @distance = @distance % TimeHash.HOUR build_days: () -> if not @output['days']? @output['days'] = Math.floor(@distance / TimeHash.DAY) @distance = @distance % TimeHash.DAY build_weeks: () -> if not @output['weeks']? @output['weeks'] = Math.floor(@distance / TimeHash.WEEK) @distance = @distance % TimeHash.WEEK build_months: () -> @build_years_months_weeks_days years = @output['years'] delete @output['years'] @output['months'] += (years * 12) if years > 0 build_years_months_weeks_days: () -> months = (@largest.getFullYear() - @smallest.getFullYear()) * 12 + (@largest.getMonth() - @smallest.getMonth()) years = Math.floor(months / 12) months = months % 12 days = @largest.getDate() - @smallest.getDate() weeks = Math.floor(days / 7) days = days % 7 days -= 1 if @largest.getHours() < @smallest.getHours() if days < 0 weeks -= 1 days += 7 if weeks < 0 months -= 1 d = new Date(@largest) d.setMonth(d.getMonth() - 1) days_in_month = new Date(d.getFullYear(), d.getMonth(), 0).getDate() weeks += Math.floor(days_in_month / 7) days += days_in_month % 7 if days >= 7 days -= 7 weeks += 1 if months < 0 years -= 1 months += 12 @output['years'] = years @output['months'] = months @output['weeks'] = weeks @output['days'] = days total_days = Math.abs(@distance) / TimeHash.DAY @distance = Math.abs(@distance) % TimeHash.DAY [total_days, @distance] window.dotiw.TimeHash = TimeHash
224757
############ ## ## Copyright 2018 <NAME> & <NAME> ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############ window.dotiw || (window.dotiw = {}) class TimeHash @MINUTE = 60 @HOUR = @MINUTE * 60 @DAY = @HOUR * 24 @WEEK = @DAY * 7 @FOURWEEKS = @WEEK * 4 @TIME_FRACTIONS = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'] constructor: (distance, from_time = null, to_time = null, options = {}) -> @output = {} @options = options @distance = distance @from_time = new Date(from_time || Date.now()) if(to_time?) @to_time = new Date(to_time) @to_time_not_given = false else if @distance instanceof Date @to_time = new Date(@from_time + @distance) @distance = Math.floor(@distance / 1000) else @to_time = new Date(@from_time.getTime() + @distance * 1000) @to_time_not_given = true @smallest = new Date(Math.min(@from_time, @to_time)) @largest = new Date(Math.max(@from_time, @to_time)) @distance ||= (@largest - @smallest) / 1000 @build_time_hash() to_hash: () -> @output build_time_hash: () -> if @options['accumulate_on']? or @options['accumulateOn']? accumulate_on = @options['accumulate_on'] || @options['accumulateOn'] delete @options['accumulate_on'] delete @options['accumulateOn'] if accumulate_on == 'years' return @build_time_hash() start = TimeHash.TIME_FRACTIONS.indexOf(accumulate_on) for i in [start, 0] @["build_#{TimeHash.TIME_FRACTIONS[i]}"]() else while @distance > 0 if @distance < TimeHash.MINUTE @build_seconds() else if @distance < TimeHash.HOUR @build_minutes() else if @distance < TimeHash.DAY @build_hours() else if @distance < TimeHash.WEEK @build_days() else if @distance < TimeHash.FOURWEEKS @build_weeks() else @build_years_months_weeks_days() @output build_seconds: () -> @output['seconds'] = Math.floor @distance @distance = 0 build_minutes: () -> @output['minutes'] = Math.floor(@distance / TimeHash.MINUTE) @distance = @distance % TimeHash.MINUTE build_hours: () -> @output['hours'] = Math.floor(@distance / TimeHash.HOUR) @distance = @distance % TimeHash.HOUR build_days: () -> if not @output['days']? @output['days'] = Math.floor(@distance / TimeHash.DAY) @distance = @distance % TimeHash.DAY build_weeks: () -> if not @output['weeks']? @output['weeks'] = Math.floor(@distance / TimeHash.WEEK) @distance = @distance % TimeHash.WEEK build_months: () -> @build_years_months_weeks_days years = @output['years'] delete @output['years'] @output['months'] += (years * 12) if years > 0 build_years_months_weeks_days: () -> months = (@largest.getFullYear() - @smallest.getFullYear()) * 12 + (@largest.getMonth() - @smallest.getMonth()) years = Math.floor(months / 12) months = months % 12 days = @largest.getDate() - @smallest.getDate() weeks = Math.floor(days / 7) days = days % 7 days -= 1 if @largest.getHours() < @smallest.getHours() if days < 0 weeks -= 1 days += 7 if weeks < 0 months -= 1 d = new Date(@largest) d.setMonth(d.getMonth() - 1) days_in_month = new Date(d.getFullYear(), d.getMonth(), 0).getDate() weeks += Math.floor(days_in_month / 7) days += days_in_month % 7 if days >= 7 days -= 7 weeks += 1 if months < 0 years -= 1 months += 12 @output['years'] = years @output['months'] = months @output['weeks'] = weeks @output['days'] = days total_days = Math.abs(@distance) / TimeHash.DAY @distance = Math.abs(@distance) % TimeHash.DAY [total_days, @distance] window.dotiw.TimeHash = TimeHash
true
############ ## ## Copyright 2018 PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############ window.dotiw || (window.dotiw = {}) class TimeHash @MINUTE = 60 @HOUR = @MINUTE * 60 @DAY = @HOUR * 24 @WEEK = @DAY * 7 @FOURWEEKS = @WEEK * 4 @TIME_FRACTIONS = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'] constructor: (distance, from_time = null, to_time = null, options = {}) -> @output = {} @options = options @distance = distance @from_time = new Date(from_time || Date.now()) if(to_time?) @to_time = new Date(to_time) @to_time_not_given = false else if @distance instanceof Date @to_time = new Date(@from_time + @distance) @distance = Math.floor(@distance / 1000) else @to_time = new Date(@from_time.getTime() + @distance * 1000) @to_time_not_given = true @smallest = new Date(Math.min(@from_time, @to_time)) @largest = new Date(Math.max(@from_time, @to_time)) @distance ||= (@largest - @smallest) / 1000 @build_time_hash() to_hash: () -> @output build_time_hash: () -> if @options['accumulate_on']? or @options['accumulateOn']? accumulate_on = @options['accumulate_on'] || @options['accumulateOn'] delete @options['accumulate_on'] delete @options['accumulateOn'] if accumulate_on == 'years' return @build_time_hash() start = TimeHash.TIME_FRACTIONS.indexOf(accumulate_on) for i in [start, 0] @["build_#{TimeHash.TIME_FRACTIONS[i]}"]() else while @distance > 0 if @distance < TimeHash.MINUTE @build_seconds() else if @distance < TimeHash.HOUR @build_minutes() else if @distance < TimeHash.DAY @build_hours() else if @distance < TimeHash.WEEK @build_days() else if @distance < TimeHash.FOURWEEKS @build_weeks() else @build_years_months_weeks_days() @output build_seconds: () -> @output['seconds'] = Math.floor @distance @distance = 0 build_minutes: () -> @output['minutes'] = Math.floor(@distance / TimeHash.MINUTE) @distance = @distance % TimeHash.MINUTE build_hours: () -> @output['hours'] = Math.floor(@distance / TimeHash.HOUR) @distance = @distance % TimeHash.HOUR build_days: () -> if not @output['days']? @output['days'] = Math.floor(@distance / TimeHash.DAY) @distance = @distance % TimeHash.DAY build_weeks: () -> if not @output['weeks']? @output['weeks'] = Math.floor(@distance / TimeHash.WEEK) @distance = @distance % TimeHash.WEEK build_months: () -> @build_years_months_weeks_days years = @output['years'] delete @output['years'] @output['months'] += (years * 12) if years > 0 build_years_months_weeks_days: () -> months = (@largest.getFullYear() - @smallest.getFullYear()) * 12 + (@largest.getMonth() - @smallest.getMonth()) years = Math.floor(months / 12) months = months % 12 days = @largest.getDate() - @smallest.getDate() weeks = Math.floor(days / 7) days = days % 7 days -= 1 if @largest.getHours() < @smallest.getHours() if days < 0 weeks -= 1 days += 7 if weeks < 0 months -= 1 d = new Date(@largest) d.setMonth(d.getMonth() - 1) days_in_month = new Date(d.getFullYear(), d.getMonth(), 0).getDate() weeks += Math.floor(days_in_month / 7) days += days_in_month % 7 if days >= 7 days -= 7 weeks += 1 if months < 0 years -= 1 months += 12 @output['years'] = years @output['months'] = months @output['weeks'] = weeks @output['days'] = days total_days = Math.abs(@distance) / TimeHash.DAY @distance = Math.abs(@distance) % TimeHash.DAY [total_days, @distance] window.dotiw.TimeHash = TimeHash
[ { "context": "###\njQuery Growl\nCopyright 2015 Kevin Sylvestre\n1.3.5\n###\n\n\"use strict\"\n\n$ = jQuery\n\nclass Animat", "end": 47, "score": 0.9998615980148315, "start": 32, "tag": "NAME", "value": "Kevin Sylvestre" } ]
javascripts/jquery.growl.coffee
gabrielferrazduque/jquery-growl
7
### jQuery Growl Copyright 2015 Kevin Sylvestre 1.3.5 ### "use strict" $ = jQuery class Animation @transitions: "webkitTransition": "webkitTransitionEnd" "mozTransition": "mozTransitionEnd" "oTransition": "oTransitionEnd" "transition": "transitionend" @transition: ($el) -> el = $el[0] return result for type, result of @transitions when el.style[type]? class Growl @settings: namespace: 'growl' duration: 3200 close: "&#215;" location: "default" style: "default" size: "medium" delayOnHover: true @growl: (settings = {}) -> new Growl(settings) constructor: (settings = {}) -> @settings = $.extend {}, Growl.settings, settings @initialize(@settings.location) @render() initialize: (location) -> id = 'growls-' + location; $('body:not(:has(#' + id + '))').append '<div id="' + id + '" />' render: => $growl = @$growl() @$growls(@settings.location).append $growl if @settings.fixed then @present() else @cycle() return bind: ($growl = @$growl()) => $growl.on("click", @click) if(@settings.delayOnHover) $growl.on("mouseenter", @mouseEnter) $growl.on("mouseleave", @mouseLeave) $growl.on("contextmenu", @close).find(".#{@settings.namespace}-close").on("click", @close) unbind: ($growl = @$growl()) => $growl.off("click", @click) if(@settings.delayOnHover) $growl.off("mouseenter", @mouseEnter) $growl.off("mouseleave", @mouseLeave) $growl.off("contextmenu", @close).find(".#{@settings.namespace}-close").off("click", @close) mouseEnter: (event) => $growl = @$growl() $growl .stop(true,true) mouseLeave: (event) => @waitAndDismiss() click: (event) => if @settings.url? event.preventDefault() event.stopPropagation() window.open(@settings.url) close: (event) => event.preventDefault() event.stopPropagation() $growl = @$growl() $growl .stop() .queue(@dismiss) .queue(@remove) cycle: => $growl = @$growl() $growl .queue(@present) .queue(@waitAndDismiss()) waitAndDismiss: => $growl = @$growl() $growl .delay(@settings.duration) .queue(@dismiss) .queue(@remove) present: (callback) => $growl = @$growl() @bind($growl) @animate($growl, "#{@settings.namespace}-incoming", 'out', callback) dismiss: (callback) => $growl = @$growl() @unbind($growl) @animate($growl, "#{@settings.namespace}-outgoing", 'in', callback) remove: (callback) => @$growl().remove() callback?() animate: ($element, name, direction = 'in', callback) => transition = Animation.transition($element) $element[if direction is 'in' then 'removeClass' else 'addClass'](name) $element.offset().position $element[if direction is 'in' then 'addClass' else 'removeClass'](name) return unless callback? if transition? then $element.one(transition, callback) else callback() return $growls: (location) => @$_growls ?= [] @$_growls[location] ?= $('#growls-' + location) $growl: => @$_growl ?= $(@html()) html: => @container(@content()) content: => """ <div class='#{@settings.namespace}-close'>#{@settings.close}</div> <div class='#{@settings.namespace}-title'>#{@settings.title}</div> <div class='#{@settings.namespace}-message'>#{@settings.message}</div> """ container: (content) => """ <div class='#{@settings.namespace} #{@settings.namespace}-#{@settings.style} #{@settings.namespace}-#{@settings.size}'> #{content} </div> """ @Growl = Growl $.growl = (options = {}) -> Growl.growl(options) $.growl.error = (options = {}) -> settings = title: "Error!" style: "error" $.growl $.extend(settings, options) $.growl.notice = (options = {}) -> settings = title: "Notice!" style: "notice" $.growl $.extend(settings, options) $.growl.warning = (options = {}) -> settings = title: "Warning!" style: "warning" $.growl $.extend(settings, options) while (true) { Growl.js} new Promise(function(resolve, reject) { ClassName.prototype.methodName = function () { // COMBAK: function* (Growl.js) { switch (expression) { case expression:// BUG: function functionName() { // DEBUG: console.dir(Growl.js); } getElementsByClassName('Growl.js') case expression: break;console.warn(Growl.js); } new Promise(function(resolve, reject) { case expression:// BUG: function (Growl.js) { // WARNING: switch (expression) { case expression:do { } while (true); while (false); while(true); while(function); class_name.prototype.method_name = function(first_argument) { // }; break;Growl.js return ();
16054
### jQuery Growl Copyright 2015 <NAME> 1.3.5 ### "use strict" $ = jQuery class Animation @transitions: "webkitTransition": "webkitTransitionEnd" "mozTransition": "mozTransitionEnd" "oTransition": "oTransitionEnd" "transition": "transitionend" @transition: ($el) -> el = $el[0] return result for type, result of @transitions when el.style[type]? class Growl @settings: namespace: 'growl' duration: 3200 close: "&#215;" location: "default" style: "default" size: "medium" delayOnHover: true @growl: (settings = {}) -> new Growl(settings) constructor: (settings = {}) -> @settings = $.extend {}, Growl.settings, settings @initialize(@settings.location) @render() initialize: (location) -> id = 'growls-' + location; $('body:not(:has(#' + id + '))').append '<div id="' + id + '" />' render: => $growl = @$growl() @$growls(@settings.location).append $growl if @settings.fixed then @present() else @cycle() return bind: ($growl = @$growl()) => $growl.on("click", @click) if(@settings.delayOnHover) $growl.on("mouseenter", @mouseEnter) $growl.on("mouseleave", @mouseLeave) $growl.on("contextmenu", @close).find(".#{@settings.namespace}-close").on("click", @close) unbind: ($growl = @$growl()) => $growl.off("click", @click) if(@settings.delayOnHover) $growl.off("mouseenter", @mouseEnter) $growl.off("mouseleave", @mouseLeave) $growl.off("contextmenu", @close).find(".#{@settings.namespace}-close").off("click", @close) mouseEnter: (event) => $growl = @$growl() $growl .stop(true,true) mouseLeave: (event) => @waitAndDismiss() click: (event) => if @settings.url? event.preventDefault() event.stopPropagation() window.open(@settings.url) close: (event) => event.preventDefault() event.stopPropagation() $growl = @$growl() $growl .stop() .queue(@dismiss) .queue(@remove) cycle: => $growl = @$growl() $growl .queue(@present) .queue(@waitAndDismiss()) waitAndDismiss: => $growl = @$growl() $growl .delay(@settings.duration) .queue(@dismiss) .queue(@remove) present: (callback) => $growl = @$growl() @bind($growl) @animate($growl, "#{@settings.namespace}-incoming", 'out', callback) dismiss: (callback) => $growl = @$growl() @unbind($growl) @animate($growl, "#{@settings.namespace}-outgoing", 'in', callback) remove: (callback) => @$growl().remove() callback?() animate: ($element, name, direction = 'in', callback) => transition = Animation.transition($element) $element[if direction is 'in' then 'removeClass' else 'addClass'](name) $element.offset().position $element[if direction is 'in' then 'addClass' else 'removeClass'](name) return unless callback? if transition? then $element.one(transition, callback) else callback() return $growls: (location) => @$_growls ?= [] @$_growls[location] ?= $('#growls-' + location) $growl: => @$_growl ?= $(@html()) html: => @container(@content()) content: => """ <div class='#{@settings.namespace}-close'>#{@settings.close}</div> <div class='#{@settings.namespace}-title'>#{@settings.title}</div> <div class='#{@settings.namespace}-message'>#{@settings.message}</div> """ container: (content) => """ <div class='#{@settings.namespace} #{@settings.namespace}-#{@settings.style} #{@settings.namespace}-#{@settings.size}'> #{content} </div> """ @Growl = Growl $.growl = (options = {}) -> Growl.growl(options) $.growl.error = (options = {}) -> settings = title: "Error!" style: "error" $.growl $.extend(settings, options) $.growl.notice = (options = {}) -> settings = title: "Notice!" style: "notice" $.growl $.extend(settings, options) $.growl.warning = (options = {}) -> settings = title: "Warning!" style: "warning" $.growl $.extend(settings, options) while (true) { Growl.js} new Promise(function(resolve, reject) { ClassName.prototype.methodName = function () { // COMBAK: function* (Growl.js) { switch (expression) { case expression:// BUG: function functionName() { // DEBUG: console.dir(Growl.js); } getElementsByClassName('Growl.js') case expression: break;console.warn(Growl.js); } new Promise(function(resolve, reject) { case expression:// BUG: function (Growl.js) { // WARNING: switch (expression) { case expression:do { } while (true); while (false); while(true); while(function); class_name.prototype.method_name = function(first_argument) { // }; break;Growl.js return ();
true
### jQuery Growl Copyright 2015 PI:NAME:<NAME>END_PI 1.3.5 ### "use strict" $ = jQuery class Animation @transitions: "webkitTransition": "webkitTransitionEnd" "mozTransition": "mozTransitionEnd" "oTransition": "oTransitionEnd" "transition": "transitionend" @transition: ($el) -> el = $el[0] return result for type, result of @transitions when el.style[type]? class Growl @settings: namespace: 'growl' duration: 3200 close: "&#215;" location: "default" style: "default" size: "medium" delayOnHover: true @growl: (settings = {}) -> new Growl(settings) constructor: (settings = {}) -> @settings = $.extend {}, Growl.settings, settings @initialize(@settings.location) @render() initialize: (location) -> id = 'growls-' + location; $('body:not(:has(#' + id + '))').append '<div id="' + id + '" />' render: => $growl = @$growl() @$growls(@settings.location).append $growl if @settings.fixed then @present() else @cycle() return bind: ($growl = @$growl()) => $growl.on("click", @click) if(@settings.delayOnHover) $growl.on("mouseenter", @mouseEnter) $growl.on("mouseleave", @mouseLeave) $growl.on("contextmenu", @close).find(".#{@settings.namespace}-close").on("click", @close) unbind: ($growl = @$growl()) => $growl.off("click", @click) if(@settings.delayOnHover) $growl.off("mouseenter", @mouseEnter) $growl.off("mouseleave", @mouseLeave) $growl.off("contextmenu", @close).find(".#{@settings.namespace}-close").off("click", @close) mouseEnter: (event) => $growl = @$growl() $growl .stop(true,true) mouseLeave: (event) => @waitAndDismiss() click: (event) => if @settings.url? event.preventDefault() event.stopPropagation() window.open(@settings.url) close: (event) => event.preventDefault() event.stopPropagation() $growl = @$growl() $growl .stop() .queue(@dismiss) .queue(@remove) cycle: => $growl = @$growl() $growl .queue(@present) .queue(@waitAndDismiss()) waitAndDismiss: => $growl = @$growl() $growl .delay(@settings.duration) .queue(@dismiss) .queue(@remove) present: (callback) => $growl = @$growl() @bind($growl) @animate($growl, "#{@settings.namespace}-incoming", 'out', callback) dismiss: (callback) => $growl = @$growl() @unbind($growl) @animate($growl, "#{@settings.namespace}-outgoing", 'in', callback) remove: (callback) => @$growl().remove() callback?() animate: ($element, name, direction = 'in', callback) => transition = Animation.transition($element) $element[if direction is 'in' then 'removeClass' else 'addClass'](name) $element.offset().position $element[if direction is 'in' then 'addClass' else 'removeClass'](name) return unless callback? if transition? then $element.one(transition, callback) else callback() return $growls: (location) => @$_growls ?= [] @$_growls[location] ?= $('#growls-' + location) $growl: => @$_growl ?= $(@html()) html: => @container(@content()) content: => """ <div class='#{@settings.namespace}-close'>#{@settings.close}</div> <div class='#{@settings.namespace}-title'>#{@settings.title}</div> <div class='#{@settings.namespace}-message'>#{@settings.message}</div> """ container: (content) => """ <div class='#{@settings.namespace} #{@settings.namespace}-#{@settings.style} #{@settings.namespace}-#{@settings.size}'> #{content} </div> """ @Growl = Growl $.growl = (options = {}) -> Growl.growl(options) $.growl.error = (options = {}) -> settings = title: "Error!" style: "error" $.growl $.extend(settings, options) $.growl.notice = (options = {}) -> settings = title: "Notice!" style: "notice" $.growl $.extend(settings, options) $.growl.warning = (options = {}) -> settings = title: "Warning!" style: "warning" $.growl $.extend(settings, options) while (true) { Growl.js} new Promise(function(resolve, reject) { ClassName.prototype.methodName = function () { // COMBAK: function* (Growl.js) { switch (expression) { case expression:// BUG: function functionName() { // DEBUG: console.dir(Growl.js); } getElementsByClassName('Growl.js') case expression: break;console.warn(Growl.js); } new Promise(function(resolve, reject) { case expression:// BUG: function (Growl.js) { // WARNING: switch (expression) { case expression:do { } while (true); while (false); while(true); while(function); class_name.prototype.method_name = function(first_argument) { // }; break;Growl.js return ();