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": "ffee\n# Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai>\n\npath = require 'path'\nasync = require 'async'\n_", "end": 79, "score": 0.9998911023139954, "start": 65, "tag": "EMAIL", "value": "legal@fuzzy.ai" } ]
src/simulation.coffee
enterstudio/lemonade-stand
2
# simulation.coffee # Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai> path = require 'path' async = require 'async' _ = require 'lodash' APIClient = require 'fuzzy.ai' debug = require('debug')('simulation') argv = require('yargs') .demand('k') .alias('k', 'key') .describe('k', 'API key') .default('r', 'https://api.fuzzy.ai') .alias('r', 'root') .describe('r', 'API root URL') .default('b', 100) .alias('b', 'buyers') .describe('b', 'number of buyers') .default('p', 8) .alias('p', 'parallel') .describe('p', 'number of buyers to run in parallel') .default('t', 0.5) .alias('t', 'threshold') .describe('t', 'buy threshold') .default('c', 0.50) .alias('c', 'cost') .describe('c', 'Total unit cost') .env('HOT_CHOCOLATE') .config() .default('config', path.join(process.env['HOME'], '.hotchocolate.json')) .alias('f', 'config') .help() .alias('h', 'help') .argv { seller, buyer } = require './agents' main = (argv) -> # Explode these so we aren't depending on argv everywhere debug(argv) {key, root, buyers, threshold, cost, parallel} = argv cost = 0.50 client = new APIClient {key: key, root: root} buyerID = null sellerID = null temperature = 32 sunny = 0 attemptSale = (i, callback) -> debug "Attempting sale #{i}" id = null price = null # randomly change up the environment if Math.round(Math.random()) temperature = Math.round(Math.random() * 100) sunny = Math.round(Math.random()) status = numBuyers: buyers - i temperature: temperature sunny: sunny debug status async.waterfall [ (callback) -> inputs = _.clone(status) debug "Calling seller for attempt #{i}" client.evaluate sellerID, inputs, true, callback (results, callback) -> debug "Results for seller for attempt #{i}" debug results id = results.meta.reqID price = Math.round(results.price * 100) / 100 inputs = _.extend({price: price}, status) debug "Calling buyer for attempt #{i}" client.evaluate buyerID, inputs, callback (results, callback) -> debug "Results for buyer for attempt #{i}" debug results if results.willBuy > threshold profit = Math.round((price - cost) * 100) / 100 else profit = 0 debug "profit for attempt #{i} = #{profit}" client.feedback id, {profit: profit}, (err, fb) -> if err callback err else callback null, profit ], callback profits = null async.waterfall [ (callback) -> debug "Creating new buyer agent" client.newAgent buyer, callback (saved, callback) -> buyerID = saved.id debug saved debug "Buyer ID = #{buyerID}" debug "Creating new seller agent" client.newAgent seller, callback (saved, callback) -> sellerID = saved.id debug saved debug "Seller ID = #{sellerID}" async.timesLimit buyers, parallel, attemptSale, callback (results, callback) -> profits = results debug "Deleting buyer agent #{buyerID}" client.deleteAgent buyerID, callback (callback) -> debug "Deleting seller agent #{sellerID}" client.deleteAgent sellerID, callback ], (err) -> if err console.error err else console.dir profits false main argv
124499
# simulation.coffee # Copyright 2016 9165584 Canada Corporation <<EMAIL>> path = require 'path' async = require 'async' _ = require 'lodash' APIClient = require 'fuzzy.ai' debug = require('debug')('simulation') argv = require('yargs') .demand('k') .alias('k', 'key') .describe('k', 'API key') .default('r', 'https://api.fuzzy.ai') .alias('r', 'root') .describe('r', 'API root URL') .default('b', 100) .alias('b', 'buyers') .describe('b', 'number of buyers') .default('p', 8) .alias('p', 'parallel') .describe('p', 'number of buyers to run in parallel') .default('t', 0.5) .alias('t', 'threshold') .describe('t', 'buy threshold') .default('c', 0.50) .alias('c', 'cost') .describe('c', 'Total unit cost') .env('HOT_CHOCOLATE') .config() .default('config', path.join(process.env['HOME'], '.hotchocolate.json')) .alias('f', 'config') .help() .alias('h', 'help') .argv { seller, buyer } = require './agents' main = (argv) -> # Explode these so we aren't depending on argv everywhere debug(argv) {key, root, buyers, threshold, cost, parallel} = argv cost = 0.50 client = new APIClient {key: key, root: root} buyerID = null sellerID = null temperature = 32 sunny = 0 attemptSale = (i, callback) -> debug "Attempting sale #{i}" id = null price = null # randomly change up the environment if Math.round(Math.random()) temperature = Math.round(Math.random() * 100) sunny = Math.round(Math.random()) status = numBuyers: buyers - i temperature: temperature sunny: sunny debug status async.waterfall [ (callback) -> inputs = _.clone(status) debug "Calling seller for attempt #{i}" client.evaluate sellerID, inputs, true, callback (results, callback) -> debug "Results for seller for attempt #{i}" debug results id = results.meta.reqID price = Math.round(results.price * 100) / 100 inputs = _.extend({price: price}, status) debug "Calling buyer for attempt #{i}" client.evaluate buyerID, inputs, callback (results, callback) -> debug "Results for buyer for attempt #{i}" debug results if results.willBuy > threshold profit = Math.round((price - cost) * 100) / 100 else profit = 0 debug "profit for attempt #{i} = #{profit}" client.feedback id, {profit: profit}, (err, fb) -> if err callback err else callback null, profit ], callback profits = null async.waterfall [ (callback) -> debug "Creating new buyer agent" client.newAgent buyer, callback (saved, callback) -> buyerID = saved.id debug saved debug "Buyer ID = #{buyerID}" debug "Creating new seller agent" client.newAgent seller, callback (saved, callback) -> sellerID = saved.id debug saved debug "Seller ID = #{sellerID}" async.timesLimit buyers, parallel, attemptSale, callback (results, callback) -> profits = results debug "Deleting buyer agent #{buyerID}" client.deleteAgent buyerID, callback (callback) -> debug "Deleting seller agent #{sellerID}" client.deleteAgent sellerID, callback ], (err) -> if err console.error err else console.dir profits false main argv
true
# simulation.coffee # Copyright 2016 9165584 Canada Corporation <PI:EMAIL:<EMAIL>END_PI> path = require 'path' async = require 'async' _ = require 'lodash' APIClient = require 'fuzzy.ai' debug = require('debug')('simulation') argv = require('yargs') .demand('k') .alias('k', 'key') .describe('k', 'API key') .default('r', 'https://api.fuzzy.ai') .alias('r', 'root') .describe('r', 'API root URL') .default('b', 100) .alias('b', 'buyers') .describe('b', 'number of buyers') .default('p', 8) .alias('p', 'parallel') .describe('p', 'number of buyers to run in parallel') .default('t', 0.5) .alias('t', 'threshold') .describe('t', 'buy threshold') .default('c', 0.50) .alias('c', 'cost') .describe('c', 'Total unit cost') .env('HOT_CHOCOLATE') .config() .default('config', path.join(process.env['HOME'], '.hotchocolate.json')) .alias('f', 'config') .help() .alias('h', 'help') .argv { seller, buyer } = require './agents' main = (argv) -> # Explode these so we aren't depending on argv everywhere debug(argv) {key, root, buyers, threshold, cost, parallel} = argv cost = 0.50 client = new APIClient {key: key, root: root} buyerID = null sellerID = null temperature = 32 sunny = 0 attemptSale = (i, callback) -> debug "Attempting sale #{i}" id = null price = null # randomly change up the environment if Math.round(Math.random()) temperature = Math.round(Math.random() * 100) sunny = Math.round(Math.random()) status = numBuyers: buyers - i temperature: temperature sunny: sunny debug status async.waterfall [ (callback) -> inputs = _.clone(status) debug "Calling seller for attempt #{i}" client.evaluate sellerID, inputs, true, callback (results, callback) -> debug "Results for seller for attempt #{i}" debug results id = results.meta.reqID price = Math.round(results.price * 100) / 100 inputs = _.extend({price: price}, status) debug "Calling buyer for attempt #{i}" client.evaluate buyerID, inputs, callback (results, callback) -> debug "Results for buyer for attempt #{i}" debug results if results.willBuy > threshold profit = Math.round((price - cost) * 100) / 100 else profit = 0 debug "profit for attempt #{i} = #{profit}" client.feedback id, {profit: profit}, (err, fb) -> if err callback err else callback null, profit ], callback profits = null async.waterfall [ (callback) -> debug "Creating new buyer agent" client.newAgent buyer, callback (saved, callback) -> buyerID = saved.id debug saved debug "Buyer ID = #{buyerID}" debug "Creating new seller agent" client.newAgent seller, callback (saved, callback) -> sellerID = saved.id debug saved debug "Seller ID = #{sellerID}" async.timesLimit buyers, parallel, attemptSale, callback (results, callback) -> profits = results debug "Deleting buyer agent #{buyerID}" client.deleteAgent buyerID, callback (callback) -> debug "Deleting seller agent #{sellerID}" client.deleteAgent sellerID, callback ], (err) -> if err console.error err else console.dir profits false main argv
[ { "context": "\"How could you forget about me. I'm your assistant Rachel.\"\n ]\n }\n {\n id: 'iloveyou'\n ", "end": 1137, "score": 0.8711712956428528, "start": 1131, "tag": "NAME", "value": "Rachel" }, { "context": "istant Rachel.\"\n ]\n }\n {\n ...
src/server/services/general-parsers.coffee
FindBoat/rachel-bot
0
mappings = (name) -> [ { id: 'hi' regex: /// (^hi$)|(^hi\s\S+) /// answers: ["Hi #{name}, what can I do for you?"] } { id: 'hru' regex: /// (how\sare\syou)|(how's\sit\sgoin)|(what's\sup) /// answers: [ "I am better than heaven today!, thank you #{name}. How about you?" "Cool as a cucumber! How about you #{name}?" "I'd be better if I won the lottery. And you?" "I can't complain... I've tried, but no one listens." "Blood pressure 120/80, respiration 16, CBC and Chem Panels normal." "I am feeling happier than ever!! And you?" ] } { id: 'thank' regex: /// (\bthank)|(\bthx\b) /// answers: [ "You're very welcome #{name}!" "No problem #{name}!" "You're welcome #{name}!" ] } { id: 'sorry' regex: /// \bsorry\b /// answers: [ "Please, no apology needed. I only exist to serve you #{name}." ] } { id: 'wru' regex: /// who\sare\syou /// answers: [ "How could you forget about me. I'm your assistant Rachel." ] } { id: 'iloveyou' regex: /// i\slove\syou /// answers: [ "Rachel also loves you!" ] } ] parse = (text, user, next) -> for rule in mappings user.firstName if rule.regex.test text r = Math.floor (Math.random() * rule.answers.length) next null, {id: rule.id, answer: rule.answers[r]} return next null, null module.exports = parse: parse
162592
mappings = (name) -> [ { id: 'hi' regex: /// (^hi$)|(^hi\s\S+) /// answers: ["Hi #{name}, what can I do for you?"] } { id: 'hru' regex: /// (how\sare\syou)|(how's\sit\sgoin)|(what's\sup) /// answers: [ "I am better than heaven today!, thank you #{name}. How about you?" "Cool as a cucumber! How about you #{name}?" "I'd be better if I won the lottery. And you?" "I can't complain... I've tried, but no one listens." "Blood pressure 120/80, respiration 16, CBC and Chem Panels normal." "I am feeling happier than ever!! And you?" ] } { id: 'thank' regex: /// (\bthank)|(\bthx\b) /// answers: [ "You're very welcome #{name}!" "No problem #{name}!" "You're welcome #{name}!" ] } { id: 'sorry' regex: /// \bsorry\b /// answers: [ "Please, no apology needed. I only exist to serve you #{name}." ] } { id: 'wru' regex: /// who\sare\syou /// answers: [ "How could you forget about me. I'm your assistant <NAME>." ] } { id: 'iloveyou' regex: /// i\slove\syou /// answers: [ "<NAME> also loves you!" ] } ] parse = (text, user, next) -> for rule in mappings user.firstName if rule.regex.test text r = Math.floor (Math.random() * rule.answers.length) next null, {id: rule.id, answer: rule.answers[r]} return next null, null module.exports = parse: parse
true
mappings = (name) -> [ { id: 'hi' regex: /// (^hi$)|(^hi\s\S+) /// answers: ["Hi #{name}, what can I do for you?"] } { id: 'hru' regex: /// (how\sare\syou)|(how's\sit\sgoin)|(what's\sup) /// answers: [ "I am better than heaven today!, thank you #{name}. How about you?" "Cool as a cucumber! How about you #{name}?" "I'd be better if I won the lottery. And you?" "I can't complain... I've tried, but no one listens." "Blood pressure 120/80, respiration 16, CBC and Chem Panels normal." "I am feeling happier than ever!! And you?" ] } { id: 'thank' regex: /// (\bthank)|(\bthx\b) /// answers: [ "You're very welcome #{name}!" "No problem #{name}!" "You're welcome #{name}!" ] } { id: 'sorry' regex: /// \bsorry\b /// answers: [ "Please, no apology needed. I only exist to serve you #{name}." ] } { id: 'wru' regex: /// who\sare\syou /// answers: [ "How could you forget about me. I'm your assistant PI:NAME:<NAME>END_PI." ] } { id: 'iloveyou' regex: /// i\slove\syou /// answers: [ "PI:NAME:<NAME>END_PI also loves you!" ] } ] parse = (text, user, next) -> for rule in mappings user.firstName if rule.regex.test text r = Math.floor (Math.random() * rule.answers.length) next null, {id: rule.id, answer: rule.answers[r]} return next null, null module.exports = parse: parse
[ { "context": "le\n# resin.models.device.get('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(f", "end": 3283, "score": 0.5050502419471741, "start": 3282, "tag": "KEY", "value": "5" }, { "context": "sin.models.device.get('7cf02a62a3a84440b1bb5579a3d57469148943278...
lib/models/device.coffee
everyside/resin-sdk
0
### The MIT License Copyright (c) 2015 Resin.io, Inc. https://resin.io. 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. ### Promise = require('bluebird') crypto = require('crypto') _ = require('lodash') pine = require('resin-pine') errors = require('resin-errors') request = require('resin-request') registerDevice = require('resin-register-device') configModel = require('./config') applicationModel = require('./application') auth = require('../auth') ###* # @summary Get all devices # @name getAll # @public # @function # @memberof resin.models.device # # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getAll().then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getAll(function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getAll = (callback) -> return pine.get resource: 'device' options: expand: 'application' orderby: 'name asc' .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get all devices by application # @name getAllByApplication # @public # @function # @memberof resin.models.device # # @param {String} name - application name # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getAllByApplication('MyApp').then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getAllByApplication('MyApp', function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getAllByApplication = (name, callback) -> applicationModel.has(name).then (hasApplication) -> if not hasApplication throw new errors.ResinApplicationNotFound(name) return pine.get resource: 'device' options: filter: application: app_name: name expand: 'application' orderby: 'name asc' # TODO: Move to server .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get a single device # @name get # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Object} - device # @returns {Promise} # # @example # resin.models.device.get('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(device) { # console.log(device); # }) # # @example # resin.models.device.get('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, device) { # if (error) throw error; # console.log(device); # }); ### exports.get = (uuid, callback) -> return pine.get resource: 'device' options: expand: 'application' filter: uuid: uuid .tap (device) -> if _.isEmpty(device) throw new errors.ResinDeviceNotFound(uuid) .get(0) .tap (device) -> device.application_name = device.application[0].app_name .nodeify(callback) ###* # @summary Get devices by name # @name getByName # @public # @function # @memberof resin.models.device # # @param {String} name - device name # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getByName('MyDevice').then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getByName('MyDevice', function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getByName = (name, callback) -> return pine.get resource: 'device' options: expand: 'application' filter: name: name .tap (devices) -> if _.isEmpty(devices) throw new errors.ResinDeviceNotFound(name) .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get the name of a device # @name getName # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - device name # @returns {Promise} # # @example # resin.models.device.getName('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(deviceName) { # console.log(deviceName); # }); # # @example # resin.models.device.getName('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, deviceName) { # if (error) throw error; # console.log(deviceName); # }); ### exports.getName = (uuid, callback) -> exports.get(uuid).get('name').nodeify(callback) ###* # @summary Get application name # @name getApplicationName # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - application name # @returns {Promise} # # @example # resin.models.device.getApplicationName('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(applicationName) { # console.log(applicationName); # }); # # @example # resin.models.device.getApplicationName('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, applicationName) { # if (error) throw error; # console.log(applicationName); # }); ### exports.getApplicationName = (uuid, callback) -> exports.get(uuid).get('application_name').nodeify(callback) ###* # @summary Check if a device exists # @name has # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - has device # @returns {Promise} # # @example # resin.models.device.has('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(hasDevice) { # console.log(hasDevice); # }); # # @example # resin.models.device.has('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, hasDevice) { # if (error) throw error; # console.log(hasDevice); # }); ### exports.has = (uuid, callback) -> exports.get(uuid).return(true) .catch errors.ResinDeviceNotFound, -> return false .nodeify(callback) ###* # @summary Check if a device is online # @name isOnline # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - is device online # @returns {Promise} # # @example # resin.models.device.isOnline('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(isOnline) { # console.log('Is device online?', isOnline); # }); # # @example # resin.models.device.isOnline('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, isOnline) { # if (error) throw error; # console.log('Is device online?', isOnline); # }); ### exports.isOnline = (uuid, callback) -> exports.get(uuid).get('is_online').nodeify(callback) ###* # @summary Get the local IP addresses of a device # @name getLocalIPAddresses # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String[]} - local ip addresses # @reject {Error} Will reject if the device is offline # @returns {Promise} # # @example # resin.models.device.getLocalIPAddresses('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(localIPAddresses) { # localIPAddresses.forEach(function(localIP) { # console.log(localIP); # }); # }); # # @example # resin.models.device.getLocalIPAddresses('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, localIPAddresses) { # if (error) throw error; # # localIPAddresses.forEach(function(localIP) { # console.log(localIP); # }); # }); ### exports.getLocalIPAddresses = (uuid, callback) -> exports.get(uuid).then (device) -> if not device.is_online throw new Error("The device is offline: #{uuid}") ips = device.ip_address.split(' ') return _.without(ips, device.vpn_address) .nodeify(callback) ###* # @summary Remove device # @name remove # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.remove('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9'); # # @example # resin.models.device.remove('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error) { # if (error) throw error; # }); ### exports.remove = (uuid, callback) -> exports.get(uuid).then -> return pine.delete resource: 'device' options: filter: uuid: uuid .nodeify(callback) ###* # @summary Identify device # @name identify # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.identify('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9'); # # @example # resin.models.device.identify('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error) { # if (error) throw error; # }); ### exports.identify = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return request.send method: 'POST' url: '/blink' body: uuid: uuid .return(undefined) .nodeify(callback) ###* # @summary Rename device # @name rename # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} newName - the device new name # # @returns {Promise} # # @example # resin.models.device.rename('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'NewName'); # # @example # resin.models.device.rename('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'NewName', function(error) { # if (error) throw error; # }); ### exports.rename = (uuid, newName, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: name: newName options: filter: uuid: uuid .nodeify(callback) ###* # @summary Note a device # @name note # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} note - the note # # @returns {Promise} # # @example # resin.models.device.note('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'My useful note'); # # @example # resin.models.device.note('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'My useful note', function(error) { # if (error) throw error; # }); ### exports.note = (uuid, note, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: note: note options: filter: uuid: uuid .nodeify(callback) ###* # @summary Move a device to another application # @name move # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} application - application name # # @returns {Promise} # # @example # resin.models.device.move('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'MyApp'); # # @example # resin.models.device.move('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'MyApp', function(error) { # if (error) throw error; # }); ### exports.move = (uuid, application, callback) -> Promise.props device: exports.get(uuid) application: applicationModel.get(application) .then (results) -> if results.device.device_type isnt results.application.device_type throw new Error("Incompatible application: #{application}") return pine.patch resource: 'device' body: application: results.application.id options: filter: uuid: uuid .nodeify(callback) ###* # @summary Restart device # @name restart # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.restart('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9'); # # @example # resin.models.device.restart('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error) { # if (error) throw error; # }); ### exports.restart = (uuid, callback) -> exports.get(uuid).then (device) -> return request.send method: 'POST' url: "/device/#{device.id}/restart" .get('body') .nodeify(callback) ###* # @summary Get display name for a device # @name getDisplayName # @public # @function # @memberof resin.models.device # # @see {@link module:resin.models.device.getSupportedDeviceTypes} for a list of supported devices # # @param {String} deviceTypeSlug - device type slug # @fulfil {String} - device display name # @returns {Promise} # # @example # resin.models.device.getDisplayName('raspberry-pi').then(function(deviceTypeName) { # console.log(deviceTypeName); # // Raspberry Pi # }); # # @example # resin.models.device.getDisplayName('raspberry-pi', function(error, deviceTypeName) { # if (error) throw error; # console.log(deviceTypeName); # // Raspberry Pi # }); ### exports.getDisplayName = (deviceTypeSlug, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> deviceTypeFound = _.findWhere(deviceTypes, slug: deviceTypeSlug) return deviceTypeFound?.name .nodeify(callback) ###* # @summary Get device slug # @name getDeviceSlug # @public # @function # @memberof resin.models.device # # @see {@link module:resin.models.device.getSupportedDeviceTypes} for a list of supported devices # # @param {String} deviceTypeName - device type name # @fulfil {String} - device slug name # @returns {Promise} # # @example # resin.models.device.getDeviceSlug('Raspberry Pi').then(function(deviceTypeSlug) { # console.log(deviceTypeSlug); # // raspberry-pi # }); # # @example # resin.models.device.getDeviceSlug('Raspberry Pi', function(error, deviceTypeSlug) { # if (error) throw error; # console.log(deviceTypeSlug); # // raspberry-pi # }); ### exports.getDeviceSlug = (deviceTypeName, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> foundByName = _.findWhere(deviceTypes, name: deviceTypeName) foundBySlug = _.findWhere(deviceTypes, slug: deviceTypeName) deviceTypeFound = foundByName or foundBySlug return deviceTypeFound?.slug .nodeify(callback) ###* # @summary Get supported device types # @name getSupportedDeviceTypes # @public # @function # @memberof resin.models.device # # @fulfil {String[]} - supported device types # @returns {Promise} # # @example # resin.models.device.getSupportedDeviceTypes().then(function(supportedDeviceTypes) { # supportedDeviceTypes.forEach(function(supportedDeviceType) { # console.log('Resin supports:', supportedDeviceType); # }); # }); # # @example # resin.models.device.getSupportedDeviceTypes(function(error, supportedDeviceTypes) { # if (error) throw error; # # supportedDeviceTypes.forEach(function(supportedDeviceType) { # console.log('Resin supports:', supportedDeviceType); # }); # }); ### exports.getSupportedDeviceTypes = (callback) -> configModel.getDeviceTypes().then (deviceTypes) -> return _.pluck(deviceTypes, 'name') .nodeify(callback) ###* # @summary Get a device manifest by slug # @name getManifestBySlug # @public # @function # @memberof resin.models.device # # @param {String} slug - device slug # @fulfil {Object} - device manifest # @returns {Promise} # # @example # resin.models.device.getManifestBySlug('raspberry-pi').then(function(manifest) { # console.log(manifest); # }); # # @example # resin.models.device.getManifestBySlug('raspberry-pi', function(error, manifest) { # if (error) throw error; # console.log(manifest); # }); ### exports.getManifestBySlug = (slug, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> deviceManifest = _.find(deviceTypes, { slug }) if not deviceManifest? throw new Error("Unsupported device: #{slug}") return deviceManifest .nodeify(callback) ###* # @summary Get a device manifest by application name # @name getManifestByApplication # @public # @function # @memberof resin.models.device # # @param {String} applicationName - application name # @fulfil {Object} - device manifest # @returns {Promise} # # @example # resin.models.device.getManifestByApplication('MyApp').then(function(manifest) { # console.log(manifest); # }); # # @example # resin.models.device.getManifestByApplication('MyApp', function(error, manifest) { # if (error) throw error; # console.log(manifest); # }); ### exports.getManifestByApplication = (applicationName, callback) -> applicationModel.get(applicationName).get('device_type').then (deviceType) -> return exports.getManifestBySlug(deviceType) .nodeify(callback) ###* # @summary Generate a random device UUID # @name generateUUID # @function # @public # @memberof resin.models.device # # @fulfil {String} - a generated UUID # @returns {Promise} # # @example # resin.models.device.generateUUID().then(function(uuid) { # console.log(uuid); # }); # # @example # resin.models.device.generateUUID(function(error, uuid) { # if (error) throw error; # console.log(uuid); # }); ### exports.generateUUID = registerDevice.generateUUID ###* # @summary Register a new device with a Resin.io application # @name register # @public # @function # @memberof resin.models.device # # @param {String} applicationName - application name # @param {String} uuid - device uuid # # @fulfil {Object} - device # @returns {Promise} # # @example # resin.models.device.generateUUID().then(function(uuid) { # resin.models.device.register('MyApp', uuid).then(function(device) { # console.log(device); # }); # }); # # @example # resin.models.device.generateUUID(function(error, uuid) { # if (error) throw error; # # resin.models.device.register('MyApp', uuid, function(error, device) { # if (error) throw error; # # console.log(device); # }); # }); ### exports.register = (applicationName, uuid, callback) -> Promise.props userId: auth.getUserId() apiKey: applicationModel.getApiKey(applicationName) application: applicationModel.get(applicationName) .then (results) -> return registerDevice.register pine, userId: results.userId applicationId: results.application.id deviceType: results.application.device_type uuid: uuid apiKey: results.apiKey .nodeify(callback) ###* # @summary Check if a device is web accessible with device utls # @name hasDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - has device url # @returns {Promise} # # @example # resin.models.device.hasDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9'); # # @example # resin.models.device.hasDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error) { # if (error) throw error; # }); ### exports.hasDeviceUrl = (uuid, callback) -> exports.get(uuid).get('is_web_accessible').nodeify(callback) ###* # @summary Get a device url # @name getDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - device url # @returns {Promise} # # @example # resin.models.device.getDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9').then(function(url) { # console.log(url); # }); # # @example # resin.models.device.getDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error, url) { # if (error) throw error; # console.log(url); # }); ### exports.getDeviceUrl = (uuid, callback) -> exports.hasDeviceUrl(uuid).then (hasDeviceUrl) -> if not hasDeviceUrl throw new Error("Device is not web accessible: #{uuid}") return configModel.getAll().get('deviceUrlsBase') .then (deviceUrlsBase) -> return "https://#{uuid}.#{deviceUrlsBase}" .nodeify(callback) ###* # @summary Enable device url for a device # @name enableDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.enableDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9'); # # @example # resin.models.device.enableDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error) { # if (error) throw error; # }); ### exports.enableDeviceUrl = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: is_web_accessible: true options: filter: uuid: uuid .nodeify(callback) ###* # @summary Disable device url for a device # @name disableDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.disableDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9'); # # @example # resin.models.device.disableDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', function(error) { # if (error) throw error; # }); ### exports.disableDeviceUrl = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: is_web_accessible: false options: filter: uuid: uuid .nodeify(callback)
56665
### The MIT License Copyright (c) 2015 Resin.io, Inc. https://resin.io. 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. ### Promise = require('bluebird') crypto = require('crypto') _ = require('lodash') pine = require('resin-pine') errors = require('resin-errors') request = require('resin-request') registerDevice = require('resin-register-device') configModel = require('./config') applicationModel = require('./application') auth = require('../auth') ###* # @summary Get all devices # @name getAll # @public # @function # @memberof resin.models.device # # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getAll().then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getAll(function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getAll = (callback) -> return pine.get resource: 'device' options: expand: 'application' orderby: 'name asc' .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get all devices by application # @name getAllByApplication # @public # @function # @memberof resin.models.device # # @param {String} name - application name # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getAllByApplication('MyApp').then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getAllByApplication('MyApp', function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getAllByApplication = (name, callback) -> applicationModel.has(name).then (hasApplication) -> if not hasApplication throw new errors.ResinApplicationNotFound(name) return pine.get resource: 'device' options: filter: application: app_name: name expand: 'application' orderby: 'name asc' # TODO: Move to server .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get a single device # @name get # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Object} - device # @returns {Promise} # # @example # resin.models.device.get('7cf02a62a3a84440b1bb<KEY>579a3d<KEY>46<KEY>4<KEY>630b17e7fc6c4f7b465c9').then(function(device) { # console.log(device); # }) # # @example # resin.models.device.get('<KEY>', function(error, device) { # if (error) throw error; # console.log(device); # }); ### exports.get = (uuid, callback) -> return pine.get resource: 'device' options: expand: 'application' filter: uuid: uuid .tap (device) -> if _.isEmpty(device) throw new errors.ResinDeviceNotFound(uuid) .get(0) .tap (device) -> device.application_name = device.application[0].app_name .nodeify(callback) ###* # @summary Get devices by name # @name getByName # @public # @function # @memberof resin.models.device # # @param {String} name - device name # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getByName('MyDevice').then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getByName('MyDevice', function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getByName = (name, callback) -> return pine.get resource: 'device' options: expand: 'application' filter: name: name .tap (devices) -> if _.isEmpty(devices) throw new errors.ResinDeviceNotFound(name) .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get the name of a device # @name getName # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - device name # @returns {Promise} # # @example # resin.models.device.getName('<KEY>').then(function(deviceName) { # console.log(deviceName); # }); # # @example # resin.models.device.getName('<KEY>', function(error, deviceName) { # if (error) throw error; # console.log(deviceName); # }); ### exports.getName = (uuid, callback) -> exports.get(uuid).get('name').nodeify(callback) ###* # @summary Get application name # @name getApplicationName # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - application name # @returns {Promise} # # @example # resin.models.device.getApplicationName('<KEY>').then(function(applicationName) { # console.log(applicationName); # }); # # @example # resin.models.device.getApplicationName('7<KEY>', function(error, applicationName) { # if (error) throw error; # console.log(applicationName); # }); ### exports.getApplicationName = (uuid, callback) -> exports.get(uuid).get('application_name').nodeify(callback) ###* # @summary Check if a device exists # @name has # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - has device # @returns {Promise} # # @example # resin.models.device.has('<KEY>').then(function(hasDevice) { # console.log(hasDevice); # }); # # @example # resin.models.device.has('<KEY>', function(error, hasDevice) { # if (error) throw error; # console.log(hasDevice); # }); ### exports.has = (uuid, callback) -> exports.get(uuid).return(true) .catch errors.ResinDeviceNotFound, -> return false .nodeify(callback) ###* # @summary Check if a device is online # @name isOnline # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - is device online # @returns {Promise} # # @example # resin.models.device.isOnline('7<KEY>').then(function(isOnline) { # console.log('Is device online?', isOnline); # }); # # @example # resin.models.device.isOnline('<KEY>', function(error, isOnline) { # if (error) throw error; # console.log('Is device online?', isOnline); # }); ### exports.isOnline = (uuid, callback) -> exports.get(uuid).get('is_online').nodeify(callback) ###* # @summary Get the local IP addresses of a device # @name getLocalIPAddresses # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String[]} - local ip addresses # @reject {Error} Will reject if the device is offline # @returns {Promise} # # @example # resin.models.device.getLocalIPAddresses('<KEY>').then(function(localIPAddresses) { # localIPAddresses.forEach(function(localIP) { # console.log(localIP); # }); # }); # # @example # resin.models.device.getLocalIPAddresses('<KEY>', function(error, localIPAddresses) { # if (error) throw error; # # localIPAddresses.forEach(function(localIP) { # console.log(localIP); # }); # }); ### exports.getLocalIPAddresses = (uuid, callback) -> exports.get(uuid).then (device) -> if not device.is_online throw new Error("The device is offline: #{uuid}") ips = device.ip_address.split(' ') return _.without(ips, device.vpn_address) .nodeify(callback) ###* # @summary Remove device # @name remove # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.remove('7<KEY>'); # # @example # resin.models.device.remove('7<KEY>', function(error) { # if (error) throw error; # }); ### exports.remove = (uuid, callback) -> exports.get(uuid).then -> return pine.delete resource: 'device' options: filter: uuid: uuid .nodeify(callback) ###* # @summary Identify device # @name identify # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.identify('7cf<KEY>'); # # @example # resin.models.device.identify('<KEY>', function(error) { # if (error) throw error; # }); ### exports.identify = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return request.send method: 'POST' url: '/blink' body: uuid: uuid .return(undefined) .nodeify(callback) ###* # @summary Rename device # @name rename # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} newName - the device new name # # @returns {Promise} # # @example # resin.models.device.rename('<KEY>', 'NewName'); # # @example # resin.models.device.rename('<KEY>', 'NewName', function(error) { # if (error) throw error; # }); ### exports.rename = (uuid, newName, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: name: newName options: filter: uuid: uuid .nodeify(callback) ###* # @summary Note a device # @name note # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} note - the note # # @returns {Promise} # # @example # resin.models.device.note('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'My useful note'); # # @example # resin.models.device.note('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'My useful note', function(error) { # if (error) throw error; # }); ### exports.note = (uuid, note, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: note: note options: filter: uuid: uuid .nodeify(callback) ###* # @summary Move a device to another application # @name move # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} application - application name # # @returns {Promise} # # @example # resin.models.device.move('7cf02a62a3a84440b1bb5579a3<KEY>', 'MyApp'); # # @example # resin.models.device.move('7<KEY>', 'MyApp', function(error) { # if (error) throw error; # }); ### exports.move = (uuid, application, callback) -> Promise.props device: exports.get(uuid) application: applicationModel.get(application) .then (results) -> if results.device.device_type isnt results.application.device_type throw new Error("Incompatible application: #{application}") return pine.patch resource: 'device' body: application: results.application.id options: filter: uuid: uuid .nodeify(callback) ###* # @summary Restart device # @name restart # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.restart('7<KEY>'); # # @example # resin.models.device.restart('7<KEY>', function(error) { # if (error) throw error; # }); ### exports.restart = (uuid, callback) -> exports.get(uuid).then (device) -> return request.send method: 'POST' url: "/device/#{device.id}/restart" .get('body') .nodeify(callback) ###* # @summary Get display name for a device # @name getDisplayName # @public # @function # @memberof resin.models.device # # @see {@link module:resin.models.device.getSupportedDeviceTypes} for a list of supported devices # # @param {String} deviceTypeSlug - device type slug # @fulfil {String} - device display name # @returns {Promise} # # @example # resin.models.device.getDisplayName('raspberry-pi').then(function(deviceTypeName) { # console.log(deviceTypeName); # // Raspberry Pi # }); # # @example # resin.models.device.getDisplayName('raspberry-pi', function(error, deviceTypeName) { # if (error) throw error; # console.log(deviceTypeName); # // Raspberry Pi # }); ### exports.getDisplayName = (deviceTypeSlug, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> deviceTypeFound = _.findWhere(deviceTypes, slug: deviceTypeSlug) return deviceTypeFound?.name .nodeify(callback) ###* # @summary Get device slug # @name getDeviceSlug # @public # @function # @memberof resin.models.device # # @see {@link module:resin.models.device.getSupportedDeviceTypes} for a list of supported devices # # @param {String} deviceTypeName - device type name # @fulfil {String} - device slug name # @returns {Promise} # # @example # resin.models.device.getDeviceSlug('Raspberry Pi').then(function(deviceTypeSlug) { # console.log(deviceTypeSlug); # // raspberry-pi # }); # # @example # resin.models.device.getDeviceSlug('Raspberry Pi', function(error, deviceTypeSlug) { # if (error) throw error; # console.log(deviceTypeSlug); # // raspberry-pi # }); ### exports.getDeviceSlug = (deviceTypeName, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> foundByName = _.findWhere(deviceTypes, name: deviceTypeName) foundBySlug = _.findWhere(deviceTypes, slug: deviceTypeName) deviceTypeFound = foundByName or foundBySlug return deviceTypeFound?.slug .nodeify(callback) ###* # @summary Get supported device types # @name getSupportedDeviceTypes # @public # @function # @memberof resin.models.device # # @fulfil {String[]} - supported device types # @returns {Promise} # # @example # resin.models.device.getSupportedDeviceTypes().then(function(supportedDeviceTypes) { # supportedDeviceTypes.forEach(function(supportedDeviceType) { # console.log('Resin supports:', supportedDeviceType); # }); # }); # # @example # resin.models.device.getSupportedDeviceTypes(function(error, supportedDeviceTypes) { # if (error) throw error; # # supportedDeviceTypes.forEach(function(supportedDeviceType) { # console.log('Resin supports:', supportedDeviceType); # }); # }); ### exports.getSupportedDeviceTypes = (callback) -> configModel.getDeviceTypes().then (deviceTypes) -> return _.pluck(deviceTypes, 'name') .nodeify(callback) ###* # @summary Get a device manifest by slug # @name getManifestBySlug # @public # @function # @memberof resin.models.device # # @param {String} slug - device slug # @fulfil {Object} - device manifest # @returns {Promise} # # @example # resin.models.device.getManifestBySlug('raspberry-pi').then(function(manifest) { # console.log(manifest); # }); # # @example # resin.models.device.getManifestBySlug('raspberry-pi', function(error, manifest) { # if (error) throw error; # console.log(manifest); # }); ### exports.getManifestBySlug = (slug, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> deviceManifest = _.find(deviceTypes, { slug }) if not deviceManifest? throw new Error("Unsupported device: #{slug}") return deviceManifest .nodeify(callback) ###* # @summary Get a device manifest by application name # @name getManifestByApplication # @public # @function # @memberof resin.models.device # # @param {String} applicationName - application name # @fulfil {Object} - device manifest # @returns {Promise} # # @example # resin.models.device.getManifestByApplication('MyApp').then(function(manifest) { # console.log(manifest); # }); # # @example # resin.models.device.getManifestByApplication('MyApp', function(error, manifest) { # if (error) throw error; # console.log(manifest); # }); ### exports.getManifestByApplication = (applicationName, callback) -> applicationModel.get(applicationName).get('device_type').then (deviceType) -> return exports.getManifestBySlug(deviceType) .nodeify(callback) ###* # @summary Generate a random device UUID # @name generateUUID # @function # @public # @memberof resin.models.device # # @fulfil {String} - a generated UUID # @returns {Promise} # # @example # resin.models.device.generateUUID().then(function(uuid) { # console.log(uuid); # }); # # @example # resin.models.device.generateUUID(function(error, uuid) { # if (error) throw error; # console.log(uuid); # }); ### exports.generateUUID = registerDevice.generateUUID ###* # @summary Register a new device with a Resin.io application # @name register # @public # @function # @memberof resin.models.device # # @param {String} applicationName - application name # @param {String} uuid - device uuid # # @fulfil {Object} - device # @returns {Promise} # # @example # resin.models.device.generateUUID().then(function(uuid) { # resin.models.device.register('MyApp', uuid).then(function(device) { # console.log(device); # }); # }); # # @example # resin.models.device.generateUUID(function(error, uuid) { # if (error) throw error; # # resin.models.device.register('MyApp', uuid, function(error, device) { # if (error) throw error; # # console.log(device); # }); # }); ### exports.register = (applicationName, uuid, callback) -> Promise.props userId: auth.getUserId() apiKey: applicationModel.getApiKey(applicationName) application: applicationModel.get(applicationName) .then (results) -> return registerDevice.register pine, userId: results.userId applicationId: results.application.id deviceType: results.application.device_type uuid: uuid apiKey: results.apiKey .nodeify(callback) ###* # @summary Check if a device is web accessible with device utls # @name hasDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - has device url # @returns {Promise} # # @example # resin.models.device.hasDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b<KEY>'); # # @example # resin.models.device.hasDeviceUrl('7cf<KEY>', function(error) { # if (error) throw error; # }); ### exports.hasDeviceUrl = (uuid, callback) -> exports.get(uuid).get('is_web_accessible').nodeify(callback) ###* # @summary Get a device url # @name getDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - device url # @returns {Promise} # # @example # resin.models.device.getDeviceUrl('7cf<KEY>').then(function(url) { # console.log(url); # }); # # @example # resin.models.device.getDeviceUrl('7cf02a6<KEY>a3a8<KEY>b<KEY>bb<KEY>3d<KEY>', function(error, url) { # if (error) throw error; # console.log(url); # }); ### exports.getDeviceUrl = (uuid, callback) -> exports.hasDeviceUrl(uuid).then (hasDeviceUrl) -> if not hasDeviceUrl throw new Error("Device is not web accessible: #{uuid}") return configModel.getAll().get('deviceUrlsBase') .then (deviceUrlsBase) -> return "https://#{uuid}.#{deviceUrlsBase}" .nodeify(callback) ###* # @summary Enable device url for a device # @name enableDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.enableDeviceUrl('<KEY>'); # # @example # resin.models.device.enableDeviceUrl('<KEY>', function(error) { # if (error) throw error; # }); ### exports.enableDeviceUrl = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: is_web_accessible: true options: filter: uuid: uuid .nodeify(callback) ###* # @summary Disable device url for a device # @name disableDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.disableDeviceUrl('<KEY>'); # # @example # resin.models.device.disableDeviceUrl('7<KEY>', function(error) { # if (error) throw error; # }); ### exports.disableDeviceUrl = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: is_web_accessible: false options: filter: uuid: uuid .nodeify(callback)
true
### The MIT License Copyright (c) 2015 Resin.io, Inc. https://resin.io. 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. ### Promise = require('bluebird') crypto = require('crypto') _ = require('lodash') pine = require('resin-pine') errors = require('resin-errors') request = require('resin-request') registerDevice = require('resin-register-device') configModel = require('./config') applicationModel = require('./application') auth = require('../auth') ###* # @summary Get all devices # @name getAll # @public # @function # @memberof resin.models.device # # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getAll().then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getAll(function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getAll = (callback) -> return pine.get resource: 'device' options: expand: 'application' orderby: 'name asc' .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get all devices by application # @name getAllByApplication # @public # @function # @memberof resin.models.device # # @param {String} name - application name # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getAllByApplication('MyApp').then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getAllByApplication('MyApp', function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getAllByApplication = (name, callback) -> applicationModel.has(name).then (hasApplication) -> if not hasApplication throw new errors.ResinApplicationNotFound(name) return pine.get resource: 'device' options: filter: application: app_name: name expand: 'application' orderby: 'name asc' # TODO: Move to server .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get a single device # @name get # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Object} - device # @returns {Promise} # # @example # resin.models.device.get('7cf02a62a3a84440b1bbPI:KEY:<KEY>END_PI579a3dPI:KEY:<KEY>END_PI46PI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PI630b17e7fc6c4f7b465c9').then(function(device) { # console.log(device); # }) # # @example # resin.models.device.get('PI:KEY:<KEY>END_PI', function(error, device) { # if (error) throw error; # console.log(device); # }); ### exports.get = (uuid, callback) -> return pine.get resource: 'device' options: expand: 'application' filter: uuid: uuid .tap (device) -> if _.isEmpty(device) throw new errors.ResinDeviceNotFound(uuid) .get(0) .tap (device) -> device.application_name = device.application[0].app_name .nodeify(callback) ###* # @summary Get devices by name # @name getByName # @public # @function # @memberof resin.models.device # # @param {String} name - device name # @fulfil {Object[]} - devices # @returns {Promise} # # @example # resin.models.device.getByName('MyDevice').then(function(devices) { # console.log(devices); # }); # # @example # resin.models.device.getByName('MyDevice', function(error, devices) { # if (error) throw error; # console.log(devices); # }); ### exports.getByName = (name, callback) -> return pine.get resource: 'device' options: expand: 'application' filter: name: name .tap (devices) -> if _.isEmpty(devices) throw new errors.ResinDeviceNotFound(name) .map (device) -> device.application_name = device.application[0].app_name return device .nodeify(callback) ###* # @summary Get the name of a device # @name getName # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - device name # @returns {Promise} # # @example # resin.models.device.getName('PI:KEY:<KEY>END_PI').then(function(deviceName) { # console.log(deviceName); # }); # # @example # resin.models.device.getName('PI:KEY:<KEY>END_PI', function(error, deviceName) { # if (error) throw error; # console.log(deviceName); # }); ### exports.getName = (uuid, callback) -> exports.get(uuid).get('name').nodeify(callback) ###* # @summary Get application name # @name getApplicationName # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - application name # @returns {Promise} # # @example # resin.models.device.getApplicationName('PI:KEY:<KEY>END_PI').then(function(applicationName) { # console.log(applicationName); # }); # # @example # resin.models.device.getApplicationName('7PI:KEY:<KEY>END_PI', function(error, applicationName) { # if (error) throw error; # console.log(applicationName); # }); ### exports.getApplicationName = (uuid, callback) -> exports.get(uuid).get('application_name').nodeify(callback) ###* # @summary Check if a device exists # @name has # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - has device # @returns {Promise} # # @example # resin.models.device.has('PI:KEY:<KEY>END_PI').then(function(hasDevice) { # console.log(hasDevice); # }); # # @example # resin.models.device.has('PI:KEY:<KEY>END_PI', function(error, hasDevice) { # if (error) throw error; # console.log(hasDevice); # }); ### exports.has = (uuid, callback) -> exports.get(uuid).return(true) .catch errors.ResinDeviceNotFound, -> return false .nodeify(callback) ###* # @summary Check if a device is online # @name isOnline # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - is device online # @returns {Promise} # # @example # resin.models.device.isOnline('7PI:KEY:<KEY>END_PI').then(function(isOnline) { # console.log('Is device online?', isOnline); # }); # # @example # resin.models.device.isOnline('PI:KEY:<KEY>END_PI', function(error, isOnline) { # if (error) throw error; # console.log('Is device online?', isOnline); # }); ### exports.isOnline = (uuid, callback) -> exports.get(uuid).get('is_online').nodeify(callback) ###* # @summary Get the local IP addresses of a device # @name getLocalIPAddresses # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String[]} - local ip addresses # @reject {Error} Will reject if the device is offline # @returns {Promise} # # @example # resin.models.device.getLocalIPAddresses('PI:KEY:<KEY>END_PI').then(function(localIPAddresses) { # localIPAddresses.forEach(function(localIP) { # console.log(localIP); # }); # }); # # @example # resin.models.device.getLocalIPAddresses('PI:KEY:<KEY>END_PI', function(error, localIPAddresses) { # if (error) throw error; # # localIPAddresses.forEach(function(localIP) { # console.log(localIP); # }); # }); ### exports.getLocalIPAddresses = (uuid, callback) -> exports.get(uuid).then (device) -> if not device.is_online throw new Error("The device is offline: #{uuid}") ips = device.ip_address.split(' ') return _.without(ips, device.vpn_address) .nodeify(callback) ###* # @summary Remove device # @name remove # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.remove('7PI:KEY:<KEY>END_PI'); # # @example # resin.models.device.remove('7PI:KEY:<KEY>END_PI', function(error) { # if (error) throw error; # }); ### exports.remove = (uuid, callback) -> exports.get(uuid).then -> return pine.delete resource: 'device' options: filter: uuid: uuid .nodeify(callback) ###* # @summary Identify device # @name identify # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.identify('7cfPI:KEY:<KEY>END_PI'); # # @example # resin.models.device.identify('PI:KEY:<KEY>END_PI', function(error) { # if (error) throw error; # }); ### exports.identify = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return request.send method: 'POST' url: '/blink' body: uuid: uuid .return(undefined) .nodeify(callback) ###* # @summary Rename device # @name rename # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} newName - the device new name # # @returns {Promise} # # @example # resin.models.device.rename('PI:KEY:<KEY>END_PI', 'NewName'); # # @example # resin.models.device.rename('PI:KEY:<KEY>END_PI', 'NewName', function(error) { # if (error) throw error; # }); ### exports.rename = (uuid, newName, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: name: newName options: filter: uuid: uuid .nodeify(callback) ###* # @summary Note a device # @name note # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} note - the note # # @returns {Promise} # # @example # resin.models.device.note('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'My useful note'); # # @example # resin.models.device.note('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7b465c9', 'My useful note', function(error) { # if (error) throw error; # }); ### exports.note = (uuid, note, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: note: note options: filter: uuid: uuid .nodeify(callback) ###* # @summary Move a device to another application # @name move # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @param {String} application - application name # # @returns {Promise} # # @example # resin.models.device.move('7cf02a62a3a84440b1bb5579a3PI:KEY:<KEY>END_PI', 'MyApp'); # # @example # resin.models.device.move('7PI:KEY:<KEY>END_PI', 'MyApp', function(error) { # if (error) throw error; # }); ### exports.move = (uuid, application, callback) -> Promise.props device: exports.get(uuid) application: applicationModel.get(application) .then (results) -> if results.device.device_type isnt results.application.device_type throw new Error("Incompatible application: #{application}") return pine.patch resource: 'device' body: application: results.application.id options: filter: uuid: uuid .nodeify(callback) ###* # @summary Restart device # @name restart # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.restart('7PI:KEY:<KEY>END_PI'); # # @example # resin.models.device.restart('7PI:KEY:<KEY>END_PI', function(error) { # if (error) throw error; # }); ### exports.restart = (uuid, callback) -> exports.get(uuid).then (device) -> return request.send method: 'POST' url: "/device/#{device.id}/restart" .get('body') .nodeify(callback) ###* # @summary Get display name for a device # @name getDisplayName # @public # @function # @memberof resin.models.device # # @see {@link module:resin.models.device.getSupportedDeviceTypes} for a list of supported devices # # @param {String} deviceTypeSlug - device type slug # @fulfil {String} - device display name # @returns {Promise} # # @example # resin.models.device.getDisplayName('raspberry-pi').then(function(deviceTypeName) { # console.log(deviceTypeName); # // Raspberry Pi # }); # # @example # resin.models.device.getDisplayName('raspberry-pi', function(error, deviceTypeName) { # if (error) throw error; # console.log(deviceTypeName); # // Raspberry Pi # }); ### exports.getDisplayName = (deviceTypeSlug, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> deviceTypeFound = _.findWhere(deviceTypes, slug: deviceTypeSlug) return deviceTypeFound?.name .nodeify(callback) ###* # @summary Get device slug # @name getDeviceSlug # @public # @function # @memberof resin.models.device # # @see {@link module:resin.models.device.getSupportedDeviceTypes} for a list of supported devices # # @param {String} deviceTypeName - device type name # @fulfil {String} - device slug name # @returns {Promise} # # @example # resin.models.device.getDeviceSlug('Raspberry Pi').then(function(deviceTypeSlug) { # console.log(deviceTypeSlug); # // raspberry-pi # }); # # @example # resin.models.device.getDeviceSlug('Raspberry Pi', function(error, deviceTypeSlug) { # if (error) throw error; # console.log(deviceTypeSlug); # // raspberry-pi # }); ### exports.getDeviceSlug = (deviceTypeName, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> foundByName = _.findWhere(deviceTypes, name: deviceTypeName) foundBySlug = _.findWhere(deviceTypes, slug: deviceTypeName) deviceTypeFound = foundByName or foundBySlug return deviceTypeFound?.slug .nodeify(callback) ###* # @summary Get supported device types # @name getSupportedDeviceTypes # @public # @function # @memberof resin.models.device # # @fulfil {String[]} - supported device types # @returns {Promise} # # @example # resin.models.device.getSupportedDeviceTypes().then(function(supportedDeviceTypes) { # supportedDeviceTypes.forEach(function(supportedDeviceType) { # console.log('Resin supports:', supportedDeviceType); # }); # }); # # @example # resin.models.device.getSupportedDeviceTypes(function(error, supportedDeviceTypes) { # if (error) throw error; # # supportedDeviceTypes.forEach(function(supportedDeviceType) { # console.log('Resin supports:', supportedDeviceType); # }); # }); ### exports.getSupportedDeviceTypes = (callback) -> configModel.getDeviceTypes().then (deviceTypes) -> return _.pluck(deviceTypes, 'name') .nodeify(callback) ###* # @summary Get a device manifest by slug # @name getManifestBySlug # @public # @function # @memberof resin.models.device # # @param {String} slug - device slug # @fulfil {Object} - device manifest # @returns {Promise} # # @example # resin.models.device.getManifestBySlug('raspberry-pi').then(function(manifest) { # console.log(manifest); # }); # # @example # resin.models.device.getManifestBySlug('raspberry-pi', function(error, manifest) { # if (error) throw error; # console.log(manifest); # }); ### exports.getManifestBySlug = (slug, callback) -> configModel.getDeviceTypes().then (deviceTypes) -> deviceManifest = _.find(deviceTypes, { slug }) if not deviceManifest? throw new Error("Unsupported device: #{slug}") return deviceManifest .nodeify(callback) ###* # @summary Get a device manifest by application name # @name getManifestByApplication # @public # @function # @memberof resin.models.device # # @param {String} applicationName - application name # @fulfil {Object} - device manifest # @returns {Promise} # # @example # resin.models.device.getManifestByApplication('MyApp').then(function(manifest) { # console.log(manifest); # }); # # @example # resin.models.device.getManifestByApplication('MyApp', function(error, manifest) { # if (error) throw error; # console.log(manifest); # }); ### exports.getManifestByApplication = (applicationName, callback) -> applicationModel.get(applicationName).get('device_type').then (deviceType) -> return exports.getManifestBySlug(deviceType) .nodeify(callback) ###* # @summary Generate a random device UUID # @name generateUUID # @function # @public # @memberof resin.models.device # # @fulfil {String} - a generated UUID # @returns {Promise} # # @example # resin.models.device.generateUUID().then(function(uuid) { # console.log(uuid); # }); # # @example # resin.models.device.generateUUID(function(error, uuid) { # if (error) throw error; # console.log(uuid); # }); ### exports.generateUUID = registerDevice.generateUUID ###* # @summary Register a new device with a Resin.io application # @name register # @public # @function # @memberof resin.models.device # # @param {String} applicationName - application name # @param {String} uuid - device uuid # # @fulfil {Object} - device # @returns {Promise} # # @example # resin.models.device.generateUUID().then(function(uuid) { # resin.models.device.register('MyApp', uuid).then(function(device) { # console.log(device); # }); # }); # # @example # resin.models.device.generateUUID(function(error, uuid) { # if (error) throw error; # # resin.models.device.register('MyApp', uuid, function(error, device) { # if (error) throw error; # # console.log(device); # }); # }); ### exports.register = (applicationName, uuid, callback) -> Promise.props userId: auth.getUserId() apiKey: applicationModel.getApiKey(applicationName) application: applicationModel.get(applicationName) .then (results) -> return registerDevice.register pine, userId: results.userId applicationId: results.application.id deviceType: results.application.device_type uuid: uuid apiKey: results.apiKey .nodeify(callback) ###* # @summary Check if a device is web accessible with device utls # @name hasDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {Boolean} - has device url # @returns {Promise} # # @example # resin.models.device.hasDeviceUrl('7cf02a62a3a84440b1bb5579a3d57469148943278630b17e7fc6c4f7bPI:KEY:<KEY>END_PI'); # # @example # resin.models.device.hasDeviceUrl('7cfPI:KEY:<KEY>END_PI', function(error) { # if (error) throw error; # }); ### exports.hasDeviceUrl = (uuid, callback) -> exports.get(uuid).get('is_web_accessible').nodeify(callback) ###* # @summary Get a device url # @name getDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @fulfil {String} - device url # @returns {Promise} # # @example # resin.models.device.getDeviceUrl('7cfPI:KEY:<KEY>END_PI').then(function(url) { # console.log(url); # }); # # @example # resin.models.device.getDeviceUrl('7cf02a6PI:KEY:<KEY>END_PIa3a8PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIbbPI:KEY:<KEY>END_PI3dPI:KEY:<KEY>END_PI', function(error, url) { # if (error) throw error; # console.log(url); # }); ### exports.getDeviceUrl = (uuid, callback) -> exports.hasDeviceUrl(uuid).then (hasDeviceUrl) -> if not hasDeviceUrl throw new Error("Device is not web accessible: #{uuid}") return configModel.getAll().get('deviceUrlsBase') .then (deviceUrlsBase) -> return "https://#{uuid}.#{deviceUrlsBase}" .nodeify(callback) ###* # @summary Enable device url for a device # @name enableDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.enableDeviceUrl('PI:KEY:<KEY>END_PI'); # # @example # resin.models.device.enableDeviceUrl('PI:KEY:<KEY>END_PI', function(error) { # if (error) throw error; # }); ### exports.enableDeviceUrl = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: is_web_accessible: true options: filter: uuid: uuid .nodeify(callback) ###* # @summary Disable device url for a device # @name disableDeviceUrl # @public # @function # @memberof resin.models.device # # @param {String} uuid - device uuid # @returns {Promise} # # @example # resin.models.device.disableDeviceUrl('PI:KEY:<KEY>END_PI'); # # @example # resin.models.device.disableDeviceUrl('7PI:KEY:<KEY>END_PI', function(error) { # if (error) throw error; # }); ### exports.disableDeviceUrl = (uuid, callback) -> exports.has(uuid).then (hasDevice) -> if not hasDevice throw new errors.ResinDeviceNotFound(uuid) return pine.patch resource: 'device' body: is_web_accessible: false options: filter: uuid: uuid .nodeify(callback)
[ { "context": "#### Copyright Paules\n#### Collbot\n\n#### ToDos\n\n# - beim start checken ", "end": 21, "score": 0.9997296929359436, "start": 15, "tag": "NAME", "value": "Paules" } ]
bot_collatzesar_margin.coffee
drcollatz/crypto
1
#### Copyright Paules #### Collbot #### ToDos # - beim start checken ob bereits eine Position offen ist und evtl. invested=true setzen # - Programmablauf / logging etc neu sortieren # - Fees berechnen (0.2 % von komplettem Kauf- oder Verkaufswert) #### START mt = require 'margin_trading' # import margin trading module talib = require 'talib' # import technical indicators library (https://cryptotrader.org/talib) ds = require 'datasources' ds.add 'bitfinex', 'btc_usd', '30m', 500 class functions @OpenPositionPL: (currentPrice, marginPosition) -> pl = ((currentPrice - marginPosition.price)/marginPosition.price) * 100 if (marginPosition.amount < 0) return -pl else return pl @OpenPositionCurrentBalance: (currentPrice, startingBalance, marginPosition) -> return (startingBalance + marginPosition.amount * (currentPrice - marginPosition.price)) @sar: (high, low, lag, accel, accelmax) -> results = talib.SAR high: high low: low startIdx: 0 endIdx: high.length - lag optInAcceleration: accel optInMaximum: accelmax _.last(results) @adx: (high, low, close, lag, period) -> results = talib.ADX high: high low: low close: close startIdx: 0 endIdx: high.length - lag optInTimePeriod: period _.last(results) @macd: (data, lag, FastPeriod,SlowPeriod,SignalPeriod) -> results = talib.MACD inReal: data startIdx: 0 endIdx: data.length - lag optInFastPeriod: FastPeriod optInSlowPeriod: SlowPeriod optInSignalPeriod: SignalPeriod result = macd: _.last(results.outMACD) signal: _.last(results.outMACDSignal) histogram: _.last(results.outMACDHist) result #### Init init: -> context.lag = 1 context.period = 20 context.close = 1 context.FastPeriod = 12 context.SlowPeriod = 26 context.SignalPeriod= 9 context.sarAccel = 0.02 context.sarAccelmax = 0.02 # context.adxLimit = 25 # context.histoLimit = 10 context.macdLimit = 30 context.marginFactor = 0.9 context.trailingStopPercent = 0.8 context.takeProfitPercent = 0.8 context.invested = false context.locked = "unlocked" context.positionStatus = "start" context.priceRef = 0 setPlotOptions performance: color: 'blue' secondary: true size: 5 sarLong: color: 'green' size: 3 sarShort: color: 'red' size: 3 SL: color: 'black' size: 5 TP: color: 'Chartreuse' size: 5 macd: color: 'DarkOrange' secondary: true size: 2 macd_limit: color: 'red' secondary: true size: 4 #### Tick execution handle: -> btc_30m = ds.get 'bitfinex', 'btc_usd', '30m' instrument = data.instruments[0] instrument_30m = data.instruments[1] storage.coin ?= instrument.pair.substring(0, 3).toUpperCase() #coin name currentPrice = instrument.price #current price storage.startPrice ?= instrument.price #initial price marginInfo = mt.getMarginInfo instrument currentBalance = marginInfo.margin_balance #current margin balance tradeableBalance = marginInfo.tradable_balance #current tradeable margin balance storage.startBalance ?= marginInfo.margin_balance #initial margin balance lastTotalProfitPercent = (currentBalance / storage.startBalance - 1) * 100 #Profit vor aktuellem Trade # sar = functions.sar(instrument.high, instrument.low, 1,context.sarAccel, context.sarAccelmax) sar_30m = functions.sar(instrument_30m.high, instrument_30m.low, 1,context.sarAccel, context.sarAccelmax) macd = functions.macd(instrument.close,context.lag,context.FastPeriod,context.SlowPeriod,context.SignalPeriod) adx = functions.adx(instrument.high, instrument.low, instrument.close,context.lag, context.period) if sar_30m > currentPrice info "BEARISH" if context.locked == "long" context.locked = "unlocked" plotMark sarShort: sar_30m else if context.locked == "short" context.locked = "unlocked" info "BULLISH" plotMark sarLong: sar_30m if macd.macd > context.macdLimit || macd.macd < -context.macdLimit plotMark macd_limit: macd.macd else plotMark macd: macd.macd ##### Logging info "STATUS__________: #{context.positionStatus} / INVESTED?: #{context.invested} / LOCKED?: #{context.locked}" debug "CURRENT PRICE___: #{currentPrice.toFixed(2)} USD" debug "INDICATORS______: MACD: #{macd.macd.toFixed(2)} / HISTO: #{macd.histogram.toFixed(2)} / ADX: #{adx.toFixed(2)} / SAR: #{sar_30m.toFixed(2)}" debug "SETTINGS________: TS: #{context.trailingStopPercent}% / TP: #{context.takeProfitPercent}% / MACD LIMIT: #{context.macdLimit}" debug "CURRENT BALANCE_: #{currentBalance.toFixed(2)} USD (START: #{storage.startBalance.toFixed(2)} USD)" info "PROFIT__________: BOT: #{lastTotalProfitPercent.toFixed(2)}% / B&H: #{((currentPrice / storage.startPrice - 1) * 100).toFixed(2)}%" ##### Postition currentPosition = mt.getPosition instrument if currentPosition context.invested = true curPosAmount = currentPosition.amount curPosPrice = currentPosition.price curPosBalanceAtStart = curPosAmount * curPosPrice curPosBalance = curPosAmount * currentPrice curPosProfit = curPosBalance - curPosBalanceAtStart curPosProfitPercent = @functions.OpenPositionPL(instrument.price, currentPosition) curBalanceTotal = currentBalance + curPosProfit - storage.startBalance curProfitPercentTotal = ((currentBalance + curPosProfit) / storage.startBalance - 1) * 100 if !context.stopOrder warn "ACHTUNG kein STOP LOSS AKTIV" if context.positionStatus == "long" context.stopOrder = mt.addOrder instrument: instrument side: 'sell' type: 'stop' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 - (context.trailingStopPercent / 100)) plotMark SL: currentPosition.price * (1 - (context.trailingStopPercent / 100)) if context.positionStatus == "short" context.stopOrder = mt.addOrder instrument: instrument side: 'buy' type: 'stop' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 + (context.trailingStopPercent / 100)) plotMark SL: currentPosition.price * (1 + (context.trailingStopPercent / 100)) if !context.takeProfitOrder warn "ACHTUNG kein TAKE PROFIT AKTIV" if context.positionStatus == "long" && (currentPosition.price * (1 + (context.takeProfitPercent / 100))) > currentPrice context.takeProfitOrder = mt.addOrder instrument: instrument side: 'sell' type: 'limit' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 + (context.takeProfitPercent / 100)) plotMark TP: currentPosition.price * (1 + (context.takeProfitPercent / 100)) if context.positionStatus == "short" && currentPosition.price * (1 - (context.takeProfitPercent / 100)) < currentPrice context.takeProfitOrder = mt.addOrder instrument: instrument side: 'buy' type: 'limit' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 - (context.takeProfitPercent / 100)) plotMark TP: currentPosition.price * (1 - (context.takeProfitPercent / 100)) plot performance: curProfitPercentTotal debug "--------------------------------------------------------" if curPosAmount > 0 info "LONG POSITION___________: #{curPosAmount} #{storage.coin} @ #{currentPosition.price.toFixed(2)} USD" else warn "SHORT POSITION__________: #{curPosAmount} #{storage.coin} @ #{currentPosition.price.toFixed(2)} USD" debug "CURRENT POS BALANCE____: #{curPosBalance.toFixed(2)} USD" debug "START POS BALANCE______: #{curPosBalanceAtStart.toFixed(2)} USD" debug "PROFIT POSITION________: #{curPosProfit.toFixed(2)} USD (#{curPosProfitPercent.toFixed(2)}%)" debug "PROFIT TOTAL___________: #{curBalanceTotal.toFixed(2)} USD (#{curProfitPercentTotal.toFixed(2)}%)" debug "CURRENT MARGIN BALANCE_: #{@functions.OpenPositionCurrentBalance(instrument.price, storage.startBalance, currentPosition).toFixed(2)}" else info "KEINE POSITION" if context.stopOrder debug "STOP ORDER______: ##{context.stopOrder.id}" if context.stopOrder.filled context.positionStatus = "start" context.invested = false debug "STOP ORDER______: ##{context.stopOrder.id} (FILLED)" if context.takeProfitOrder mt.cancelOrder(context.takeProfitOrder) context.takeProfitOrder = null context.stopOrder = null else debug "STOP ORDER______: NOT ACTIVE" if context.takeProfitOrder debug "PROF ORDER______: ##{context.takeProfitOrder.id}" if context.takeProfitOrder.filled context.positionStatus = "start" context.invested = false debug "PROF ORDER______: ##{context.takeProfitOrder.id} (FILLED)" if context.stopOrder mt.cancelOrder(context.stopOrder) context.stopOrder = null context.takeProfitOrder = null else debug "PROF ORDER______: NOT ACTIVE" activeOrders = [] activeOrders = mt.getActiveOrders() if (activeOrders and activeOrders.length) for activeOrder in activeOrders mt.cancelOrder(activeOrder) warn "Restliche Order gelöscht: #{activeOrder.id}" ##### state machine switch context.positionStatus when "start" if (sar_30m < instrument.price) && context.locked == "unlocked" && macd.macd > context.macdLimit #long context.positionStatus = "long" break if (sar_30m > instrument.price) && context.locked == "unlocked" && macd.macd < -context.macdLimit #short context.positionStatus = "short" break when "long" if instrument.price >= context.priceRef && currentPosition mt.cancelOrder(context.stopOrder) context.stopOrder = mt.addOrder instrument: instrument side: 'sell' type: 'stop' amount: curPosAmount price: currentPrice * (1 - context.trailingStopPercent / 100) warn "STOP ORDER UPDATE______: #{currentPrice * (1 - context.trailingStopPercent / 100)}" plotMark SL: currentPrice * (1 - context.trailingStopPercent / 100) if currentPrice > context.priceRef context.priceRef = currentPrice if (sar_30m > instrument.price) && context.invested == false #short context.positionStatus = "start" break when "short" if instrument.price <= context.priceRef && currentPosition mt.cancelOrder(context.stopOrder) context.stopOrder = mt.addOrder instrument: instrument side: 'buy' type: 'stop' amount: Math.abs(curPosAmount) price: currentPrice * (1 + context.trailingStopPercent / 100) warn "STOP ORDER UPDATE______: #{currentPrice * (1 + context.trailingStopPercent / 100)}" plotMark SL: currentPrice * (1 + context.trailingStopPercent / 100) if currentPrice < context.priceRef context.priceRef = currentPrice if (sar_30m < instrument.price) && context.invested == false #long context.positionStatus = "start" break #### Trading ######## LONG investableCash = (marginInfo.tradable_balance / currentPrice) * context.marginFactor if context.positionStatus == "long" unless context.invested # open long position if mt.buy instrument, 'market', investableCash, instrument.price info "LONG Position opened!" context.invested = true context.locked = "long" context.priceRef = currentPrice ######## SHORT if context.positionStatus == "short" unless context.invested # open short position if mt.sell instrument, 'market', investableCash, instrument.price info "SHORT Position opened!" context.invested = true context.locked = "short" context.priceRef = currentPrice debug "######################################################## " onRestart: -> warn "RESTART DETECTED!!!" #### ENDE onStop: -> info "*********************** BOT ENDE ***********************" instrument = @data.instruments[0] if (currentPosition = mt.getPosition instrument) && context.live == false warn "CLOSING POSITION" mt.closePosition instrument marginInfo = mt.getMarginInfo instrument currentBalance = marginInfo.margin_balance #current margin balance debug "START BALANCE___: #{storage.startBalance.toFixed(2)} USD" debug "END BALANCE_____: #{currentBalance.toFixed(2)} USD" botProfit = ((currentBalance / storage.startBalance - 1)*100) buhProfit = ((instrument.price / storage.startPrice - 1)*100) if botProfit >= 0 info "BOT PROFIT SUM__: #{botProfit.toFixed(2)}%" else warn "BOT PROFIT SUM__: #{botProfit.toFixed(2)}%" if buhProfit >= 0 info "B&H PROFIT SUM__: #{buhProfit.toFixed(2)}%" else warn "B&H PROFIT SUM__: #{buhProfit.toFixed(2)}%"
205844
#### Copyright <NAME> #### Collbot #### ToDos # - beim start checken ob bereits eine Position offen ist und evtl. invested=true setzen # - Programmablauf / logging etc neu sortieren # - Fees berechnen (0.2 % von komplettem Kauf- oder Verkaufswert) #### START mt = require 'margin_trading' # import margin trading module talib = require 'talib' # import technical indicators library (https://cryptotrader.org/talib) ds = require 'datasources' ds.add 'bitfinex', 'btc_usd', '30m', 500 class functions @OpenPositionPL: (currentPrice, marginPosition) -> pl = ((currentPrice - marginPosition.price)/marginPosition.price) * 100 if (marginPosition.amount < 0) return -pl else return pl @OpenPositionCurrentBalance: (currentPrice, startingBalance, marginPosition) -> return (startingBalance + marginPosition.amount * (currentPrice - marginPosition.price)) @sar: (high, low, lag, accel, accelmax) -> results = talib.SAR high: high low: low startIdx: 0 endIdx: high.length - lag optInAcceleration: accel optInMaximum: accelmax _.last(results) @adx: (high, low, close, lag, period) -> results = talib.ADX high: high low: low close: close startIdx: 0 endIdx: high.length - lag optInTimePeriod: period _.last(results) @macd: (data, lag, FastPeriod,SlowPeriod,SignalPeriod) -> results = talib.MACD inReal: data startIdx: 0 endIdx: data.length - lag optInFastPeriod: FastPeriod optInSlowPeriod: SlowPeriod optInSignalPeriod: SignalPeriod result = macd: _.last(results.outMACD) signal: _.last(results.outMACDSignal) histogram: _.last(results.outMACDHist) result #### Init init: -> context.lag = 1 context.period = 20 context.close = 1 context.FastPeriod = 12 context.SlowPeriod = 26 context.SignalPeriod= 9 context.sarAccel = 0.02 context.sarAccelmax = 0.02 # context.adxLimit = 25 # context.histoLimit = 10 context.macdLimit = 30 context.marginFactor = 0.9 context.trailingStopPercent = 0.8 context.takeProfitPercent = 0.8 context.invested = false context.locked = "unlocked" context.positionStatus = "start" context.priceRef = 0 setPlotOptions performance: color: 'blue' secondary: true size: 5 sarLong: color: 'green' size: 3 sarShort: color: 'red' size: 3 SL: color: 'black' size: 5 TP: color: 'Chartreuse' size: 5 macd: color: 'DarkOrange' secondary: true size: 2 macd_limit: color: 'red' secondary: true size: 4 #### Tick execution handle: -> btc_30m = ds.get 'bitfinex', 'btc_usd', '30m' instrument = data.instruments[0] instrument_30m = data.instruments[1] storage.coin ?= instrument.pair.substring(0, 3).toUpperCase() #coin name currentPrice = instrument.price #current price storage.startPrice ?= instrument.price #initial price marginInfo = mt.getMarginInfo instrument currentBalance = marginInfo.margin_balance #current margin balance tradeableBalance = marginInfo.tradable_balance #current tradeable margin balance storage.startBalance ?= marginInfo.margin_balance #initial margin balance lastTotalProfitPercent = (currentBalance / storage.startBalance - 1) * 100 #Profit vor aktuellem Trade # sar = functions.sar(instrument.high, instrument.low, 1,context.sarAccel, context.sarAccelmax) sar_30m = functions.sar(instrument_30m.high, instrument_30m.low, 1,context.sarAccel, context.sarAccelmax) macd = functions.macd(instrument.close,context.lag,context.FastPeriod,context.SlowPeriod,context.SignalPeriod) adx = functions.adx(instrument.high, instrument.low, instrument.close,context.lag, context.period) if sar_30m > currentPrice info "BEARISH" if context.locked == "long" context.locked = "unlocked" plotMark sarShort: sar_30m else if context.locked == "short" context.locked = "unlocked" info "BULLISH" plotMark sarLong: sar_30m if macd.macd > context.macdLimit || macd.macd < -context.macdLimit plotMark macd_limit: macd.macd else plotMark macd: macd.macd ##### Logging info "STATUS__________: #{context.positionStatus} / INVESTED?: #{context.invested} / LOCKED?: #{context.locked}" debug "CURRENT PRICE___: #{currentPrice.toFixed(2)} USD" debug "INDICATORS______: MACD: #{macd.macd.toFixed(2)} / HISTO: #{macd.histogram.toFixed(2)} / ADX: #{adx.toFixed(2)} / SAR: #{sar_30m.toFixed(2)}" debug "SETTINGS________: TS: #{context.trailingStopPercent}% / TP: #{context.takeProfitPercent}% / MACD LIMIT: #{context.macdLimit}" debug "CURRENT BALANCE_: #{currentBalance.toFixed(2)} USD (START: #{storage.startBalance.toFixed(2)} USD)" info "PROFIT__________: BOT: #{lastTotalProfitPercent.toFixed(2)}% / B&H: #{((currentPrice / storage.startPrice - 1) * 100).toFixed(2)}%" ##### Postition currentPosition = mt.getPosition instrument if currentPosition context.invested = true curPosAmount = currentPosition.amount curPosPrice = currentPosition.price curPosBalanceAtStart = curPosAmount * curPosPrice curPosBalance = curPosAmount * currentPrice curPosProfit = curPosBalance - curPosBalanceAtStart curPosProfitPercent = @functions.OpenPositionPL(instrument.price, currentPosition) curBalanceTotal = currentBalance + curPosProfit - storage.startBalance curProfitPercentTotal = ((currentBalance + curPosProfit) / storage.startBalance - 1) * 100 if !context.stopOrder warn "ACHTUNG kein STOP LOSS AKTIV" if context.positionStatus == "long" context.stopOrder = mt.addOrder instrument: instrument side: 'sell' type: 'stop' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 - (context.trailingStopPercent / 100)) plotMark SL: currentPosition.price * (1 - (context.trailingStopPercent / 100)) if context.positionStatus == "short" context.stopOrder = mt.addOrder instrument: instrument side: 'buy' type: 'stop' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 + (context.trailingStopPercent / 100)) plotMark SL: currentPosition.price * (1 + (context.trailingStopPercent / 100)) if !context.takeProfitOrder warn "ACHTUNG kein TAKE PROFIT AKTIV" if context.positionStatus == "long" && (currentPosition.price * (1 + (context.takeProfitPercent / 100))) > currentPrice context.takeProfitOrder = mt.addOrder instrument: instrument side: 'sell' type: 'limit' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 + (context.takeProfitPercent / 100)) plotMark TP: currentPosition.price * (1 + (context.takeProfitPercent / 100)) if context.positionStatus == "short" && currentPosition.price * (1 - (context.takeProfitPercent / 100)) < currentPrice context.takeProfitOrder = mt.addOrder instrument: instrument side: 'buy' type: 'limit' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 - (context.takeProfitPercent / 100)) plotMark TP: currentPosition.price * (1 - (context.takeProfitPercent / 100)) plot performance: curProfitPercentTotal debug "--------------------------------------------------------" if curPosAmount > 0 info "LONG POSITION___________: #{curPosAmount} #{storage.coin} @ #{currentPosition.price.toFixed(2)} USD" else warn "SHORT POSITION__________: #{curPosAmount} #{storage.coin} @ #{currentPosition.price.toFixed(2)} USD" debug "CURRENT POS BALANCE____: #{curPosBalance.toFixed(2)} USD" debug "START POS BALANCE______: #{curPosBalanceAtStart.toFixed(2)} USD" debug "PROFIT POSITION________: #{curPosProfit.toFixed(2)} USD (#{curPosProfitPercent.toFixed(2)}%)" debug "PROFIT TOTAL___________: #{curBalanceTotal.toFixed(2)} USD (#{curProfitPercentTotal.toFixed(2)}%)" debug "CURRENT MARGIN BALANCE_: #{@functions.OpenPositionCurrentBalance(instrument.price, storage.startBalance, currentPosition).toFixed(2)}" else info "KEINE POSITION" if context.stopOrder debug "STOP ORDER______: ##{context.stopOrder.id}" if context.stopOrder.filled context.positionStatus = "start" context.invested = false debug "STOP ORDER______: ##{context.stopOrder.id} (FILLED)" if context.takeProfitOrder mt.cancelOrder(context.takeProfitOrder) context.takeProfitOrder = null context.stopOrder = null else debug "STOP ORDER______: NOT ACTIVE" if context.takeProfitOrder debug "PROF ORDER______: ##{context.takeProfitOrder.id}" if context.takeProfitOrder.filled context.positionStatus = "start" context.invested = false debug "PROF ORDER______: ##{context.takeProfitOrder.id} (FILLED)" if context.stopOrder mt.cancelOrder(context.stopOrder) context.stopOrder = null context.takeProfitOrder = null else debug "PROF ORDER______: NOT ACTIVE" activeOrders = [] activeOrders = mt.getActiveOrders() if (activeOrders and activeOrders.length) for activeOrder in activeOrders mt.cancelOrder(activeOrder) warn "Restliche Order gelöscht: #{activeOrder.id}" ##### state machine switch context.positionStatus when "start" if (sar_30m < instrument.price) && context.locked == "unlocked" && macd.macd > context.macdLimit #long context.positionStatus = "long" break if (sar_30m > instrument.price) && context.locked == "unlocked" && macd.macd < -context.macdLimit #short context.positionStatus = "short" break when "long" if instrument.price >= context.priceRef && currentPosition mt.cancelOrder(context.stopOrder) context.stopOrder = mt.addOrder instrument: instrument side: 'sell' type: 'stop' amount: curPosAmount price: currentPrice * (1 - context.trailingStopPercent / 100) warn "STOP ORDER UPDATE______: #{currentPrice * (1 - context.trailingStopPercent / 100)}" plotMark SL: currentPrice * (1 - context.trailingStopPercent / 100) if currentPrice > context.priceRef context.priceRef = currentPrice if (sar_30m > instrument.price) && context.invested == false #short context.positionStatus = "start" break when "short" if instrument.price <= context.priceRef && currentPosition mt.cancelOrder(context.stopOrder) context.stopOrder = mt.addOrder instrument: instrument side: 'buy' type: 'stop' amount: Math.abs(curPosAmount) price: currentPrice * (1 + context.trailingStopPercent / 100) warn "STOP ORDER UPDATE______: #{currentPrice * (1 + context.trailingStopPercent / 100)}" plotMark SL: currentPrice * (1 + context.trailingStopPercent / 100) if currentPrice < context.priceRef context.priceRef = currentPrice if (sar_30m < instrument.price) && context.invested == false #long context.positionStatus = "start" break #### Trading ######## LONG investableCash = (marginInfo.tradable_balance / currentPrice) * context.marginFactor if context.positionStatus == "long" unless context.invested # open long position if mt.buy instrument, 'market', investableCash, instrument.price info "LONG Position opened!" context.invested = true context.locked = "long" context.priceRef = currentPrice ######## SHORT if context.positionStatus == "short" unless context.invested # open short position if mt.sell instrument, 'market', investableCash, instrument.price info "SHORT Position opened!" context.invested = true context.locked = "short" context.priceRef = currentPrice debug "######################################################## " onRestart: -> warn "RESTART DETECTED!!!" #### ENDE onStop: -> info "*********************** BOT ENDE ***********************" instrument = @data.instruments[0] if (currentPosition = mt.getPosition instrument) && context.live == false warn "CLOSING POSITION" mt.closePosition instrument marginInfo = mt.getMarginInfo instrument currentBalance = marginInfo.margin_balance #current margin balance debug "START BALANCE___: #{storage.startBalance.toFixed(2)} USD" debug "END BALANCE_____: #{currentBalance.toFixed(2)} USD" botProfit = ((currentBalance / storage.startBalance - 1)*100) buhProfit = ((instrument.price / storage.startPrice - 1)*100) if botProfit >= 0 info "BOT PROFIT SUM__: #{botProfit.toFixed(2)}%" else warn "BOT PROFIT SUM__: #{botProfit.toFixed(2)}%" if buhProfit >= 0 info "B&H PROFIT SUM__: #{buhProfit.toFixed(2)}%" else warn "B&H PROFIT SUM__: #{buhProfit.toFixed(2)}%"
true
#### Copyright PI:NAME:<NAME>END_PI #### Collbot #### ToDos # - beim start checken ob bereits eine Position offen ist und evtl. invested=true setzen # - Programmablauf / logging etc neu sortieren # - Fees berechnen (0.2 % von komplettem Kauf- oder Verkaufswert) #### START mt = require 'margin_trading' # import margin trading module talib = require 'talib' # import technical indicators library (https://cryptotrader.org/talib) ds = require 'datasources' ds.add 'bitfinex', 'btc_usd', '30m', 500 class functions @OpenPositionPL: (currentPrice, marginPosition) -> pl = ((currentPrice - marginPosition.price)/marginPosition.price) * 100 if (marginPosition.amount < 0) return -pl else return pl @OpenPositionCurrentBalance: (currentPrice, startingBalance, marginPosition) -> return (startingBalance + marginPosition.amount * (currentPrice - marginPosition.price)) @sar: (high, low, lag, accel, accelmax) -> results = talib.SAR high: high low: low startIdx: 0 endIdx: high.length - lag optInAcceleration: accel optInMaximum: accelmax _.last(results) @adx: (high, low, close, lag, period) -> results = talib.ADX high: high low: low close: close startIdx: 0 endIdx: high.length - lag optInTimePeriod: period _.last(results) @macd: (data, lag, FastPeriod,SlowPeriod,SignalPeriod) -> results = talib.MACD inReal: data startIdx: 0 endIdx: data.length - lag optInFastPeriod: FastPeriod optInSlowPeriod: SlowPeriod optInSignalPeriod: SignalPeriod result = macd: _.last(results.outMACD) signal: _.last(results.outMACDSignal) histogram: _.last(results.outMACDHist) result #### Init init: -> context.lag = 1 context.period = 20 context.close = 1 context.FastPeriod = 12 context.SlowPeriod = 26 context.SignalPeriod= 9 context.sarAccel = 0.02 context.sarAccelmax = 0.02 # context.adxLimit = 25 # context.histoLimit = 10 context.macdLimit = 30 context.marginFactor = 0.9 context.trailingStopPercent = 0.8 context.takeProfitPercent = 0.8 context.invested = false context.locked = "unlocked" context.positionStatus = "start" context.priceRef = 0 setPlotOptions performance: color: 'blue' secondary: true size: 5 sarLong: color: 'green' size: 3 sarShort: color: 'red' size: 3 SL: color: 'black' size: 5 TP: color: 'Chartreuse' size: 5 macd: color: 'DarkOrange' secondary: true size: 2 macd_limit: color: 'red' secondary: true size: 4 #### Tick execution handle: -> btc_30m = ds.get 'bitfinex', 'btc_usd', '30m' instrument = data.instruments[0] instrument_30m = data.instruments[1] storage.coin ?= instrument.pair.substring(0, 3).toUpperCase() #coin name currentPrice = instrument.price #current price storage.startPrice ?= instrument.price #initial price marginInfo = mt.getMarginInfo instrument currentBalance = marginInfo.margin_balance #current margin balance tradeableBalance = marginInfo.tradable_balance #current tradeable margin balance storage.startBalance ?= marginInfo.margin_balance #initial margin balance lastTotalProfitPercent = (currentBalance / storage.startBalance - 1) * 100 #Profit vor aktuellem Trade # sar = functions.sar(instrument.high, instrument.low, 1,context.sarAccel, context.sarAccelmax) sar_30m = functions.sar(instrument_30m.high, instrument_30m.low, 1,context.sarAccel, context.sarAccelmax) macd = functions.macd(instrument.close,context.lag,context.FastPeriod,context.SlowPeriod,context.SignalPeriod) adx = functions.adx(instrument.high, instrument.low, instrument.close,context.lag, context.period) if sar_30m > currentPrice info "BEARISH" if context.locked == "long" context.locked = "unlocked" plotMark sarShort: sar_30m else if context.locked == "short" context.locked = "unlocked" info "BULLISH" plotMark sarLong: sar_30m if macd.macd > context.macdLimit || macd.macd < -context.macdLimit plotMark macd_limit: macd.macd else plotMark macd: macd.macd ##### Logging info "STATUS__________: #{context.positionStatus} / INVESTED?: #{context.invested} / LOCKED?: #{context.locked}" debug "CURRENT PRICE___: #{currentPrice.toFixed(2)} USD" debug "INDICATORS______: MACD: #{macd.macd.toFixed(2)} / HISTO: #{macd.histogram.toFixed(2)} / ADX: #{adx.toFixed(2)} / SAR: #{sar_30m.toFixed(2)}" debug "SETTINGS________: TS: #{context.trailingStopPercent}% / TP: #{context.takeProfitPercent}% / MACD LIMIT: #{context.macdLimit}" debug "CURRENT BALANCE_: #{currentBalance.toFixed(2)} USD (START: #{storage.startBalance.toFixed(2)} USD)" info "PROFIT__________: BOT: #{lastTotalProfitPercent.toFixed(2)}% / B&H: #{((currentPrice / storage.startPrice - 1) * 100).toFixed(2)}%" ##### Postition currentPosition = mt.getPosition instrument if currentPosition context.invested = true curPosAmount = currentPosition.amount curPosPrice = currentPosition.price curPosBalanceAtStart = curPosAmount * curPosPrice curPosBalance = curPosAmount * currentPrice curPosProfit = curPosBalance - curPosBalanceAtStart curPosProfitPercent = @functions.OpenPositionPL(instrument.price, currentPosition) curBalanceTotal = currentBalance + curPosProfit - storage.startBalance curProfitPercentTotal = ((currentBalance + curPosProfit) / storage.startBalance - 1) * 100 if !context.stopOrder warn "ACHTUNG kein STOP LOSS AKTIV" if context.positionStatus == "long" context.stopOrder = mt.addOrder instrument: instrument side: 'sell' type: 'stop' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 - (context.trailingStopPercent / 100)) plotMark SL: currentPosition.price * (1 - (context.trailingStopPercent / 100)) if context.positionStatus == "short" context.stopOrder = mt.addOrder instrument: instrument side: 'buy' type: 'stop' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 + (context.trailingStopPercent / 100)) plotMark SL: currentPosition.price * (1 + (context.trailingStopPercent / 100)) if !context.takeProfitOrder warn "ACHTUNG kein TAKE PROFIT AKTIV" if context.positionStatus == "long" && (currentPosition.price * (1 + (context.takeProfitPercent / 100))) > currentPrice context.takeProfitOrder = mt.addOrder instrument: instrument side: 'sell' type: 'limit' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 + (context.takeProfitPercent / 100)) plotMark TP: currentPosition.price * (1 + (context.takeProfitPercent / 100)) if context.positionStatus == "short" && currentPosition.price * (1 - (context.takeProfitPercent / 100)) < currentPrice context.takeProfitOrder = mt.addOrder instrument: instrument side: 'buy' type: 'limit' amount: Math.abs(currentPosition.amount) price: currentPosition.price * (1 - (context.takeProfitPercent / 100)) plotMark TP: currentPosition.price * (1 - (context.takeProfitPercent / 100)) plot performance: curProfitPercentTotal debug "--------------------------------------------------------" if curPosAmount > 0 info "LONG POSITION___________: #{curPosAmount} #{storage.coin} @ #{currentPosition.price.toFixed(2)} USD" else warn "SHORT POSITION__________: #{curPosAmount} #{storage.coin} @ #{currentPosition.price.toFixed(2)} USD" debug "CURRENT POS BALANCE____: #{curPosBalance.toFixed(2)} USD" debug "START POS BALANCE______: #{curPosBalanceAtStart.toFixed(2)} USD" debug "PROFIT POSITION________: #{curPosProfit.toFixed(2)} USD (#{curPosProfitPercent.toFixed(2)}%)" debug "PROFIT TOTAL___________: #{curBalanceTotal.toFixed(2)} USD (#{curProfitPercentTotal.toFixed(2)}%)" debug "CURRENT MARGIN BALANCE_: #{@functions.OpenPositionCurrentBalance(instrument.price, storage.startBalance, currentPosition).toFixed(2)}" else info "KEINE POSITION" if context.stopOrder debug "STOP ORDER______: ##{context.stopOrder.id}" if context.stopOrder.filled context.positionStatus = "start" context.invested = false debug "STOP ORDER______: ##{context.stopOrder.id} (FILLED)" if context.takeProfitOrder mt.cancelOrder(context.takeProfitOrder) context.takeProfitOrder = null context.stopOrder = null else debug "STOP ORDER______: NOT ACTIVE" if context.takeProfitOrder debug "PROF ORDER______: ##{context.takeProfitOrder.id}" if context.takeProfitOrder.filled context.positionStatus = "start" context.invested = false debug "PROF ORDER______: ##{context.takeProfitOrder.id} (FILLED)" if context.stopOrder mt.cancelOrder(context.stopOrder) context.stopOrder = null context.takeProfitOrder = null else debug "PROF ORDER______: NOT ACTIVE" activeOrders = [] activeOrders = mt.getActiveOrders() if (activeOrders and activeOrders.length) for activeOrder in activeOrders mt.cancelOrder(activeOrder) warn "Restliche Order gelöscht: #{activeOrder.id}" ##### state machine switch context.positionStatus when "start" if (sar_30m < instrument.price) && context.locked == "unlocked" && macd.macd > context.macdLimit #long context.positionStatus = "long" break if (sar_30m > instrument.price) && context.locked == "unlocked" && macd.macd < -context.macdLimit #short context.positionStatus = "short" break when "long" if instrument.price >= context.priceRef && currentPosition mt.cancelOrder(context.stopOrder) context.stopOrder = mt.addOrder instrument: instrument side: 'sell' type: 'stop' amount: curPosAmount price: currentPrice * (1 - context.trailingStopPercent / 100) warn "STOP ORDER UPDATE______: #{currentPrice * (1 - context.trailingStopPercent / 100)}" plotMark SL: currentPrice * (1 - context.trailingStopPercent / 100) if currentPrice > context.priceRef context.priceRef = currentPrice if (sar_30m > instrument.price) && context.invested == false #short context.positionStatus = "start" break when "short" if instrument.price <= context.priceRef && currentPosition mt.cancelOrder(context.stopOrder) context.stopOrder = mt.addOrder instrument: instrument side: 'buy' type: 'stop' amount: Math.abs(curPosAmount) price: currentPrice * (1 + context.trailingStopPercent / 100) warn "STOP ORDER UPDATE______: #{currentPrice * (1 + context.trailingStopPercent / 100)}" plotMark SL: currentPrice * (1 + context.trailingStopPercent / 100) if currentPrice < context.priceRef context.priceRef = currentPrice if (sar_30m < instrument.price) && context.invested == false #long context.positionStatus = "start" break #### Trading ######## LONG investableCash = (marginInfo.tradable_balance / currentPrice) * context.marginFactor if context.positionStatus == "long" unless context.invested # open long position if mt.buy instrument, 'market', investableCash, instrument.price info "LONG Position opened!" context.invested = true context.locked = "long" context.priceRef = currentPrice ######## SHORT if context.positionStatus == "short" unless context.invested # open short position if mt.sell instrument, 'market', investableCash, instrument.price info "SHORT Position opened!" context.invested = true context.locked = "short" context.priceRef = currentPrice debug "######################################################## " onRestart: -> warn "RESTART DETECTED!!!" #### ENDE onStop: -> info "*********************** BOT ENDE ***********************" instrument = @data.instruments[0] if (currentPosition = mt.getPosition instrument) && context.live == false warn "CLOSING POSITION" mt.closePosition instrument marginInfo = mt.getMarginInfo instrument currentBalance = marginInfo.margin_balance #current margin balance debug "START BALANCE___: #{storage.startBalance.toFixed(2)} USD" debug "END BALANCE_____: #{currentBalance.toFixed(2)} USD" botProfit = ((currentBalance / storage.startBalance - 1)*100) buhProfit = ((instrument.price / storage.startPrice - 1)*100) if botProfit >= 0 info "BOT PROFIT SUM__: #{botProfit.toFixed(2)}%" else warn "BOT PROFIT SUM__: #{botProfit.toFixed(2)}%" if buhProfit >= 0 info "B&H PROFIT SUM__: #{buhProfit.toFixed(2)}%" else warn "B&H PROFIT SUM__: #{buhProfit.toFixed(2)}%"
[ { "context": "\n###\nBinaryReader\n\nModified by Isaiah Odhner\n@TODO: use jDataView + jBinary instead\n\nRefactore", "end": 44, "score": 0.9998953938484192, "start": 31, "tag": "NAME", "value": "Isaiah Odhner" }, { "context": "jDataView + jBinary instead\n\nRefactored by Vjeux <vjeu...
src/BinaryReader.coffee
sahwar/anypalette.js
1
### BinaryReader Modified by Isaiah Odhner @TODO: use jDataView + jBinary instead Refactored by Vjeux <vjeuxx@gmail.com> http://blog.vjeux.com/2010/javascript/javascript-binary-reader.html Original + Jonas Raoni Soares Silva @ http://jsfromhell.com/classes/binary-parser [rev. #1] ### module.exports = class BinaryReader constructor: (data)-> @_buffer = data @_pos = 0 # Public (custom) readByte: -> @_checkSize(8) ch = this._buffer.charCodeAt(@_pos) & 0xff @_pos += 1 ch & 0xff readUnicodeString: -> length = @readUInt16() # console.log {length} @_checkSize(length * 16) str = "" for i in [0..length] str += String.fromCharCode(@_buffer.substr(@_pos, 1) | (@_buffer.substr(@_pos+1, 1) << 8)) @_pos += 2 str # Public readInt8: -> @_decodeInt(8, true) readUInt8: -> @_decodeInt(8, false) readInt16: -> @_decodeInt(16, true) readUInt16: -> @_decodeInt(16, false) readInt32: -> @_decodeInt(32, true) readUInt32: -> @_decodeInt(32, false) readFloat: -> @_decodeFloat(23, 8) readDouble: -> @_decodeFloat(52, 11) readChar: -> @readString(1) readString: (length)-> @_checkSize(length * 8) result = @_buffer.substr(@_pos, length) @_pos += length result seek: (pos)-> @_pos = pos @_checkSize(0) getPosition: -> @_pos getSize: -> @_buffer.length # Private _decodeFloat: `function(precisionBits, exponentBits){ var length = precisionBits + exponentBits + 1; var size = length >> 3; this._checkSize(length); var bias = Math.pow(2, exponentBits - 1) - 1; var signal = this._readBits(precisionBits + exponentBits, 1, size); var exponent = this._readBits(precisionBits, exponentBits, size); var significand = 0; var divisor = 2; var curByte = 0; //length + (-precisionBits >> 3) - 1; do { var byteValue = this._readByte(++curByte, size); var startBit = precisionBits % 8 || 8; var mask = 1 << startBit; while (mask >>= 1) { if (byteValue & mask) { significand += 1 / divisor; } divisor *= 2; } } while (precisionBits -= startBit); this._pos += size; return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand : Math.pow(2, exponent - bias) * (1 + significand) : 0); }` _decodeInt: `function(bits, signed){ var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits); var result = signed && x >= max / 2 ? x - max : x; this._pos += bits / 8; return result; }` #shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) _shl: `function (a, b){ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return a; }` _readByte: `function (i, size) { return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff; }` _readBits: `function (start, length, size) { var offsetLeft = (start + length) % 8; var offsetRight = start % 8; var curByte = size - (start >> 3) - 1; var lastByte = size + (-(start + length) >> 3); var diff = curByte - lastByte; var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1); if (diff && offsetLeft) { sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight; } while (diff) { sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight); } return sum; }` _checkSize: (neededBits)-> if @_pos + Math.ceil(neededBits / 8) > @_buffer.length throw new Error "Index out of bound"
183956
### BinaryReader Modified by <NAME> @TODO: use jDataView + jBinary instead Refactored by Vjeux <<EMAIL>> http://blog.vjeux.com/2010/javascript/javascript-binary-reader.html Original + <NAME> @ http://jsfromhell.com/classes/binary-parser [rev. #1] ### module.exports = class BinaryReader constructor: (data)-> @_buffer = data @_pos = 0 # Public (custom) readByte: -> @_checkSize(8) ch = this._buffer.charCodeAt(@_pos) & 0xff @_pos += 1 ch & 0xff readUnicodeString: -> length = @readUInt16() # console.log {length} @_checkSize(length * 16) str = "" for i in [0..length] str += String.fromCharCode(@_buffer.substr(@_pos, 1) | (@_buffer.substr(@_pos+1, 1) << 8)) @_pos += 2 str # Public readInt8: -> @_decodeInt(8, true) readUInt8: -> @_decodeInt(8, false) readInt16: -> @_decodeInt(16, true) readUInt16: -> @_decodeInt(16, false) readInt32: -> @_decodeInt(32, true) readUInt32: -> @_decodeInt(32, false) readFloat: -> @_decodeFloat(23, 8) readDouble: -> @_decodeFloat(52, 11) readChar: -> @readString(1) readString: (length)-> @_checkSize(length * 8) result = @_buffer.substr(@_pos, length) @_pos += length result seek: (pos)-> @_pos = pos @_checkSize(0) getPosition: -> @_pos getSize: -> @_buffer.length # Private _decodeFloat: `function(precisionBits, exponentBits){ var length = precisionBits + exponentBits + 1; var size = length >> 3; this._checkSize(length); var bias = Math.pow(2, exponentBits - 1) - 1; var signal = this._readBits(precisionBits + exponentBits, 1, size); var exponent = this._readBits(precisionBits, exponentBits, size); var significand = 0; var divisor = 2; var curByte = 0; //length + (-precisionBits >> 3) - 1; do { var byteValue = this._readByte(++curByte, size); var startBit = precisionBits % 8 || 8; var mask = 1 << startBit; while (mask >>= 1) { if (byteValue & mask) { significand += 1 / divisor; } divisor *= 2; } } while (precisionBits -= startBit); this._pos += size; return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand : Math.pow(2, exponent - bias) * (1 + significand) : 0); }` _decodeInt: `function(bits, signed){ var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits); var result = signed && x >= max / 2 ? x - max : x; this._pos += bits / 8; return result; }` #shl fix: <NAME> ~1996 (compressed by <NAME>) _shl: `function (a, b){ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return a; }` _readByte: `function (i, size) { return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff; }` _readBits: `function (start, length, size) { var offsetLeft = (start + length) % 8; var offsetRight = start % 8; var curByte = size - (start >> 3) - 1; var lastByte = size + (-(start + length) >> 3); var diff = curByte - lastByte; var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1); if (diff && offsetLeft) { sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight; } while (diff) { sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight); } return sum; }` _checkSize: (neededBits)-> if @_pos + Math.ceil(neededBits / 8) > @_buffer.length throw new Error "Index out of bound"
true
### BinaryReader Modified by PI:NAME:<NAME>END_PI @TODO: use jDataView + jBinary instead Refactored by Vjeux <PI:EMAIL:<EMAIL>END_PI> http://blog.vjeux.com/2010/javascript/javascript-binary-reader.html Original + PI:NAME:<NAME>END_PI @ http://jsfromhell.com/classes/binary-parser [rev. #1] ### module.exports = class BinaryReader constructor: (data)-> @_buffer = data @_pos = 0 # Public (custom) readByte: -> @_checkSize(8) ch = this._buffer.charCodeAt(@_pos) & 0xff @_pos += 1 ch & 0xff readUnicodeString: -> length = @readUInt16() # console.log {length} @_checkSize(length * 16) str = "" for i in [0..length] str += String.fromCharCode(@_buffer.substr(@_pos, 1) | (@_buffer.substr(@_pos+1, 1) << 8)) @_pos += 2 str # Public readInt8: -> @_decodeInt(8, true) readUInt8: -> @_decodeInt(8, false) readInt16: -> @_decodeInt(16, true) readUInt16: -> @_decodeInt(16, false) readInt32: -> @_decodeInt(32, true) readUInt32: -> @_decodeInt(32, false) readFloat: -> @_decodeFloat(23, 8) readDouble: -> @_decodeFloat(52, 11) readChar: -> @readString(1) readString: (length)-> @_checkSize(length * 8) result = @_buffer.substr(@_pos, length) @_pos += length result seek: (pos)-> @_pos = pos @_checkSize(0) getPosition: -> @_pos getSize: -> @_buffer.length # Private _decodeFloat: `function(precisionBits, exponentBits){ var length = precisionBits + exponentBits + 1; var size = length >> 3; this._checkSize(length); var bias = Math.pow(2, exponentBits - 1) - 1; var signal = this._readBits(precisionBits + exponentBits, 1, size); var exponent = this._readBits(precisionBits, exponentBits, size); var significand = 0; var divisor = 2; var curByte = 0; //length + (-precisionBits >> 3) - 1; do { var byteValue = this._readByte(++curByte, size); var startBit = precisionBits % 8 || 8; var mask = 1 << startBit; while (mask >>= 1) { if (byteValue & mask) { significand += 1 / divisor; } divisor *= 2; } } while (precisionBits -= startBit); this._pos += size; return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand : Math.pow(2, exponent - bias) * (1 + significand) : 0); }` _decodeInt: `function(bits, signed){ var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits); var result = signed && x >= max / 2 ? x - max : x; this._pos += bits / 8; return result; }` #shl fix: PI:NAME:<NAME>END_PI ~1996 (compressed by PI:NAME:<NAME>END_PI) _shl: `function (a, b){ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return a; }` _readByte: `function (i, size) { return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff; }` _readBits: `function (start, length, size) { var offsetLeft = (start + length) % 8; var offsetRight = start % 8; var curByte = size - (start >> 3) - 1; var lastByte = size + (-(start + length) >> 3); var diff = curByte - lastByte; var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1); if (diff && offsetLeft) { sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight; } while (diff) { sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight); } return sum; }` _checkSize: (neededBits)-> if @_pos + Math.ceil(neededBits / 8) > @_buffer.length throw new Error "Index out of bound"
[ { "context": "T, cb) ->\n\n await db.put { key : \"max\", value : \"krohn\" }, defer err\n T.no_error err\n await db.get", "end": 294, "score": 0.4921227991580963, "start": 293, "tag": "USERNAME", "value": "k" }, { "context": ", cb) ->\n\n await db.put { key : \"max\", value : \"...
test/files/0_basics.iced
maxtaco/iced-db
151
{E,DB} = require '../../lib/main' {db} = require './lib' #================================= exports.setup = setup = (T,cb) -> await db.create defer err T.no_error err cb() #================================= exports.put_get_del_0 = (T, cb) -> await db.put { key : "max", value : "krohn" }, defer err T.no_error err await db.get { key : "max" }, defer err, val T.no_error err T.assert val?, "a value came back" T.equal "krohn", val.toString('utf8'), "the right value" await db.get { key : "chris" }, defer err, val T.assert err?, "got an error back" T.assert (err instanceof E.NotFoundError), "not found error" T.assert not(val?), "no val" await db.del { key : "max" }, defer err T.no_error err await db.get { key : "max" }, defer err, val T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" T.assert not(val?), "no value" await db.del { key : "max" }, defer err T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" await db.del { key : "chris" }, defer err T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" cb() #================================= exports.put_get_json_1 = (T,cb) -> obj = { foo : [1,2,3], bar : [ { biz: 1, jam : [1,2,34]}]} key = "k1" await db.put { key, value : obj, json : true }, defer err T.no_error err await db.get { key }, defer err, val T.no_error err T.equal obj, val, "json object came back" obj.boop = true k2 = "k2" await db.put { key : k2, value : obj, json : true }, defer err T.no_error err await db.get { key : k2 }, defer err, val T.no_error err T.equal obj, val, "json object came back" cb() #================================= exports.put_key_get_hkey = (T,cb) -> key = "k3" value = 1 await db.put { key, value, json : true }, defer err, { hkey } T.no_error err await db.get { hkey }, defer err, val2 T.no_error err T.equal value, val2, "value was right" cb() #=================================
159517
{E,DB} = require '../../lib/main' {db} = require './lib' #================================= exports.setup = setup = (T,cb) -> await db.create defer err T.no_error err cb() #================================= exports.put_get_del_0 = (T, cb) -> await db.put { key : "max", value : "k<KEY>hn" }, defer err T.no_error err await db.get { key : "max" }, defer err, val T.no_error err T.assert val?, "a value came back" T.equal "krohn", val.toString('utf8'), "the right value" await db.get { key : "<KEY>is" }, defer err, val T.assert err?, "got an error back" T.assert (err instanceof E.NotFoundError), "not found error" T.assert not(val?), "no val" await db.del { key : "max" }, defer err T.no_error err await db.get { key : "max" }, defer err, val T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" T.assert not(val?), "no value" await db.del { key : "max" }, defer err T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" await db.del { key : "chr<NAME>" }, defer err T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" cb() #================================= exports.put_get_json_1 = (T,cb) -> obj = { foo : [1,2,3], bar : [ { biz: 1, jam : [1,2,34]}]} key = "<KEY>" await db.put { key, value : obj, json : true }, defer err T.no_error err await db.get { key }, defer err, val T.no_error err T.equal obj, val, "json object came back" obj.boop = true k2 = "k2" await db.put { key : k2, value : obj, json : true }, defer err T.no_error err await db.get { key : k2 }, defer err, val T.no_error err T.equal obj, val, "json object came back" cb() #================================= exports.put_key_get_hkey = (T,cb) -> key = "<KEY>" value = 1 await db.put { key, value, json : true }, defer err, { hkey } T.no_error err await db.get { hkey }, defer err, val2 T.no_error err T.equal value, val2, "value was right" cb() #=================================
true
{E,DB} = require '../../lib/main' {db} = require './lib' #================================= exports.setup = setup = (T,cb) -> await db.create defer err T.no_error err cb() #================================= exports.put_get_del_0 = (T, cb) -> await db.put { key : "max", value : "kPI:KEY:<KEY>END_PIhn" }, defer err T.no_error err await db.get { key : "max" }, defer err, val T.no_error err T.assert val?, "a value came back" T.equal "krohn", val.toString('utf8'), "the right value" await db.get { key : "PI:KEY:<KEY>END_PIis" }, defer err, val T.assert err?, "got an error back" T.assert (err instanceof E.NotFoundError), "not found error" T.assert not(val?), "no val" await db.del { key : "max" }, defer err T.no_error err await db.get { key : "max" }, defer err, val T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" T.assert not(val?), "no value" await db.del { key : "max" }, defer err T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" await db.del { key : "chrPI:NAME:<NAME>END_PI" }, defer err T.assert err?, "error happened" T.assert (err instanceof E.NotFoundError), "not found error" cb() #================================= exports.put_get_json_1 = (T,cb) -> obj = { foo : [1,2,3], bar : [ { biz: 1, jam : [1,2,34]}]} key = "PI:KEY:<KEY>END_PI" await db.put { key, value : obj, json : true }, defer err T.no_error err await db.get { key }, defer err, val T.no_error err T.equal obj, val, "json object came back" obj.boop = true k2 = "k2" await db.put { key : k2, value : obj, json : true }, defer err T.no_error err await db.get { key : k2 }, defer err, val T.no_error err T.equal obj, val, "json object came back" cb() #================================= exports.put_key_get_hkey = (T,cb) -> key = "PI:KEY:<KEY>END_PI" value = 1 await db.put { key, value, json : true }, defer err, { hkey } T.no_error err await db.get { hkey }, defer err, val2 T.no_error err T.equal value, val2, "value was right" cb() #=================================
[ { "context": "'schemaverse'\n user: username\n password: password\n\n console.log \"about to connect #{username}:#{", "end": 362, "score": 0.9994585514068604, "start": 354, "tag": "PASSWORD", "value": "password" }, { "context": " qs:\n cmd: 'register'\n ...
models/schemaverse.coffee
redaphid/schemaverse
0
_ = require 'lodash' Chance = require 'chance' request = require 'request' class Schemaverse constructor: -> @chance = new Chance() postgresShit: ({username, password}, callback) => { Client } = require 'pg' client = new Client host: 'db.schemaverse.com' database: 'schemaverse' user: username password: password console.log "about to connect #{username}:#{password}" client.connect (error) => console.error error.stack if error? return callback() if error? console.log 'connected' client.query 'SELECT GET_PLAYER_ID(SESSION_USER);', (error, results) => return callback() if error? callback null, results postCreateAccount: ({username, password}, callback) => #-H 'Cookie: PHPSESSID=4vcdp0c7q5t45p0m98f16h2gp4' #-H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Referer: https://schemaverse.com/tutorial/tutorial.php?page=Registration' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --compressed options = url: "https://schemaverse.com/tw/command.php" rejectUnauthorized: false qs: cmd: 'register' username: username password: password headers: "Cookie": "PHPSESSID=rs8slqde5mr0f8jio7nuojiul2" "Origin": "https://schemaverse.com" "Accept-Encoding": "gzip, deflate, br" "Accept-Language": "en-US,en;q=0.8" "Upgrade-Insecure-Requests": "1" "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" "Content-Type": "application/x-www-form-urlencoded" "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" "Cache-Control": "max-age=0" "Referer": "https://schemaverse.com/tw/index.php" "Connection": "keep-alive" "DNT": "1" request.post options, (error, response) => return callback() if error? return callback() if response.statusCode != 200 console.log {username, password} callback null, {username, password} createAccount: (nothing, callback) => username = @chance.name().split(' ').join('').toLowerCase() password = _.random(99999,9999999999999999).toString '16' @postCreateAccount {username, password}, callback module.exports = Schemaverse
185121
_ = require 'lodash' Chance = require 'chance' request = require 'request' class Schemaverse constructor: -> @chance = new Chance() postgresShit: ({username, password}, callback) => { Client } = require 'pg' client = new Client host: 'db.schemaverse.com' database: 'schemaverse' user: username password: <PASSWORD> console.log "about to connect #{username}:#{password}" client.connect (error) => console.error error.stack if error? return callback() if error? console.log 'connected' client.query 'SELECT GET_PLAYER_ID(SESSION_USER);', (error, results) => return callback() if error? callback null, results postCreateAccount: ({username, password}, callback) => #-H 'Cookie: PHPSESSID=4vcdp0c7q5t45p0m98f16h2gp4' #-H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Referer: https://schemaverse.com/tutorial/tutorial.php?page=Registration' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --compressed options = url: "https://schemaverse.com/tw/command.php" rejectUnauthorized: false qs: cmd: 'register' username: username password: <PASSWORD> headers: "Cookie": "PHPSESSID=rs8slqde5mr0f8jio7nuojiul2" "Origin": "https://schemaverse.com" "Accept-Encoding": "gzip, deflate, br" "Accept-Language": "en-US,en;q=0.8" "Upgrade-Insecure-Requests": "1" "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" "Content-Type": "application/x-www-form-urlencoded" "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" "Cache-Control": "max-age=0" "Referer": "https://schemaverse.com/tw/index.php" "Connection": "keep-alive" "DNT": "1" request.post options, (error, response) => return callback() if error? return callback() if response.statusCode != 200 console.log {username, password} callback null, {username, password} createAccount: (nothing, callback) => username = @chance.name().split(' ').join('').toLowerCase() password = _.<PASSWORD>(<PASSWORD>,<PASSWORD>' @postCreateAccount {username, password}, callback module.exports = Schemaverse
true
_ = require 'lodash' Chance = require 'chance' request = require 'request' class Schemaverse constructor: -> @chance = new Chance() postgresShit: ({username, password}, callback) => { Client } = require 'pg' client = new Client host: 'db.schemaverse.com' database: 'schemaverse' user: username password: PI:PASSWORD:<PASSWORD>END_PI console.log "about to connect #{username}:#{password}" client.connect (error) => console.error error.stack if error? return callback() if error? console.log 'connected' client.query 'SELECT GET_PLAYER_ID(SESSION_USER);', (error, results) => return callback() if error? callback null, results postCreateAccount: ({username, password}, callback) => #-H 'Cookie: PHPSESSID=4vcdp0c7q5t45p0m98f16h2gp4' #-H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Referer: https://schemaverse.com/tutorial/tutorial.php?page=Registration' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --compressed options = url: "https://schemaverse.com/tw/command.php" rejectUnauthorized: false qs: cmd: 'register' username: username password: PI:PASSWORD:<PASSWORD>END_PI headers: "Cookie": "PHPSESSID=rs8slqde5mr0f8jio7nuojiul2" "Origin": "https://schemaverse.com" "Accept-Encoding": "gzip, deflate, br" "Accept-Language": "en-US,en;q=0.8" "Upgrade-Insecure-Requests": "1" "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" "Content-Type": "application/x-www-form-urlencoded" "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" "Cache-Control": "max-age=0" "Referer": "https://schemaverse.com/tw/index.php" "Connection": "keep-alive" "DNT": "1" request.post options, (error, response) => return callback() if error? return callback() if response.statusCode != 200 console.log {username, password} callback null, {username, password} createAccount: (nothing, callback) => username = @chance.name().split(' ').join('').toLowerCase() password = _.PI:PASSWORD:<PASSWORD>END_PI(PI:PASSWORD:<PASSWORD>END_PI,PI:PASSWORD:<PASSWORD>END_PI' @postCreateAccount {username, password}, callback module.exports = Schemaverse
[ { "context": "a[@title=\":title\"]');\n # pathway.bind({title: \"Wesabe\"}).value; // => '//a[@title=\"Wesabe\"]'\n #\n ", "end": 3761, "score": 0.6275343298912048, "start": 3760, "tag": "NAME", "value": "W" } ]
application/chrome/content/wesabe/xpath.coffee
wesabe/ssu
28
type = require 'lang/type' array = require 'lang/array' inspect = require 'util/inspect' privacy = require 'util/privacy' # # Provides methods for generating, manipulating, and searching by XPaths. # # ==== Types (shortcuts for use in this file) # Xpath:: <String, Array[String], Pathway, Pathset> # class Pathway constructor: (value) -> @value = @_prepare(value) @REPLACEMENTS: 'upper-case($1)': 'translate($1, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")' 'lower-case($1)': 'translate($1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")' 'has-class("$1")': 'contains(concat(" ", @class, " "), " $1 ")' _prepare: (value) -> for own func, replacement of @constructor.REPLACEMENTS [head, tail] = func.split('$1') [replacementHead, replacementTail] = replacement.split('$1') while (start = value.indexOf(head)) isnt -1 end = start nesting = 0 while end < (start + head.length) switch value.substring(end, end+1) when '(' nesting++ when ')' nesting-- if nesting < 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") end++ while nesting > 0 or end < value.length switch value.substring(end, end+1) when '(' nesting++ when ')' nesting-- if nesting < 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") end++ break if nesting is 0 and value.substring(end-tail.length, end) is tail if nesting isnt 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") value = value.substring(0, start) + "#{replacementHead}#{value.substring(start+head.length, end-tail.length)}#{replacementTail}" + value.substring(end) return value # # Returns the first matching DOM element in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement>:: The element to scope the search to. # # ==== Returns # tainted(HTMLElement):: The first matching DOM element. # # @public # first: (document, scope) -> try result = document.evaluate( privacy.untaint(@value), privacy.untaint(scope or document), null, XPathResult.ANY_TYPE, null, null) catch err if err instanceof XPathException throw new Error "#{err.message} (XPath = #{@value})" throw err privacy.taint result?.iterateNext() # # Returns all matching DOM elements in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement, null>:: An optional scope to search within. # # ==== Returns # tainted(Array[HTMLElement]):: All matching DOM elements. # # @public # select: (document, scope) -> result = document.evaluate( privacy.untaint(@value), privacy.untaint(scope or document), null, XPathResult.ANY_TYPE, null, null) nodes = [] nodes.push(node) while node = result.iterateNext() return privacy.taint @constructor.inDocumentOrder(nodes) # # Applies a binding to a copy of this +Pathway+. # # ==== Parameters # binding<Object>:: Key-value pairs to interpolate into the +Pathway+. # # ==== Returns # Pathway:: A new +Pathway+ bound to +binding+. # # ==== Example # var pathway = new Pathway('//a[@title=":title"]'); # pathway.bind({title: "Wesabe"}).value; // => '//a[@title="Wesabe"]' # # @public # bind: (binding) -> boundValue = @value for own key, value of binding boundValue = boundValue.replace(new RegExp(":#{key}", 'g'), privacy.untaint(value)) boundValue = privacy.taint(boundValue) if type.isTainted(value) return new Pathway boundValue # # Returns a +Pathway+-compatible object if one can be generated from +xpath+. # # ==== Parameters # xpath<Xpath>:: # Something that can be used as a +Pathway+. # # ==== Returns # Pathway,Pathset:: # A +Pathway+ or +Pathset+ converted from the argument. # # @public # @from: (xpath) -> if type.isString xpath new Pathway(xpath) else if type.isArray xpath new Pathset(xpath) else if type.is(xpath, Pathway) or type.is(xpath, Pathset) xpath else throw new Error "Could not convert #{inspect xpath} to a Pathway." # # Returns the given array with elements sorted by document order. # # ==== Parameters # elements<Array[~compareDocumentPosition]>:: List of elements to sort. # # ==== Returns # Array[~compareDocumentPosition]:: List of sorted elements. # # @public # @inDocumentOrder: (elements) -> elements.sort (a, b) -> a = privacy.untaint(a) b = privacy.untaint(b) switch a.compareDocumentPosition(b) when Node.DOCUMENT_POSITION_PRECEDING, Node.DOCUMENT_POSITION_CONTAINS 1 when Node.DOCUMENT_POSITION_FOLLOWING, Node.DOCUMENT_POSITION_IS_CONTAINED -1 else 0 # # Applies a binding to an +Xpath+. # # ==== Parameters # xpath<Xpath>:: The thing to bind. # binding<Object>:: Key-value pairs to interpolate into the xpath. # # ==== Returns # Pathway,Pathset:: # A +Pathway+-compatible object with bindings applied from +binding+. # # ==== Example # Pathway.bind('//a[@title=":title"]', {title: "Wesabe"}).value // => '//a[@title="Wesabe"]' # # @public # @bind: (xpath, binding) -> @from(xpath).bind(binding) # # Provides methods for dealing with sets of +Pathways+. # class Pathset constructor: (args...) -> args = args[0] if args.length == 1 && type.isArray(args[0]) @xpaths = [] for arg in args @xpaths.push(Pathway.from(arg)) # # Returns the first matching DOM element in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement>:: The element to scope the search to. # # ==== Returns # tainted(HTMLElement):: The first matching DOM element. # # @public # first: (document, scope) -> for xpath in @xpaths if element = xpath.first(document, scope) return element # # Returns all matching DOM elements from the all matching Pathways in the set. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement, null>:: An optional scope to search within. # # ==== Returns # tainted(Array[HTMLElement]):: All matching DOM elements. # # @public # select: (document, scope) -> elements = [] for xpath in @xpaths elements = elements.concat(xpath.select(document, scope)) Pathway.inDocumentOrder(array.uniq(elements)) # # Applies a binding to a copy of this +Pathset+. # # ==== Parameters # binding<Object>:: Key-value pairs to interpolate into the +Pathset+. # # ==== Returns # Pathset:: A new +Pathset+ bound to +binding+. # # ==== Example # var pathset = new Pathset( # '//a[@title=":title"]', '//a[contains(string(.), ":title")]); # pathway.bind({title: "Wesabe"}); # // results in #<Pathset value=[ # '//a[@title="Wesabe"]', '//a[contains(string(.), "Wesabe")]> # # @public # bind: (binding) -> new @constructor(xpath.bind(binding) for xpath in @xpaths) module.exports = {Pathset, Pathway} # DEPRECATIONS # # We previously allowed: # # wesabe.xpath.bind(xpath, binding) # # to be shorthand for: # # wesabe.xpath.Pathway.from(xpath).bind(binding) # # but now the preferred shorthand is: # # wesabe.xpath.Pathway.bind(xpath, binding) # # We re-add the original here with a deprecation notice. module.exports.bind = logger.wrapDeprecated('wesabe.xpath.bind', 'wesabe.xpath.Pathway.bind', (args...) -> Pathway.bind args...)
121540
type = require 'lang/type' array = require 'lang/array' inspect = require 'util/inspect' privacy = require 'util/privacy' # # Provides methods for generating, manipulating, and searching by XPaths. # # ==== Types (shortcuts for use in this file) # Xpath:: <String, Array[String], Pathway, Pathset> # class Pathway constructor: (value) -> @value = @_prepare(value) @REPLACEMENTS: 'upper-case($1)': 'translate($1, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")' 'lower-case($1)': 'translate($1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")' 'has-class("$1")': 'contains(concat(" ", @class, " "), " $1 ")' _prepare: (value) -> for own func, replacement of @constructor.REPLACEMENTS [head, tail] = func.split('$1') [replacementHead, replacementTail] = replacement.split('$1') while (start = value.indexOf(head)) isnt -1 end = start nesting = 0 while end < (start + head.length) switch value.substring(end, end+1) when '(' nesting++ when ')' nesting-- if nesting < 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") end++ while nesting > 0 or end < value.length switch value.substring(end, end+1) when '(' nesting++ when ')' nesting-- if nesting < 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") end++ break if nesting is 0 and value.substring(end-tail.length, end) is tail if nesting isnt 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") value = value.substring(0, start) + "#{replacementHead}#{value.substring(start+head.length, end-tail.length)}#{replacementTail}" + value.substring(end) return value # # Returns the first matching DOM element in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement>:: The element to scope the search to. # # ==== Returns # tainted(HTMLElement):: The first matching DOM element. # # @public # first: (document, scope) -> try result = document.evaluate( privacy.untaint(@value), privacy.untaint(scope or document), null, XPathResult.ANY_TYPE, null, null) catch err if err instanceof XPathException throw new Error "#{err.message} (XPath = #{@value})" throw err privacy.taint result?.iterateNext() # # Returns all matching DOM elements in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement, null>:: An optional scope to search within. # # ==== Returns # tainted(Array[HTMLElement]):: All matching DOM elements. # # @public # select: (document, scope) -> result = document.evaluate( privacy.untaint(@value), privacy.untaint(scope or document), null, XPathResult.ANY_TYPE, null, null) nodes = [] nodes.push(node) while node = result.iterateNext() return privacy.taint @constructor.inDocumentOrder(nodes) # # Applies a binding to a copy of this +Pathway+. # # ==== Parameters # binding<Object>:: Key-value pairs to interpolate into the +Pathway+. # # ==== Returns # Pathway:: A new +Pathway+ bound to +binding+. # # ==== Example # var pathway = new Pathway('//a[@title=":title"]'); # pathway.bind({title: "<NAME>esabe"}).value; // => '//a[@title="Wesabe"]' # # @public # bind: (binding) -> boundValue = @value for own key, value of binding boundValue = boundValue.replace(new RegExp(":#{key}", 'g'), privacy.untaint(value)) boundValue = privacy.taint(boundValue) if type.isTainted(value) return new Pathway boundValue # # Returns a +Pathway+-compatible object if one can be generated from +xpath+. # # ==== Parameters # xpath<Xpath>:: # Something that can be used as a +Pathway+. # # ==== Returns # Pathway,Pathset:: # A +Pathway+ or +Pathset+ converted from the argument. # # @public # @from: (xpath) -> if type.isString xpath new Pathway(xpath) else if type.isArray xpath new Pathset(xpath) else if type.is(xpath, Pathway) or type.is(xpath, Pathset) xpath else throw new Error "Could not convert #{inspect xpath} to a Pathway." # # Returns the given array with elements sorted by document order. # # ==== Parameters # elements<Array[~compareDocumentPosition]>:: List of elements to sort. # # ==== Returns # Array[~compareDocumentPosition]:: List of sorted elements. # # @public # @inDocumentOrder: (elements) -> elements.sort (a, b) -> a = privacy.untaint(a) b = privacy.untaint(b) switch a.compareDocumentPosition(b) when Node.DOCUMENT_POSITION_PRECEDING, Node.DOCUMENT_POSITION_CONTAINS 1 when Node.DOCUMENT_POSITION_FOLLOWING, Node.DOCUMENT_POSITION_IS_CONTAINED -1 else 0 # # Applies a binding to an +Xpath+. # # ==== Parameters # xpath<Xpath>:: The thing to bind. # binding<Object>:: Key-value pairs to interpolate into the xpath. # # ==== Returns # Pathway,Pathset:: # A +Pathway+-compatible object with bindings applied from +binding+. # # ==== Example # Pathway.bind('//a[@title=":title"]', {title: "Wesabe"}).value // => '//a[@title="Wesabe"]' # # @public # @bind: (xpath, binding) -> @from(xpath).bind(binding) # # Provides methods for dealing with sets of +Pathways+. # class Pathset constructor: (args...) -> args = args[0] if args.length == 1 && type.isArray(args[0]) @xpaths = [] for arg in args @xpaths.push(Pathway.from(arg)) # # Returns the first matching DOM element in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement>:: The element to scope the search to. # # ==== Returns # tainted(HTMLElement):: The first matching DOM element. # # @public # first: (document, scope) -> for xpath in @xpaths if element = xpath.first(document, scope) return element # # Returns all matching DOM elements from the all matching Pathways in the set. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement, null>:: An optional scope to search within. # # ==== Returns # tainted(Array[HTMLElement]):: All matching DOM elements. # # @public # select: (document, scope) -> elements = [] for xpath in @xpaths elements = elements.concat(xpath.select(document, scope)) Pathway.inDocumentOrder(array.uniq(elements)) # # Applies a binding to a copy of this +Pathset+. # # ==== Parameters # binding<Object>:: Key-value pairs to interpolate into the +Pathset+. # # ==== Returns # Pathset:: A new +Pathset+ bound to +binding+. # # ==== Example # var pathset = new Pathset( # '//a[@title=":title"]', '//a[contains(string(.), ":title")]); # pathway.bind({title: "Wesabe"}); # // results in #<Pathset value=[ # '//a[@title="Wesabe"]', '//a[contains(string(.), "Wesabe")]> # # @public # bind: (binding) -> new @constructor(xpath.bind(binding) for xpath in @xpaths) module.exports = {Pathset, Pathway} # DEPRECATIONS # # We previously allowed: # # wesabe.xpath.bind(xpath, binding) # # to be shorthand for: # # wesabe.xpath.Pathway.from(xpath).bind(binding) # # but now the preferred shorthand is: # # wesabe.xpath.Pathway.bind(xpath, binding) # # We re-add the original here with a deprecation notice. module.exports.bind = logger.wrapDeprecated('wesabe.xpath.bind', 'wesabe.xpath.Pathway.bind', (args...) -> Pathway.bind args...)
true
type = require 'lang/type' array = require 'lang/array' inspect = require 'util/inspect' privacy = require 'util/privacy' # # Provides methods for generating, manipulating, and searching by XPaths. # # ==== Types (shortcuts for use in this file) # Xpath:: <String, Array[String], Pathway, Pathset> # class Pathway constructor: (value) -> @value = @_prepare(value) @REPLACEMENTS: 'upper-case($1)': 'translate($1, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")' 'lower-case($1)': 'translate($1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")' 'has-class("$1")': 'contains(concat(" ", @class, " "), " $1 ")' _prepare: (value) -> for own func, replacement of @constructor.REPLACEMENTS [head, tail] = func.split('$1') [replacementHead, replacementTail] = replacement.split('$1') while (start = value.indexOf(head)) isnt -1 end = start nesting = 0 while end < (start + head.length) switch value.substring(end, end+1) when '(' nesting++ when ')' nesting-- if nesting < 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") end++ while nesting > 0 or end < value.length switch value.substring(end, end+1) when '(' nesting++ when ')' nesting-- if nesting < 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") end++ break if nesting is 0 and value.substring(end-tail.length, end) is tail if nesting isnt 0 throw new Error("unbalanced parentheses in xpath expression: #{value}") value = value.substring(0, start) + "#{replacementHead}#{value.substring(start+head.length, end-tail.length)}#{replacementTail}" + value.substring(end) return value # # Returns the first matching DOM element in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement>:: The element to scope the search to. # # ==== Returns # tainted(HTMLElement):: The first matching DOM element. # # @public # first: (document, scope) -> try result = document.evaluate( privacy.untaint(@value), privacy.untaint(scope or document), null, XPathResult.ANY_TYPE, null, null) catch err if err instanceof XPathException throw new Error "#{err.message} (XPath = #{@value})" throw err privacy.taint result?.iterateNext() # # Returns all matching DOM elements in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement, null>:: An optional scope to search within. # # ==== Returns # tainted(Array[HTMLElement]):: All matching DOM elements. # # @public # select: (document, scope) -> result = document.evaluate( privacy.untaint(@value), privacy.untaint(scope or document), null, XPathResult.ANY_TYPE, null, null) nodes = [] nodes.push(node) while node = result.iterateNext() return privacy.taint @constructor.inDocumentOrder(nodes) # # Applies a binding to a copy of this +Pathway+. # # ==== Parameters # binding<Object>:: Key-value pairs to interpolate into the +Pathway+. # # ==== Returns # Pathway:: A new +Pathway+ bound to +binding+. # # ==== Example # var pathway = new Pathway('//a[@title=":title"]'); # pathway.bind({title: "PI:NAME:<NAME>END_PIesabe"}).value; // => '//a[@title="Wesabe"]' # # @public # bind: (binding) -> boundValue = @value for own key, value of binding boundValue = boundValue.replace(new RegExp(":#{key}", 'g'), privacy.untaint(value)) boundValue = privacy.taint(boundValue) if type.isTainted(value) return new Pathway boundValue # # Returns a +Pathway+-compatible object if one can be generated from +xpath+. # # ==== Parameters # xpath<Xpath>:: # Something that can be used as a +Pathway+. # # ==== Returns # Pathway,Pathset:: # A +Pathway+ or +Pathset+ converted from the argument. # # @public # @from: (xpath) -> if type.isString xpath new Pathway(xpath) else if type.isArray xpath new Pathset(xpath) else if type.is(xpath, Pathway) or type.is(xpath, Pathset) xpath else throw new Error "Could not convert #{inspect xpath} to a Pathway." # # Returns the given array with elements sorted by document order. # # ==== Parameters # elements<Array[~compareDocumentPosition]>:: List of elements to sort. # # ==== Returns # Array[~compareDocumentPosition]:: List of sorted elements. # # @public # @inDocumentOrder: (elements) -> elements.sort (a, b) -> a = privacy.untaint(a) b = privacy.untaint(b) switch a.compareDocumentPosition(b) when Node.DOCUMENT_POSITION_PRECEDING, Node.DOCUMENT_POSITION_CONTAINS 1 when Node.DOCUMENT_POSITION_FOLLOWING, Node.DOCUMENT_POSITION_IS_CONTAINED -1 else 0 # # Applies a binding to an +Xpath+. # # ==== Parameters # xpath<Xpath>:: The thing to bind. # binding<Object>:: Key-value pairs to interpolate into the xpath. # # ==== Returns # Pathway,Pathset:: # A +Pathway+-compatible object with bindings applied from +binding+. # # ==== Example # Pathway.bind('//a[@title=":title"]', {title: "Wesabe"}).value // => '//a[@title="Wesabe"]' # # @public # @bind: (xpath, binding) -> @from(xpath).bind(binding) # # Provides methods for dealing with sets of +Pathways+. # class Pathset constructor: (args...) -> args = args[0] if args.length == 1 && type.isArray(args[0]) @xpaths = [] for arg in args @xpaths.push(Pathway.from(arg)) # # Returns the first matching DOM element in the given document. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement>:: The element to scope the search to. # # ==== Returns # tainted(HTMLElement):: The first matching DOM element. # # @public # first: (document, scope) -> for xpath in @xpaths if element = xpath.first(document, scope) return element # # Returns all matching DOM elements from the all matching Pathways in the set. # # ==== Parameters # document<HTMLDocument>:: The document to serve as the root. # scope<HTMLElement, null>:: An optional scope to search within. # # ==== Returns # tainted(Array[HTMLElement]):: All matching DOM elements. # # @public # select: (document, scope) -> elements = [] for xpath in @xpaths elements = elements.concat(xpath.select(document, scope)) Pathway.inDocumentOrder(array.uniq(elements)) # # Applies a binding to a copy of this +Pathset+. # # ==== Parameters # binding<Object>:: Key-value pairs to interpolate into the +Pathset+. # # ==== Returns # Pathset:: A new +Pathset+ bound to +binding+. # # ==== Example # var pathset = new Pathset( # '//a[@title=":title"]', '//a[contains(string(.), ":title")]); # pathway.bind({title: "Wesabe"}); # // results in #<Pathset value=[ # '//a[@title="Wesabe"]', '//a[contains(string(.), "Wesabe")]> # # @public # bind: (binding) -> new @constructor(xpath.bind(binding) for xpath in @xpaths) module.exports = {Pathset, Pathway} # DEPRECATIONS # # We previously allowed: # # wesabe.xpath.bind(xpath, binding) # # to be shorthand for: # # wesabe.xpath.Pathway.from(xpath).bind(binding) # # but now the preferred shorthand is: # # wesabe.xpath.Pathway.bind(xpath, binding) # # We re-add the original here with a deprecation notice. module.exports.bind = logger.wrapDeprecated('wesabe.xpath.bind', 'wesabe.xpath.Pathway.bind', (args...) -> Pathway.bind args...)
[ { "context": "ss.env.JENKINS_USERNAME\nexports.JENKINS_PASSWORD = process.env.JENKINS_PASSWORD\nexports.JENKINS_TEMPLATE_JOB_NAME = process.env.J", "end": 333, "score": 0.9801487922668457, "start": 305, "tag": "PASSWORD", "value": "process.env.JENKINS_PASSWORD" } ]
env.coffee
Nestio/jennifer
3
# All constants in this block must be defined as env variables # exports.LOG_FILE = process.env.LOG_FILE || 'jennifer.log' exports.LOG_LEVEL = process.env.LOG_LEVEL || 'INFO' exports.JENKINS_URL = process.env.JENKINS_URL exports.JENKINS_USERNAME = process.env.JENKINS_USERNAME exports.JENKINS_PASSWORD = process.env.JENKINS_PASSWORD exports.JENKINS_TEMPLATE_JOB_NAME = process.env.JENKINS_TEMPLATE_JOB_NAME exports.JENKINS_REMOTE_BUILD_AUTH_TOKEN = process.env.JENKINS_REMOTE_BUILD_AUTH_TOKEN exports.GITHUB_REPO_OWNER = process.env.GITHUB_REPO_OWNER exports.GITHUB_REPO = process.env.GITHUB_REPO exports.GITHUB_OAUTH_TOKEN = process.env.GITHUB_OAUTH_TOKEN # exports.JENKINS_AUTHED_URL = exports.JENKINS_URL.replace( /\/\//, "//#{exports.JENKINS_USERNAME}:#{exports.JENKINS_PASSWORD}@")
82960
# All constants in this block must be defined as env variables # exports.LOG_FILE = process.env.LOG_FILE || 'jennifer.log' exports.LOG_LEVEL = process.env.LOG_LEVEL || 'INFO' exports.JENKINS_URL = process.env.JENKINS_URL exports.JENKINS_USERNAME = process.env.JENKINS_USERNAME exports.JENKINS_PASSWORD = <PASSWORD> exports.JENKINS_TEMPLATE_JOB_NAME = process.env.JENKINS_TEMPLATE_JOB_NAME exports.JENKINS_REMOTE_BUILD_AUTH_TOKEN = process.env.JENKINS_REMOTE_BUILD_AUTH_TOKEN exports.GITHUB_REPO_OWNER = process.env.GITHUB_REPO_OWNER exports.GITHUB_REPO = process.env.GITHUB_REPO exports.GITHUB_OAUTH_TOKEN = process.env.GITHUB_OAUTH_TOKEN # exports.JENKINS_AUTHED_URL = exports.JENKINS_URL.replace( /\/\//, "//#{exports.JENKINS_USERNAME}:#{exports.JENKINS_PASSWORD}@")
true
# All constants in this block must be defined as env variables # exports.LOG_FILE = process.env.LOG_FILE || 'jennifer.log' exports.LOG_LEVEL = process.env.LOG_LEVEL || 'INFO' exports.JENKINS_URL = process.env.JENKINS_URL exports.JENKINS_USERNAME = process.env.JENKINS_USERNAME exports.JENKINS_PASSWORD = PI:PASSWORD:<PASSWORD>END_PI exports.JENKINS_TEMPLATE_JOB_NAME = process.env.JENKINS_TEMPLATE_JOB_NAME exports.JENKINS_REMOTE_BUILD_AUTH_TOKEN = process.env.JENKINS_REMOTE_BUILD_AUTH_TOKEN exports.GITHUB_REPO_OWNER = process.env.GITHUB_REPO_OWNER exports.GITHUB_REPO = process.env.GITHUB_REPO exports.GITHUB_OAUTH_TOKEN = process.env.GITHUB_OAUTH_TOKEN # exports.JENKINS_AUTHED_URL = exports.JENKINS_URL.replace( /\/\//, "//#{exports.JENKINS_USERNAME}:#{exports.JENKINS_PASSWORD}@")
[ { "context": " [class] [method] - please see https://github.com/stympy/faker for class and methods\n#\n# Notes:\n# <optio", "end": 256, "score": 0.9961460828781128, "start": 250, "tag": "USERNAME", "value": "stympy" }, { "context": "nal notes required for the script>\n#\n# Author:\...
src/faker.coffee
Dustinschie/hubot-faker
0
# Description # A hubot script that does the faking of things # # Configuration: # HUBOT_FAKER_API_URL = Optional. If set, allow you to use your own faker-api instance # # Commands: # hubot fake [class] [method] - please see https://github.com/stympy/faker for class and methods # # Notes: # <optional notes required for the script> # # Author: # Dustin Schie <me@dustinschie.com> URL = process.env.HUBOT_FAKER_API_URL || 'https://fakerapi.herokuapp.com' module.exports = (robot) -> robot.respond /fake( \w+ \w+)$/i, (res) -> path = res.match[1].split(' ').join('/') robot.http("#{URL}/#{path}") .get() (err, resp, body) -> if resp.statusCode isnt 200 res.send "I can't; something went wrong!" else res.send body
19562
# Description # A hubot script that does the faking of things # # Configuration: # HUBOT_FAKER_API_URL = Optional. If set, allow you to use your own faker-api instance # # Commands: # hubot fake [class] [method] - please see https://github.com/stympy/faker for class and methods # # Notes: # <optional notes required for the script> # # Author: # <NAME> <<EMAIL>> URL = process.env.HUBOT_FAKER_API_URL || 'https://fakerapi.herokuapp.com' module.exports = (robot) -> robot.respond /fake( \w+ \w+)$/i, (res) -> path = res.match[1].split(' ').join('/') robot.http("#{URL}/#{path}") .get() (err, resp, body) -> if resp.statusCode isnt 200 res.send "I can't; something went wrong!" else res.send body
true
# Description # A hubot script that does the faking of things # # Configuration: # HUBOT_FAKER_API_URL = Optional. If set, allow you to use your own faker-api instance # # Commands: # hubot fake [class] [method] - please see https://github.com/stympy/faker for class and methods # # Notes: # <optional notes required for the script> # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> URL = process.env.HUBOT_FAKER_API_URL || 'https://fakerapi.herokuapp.com' module.exports = (robot) -> robot.respond /fake( \w+ \w+)$/i, (res) -> path = res.match[1].split(' ').join('/') robot.http("#{URL}/#{path}") .get() (err, resp, body) -> if resp.statusCode isnt 200 res.send "I can't; something went wrong!" else res.send body
[ { "context": "cket\n ex: ngist file.js -u username -t token\n-p, --private Make gist private\n-o,", "end": 1018, "score": 0.9948518872261047, "start": 1010, "tag": "USERNAME", "value": "username" }, { "context": "et_creds = (files) ->\n keys = ['get', 's...
src/cli.coffee
chapel/ngist
4
os = require 'os' ngist = require './ngist' {exec} = require 'child_process' opt = require('optimist').argv run = -> # Set args to the appropriate values opt._ = null if opt._.length is 0 opt.help = opt.help or opt.h opt.clip = opt.clip or opt.c opt.desc = opt.desc or opt.d opt.private = opt.private or opt.p opt.user = opt.user or opt.u opt.token = opt.token or opt.t opt.out = opt.out or opt.o # Return help message if -h or --help is set if opt.help return console.log ''' Usage: ngist [file.js file2.js ...] [options] [Options] -h, --help Display this help page -c, --clip Use clipboard content ex: ngist [file.js] -c file.js -d, --desc Set description of gist ex: ngist file.js -d 'Description' -u, --user Github username -t, --token Github API token | https://github.com/account#admin_bucket ex: ngist file.js -u username -t token -p, --private Make gist private -o, --out Copy gist url to clipboard [How to set user/token with git config] Once you get your Github API token from https://github.com/account#admin_bucket If you set your Github username and API token using these steps, ngist will automatically gather them and authenticate for you. Run these two commands: git config --add github.user [github_username] git config --add github.token [github_api_token] To verify that they have been set, use: git config --get github.[user/token] ''' if opt._ and opt.clip ngist.files opt._, (err, files) -> spit_error err if err get_clip (clip) -> files = files.concat clip next(files) else if opt._ ngist.files opt._, (err, files) -> spit_error err if err next(files) else if opt.clip get_clip (clip) -> next clip else spit_error 'You must set file(s) and/or a clip from the clipboard (-c)' next = (files) -> if opt.user and opt.token finish files, opt.user, opt.token else if (opt.user and not opt.token) or (opt.token and not opt.user) spit_error 'Both user (-u) and token (-t) must be set if you wish to login' else get_creds files finish = (files, user, token) -> if opt.desc or opt.private or (user and token) options = {} else options = null options.private = true if opt.private options.description = opt.desc if opt.desc options.user = user if user options.token = token if token ngist.send files, options, (err, url) -> spit_error err if err set_clip url if opt.out console.log "Gist: #{url}" get_creds = (files) -> keys = ['get', 'system', 'global', 'simple'] serial keys, (key, i, _next) -> exec "git config --#{key} github.user", (err, stdout, stderr) -> unless err user = stdout.replace("\n", "") exec "git config --#{key} github.token", (err, stdout, stderr) -> unless err token = stdout.replace("\n", "") return finish files, user, token else _next() , -> console.log "For instructions on how to authenticate your gists: ngist -h" return finish files, null, null set_clip = (url) -> switch os.type() when 'Darwin' then clipboard = "echo #{url} | pbcopy" when 'Linux' then clipboard = "echo #{url} | xclip" exec clipboard, (err, stdout) -> spit_error 'Problem sending url to clipboard' if err get_clip = (callback) -> clip = [] switch os.type() when 'Darwin' then clipboard = 'pbpaste' when 'Linux' then clipboard = 'xclip -out -selection clipboard' exec clipboard, (err, stdout) -> spit_error 'Nothing in clipboard' if stdout == '' spit_error 'Problem getting contents of clipboard' if err clip.push name: opt.clip contents: stdout callback clip spit_error = (err) -> console.error "#{err}\nFor more help see: ngist -h" process.exit 1 serial = (array, iterator, next) -> cycle = (i) -> if i < array.length iterator array[i], i, -> cycle i+1 else next() cycle 0 run()
12693
os = require 'os' ngist = require './ngist' {exec} = require 'child_process' opt = require('optimist').argv run = -> # Set args to the appropriate values opt._ = null if opt._.length is 0 opt.help = opt.help or opt.h opt.clip = opt.clip or opt.c opt.desc = opt.desc or opt.d opt.private = opt.private or opt.p opt.user = opt.user or opt.u opt.token = opt.token or opt.t opt.out = opt.out or opt.o # Return help message if -h or --help is set if opt.help return console.log ''' Usage: ngist [file.js file2.js ...] [options] [Options] -h, --help Display this help page -c, --clip Use clipboard content ex: ngist [file.js] -c file.js -d, --desc Set description of gist ex: ngist file.js -d 'Description' -u, --user Github username -t, --token Github API token | https://github.com/account#admin_bucket ex: ngist file.js -u username -t token -p, --private Make gist private -o, --out Copy gist url to clipboard [How to set user/token with git config] Once you get your Github API token from https://github.com/account#admin_bucket If you set your Github username and API token using these steps, ngist will automatically gather them and authenticate for you. Run these two commands: git config --add github.user [github_username] git config --add github.token [github_api_token] To verify that they have been set, use: git config --get github.[user/token] ''' if opt._ and opt.clip ngist.files opt._, (err, files) -> spit_error err if err get_clip (clip) -> files = files.concat clip next(files) else if opt._ ngist.files opt._, (err, files) -> spit_error err if err next(files) else if opt.clip get_clip (clip) -> next clip else spit_error 'You must set file(s) and/or a clip from the clipboard (-c)' next = (files) -> if opt.user and opt.token finish files, opt.user, opt.token else if (opt.user and not opt.token) or (opt.token and not opt.user) spit_error 'Both user (-u) and token (-t) must be set if you wish to login' else get_creds files finish = (files, user, token) -> if opt.desc or opt.private or (user and token) options = {} else options = null options.private = true if opt.private options.description = opt.desc if opt.desc options.user = user if user options.token = token if token ngist.send files, options, (err, url) -> spit_error err if err set_clip url if opt.out console.log "Gist: #{url}" get_creds = (files) -> keys = ['get', 'system', '<KEY>', '<KEY>'] serial keys, (key, i, _next) -> exec "git config --#{key} github.user", (err, stdout, stderr) -> unless err user = stdout.replace("\n", "") exec "git config --#{key} github.token", (err, stdout, stderr) -> unless err token = stdout.replace("\n", "") return finish files, user, token else _next() , -> console.log "For instructions on how to authenticate your gists: ngist -h" return finish files, null, null set_clip = (url) -> switch os.type() when 'Darwin' then clipboard = "echo #{url} | pbcopy" when 'Linux' then clipboard = "echo #{url} | xclip" exec clipboard, (err, stdout) -> spit_error 'Problem sending url to clipboard' if err get_clip = (callback) -> clip = [] switch os.type() when 'Darwin' then clipboard = 'pbpaste' when 'Linux' then clipboard = 'xclip -out -selection clipboard' exec clipboard, (err, stdout) -> spit_error 'Nothing in clipboard' if stdout == '' spit_error 'Problem getting contents of clipboard' if err clip.push name: opt.clip contents: stdout callback clip spit_error = (err) -> console.error "#{err}\nFor more help see: ngist -h" process.exit 1 serial = (array, iterator, next) -> cycle = (i) -> if i < array.length iterator array[i], i, -> cycle i+1 else next() cycle 0 run()
true
os = require 'os' ngist = require './ngist' {exec} = require 'child_process' opt = require('optimist').argv run = -> # Set args to the appropriate values opt._ = null if opt._.length is 0 opt.help = opt.help or opt.h opt.clip = opt.clip or opt.c opt.desc = opt.desc or opt.d opt.private = opt.private or opt.p opt.user = opt.user or opt.u opt.token = opt.token or opt.t opt.out = opt.out or opt.o # Return help message if -h or --help is set if opt.help return console.log ''' Usage: ngist [file.js file2.js ...] [options] [Options] -h, --help Display this help page -c, --clip Use clipboard content ex: ngist [file.js] -c file.js -d, --desc Set description of gist ex: ngist file.js -d 'Description' -u, --user Github username -t, --token Github API token | https://github.com/account#admin_bucket ex: ngist file.js -u username -t token -p, --private Make gist private -o, --out Copy gist url to clipboard [How to set user/token with git config] Once you get your Github API token from https://github.com/account#admin_bucket If you set your Github username and API token using these steps, ngist will automatically gather them and authenticate for you. Run these two commands: git config --add github.user [github_username] git config --add github.token [github_api_token] To verify that they have been set, use: git config --get github.[user/token] ''' if opt._ and opt.clip ngist.files opt._, (err, files) -> spit_error err if err get_clip (clip) -> files = files.concat clip next(files) else if opt._ ngist.files opt._, (err, files) -> spit_error err if err next(files) else if opt.clip get_clip (clip) -> next clip else spit_error 'You must set file(s) and/or a clip from the clipboard (-c)' next = (files) -> if opt.user and opt.token finish files, opt.user, opt.token else if (opt.user and not opt.token) or (opt.token and not opt.user) spit_error 'Both user (-u) and token (-t) must be set if you wish to login' else get_creds files finish = (files, user, token) -> if opt.desc or opt.private or (user and token) options = {} else options = null options.private = true if opt.private options.description = opt.desc if opt.desc options.user = user if user options.token = token if token ngist.send files, options, (err, url) -> spit_error err if err set_clip url if opt.out console.log "Gist: #{url}" get_creds = (files) -> keys = ['get', 'system', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] serial keys, (key, i, _next) -> exec "git config --#{key} github.user", (err, stdout, stderr) -> unless err user = stdout.replace("\n", "") exec "git config --#{key} github.token", (err, stdout, stderr) -> unless err token = stdout.replace("\n", "") return finish files, user, token else _next() , -> console.log "For instructions on how to authenticate your gists: ngist -h" return finish files, null, null set_clip = (url) -> switch os.type() when 'Darwin' then clipboard = "echo #{url} | pbcopy" when 'Linux' then clipboard = "echo #{url} | xclip" exec clipboard, (err, stdout) -> spit_error 'Problem sending url to clipboard' if err get_clip = (callback) -> clip = [] switch os.type() when 'Darwin' then clipboard = 'pbpaste' when 'Linux' then clipboard = 'xclip -out -selection clipboard' exec clipboard, (err, stdout) -> spit_error 'Nothing in clipboard' if stdout == '' spit_error 'Problem getting contents of clipboard' if err clip.push name: opt.clip contents: stdout callback clip spit_error = (err) -> console.error "#{err}\nFor more help see: ngist -h" process.exit 1 serial = (array, iterator, next) -> cycle = (i) -> if i < array.length iterator array[i], i, -> cycle i+1 else next() cycle 0 run()
[ { "context": "'''\nwatchOS : Scroll\n\n@auther Jungho song (threeword.com)\n@since 2016.11.23\n'''\nclass expor", "end": 41, "score": 0.9998558759689331, "start": 30, "tag": "NAME", "value": "Jungho song" } ]
modules/watchos-kit-scroll.coffee
framer-modules/watchos
2
''' watchOS : Scroll @auther Jungho song (threeword.com) @since 2016.11.23 ''' class exports.Scroll extends ScrollComponent ''' scrollbar: y: ''' defaultScrollbar = y: 42 # Constructor constructor: (options = {}) -> options.scrollHorizontal = false super options # Bar @scrollbar = new Layer name: "ScrollBar" x: Align.right(-5), y: Align.top(@_contentInset.top) width: 12, height: 75 borderRadius: 10 backgroundColor: "rgba(255,255,255,.25)" opacity: 0 parent: @ @scrollbar.states = show: opacity: 1, animationOptions: { time: .15 } # Thumb @scrollbar.thumb = new Layer name: ".thumb" x: Align.center, y: Align.top(1) width: 10, height: 36 borderRadius: 10 backgroundColor: "white" parent: @scrollbar # Event : Scroll Start - visible bar @onScrollStart => unless @scrollbar.thumb.height is 73 @scrollbar.animateStop() @scrollbar.animate "show" # Event : Scroll End - invisible bar @onScrollAnimationDidEnd => unless @scrollbar.thumb.height is 73 @scrollbar.animateStop() @scrollbar.animate "default" # Event : Move @onMove => min = 0 max = @content.height - @height + (@_contentInset.top + @_contentInset.bottom) @scrollbar.thumb.y = Utils.modulate @scrollY, [min, max], [1, 74 - @thumbHeight] # Anchor bottom if @scrollY <= min @scrollbar.thumb.height = Utils.clamp @thumbHeight + @scrollbar.thumb.y, 12, @thumbHeight @scrollbar.thumb.y = 1 # Anchor top else if @scrollY >= max @scrollbar.thumb.height = Utils.clamp 74 - @scrollbar.thumb.y, 12, @thumbHeight @scrollbar.thumb.y = 74 - 12 if @scrollbar.thumb.height <= 12 else @scrollbar.thumb.height = @thumbHeight # Update content updateContent: => super return unless @scrollbar # @thumbHeight = Utils.clamp (@scrollbar.height * @height / @content.draggable.constraints.height), 12, 73
165007
''' watchOS : Scroll @auther <NAME> (threeword.com) @since 2016.11.23 ''' class exports.Scroll extends ScrollComponent ''' scrollbar: y: ''' defaultScrollbar = y: 42 # Constructor constructor: (options = {}) -> options.scrollHorizontal = false super options # Bar @scrollbar = new Layer name: "ScrollBar" x: Align.right(-5), y: Align.top(@_contentInset.top) width: 12, height: 75 borderRadius: 10 backgroundColor: "rgba(255,255,255,.25)" opacity: 0 parent: @ @scrollbar.states = show: opacity: 1, animationOptions: { time: .15 } # Thumb @scrollbar.thumb = new Layer name: ".thumb" x: Align.center, y: Align.top(1) width: 10, height: 36 borderRadius: 10 backgroundColor: "white" parent: @scrollbar # Event : Scroll Start - visible bar @onScrollStart => unless @scrollbar.thumb.height is 73 @scrollbar.animateStop() @scrollbar.animate "show" # Event : Scroll End - invisible bar @onScrollAnimationDidEnd => unless @scrollbar.thumb.height is 73 @scrollbar.animateStop() @scrollbar.animate "default" # Event : Move @onMove => min = 0 max = @content.height - @height + (@_contentInset.top + @_contentInset.bottom) @scrollbar.thumb.y = Utils.modulate @scrollY, [min, max], [1, 74 - @thumbHeight] # Anchor bottom if @scrollY <= min @scrollbar.thumb.height = Utils.clamp @thumbHeight + @scrollbar.thumb.y, 12, @thumbHeight @scrollbar.thumb.y = 1 # Anchor top else if @scrollY >= max @scrollbar.thumb.height = Utils.clamp 74 - @scrollbar.thumb.y, 12, @thumbHeight @scrollbar.thumb.y = 74 - 12 if @scrollbar.thumb.height <= 12 else @scrollbar.thumb.height = @thumbHeight # Update content updateContent: => super return unless @scrollbar # @thumbHeight = Utils.clamp (@scrollbar.height * @height / @content.draggable.constraints.height), 12, 73
true
''' watchOS : Scroll @auther PI:NAME:<NAME>END_PI (threeword.com) @since 2016.11.23 ''' class exports.Scroll extends ScrollComponent ''' scrollbar: y: ''' defaultScrollbar = y: 42 # Constructor constructor: (options = {}) -> options.scrollHorizontal = false super options # Bar @scrollbar = new Layer name: "ScrollBar" x: Align.right(-5), y: Align.top(@_contentInset.top) width: 12, height: 75 borderRadius: 10 backgroundColor: "rgba(255,255,255,.25)" opacity: 0 parent: @ @scrollbar.states = show: opacity: 1, animationOptions: { time: .15 } # Thumb @scrollbar.thumb = new Layer name: ".thumb" x: Align.center, y: Align.top(1) width: 10, height: 36 borderRadius: 10 backgroundColor: "white" parent: @scrollbar # Event : Scroll Start - visible bar @onScrollStart => unless @scrollbar.thumb.height is 73 @scrollbar.animateStop() @scrollbar.animate "show" # Event : Scroll End - invisible bar @onScrollAnimationDidEnd => unless @scrollbar.thumb.height is 73 @scrollbar.animateStop() @scrollbar.animate "default" # Event : Move @onMove => min = 0 max = @content.height - @height + (@_contentInset.top + @_contentInset.bottom) @scrollbar.thumb.y = Utils.modulate @scrollY, [min, max], [1, 74 - @thumbHeight] # Anchor bottom if @scrollY <= min @scrollbar.thumb.height = Utils.clamp @thumbHeight + @scrollbar.thumb.y, 12, @thumbHeight @scrollbar.thumb.y = 1 # Anchor top else if @scrollY >= max @scrollbar.thumb.height = Utils.clamp 74 - @scrollbar.thumb.y, 12, @thumbHeight @scrollbar.thumb.y = 74 - 12 if @scrollbar.thumb.height <= 12 else @scrollbar.thumb.height = @thumbHeight # Update content updateContent: => super return unless @scrollbar # @thumbHeight = Utils.clamp (@scrollbar.height * @height / @content.draggable.constraints.height), 12, 73
[ { "context": "verview Prevent usage of UNSAFE_ methods\n# @author Sergei Startsev\n###\n'use strict'\n\n# -----------------------------", "end": 79, "score": 0.9998651146888733, "start": 64, "tag": "NAME", "value": "Sergei Startsev" } ]
src/tests/rules/no-unsafe.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Prevent usage of UNSAFE_ methods # @author Sergei Startsev ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require 'eslint-plugin-react/lib/rules/no-unsafe' {RuleTester} = require 'eslint' path = require 'path' errorMessage = (method, useInstead = 'componentDidMount') -> "#{method} is unsafe for use in async rendering. Update the component to use #{useInstead} instead. See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html." # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unsafe', rule, valid: [ code: ''' class Foo extends React.Component componentDidUpdate: -> render: -> ''' settings: react: version: '16.4.0' , code: ''' Foo = createReactClass componentDidUpdate: -> render: -> ''' settings: react: version: '16.4.0' , code: ''' class Foo extends Bar { UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> } ''' settings: react: version: '16.4.0' , code: ''' Foo = bar({ UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> }) ''' settings: react: version: '16.4.0' , code: ''' class Foo extends React.Component UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.2.0' , code: ''' Foo = createReactClass({ UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> }) ''' settings: react: version: '16.2.0' ] invalid: [ code: ''' class Foo extends React.Component UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.3.0' errors: [ message: errorMessage 'UNSAFE_componentWillMount' line: 1 column: 1 type: 'ClassDeclaration' , message: errorMessage( 'UNSAFE_componentWillReceiveProps' 'getDerivedStateFromProps' ) line: 1 column: 1 type: 'ClassDeclaration' , message: errorMessage 'UNSAFE_componentWillUpdate', 'componentDidUpdate' line: 1 column: 1 type: 'ClassDeclaration' ] , code: ''' Foo = createReactClass UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.3.0' errors: [ message: errorMessage 'UNSAFE_componentWillMount' line: 2 column: 3 type: 'ObjectExpression' , message: errorMessage( 'UNSAFE_componentWillReceiveProps' 'getDerivedStateFromProps' ) line: 2 column: 3 type: 'ObjectExpression' , message: errorMessage 'UNSAFE_componentWillUpdate', 'componentDidUpdate' line: 2 column: 3 type: 'ObjectExpression' ] ]
88230
###* # @fileoverview Prevent usage of UNSAFE_ methods # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require 'eslint-plugin-react/lib/rules/no-unsafe' {RuleTester} = require 'eslint' path = require 'path' errorMessage = (method, useInstead = 'componentDidMount') -> "#{method} is unsafe for use in async rendering. Update the component to use #{useInstead} instead. See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html." # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unsafe', rule, valid: [ code: ''' class Foo extends React.Component componentDidUpdate: -> render: -> ''' settings: react: version: '16.4.0' , code: ''' Foo = createReactClass componentDidUpdate: -> render: -> ''' settings: react: version: '16.4.0' , code: ''' class Foo extends Bar { UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> } ''' settings: react: version: '16.4.0' , code: ''' Foo = bar({ UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> }) ''' settings: react: version: '16.4.0' , code: ''' class Foo extends React.Component UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.2.0' , code: ''' Foo = createReactClass({ UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> }) ''' settings: react: version: '16.2.0' ] invalid: [ code: ''' class Foo extends React.Component UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.3.0' errors: [ message: errorMessage 'UNSAFE_componentWillMount' line: 1 column: 1 type: 'ClassDeclaration' , message: errorMessage( 'UNSAFE_componentWillReceiveProps' 'getDerivedStateFromProps' ) line: 1 column: 1 type: 'ClassDeclaration' , message: errorMessage 'UNSAFE_componentWillUpdate', 'componentDidUpdate' line: 1 column: 1 type: 'ClassDeclaration' ] , code: ''' Foo = createReactClass UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.3.0' errors: [ message: errorMessage 'UNSAFE_componentWillMount' line: 2 column: 3 type: 'ObjectExpression' , message: errorMessage( 'UNSAFE_componentWillReceiveProps' 'getDerivedStateFromProps' ) line: 2 column: 3 type: 'ObjectExpression' , message: errorMessage 'UNSAFE_componentWillUpdate', 'componentDidUpdate' line: 2 column: 3 type: 'ObjectExpression' ] ]
true
###* # @fileoverview Prevent usage of UNSAFE_ methods # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require 'eslint-plugin-react/lib/rules/no-unsafe' {RuleTester} = require 'eslint' path = require 'path' errorMessage = (method, useInstead = 'componentDidMount') -> "#{method} is unsafe for use in async rendering. Update the component to use #{useInstead} instead. See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html." # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unsafe', rule, valid: [ code: ''' class Foo extends React.Component componentDidUpdate: -> render: -> ''' settings: react: version: '16.4.0' , code: ''' Foo = createReactClass componentDidUpdate: -> render: -> ''' settings: react: version: '16.4.0' , code: ''' class Foo extends Bar { UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> } ''' settings: react: version: '16.4.0' , code: ''' Foo = bar({ UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> }) ''' settings: react: version: '16.4.0' , code: ''' class Foo extends React.Component UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.2.0' , code: ''' Foo = createReactClass({ UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> }) ''' settings: react: version: '16.2.0' ] invalid: [ code: ''' class Foo extends React.Component UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.3.0' errors: [ message: errorMessage 'UNSAFE_componentWillMount' line: 1 column: 1 type: 'ClassDeclaration' , message: errorMessage( 'UNSAFE_componentWillReceiveProps' 'getDerivedStateFromProps' ) line: 1 column: 1 type: 'ClassDeclaration' , message: errorMessage 'UNSAFE_componentWillUpdate', 'componentDidUpdate' line: 1 column: 1 type: 'ClassDeclaration' ] , code: ''' Foo = createReactClass UNSAFE_componentWillMount: -> UNSAFE_componentWillReceiveProps: -> UNSAFE_componentWillUpdate: -> ''' settings: react: version: '16.3.0' errors: [ message: errorMessage 'UNSAFE_componentWillMount' line: 2 column: 3 type: 'ObjectExpression' , message: errorMessage( 'UNSAFE_componentWillReceiveProps' 'getDerivedStateFromProps' ) line: 2 column: 3 type: 'ObjectExpression' , message: errorMessage 'UNSAFE_componentWillUpdate', 'componentDidUpdate' line: 2 column: 3 type: 'ObjectExpression' ] ]
[ { "context": "# Copyright (c) 2014 Michele Bini\n#\n# version \"0.2.2\"\n\n# MIT license\n\n{ htmlcup } =", "end": 33, "score": 0.9998624920845032, "start": 21, "tag": "NAME", "value": "Michele Bini" } ]
html2cup.coffee
rev22/html2cup
0
# Copyright (c) 2014 Michele Bini # # version "0.2.2" # MIT license { htmlcup } = require 'htmlcup' htmlcup = htmlcup.extendObject withPhpChunks: (chunks = {})-> orig = @ phpLib = require './phpLib' phpLib.chunks = chunks lib = orig.extendObject phpLib: phpLib origLib: orig printHtml: (x)-> @origLib.printHtml(@phpLib.dress(x)) quoteText: (x)-> @phpLib.dress(@origLib.quoteText(x)) phpChunk: (k, chunk)-> @autoSpace() unless @noAutoSpaceBefore unless chunk? chunk = @phpLib.chunks[k] unless chunk? throw "Could not find chuck with key #{k}" @origLib.printHtml chunk @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ phpIf0: -> @phpIf "0" phpIf: (x)-> @phpChunk null, "<?php if (#{x}): ?>" phpForeach: (x)-> @phpChunk null, "<?php foreach (#{x}): ?>" phpElseif: (x)-> @phpChunk null, "<?php elseif (#{x}): ?>" phpElse: -> @phpChunk null, "<?php else: ?>" phpEndif: -> @phpChunk null, "<?php endif; ?>" phpEndforeach: -> @phpChunk null, "<?php endforeach; ?>" php: (x)-> @phpLib.strip(x) lib.compileLib() _: (x)-> @nesting.spaced = 1 @printHtml x if x? @ self: (x)-> @[x + 'Self'] ? @ S: ()-> x = autoSpaceSelf: @self('autoSpace') noAutoSpace: true modApplyTag: (tag, f)-> @self('autoSpace').modApplyTag tag, f; @ x.__proto__ = @self('autoSpace') x SS: -> @Z.apply @, arguments Z: ()-> x = autoSpaceSelf: @self('autoSpace') noAutoSpaceAfter: true modApplyTag: (tag, f)-> @self('autoSpace').modApplyTag tag, f; @ x.__proto__ = @self('autoSpace') x _n: (x = "\n")-> @printHtml x @ modApply: (f)-> f.apply @; @ modApplyTag: (tag, f)-> oldNesting = @nesting try @nesting = level: oldNesting.level + 1 tag: tag parent: oldNesting spaced: oldNesting.spaced @modApply f finally oldNesting.spaced = @nesting.spaced @nesting = oldNesting @ nesting: level: 0 autoSpace: (justTest)-> return if @noAutoSpace return if @nesting.spaced spacing = "\n" + Array(@nesting.level + 1).join(" ") return spacing if justTest @_ spacing commentTag: (x)-> @autoSpace() unless @noAutoSpaceBefore @printHtml "<!--#{x}-->" @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ compileTag: (tagName, isVoid, isRawText) -> tag = { tagName, isVoid, isRawText }; (args...) -> @autoSpace() unless @noAutoSpaceBefore @printHtml "<#{tagName}" for arg in args if typeof arg is 'function' f = arg break if typeof arg is 'string' s = arg break for x,y of arg if y? and y isnt "" @printHtml " #{x}=\"#{@quoteText y}\"" else @printHtml " #{x}" @printHtml '>' if isVoid @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 return else @nesting.spaced = 0 if f @modApplyTag tag, f else if s? if isRawText @_ s else @_ @quoteTagText(s) else @nesting.spaced = 1 @autoSpace() @printHtml '</' + tagName + '>' @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ htmlcup = htmlcup.compileLib() module.exports = htmlcup
91424
# Copyright (c) 2014 <NAME> # # version "0.2.2" # MIT license { htmlcup } = require 'htmlcup' htmlcup = htmlcup.extendObject withPhpChunks: (chunks = {})-> orig = @ phpLib = require './phpLib' phpLib.chunks = chunks lib = orig.extendObject phpLib: phpLib origLib: orig printHtml: (x)-> @origLib.printHtml(@phpLib.dress(x)) quoteText: (x)-> @phpLib.dress(@origLib.quoteText(x)) phpChunk: (k, chunk)-> @autoSpace() unless @noAutoSpaceBefore unless chunk? chunk = @phpLib.chunks[k] unless chunk? throw "Could not find chuck with key #{k}" @origLib.printHtml chunk @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ phpIf0: -> @phpIf "0" phpIf: (x)-> @phpChunk null, "<?php if (#{x}): ?>" phpForeach: (x)-> @phpChunk null, "<?php foreach (#{x}): ?>" phpElseif: (x)-> @phpChunk null, "<?php elseif (#{x}): ?>" phpElse: -> @phpChunk null, "<?php else: ?>" phpEndif: -> @phpChunk null, "<?php endif; ?>" phpEndforeach: -> @phpChunk null, "<?php endforeach; ?>" php: (x)-> @phpLib.strip(x) lib.compileLib() _: (x)-> @nesting.spaced = 1 @printHtml x if x? @ self: (x)-> @[x + 'Self'] ? @ S: ()-> x = autoSpaceSelf: @self('autoSpace') noAutoSpace: true modApplyTag: (tag, f)-> @self('autoSpace').modApplyTag tag, f; @ x.__proto__ = @self('autoSpace') x SS: -> @Z.apply @, arguments Z: ()-> x = autoSpaceSelf: @self('autoSpace') noAutoSpaceAfter: true modApplyTag: (tag, f)-> @self('autoSpace').modApplyTag tag, f; @ x.__proto__ = @self('autoSpace') x _n: (x = "\n")-> @printHtml x @ modApply: (f)-> f.apply @; @ modApplyTag: (tag, f)-> oldNesting = @nesting try @nesting = level: oldNesting.level + 1 tag: tag parent: oldNesting spaced: oldNesting.spaced @modApply f finally oldNesting.spaced = @nesting.spaced @nesting = oldNesting @ nesting: level: 0 autoSpace: (justTest)-> return if @noAutoSpace return if @nesting.spaced spacing = "\n" + Array(@nesting.level + 1).join(" ") return spacing if justTest @_ spacing commentTag: (x)-> @autoSpace() unless @noAutoSpaceBefore @printHtml "<!--#{x}-->" @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ compileTag: (tagName, isVoid, isRawText) -> tag = { tagName, isVoid, isRawText }; (args...) -> @autoSpace() unless @noAutoSpaceBefore @printHtml "<#{tagName}" for arg in args if typeof arg is 'function' f = arg break if typeof arg is 'string' s = arg break for x,y of arg if y? and y isnt "" @printHtml " #{x}=\"#{@quoteText y}\"" else @printHtml " #{x}" @printHtml '>' if isVoid @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 return else @nesting.spaced = 0 if f @modApplyTag tag, f else if s? if isRawText @_ s else @_ @quoteTagText(s) else @nesting.spaced = 1 @autoSpace() @printHtml '</' + tagName + '>' @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ htmlcup = htmlcup.compileLib() module.exports = htmlcup
true
# Copyright (c) 2014 PI:NAME:<NAME>END_PI # # version "0.2.2" # MIT license { htmlcup } = require 'htmlcup' htmlcup = htmlcup.extendObject withPhpChunks: (chunks = {})-> orig = @ phpLib = require './phpLib' phpLib.chunks = chunks lib = orig.extendObject phpLib: phpLib origLib: orig printHtml: (x)-> @origLib.printHtml(@phpLib.dress(x)) quoteText: (x)-> @phpLib.dress(@origLib.quoteText(x)) phpChunk: (k, chunk)-> @autoSpace() unless @noAutoSpaceBefore unless chunk? chunk = @phpLib.chunks[k] unless chunk? throw "Could not find chuck with key #{k}" @origLib.printHtml chunk @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ phpIf0: -> @phpIf "0" phpIf: (x)-> @phpChunk null, "<?php if (#{x}): ?>" phpForeach: (x)-> @phpChunk null, "<?php foreach (#{x}): ?>" phpElseif: (x)-> @phpChunk null, "<?php elseif (#{x}): ?>" phpElse: -> @phpChunk null, "<?php else: ?>" phpEndif: -> @phpChunk null, "<?php endif; ?>" phpEndforeach: -> @phpChunk null, "<?php endforeach; ?>" php: (x)-> @phpLib.strip(x) lib.compileLib() _: (x)-> @nesting.spaced = 1 @printHtml x if x? @ self: (x)-> @[x + 'Self'] ? @ S: ()-> x = autoSpaceSelf: @self('autoSpace') noAutoSpace: true modApplyTag: (tag, f)-> @self('autoSpace').modApplyTag tag, f; @ x.__proto__ = @self('autoSpace') x SS: -> @Z.apply @, arguments Z: ()-> x = autoSpaceSelf: @self('autoSpace') noAutoSpaceAfter: true modApplyTag: (tag, f)-> @self('autoSpace').modApplyTag tag, f; @ x.__proto__ = @self('autoSpace') x _n: (x = "\n")-> @printHtml x @ modApply: (f)-> f.apply @; @ modApplyTag: (tag, f)-> oldNesting = @nesting try @nesting = level: oldNesting.level + 1 tag: tag parent: oldNesting spaced: oldNesting.spaced @modApply f finally oldNesting.spaced = @nesting.spaced @nesting = oldNesting @ nesting: level: 0 autoSpace: (justTest)-> return if @noAutoSpace return if @nesting.spaced spacing = "\n" + Array(@nesting.level + 1).join(" ") return spacing if justTest @_ spacing commentTag: (x)-> @autoSpace() unless @noAutoSpaceBefore @printHtml "<!--#{x}-->" @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ compileTag: (tagName, isVoid, isRawText) -> tag = { tagName, isVoid, isRawText }; (args...) -> @autoSpace() unless @noAutoSpaceBefore @printHtml "<#{tagName}" for arg in args if typeof arg is 'function' f = arg break if typeof arg is 'string' s = arg break for x,y of arg if y? and y isnt "" @printHtml " #{x}=\"#{@quoteText y}\"" else @printHtml " #{x}" @printHtml '>' if isVoid @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 return else @nesting.spaced = 0 if f @modApplyTag tag, f else if s? if isRawText @_ s else @_ @quoteTagText(s) else @nesting.spaced = 1 @autoSpace() @printHtml '</' + tagName + '>' @nesting.spaced = if @noAutoSpace or @noAutoSpaceAfter then 1 else 0 @ htmlcup = htmlcup.compileLib() module.exports = htmlcup
[ { "context": "=\n username: null\n email: null\n password: null\n code: null\n\n link: (scope, elem, attr, ctrl)", "end": 82, "score": 0.9988377690315247, "start": 78, "tag": "PASSWORD", "value": "null" }, { "context": "rective('thread', thread)\n .directive('username',...
h/js/directives.coffee
gnott/h
0
authentication = -> base = username: null email: null password: null code: null link: (scope, elem, attr, ctrl) -> angular.copy base, scope.model controller: [ '$scope', 'authentication', ($scope, authentication) -> $scope.$on '$reset', => angular.copy base, $scope.model $scope.submit = (form) -> angular.extend authentication, $scope.model return unless form.$valid authentication["$#{form.$name}"] -> $scope.$emit 'success', form.$name ] restrict: 'ACE' markdown = ['$filter', '$timeout', ($filter, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? input = elem.find('textarea') output = elem.find('div') # Re-render the markdown when the view needs updating. ctrl.$render = -> input.val (ctrl.$viewValue or '') scope.rendered = ($filter 'converter') (ctrl.$viewValue or '') # React to the changes to the text area input.bind 'blur change keyup', -> ctrl.$setViewValue input.val() scope.$digest() # Auto-focus the input box when the widget becomes editable. # Re-render when it becomes uneditable. scope.$watch 'readonly', (readonly) -> ctrl.$render() unless readonly then $timeout -> input.focus() require: '?ngModel' restrict: 'E' scope: readonly: '@' required: '@' templateUrl: 'markdown.html' ] privacy = -> levels = ['Public', 'Private'] link: (scope, elem, attrs, controller) -> return unless controller? controller.$formatters.push (permissions) -> return unless permissions? if 'group:__world__' in (permissions.read or []) 'Public' else 'Private' controller.$parsers.push (privacy) -> return unless privacy? permissions = controller.$modelValue if privacy is 'Public' if permissions.read unless 'group:__world__' in permissions.read permissions.read.push 'group:__world__' else permissions.read = ['group:__world__'] else read = permissions.read or [] read = (role for role in read when role isnt 'group:__world__') permissions.read = read permissions controller.$render = -> scope.level = controller.$viewValue scope.levels = levels scope.setLevel = (level) -> controller.$setViewValue level controller.$render() require: '?ngModel' restrict: 'E' scope: {} templateUrl: 'privacy.html' recursive = ['$compile', '$timeout', ($compile, $timeout) -> compile: (tElement, tAttrs, transclude) -> placeholder = angular.element '<!-- recursive -->' attachQueue = [] tick = false template = tElement.contents().clone() tElement.html '' transclude = $compile template, (scope, cloneAttachFn) -> clone = placeholder.clone() cloneAttachFn clone $timeout -> transclude scope, (el, scope) -> attachQueue.push [clone, el] unless tick tick = true requestAnimationFrame -> tick = false for [clone, el] in attachQueue clone.after el clone.bind '$destroy', -> el.remove() attachQueue = [] clone post: (scope, iElement, iAttrs, controller) -> transclude scope, (contents) -> iElement.append contents restrict: 'A' terminal: true ] resettable = -> compile: (tElement, tAttrs, transclude) -> post: (scope, iElement, iAttrs) -> reset = -> transclude scope, (el) -> iElement.replaceWith el iElement = el reset() scope.$on '$reset', reset priority: 5000 restrict: 'A' transclude: 'element' ### # The slow validation directive ties an to a model controller and hides # it while the model is being edited. This behavior improves the user # experience of filling out forms by delaying validation messages until # after the user has made a mistake. ### slowValidate = ['$parse', '$timeout', ($parse, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? promise = null elem.addClass 'slow-validate' ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) -> elem.removeClass 'slow-validate-show' if promise $timeout.cancel promise promise = null promise = $timeout -> elem.addClass 'slow-validate-show' require: '^form' restrict: 'A' ] tabReveal = ['$parse', ($parse) -> compile: (tElement, tAttrs, transclude) -> panes = [] hiddenPanesGet = $parse tAttrs.tabReveal pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> # Hijack the tabbable controller's addPane so that the visibility of the # secret ones can be managed. This avoids traversing the DOM to find # the tab panes. addPane = tabbable.addPane tabbable.addPane = (element, attr) => removePane = addPane.call tabbable, element, attr panes.push element: element attr: attr => for i in [0..panes.length] if panes[i].element is element panes.splice i, 1 break removePane() post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> tabs = angular.element(iElement.children()[0].childNodes) render = angular.bind ngModel, ngModel.$render ngModel.$render = -> render() hiddenPanes = hiddenPanesGet scope return unless angular.isArray hiddenPanes for i in [0..panes.length-1] pane = panes[i] value = pane.attr.value || pane.attr.title if value == ngModel.$viewValue pane.element.css 'display', '' angular.element(tabs[i]).css 'display', '' else if value in hiddenPanes pane.element.css 'display', 'none' angular.element(tabs[i]).css 'display', 'none' require: ['ngModel', 'tabbable'] ] thread = ['$rootScope', '$window', ($rootScope, $window) -> # Helper -- true if selection ends inside the target and is non-empty ignoreClick = (event) -> sel = $window.getSelection() if sel.focusNode?.compareDocumentPosition(event.target) & 8 if sel.toString().length return true return false link: (scope, elem, attr, ctrl) -> childrenEditing = {} # If this is supposed to be focused, then open it if scope.annotation in $rootScope.focused scope.collapsed = false scope.$on "focusChange", -> # XXX: This not needed to be done when the viewer and search will be unified ann = scope.annotation ? scope.thread.message if ann in $rootScope.focused scope.collapsed = false else unless ann.references?.length scope.collapsed = true scope.toggleCollapsed = (event) -> event.stopPropagation() return if (ignoreClick event) or Object.keys(childrenEditing).length scope.collapsed = !scope.collapsed # XXX: This not needed to be done when the viewer and search will be unified ann = scope.annotation ? scope.thread.message if scope.collapsed $rootScope.unFocus ann, true else scope.openDetails ann $rootScope.focus ann, true scope.$on 'toggleEditing', (event) -> {$id, editing} = event.targetScope if editing scope.collapsed = false unless childrenEditing[$id] event.targetScope.$on '$destroy', -> delete childrenEditing[$id] childrenEditing[$id] = true else delete childrenEditing[$id] restrict: 'C' ] userPicker = -> restrict: 'ACE' scope: model: '=userPickerModel' options: '=userPickerOptions' templateUrl: 'userPicker.html' repeatAnim = -> restrict: 'A' scope: array: '=' template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>' transclude: true controller: ($scope, $element, $attrs) -> $scope.runAnimOnLast = -> #Run anim on the item's element #(which will be last child of directive element) item=$scope.array[0] itemElm = jQuery($element) .children() .first() .children() unless item._anim? return if item._anim is 'fade' itemElm .css({ opacity: 0 }) .animate({ opacity: 1 }, 1500) else if item._anim is 'slide' itemElm .css({ 'margin-left': itemElm.width() }) .animate({ 'margin-left': '0px' }, 1500) return # Directive to edit/display a tag list. tags = ['$window', ($window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? elem.tagit caseSensitive: false placeholderText: attr.placeholder keepPlaceholder: true preprocessTag: (val) -> val.replace /[^a-zA-Z0-9\-\_\s]/g, '' afterTagAdded: (evt, ui) -> ctrl.$setViewValue elem.tagit 'assignedTags' afterTagRemoved: (evt, ui) -> ctrl.$setViewValue elem.tagit 'assignedTags' autocomplete: source: [] onTagClicked: (evt, ui) -> evt.stopPropagation() tag = ui.tagLabel $window.open "/t/" + tag ctrl.$formatters.push (tags=[]) -> assigned = elem.tagit 'assignedTags' for t in assigned when t not in tags elem.tagit 'removeTagByLabel', t for t in tags when t not in assigned elem.tagit 'createTag', t if assigned.length or not attr.readOnly then elem.show() else elem.hide() attr.$observe 'readonly', (readonly) -> tagInput = elem.find('input').last() assigned = elem.tagit 'assignedTags' if readonly tagInput.attr('disabled', true) tagInput.removeAttr('placeholder') if assigned.length then elem.show() else elem.hide() else tagInput.removeAttr('disabled') tagInput.attr('placeholder', attr['placeholder']) elem.show() require: '?ngModel' restrict: 'C' ] username = ['$filter', '$window', ($filter, $window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? ctrl.$render = -> scope.uname = ($filter 'userName') ctrl.$viewValue scope.uclick = (event) -> event.stopPropagation() $window.open "/u/" + scope.uname return require: '?ngModel' restrict: 'E' template: '<span class="user" ng-click="uclick($event)">{{uname}}</span>' ] fuzzytime = ['$filter', '$window', ($filter, $window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? elem .find('a') .bind 'click', (event) -> event.stopPropagation() .tooltip tooltipClass: 'small' position: collision: 'fit' at: "left center" ctrl.$render = -> scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue # Determining the timezone name timezone = jstz.determine().name() # The browser language userLang = navigator.language || navigator.userLanguage # Now to make a localized hint date, set the language momentDate = moment ctrl.$viewValue momentDate.lang(userLang) # Try to localize to the browser's timezone try scope.hint = momentDate.tz(timezone).format('LLLL') catch error # For invalid timezone, use the default scope.hint = momentDate.format('LLLL') toolparams = tooltipClass: 'small' position: collision: 'none' at: "left center" elem.tooltip(toolparams) timefunct = -> $window.setInterval => scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue scope.$digest() , 5000 scope.timer = timefunct() scope.$on '$destroy', -> $window.clearInterval scope.timer require: '?ngModel' restrict: 'E' scope: true template: '<a target="_blank" href="{{shared_link}}" title="{{hint}}">{{ftime | date:mediumDate}}</a>' ] streamviewer = [ -> link: (scope, elem, attr, ctrl) -> return unless ctrl? require: '?ngModel' restrict: 'E' templateUrl: 'streamviewer.html' ] whenscrolled = ['$window', ($window) -> link: (scope, elem, attr) -> $window = angular.element($window) $window.on 'scroll', -> windowBottom = $window.height() + $window.scrollTop() elementBottom = elem.offset().top + elem.height() remaining = elementBottom - windowBottom shouldScroll = remaining <= $window.height() * 0 if shouldScroll scope.$apply attr.whenscrolled ] angular.module('h.directives', ['ngSanitize']) .directive('authentication', authentication) .directive('fuzzytime', fuzzytime) .directive('markdown', markdown) .directive('privacy', privacy) .directive('recursive', recursive) .directive('resettable', resettable) .directive('slowValidate', slowValidate) .directive('tabReveal', tabReveal) .directive('tags', tags) .directive('thread', thread) .directive('username', username) .directive('userPicker', userPicker) .directive('repeatAnim', repeatAnim) .directive('streamviewer', streamviewer) .directive('whenscrolled', whenscrolled)
219072
authentication = -> base = username: null email: null password: <PASSWORD> code: null link: (scope, elem, attr, ctrl) -> angular.copy base, scope.model controller: [ '$scope', 'authentication', ($scope, authentication) -> $scope.$on '$reset', => angular.copy base, $scope.model $scope.submit = (form) -> angular.extend authentication, $scope.model return unless form.$valid authentication["$#{form.$name}"] -> $scope.$emit 'success', form.$name ] restrict: 'ACE' markdown = ['$filter', '$timeout', ($filter, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? input = elem.find('textarea') output = elem.find('div') # Re-render the markdown when the view needs updating. ctrl.$render = -> input.val (ctrl.$viewValue or '') scope.rendered = ($filter 'converter') (ctrl.$viewValue or '') # React to the changes to the text area input.bind 'blur change keyup', -> ctrl.$setViewValue input.val() scope.$digest() # Auto-focus the input box when the widget becomes editable. # Re-render when it becomes uneditable. scope.$watch 'readonly', (readonly) -> ctrl.$render() unless readonly then $timeout -> input.focus() require: '?ngModel' restrict: 'E' scope: readonly: '@' required: '@' templateUrl: 'markdown.html' ] privacy = -> levels = ['Public', 'Private'] link: (scope, elem, attrs, controller) -> return unless controller? controller.$formatters.push (permissions) -> return unless permissions? if 'group:__world__' in (permissions.read or []) 'Public' else 'Private' controller.$parsers.push (privacy) -> return unless privacy? permissions = controller.$modelValue if privacy is 'Public' if permissions.read unless 'group:__world__' in permissions.read permissions.read.push 'group:__world__' else permissions.read = ['group:__world__'] else read = permissions.read or [] read = (role for role in read when role isnt 'group:__world__') permissions.read = read permissions controller.$render = -> scope.level = controller.$viewValue scope.levels = levels scope.setLevel = (level) -> controller.$setViewValue level controller.$render() require: '?ngModel' restrict: 'E' scope: {} templateUrl: 'privacy.html' recursive = ['$compile', '$timeout', ($compile, $timeout) -> compile: (tElement, tAttrs, transclude) -> placeholder = angular.element '<!-- recursive -->' attachQueue = [] tick = false template = tElement.contents().clone() tElement.html '' transclude = $compile template, (scope, cloneAttachFn) -> clone = placeholder.clone() cloneAttachFn clone $timeout -> transclude scope, (el, scope) -> attachQueue.push [clone, el] unless tick tick = true requestAnimationFrame -> tick = false for [clone, el] in attachQueue clone.after el clone.bind '$destroy', -> el.remove() attachQueue = [] clone post: (scope, iElement, iAttrs, controller) -> transclude scope, (contents) -> iElement.append contents restrict: 'A' terminal: true ] resettable = -> compile: (tElement, tAttrs, transclude) -> post: (scope, iElement, iAttrs) -> reset = -> transclude scope, (el) -> iElement.replaceWith el iElement = el reset() scope.$on '$reset', reset priority: 5000 restrict: 'A' transclude: 'element' ### # The slow validation directive ties an to a model controller and hides # it while the model is being edited. This behavior improves the user # experience of filling out forms by delaying validation messages until # after the user has made a mistake. ### slowValidate = ['$parse', '$timeout', ($parse, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? promise = null elem.addClass 'slow-validate' ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) -> elem.removeClass 'slow-validate-show' if promise $timeout.cancel promise promise = null promise = $timeout -> elem.addClass 'slow-validate-show' require: '^form' restrict: 'A' ] tabReveal = ['$parse', ($parse) -> compile: (tElement, tAttrs, transclude) -> panes = [] hiddenPanesGet = $parse tAttrs.tabReveal pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> # Hijack the tabbable controller's addPane so that the visibility of the # secret ones can be managed. This avoids traversing the DOM to find # the tab panes. addPane = tabbable.addPane tabbable.addPane = (element, attr) => removePane = addPane.call tabbable, element, attr panes.push element: element attr: attr => for i in [0..panes.length] if panes[i].element is element panes.splice i, 1 break removePane() post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> tabs = angular.element(iElement.children()[0].childNodes) render = angular.bind ngModel, ngModel.$render ngModel.$render = -> render() hiddenPanes = hiddenPanesGet scope return unless angular.isArray hiddenPanes for i in [0..panes.length-1] pane = panes[i] value = pane.attr.value || pane.attr.title if value == ngModel.$viewValue pane.element.css 'display', '' angular.element(tabs[i]).css 'display', '' else if value in hiddenPanes pane.element.css 'display', 'none' angular.element(tabs[i]).css 'display', 'none' require: ['ngModel', 'tabbable'] ] thread = ['$rootScope', '$window', ($rootScope, $window) -> # Helper -- true if selection ends inside the target and is non-empty ignoreClick = (event) -> sel = $window.getSelection() if sel.focusNode?.compareDocumentPosition(event.target) & 8 if sel.toString().length return true return false link: (scope, elem, attr, ctrl) -> childrenEditing = {} # If this is supposed to be focused, then open it if scope.annotation in $rootScope.focused scope.collapsed = false scope.$on "focusChange", -> # XXX: This not needed to be done when the viewer and search will be unified ann = scope.annotation ? scope.thread.message if ann in $rootScope.focused scope.collapsed = false else unless ann.references?.length scope.collapsed = true scope.toggleCollapsed = (event) -> event.stopPropagation() return if (ignoreClick event) or Object.keys(childrenEditing).length scope.collapsed = !scope.collapsed # XXX: This not needed to be done when the viewer and search will be unified ann = scope.annotation ? scope.thread.message if scope.collapsed $rootScope.unFocus ann, true else scope.openDetails ann $rootScope.focus ann, true scope.$on 'toggleEditing', (event) -> {$id, editing} = event.targetScope if editing scope.collapsed = false unless childrenEditing[$id] event.targetScope.$on '$destroy', -> delete childrenEditing[$id] childrenEditing[$id] = true else delete childrenEditing[$id] restrict: 'C' ] userPicker = -> restrict: 'ACE' scope: model: '=userPickerModel' options: '=userPickerOptions' templateUrl: 'userPicker.html' repeatAnim = -> restrict: 'A' scope: array: '=' template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>' transclude: true controller: ($scope, $element, $attrs) -> $scope.runAnimOnLast = -> #Run anim on the item's element #(which will be last child of directive element) item=$scope.array[0] itemElm = jQuery($element) .children() .first() .children() unless item._anim? return if item._anim is 'fade' itemElm .css({ opacity: 0 }) .animate({ opacity: 1 }, 1500) else if item._anim is 'slide' itemElm .css({ 'margin-left': itemElm.width() }) .animate({ 'margin-left': '0px' }, 1500) return # Directive to edit/display a tag list. tags = ['$window', ($window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? elem.tagit caseSensitive: false placeholderText: attr.placeholder keepPlaceholder: true preprocessTag: (val) -> val.replace /[^a-zA-Z0-9\-\_\s]/g, '' afterTagAdded: (evt, ui) -> ctrl.$setViewValue elem.tagit 'assignedTags' afterTagRemoved: (evt, ui) -> ctrl.$setViewValue elem.tagit 'assignedTags' autocomplete: source: [] onTagClicked: (evt, ui) -> evt.stopPropagation() tag = ui.tagLabel $window.open "/t/" + tag ctrl.$formatters.push (tags=[]) -> assigned = elem.tagit 'assignedTags' for t in assigned when t not in tags elem.tagit 'removeTagByLabel', t for t in tags when t not in assigned elem.tagit 'createTag', t if assigned.length or not attr.readOnly then elem.show() else elem.hide() attr.$observe 'readonly', (readonly) -> tagInput = elem.find('input').last() assigned = elem.tagit 'assignedTags' if readonly tagInput.attr('disabled', true) tagInput.removeAttr('placeholder') if assigned.length then elem.show() else elem.hide() else tagInput.removeAttr('disabled') tagInput.attr('placeholder', attr['placeholder']) elem.show() require: '?ngModel' restrict: 'C' ] username = ['$filter', '$window', ($filter, $window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? ctrl.$render = -> scope.uname = ($filter 'userName') ctrl.$viewValue scope.uclick = (event) -> event.stopPropagation() $window.open "/u/" + scope.uname return require: '?ngModel' restrict: 'E' template: '<span class="user" ng-click="uclick($event)">{{uname}}</span>' ] fuzzytime = ['$filter', '$window', ($filter, $window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? elem .find('a') .bind 'click', (event) -> event.stopPropagation() .tooltip tooltipClass: 'small' position: collision: 'fit' at: "left center" ctrl.$render = -> scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue # Determining the timezone name timezone = jstz.determine().name() # The browser language userLang = navigator.language || navigator.userLanguage # Now to make a localized hint date, set the language momentDate = moment ctrl.$viewValue momentDate.lang(userLang) # Try to localize to the browser's timezone try scope.hint = momentDate.tz(timezone).format('LLLL') catch error # For invalid timezone, use the default scope.hint = momentDate.format('LLLL') toolparams = tooltipClass: 'small' position: collision: 'none' at: "left center" elem.tooltip(toolparams) timefunct = -> $window.setInterval => scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue scope.$digest() , 5000 scope.timer = timefunct() scope.$on '$destroy', -> $window.clearInterval scope.timer require: '?ngModel' restrict: 'E' scope: true template: '<a target="_blank" href="{{shared_link}}" title="{{hint}}">{{ftime | date:mediumDate}}</a>' ] streamviewer = [ -> link: (scope, elem, attr, ctrl) -> return unless ctrl? require: '?ngModel' restrict: 'E' templateUrl: 'streamviewer.html' ] whenscrolled = ['$window', ($window) -> link: (scope, elem, attr) -> $window = angular.element($window) $window.on 'scroll', -> windowBottom = $window.height() + $window.scrollTop() elementBottom = elem.offset().top + elem.height() remaining = elementBottom - windowBottom shouldScroll = remaining <= $window.height() * 0 if shouldScroll scope.$apply attr.whenscrolled ] angular.module('h.directives', ['ngSanitize']) .directive('authentication', authentication) .directive('fuzzytime', fuzzytime) .directive('markdown', markdown) .directive('privacy', privacy) .directive('recursive', recursive) .directive('resettable', resettable) .directive('slowValidate', slowValidate) .directive('tabReveal', tabReveal) .directive('tags', tags) .directive('thread', thread) .directive('username', username) .directive('userPicker', userPicker) .directive('repeatAnim', repeatAnim) .directive('streamviewer', streamviewer) .directive('whenscrolled', whenscrolled)
true
authentication = -> base = username: null email: null password: PI:PASSWORD:<PASSWORD>END_PI code: null link: (scope, elem, attr, ctrl) -> angular.copy base, scope.model controller: [ '$scope', 'authentication', ($scope, authentication) -> $scope.$on '$reset', => angular.copy base, $scope.model $scope.submit = (form) -> angular.extend authentication, $scope.model return unless form.$valid authentication["$#{form.$name}"] -> $scope.$emit 'success', form.$name ] restrict: 'ACE' markdown = ['$filter', '$timeout', ($filter, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? input = elem.find('textarea') output = elem.find('div') # Re-render the markdown when the view needs updating. ctrl.$render = -> input.val (ctrl.$viewValue or '') scope.rendered = ($filter 'converter') (ctrl.$viewValue or '') # React to the changes to the text area input.bind 'blur change keyup', -> ctrl.$setViewValue input.val() scope.$digest() # Auto-focus the input box when the widget becomes editable. # Re-render when it becomes uneditable. scope.$watch 'readonly', (readonly) -> ctrl.$render() unless readonly then $timeout -> input.focus() require: '?ngModel' restrict: 'E' scope: readonly: '@' required: '@' templateUrl: 'markdown.html' ] privacy = -> levels = ['Public', 'Private'] link: (scope, elem, attrs, controller) -> return unless controller? controller.$formatters.push (permissions) -> return unless permissions? if 'group:__world__' in (permissions.read or []) 'Public' else 'Private' controller.$parsers.push (privacy) -> return unless privacy? permissions = controller.$modelValue if privacy is 'Public' if permissions.read unless 'group:__world__' in permissions.read permissions.read.push 'group:__world__' else permissions.read = ['group:__world__'] else read = permissions.read or [] read = (role for role in read when role isnt 'group:__world__') permissions.read = read permissions controller.$render = -> scope.level = controller.$viewValue scope.levels = levels scope.setLevel = (level) -> controller.$setViewValue level controller.$render() require: '?ngModel' restrict: 'E' scope: {} templateUrl: 'privacy.html' recursive = ['$compile', '$timeout', ($compile, $timeout) -> compile: (tElement, tAttrs, transclude) -> placeholder = angular.element '<!-- recursive -->' attachQueue = [] tick = false template = tElement.contents().clone() tElement.html '' transclude = $compile template, (scope, cloneAttachFn) -> clone = placeholder.clone() cloneAttachFn clone $timeout -> transclude scope, (el, scope) -> attachQueue.push [clone, el] unless tick tick = true requestAnimationFrame -> tick = false for [clone, el] in attachQueue clone.after el clone.bind '$destroy', -> el.remove() attachQueue = [] clone post: (scope, iElement, iAttrs, controller) -> transclude scope, (contents) -> iElement.append contents restrict: 'A' terminal: true ] resettable = -> compile: (tElement, tAttrs, transclude) -> post: (scope, iElement, iAttrs) -> reset = -> transclude scope, (el) -> iElement.replaceWith el iElement = el reset() scope.$on '$reset', reset priority: 5000 restrict: 'A' transclude: 'element' ### # The slow validation directive ties an to a model controller and hides # it while the model is being edited. This behavior improves the user # experience of filling out forms by delaying validation messages until # after the user has made a mistake. ### slowValidate = ['$parse', '$timeout', ($parse, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? promise = null elem.addClass 'slow-validate' ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) -> elem.removeClass 'slow-validate-show' if promise $timeout.cancel promise promise = null promise = $timeout -> elem.addClass 'slow-validate-show' require: '^form' restrict: 'A' ] tabReveal = ['$parse', ($parse) -> compile: (tElement, tAttrs, transclude) -> panes = [] hiddenPanesGet = $parse tAttrs.tabReveal pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> # Hijack the tabbable controller's addPane so that the visibility of the # secret ones can be managed. This avoids traversing the DOM to find # the tab panes. addPane = tabbable.addPane tabbable.addPane = (element, attr) => removePane = addPane.call tabbable, element, attr panes.push element: element attr: attr => for i in [0..panes.length] if panes[i].element is element panes.splice i, 1 break removePane() post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> tabs = angular.element(iElement.children()[0].childNodes) render = angular.bind ngModel, ngModel.$render ngModel.$render = -> render() hiddenPanes = hiddenPanesGet scope return unless angular.isArray hiddenPanes for i in [0..panes.length-1] pane = panes[i] value = pane.attr.value || pane.attr.title if value == ngModel.$viewValue pane.element.css 'display', '' angular.element(tabs[i]).css 'display', '' else if value in hiddenPanes pane.element.css 'display', 'none' angular.element(tabs[i]).css 'display', 'none' require: ['ngModel', 'tabbable'] ] thread = ['$rootScope', '$window', ($rootScope, $window) -> # Helper -- true if selection ends inside the target and is non-empty ignoreClick = (event) -> sel = $window.getSelection() if sel.focusNode?.compareDocumentPosition(event.target) & 8 if sel.toString().length return true return false link: (scope, elem, attr, ctrl) -> childrenEditing = {} # If this is supposed to be focused, then open it if scope.annotation in $rootScope.focused scope.collapsed = false scope.$on "focusChange", -> # XXX: This not needed to be done when the viewer and search will be unified ann = scope.annotation ? scope.thread.message if ann in $rootScope.focused scope.collapsed = false else unless ann.references?.length scope.collapsed = true scope.toggleCollapsed = (event) -> event.stopPropagation() return if (ignoreClick event) or Object.keys(childrenEditing).length scope.collapsed = !scope.collapsed # XXX: This not needed to be done when the viewer and search will be unified ann = scope.annotation ? scope.thread.message if scope.collapsed $rootScope.unFocus ann, true else scope.openDetails ann $rootScope.focus ann, true scope.$on 'toggleEditing', (event) -> {$id, editing} = event.targetScope if editing scope.collapsed = false unless childrenEditing[$id] event.targetScope.$on '$destroy', -> delete childrenEditing[$id] childrenEditing[$id] = true else delete childrenEditing[$id] restrict: 'C' ] userPicker = -> restrict: 'ACE' scope: model: '=userPickerModel' options: '=userPickerOptions' templateUrl: 'userPicker.html' repeatAnim = -> restrict: 'A' scope: array: '=' template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>' transclude: true controller: ($scope, $element, $attrs) -> $scope.runAnimOnLast = -> #Run anim on the item's element #(which will be last child of directive element) item=$scope.array[0] itemElm = jQuery($element) .children() .first() .children() unless item._anim? return if item._anim is 'fade' itemElm .css({ opacity: 0 }) .animate({ opacity: 1 }, 1500) else if item._anim is 'slide' itemElm .css({ 'margin-left': itemElm.width() }) .animate({ 'margin-left': '0px' }, 1500) return # Directive to edit/display a tag list. tags = ['$window', ($window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? elem.tagit caseSensitive: false placeholderText: attr.placeholder keepPlaceholder: true preprocessTag: (val) -> val.replace /[^a-zA-Z0-9\-\_\s]/g, '' afterTagAdded: (evt, ui) -> ctrl.$setViewValue elem.tagit 'assignedTags' afterTagRemoved: (evt, ui) -> ctrl.$setViewValue elem.tagit 'assignedTags' autocomplete: source: [] onTagClicked: (evt, ui) -> evt.stopPropagation() tag = ui.tagLabel $window.open "/t/" + tag ctrl.$formatters.push (tags=[]) -> assigned = elem.tagit 'assignedTags' for t in assigned when t not in tags elem.tagit 'removeTagByLabel', t for t in tags when t not in assigned elem.tagit 'createTag', t if assigned.length or not attr.readOnly then elem.show() else elem.hide() attr.$observe 'readonly', (readonly) -> tagInput = elem.find('input').last() assigned = elem.tagit 'assignedTags' if readonly tagInput.attr('disabled', true) tagInput.removeAttr('placeholder') if assigned.length then elem.show() else elem.hide() else tagInput.removeAttr('disabled') tagInput.attr('placeholder', attr['placeholder']) elem.show() require: '?ngModel' restrict: 'C' ] username = ['$filter', '$window', ($filter, $window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? ctrl.$render = -> scope.uname = ($filter 'userName') ctrl.$viewValue scope.uclick = (event) -> event.stopPropagation() $window.open "/u/" + scope.uname return require: '?ngModel' restrict: 'E' template: '<span class="user" ng-click="uclick($event)">{{uname}}</span>' ] fuzzytime = ['$filter', '$window', ($filter, $window) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? elem .find('a') .bind 'click', (event) -> event.stopPropagation() .tooltip tooltipClass: 'small' position: collision: 'fit' at: "left center" ctrl.$render = -> scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue # Determining the timezone name timezone = jstz.determine().name() # The browser language userLang = navigator.language || navigator.userLanguage # Now to make a localized hint date, set the language momentDate = moment ctrl.$viewValue momentDate.lang(userLang) # Try to localize to the browser's timezone try scope.hint = momentDate.tz(timezone).format('LLLL') catch error # For invalid timezone, use the default scope.hint = momentDate.format('LLLL') toolparams = tooltipClass: 'small' position: collision: 'none' at: "left center" elem.tooltip(toolparams) timefunct = -> $window.setInterval => scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue scope.$digest() , 5000 scope.timer = timefunct() scope.$on '$destroy', -> $window.clearInterval scope.timer require: '?ngModel' restrict: 'E' scope: true template: '<a target="_blank" href="{{shared_link}}" title="{{hint}}">{{ftime | date:mediumDate}}</a>' ] streamviewer = [ -> link: (scope, elem, attr, ctrl) -> return unless ctrl? require: '?ngModel' restrict: 'E' templateUrl: 'streamviewer.html' ] whenscrolled = ['$window', ($window) -> link: (scope, elem, attr) -> $window = angular.element($window) $window.on 'scroll', -> windowBottom = $window.height() + $window.scrollTop() elementBottom = elem.offset().top + elem.height() remaining = elementBottom - windowBottom shouldScroll = remaining <= $window.height() * 0 if shouldScroll scope.$apply attr.whenscrolled ] angular.module('h.directives', ['ngSanitize']) .directive('authentication', authentication) .directive('fuzzytime', fuzzytime) .directive('markdown', markdown) .directive('privacy', privacy) .directive('recursive', recursive) .directive('resettable', resettable) .directive('slowValidate', slowValidate) .directive('tabReveal', tabReveal) .directive('tags', tags) .directive('thread', thread) .directive('username', username) .directive('userPicker', userPicker) .directive('repeatAnim', repeatAnim) .directive('streamviewer', streamviewer) .directive('whenscrolled', whenscrolled)
[ { "context": "me\"],\"findIn\":[\"Name\",\"Nickname\",\"Email\"],\"find\":\"Andre\"}')\n\n V1.Backbone.setDefaultRetriever(url: \"", "end": 1357, "score": 0.9914065599441528, "start": 1352, "tag": "NAME", "value": "Andre" }, { "context": " = new MemberSearch()\n search.fetc...
tests/V1.Backbone.Collection.Tests.coffee
versionone/V1.Backbone
1
V1 = require('../V1.Backbone') expect = require('chai').expect recorded = require('./recorded') deferred = require('JQDeferred') spy = require('sinon').spy makeFetcher = (queryChecker) -> spy (actualUrl, query) -> queryChecker(query) if queryChecker? deferred() describe "A V1.Backbone.Collection", -> describe "filtering a collection", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name"],"filter":["ParticipatesIn[AssetState!=\'Dead\'].Participants=\'Member:20\'"]}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name"] Teammates = V1.Backbone.Collection.extend model: Member queryOptions: filter: ["ParticipatesIn[AssetState!='Dead'].Participants='Member:20'"] mates = new Teammates() mates.fetch() describe "finding for a collection", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name"],"findIn":["Name","Nickname","Email"],"find":"Andre"}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name"] MemberSearch = V1.Backbone.Collection.extend model: Member queryOptions: findIn: ["Name", "Nickname", "Email"] search = new MemberSearch() search.fetch({"find":"Andre"}) describe "using WITH", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name","Email"],"with":{"$name":"Andre Agile","$email":"andre.agile@company.com"},"where":{"Name":"$name","Email":"$email"}}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name","Email"] MemberSearch = V1.Backbone.Collection.extend model: Member search = new MemberSearch() search.fetch("with": {"$name": "Andre Agile", "$email": "andre.agile@company.com"},"where": {"Name": "$name", "Email": "$email"}) describe "using WITH via queryOptions", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name","Email"],"filter":["Name=$name;Email=$email"],"with":{"$name":"Andre Agile","$email":"andre.agile@company.com"}}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name","Email"] MemberSearch = V1.Backbone.Collection.extend model: Member queryOptions: with: {"$name": "Andre Agile", "$email": "andre.agile@company.com"} filter: ["Name=$name;Email=$email"] search = new MemberSearch() search.fetch()
185716
V1 = require('../V1.Backbone') expect = require('chai').expect recorded = require('./recorded') deferred = require('JQDeferred') spy = require('sinon').spy makeFetcher = (queryChecker) -> spy (actualUrl, query) -> queryChecker(query) if queryChecker? deferred() describe "A V1.Backbone.Collection", -> describe "filtering a collection", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name"],"filter":["ParticipatesIn[AssetState!=\'Dead\'].Participants=\'Member:20\'"]}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name"] Teammates = V1.Backbone.Collection.extend model: Member queryOptions: filter: ["ParticipatesIn[AssetState!='Dead'].Participants='Member:20'"] mates = new Teammates() mates.fetch() describe "finding for a collection", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name"],"findIn":["Name","Nickname","Email"],"find":"<NAME>"}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name"] MemberSearch = V1.Backbone.Collection.extend model: Member queryOptions: findIn: ["Name", "Nickname", "Email"] search = new MemberSearch() search.fetch({"find":"<NAME>"}) describe "using WITH", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name","Email"],"with":{"$name":"<NAME>","$email":"<EMAIL>"},"where":{"Name":"$name","Email":"$email"}}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name","Email"] MemberSearch = V1.Backbone.Collection.extend model: Member search = new MemberSearch() search.fetch("with": {"$name": "<NAME>", "$email": "<EMAIL>"},"where": {"Name": "$name", "Email": "$email"}) describe "using WITH via queryOptions", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name","Email"],"filter":["Name=$name;Email=$email"],"with":{"$name":"<NAME>","$email":"<EMAIL>"}}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name","Email"] MemberSearch = V1.Backbone.Collection.extend model: Member queryOptions: with: {"$name": "<NAME>", "$email": "<EMAIL>"} filter: ["Name=$name;Email=$email"] search = new MemberSearch() search.fetch()
true
V1 = require('../V1.Backbone') expect = require('chai').expect recorded = require('./recorded') deferred = require('JQDeferred') spy = require('sinon').spy makeFetcher = (queryChecker) -> spy (actualUrl, query) -> queryChecker(query) if queryChecker? deferred() describe "A V1.Backbone.Collection", -> describe "filtering a collection", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name"],"filter":["ParticipatesIn[AssetState!=\'Dead\'].Participants=\'Member:20\'"]}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name"] Teammates = V1.Backbone.Collection.extend model: Member queryOptions: filter: ["ParticipatesIn[AssetState!='Dead'].Participants='Member:20'"] mates = new Teammates() mates.fetch() describe "finding for a collection", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name"],"findIn":["Name","Nickname","Email"],"find":"PI:NAME:<NAME>END_PI"}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name"] MemberSearch = V1.Backbone.Collection.extend model: Member queryOptions: findIn: ["Name", "Nickname", "Email"] search = new MemberSearch() search.fetch({"find":"PI:NAME:<NAME>END_PI"}) describe "using WITH", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name","Email"],"with":{"$name":"PI:NAME:<NAME>END_PI","$email":"PI:EMAIL:<EMAIL>END_PI"},"where":{"Name":"$name","Email":"$email"}}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name","Email"] MemberSearch = V1.Backbone.Collection.extend model: Member search = new MemberSearch() search.fetch("with": {"$name": "PI:NAME:<NAME>END_PI", "$email": "PI:EMAIL:<EMAIL>END_PI"},"where": {"Name": "$name", "Email": "$email"}) describe "using WITH via queryOptions", -> afterEach -> V1.Backbone.clearDefaultRetriever() it "should generate a correct query", -> fetch = makeFetcher (query) -> expect(query).to.equal('{"from":"Member","select":["Name","Email"],"filter":["Name=$name;Email=$email"],"with":{"$name":"PI:NAME:<NAME>END_PI","$email":"PI:EMAIL:<EMAIL>END_PI"}}') V1.Backbone.setDefaultRetriever(url: "url", fetch: fetch) Member = V1.Backbone.Model.extend queryOptions: assetType: "Member" schema: ["Name","Email"] MemberSearch = V1.Backbone.Collection.extend model: Member queryOptions: with: {"$name": "PI:NAME:<NAME>END_PI", "$email": "PI:EMAIL:<EMAIL>END_PI"} filter: ["Name=$name;Email=$email"] search = new MemberSearch() search.fetch()
[ { "context": " (options)->\n @storage = {}\n @storageKey = 'inputHistory'\n @options = options\n @h0 = if (s = @storag", "end": 95, "score": 0.7894008159637451, "start": 83, "tag": "KEY", "value": "inputHistory" } ]
app/assets/javascripts/input_history.js.coffee
phateio/phateio
19
class InputHistory constructor: (options)-> @storage = {} @storageKey = 'inputHistory' @options = options @h0 = if (s = @storage[@storageKey]) then s.split('\n') else [] # original history @h = @h0.concat(['']) # temporarily edited history @i = @h0.length # current index in history up: (event) -> $self = $(event.currentTarget) if @i > 0 @h[@i--] = $self.val() $self.val @h[@i] @options.up(event) if @options.up down: (event) -> $self = $(event.currentTarget) if @i < @h0.length @h[@i++] = $self.val() $self.val @h[@i] @options.down(event) if @options.down enter: (event) -> $self = $(event.currentTarget) @options.before_enter(event) if @options.before_enter if @i < @h0.length @h[@i] = @h0[@i] input_value = $self.val() if @i >= 0 and @i >= @h0.length - 1 and @h0[@h0.length - 1] is input_value @h[@h0.length] = '' else @h[@h0.length] = input_value @h.push '' @h0.push input_value @storage[@storageKey] = @h0.join '\n' @i = @h0.length @options.after_enter(event) if @options.after_enter $self.val('') $.fn.inputHistory = (options = {})-> input_history = new InputHistory(options) @keydown (event) => KEY_ENTER = 13 KEY_UP = 38 KEY_DOWN = 40 switch event.which when KEY_UP then input_history.up(event) when KEY_DOWN then input_history.down(event) when KEY_ENTER then input_history.enter(event)
2426
class InputHistory constructor: (options)-> @storage = {} @storageKey = '<KEY>' @options = options @h0 = if (s = @storage[@storageKey]) then s.split('\n') else [] # original history @h = @h0.concat(['']) # temporarily edited history @i = @h0.length # current index in history up: (event) -> $self = $(event.currentTarget) if @i > 0 @h[@i--] = $self.val() $self.val @h[@i] @options.up(event) if @options.up down: (event) -> $self = $(event.currentTarget) if @i < @h0.length @h[@i++] = $self.val() $self.val @h[@i] @options.down(event) if @options.down enter: (event) -> $self = $(event.currentTarget) @options.before_enter(event) if @options.before_enter if @i < @h0.length @h[@i] = @h0[@i] input_value = $self.val() if @i >= 0 and @i >= @h0.length - 1 and @h0[@h0.length - 1] is input_value @h[@h0.length] = '' else @h[@h0.length] = input_value @h.push '' @h0.push input_value @storage[@storageKey] = @h0.join '\n' @i = @h0.length @options.after_enter(event) if @options.after_enter $self.val('') $.fn.inputHistory = (options = {})-> input_history = new InputHistory(options) @keydown (event) => KEY_ENTER = 13 KEY_UP = 38 KEY_DOWN = 40 switch event.which when KEY_UP then input_history.up(event) when KEY_DOWN then input_history.down(event) when KEY_ENTER then input_history.enter(event)
true
class InputHistory constructor: (options)-> @storage = {} @storageKey = 'PI:KEY:<KEY>END_PI' @options = options @h0 = if (s = @storage[@storageKey]) then s.split('\n') else [] # original history @h = @h0.concat(['']) # temporarily edited history @i = @h0.length # current index in history up: (event) -> $self = $(event.currentTarget) if @i > 0 @h[@i--] = $self.val() $self.val @h[@i] @options.up(event) if @options.up down: (event) -> $self = $(event.currentTarget) if @i < @h0.length @h[@i++] = $self.val() $self.val @h[@i] @options.down(event) if @options.down enter: (event) -> $self = $(event.currentTarget) @options.before_enter(event) if @options.before_enter if @i < @h0.length @h[@i] = @h0[@i] input_value = $self.val() if @i >= 0 and @i >= @h0.length - 1 and @h0[@h0.length - 1] is input_value @h[@h0.length] = '' else @h[@h0.length] = input_value @h.push '' @h0.push input_value @storage[@storageKey] = @h0.join '\n' @i = @h0.length @options.after_enter(event) if @options.after_enter $self.val('') $.fn.inputHistory = (options = {})-> input_history = new InputHistory(options) @keydown (event) => KEY_ENTER = 13 KEY_UP = 38 KEY_DOWN = 40 switch event.which when KEY_UP then input_history.up(event) when KEY_DOWN then input_history.down(event) when KEY_ENTER then input_history.enter(event)
[ { "context": "\n#\n# Frontend main library\n#\n# 2017.07.21 coded by Hajime Oh-yake\n#\n#==============================================", "end": 139, "score": 0.9998812675476074, "start": 125, "tag": "NAME", "value": "Hajime Oh-yake" } ]
src/libs/frontend/main.coffee
digitarhythm/viewllerjs
0
#========================================================================= # # Frontend main library # # 2017.07.21 coded by Hajime Oh-yake # #========================================================================= GLOBAL = {} ORIGIN = node_origin LAPSEDTIME = Date.now() __ACTORLIST = [] #========================================================================= # remove element from Array #========================================================================= Array.remove = (xs) -> (x) -> xs.filter (_, i, arr) => i != arr.indexOf(x) #========================================================================= # debug write #========================================================================= echo = (a, b...) -> if (node_env == "develop") for data in b if (typeof(data) == 'object') data = JSON.stringify(data) a = a.replace('%@', data) console.log(a) #========================================================================= # format strings #========================================================================= sprintf = (a, b...) -> for data in b if (typeof(data) == 'object') data = JSON.stringify(data) match = a.match(/%0\d*@/) if (match?) repstr = match[0] num = parseInt(repstr.match(/\d+/)) zero ="" zero += "0" while (zero.length < num) data2 = (zero+data).substr(-num) a = a.replace(repstr, data2) else a = a.replace('%@', data) return a #========================================================================= # real copy for object #========================================================================= objCopy = (a)-> return Object.assign({}, a) #========================================================================= # rgba #========================================================================= CSSRGBA = (param, defvalue = undefined) -> if (!defvalue?) defvalue = red: 255 green: 255 blue: 255 alpha: 1.0 if (param?) red = if (param.red?) then param.red else defvalue.red green = if (param.green?) then param.green else defvalue.green blue = if (param.blue?) then param.blue else defvalue.blue alpha = if (param.alpha?) then param.alpha else defvalue.alpha else red = defvalue.red green = defvalue.green blue = defvalue.blue alpha = defvalue.alpha str = "rgba(#{red}, #{green}, #{blue}, #{alpha})" return str #========================================================================= # Color Object #========================================================================= FWColor = (r, g, b, a) -> return red: r green: g blue: b alpha: a #========================================================================= # create rect #========================================================================= FWRectMake = (x, y, w, h) -> origin = x: x y: y size = width: w height: h frame = origin: origin size: size return frame #========================================================================= # create range #========================================================================= FWRangeMake = (loc, len) -> range = location: loc length: len return range #========================================================================= # PATH search #========================================================================= FWSearchPathForDirectoriesInDomains = (kind)-> switch (kind) when "FWPictureDirectory" path = "public/picture" when "FWPublicDirectory" path = "public" when "FWLibraryDirectory" path = "library" else path = undefined return path #========================================================================= # API Access function #========================================================================= FWAPICALL = (param, func = undefined) -> type = param.type || 'POST' file = node_pkg+"/api/"+param.file endpoint = param.endpoint headers = param.headers data = JSON.stringify(param.data) if (typeof param.data == 'object') url = "#{window.origin}/#{file}/#{endpoint}" ### $.ajaxSetup type : type dataType: 'json' timeout : 30000 headers: 'pragma' : 'no-cache' 'Cache-Control' : 'no-cache' 'If-Modified-Since': 'Thu, 01 Jun 1970 00:00:00 GMT' $.ajax url:url headers: headers data: data .done (ret) -> func(ret) if (typeof(func) == "function") .fail (jqXHR, textStatus, errorThrown)-> func err: -1 message: textStatus ### axios method: type url: url responseType: 'json' .then (ret) => func(ret) if (typeof(func) == "function") .catch (e) => func err: -1 message: textStatus #========================================================================= # return toggle #========================================================================= toggle = (value) -> return !value #========================================================================= # execute a number of times #========================================================================= timesFunc = (num, func) -> for i in [0...num] func() #========================================================================= # escape HTML tag #========================================================================= escapeHTML = (s) -> escapeRules = "&": "&amp;" "\"": "&quot;" "<": "&lt;" ">": "&gt;" s.replace /[&"<>]/g, (c) -> escapeRules[c] #========================================================================= # boot proc #========================================================================= #$ -> window.onload = -> requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame window.requestAnimationFrame = requestAnimationFrame #========================================================================= # animation frame #========================================================================= __animationRequest = (func) -> func() window.requestAnimationFrame -> __animationRequest(func) __animationRequest -> LAPSEDTIME = Date.now() for id, obj of __ACTORLIST if (typeof(obj.behavior) == 'function') obj.behavior() ### $.Finger = pressDuration: 300 doubleTapInterval: 100 flickDuration: 150 motionThreshold: 5 $("html").css("width", "100%") $("html").css("height", "100%") $("html").css("overflow", "hidden") $("body").css("position", "absolute") $("body").css("top", "0px") $("body").css("left", "0px") $("body").css("right", "0px") $("body").css("bottom", "0px") $("body").css("overflow", "auto") ### document.body.style.position = "absolute" document.body.style.top = "0px" document.body.style.left = "0px" document.body.style.right = "0px" document.body.style.bottom = "0px" document.body.style.overflow = "auto" #$(document).on "contextmenu", (e) => document.addEventListener "contextmenu", (e) => e.preventDefault() return false frm = FWApplication.getBounds() main = new applicationMain(frm) mainelement = main.__viewSelector __ACTORLIST[main.UniqueID] = main main.borderWidth = 0.0 main.containment = true main.clipToBounds = true main.backgroundColor = FWColor(255, 255, 255, 1.0) main.__setFrame(frm) timer = false window.onresize = -> if (timer != false) clearTimeout(timer) timer = setTimeout -> frm = FWApplication.getBounds() #$(main.__viewSelector).css("width", frm.size.width) #$(main.__viewSelector).css("height", frm.size.height) document.getElementById(mainelement).stype.width = frm.size.width+"px" document.getElementById(mainelement).stype.height = frm.size.height+"px" main.didBrowserResize(frm) , 300 document.body.append(main.viewelement) main.setStyle() main.__bindGesture() main.__setTouches() GLOBAL['rootview'] = main main.didFinishLaunching()
172996
#========================================================================= # # Frontend main library # # 2017.07.21 coded by <NAME> # #========================================================================= GLOBAL = {} ORIGIN = node_origin LAPSEDTIME = Date.now() __ACTORLIST = [] #========================================================================= # remove element from Array #========================================================================= Array.remove = (xs) -> (x) -> xs.filter (_, i, arr) => i != arr.indexOf(x) #========================================================================= # debug write #========================================================================= echo = (a, b...) -> if (node_env == "develop") for data in b if (typeof(data) == 'object') data = JSON.stringify(data) a = a.replace('%@', data) console.log(a) #========================================================================= # format strings #========================================================================= sprintf = (a, b...) -> for data in b if (typeof(data) == 'object') data = JSON.stringify(data) match = a.match(/%0\d*@/) if (match?) repstr = match[0] num = parseInt(repstr.match(/\d+/)) zero ="" zero += "0" while (zero.length < num) data2 = (zero+data).substr(-num) a = a.replace(repstr, data2) else a = a.replace('%@', data) return a #========================================================================= # real copy for object #========================================================================= objCopy = (a)-> return Object.assign({}, a) #========================================================================= # rgba #========================================================================= CSSRGBA = (param, defvalue = undefined) -> if (!defvalue?) defvalue = red: 255 green: 255 blue: 255 alpha: 1.0 if (param?) red = if (param.red?) then param.red else defvalue.red green = if (param.green?) then param.green else defvalue.green blue = if (param.blue?) then param.blue else defvalue.blue alpha = if (param.alpha?) then param.alpha else defvalue.alpha else red = defvalue.red green = defvalue.green blue = defvalue.blue alpha = defvalue.alpha str = "rgba(#{red}, #{green}, #{blue}, #{alpha})" return str #========================================================================= # Color Object #========================================================================= FWColor = (r, g, b, a) -> return red: r green: g blue: b alpha: a #========================================================================= # create rect #========================================================================= FWRectMake = (x, y, w, h) -> origin = x: x y: y size = width: w height: h frame = origin: origin size: size return frame #========================================================================= # create range #========================================================================= FWRangeMake = (loc, len) -> range = location: loc length: len return range #========================================================================= # PATH search #========================================================================= FWSearchPathForDirectoriesInDomains = (kind)-> switch (kind) when "FWPictureDirectory" path = "public/picture" when "FWPublicDirectory" path = "public" when "FWLibraryDirectory" path = "library" else path = undefined return path #========================================================================= # API Access function #========================================================================= FWAPICALL = (param, func = undefined) -> type = param.type || 'POST' file = node_pkg+"/api/"+param.file endpoint = param.endpoint headers = param.headers data = JSON.stringify(param.data) if (typeof param.data == 'object') url = "#{window.origin}/#{file}/#{endpoint}" ### $.ajaxSetup type : type dataType: 'json' timeout : 30000 headers: 'pragma' : 'no-cache' 'Cache-Control' : 'no-cache' 'If-Modified-Since': 'Thu, 01 Jun 1970 00:00:00 GMT' $.ajax url:url headers: headers data: data .done (ret) -> func(ret) if (typeof(func) == "function") .fail (jqXHR, textStatus, errorThrown)-> func err: -1 message: textStatus ### axios method: type url: url responseType: 'json' .then (ret) => func(ret) if (typeof(func) == "function") .catch (e) => func err: -1 message: textStatus #========================================================================= # return toggle #========================================================================= toggle = (value) -> return !value #========================================================================= # execute a number of times #========================================================================= timesFunc = (num, func) -> for i in [0...num] func() #========================================================================= # escape HTML tag #========================================================================= escapeHTML = (s) -> escapeRules = "&": "&amp;" "\"": "&quot;" "<": "&lt;" ">": "&gt;" s.replace /[&"<>]/g, (c) -> escapeRules[c] #========================================================================= # boot proc #========================================================================= #$ -> window.onload = -> requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame window.requestAnimationFrame = requestAnimationFrame #========================================================================= # animation frame #========================================================================= __animationRequest = (func) -> func() window.requestAnimationFrame -> __animationRequest(func) __animationRequest -> LAPSEDTIME = Date.now() for id, obj of __ACTORLIST if (typeof(obj.behavior) == 'function') obj.behavior() ### $.Finger = pressDuration: 300 doubleTapInterval: 100 flickDuration: 150 motionThreshold: 5 $("html").css("width", "100%") $("html").css("height", "100%") $("html").css("overflow", "hidden") $("body").css("position", "absolute") $("body").css("top", "0px") $("body").css("left", "0px") $("body").css("right", "0px") $("body").css("bottom", "0px") $("body").css("overflow", "auto") ### document.body.style.position = "absolute" document.body.style.top = "0px" document.body.style.left = "0px" document.body.style.right = "0px" document.body.style.bottom = "0px" document.body.style.overflow = "auto" #$(document).on "contextmenu", (e) => document.addEventListener "contextmenu", (e) => e.preventDefault() return false frm = FWApplication.getBounds() main = new applicationMain(frm) mainelement = main.__viewSelector __ACTORLIST[main.UniqueID] = main main.borderWidth = 0.0 main.containment = true main.clipToBounds = true main.backgroundColor = FWColor(255, 255, 255, 1.0) main.__setFrame(frm) timer = false window.onresize = -> if (timer != false) clearTimeout(timer) timer = setTimeout -> frm = FWApplication.getBounds() #$(main.__viewSelector).css("width", frm.size.width) #$(main.__viewSelector).css("height", frm.size.height) document.getElementById(mainelement).stype.width = frm.size.width+"px" document.getElementById(mainelement).stype.height = frm.size.height+"px" main.didBrowserResize(frm) , 300 document.body.append(main.viewelement) main.setStyle() main.__bindGesture() main.__setTouches() GLOBAL['rootview'] = main main.didFinishLaunching()
true
#========================================================================= # # Frontend main library # # 2017.07.21 coded by PI:NAME:<NAME>END_PI # #========================================================================= GLOBAL = {} ORIGIN = node_origin LAPSEDTIME = Date.now() __ACTORLIST = [] #========================================================================= # remove element from Array #========================================================================= Array.remove = (xs) -> (x) -> xs.filter (_, i, arr) => i != arr.indexOf(x) #========================================================================= # debug write #========================================================================= echo = (a, b...) -> if (node_env == "develop") for data in b if (typeof(data) == 'object') data = JSON.stringify(data) a = a.replace('%@', data) console.log(a) #========================================================================= # format strings #========================================================================= sprintf = (a, b...) -> for data in b if (typeof(data) == 'object') data = JSON.stringify(data) match = a.match(/%0\d*@/) if (match?) repstr = match[0] num = parseInt(repstr.match(/\d+/)) zero ="" zero += "0" while (zero.length < num) data2 = (zero+data).substr(-num) a = a.replace(repstr, data2) else a = a.replace('%@', data) return a #========================================================================= # real copy for object #========================================================================= objCopy = (a)-> return Object.assign({}, a) #========================================================================= # rgba #========================================================================= CSSRGBA = (param, defvalue = undefined) -> if (!defvalue?) defvalue = red: 255 green: 255 blue: 255 alpha: 1.0 if (param?) red = if (param.red?) then param.red else defvalue.red green = if (param.green?) then param.green else defvalue.green blue = if (param.blue?) then param.blue else defvalue.blue alpha = if (param.alpha?) then param.alpha else defvalue.alpha else red = defvalue.red green = defvalue.green blue = defvalue.blue alpha = defvalue.alpha str = "rgba(#{red}, #{green}, #{blue}, #{alpha})" return str #========================================================================= # Color Object #========================================================================= FWColor = (r, g, b, a) -> return red: r green: g blue: b alpha: a #========================================================================= # create rect #========================================================================= FWRectMake = (x, y, w, h) -> origin = x: x y: y size = width: w height: h frame = origin: origin size: size return frame #========================================================================= # create range #========================================================================= FWRangeMake = (loc, len) -> range = location: loc length: len return range #========================================================================= # PATH search #========================================================================= FWSearchPathForDirectoriesInDomains = (kind)-> switch (kind) when "FWPictureDirectory" path = "public/picture" when "FWPublicDirectory" path = "public" when "FWLibraryDirectory" path = "library" else path = undefined return path #========================================================================= # API Access function #========================================================================= FWAPICALL = (param, func = undefined) -> type = param.type || 'POST' file = node_pkg+"/api/"+param.file endpoint = param.endpoint headers = param.headers data = JSON.stringify(param.data) if (typeof param.data == 'object') url = "#{window.origin}/#{file}/#{endpoint}" ### $.ajaxSetup type : type dataType: 'json' timeout : 30000 headers: 'pragma' : 'no-cache' 'Cache-Control' : 'no-cache' 'If-Modified-Since': 'Thu, 01 Jun 1970 00:00:00 GMT' $.ajax url:url headers: headers data: data .done (ret) -> func(ret) if (typeof(func) == "function") .fail (jqXHR, textStatus, errorThrown)-> func err: -1 message: textStatus ### axios method: type url: url responseType: 'json' .then (ret) => func(ret) if (typeof(func) == "function") .catch (e) => func err: -1 message: textStatus #========================================================================= # return toggle #========================================================================= toggle = (value) -> return !value #========================================================================= # execute a number of times #========================================================================= timesFunc = (num, func) -> for i in [0...num] func() #========================================================================= # escape HTML tag #========================================================================= escapeHTML = (s) -> escapeRules = "&": "&amp;" "\"": "&quot;" "<": "&lt;" ">": "&gt;" s.replace /[&"<>]/g, (c) -> escapeRules[c] #========================================================================= # boot proc #========================================================================= #$ -> window.onload = -> requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame window.requestAnimationFrame = requestAnimationFrame #========================================================================= # animation frame #========================================================================= __animationRequest = (func) -> func() window.requestAnimationFrame -> __animationRequest(func) __animationRequest -> LAPSEDTIME = Date.now() for id, obj of __ACTORLIST if (typeof(obj.behavior) == 'function') obj.behavior() ### $.Finger = pressDuration: 300 doubleTapInterval: 100 flickDuration: 150 motionThreshold: 5 $("html").css("width", "100%") $("html").css("height", "100%") $("html").css("overflow", "hidden") $("body").css("position", "absolute") $("body").css("top", "0px") $("body").css("left", "0px") $("body").css("right", "0px") $("body").css("bottom", "0px") $("body").css("overflow", "auto") ### document.body.style.position = "absolute" document.body.style.top = "0px" document.body.style.left = "0px" document.body.style.right = "0px" document.body.style.bottom = "0px" document.body.style.overflow = "auto" #$(document).on "contextmenu", (e) => document.addEventListener "contextmenu", (e) => e.preventDefault() return false frm = FWApplication.getBounds() main = new applicationMain(frm) mainelement = main.__viewSelector __ACTORLIST[main.UniqueID] = main main.borderWidth = 0.0 main.containment = true main.clipToBounds = true main.backgroundColor = FWColor(255, 255, 255, 1.0) main.__setFrame(frm) timer = false window.onresize = -> if (timer != false) clearTimeout(timer) timer = setTimeout -> frm = FWApplication.getBounds() #$(main.__viewSelector).css("width", frm.size.width) #$(main.__viewSelector).css("height", frm.size.height) document.getElementById(mainelement).stype.width = frm.size.width+"px" document.getElementById(mainelement).stype.height = frm.size.height+"px" main.didBrowserResize(frm) , 300 document.body.append(main.viewelement) main.setStyle() main.__bindGesture() main.__setTouches() GLOBAL['rootview'] = main main.didFinishLaunching()
[ { "context": "he latest English versions:\n## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascri", "end": 185, "score": 0.9885407090187073, "start": 175, "tag": "USERNAME", "value": "uploadcare" }, { "context": "n'\n upload: 'Không thể tải lên'\n ...
app/assets/javascripts/uploadcare/locale/vi.js.coffee
bartclaeys/uploadcare-widget
1
## ## Please, do not use this locale as a reference for new translations. ## It could be outdated or incomplete. Always use the latest English versions: ## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee ## ## Any fixes are welcome. ## uploadcare.namespace 'locale.translations', (ns) -> ns.vi = loadingInfo: 'Đang tải thông tin...' errors: default: 'Lỗi' baddata: 'Giá trị không đúng' size: 'Tệp quá lớn' upload: 'Không thể tải lên' user: 'Tải lên bị hủy' info: 'Không thể nạp thông tin' image: 'Chỉ cho phép các hình ảnh' createGroup: 'Không thể tạo nhóm tệp' deleted: 'Tệp đã bị xóa' uploading: 'Đang tải lên... Vui lòng chờ đợi.' draghere: 'Thả một tệp vào đây' file: other: '%1 tệp' buttons: cancel: 'Hủy' remove: 'Xóa' choose: files: other: 'Lựa chọn các tệp' images: other: 'Lựa chọn hình ảnh' dialog: close: 'Đóng' openMenu: 'Mở menu' done: 'Xong' showFiles: 'Hiển thị tệp' tabs: names: 'empty-pubkey': 'Chào mừng' preview: 'Xem trước' file: 'Các tệp trên máy' url: 'Liên kết tr.tiếp' camera: 'Máy ảnh' facebook: 'Facebook' dropbox: 'Dropbox' gdrive: 'Google Drive' instagram: 'Instagram' gphotos: 'Google Photos' vk: 'VK' evernote: 'Evernote' box: 'Box' skydrive: 'OneDrive' flickr: 'Flickr' huddle: 'Huddle' file: drag: 'kéo & thả<br>bất kỳ tệp nào' nodrop: 'Tải lên các tệp từ &nbsp;máy tính của bạn' cloudsTip: 'Lưu trữ Đám mây<br>và các mạng xã hội' or: 'hoặc' button: 'Lựa chọn một tệp trên máy' also: 'hoặc lựa chọn từ' url: title: 'Các tệp trên Web' line1: 'Chọn bất từ tệp nào từ web.' line2: 'Chỉ cần cung cấp liên kết.' input: 'Dán liên kết của bạn xuống đây...' button: 'Tải lên' camera: title: 'Tệp từ web cam' capture: 'Chụp một bức ảnh' mirror: 'Gương' startRecord: 'Quay một video' cancelRecord: 'Hủy' stopRecord: 'Dừng' retry: 'Yêu cầu cấp phép lần nữa' pleaseAllow: text: 'Bạn đã được nhắc nhở để cho phép truy cập vào camera từ trang này.<br>Để có thể chụp ảnh với camera, bạn phải chấp thuận yêu cầu này.' title: 'Vui lòng cho phép truy cập tới camera của bạn' notFound: title: 'Không tìm thấy camera nào' text: 'Có vẻ như bạn không có camera nào nối với thiết bị này.' preview: unknownName: 'vô danh' change: 'Hủy' back: 'Quay lại' done: 'Thêm' unknown: title: 'Đang tải lên...Vui lòng đợi để xem trước.' done: 'Bỏ qua và chấp nhận' regular: title: 'Thêm tệp này?' line1: 'Bạn dự định thêm tệp ở trên.' line2: 'Vui lòng chấp thuận.' image: title: 'Thêm hình ảnh này?' change: 'Hủy' crop: title: 'Cắt và thêm ảnh này' done: 'Xong' free: 'miễn phí' video: title: 'Thêm video này?' change: 'Hủy' error: default: title: 'Ồ!' back: 'Vui lòng thử lại' text: 'Có lỗi gì đó trong quá trình tải lên.' image: title: 'Chỉ chấp thuận các tệp hình ảnh.' text: 'Vui lòng thử lại với một tệp mới.' back: 'Lựa chọn hình ảnh' size: title: 'Tệp bạn đã lựa chọn vượt quá giới hạn' text: 'Vui lòng thử lại với một tệp khác.' loadImage: title: 'Lỗi' text: 'Không thể tải hình ảnh' multiple: title: 'Bạn đã lựa chọn %files%' question: 'Thêm %files%?' tooManyFiles: 'Bạn đã lựa chọn quá nhiều tệp. %max% là tối đa.' tooFewFiles: 'Bạn đã lựa chọn %files%. Ít nhất cần %min%' clear: 'Xoá Tất cả' file: preview: 'Xem trước %file%' remove: 'Xóa %file%' done: 'Thêm' footer: text: 'được hỗ trợ bởi' link: 'uploadcare' # Pluralization rules taken from: # http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html uploadcare.namespace 'locale.pluralize', (ns) -> ns.vi = (n) -> return 'other'
149182
## ## Please, do not use this locale as a reference for new translations. ## It could be outdated or incomplete. Always use the latest English versions: ## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee ## ## Any fixes are welcome. ## uploadcare.namespace 'locale.translations', (ns) -> ns.vi = loadingInfo: 'Đang tải thông tin...' errors: default: 'Lỗi' baddata: 'Giá trị không đúng' size: 'Tệp quá lớn' upload: 'Không thể tải lên' user: '<NAME>' info: 'Không thể nạp thông tin' image: 'Chỉ cho phép các hình ảnh' createGroup: 'Không thể tạo nhóm tệp' deleted: 'Tệp đã bị xóa' uploading: 'Đang tải lên... Vui lòng chờ đợi.' draghere: 'Thả một tệp vào đây' file: other: '%1 tệp' buttons: cancel: 'Hủy' remove: 'Xóa' choose: files: other: 'Lựa chọn các tệp' images: other: 'Lựa chọn hình ảnh' dialog: close: 'Đóng' openMenu: 'Mở menu' done: 'Xong' showFiles: 'Hiển thị tệp' tabs: names: 'empty-pubkey': 'Chào mừng' preview: 'Xem trước' file: 'Các tệp trên máy' url: 'Liên kết tr.tiếp' camera: 'Máy ảnh' facebook: 'Facebook' dropbox: 'Dropbox' gdrive: 'Google Drive' instagram: 'Instagram' gphotos: 'Google Photos' vk: 'VK' evernote: '<NAME>' box: 'Box' skydrive: 'OneDrive' flickr: 'Flickr' huddle: 'Huddle' file: drag: 'kéo & thả<br>bất kỳ tệp nào' nodrop: 'Tải lên các tệp từ &nbsp;máy tính của bạn' cloudsTip: 'Lưu trữ Đám mây<br>và các mạng xã hội' or: 'hoặc' button: 'Lựa chọn một tệp trên máy' also: 'hoặc lựa chọn từ' url: title: 'Các tệp trên Web' line1: 'Chọn bất từ tệp nào từ web.' line2: 'Chỉ cần cung cấp liên kết.' input: 'Dán liên kết của bạn xuống đây...' button: 'Tải lên' camera: title: 'Tệp từ web cam' capture: 'Chụp một bức ảnh' mirror: 'Gương' startRecord: 'Quay một video' cancelRecord: 'Hủy' stopRecord: 'Dừng' retry: 'Yêu cầu cấp phép lần nữa' pleaseAllow: text: 'Bạn đã được nhắc nhở để cho phép truy cập vào camera từ trang này.<br>Để có thể chụp ảnh với camera, bạn phải chấp thuận yêu cầu này.' title: 'Vui lòng cho phép truy cập tới camera của bạn' notFound: title: 'Không tìm thấy camera nào' text: 'Có vẻ như bạn không có camera nào nối với thiết bị này.' preview: unknownName: '<NAME>' change: 'Hủy' back: 'Quay lại' done: 'Thêm' unknown: title: 'Đang tải lên...Vui lòng đợi để xem trước.' done: 'Bỏ qua và chấp nhận' regular: title: 'Thêm tệp này?' line1: 'Bạn dự định thêm tệp ở trên.' line2: 'Vui lòng chấp thuận.' image: title: 'Thêm hình ảnh này?' change: 'Hủy' crop: title: 'Cắt và thêm ảnh này' done: 'Xong' free: 'miễn phí' video: title: 'Thêm video này?' change: 'Hủy' error: default: title: 'Ồ!' back: 'Vui lòng thử lại' text: 'Có lỗi gì đó trong quá trình tải lên.' image: title: 'Chỉ chấp thuận các tệp hình ảnh.' text: 'Vui lòng thử lại với một tệp mới.' back: 'Lựa chọn hình ảnh' size: title: 'Tệp bạn đã lựa chọn vượt quá giới hạn' text: 'Vui lòng thử lại với một tệp khác.' loadImage: title: 'Lỗi' text: 'Không thể tải hình ảnh' multiple: title: 'Bạn đã lựa chọn %files%' question: 'Thêm %files%?' tooManyFiles: 'Bạn đã lựa chọn quá nhiều tệp. %max% là tối đa.' tooFewFiles: 'Bạn đã lựa chọn %files%. Ít nhất cần %min%' clear: 'Xoá Tất cả' file: preview: 'Xem trước %file%' remove: 'Xóa %file%' done: 'Thêm' footer: text: 'được hỗ trợ bởi' link: 'uploadcare' # Pluralization rules taken from: # http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html uploadcare.namespace 'locale.pluralize', (ns) -> ns.vi = (n) -> return 'other'
true
## ## Please, do not use this locale as a reference for new translations. ## It could be outdated or incomplete. Always use the latest English versions: ## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee ## ## Any fixes are welcome. ## uploadcare.namespace 'locale.translations', (ns) -> ns.vi = loadingInfo: 'Đang tải thông tin...' errors: default: 'Lỗi' baddata: 'Giá trị không đúng' size: 'Tệp quá lớn' upload: 'Không thể tải lên' user: 'PI:NAME:<NAME>END_PI' info: 'Không thể nạp thông tin' image: 'Chỉ cho phép các hình ảnh' createGroup: 'Không thể tạo nhóm tệp' deleted: 'Tệp đã bị xóa' uploading: 'Đang tải lên... Vui lòng chờ đợi.' draghere: 'Thả một tệp vào đây' file: other: '%1 tệp' buttons: cancel: 'Hủy' remove: 'Xóa' choose: files: other: 'Lựa chọn các tệp' images: other: 'Lựa chọn hình ảnh' dialog: close: 'Đóng' openMenu: 'Mở menu' done: 'Xong' showFiles: 'Hiển thị tệp' tabs: names: 'empty-pubkey': 'Chào mừng' preview: 'Xem trước' file: 'Các tệp trên máy' url: 'Liên kết tr.tiếp' camera: 'Máy ảnh' facebook: 'Facebook' dropbox: 'Dropbox' gdrive: 'Google Drive' instagram: 'Instagram' gphotos: 'Google Photos' vk: 'VK' evernote: 'PI:NAME:<NAME>END_PI' box: 'Box' skydrive: 'OneDrive' flickr: 'Flickr' huddle: 'Huddle' file: drag: 'kéo & thả<br>bất kỳ tệp nào' nodrop: 'Tải lên các tệp từ &nbsp;máy tính của bạn' cloudsTip: 'Lưu trữ Đám mây<br>và các mạng xã hội' or: 'hoặc' button: 'Lựa chọn một tệp trên máy' also: 'hoặc lựa chọn từ' url: title: 'Các tệp trên Web' line1: 'Chọn bất từ tệp nào từ web.' line2: 'Chỉ cần cung cấp liên kết.' input: 'Dán liên kết của bạn xuống đây...' button: 'Tải lên' camera: title: 'Tệp từ web cam' capture: 'Chụp một bức ảnh' mirror: 'Gương' startRecord: 'Quay một video' cancelRecord: 'Hủy' stopRecord: 'Dừng' retry: 'Yêu cầu cấp phép lần nữa' pleaseAllow: text: 'Bạn đã được nhắc nhở để cho phép truy cập vào camera từ trang này.<br>Để có thể chụp ảnh với camera, bạn phải chấp thuận yêu cầu này.' title: 'Vui lòng cho phép truy cập tới camera của bạn' notFound: title: 'Không tìm thấy camera nào' text: 'Có vẻ như bạn không có camera nào nối với thiết bị này.' preview: unknownName: 'PI:NAME:<NAME>END_PI' change: 'Hủy' back: 'Quay lại' done: 'Thêm' unknown: title: 'Đang tải lên...Vui lòng đợi để xem trước.' done: 'Bỏ qua và chấp nhận' regular: title: 'Thêm tệp này?' line1: 'Bạn dự định thêm tệp ở trên.' line2: 'Vui lòng chấp thuận.' image: title: 'Thêm hình ảnh này?' change: 'Hủy' crop: title: 'Cắt và thêm ảnh này' done: 'Xong' free: 'miễn phí' video: title: 'Thêm video này?' change: 'Hủy' error: default: title: 'Ồ!' back: 'Vui lòng thử lại' text: 'Có lỗi gì đó trong quá trình tải lên.' image: title: 'Chỉ chấp thuận các tệp hình ảnh.' text: 'Vui lòng thử lại với một tệp mới.' back: 'Lựa chọn hình ảnh' size: title: 'Tệp bạn đã lựa chọn vượt quá giới hạn' text: 'Vui lòng thử lại với một tệp khác.' loadImage: title: 'Lỗi' text: 'Không thể tải hình ảnh' multiple: title: 'Bạn đã lựa chọn %files%' question: 'Thêm %files%?' tooManyFiles: 'Bạn đã lựa chọn quá nhiều tệp. %max% là tối đa.' tooFewFiles: 'Bạn đã lựa chọn %files%. Ít nhất cần %min%' clear: 'Xoá Tất cả' file: preview: 'Xem trước %file%' remove: 'Xóa %file%' done: 'Thêm' footer: text: 'được hỗ trợ bởi' link: 'uploadcare' # Pluralization rules taken from: # http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html uploadcare.namespace 'locale.pluralize', (ns) -> ns.vi = (n) -> return 'other'
[ { "context": "y is not required when using this method.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass ProductImageRpc", "end": 226, "score": 0.9998190402984619, "start": 214, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/specification/request/rpc/ProductImageRpcRequest.coffee
qrefdev/qref
0
RpcRequest = require('../../../serialization/RpcRequest') ### Object sent as the body of an HTTP POST request to upload a product image. @note The token property is not required when using this method. @author Nathan Klick @copyright QRef 2012 ### class ProductImageRpcRequest extends RpcRequest ### @property [ObjectId] (Required) The product ID of the product to update. ### product: type: String required: true unique: true module.exports = ProductImageRpcRequest
206066
RpcRequest = require('../../../serialization/RpcRequest') ### Object sent as the body of an HTTP POST request to upload a product image. @note The token property is not required when using this method. @author <NAME> @copyright QRef 2012 ### class ProductImageRpcRequest extends RpcRequest ### @property [ObjectId] (Required) The product ID of the product to update. ### product: type: String required: true unique: true module.exports = ProductImageRpcRequest
true
RpcRequest = require('../../../serialization/RpcRequest') ### Object sent as the body of an HTTP POST request to upload a product image. @note The token property is not required when using this method. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class ProductImageRpcRequest extends RpcRequest ### @property [ObjectId] (Required) The product ID of the product to update. ### product: type: String required: true unique: true module.exports = ProductImageRpcRequest
[ { "context": "'\n\nclass Script extends AbstractScript\n artist: 'Anamanaguchi'\n title: 'Meow'\n image: '/images/anamanaguchi.m", "end": 125, "score": 0.9998594522476196, "start": 113, "tag": "NAME", "value": "Anamanaguchi" }, { "context": "anaguchi.meow.jpg'\n url: 'https://sou...
app/scripts/anamanaguchi.meow.coffee
bmatcuk/lasercatparty
2
"use strict" AbstractScript = require 'scripts/abstract_script' class Script extends AbstractScript artist: 'Anamanaguchi' title: 'Meow' image: '/images/anamanaguchi.meow.jpg' url: 'https://soundcloud.com/anamanaguchi/meow-1' run: (objs) -> super objs @registrar.onceAt 0, -> do objs.pizzacat.show objs.pizzacat.set -1.1, -0.1 objs.pizzacat.moveTo(0, -0.1, window.performance.now(), 2400, 'easeout').then -> objs.pizzacat.hover(0.01, window.performance.now(), 5400, 4).then -> objs.pizzacat.moveTo(1.1, -0.1, window.performance.now(), 2400, 'easein').then -> do objs.pizzacat.hide @scheduleLasers 3.14, 212, 100 @registrar.onceAt 3.14, -> objs.background.show window.performance.now(), 7000 @registrar.onceAt 5.9, -> objs.countdown.start 4, window.performance.now(), 1200 @registrar.onceAt 10.7, -> now = window.performance.now() objs.danceFloor.show now objs.danceFloor.startAnimation now, 100 objs.spectrum.show now objs.spectrum.startAnimation now, 100 objs.backgroundcat.show now objs.backgroundcat.startAnimation now, 100 for obj in objs.scene.frontPerspectiveObjs obj.show now obj.startAnimation now, 100 @registrar.onceAt 212, -> do objs.spectrum.stopAnimation do objs.spectrum.hide now = window.performance.now() objs.danceFloor.hide now, 2400 objs.backgroundcat.hide now, 2400 do objs.backgroundcat.stopAnimation obj.hide now, 2400 for obj in objs.scene.frontPerspectiveObjs @registrar.onceAt 214.4, -> do objs.danceFloor.stopAnimation do obj.stopAnimation for obj in objs.scene.frontPerspectiveObjs objs.background.hide window.performance.now(), 7000 module.exports = Script
130
"use strict" AbstractScript = require 'scripts/abstract_script' class Script extends AbstractScript artist: '<NAME>' title: 'Meow' image: '/images/anamanaguchi.meow.jpg' url: 'https://soundcloud.com/anamanaguchi/meow-1' run: (objs) -> super objs @registrar.onceAt 0, -> do objs.pizzacat.show objs.pizzacat.set -1.1, -0.1 objs.pizzacat.moveTo(0, -0.1, window.performance.now(), 2400, 'easeout').then -> objs.pizzacat.hover(0.01, window.performance.now(), 5400, 4).then -> objs.pizzacat.moveTo(1.1, -0.1, window.performance.now(), 2400, 'easein').then -> do objs.pizzacat.hide @scheduleLasers 3.14, 212, 100 @registrar.onceAt 3.14, -> objs.background.show window.performance.now(), 7000 @registrar.onceAt 5.9, -> objs.countdown.start 4, window.performance.now(), 1200 @registrar.onceAt 10.7, -> now = window.performance.now() objs.danceFloor.show now objs.danceFloor.startAnimation now, 100 objs.spectrum.show now objs.spectrum.startAnimation now, 100 objs.backgroundcat.show now objs.backgroundcat.startAnimation now, 100 for obj in objs.scene.frontPerspectiveObjs obj.show now obj.startAnimation now, 100 @registrar.onceAt 212, -> do objs.spectrum.stopAnimation do objs.spectrum.hide now = window.performance.now() objs.danceFloor.hide now, 2400 objs.backgroundcat.hide now, 2400 do objs.backgroundcat.stopAnimation obj.hide now, 2400 for obj in objs.scene.frontPerspectiveObjs @registrar.onceAt 214.4, -> do objs.danceFloor.stopAnimation do obj.stopAnimation for obj in objs.scene.frontPerspectiveObjs objs.background.hide window.performance.now(), 7000 module.exports = Script
true
"use strict" AbstractScript = require 'scripts/abstract_script' class Script extends AbstractScript artist: 'PI:NAME:<NAME>END_PI' title: 'Meow' image: '/images/anamanaguchi.meow.jpg' url: 'https://soundcloud.com/anamanaguchi/meow-1' run: (objs) -> super objs @registrar.onceAt 0, -> do objs.pizzacat.show objs.pizzacat.set -1.1, -0.1 objs.pizzacat.moveTo(0, -0.1, window.performance.now(), 2400, 'easeout').then -> objs.pizzacat.hover(0.01, window.performance.now(), 5400, 4).then -> objs.pizzacat.moveTo(1.1, -0.1, window.performance.now(), 2400, 'easein').then -> do objs.pizzacat.hide @scheduleLasers 3.14, 212, 100 @registrar.onceAt 3.14, -> objs.background.show window.performance.now(), 7000 @registrar.onceAt 5.9, -> objs.countdown.start 4, window.performance.now(), 1200 @registrar.onceAt 10.7, -> now = window.performance.now() objs.danceFloor.show now objs.danceFloor.startAnimation now, 100 objs.spectrum.show now objs.spectrum.startAnimation now, 100 objs.backgroundcat.show now objs.backgroundcat.startAnimation now, 100 for obj in objs.scene.frontPerspectiveObjs obj.show now obj.startAnimation now, 100 @registrar.onceAt 212, -> do objs.spectrum.stopAnimation do objs.spectrum.hide now = window.performance.now() objs.danceFloor.hide now, 2400 objs.backgroundcat.hide now, 2400 do objs.backgroundcat.stopAnimation obj.hide now, 2400 for obj in objs.scene.frontPerspectiveObjs @registrar.onceAt 214.4, -> do objs.danceFloor.stopAnimation do obj.stopAnimation for obj in objs.scene.frontPerspectiveObjs objs.background.hide window.performance.now(), 7000 module.exports = Script
[ { "context": "image: \"http://manuel-schoebel.com/images/authors/manuel-schoebel.jpg\"", "end": 210, "score": 0.6218435168266296, "start": 204, "tag": "NAME", "value": "manuel" } ]
both/_config/seo.coffee
gkodikara/meteor-starter-template
0
Meteor.startup -> if Meteor.isClient SEO.config title: @Config.name meta: description: @Config.subtitle # og: # image: "http://manuel-schoebel.com/images/authors/manuel-schoebel.jpg"
163573
Meteor.startup -> if Meteor.isClient SEO.config title: @Config.name meta: description: @Config.subtitle # og: # image: "http://manuel-schoebel.com/images/authors/<NAME>-schoebel.jpg"
true
Meteor.startup -> if Meteor.isClient SEO.config title: @Config.name meta: description: @Config.subtitle # og: # image: "http://manuel-schoebel.com/images/authors/PI:NAME:<NAME>END_PI-schoebel.jpg"
[ { "context": "###*\n * Error handlers\n * @copyright khalid RAFIK 2019\n###\n'use strict'\nPath = require 'path'\n\n#=in", "end": 49, "score": 0.9989573359489441, "start": 37, "tag": "NAME", "value": "khalid RAFIK" } ]
assets/index.coffee
gridfw/gridfw-errors
0
###* * Error handlers * @copyright khalid RAFIK 2019 ### 'use strict' Path = require 'path' #=include _handlers.coffee class ErrorHandling constructor: (@app)-> @enabled = on # the plugin is enabled return ###* * Reload parser ### reload: (settings)-> @enable() ###* * destroy ### destroy: -> @disable() ###* * Disable, enable ### disable: -> gErr = @app.errors for k,v of gErr if v is errorHandlers[k] delete gErr[k] return enable: -> gErr = @app.errors for k,v of errorHandlers unless k of gErr gErr[k] = v return module.exports = ErrorHandling
175949
###* * Error handlers * @copyright <NAME> 2019 ### 'use strict' Path = require 'path' #=include _handlers.coffee class ErrorHandling constructor: (@app)-> @enabled = on # the plugin is enabled return ###* * Reload parser ### reload: (settings)-> @enable() ###* * destroy ### destroy: -> @disable() ###* * Disable, enable ### disable: -> gErr = @app.errors for k,v of gErr if v is errorHandlers[k] delete gErr[k] return enable: -> gErr = @app.errors for k,v of errorHandlers unless k of gErr gErr[k] = v return module.exports = ErrorHandling
true
###* * Error handlers * @copyright PI:NAME:<NAME>END_PI 2019 ### 'use strict' Path = require 'path' #=include _handlers.coffee class ErrorHandling constructor: (@app)-> @enabled = on # the plugin is enabled return ###* * Reload parser ### reload: (settings)-> @enable() ###* * destroy ### destroy: -> @disable() ###* * Disable, enable ### disable: -> gErr = @app.errors for k,v of gErr if v is errorHandlers[k] delete gErr[k] return enable: -> gErr = @app.errors for k,v of errorHandlers unless k of gErr gErr[k] = v return module.exports = ErrorHandling
[ { "context": "p://paulkinzett.github.com/toolbar/\n@author Paul Kinzett (http://kinzett.co.nz/)\n@version 1.0.4\n@req", "end": 163, "score": 0.999874472618103, "start": 151, "tag": "NAME", "value": "Paul Kinzett" }, { "context": "p://paulkinzett.github.com/toolbar/\nCopy...
coffee/toolbar.coffee
IcaliaLabs/furatto
133
### Toolbar.js @fileoverview jQuery plugin that creates tooltip style toolbars. @link http://paulkinzett.github.com/toolbar/ @author Paul Kinzett (http://kinzett.co.nz/) @version 1.0.4 @requires jQuery 1.7+ @license jQuery Toolbar Plugin v1.0.4 http://paulkinzett.github.com/toolbar/ Copyright 2013 Paul Kinzett (http://kinzett.co.nz/) Released under the MIT license. <https://raw.github.com/paulkinzett/toolbar/master/LICENSE.txt> ### if typeof Object.create isnt "function" Object.create = (obj) -> F = -> F:: = obj new F() (($, window, document, undefined_) -> ToolBar = init: (options, elem) -> self = this self.elem = elem self.$elem = $(elem) self.options = $.extend({}, $.fn.toolbar.options, options) self.toolbar = $("<div class='tool-container gradient ' />").addClass("tool-" + self.options.position).addClass("tool-rounded").addClass(self.options.theme).append("<div class=\"tool-items\" />").append("<div class='arrow " + self.options.theme + "' />").appendTo("body").css("opacity", 0).hide() self.toolbar_arrow = self.toolbar.find(".arrow") self.initializeToolbar() initializeToolbar: -> self = this self.populateContent() self.setTrigger() self.toolbarWidth = self.toolbar.width() setTrigger: -> self = this self.$elem.on "click", (event) -> event.preventDefault() if self.$elem.hasClass("pressed") self.hide() else self.show() if self.options.hideOnClick $("html").on "click.toolbar", (event) -> self.hide() if event.target isnt self.elem and self.$elem.has(event.target).length is 0 and self.toolbar.has(event.target).length is 0 and self.toolbar.is(":visible") $(window).resize (event) -> event.stopPropagation() if self.toolbar.is(":visible") self.toolbarCss = self.getCoordinates(self.options.position, 20) self.collisionDetection() self.toolbar.css self.toolbarCss self.toolbar_arrow.css self.arrowCss populateContent: -> self = this location = self.toolbar.find(".tool-items") content = $(self.options.content).clone(true).find("a").addClass("tool-item gradient").addClass(self.options.theme) location.html content location.find(".tool-item").on "click", (event) -> event.preventDefault() self.$elem.trigger "toolbarItemClick", this calculatePosition: -> self = this self.arrowCss = {} self.toolbarCss = self.getCoordinates(self.options.position, 0) self.toolbarCss.position = "absolute" self.toolbarCss.zIndex = self.options.zIndex self.collisionDetection() self.toolbar.css self.toolbarCss self.toolbar_arrow.css self.arrowCss getCoordinates: (position, adjustment) -> self = this self.coordinates = self.$elem.offset() adjustment = self.options.adjustment[self.options.position] if self.options.adjustment and self.options.adjustment[self.options.position] switch self.options.position when "top" left: self.coordinates.left - (self.toolbar.width() / 2) + (self.$elem.outerWidth() / 2) top: self.coordinates.top - self.$elem.height() - adjustment right: "auto" when "left" left: self.coordinates.left - (self.toolbar.width() / 2) - (self.$elem.width() / 2) - adjustment top: self.coordinates.top - (self.toolbar.height() / 2) + (self.$elem.outerHeight() / 2) right: "auto" when "right" left: self.coordinates.left + (self.toolbar.width() / 2) + (self.$elem.width() / 3) + adjustment top: self.coordinates.top - (self.toolbar.height() / 2) + (self.$elem.outerHeight() / 2) right: "auto" when "bottom" left: self.coordinates.left - (self.toolbar.width() / 2) + (self.$elem.outerWidth() / 2) top: self.coordinates.top + self.$elem.height() + adjustment right: "auto" collisionDetection: -> self = this edgeOffset = 20 if self.options.position is "top" or self.options.position is "bottom" self.arrowCss = left: "50%" right: "50%" if self.toolbarCss.left < edgeOffset self.toolbarCss.left = edgeOffset self.arrowCss.left = self.$elem.offset().left + self.$elem.width() / 2 - (edgeOffset) else if ($(window).width() - (self.toolbarCss.left + self.toolbarWidth)) < edgeOffset self.toolbarCss.right = edgeOffset self.toolbarCss.left = "auto" self.arrowCss.left = "auto" self.arrowCss.right = ($(window).width() - self.$elem.offset().left) - (self.$elem.width() / 2) - (edgeOffset) - 5 show: -> self = this animation = opacity: 1 self.$elem.addClass "pressed" self.calculatePosition() switch self.options.position when "top" animation.top = "-=20" when "left" animation.left = "-=20" when "right" animation.left = "+=20" when "bottom" animation.top = "+=20" self.toolbar.show().animate animation, 200 self.$elem.trigger "toolbarShown" hide: -> self = this animation = opacity: 0 self.$elem.removeClass "pressed" switch self.options.position when "top" animation.top = "+=20" when "left" animation.left = "+=20" when "right" animation.left = "-=20" when "bottom" animation.top = "-=20" self.toolbar.animate animation, 200, -> self.toolbar.hide() self.$elem.trigger "toolbarHidden" getToolbarElement: -> @toolbar.find ".tool-items" $.fn.toolbar = (options) -> if $.isPlainObject(options) @each -> toolbarObj = Object.create(ToolBar) toolbarObj.init options, this $(this).data "toolbarObj", toolbarObj else if typeof options is "string" and options.indexOf("_") isnt 0 toolbarObj = $(this).data("toolbarObj") method = toolbarObj[options] method.apply toolbarObj, $.makeArray(arguments_).slice(1) $.fn.toolbar.options = content: "#myContent" position: "top" hideOnClick: false zIndex: 120 theme: "" $(document).ready -> $('[data-furatto="toolbar"]').each -> $(@).toolbar content: $(@).data('content') position: $(@).data('position') || 'top' hideOnClick: true theme: $(@).data('theme') ) jQuery, window, document
104755
### Toolbar.js @fileoverview jQuery plugin that creates tooltip style toolbars. @link http://paulkinzett.github.com/toolbar/ @author <NAME> (http://kinzett.co.nz/) @version 1.0.4 @requires jQuery 1.7+ @license jQuery Toolbar Plugin v1.0.4 http://paulkinzett.github.com/toolbar/ Copyright 2013 <NAME> (http://kinzett.co.nz/) Released under the MIT license. <https://raw.github.com/paulkinzett/toolbar/master/LICENSE.txt> ### if typeof Object.create isnt "function" Object.create = (obj) -> F = -> F:: = obj new F() (($, window, document, undefined_) -> ToolBar = init: (options, elem) -> self = this self.elem = elem self.$elem = $(elem) self.options = $.extend({}, $.fn.toolbar.options, options) self.toolbar = $("<div class='tool-container gradient ' />").addClass("tool-" + self.options.position).addClass("tool-rounded").addClass(self.options.theme).append("<div class=\"tool-items\" />").append("<div class='arrow " + self.options.theme + "' />").appendTo("body").css("opacity", 0).hide() self.toolbar_arrow = self.toolbar.find(".arrow") self.initializeToolbar() initializeToolbar: -> self = this self.populateContent() self.setTrigger() self.toolbarWidth = self.toolbar.width() setTrigger: -> self = this self.$elem.on "click", (event) -> event.preventDefault() if self.$elem.hasClass("pressed") self.hide() else self.show() if self.options.hideOnClick $("html").on "click.toolbar", (event) -> self.hide() if event.target isnt self.elem and self.$elem.has(event.target).length is 0 and self.toolbar.has(event.target).length is 0 and self.toolbar.is(":visible") $(window).resize (event) -> event.stopPropagation() if self.toolbar.is(":visible") self.toolbarCss = self.getCoordinates(self.options.position, 20) self.collisionDetection() self.toolbar.css self.toolbarCss self.toolbar_arrow.css self.arrowCss populateContent: -> self = this location = self.toolbar.find(".tool-items") content = $(self.options.content).clone(true).find("a").addClass("tool-item gradient").addClass(self.options.theme) location.html content location.find(".tool-item").on "click", (event) -> event.preventDefault() self.$elem.trigger "toolbarItemClick", this calculatePosition: -> self = this self.arrowCss = {} self.toolbarCss = self.getCoordinates(self.options.position, 0) self.toolbarCss.position = "absolute" self.toolbarCss.zIndex = self.options.zIndex self.collisionDetection() self.toolbar.css self.toolbarCss self.toolbar_arrow.css self.arrowCss getCoordinates: (position, adjustment) -> self = this self.coordinates = self.$elem.offset() adjustment = self.options.adjustment[self.options.position] if self.options.adjustment and self.options.adjustment[self.options.position] switch self.options.position when "top" left: self.coordinates.left - (self.toolbar.width() / 2) + (self.$elem.outerWidth() / 2) top: self.coordinates.top - self.$elem.height() - adjustment right: "auto" when "left" left: self.coordinates.left - (self.toolbar.width() / 2) - (self.$elem.width() / 2) - adjustment top: self.coordinates.top - (self.toolbar.height() / 2) + (self.$elem.outerHeight() / 2) right: "auto" when "right" left: self.coordinates.left + (self.toolbar.width() / 2) + (self.$elem.width() / 3) + adjustment top: self.coordinates.top - (self.toolbar.height() / 2) + (self.$elem.outerHeight() / 2) right: "auto" when "bottom" left: self.coordinates.left - (self.toolbar.width() / 2) + (self.$elem.outerWidth() / 2) top: self.coordinates.top + self.$elem.height() + adjustment right: "auto" collisionDetection: -> self = this edgeOffset = 20 if self.options.position is "top" or self.options.position is "bottom" self.arrowCss = left: "50%" right: "50%" if self.toolbarCss.left < edgeOffset self.toolbarCss.left = edgeOffset self.arrowCss.left = self.$elem.offset().left + self.$elem.width() / 2 - (edgeOffset) else if ($(window).width() - (self.toolbarCss.left + self.toolbarWidth)) < edgeOffset self.toolbarCss.right = edgeOffset self.toolbarCss.left = "auto" self.arrowCss.left = "auto" self.arrowCss.right = ($(window).width() - self.$elem.offset().left) - (self.$elem.width() / 2) - (edgeOffset) - 5 show: -> self = this animation = opacity: 1 self.$elem.addClass "pressed" self.calculatePosition() switch self.options.position when "top" animation.top = "-=20" when "left" animation.left = "-=20" when "right" animation.left = "+=20" when "bottom" animation.top = "+=20" self.toolbar.show().animate animation, 200 self.$elem.trigger "toolbarShown" hide: -> self = this animation = opacity: 0 self.$elem.removeClass "pressed" switch self.options.position when "top" animation.top = "+=20" when "left" animation.left = "+=20" when "right" animation.left = "-=20" when "bottom" animation.top = "-=20" self.toolbar.animate animation, 200, -> self.toolbar.hide() self.$elem.trigger "toolbarHidden" getToolbarElement: -> @toolbar.find ".tool-items" $.fn.toolbar = (options) -> if $.isPlainObject(options) @each -> toolbarObj = Object.create(ToolBar) toolbarObj.init options, this $(this).data "toolbarObj", toolbarObj else if typeof options is "string" and options.indexOf("_") isnt 0 toolbarObj = $(this).data("toolbarObj") method = toolbarObj[options] method.apply toolbarObj, $.makeArray(arguments_).slice(1) $.fn.toolbar.options = content: "#myContent" position: "top" hideOnClick: false zIndex: 120 theme: "" $(document).ready -> $('[data-furatto="toolbar"]').each -> $(@).toolbar content: $(@).data('content') position: $(@).data('position') || 'top' hideOnClick: true theme: $(@).data('theme') ) jQuery, window, document
true
### Toolbar.js @fileoverview jQuery plugin that creates tooltip style toolbars. @link http://paulkinzett.github.com/toolbar/ @author PI:NAME:<NAME>END_PI (http://kinzett.co.nz/) @version 1.0.4 @requires jQuery 1.7+ @license jQuery Toolbar Plugin v1.0.4 http://paulkinzett.github.com/toolbar/ Copyright 2013 PI:NAME:<NAME>END_PI (http://kinzett.co.nz/) Released under the MIT license. <https://raw.github.com/paulkinzett/toolbar/master/LICENSE.txt> ### if typeof Object.create isnt "function" Object.create = (obj) -> F = -> F:: = obj new F() (($, window, document, undefined_) -> ToolBar = init: (options, elem) -> self = this self.elem = elem self.$elem = $(elem) self.options = $.extend({}, $.fn.toolbar.options, options) self.toolbar = $("<div class='tool-container gradient ' />").addClass("tool-" + self.options.position).addClass("tool-rounded").addClass(self.options.theme).append("<div class=\"tool-items\" />").append("<div class='arrow " + self.options.theme + "' />").appendTo("body").css("opacity", 0).hide() self.toolbar_arrow = self.toolbar.find(".arrow") self.initializeToolbar() initializeToolbar: -> self = this self.populateContent() self.setTrigger() self.toolbarWidth = self.toolbar.width() setTrigger: -> self = this self.$elem.on "click", (event) -> event.preventDefault() if self.$elem.hasClass("pressed") self.hide() else self.show() if self.options.hideOnClick $("html").on "click.toolbar", (event) -> self.hide() if event.target isnt self.elem and self.$elem.has(event.target).length is 0 and self.toolbar.has(event.target).length is 0 and self.toolbar.is(":visible") $(window).resize (event) -> event.stopPropagation() if self.toolbar.is(":visible") self.toolbarCss = self.getCoordinates(self.options.position, 20) self.collisionDetection() self.toolbar.css self.toolbarCss self.toolbar_arrow.css self.arrowCss populateContent: -> self = this location = self.toolbar.find(".tool-items") content = $(self.options.content).clone(true).find("a").addClass("tool-item gradient").addClass(self.options.theme) location.html content location.find(".tool-item").on "click", (event) -> event.preventDefault() self.$elem.trigger "toolbarItemClick", this calculatePosition: -> self = this self.arrowCss = {} self.toolbarCss = self.getCoordinates(self.options.position, 0) self.toolbarCss.position = "absolute" self.toolbarCss.zIndex = self.options.zIndex self.collisionDetection() self.toolbar.css self.toolbarCss self.toolbar_arrow.css self.arrowCss getCoordinates: (position, adjustment) -> self = this self.coordinates = self.$elem.offset() adjustment = self.options.adjustment[self.options.position] if self.options.adjustment and self.options.adjustment[self.options.position] switch self.options.position when "top" left: self.coordinates.left - (self.toolbar.width() / 2) + (self.$elem.outerWidth() / 2) top: self.coordinates.top - self.$elem.height() - adjustment right: "auto" when "left" left: self.coordinates.left - (self.toolbar.width() / 2) - (self.$elem.width() / 2) - adjustment top: self.coordinates.top - (self.toolbar.height() / 2) + (self.$elem.outerHeight() / 2) right: "auto" when "right" left: self.coordinates.left + (self.toolbar.width() / 2) + (self.$elem.width() / 3) + adjustment top: self.coordinates.top - (self.toolbar.height() / 2) + (self.$elem.outerHeight() / 2) right: "auto" when "bottom" left: self.coordinates.left - (self.toolbar.width() / 2) + (self.$elem.outerWidth() / 2) top: self.coordinates.top + self.$elem.height() + adjustment right: "auto" collisionDetection: -> self = this edgeOffset = 20 if self.options.position is "top" or self.options.position is "bottom" self.arrowCss = left: "50%" right: "50%" if self.toolbarCss.left < edgeOffset self.toolbarCss.left = edgeOffset self.arrowCss.left = self.$elem.offset().left + self.$elem.width() / 2 - (edgeOffset) else if ($(window).width() - (self.toolbarCss.left + self.toolbarWidth)) < edgeOffset self.toolbarCss.right = edgeOffset self.toolbarCss.left = "auto" self.arrowCss.left = "auto" self.arrowCss.right = ($(window).width() - self.$elem.offset().left) - (self.$elem.width() / 2) - (edgeOffset) - 5 show: -> self = this animation = opacity: 1 self.$elem.addClass "pressed" self.calculatePosition() switch self.options.position when "top" animation.top = "-=20" when "left" animation.left = "-=20" when "right" animation.left = "+=20" when "bottom" animation.top = "+=20" self.toolbar.show().animate animation, 200 self.$elem.trigger "toolbarShown" hide: -> self = this animation = opacity: 0 self.$elem.removeClass "pressed" switch self.options.position when "top" animation.top = "+=20" when "left" animation.left = "+=20" when "right" animation.left = "-=20" when "bottom" animation.top = "-=20" self.toolbar.animate animation, 200, -> self.toolbar.hide() self.$elem.trigger "toolbarHidden" getToolbarElement: -> @toolbar.find ".tool-items" $.fn.toolbar = (options) -> if $.isPlainObject(options) @each -> toolbarObj = Object.create(ToolBar) toolbarObj.init options, this $(this).data "toolbarObj", toolbarObj else if typeof options is "string" and options.indexOf("_") isnt 0 toolbarObj = $(this).data("toolbarObj") method = toolbarObj[options] method.apply toolbarObj, $.makeArray(arguments_).slice(1) $.fn.toolbar.options = content: "#myContent" position: "top" hideOnClick: false zIndex: 120 theme: "" $(document).ready -> $('[data-furatto="toolbar"]').each -> $(@).toolbar content: $(@).data('content') position: $(@).data('position') || 'top' hideOnClick: true theme: $(@).data('theme') ) jQuery, window, document
[ { "context": "ood emails and not bad ones', ->\n\n good = 'jimmyjames@hotmail.com'\n bad = 'jimmyjames@hotmail'\n expec", "end": 1598, "score": 0.9998795390129089, "start": 1576, "tag": "EMAIL", "value": "jimmyjames@hotmail.com" }, { "context": " good = 'jimmyj...
test/utils/utils.spec.coffee
OpenSourceFieldlinguistics/dative
7
################################################################################ # Unit tests for utils/utils.coffee ################################################################################ # # global beforeEach, describe, it, assert, expect # # TODO: test utils.selectText. Needs DOM fixture. define (require) -> utils = require '../../../scripts/utils/utils' describe '`utils` object', -> describe '`utils.clone`', -> # Optimist handler: unbridled success! optimistHandler = onsuccess: -> expect(true).to.be.ok onerror: -> expect(false).to.be.ok it 'can clone a date', -> d = new Date() dClone = utils.clone d expect(d.toString()).to.equal dClone.toString() it 'can clone an array', -> a = [[[37]]] aClone = utils.clone a expect(a[0][0][0]).to.equal aClone[0][0][0] it 'can clone an object', -> o = dave: bill: 'susan' oClone = utils.clone o expect(o.dave.bill).to.equal oClone.dave.bill describe '`utils.type`', -> it 'identifies an array', -> expect(utils.type([])).to.equal 'array' expect(typeof []).to.equal 'object' describe '`utils.guid`', -> it 'generates a GUID', -> guid = utils.guid() re = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/g expect(guid).to.be.a 'string' expect(guid).to.match re describe '`utils.emailIsValid`', -> it 'recognizes good emails and not bad ones', -> good = 'jimmyjames@hotmail.com' bad = 'jimmyjames@hotmail' expect(utils.emailIsValid good).to.be.ok expect(utils.emailIsValid bad).to.not.be.ok describe '`utils.startsWith`', -> it 'can tell whether one string starts with another string', -> expect(utils.startsWith('prefix', 'pref')).to.be.true expect(utils.startsWith('pre\u0301fix', 'pre\u0301f')).to.be.true expect(utils.startsWith('pre\u0301fix', 'pref')).to.be.false describe '`utils.endsWith`', -> it 'can tell whether one string ends with another string', -> expect(utils.endsWith('suffix', 'fix')).to.be.true expect(utils.endsWith('suffi\u0301x', 'fi\u0301x')).to.be.true expect(utils.endsWith('suffi\u0301x', 'fix')).to.be.false describe '`utils.integerWithCommas`', -> it 'can turn a number into a string with commas in it for easier reading', -> expect(utils.integerWithCommas 123456789).to.equal '123,456,789' it 'cannot handle non-integers', -> expect(utils.integerWithCommas(12345.6789)).to.not.equal '12,345.6789' describe '`utils.singularize`', -> it 'returns the singular of regular plurals', -> expect(utils.singularize 'dogs').to.equal 'dog' it 'returns the singular of ‘...ies’ plurals', -> expect(utils.singularize 'skies').to.equal 'sky' it 'returns the singular of ‘...hes’ plurals', -> expect(utils.singularize 'bushes').to.equal 'bush' expect(utils.singularize 'churches').to.equal 'church' expect(utils.singularize 'watches').to.equal 'watch' it 'return a non-string as itself', -> expect(utils.singularize null).to.be.null expect(utils.singularize 2).to.equal 2 expect(utils.singularize []).to.eql [] expect(utils.singularize {}).to.eql {} describe '`utils.pluralize`', -> it 'pluralizes regular nouns', -> expect(utils.pluralize 'dog').to.equal 'dogs' it 'pluralizes nouns ending in ‘y’', -> expect(utils.pluralize 'sky').to.equal 'skies' it 'pluralizes ‘status’ as ‘statuses’', -> expect(utils.pluralize 'status').to.equal 'statuses' it 'pluralizes other words ending in ‘us’ as ‘ora’ (which is crazy)', -> expect(utils.pluralize 'corpus').to.equal 'corpora' it 'pluralizes nouns ending in sibilants using the ‘-es’ suffix', -> expect(utils.pluralize 'ass').to.equal 'asses' expect(utils.pluralize 'buzz').to.equal 'buzzes' expect(utils.pluralize 'bush').to.equal 'bushes' expect(utils.pluralize 'watch').to.equal 'watches' describe '`utils.pluralizeByNumber`', -> it 'doesn’t pluralize when the number is 1', -> expect(utils.pluralizeByNum 'corpus', 1).to.equal 'corpus' it 'does pluralize when the number is not 1', -> expect(utils.pluralizeByNum 'corpus', 0).to.equal 'corpora' expect(utils.pluralizeByNum 'corpus', 6).to.equal 'corpora' describe '`utils.indefiniteDeterminer`', -> it 'returns ‘an’ if the complement begins with a vowel', -> expect(utils.indefiniteDeterminer 'owl').to.equal 'an' expect(utils.indefiniteDeterminer 'apple').to.equal 'an' it 'returns ‘a’ if the complement begins with a consonant or is ‘user’', -> expect(utils.indefiniteDeterminer 'tower').to.equal 'a' expect(utils.indefiniteDeterminer 'user').to.equal 'a' describe '`utils.dateString2object`', -> it 'returns a `Date()` instance, given an ISO 8601 datetime string', -> d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' # This format doesn't work expect(utils.dateString2object(d1)).to.be.instanceof Date expect(utils.dateString2object(d2)).to.be.instanceof Date expect(utils.dateString2object(d3)).to.be.instanceof Date expect(utils.dateString2object(dBad1)).to.not.be.instanceof Date expect(utils.dateString2object(d1).getMonth()).to.equal 8 expect(utils.dateString2object(d3).getFullYear()).to.equal 2015 expect(utils.dateString2object(dBad1).getMonth).to.be.undefined describe '`utils.asDateObject`', -> it 'returns a ISO 8601 date string as a Date, if possible', -> d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' # This format doesn't work expect(utils.asDateObject(d1)).to.be.instanceof Date expect(utils.asDateObject(d2)).to.be.instanceof Date expect(utils.asDateObject(d3)).to.be.instanceof Date expect(utils.asDateObject(dBad1)).to.not.be.instanceof Date expect(utils.asDateObject(dBad1)).to.equal dBad1 expect(utils.asDateObject(null)).to.be.null expect(utils.asDateObject(undefined)).to.be.null expect(utils.asDateObject(d1).getMonth()).to.equal 8 expect(utils.asDateObject(d3).getFullYear()).to.equal 2015 expect(utils.asDateObject(dBad1).getMonth).to.be.undefined describe '`humanDatetime`', -> it 'returns a datetime string or a Date() instance as a human-readable date and time string, something like ‘September 27, 2015 at 10:21 p.m.’', -> humanDatetimeRegex = /// ^ \w+ \u0020 \d{1,2} , \u0020 \d{4} \u0020 at \u0020 \d{1,2} : \d{2} \u0020 [ap]\.m\. $ /// d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' expect(utils.humanDatetime(d2)).to.match humanDatetimeRegex expect(utils.humanDatetime(d1)).to.match humanDatetimeRegex expect(utils.humanDatetime(d3)).to.match humanDatetimeRegex expect(utils.humanDatetime(dBad1)).to.equal dBad1 expect(utils.humanDatetime(null)).to.be.null expect(utils.humanDatetime(undefined)).to.be.null describe '`humanDate`', -> it 'returns a Date() instance or an ISO 8601 datetime string as a human-readable date string, something like ‘September 27, 2015’', -> humanDateRegex = /// ^ \w+ \u0020 \d{1,2} , \u0020 \d{4} $ /// dGood = new Date() dBad1 = '2015-09-26T19:47:03+00:00' dBad2 = null dBad3 = undefined expect(utils.humanDate(dGood)).to.match humanDateRegex expect(utils.humanDate(dBad1)).to.match humanDateRegex expect(utils.humanDate(dBad2)).to.be.null expect(utils.humanDate(dBad3)).to.be.null describe '`humanTime`', -> it 'returns a `Date()` instance as a human-readable time string, something like 5:45 p.m.', -> humanTimeRegex = /// ^ \d{1,2} : \d{2} \u0020 [ap]\.m\. $ /// humanTimeRegexWithSeconds = /// ^ \d{1,2} : \d{2} : \d{2} \u0020 [ap]\.m\. $ /// dBad1 = '2015-09-26T19:47:03+00:00' expect(utils.humanTime(new Date())).to.match humanTimeRegex expect(utils.humanTime(new Date(), true)) .to.match humanTimeRegexWithSeconds expect(utils.humanTime(dBad1)).to.be.null expect(utils.humanTime(null)).to.be.null expect(utils.humanTime(undefined)).to.be.null describe '`timeSince`', -> it 'returns a string indicating how long ago a `Date()` instance is from now.', -> today = new Date() thirteenSecondsAgo = new Date(today.getTime() - (1000 * 13)) thirteenMinutesAgo = new Date(today.getTime() - (1000 * 60 * 13)) thirteenHoursAgo = new Date(today.getTime() - (1000 * 60 * 60 * 13)) thirteenDaysAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 13)) thirteenMonthsAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 30 * 13)) thirteenYearsAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 365 * 13)) expect(utils.timeSince(thirteenSecondsAgo)).to.equal '13 seconds ago' expect(utils.timeSince(thirteenMinutesAgo)).to.equal '13 minutes ago' expect(utils.timeSince(thirteenHoursAgo)).to.equal '13 hours ago' expect(utils.timeSince(thirteenDaysAgo)).to.equal '13 days ago' expect(utils.timeSince(thirteenMonthsAgo)).to.equal '13 months ago' expect(utils.timeSince(thirteenYearsAgo)).to.equal '13 years ago' describe '`utils.millisecondsToTimeString`', -> it 'converts a number of milliseconds to a string formatted as 00h00m00s', -> expect(utils.millisecondsToTimeString 6000).to.equal '00h00m06s' expect(utils.millisecondsToTimeString ((13 * 60000) + 7000)) .to.equal '00h13m07s' expect(utils.millisecondsToTimeString ((13 * 60 * 60000) + (13 * 60000) + 7000)) .to.equal '13h13m07s' describe '`utils.leftPad`', -> it 'left-pads ‘0’s to a string', -> expect(utils.leftPad('3')).to.equal '03' expect(utils.leftPad('13')).to.equal '13' expect(utils.leftPad('13', 4)).to.equal '0013' it 'works with numbers (not just strings)', -> expect(utils.leftPad(3)).to.equal '03' expect(utils.leftPad(13)).to.equal '13' expect(utils.leftPad(13, 4)).to.equal '0013' describe '`utils.snake2camel`', -> it 'converts snake_case strings to camelCase ones', -> expect(utils.snake2camel 'snake_case_string').to.equal 'snakeCaseString' expect(utils.snake2camel 'snake').to.equal 'snake' it 'does not recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2camel 'Bad_Snake_Case').to.equal 'Bad_Snake_Case' describe '`utils.snake2hyphen`', -> it 'converts snake_case strings to hyphen-case ones', -> expect(utils.snake2hyphen 'snake_case_string').to.equal 'snake-case-string' expect(utils.snake2hyphen 'snake').to.equal 'snake' it 'does recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2hyphen 'Bad_Snake_Case').to.equal 'Bad-Snake-Case' describe '`utils.snake2regular`', -> it 'converts snake_case strings to regular case ones', -> expect(utils.snake2regular 'snake_case_string') .to.equal 'snake case string' expect(utils.snake2regular 'snake').to.equal 'snake' it 'does recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2regular 'Bad_Snake_Case').to.equal 'Bad Snake Case' describe '`utils.camel2snake`', -> it 'converts camelCase strings to snake_case ones', -> expect(utils.camel2snake 'camelCaseString').to.equal 'camel_case_string' expect(utils.camel2snake 'camel').to.equal 'camel' expect(utils.camel2snake 'CamelCaseString').to.equal 'camel_case_string' describe '`utils.camel2regular`', -> it 'converts camelCase strings to regular case ones', -> expect(utils.camel2regular 'camelCaseString') .to.equal 'camel case string' expect(utils.camel2regular 'camel').to.equal 'camel' expect(utils.camel2regular 'CamelCaseString') .to.equal 'camel case string' describe '`utils.camel2regularUpper`', -> it 'converts camelCase strings to Regular Capitalized ones', -> expect(utils.camel2regularUpper 'camelCaseString') .to.equal 'Camel Case String' expect(utils.camel2regularUpper 'camel').to.equal 'Camel' expect(utils.camel2regularUpper 'CamelCaseString') .to.equal 'Camel Case String' describe '`utils.camel2hyphen`', -> it 'converts camelCase strings to hypen-case ones', -> expect(utils.camel2hyphen 'camelCaseString') .to.equal 'camel-case-string' expect(utils.camel2hyphen 'camel').to.equal 'camel' expect(utils.camel2hyphen 'CamelCaseString') .to.equal 'camel-case-string' describe '`utils.capitalize`', -> it 'capitalizes strings', -> expect(utils.capitalize 'camel').to.equal 'Camel' expect(utils.capitalize 'c').to.equal 'C' expect(utils.capitalize 'Camel').to.equal 'Camel' expect(utils.capitalize 'CAMEL').to.equal 'CAMEL' describe '`utils.encloseIfNotAlready`', -> it 'encloses a string in specified start and end strings', -> expect(utils.encloseIfNotAlready 'chien', '/', '/') .to.equal '/chien/' expect(utils.encloseIfNotAlready '/chien/', '/', '/') .to.equal '/chien/' expect(utils.encloseIfNotAlready 'chien', '\u2018', '\u2019') .to.equal '\u2018chien\u2019' expect(utils.encloseIfNotAlready '\u2018chien\u2019', '\u2018', '\u2019') .to.equal '\u2018chien\u2019' expect(utils.encloseIfNotAlready undefined, '\u2018', '\u2019') .to.be.undefined expect(utils.encloseIfNotAlready null, '\u2018', '\u2019') .to.be.null it 'expects the bookmarks to be length-1 strings', -> expect(utils.encloseIfNotAlready 'chien', '\u2018\u2018', '\u2019\u2019') .to.equal '\u2018\u2018chien\u2019\u2019' expect(utils.encloseIfNotAlready '\u2018\u2018chien\u2019\u2019', '\u2018\u2018', '\u2019\u2019') .to.equal '\u2018\u2018\u2018\u2018chien\u2019\u2019\u2019\u2019' describe '`utils.smallCapsAcronyms`', -> it 'encloses acronyms in a string in “small caps” spans', -> expect(utils.smallCapsAcronyms 'PHI PL.PROX') .to.equal "<span class='small-caps'>phi</span> <span class='small-caps'>pl</span>.\ <span class='small-caps'>prox</span>" it 'does not recognyze a lone capitalized character as an acronym', -> expect(utils.smallCapsAcronyms 'PHI P.PROX') .to.equal "<span class='small-caps'>phi</span> P.<span class='small-caps'>prox</span>" describe '`utils.convertDateISO2mdySlash`', -> it 'converts an ISO 8601 date string (e.g., ‘2015-03-16’) to one in MM/DD/YYY format', -> expect(utils.convertDateISO2mdySlash '2015-03-16') .to.equal '03/16/2015' expect(utils.convertDateISO2mdySlash null).to.be.null expect(utils.convertDateISO2mdySlash undefined).to.be.undefined describe '`utils.isValidURL`', -> it 'can recognize an obviously good URL', -> expect(utils.isValidURL 'http://www.google.com').to.be.true it 'will not recognize an obviously bad URL', -> expect(utils.isValidURL 'http:/www.google.com').to.be.false expect(utils.isValidURL 'http://www.google.').to.be.false # NOTE/WARN/BUG: this will fail: # expect(utils.isValidURL 'http://www.google').to.be.false describe '`utils.getExtension`', -> it 'returns the extension from a file name or path', -> expect(utils.getExtension '/path/to/my/file.cool.wav').to.equal 'wav' expect(utils.getExtension '/path/to/my/file.cool.blargon') .to.equal 'blargon' # TODO: this is perhaps not what should be returned here ... expect(utils.getExtension '/path/to/my/file') .to.equal '/path/to/my/file' describe '`utils.getFilenameAndExtension`', -> it 'returns the filename and extension of a file name/ path as a 2-ary array', -> expect(utils.getFilenameAndExtension('/path/to/my/file.cool.wav')[0]) .to.equal '/path/to/my/file.cool' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.wav')[1]) .to.equal 'wav' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.blargon')[0]) .to.equal '/path/to/my/file.cool' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.blargon')[1]) .to.equal 'blargon' expect(utils.getFilenameAndExtension('/path/to/my/file')[0]) .to.equal '/path/to/my/file' expect(utils.getFilenameAndExtension('/path/to/my/file')[1]) .to.be.null expect(utils.getFilenameAndExtension(null)[0]).to.be.null expect(utils.getFilenameAndExtension(null)[1]).to.be.null expect(utils.getFilenameAndExtension(undefined)[0]).to.be.undefined expect(utils.getFilenameAndExtension(undefined)[1]).to.be.null describe '`utils.getMIMEType`', -> it 'returns a MIME type from a file name/path, for files with extensions that we care about', -> expect(utils.getMIMEType 'sound.wav').to.equal 'audio/x-wav' expect(utils.getMIMEType 'sound.mp3').to.equal 'audio/mp3' expect(utils.getMIMEType 'crappy-doc.doc').to.be.undefined describe '`utils.humanFileSize`', -> it 'returns a number (of bytes) as a string expressing that quantify of bytes in kB, MB, GB, etc.', -> expect(utils.humanFileSize 2455).to.equal '2.5 kB' expect(utils.humanFileSize 2455123).to.equal '2.5 MB'
85715
################################################################################ # Unit tests for utils/utils.coffee ################################################################################ # # global beforeEach, describe, it, assert, expect # # TODO: test utils.selectText. Needs DOM fixture. define (require) -> utils = require '../../../scripts/utils/utils' describe '`utils` object', -> describe '`utils.clone`', -> # Optimist handler: unbridled success! optimistHandler = onsuccess: -> expect(true).to.be.ok onerror: -> expect(false).to.be.ok it 'can clone a date', -> d = new Date() dClone = utils.clone d expect(d.toString()).to.equal dClone.toString() it 'can clone an array', -> a = [[[37]]] aClone = utils.clone a expect(a[0][0][0]).to.equal aClone[0][0][0] it 'can clone an object', -> o = dave: bill: 'susan' oClone = utils.clone o expect(o.dave.bill).to.equal oClone.dave.bill describe '`utils.type`', -> it 'identifies an array', -> expect(utils.type([])).to.equal 'array' expect(typeof []).to.equal 'object' describe '`utils.guid`', -> it 'generates a GUID', -> guid = utils.guid() re = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/g expect(guid).to.be.a 'string' expect(guid).to.match re describe '`utils.emailIsValid`', -> it 'recognizes good emails and not bad ones', -> good = '<EMAIL>' bad = '<EMAIL>' expect(utils.emailIsValid good).to.be.ok expect(utils.emailIsValid bad).to.not.be.ok describe '`utils.startsWith`', -> it 'can tell whether one string starts with another string', -> expect(utils.startsWith('prefix', 'pref')).to.be.true expect(utils.startsWith('pre\u0301fix', 'pre\u0301f')).to.be.true expect(utils.startsWith('pre\u0301fix', 'pref')).to.be.false describe '`utils.endsWith`', -> it 'can tell whether one string ends with another string', -> expect(utils.endsWith('suffix', 'fix')).to.be.true expect(utils.endsWith('suffi\u0301x', 'fi\u0301x')).to.be.true expect(utils.endsWith('suffi\u0301x', 'fix')).to.be.false describe '`utils.integerWithCommas`', -> it 'can turn a number into a string with commas in it for easier reading', -> expect(utils.integerWithCommas 123456789).to.equal '123,456,789' it 'cannot handle non-integers', -> expect(utils.integerWithCommas(12345.6789)).to.not.equal '12,345.6789' describe '`utils.singularize`', -> it 'returns the singular of regular plurals', -> expect(utils.singularize 'dogs').to.equal 'dog' it 'returns the singular of ‘...ies’ plurals', -> expect(utils.singularize 'skies').to.equal 'sky' it 'returns the singular of ‘...hes’ plurals', -> expect(utils.singularize 'bushes').to.equal 'bush' expect(utils.singularize 'churches').to.equal 'church' expect(utils.singularize 'watches').to.equal 'watch' it 'return a non-string as itself', -> expect(utils.singularize null).to.be.null expect(utils.singularize 2).to.equal 2 expect(utils.singularize []).to.eql [] expect(utils.singularize {}).to.eql {} describe '`utils.pluralize`', -> it 'pluralizes regular nouns', -> expect(utils.pluralize 'dog').to.equal 'dogs' it 'pluralizes nouns ending in ‘y’', -> expect(utils.pluralize 'sky').to.equal 'skies' it 'pluralizes ‘status’ as ‘statuses’', -> expect(utils.pluralize 'status').to.equal 'statuses' it 'pluralizes other words ending in ‘us’ as ‘ora’ (which is crazy)', -> expect(utils.pluralize 'corpus').to.equal 'corpora' it 'pluralizes nouns ending in sibilants using the ‘-es’ suffix', -> expect(utils.pluralize 'ass').to.equal 'asses' expect(utils.pluralize 'buzz').to.equal 'buzzes' expect(utils.pluralize 'bush').to.equal 'bushes' expect(utils.pluralize 'watch').to.equal 'watches' describe '`utils.pluralizeByNumber`', -> it 'doesn’t pluralize when the number is 1', -> expect(utils.pluralizeByNum 'corpus', 1).to.equal 'corpus' it 'does pluralize when the number is not 1', -> expect(utils.pluralizeByNum 'corpus', 0).to.equal 'corpora' expect(utils.pluralizeByNum 'corpus', 6).to.equal 'corpora' describe '`utils.indefiniteDeterminer`', -> it 'returns ‘an’ if the complement begins with a vowel', -> expect(utils.indefiniteDeterminer 'owl').to.equal 'an' expect(utils.indefiniteDeterminer 'apple').to.equal 'an' it 'returns ‘a’ if the complement begins with a consonant or is ‘user’', -> expect(utils.indefiniteDeterminer 'tower').to.equal 'a' expect(utils.indefiniteDeterminer 'user').to.equal 'a' describe '`utils.dateString2object`', -> it 'returns a `Date()` instance, given an ISO 8601 datetime string', -> d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' # This format doesn't work expect(utils.dateString2object(d1)).to.be.instanceof Date expect(utils.dateString2object(d2)).to.be.instanceof Date expect(utils.dateString2object(d3)).to.be.instanceof Date expect(utils.dateString2object(dBad1)).to.not.be.instanceof Date expect(utils.dateString2object(d1).getMonth()).to.equal 8 expect(utils.dateString2object(d3).getFullYear()).to.equal 2015 expect(utils.dateString2object(dBad1).getMonth).to.be.undefined describe '`utils.asDateObject`', -> it 'returns a ISO 8601 date string as a Date, if possible', -> d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' # This format doesn't work expect(utils.asDateObject(d1)).to.be.instanceof Date expect(utils.asDateObject(d2)).to.be.instanceof Date expect(utils.asDateObject(d3)).to.be.instanceof Date expect(utils.asDateObject(dBad1)).to.not.be.instanceof Date expect(utils.asDateObject(dBad1)).to.equal dBad1 expect(utils.asDateObject(null)).to.be.null expect(utils.asDateObject(undefined)).to.be.null expect(utils.asDateObject(d1).getMonth()).to.equal 8 expect(utils.asDateObject(d3).getFullYear()).to.equal 2015 expect(utils.asDateObject(dBad1).getMonth).to.be.undefined describe '`humanDatetime`', -> it 'returns a datetime string or a Date() instance as a human-readable date and time string, something like ‘September 27, 2015 at 10:21 p.m.’', -> humanDatetimeRegex = /// ^ \w+ \u0020 \d{1,2} , \u0020 \d{4} \u0020 at \u0020 \d{1,2} : \d{2} \u0020 [ap]\.m\. $ /// d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' expect(utils.humanDatetime(d2)).to.match humanDatetimeRegex expect(utils.humanDatetime(d1)).to.match humanDatetimeRegex expect(utils.humanDatetime(d3)).to.match humanDatetimeRegex expect(utils.humanDatetime(dBad1)).to.equal dBad1 expect(utils.humanDatetime(null)).to.be.null expect(utils.humanDatetime(undefined)).to.be.null describe '`humanDate`', -> it 'returns a Date() instance or an ISO 8601 datetime string as a human-readable date string, something like ‘September 27, 2015’', -> humanDateRegex = /// ^ \w+ \u0020 \d{1,2} , \u0020 \d{4} $ /// dGood = new Date() dBad1 = '2015-09-26T19:47:03+00:00' dBad2 = null dBad3 = undefined expect(utils.humanDate(dGood)).to.match humanDateRegex expect(utils.humanDate(dBad1)).to.match humanDateRegex expect(utils.humanDate(dBad2)).to.be.null expect(utils.humanDate(dBad3)).to.be.null describe '`humanTime`', -> it 'returns a `Date()` instance as a human-readable time string, something like 5:45 p.m.', -> humanTimeRegex = /// ^ \d{1,2} : \d{2} \u0020 [ap]\.m\. $ /// humanTimeRegexWithSeconds = /// ^ \d{1,2} : \d{2} : \d{2} \u0020 [ap]\.m\. $ /// dBad1 = '2015-09-26T19:47:03+00:00' expect(utils.humanTime(new Date())).to.match humanTimeRegex expect(utils.humanTime(new Date(), true)) .to.match humanTimeRegexWithSeconds expect(utils.humanTime(dBad1)).to.be.null expect(utils.humanTime(null)).to.be.null expect(utils.humanTime(undefined)).to.be.null describe '`timeSince`', -> it 'returns a string indicating how long ago a `Date()` instance is from now.', -> today = new Date() thirteenSecondsAgo = new Date(today.getTime() - (1000 * 13)) thirteenMinutesAgo = new Date(today.getTime() - (1000 * 60 * 13)) thirteenHoursAgo = new Date(today.getTime() - (1000 * 60 * 60 * 13)) thirteenDaysAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 13)) thirteenMonthsAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 30 * 13)) thirteenYearsAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 365 * 13)) expect(utils.timeSince(thirteenSecondsAgo)).to.equal '13 seconds ago' expect(utils.timeSince(thirteenMinutesAgo)).to.equal '13 minutes ago' expect(utils.timeSince(thirteenHoursAgo)).to.equal '13 hours ago' expect(utils.timeSince(thirteenDaysAgo)).to.equal '13 days ago' expect(utils.timeSince(thirteenMonthsAgo)).to.equal '13 months ago' expect(utils.timeSince(thirteenYearsAgo)).to.equal '13 years ago' describe '`utils.millisecondsToTimeString`', -> it 'converts a number of milliseconds to a string formatted as 00h00m00s', -> expect(utils.millisecondsToTimeString 6000).to.equal '00h00m06s' expect(utils.millisecondsToTimeString ((13 * 60000) + 7000)) .to.equal '00h13m07s' expect(utils.millisecondsToTimeString ((13 * 60 * 60000) + (13 * 60000) + 7000)) .to.equal '13h13m07s' describe '`utils.leftPad`', -> it 'left-pads ‘0’s to a string', -> expect(utils.leftPad('3')).to.equal '03' expect(utils.leftPad('13')).to.equal '13' expect(utils.leftPad('13', 4)).to.equal '0013' it 'works with numbers (not just strings)', -> expect(utils.leftPad(3)).to.equal '03' expect(utils.leftPad(13)).to.equal '13' expect(utils.leftPad(13, 4)).to.equal '0013' describe '`utils.snake2camel`', -> it 'converts snake_case strings to camelCase ones', -> expect(utils.snake2camel 'snake_case_string').to.equal 'snakeCaseString' expect(utils.snake2camel 'snake').to.equal 'snake' it 'does not recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2camel 'Bad_Snake_Case').to.equal 'Bad_Snake_Case' describe '`utils.snake2hyphen`', -> it 'converts snake_case strings to hyphen-case ones', -> expect(utils.snake2hyphen 'snake_case_string').to.equal 'snake-case-string' expect(utils.snake2hyphen 'snake').to.equal 'snake' it 'does recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2hyphen 'Bad_Snake_Case').to.equal 'Bad-Snake-Case' describe '`utils.snake2regular`', -> it 'converts snake_case strings to regular case ones', -> expect(utils.snake2regular 'snake_case_string') .to.equal 'snake case string' expect(utils.snake2regular 'snake').to.equal 'snake' it 'does recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2regular 'Bad_Snake_Case').to.equal 'Bad Snake Case' describe '`utils.camel2snake`', -> it 'converts camelCase strings to snake_case ones', -> expect(utils.camel2snake 'camelCaseString').to.equal 'camel_case_string' expect(utils.camel2snake 'camel').to.equal 'camel' expect(utils.camel2snake 'CamelCaseString').to.equal 'camel_case_string' describe '`utils.camel2regular`', -> it 'converts camelCase strings to regular case ones', -> expect(utils.camel2regular 'camelCaseString') .to.equal 'camel case string' expect(utils.camel2regular 'camel').to.equal 'camel' expect(utils.camel2regular 'CamelCaseString') .to.equal 'camel case string' describe '`utils.camel2regularUpper`', -> it 'converts camelCase strings to Regular Capitalized ones', -> expect(utils.camel2regularUpper 'camelCaseString') .to.equal 'Camel Case String' expect(utils.camel2regularUpper 'camel').to.equal 'Camel' expect(utils.camel2regularUpper 'CamelCaseString') .to.equal 'Camel Case String' describe '`utils.camel2hyphen`', -> it 'converts camelCase strings to hypen-case ones', -> expect(utils.camel2hyphen 'camelCaseString') .to.equal 'camel-case-string' expect(utils.camel2hyphen 'camel').to.equal 'camel' expect(utils.camel2hyphen 'CamelCaseString') .to.equal 'camel-case-string' describe '`utils.capitalize`', -> it 'capitalizes strings', -> expect(utils.capitalize 'camel').to.equal 'Camel' expect(utils.capitalize 'c').to.equal 'C' expect(utils.capitalize 'Camel').to.equal 'Camel' expect(utils.capitalize 'CAMEL').to.equal 'CAMEL' describe '`utils.encloseIfNotAlready`', -> it 'encloses a string in specified start and end strings', -> expect(utils.encloseIfNotAlready 'chien', '/', '/') .to.equal '/chien/' expect(utils.encloseIfNotAlready '/chien/', '/', '/') .to.equal '/chien/' expect(utils.encloseIfNotAlready 'chien', '\u2018', '\u2019') .to.equal '\u2018chien\u2019' expect(utils.encloseIfNotAlready '\u2018chien\u2019', '\u2018', '\u2019') .to.equal '\u2018chien\u2019' expect(utils.encloseIfNotAlready undefined, '\u2018', '\u2019') .to.be.undefined expect(utils.encloseIfNotAlready null, '\u2018', '\u2019') .to.be.null it 'expects the bookmarks to be length-1 strings', -> expect(utils.encloseIfNotAlready 'chien', '\u2018\u2018', '\u2019\u2019') .to.equal '\u2018\u2018chien\u2019\u2019' expect(utils.encloseIfNotAlready '\u2018\u2018chien\u2019\u2019', '\u2018\u2018', '\u2019\u2019') .to.equal '\u2018\u2018\u2018\u2018chien\u2019\u2019\u2019\u2019' describe '`utils.smallCapsAcronyms`', -> it 'encloses acronyms in a string in “small caps” spans', -> expect(utils.smallCapsAcronyms 'PHI PL.PROX') .to.equal "<span class='small-caps'>phi</span> <span class='small-caps'>pl</span>.\ <span class='small-caps'>prox</span>" it 'does not recognyze a lone capitalized character as an acronym', -> expect(utils.smallCapsAcronyms 'PHI P.PROX') .to.equal "<span class='small-caps'>phi</span> P.<span class='small-caps'>prox</span>" describe '`utils.convertDateISO2mdySlash`', -> it 'converts an ISO 8601 date string (e.g., ‘2015-03-16’) to one in MM/DD/YYY format', -> expect(utils.convertDateISO2mdySlash '2015-03-16') .to.equal '03/16/2015' expect(utils.convertDateISO2mdySlash null).to.be.null expect(utils.convertDateISO2mdySlash undefined).to.be.undefined describe '`utils.isValidURL`', -> it 'can recognize an obviously good URL', -> expect(utils.isValidURL 'http://www.google.com').to.be.true it 'will not recognize an obviously bad URL', -> expect(utils.isValidURL 'http:/www.google.com').to.be.false expect(utils.isValidURL 'http://www.google.').to.be.false # NOTE/WARN/BUG: this will fail: # expect(utils.isValidURL 'http://www.google').to.be.false describe '`utils.getExtension`', -> it 'returns the extension from a file name or path', -> expect(utils.getExtension '/path/to/my/file.cool.wav').to.equal 'wav' expect(utils.getExtension '/path/to/my/file.cool.blargon') .to.equal 'blargon' # TODO: this is perhaps not what should be returned here ... expect(utils.getExtension '/path/to/my/file') .to.equal '/path/to/my/file' describe '`utils.getFilenameAndExtension`', -> it 'returns the filename and extension of a file name/ path as a 2-ary array', -> expect(utils.getFilenameAndExtension('/path/to/my/file.cool.wav')[0]) .to.equal '/path/to/my/file.cool' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.wav')[1]) .to.equal 'wav' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.blargon')[0]) .to.equal '/path/to/my/file.cool' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.blargon')[1]) .to.equal 'blargon' expect(utils.getFilenameAndExtension('/path/to/my/file')[0]) .to.equal '/path/to/my/file' expect(utils.getFilenameAndExtension('/path/to/my/file')[1]) .to.be.null expect(utils.getFilenameAndExtension(null)[0]).to.be.null expect(utils.getFilenameAndExtension(null)[1]).to.be.null expect(utils.getFilenameAndExtension(undefined)[0]).to.be.undefined expect(utils.getFilenameAndExtension(undefined)[1]).to.be.null describe '`utils.getMIMEType`', -> it 'returns a MIME type from a file name/path, for files with extensions that we care about', -> expect(utils.getMIMEType 'sound.wav').to.equal 'audio/x-wav' expect(utils.getMIMEType 'sound.mp3').to.equal 'audio/mp3' expect(utils.getMIMEType 'crappy-doc.doc').to.be.undefined describe '`utils.humanFileSize`', -> it 'returns a number (of bytes) as a string expressing that quantify of bytes in kB, MB, GB, etc.', -> expect(utils.humanFileSize 2455).to.equal '2.5 kB' expect(utils.humanFileSize 2455123).to.equal '2.5 MB'
true
################################################################################ # Unit tests for utils/utils.coffee ################################################################################ # # global beforeEach, describe, it, assert, expect # # TODO: test utils.selectText. Needs DOM fixture. define (require) -> utils = require '../../../scripts/utils/utils' describe '`utils` object', -> describe '`utils.clone`', -> # Optimist handler: unbridled success! optimistHandler = onsuccess: -> expect(true).to.be.ok onerror: -> expect(false).to.be.ok it 'can clone a date', -> d = new Date() dClone = utils.clone d expect(d.toString()).to.equal dClone.toString() it 'can clone an array', -> a = [[[37]]] aClone = utils.clone a expect(a[0][0][0]).to.equal aClone[0][0][0] it 'can clone an object', -> o = dave: bill: 'susan' oClone = utils.clone o expect(o.dave.bill).to.equal oClone.dave.bill describe '`utils.type`', -> it 'identifies an array', -> expect(utils.type([])).to.equal 'array' expect(typeof []).to.equal 'object' describe '`utils.guid`', -> it 'generates a GUID', -> guid = utils.guid() re = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/g expect(guid).to.be.a 'string' expect(guid).to.match re describe '`utils.emailIsValid`', -> it 'recognizes good emails and not bad ones', -> good = 'PI:EMAIL:<EMAIL>END_PI' bad = 'PI:EMAIL:<EMAIL>END_PI' expect(utils.emailIsValid good).to.be.ok expect(utils.emailIsValid bad).to.not.be.ok describe '`utils.startsWith`', -> it 'can tell whether one string starts with another string', -> expect(utils.startsWith('prefix', 'pref')).to.be.true expect(utils.startsWith('pre\u0301fix', 'pre\u0301f')).to.be.true expect(utils.startsWith('pre\u0301fix', 'pref')).to.be.false describe '`utils.endsWith`', -> it 'can tell whether one string ends with another string', -> expect(utils.endsWith('suffix', 'fix')).to.be.true expect(utils.endsWith('suffi\u0301x', 'fi\u0301x')).to.be.true expect(utils.endsWith('suffi\u0301x', 'fix')).to.be.false describe '`utils.integerWithCommas`', -> it 'can turn a number into a string with commas in it for easier reading', -> expect(utils.integerWithCommas 123456789).to.equal '123,456,789' it 'cannot handle non-integers', -> expect(utils.integerWithCommas(12345.6789)).to.not.equal '12,345.6789' describe '`utils.singularize`', -> it 'returns the singular of regular plurals', -> expect(utils.singularize 'dogs').to.equal 'dog' it 'returns the singular of ‘...ies’ plurals', -> expect(utils.singularize 'skies').to.equal 'sky' it 'returns the singular of ‘...hes’ plurals', -> expect(utils.singularize 'bushes').to.equal 'bush' expect(utils.singularize 'churches').to.equal 'church' expect(utils.singularize 'watches').to.equal 'watch' it 'return a non-string as itself', -> expect(utils.singularize null).to.be.null expect(utils.singularize 2).to.equal 2 expect(utils.singularize []).to.eql [] expect(utils.singularize {}).to.eql {} describe '`utils.pluralize`', -> it 'pluralizes regular nouns', -> expect(utils.pluralize 'dog').to.equal 'dogs' it 'pluralizes nouns ending in ‘y’', -> expect(utils.pluralize 'sky').to.equal 'skies' it 'pluralizes ‘status’ as ‘statuses’', -> expect(utils.pluralize 'status').to.equal 'statuses' it 'pluralizes other words ending in ‘us’ as ‘ora’ (which is crazy)', -> expect(utils.pluralize 'corpus').to.equal 'corpora' it 'pluralizes nouns ending in sibilants using the ‘-es’ suffix', -> expect(utils.pluralize 'ass').to.equal 'asses' expect(utils.pluralize 'buzz').to.equal 'buzzes' expect(utils.pluralize 'bush').to.equal 'bushes' expect(utils.pluralize 'watch').to.equal 'watches' describe '`utils.pluralizeByNumber`', -> it 'doesn’t pluralize when the number is 1', -> expect(utils.pluralizeByNum 'corpus', 1).to.equal 'corpus' it 'does pluralize when the number is not 1', -> expect(utils.pluralizeByNum 'corpus', 0).to.equal 'corpora' expect(utils.pluralizeByNum 'corpus', 6).to.equal 'corpora' describe '`utils.indefiniteDeterminer`', -> it 'returns ‘an’ if the complement begins with a vowel', -> expect(utils.indefiniteDeterminer 'owl').to.equal 'an' expect(utils.indefiniteDeterminer 'apple').to.equal 'an' it 'returns ‘a’ if the complement begins with a consonant or is ‘user’', -> expect(utils.indefiniteDeterminer 'tower').to.equal 'a' expect(utils.indefiniteDeterminer 'user').to.equal 'a' describe '`utils.dateString2object`', -> it 'returns a `Date()` instance, given an ISO 8601 datetime string', -> d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' # This format doesn't work expect(utils.dateString2object(d1)).to.be.instanceof Date expect(utils.dateString2object(d2)).to.be.instanceof Date expect(utils.dateString2object(d3)).to.be.instanceof Date expect(utils.dateString2object(dBad1)).to.not.be.instanceof Date expect(utils.dateString2object(d1).getMonth()).to.equal 8 expect(utils.dateString2object(d3).getFullYear()).to.equal 2015 expect(utils.dateString2object(dBad1).getMonth).to.be.undefined describe '`utils.asDateObject`', -> it 'returns a ISO 8601 date string as a Date, if possible', -> d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' # This format doesn't work expect(utils.asDateObject(d1)).to.be.instanceof Date expect(utils.asDateObject(d2)).to.be.instanceof Date expect(utils.asDateObject(d3)).to.be.instanceof Date expect(utils.asDateObject(dBad1)).to.not.be.instanceof Date expect(utils.asDateObject(dBad1)).to.equal dBad1 expect(utils.asDateObject(null)).to.be.null expect(utils.asDateObject(undefined)).to.be.null expect(utils.asDateObject(d1).getMonth()).to.equal 8 expect(utils.asDateObject(d3).getFullYear()).to.equal 2015 expect(utils.asDateObject(dBad1).getMonth).to.be.undefined describe '`humanDatetime`', -> it 'returns a datetime string or a Date() instance as a human-readable date and time string, something like ‘September 27, 2015 at 10:21 p.m.’', -> humanDatetimeRegex = /// ^ \w+ \u0020 \d{1,2} , \u0020 \d{4} \u0020 at \u0020 \d{1,2} : \d{2} \u0020 [ap]\.m\. $ /// d1 = '2015-09-26T19:47:03+00:00' d2 = '2015-09-26T19:47:03Z' d3 = '2015-09-26T19:47:03' dBad1 = '20150926T194703Z' expect(utils.humanDatetime(d2)).to.match humanDatetimeRegex expect(utils.humanDatetime(d1)).to.match humanDatetimeRegex expect(utils.humanDatetime(d3)).to.match humanDatetimeRegex expect(utils.humanDatetime(dBad1)).to.equal dBad1 expect(utils.humanDatetime(null)).to.be.null expect(utils.humanDatetime(undefined)).to.be.null describe '`humanDate`', -> it 'returns a Date() instance or an ISO 8601 datetime string as a human-readable date string, something like ‘September 27, 2015’', -> humanDateRegex = /// ^ \w+ \u0020 \d{1,2} , \u0020 \d{4} $ /// dGood = new Date() dBad1 = '2015-09-26T19:47:03+00:00' dBad2 = null dBad3 = undefined expect(utils.humanDate(dGood)).to.match humanDateRegex expect(utils.humanDate(dBad1)).to.match humanDateRegex expect(utils.humanDate(dBad2)).to.be.null expect(utils.humanDate(dBad3)).to.be.null describe '`humanTime`', -> it 'returns a `Date()` instance as a human-readable time string, something like 5:45 p.m.', -> humanTimeRegex = /// ^ \d{1,2} : \d{2} \u0020 [ap]\.m\. $ /// humanTimeRegexWithSeconds = /// ^ \d{1,2} : \d{2} : \d{2} \u0020 [ap]\.m\. $ /// dBad1 = '2015-09-26T19:47:03+00:00' expect(utils.humanTime(new Date())).to.match humanTimeRegex expect(utils.humanTime(new Date(), true)) .to.match humanTimeRegexWithSeconds expect(utils.humanTime(dBad1)).to.be.null expect(utils.humanTime(null)).to.be.null expect(utils.humanTime(undefined)).to.be.null describe '`timeSince`', -> it 'returns a string indicating how long ago a `Date()` instance is from now.', -> today = new Date() thirteenSecondsAgo = new Date(today.getTime() - (1000 * 13)) thirteenMinutesAgo = new Date(today.getTime() - (1000 * 60 * 13)) thirteenHoursAgo = new Date(today.getTime() - (1000 * 60 * 60 * 13)) thirteenDaysAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 13)) thirteenMonthsAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 30 * 13)) thirteenYearsAgo = new Date(today.getTime() - (1000 * 60 * 60 * 24 * 365 * 13)) expect(utils.timeSince(thirteenSecondsAgo)).to.equal '13 seconds ago' expect(utils.timeSince(thirteenMinutesAgo)).to.equal '13 minutes ago' expect(utils.timeSince(thirteenHoursAgo)).to.equal '13 hours ago' expect(utils.timeSince(thirteenDaysAgo)).to.equal '13 days ago' expect(utils.timeSince(thirteenMonthsAgo)).to.equal '13 months ago' expect(utils.timeSince(thirteenYearsAgo)).to.equal '13 years ago' describe '`utils.millisecondsToTimeString`', -> it 'converts a number of milliseconds to a string formatted as 00h00m00s', -> expect(utils.millisecondsToTimeString 6000).to.equal '00h00m06s' expect(utils.millisecondsToTimeString ((13 * 60000) + 7000)) .to.equal '00h13m07s' expect(utils.millisecondsToTimeString ((13 * 60 * 60000) + (13 * 60000) + 7000)) .to.equal '13h13m07s' describe '`utils.leftPad`', -> it 'left-pads ‘0’s to a string', -> expect(utils.leftPad('3')).to.equal '03' expect(utils.leftPad('13')).to.equal '13' expect(utils.leftPad('13', 4)).to.equal '0013' it 'works with numbers (not just strings)', -> expect(utils.leftPad(3)).to.equal '03' expect(utils.leftPad(13)).to.equal '13' expect(utils.leftPad(13, 4)).to.equal '0013' describe '`utils.snake2camel`', -> it 'converts snake_case strings to camelCase ones', -> expect(utils.snake2camel 'snake_case_string').to.equal 'snakeCaseString' expect(utils.snake2camel 'snake').to.equal 'snake' it 'does not recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2camel 'Bad_Snake_Case').to.equal 'Bad_Snake_Case' describe '`utils.snake2hyphen`', -> it 'converts snake_case strings to hyphen-case ones', -> expect(utils.snake2hyphen 'snake_case_string').to.equal 'snake-case-string' expect(utils.snake2hyphen 'snake').to.equal 'snake' it 'does recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2hyphen 'Bad_Snake_Case').to.equal 'Bad-Snake-Case' describe '`utils.snake2regular`', -> it 'converts snake_case strings to regular case ones', -> expect(utils.snake2regular 'snake_case_string') .to.equal 'snake case string' expect(utils.snake2regular 'snake').to.equal 'snake' it 'does recognize capitalized Snake_Case as snake_case', -> expect(utils.snake2regular 'Bad_Snake_Case').to.equal 'Bad Snake Case' describe '`utils.camel2snake`', -> it 'converts camelCase strings to snake_case ones', -> expect(utils.camel2snake 'camelCaseString').to.equal 'camel_case_string' expect(utils.camel2snake 'camel').to.equal 'camel' expect(utils.camel2snake 'CamelCaseString').to.equal 'camel_case_string' describe '`utils.camel2regular`', -> it 'converts camelCase strings to regular case ones', -> expect(utils.camel2regular 'camelCaseString') .to.equal 'camel case string' expect(utils.camel2regular 'camel').to.equal 'camel' expect(utils.camel2regular 'CamelCaseString') .to.equal 'camel case string' describe '`utils.camel2regularUpper`', -> it 'converts camelCase strings to Regular Capitalized ones', -> expect(utils.camel2regularUpper 'camelCaseString') .to.equal 'Camel Case String' expect(utils.camel2regularUpper 'camel').to.equal 'Camel' expect(utils.camel2regularUpper 'CamelCaseString') .to.equal 'Camel Case String' describe '`utils.camel2hyphen`', -> it 'converts camelCase strings to hypen-case ones', -> expect(utils.camel2hyphen 'camelCaseString') .to.equal 'camel-case-string' expect(utils.camel2hyphen 'camel').to.equal 'camel' expect(utils.camel2hyphen 'CamelCaseString') .to.equal 'camel-case-string' describe '`utils.capitalize`', -> it 'capitalizes strings', -> expect(utils.capitalize 'camel').to.equal 'Camel' expect(utils.capitalize 'c').to.equal 'C' expect(utils.capitalize 'Camel').to.equal 'Camel' expect(utils.capitalize 'CAMEL').to.equal 'CAMEL' describe '`utils.encloseIfNotAlready`', -> it 'encloses a string in specified start and end strings', -> expect(utils.encloseIfNotAlready 'chien', '/', '/') .to.equal '/chien/' expect(utils.encloseIfNotAlready '/chien/', '/', '/') .to.equal '/chien/' expect(utils.encloseIfNotAlready 'chien', '\u2018', '\u2019') .to.equal '\u2018chien\u2019' expect(utils.encloseIfNotAlready '\u2018chien\u2019', '\u2018', '\u2019') .to.equal '\u2018chien\u2019' expect(utils.encloseIfNotAlready undefined, '\u2018', '\u2019') .to.be.undefined expect(utils.encloseIfNotAlready null, '\u2018', '\u2019') .to.be.null it 'expects the bookmarks to be length-1 strings', -> expect(utils.encloseIfNotAlready 'chien', '\u2018\u2018', '\u2019\u2019') .to.equal '\u2018\u2018chien\u2019\u2019' expect(utils.encloseIfNotAlready '\u2018\u2018chien\u2019\u2019', '\u2018\u2018', '\u2019\u2019') .to.equal '\u2018\u2018\u2018\u2018chien\u2019\u2019\u2019\u2019' describe '`utils.smallCapsAcronyms`', -> it 'encloses acronyms in a string in “small caps” spans', -> expect(utils.smallCapsAcronyms 'PHI PL.PROX') .to.equal "<span class='small-caps'>phi</span> <span class='small-caps'>pl</span>.\ <span class='small-caps'>prox</span>" it 'does not recognyze a lone capitalized character as an acronym', -> expect(utils.smallCapsAcronyms 'PHI P.PROX') .to.equal "<span class='small-caps'>phi</span> P.<span class='small-caps'>prox</span>" describe '`utils.convertDateISO2mdySlash`', -> it 'converts an ISO 8601 date string (e.g., ‘2015-03-16’) to one in MM/DD/YYY format', -> expect(utils.convertDateISO2mdySlash '2015-03-16') .to.equal '03/16/2015' expect(utils.convertDateISO2mdySlash null).to.be.null expect(utils.convertDateISO2mdySlash undefined).to.be.undefined describe '`utils.isValidURL`', -> it 'can recognize an obviously good URL', -> expect(utils.isValidURL 'http://www.google.com').to.be.true it 'will not recognize an obviously bad URL', -> expect(utils.isValidURL 'http:/www.google.com').to.be.false expect(utils.isValidURL 'http://www.google.').to.be.false # NOTE/WARN/BUG: this will fail: # expect(utils.isValidURL 'http://www.google').to.be.false describe '`utils.getExtension`', -> it 'returns the extension from a file name or path', -> expect(utils.getExtension '/path/to/my/file.cool.wav').to.equal 'wav' expect(utils.getExtension '/path/to/my/file.cool.blargon') .to.equal 'blargon' # TODO: this is perhaps not what should be returned here ... expect(utils.getExtension '/path/to/my/file') .to.equal '/path/to/my/file' describe '`utils.getFilenameAndExtension`', -> it 'returns the filename and extension of a file name/ path as a 2-ary array', -> expect(utils.getFilenameAndExtension('/path/to/my/file.cool.wav')[0]) .to.equal '/path/to/my/file.cool' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.wav')[1]) .to.equal 'wav' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.blargon')[0]) .to.equal '/path/to/my/file.cool' expect(utils.getFilenameAndExtension('/path/to/my/file.cool.blargon')[1]) .to.equal 'blargon' expect(utils.getFilenameAndExtension('/path/to/my/file')[0]) .to.equal '/path/to/my/file' expect(utils.getFilenameAndExtension('/path/to/my/file')[1]) .to.be.null expect(utils.getFilenameAndExtension(null)[0]).to.be.null expect(utils.getFilenameAndExtension(null)[1]).to.be.null expect(utils.getFilenameAndExtension(undefined)[0]).to.be.undefined expect(utils.getFilenameAndExtension(undefined)[1]).to.be.null describe '`utils.getMIMEType`', -> it 'returns a MIME type from a file name/path, for files with extensions that we care about', -> expect(utils.getMIMEType 'sound.wav').to.equal 'audio/x-wav' expect(utils.getMIMEType 'sound.mp3').to.equal 'audio/mp3' expect(utils.getMIMEType 'crappy-doc.doc').to.be.undefined describe '`utils.humanFileSize`', -> it 'returns a number (of bytes) as a string expressing that quantify of bytes in kB, MB, GB, etc.', -> expect(utils.humanFileSize 2455).to.equal '2.5 kB' expect(utils.humanFileSize 2455123).to.equal '2.5 MB'
[ { "context": "c=\"<%= avatar %>\">\n <span class=\"author\">Toni Boehm</span>\n </a>\n <% } else { %>\n ", "end": 2287, "score": 0.9997905492782593, "start": 2277, "tag": "NAME", "value": "Toni Boehm" }, { "context": "ndex in users\n if ob...
app/assets/javascripts/users_select.js.coffee
denzuko-forked/gitlab-on-heroku
8
class @UsersSelect constructor: (currentUser) -> @usersPath = "/autocomplete/users.json" @userPath = "/autocomplete/users/:id.json" if currentUser? @currentUser = JSON.parse(currentUser) $('.js-user-search').each (i, dropdown) => $dropdown = $(dropdown) @projectId = $dropdown.data('project-id') @showCurrentUser = $dropdown.data('current-user') showNullUser = $dropdown.data('null-user') showAnyUser = $dropdown.data('any-user') firstUser = $dropdown.data('first-user') @authorId = $dropdown.data('author-id') selectedId = $dropdown.data('selected') defaultLabel = $dropdown.data('default-label') issueURL = $dropdown.data('issueUpdate') $selectbox = $dropdown.closest('.selectbox') $block = $selectbox.closest('.block') abilityName = $dropdown.data('ability-name') $value = $block.find('.value') $collapsedSidebar = $block.find('.sidebar-collapsed-user') $loading = $block.find('.block-loading').fadeOut() $block.on('click', '.js-assign-yourself', (e) => e.preventDefault() assignTo(@currentUser.id) ) assignTo = (selected) -> data = {} data[abilityName] = {} data[abilityName].assignee_id = selected $loading .fadeIn() $dropdown.trigger('loading.gl.dropdown') $.ajax( type: 'PUT' dataType: 'json' url: issueURL data: data ).done (data) -> $dropdown.trigger('loaded.gl.dropdown') $loading.fadeOut() $selectbox.hide() if data.assignee user = name: data.assignee.name username: data.assignee.username avatar: data.assignee.avatar_url else user = name: 'Unassigned' username: '' avatar: '' $value.html(assigneeTemplate(user)) $collapsedSidebar.html(collapsedAssigneeTemplate(user)) collapsedAssigneeTemplate = _.template( '<% if( avatar ) { %> <a class="author_link" href="/u/<%= username %>"> <img width="24" class="avatar avatar-inline s24" alt="" src="<%= avatar %>"> <span class="author">Toni Boehm</span> </a> <% } else { %> <i class="fa fa-user"></i> <% } %>' ) assigneeTemplate = _.template( '<% if (username) { %> <a class="author_link " href="/u/<%= username %>"> <% if( avatar ) { %> <img width="32" class="avatar avatar-inline s32" alt="" src="<%= avatar %>"> <% } %> <span class="author"><%= name %></span> <span class="username"> @<%= username %> </span> </a> <% } else { %> <span class="assign-yourself"> No assignee - <a href="#" class="js-assign-yourself"> assign yourself </a> </span> <% } %>' ) $dropdown.glDropdown( data: (term, callback) => @users term, (users) => if term.length is 0 showDivider = 0 if firstUser # Move current user to the front of the list for obj, index in users if obj.username == firstUser users.splice(index, 1) users.unshift(obj) break if showNullUser showDivider += 1 users.unshift( beforeDivider: true name: 'Unassigned', id: 0 ) if showAnyUser showDivider += 1 name = showAnyUser name = 'Any User' if name == true anyUser = { beforeDivider: true name: name, id: null } users.unshift(anyUser) if showDivider users.splice(showDivider, 0, "divider") # Send the data back callback users filterable: true filterRemote: true search: fields: ['name', 'username'] selectable: true fieldName: $dropdown.data('field-name') toggleLabel: (selected) -> if selected && 'id' of selected selected.name else defaultLabel inputId: 'issue_assignee_id' hidden: (e) -> $selectbox.hide() # display:block overrides the hide-collapse rule $value.removeAttr('style') clicked: (user) -> page = $('body').data 'page' isIssueIndex = page is 'projects:issues:index' isMRIndex = page is page is 'projects:merge_requests:index' if $dropdown.hasClass('js-filter-bulk-update') return if $dropdown.hasClass('js-filter-submit') and (isIssueIndex or isMRIndex) selectedId = user.id Issuable.filterResults $dropdown.closest('form') else if $dropdown.hasClass 'js-filter-submit' $dropdown.closest('form').submit() else selected = $dropdown .closest('.selectbox') .find("input[name='#{$dropdown.data('field-name')}']").val() assignTo(selected) renderRow: (user) -> username = if user.username then "@#{user.username}" else "" avatar = if user.avatar_url then user.avatar_url else false selected = if user.id is selectedId then "is-active" else "" img = "" if user.beforeDivider? "<li> <a href='#' class='#{selected}'> #{user.name} </a> </li>" else if avatar img = "<img src='#{avatar}' class='avatar avatar-inline' width='30' />" # split into three parts so we can remove the username section if nessesary listWithName = "<li> <a href='#' class='dropdown-menu-user-link #{selected}'> #{img} <strong class='dropdown-menu-user-full-name'> #{user.name} </strong>" listWithUserName = "<span class='dropdown-menu-user-username'> #{username} </span>" listClosingTags = "</a> </li>" if username is '' listWithUserName = '' listWithName + listWithUserName + listClosingTags ) $('.ajax-users-select').each (i, select) => @projectId = $(select).data('project-id') @groupId = $(select).data('group-id') @showCurrentUser = $(select).data('current-user') @authorId = $(select).data('author-id') showNullUser = $(select).data('null-user') showAnyUser = $(select).data('any-user') showEmailUser = $(select).data('email-user') firstUser = $(select).data('first-user') $(select).select2 placeholder: "Search for a user" multiple: $(select).hasClass('multiselect') minimumInputLength: 0 query: (query) => @users query.term, (users) => data = { results: users } if query.term.length == 0 if firstUser # Move current user to the front of the list for obj, index in data.results if obj.username == firstUser data.results.splice(index, 1) data.results.unshift(obj) break if showNullUser nullUser = { name: 'Unassigned', id: 0 } data.results.unshift(nullUser) if showAnyUser name = showAnyUser name = 'Any User' if name == true anyUser = { name: name, id: null } data.results.unshift(anyUser) if showEmailUser && data.results.length == 0 && query.term.match(/^[^@]+@[^@]+$/) emailUser = { name: "Invite \"#{query.term}\"", username: query.term, id: query.term } data.results.unshift(emailUser) query.callback(data) initSelection: (args...) => @initSelection(args...) formatResult: (args...) => @formatResult(args...) formatSelection: (args...) => @formatSelection(args...) dropdownCssClass: "ajax-users-dropdown" escapeMarkup: (m) -> # we do not want to escape markup since we are displaying html in results m initSelection: (element, callback) -> id = $(element).val() if id == "0" nullUser = { name: 'Unassigned' } callback(nullUser) else if id != "" @user(id, callback) formatResult: (user) -> if user.avatar_url avatar = user.avatar_url else avatar = gon.default_avatar_url "<div class='user-result #{'no-username' unless user.username}'> <div class='user-image'><img class='avatar s24' src='#{avatar}'></div> <div class='user-name'>#{user.name}</div> <div class='user-username'>#{user.username || ""}</div> </div>" formatSelection: (user) -> user.name user: (user_id, callback) => url = @buildUrl(@userPath) url = url.replace(':id', user_id) $.ajax( url: url dataType: "json" ).done (user) -> callback(user) # Return users list. Filtered by query # Only active users retrieved users: (query, callback) => url = @buildUrl(@usersPath) $.ajax( url: url data: search: query per_page: 20 active: true project_id: @projectId group_id: @groupId current_user: @showCurrentUser author_id: @authorId dataType: "json" ).done (users) -> callback(users) buildUrl: (url) -> url = gon.relative_url_root.replace(/\/$/, '') + url if gon.relative_url_root? return url
215168
class @UsersSelect constructor: (currentUser) -> @usersPath = "/autocomplete/users.json" @userPath = "/autocomplete/users/:id.json" if currentUser? @currentUser = JSON.parse(currentUser) $('.js-user-search').each (i, dropdown) => $dropdown = $(dropdown) @projectId = $dropdown.data('project-id') @showCurrentUser = $dropdown.data('current-user') showNullUser = $dropdown.data('null-user') showAnyUser = $dropdown.data('any-user') firstUser = $dropdown.data('first-user') @authorId = $dropdown.data('author-id') selectedId = $dropdown.data('selected') defaultLabel = $dropdown.data('default-label') issueURL = $dropdown.data('issueUpdate') $selectbox = $dropdown.closest('.selectbox') $block = $selectbox.closest('.block') abilityName = $dropdown.data('ability-name') $value = $block.find('.value') $collapsedSidebar = $block.find('.sidebar-collapsed-user') $loading = $block.find('.block-loading').fadeOut() $block.on('click', '.js-assign-yourself', (e) => e.preventDefault() assignTo(@currentUser.id) ) assignTo = (selected) -> data = {} data[abilityName] = {} data[abilityName].assignee_id = selected $loading .fadeIn() $dropdown.trigger('loading.gl.dropdown') $.ajax( type: 'PUT' dataType: 'json' url: issueURL data: data ).done (data) -> $dropdown.trigger('loaded.gl.dropdown') $loading.fadeOut() $selectbox.hide() if data.assignee user = name: data.assignee.name username: data.assignee.username avatar: data.assignee.avatar_url else user = name: 'Unassigned' username: '' avatar: '' $value.html(assigneeTemplate(user)) $collapsedSidebar.html(collapsedAssigneeTemplate(user)) collapsedAssigneeTemplate = _.template( '<% if( avatar ) { %> <a class="author_link" href="/u/<%= username %>"> <img width="24" class="avatar avatar-inline s24" alt="" src="<%= avatar %>"> <span class="author"><NAME></span> </a> <% } else { %> <i class="fa fa-user"></i> <% } %>' ) assigneeTemplate = _.template( '<% if (username) { %> <a class="author_link " href="/u/<%= username %>"> <% if( avatar ) { %> <img width="32" class="avatar avatar-inline s32" alt="" src="<%= avatar %>"> <% } %> <span class="author"><%= name %></span> <span class="username"> @<%= username %> </span> </a> <% } else { %> <span class="assign-yourself"> No assignee - <a href="#" class="js-assign-yourself"> assign yourself </a> </span> <% } %>' ) $dropdown.glDropdown( data: (term, callback) => @users term, (users) => if term.length is 0 showDivider = 0 if firstUser # Move current user to the front of the list for obj, index in users if obj.username == firstUser users.splice(index, 1) users.unshift(obj) break if showNullUser showDivider += 1 users.unshift( beforeDivider: true name: 'Unassigned', id: 0 ) if showAnyUser showDivider += 1 name = showAnyUser name = 'Any User' if name == true anyUser = { beforeDivider: true name: name, id: null } users.unshift(anyUser) if showDivider users.splice(showDivider, 0, "divider") # Send the data back callback users filterable: true filterRemote: true search: fields: ['name', 'username'] selectable: true fieldName: $dropdown.data('field-name') toggleLabel: (selected) -> if selected && 'id' of selected selected.name else defaultLabel inputId: 'issue_assignee_id' hidden: (e) -> $selectbox.hide() # display:block overrides the hide-collapse rule $value.removeAttr('style') clicked: (user) -> page = $('body').data 'page' isIssueIndex = page is 'projects:issues:index' isMRIndex = page is page is 'projects:merge_requests:index' if $dropdown.hasClass('js-filter-bulk-update') return if $dropdown.hasClass('js-filter-submit') and (isIssueIndex or isMRIndex) selectedId = user.id Issuable.filterResults $dropdown.closest('form') else if $dropdown.hasClass 'js-filter-submit' $dropdown.closest('form').submit() else selected = $dropdown .closest('.selectbox') .find("input[name='#{$dropdown.data('field-name')}']").val() assignTo(selected) renderRow: (user) -> username = if user.username then "@#{user.username}" else "" avatar = if user.avatar_url then user.avatar_url else false selected = if user.id is selectedId then "is-active" else "" img = "" if user.beforeDivider? "<li> <a href='#' class='#{selected}'> #{user.name} </a> </li>" else if avatar img = "<img src='#{avatar}' class='avatar avatar-inline' width='30' />" # split into three parts so we can remove the username section if nessesary listWithName = "<li> <a href='#' class='dropdown-menu-user-link #{selected}'> #{img} <strong class='dropdown-menu-user-full-name'> #{user.name} </strong>" listWithUserName = "<span class='dropdown-menu-user-username'> #{username} </span>" listClosingTags = "</a> </li>" if username is '' listWithUserName = '' listWithName + listWithUserName + listClosingTags ) $('.ajax-users-select').each (i, select) => @projectId = $(select).data('project-id') @groupId = $(select).data('group-id') @showCurrentUser = $(select).data('current-user') @authorId = $(select).data('author-id') showNullUser = $(select).data('null-user') showAnyUser = $(select).data('any-user') showEmailUser = $(select).data('email-user') firstUser = $(select).data('first-user') $(select).select2 placeholder: "Search for a user" multiple: $(select).hasClass('multiselect') minimumInputLength: 0 query: (query) => @users query.term, (users) => data = { results: users } if query.term.length == 0 if firstUser # Move current user to the front of the list for obj, index in data.results if obj.username == firstUser data.results.splice(index, 1) data.results.unshift(obj) break if showNullUser nullUser = { name: 'Unassigned', id: 0 } data.results.unshift(nullUser) if showAnyUser name = showAnyUser name = 'Any User' if name == true anyUser = { name: name, id: null } data.results.unshift(anyUser) if showEmailUser && data.results.length == 0 && query.term.match(/^[^@]+@[^@]+$/) emailUser = { name: "Invite \"#{query.term}\"", username: query.term, id: query.term } data.results.unshift(emailUser) query.callback(data) initSelection: (args...) => @initSelection(args...) formatResult: (args...) => @formatResult(args...) formatSelection: (args...) => @formatSelection(args...) dropdownCssClass: "ajax-users-dropdown" escapeMarkup: (m) -> # we do not want to escape markup since we are displaying html in results m initSelection: (element, callback) -> id = $(element).val() if id == "0" nullUser = { name: 'Unassigned' } callback(nullUser) else if id != "" @user(id, callback) formatResult: (user) -> if user.avatar_url avatar = user.avatar_url else avatar = gon.default_avatar_url "<div class='user-result #{'no-username' unless user.username}'> <div class='user-image'><img class='avatar s24' src='#{avatar}'></div> <div class='user-name'>#{user.name}</div> <div class='user-username'>#{user.username || ""}</div> </div>" formatSelection: (user) -> user.name user: (user_id, callback) => url = @buildUrl(@userPath) url = url.replace(':id', user_id) $.ajax( url: url dataType: "json" ).done (user) -> callback(user) # Return users list. Filtered by query # Only active users retrieved users: (query, callback) => url = @buildUrl(@usersPath) $.ajax( url: url data: search: query per_page: 20 active: true project_id: @projectId group_id: @groupId current_user: @showCurrentUser author_id: @authorId dataType: "json" ).done (users) -> callback(users) buildUrl: (url) -> url = gon.relative_url_root.replace(/\/$/, '') + url if gon.relative_url_root? return url
true
class @UsersSelect constructor: (currentUser) -> @usersPath = "/autocomplete/users.json" @userPath = "/autocomplete/users/:id.json" if currentUser? @currentUser = JSON.parse(currentUser) $('.js-user-search').each (i, dropdown) => $dropdown = $(dropdown) @projectId = $dropdown.data('project-id') @showCurrentUser = $dropdown.data('current-user') showNullUser = $dropdown.data('null-user') showAnyUser = $dropdown.data('any-user') firstUser = $dropdown.data('first-user') @authorId = $dropdown.data('author-id') selectedId = $dropdown.data('selected') defaultLabel = $dropdown.data('default-label') issueURL = $dropdown.data('issueUpdate') $selectbox = $dropdown.closest('.selectbox') $block = $selectbox.closest('.block') abilityName = $dropdown.data('ability-name') $value = $block.find('.value') $collapsedSidebar = $block.find('.sidebar-collapsed-user') $loading = $block.find('.block-loading').fadeOut() $block.on('click', '.js-assign-yourself', (e) => e.preventDefault() assignTo(@currentUser.id) ) assignTo = (selected) -> data = {} data[abilityName] = {} data[abilityName].assignee_id = selected $loading .fadeIn() $dropdown.trigger('loading.gl.dropdown') $.ajax( type: 'PUT' dataType: 'json' url: issueURL data: data ).done (data) -> $dropdown.trigger('loaded.gl.dropdown') $loading.fadeOut() $selectbox.hide() if data.assignee user = name: data.assignee.name username: data.assignee.username avatar: data.assignee.avatar_url else user = name: 'Unassigned' username: '' avatar: '' $value.html(assigneeTemplate(user)) $collapsedSidebar.html(collapsedAssigneeTemplate(user)) collapsedAssigneeTemplate = _.template( '<% if( avatar ) { %> <a class="author_link" href="/u/<%= username %>"> <img width="24" class="avatar avatar-inline s24" alt="" src="<%= avatar %>"> <span class="author">PI:NAME:<NAME>END_PI</span> </a> <% } else { %> <i class="fa fa-user"></i> <% } %>' ) assigneeTemplate = _.template( '<% if (username) { %> <a class="author_link " href="/u/<%= username %>"> <% if( avatar ) { %> <img width="32" class="avatar avatar-inline s32" alt="" src="<%= avatar %>"> <% } %> <span class="author"><%= name %></span> <span class="username"> @<%= username %> </span> </a> <% } else { %> <span class="assign-yourself"> No assignee - <a href="#" class="js-assign-yourself"> assign yourself </a> </span> <% } %>' ) $dropdown.glDropdown( data: (term, callback) => @users term, (users) => if term.length is 0 showDivider = 0 if firstUser # Move current user to the front of the list for obj, index in users if obj.username == firstUser users.splice(index, 1) users.unshift(obj) break if showNullUser showDivider += 1 users.unshift( beforeDivider: true name: 'Unassigned', id: 0 ) if showAnyUser showDivider += 1 name = showAnyUser name = 'Any User' if name == true anyUser = { beforeDivider: true name: name, id: null } users.unshift(anyUser) if showDivider users.splice(showDivider, 0, "divider") # Send the data back callback users filterable: true filterRemote: true search: fields: ['name', 'username'] selectable: true fieldName: $dropdown.data('field-name') toggleLabel: (selected) -> if selected && 'id' of selected selected.name else defaultLabel inputId: 'issue_assignee_id' hidden: (e) -> $selectbox.hide() # display:block overrides the hide-collapse rule $value.removeAttr('style') clicked: (user) -> page = $('body').data 'page' isIssueIndex = page is 'projects:issues:index' isMRIndex = page is page is 'projects:merge_requests:index' if $dropdown.hasClass('js-filter-bulk-update') return if $dropdown.hasClass('js-filter-submit') and (isIssueIndex or isMRIndex) selectedId = user.id Issuable.filterResults $dropdown.closest('form') else if $dropdown.hasClass 'js-filter-submit' $dropdown.closest('form').submit() else selected = $dropdown .closest('.selectbox') .find("input[name='#{$dropdown.data('field-name')}']").val() assignTo(selected) renderRow: (user) -> username = if user.username then "@#{user.username}" else "" avatar = if user.avatar_url then user.avatar_url else false selected = if user.id is selectedId then "is-active" else "" img = "" if user.beforeDivider? "<li> <a href='#' class='#{selected}'> #{user.name} </a> </li>" else if avatar img = "<img src='#{avatar}' class='avatar avatar-inline' width='30' />" # split into three parts so we can remove the username section if nessesary listWithName = "<li> <a href='#' class='dropdown-menu-user-link #{selected}'> #{img} <strong class='dropdown-menu-user-full-name'> #{user.name} </strong>" listWithUserName = "<span class='dropdown-menu-user-username'> #{username} </span>" listClosingTags = "</a> </li>" if username is '' listWithUserName = '' listWithName + listWithUserName + listClosingTags ) $('.ajax-users-select').each (i, select) => @projectId = $(select).data('project-id') @groupId = $(select).data('group-id') @showCurrentUser = $(select).data('current-user') @authorId = $(select).data('author-id') showNullUser = $(select).data('null-user') showAnyUser = $(select).data('any-user') showEmailUser = $(select).data('email-user') firstUser = $(select).data('first-user') $(select).select2 placeholder: "Search for a user" multiple: $(select).hasClass('multiselect') minimumInputLength: 0 query: (query) => @users query.term, (users) => data = { results: users } if query.term.length == 0 if firstUser # Move current user to the front of the list for obj, index in data.results if obj.username == firstUser data.results.splice(index, 1) data.results.unshift(obj) break if showNullUser nullUser = { name: 'Unassigned', id: 0 } data.results.unshift(nullUser) if showAnyUser name = showAnyUser name = 'Any User' if name == true anyUser = { name: name, id: null } data.results.unshift(anyUser) if showEmailUser && data.results.length == 0 && query.term.match(/^[^@]+@[^@]+$/) emailUser = { name: "Invite \"#{query.term}\"", username: query.term, id: query.term } data.results.unshift(emailUser) query.callback(data) initSelection: (args...) => @initSelection(args...) formatResult: (args...) => @formatResult(args...) formatSelection: (args...) => @formatSelection(args...) dropdownCssClass: "ajax-users-dropdown" escapeMarkup: (m) -> # we do not want to escape markup since we are displaying html in results m initSelection: (element, callback) -> id = $(element).val() if id == "0" nullUser = { name: 'Unassigned' } callback(nullUser) else if id != "" @user(id, callback) formatResult: (user) -> if user.avatar_url avatar = user.avatar_url else avatar = gon.default_avatar_url "<div class='user-result #{'no-username' unless user.username}'> <div class='user-image'><img class='avatar s24' src='#{avatar}'></div> <div class='user-name'>#{user.name}</div> <div class='user-username'>#{user.username || ""}</div> </div>" formatSelection: (user) -> user.name user: (user_id, callback) => url = @buildUrl(@userPath) url = url.replace(':id', user_id) $.ajax( url: url dataType: "json" ).done (user) -> callback(user) # Return users list. Filtered by query # Only active users retrieved users: (query, callback) => url = @buildUrl(@usersPath) $.ajax( url: url data: search: query per_page: 20 active: true project_id: @projectId group_id: @groupId current_user: @showCurrentUser author_id: @authorId dataType: "json" ).done (users) -> callback(users) buildUrl: (url) -> url = gon.relative_url_root.replace(/\/$/, '') + url if gon.relative_url_root? return url
[ { "context": "###\n\nMVCoffee\n\nCopyright 2016, Kirk Bowers\nMIT License\n\nVersion 1.1.1\n\n###\n\n# Make sure ther", "end": 42, "score": 0.9998503923416138, "start": 31, "tag": "NAME", "value": "Kirk Bowers" } ]
src/main.js.coffee
kirkbowers/mvcoffee
0
### MVCoffee Copyright 2016, Kirk Bowers MIT License Version 1.1.1 ### # Make sure there is an MVCoffee object on the global namespace # This little bit of mojo lets us export things into node.js and letting node's # exports mechanism handle namespacing for us. You'd do this in node land: # var MVCoffee = require('mvcoffee'); if exports? MVCoffee = exports else # On the other hand, in the more likely case we are not in node, we need to create # an MVCoffee object on the global object, then assign the local MVCoffee variable # created by the above assignment as an alias to the object of the same name on this. this.MVCoffee || (this.MVCoffee = {}) MVCoffee = this.MVCoffee # polyfill Array.isArray, just in case if !Array.isArray Array.isArray = (arg) -> Object.prototype.toString.call(arg) is '[object Array]'
215552
### MVCoffee Copyright 2016, <NAME> MIT License Version 1.1.1 ### # Make sure there is an MVCoffee object on the global namespace # This little bit of mojo lets us export things into node.js and letting node's # exports mechanism handle namespacing for us. You'd do this in node land: # var MVCoffee = require('mvcoffee'); if exports? MVCoffee = exports else # On the other hand, in the more likely case we are not in node, we need to create # an MVCoffee object on the global object, then assign the local MVCoffee variable # created by the above assignment as an alias to the object of the same name on this. this.MVCoffee || (this.MVCoffee = {}) MVCoffee = this.MVCoffee # polyfill Array.isArray, just in case if !Array.isArray Array.isArray = (arg) -> Object.prototype.toString.call(arg) is '[object Array]'
true
### MVCoffee Copyright 2016, PI:NAME:<NAME>END_PI MIT License Version 1.1.1 ### # Make sure there is an MVCoffee object on the global namespace # This little bit of mojo lets us export things into node.js and letting node's # exports mechanism handle namespacing for us. You'd do this in node land: # var MVCoffee = require('mvcoffee'); if exports? MVCoffee = exports else # On the other hand, in the more likely case we are not in node, we need to create # an MVCoffee object on the global object, then assign the local MVCoffee variable # created by the above assignment as an alias to the object of the same name on this. this.MVCoffee || (this.MVCoffee = {}) MVCoffee = this.MVCoffee # polyfill Array.isArray, just in case if !Array.isArray Array.isArray = (arg) -> Object.prototype.toString.call(arg) is '[object Array]'
[ { "context": "module.exports = [\n student: \"51a5a56f4867bbdf51054054\"\n data:\n foo: 'bar'\n]\n", "end": 55, "score": 0.9329530596733093, "start": 31, "tag": "KEY", "value": "51a5a56f4867bbdf51054054" } ]
test/mock_data/studentproperties.coffee
Clever/clever-js
10
module.exports = [ student: "51a5a56f4867bbdf51054054" data: foo: 'bar' ]
137392
module.exports = [ student: "<KEY>" data: foo: 'bar' ]
true
module.exports = [ student: "PI:KEY:<KEY>END_PI" data: foo: 'bar' ]
[ { "context": "send(\n Indicator, 'create', {\n name: \"Anne Test Indicator\"\n theme: theme\n indicatorDefinition", "end": 11377, "score": 0.9883909821510315, "start": 11358, "tag": "NAME", "value": "Anne Test Indicator" } ]
server/test/units/indicator.coffee
unepwcmc/NRT
0
assert = require('chai').assert helpers = require '../helpers' _ = require('underscore') Q = require('q') Promise = require('bluebird') sinon = require('sinon') Theme = require('../../models/theme').model Indicator = require('../../models/indicator').model IndicatorData = require('../../models/indicator_data').model Page = require('../../models/page').model HeadlineService = require '../../lib/services/headline' suite('Indicator') test('.getIndicatorDataForCSV with no filters returns all indicator data in a 2D array', (done) -> data = [ { "year": 2000, "value": 4 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] expectedData = [ ['year', 'value'], ["2000","4"], ["2001","4"], ["2002","4"] ] indicator = new Indicator( indicatorDefinition: xAxis: 'year' yAxis: 'value' ) indicatorData = new IndicatorData( data: data ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorDataForCSV( (err, indicatorData) -> assert.ok( _.isEqual(indicatorData, expectedData), "Expected \n#{JSON.stringify(indicatorData)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorDataForCSV converts all fields to String', (done) -> data = [ { "date": new Date(2000, 12), "value": 4 } ] indicator = new Indicator( indicatorDefinition: xAxis: 'date' yAxis: 'value' ) getIndicatorDataStub = sinon.stub(indicator, 'getIndicatorData', (filters, callback) -> callback(null, data) ) try indicator.getIndicatorDataForCSV( (err, indicatorData) -> if err? getIndicatorDataStub.restore() return done(err) date = indicatorData[1][0] value = indicatorData[1][1] assert.typeOf date, 'string' assert.typeOf value, 'string' assert.match date, /Mon Jan 01 2001 00:00:00 GMT\+0000/ assert.strictEqual value, "4" done() ) catch err getIndicatorDataStub.restore() done(err) ) test('.getIndicatorDataForCSV with filters returns data matching filters in a 2D array', (done) -> data = [ { "year": 2000, "value": 3 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] expectedData = [ ['year', 'value'], ["2001","4"], ["2002","4"] ] indicator = new Indicator( indicatorDefinition: xAxis: 'year' yAxis: 'value' ) indicatorData = new IndicatorData( data: data ) filters = value: min: '4' Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorDataForCSV( filters, (err, indicatorData) -> assert.ok( _.isEqual(indicatorData, expectedData), "Expected \n#{JSON.stringify(indicatorData)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData with no filters returns all indicator data for this indicator', (done) -> expectedData = [ { "year": 2000, "value": 4 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] indicator = new Indicator() indicatorData = new IndicatorData( data: expectedData ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorData((err, data) -> assert.ok( _.isEqual(data, expectedData), "Expected \n#{JSON.stringify(data)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData with an integer filter \'min\' value returns the data correctly filtered', (done) -> fullData = [ { "year": 2000, "value": 3 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 7 } ] expectedFilteredData = [fullData[1], fullData[2]] indicator = new Indicator() indicatorData = new IndicatorData( data: fullData ) filters = value: min: '4' Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorData(filters, (err, data) -> assert.ok( _.isEqual(data, expectedFilteredData), "Expected \n#{JSON.stringify(data)} \nto equal \n#{JSON.stringify(expectedFilteredData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData on an indicator with no indicator data returns an empty array', (done) -> indicator = new Indicator() indicator.getIndicatorData((err, data) -> if err? throw err assert.ok _.isEqual(data, []), "Expected returned data to be an empty array" done() ) ) test('#calculateIndicatorDataBounds should return the upper and lower bounds of data', (done) -> indicatorData = [ { "year": 2000, "value": 2 }, { "year": 2001, "value": 9 }, { "year": 2002, "value": 4 } ] indicator = new Indicator( indicatorDefinition: fields: [{ name: 'year' type: 'integer' }, { name: "value", type: "integer" }] ) indicatorData = new IndicatorData( data: indicatorData ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.calculateIndicatorDataBounds((err, data) -> assert.property( data, 'year' ) assert.property( data, 'value' ) assert.strictEqual(data.year.min, 2000) assert.strictEqual(data.year.max, 2002) assert.strictEqual(data.value.min, 2) assert.strictEqual(data.value.max, 9) done() ) ).catch((err) -> console.error err throw err ) ) test('.getPage should be mixed in', -> indicator = new Indicator() assert.typeOf indicator.getPage, 'Function' ) test('.getFatPage should be mixed in', -> indicator = new Indicator() assert.typeOf indicator.getFatPage, 'Function' ) test(".toObjectWithNestedPage is mixed in", -> indicator = new Indicator() assert.typeOf indicator.toObjectWithNestedPage, 'Function' ) test("#findWhereIndicatorHasData returns only indicators with indicator data", (done)-> indicatorWithData = indicatorWithoutData = null helpers.createIndicatorModels([{},{}]).then((indicators) -> indicatorWithData = indicators[0] indicatorWithoutData = indicators[1] helpers.createIndicatorData({ indicator: indicatorWithData data: [{some: 'data'}] }) ).then((indicatorData) -> Indicator.findWhereIndicatorHasData() ).then((indicators) -> assert.lengthOf indicators, 1, "Expected only the one indicator with data to be returned" assert.strictEqual indicators[0]._id.toString(), indicatorWithData._id.toString(), "Expected the returned indicator to be the indicator with data" done() ).catch((err) -> console.error err console.error err.stack throw err ) ) test("#findWhereIndicatorHasData respects the given filters", (done)-> indicatorToFind = indicatorToFilterOut = null helpers.createIndicatorModels([{},{}]).then((indicators) -> indicatorToFind = indicators[0] indicatorToFilterOut = indicators[1] helpers.createIndicatorData({ indicator: indicatorToFind data: [{some: 'data'}] }) ).then((indicatorData) -> helpers.createIndicatorData({ indicator: indicatorToFilterOut data: [{some: 'data'}] }) ).then((indicatorData) -> Indicator.findWhereIndicatorHasData(_id: indicatorToFind._id) ).then((indicators) -> assert.lengthOf indicators, 1, "Expected only the one indicator with data to be returned" assert.strictEqual indicators[0]._id.toString(), indicatorToFind._id.toString(), "Expected the returned indicator to be the indicator with data" done() ).catch((err) -> console.error err console.error err.stack throw err ) ) test(".hasData returns true when an indicator has data", (done)-> indicatorWithData = null helpers.createIndicatorModels([{}]).then((indicators) -> indicatorWithData = indicators[0] helpers.createIndicatorData({ indicator: indicatorWithData data: [{some: 'data'}] }) ).then((indicatorData) -> indicatorWithData.hasData() ).then((hasData) -> try assert.isTrue hasData done() catch err done(err) ).catch(done) ) test(".hasData returns false when an indicator has no data", (done)-> helpers.createIndicatorModels([{}]).then((indicators) -> indicators[0].hasData() ).then((hasData) -> try assert.isFalse hasData done() catch err done(err) ).catch(done) ) test('#populatePages given an array of indicators, populates their page attributes', (done) -> indicator = new Indicator() page = new Page() sinon.stub(indicator, 'populatePage', -> indicator.page = page Promise.resolve() ) Indicator.populatePages([indicator]).then( -> assert.ok _.isEqual(indicator.page, page), "Expected the page attribute to be populated with the indicator page" done() ).catch((err) -> console.error err throw err ) ) test("#calculateBoundsForType when given an unkown type returns null", -> bounds = Indicator.calculateBoundsForType("party", [], 'fieldName') assert.isNull bounds, "Expected returned bounds to be null" ) test("#calculateBoundsForType given an array of dates returns the correct bounds", -> dates = [ {value: new Date("2011")}, {value: new Date("2016")}, {value: new Date("2014")} ] bounds = Indicator.calculateBoundsForType("date", dates, 'value') assert.strictEqual bounds.min.getFullYear(), 2011 assert.strictEqual bounds.max.getFullYear(), 2016 ) test("#calculateBoundsForType given text returns null", -> text = [ {value: 'hat'}, {value: 'boat'} ] bounds = Indicator.calculateBoundsForType("text", text, 'value') assert.isNull bounds ) test('.convertNestedParametersToAssociationIds converts a Theme object to a Theme ID', -> indicator = new Indicator() theme = new Theme() indicatorAttributes = indicator.toObject() indicatorAttributes.theme = theme.toObject() indicatorWithThemeId = Indicator.convertNestedParametersToAssociationIds(indicatorAttributes) assert.strictEqual( indicatorWithThemeId.theme, theme.id, 'Expected indicator theme to be an ID only' ) ) test(".generateMetadataCSV returns CSV arrays containing the name, theme, period and data date", (done) -> theIndicator = theTheme = newestHeadlineStub = null Q.nsend( Theme, 'create', { title: 'Air Quality' } ).then( (theme) -> theTheme = theme Q.nsend( Indicator, 'create', { name: "Anne Test Indicator" theme: theme indicatorDefinition: period: 'quarterly' xAxis: 'year' } ) ).then( (indicator) -> theIndicator = indicator newestHeadlineStub = sinon.stub(HeadlineService::, 'getNewestHeadline', -> Q.fcall(-> year: 2006 ) ) theIndicator.generateMetadataCSV() ).then((csvData) -> try assert.lengthOf csvData, 2, "Expected data to have 2 rows: header and data" titleRow = csvData[0] dataRow = csvData[1] assert.strictEqual titleRow[0], 'Indicator', "Expected the first column to be the indicator name" assert.strictEqual dataRow[0], theIndicator.name, "Expected the indicator name to be the name of the indicator" assert.strictEqual titleRow[1], 'Theme', "Expected the second column to be the theme" assert.strictEqual dataRow[1], theTheme.title, "Expected the theme to be the name of the indicator's theme" assert.strictEqual titleRow[2], 'Collection Frequency', "Expected the 3rd column to be the collection frequency" assert.strictEqual dataRow[2], theIndicator.indicatorDefinition.period, "Expected the Collection Frequency to be the indicator's period" assert.strictEqual titleRow[3], 'Date Updated', "Expected the 4th column to be the date updated" assert.strictEqual dataRow[3], 2006, "Expected the date updated to be 2006" done() catch e done(e) finally newestHeadlineStub.restore() ).catch( (err) -> done(err) newestHeadlineStub.restore() ) ) test(".generateMetadataCSV on an indicator with no theme or indicator defintion returns blank values for those fields", (done) -> indicator = new Indicator() indicator.generateMetadataCSV().then( (csvData)-> try assert.lengthOf csvData, 2, "Expected data to have 2 rows: header and data" titleRow = csvData[0] dataRow = csvData[1] assert.strictEqual titleRow[1], 'Theme', "Expected the second column to be the theme" assert.isUndefined dataRow[1], "Expected the theme to be blank" assert.strictEqual titleRow[2], 'Collection Frequency', "Expected the 3rd column to be the collection frequency" assert.isUndefined dataRow[2], "Expected the Collection Frequency to be blank" assert.strictEqual titleRow[3], 'Date Updated', "Expected the 4th column to be the date updated" assert.strictEqual dataRow[3], '', "Expected the date updated to be blank" done() catch e done(e) ).catch( (err) -> done(err) ) ) test("#seedData when no seed file exist reports an appropriate error", (done) -> fs = require('fs') existsSyncStub = sinon.stub(fs, 'existsSync', -> false) Indicator.seedData('./config/seeds/indicators.json').then( -> done("Expected Indicator.seedData to fail") ).catch( (err)-> assert.strictEqual( err.message, "Unable to load indicator seed file, have you copied seeds from config/instances/ to config/seeds/?" ) done() ).finally( -> existsSyncStub.restore() ) ) test('#CONDITIONS.IS_PRIMARY only returns indicators with indicators with primary: true', (done) -> helpers.createIndicatorModels([{ primary: true }, { primary: false }]).then(-> Indicator.find(Indicator.CONDITIONS.IS_PRIMARY).exec() ).then((indicators)-> try assert.lengthOf indicators, 1, "Only expected the primary indicator to be returned" done() catch err done(err) ).catch(done) ) test('creating a new Indicator without an "indicatorationConfig" attribute initialises it with a empty object', -> indicator = new Indicator() assert.deepEqual indicator.indicatorationConfig, {}, "Expected indicator.indicatoration to be defaulted to {}" )
56389
assert = require('chai').assert helpers = require '../helpers' _ = require('underscore') Q = require('q') Promise = require('bluebird') sinon = require('sinon') Theme = require('../../models/theme').model Indicator = require('../../models/indicator').model IndicatorData = require('../../models/indicator_data').model Page = require('../../models/page').model HeadlineService = require '../../lib/services/headline' suite('Indicator') test('.getIndicatorDataForCSV with no filters returns all indicator data in a 2D array', (done) -> data = [ { "year": 2000, "value": 4 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] expectedData = [ ['year', 'value'], ["2000","4"], ["2001","4"], ["2002","4"] ] indicator = new Indicator( indicatorDefinition: xAxis: 'year' yAxis: 'value' ) indicatorData = new IndicatorData( data: data ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorDataForCSV( (err, indicatorData) -> assert.ok( _.isEqual(indicatorData, expectedData), "Expected \n#{JSON.stringify(indicatorData)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorDataForCSV converts all fields to String', (done) -> data = [ { "date": new Date(2000, 12), "value": 4 } ] indicator = new Indicator( indicatorDefinition: xAxis: 'date' yAxis: 'value' ) getIndicatorDataStub = sinon.stub(indicator, 'getIndicatorData', (filters, callback) -> callback(null, data) ) try indicator.getIndicatorDataForCSV( (err, indicatorData) -> if err? getIndicatorDataStub.restore() return done(err) date = indicatorData[1][0] value = indicatorData[1][1] assert.typeOf date, 'string' assert.typeOf value, 'string' assert.match date, /Mon Jan 01 2001 00:00:00 GMT\+0000/ assert.strictEqual value, "4" done() ) catch err getIndicatorDataStub.restore() done(err) ) test('.getIndicatorDataForCSV with filters returns data matching filters in a 2D array', (done) -> data = [ { "year": 2000, "value": 3 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] expectedData = [ ['year', 'value'], ["2001","4"], ["2002","4"] ] indicator = new Indicator( indicatorDefinition: xAxis: 'year' yAxis: 'value' ) indicatorData = new IndicatorData( data: data ) filters = value: min: '4' Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorDataForCSV( filters, (err, indicatorData) -> assert.ok( _.isEqual(indicatorData, expectedData), "Expected \n#{JSON.stringify(indicatorData)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData with no filters returns all indicator data for this indicator', (done) -> expectedData = [ { "year": 2000, "value": 4 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] indicator = new Indicator() indicatorData = new IndicatorData( data: expectedData ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorData((err, data) -> assert.ok( _.isEqual(data, expectedData), "Expected \n#{JSON.stringify(data)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData with an integer filter \'min\' value returns the data correctly filtered', (done) -> fullData = [ { "year": 2000, "value": 3 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 7 } ] expectedFilteredData = [fullData[1], fullData[2]] indicator = new Indicator() indicatorData = new IndicatorData( data: fullData ) filters = value: min: '4' Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorData(filters, (err, data) -> assert.ok( _.isEqual(data, expectedFilteredData), "Expected \n#{JSON.stringify(data)} \nto equal \n#{JSON.stringify(expectedFilteredData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData on an indicator with no indicator data returns an empty array', (done) -> indicator = new Indicator() indicator.getIndicatorData((err, data) -> if err? throw err assert.ok _.isEqual(data, []), "Expected returned data to be an empty array" done() ) ) test('#calculateIndicatorDataBounds should return the upper and lower bounds of data', (done) -> indicatorData = [ { "year": 2000, "value": 2 }, { "year": 2001, "value": 9 }, { "year": 2002, "value": 4 } ] indicator = new Indicator( indicatorDefinition: fields: [{ name: 'year' type: 'integer' }, { name: "value", type: "integer" }] ) indicatorData = new IndicatorData( data: indicatorData ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.calculateIndicatorDataBounds((err, data) -> assert.property( data, 'year' ) assert.property( data, 'value' ) assert.strictEqual(data.year.min, 2000) assert.strictEqual(data.year.max, 2002) assert.strictEqual(data.value.min, 2) assert.strictEqual(data.value.max, 9) done() ) ).catch((err) -> console.error err throw err ) ) test('.getPage should be mixed in', -> indicator = new Indicator() assert.typeOf indicator.getPage, 'Function' ) test('.getFatPage should be mixed in', -> indicator = new Indicator() assert.typeOf indicator.getFatPage, 'Function' ) test(".toObjectWithNestedPage is mixed in", -> indicator = new Indicator() assert.typeOf indicator.toObjectWithNestedPage, 'Function' ) test("#findWhereIndicatorHasData returns only indicators with indicator data", (done)-> indicatorWithData = indicatorWithoutData = null helpers.createIndicatorModels([{},{}]).then((indicators) -> indicatorWithData = indicators[0] indicatorWithoutData = indicators[1] helpers.createIndicatorData({ indicator: indicatorWithData data: [{some: 'data'}] }) ).then((indicatorData) -> Indicator.findWhereIndicatorHasData() ).then((indicators) -> assert.lengthOf indicators, 1, "Expected only the one indicator with data to be returned" assert.strictEqual indicators[0]._id.toString(), indicatorWithData._id.toString(), "Expected the returned indicator to be the indicator with data" done() ).catch((err) -> console.error err console.error err.stack throw err ) ) test("#findWhereIndicatorHasData respects the given filters", (done)-> indicatorToFind = indicatorToFilterOut = null helpers.createIndicatorModels([{},{}]).then((indicators) -> indicatorToFind = indicators[0] indicatorToFilterOut = indicators[1] helpers.createIndicatorData({ indicator: indicatorToFind data: [{some: 'data'}] }) ).then((indicatorData) -> helpers.createIndicatorData({ indicator: indicatorToFilterOut data: [{some: 'data'}] }) ).then((indicatorData) -> Indicator.findWhereIndicatorHasData(_id: indicatorToFind._id) ).then((indicators) -> assert.lengthOf indicators, 1, "Expected only the one indicator with data to be returned" assert.strictEqual indicators[0]._id.toString(), indicatorToFind._id.toString(), "Expected the returned indicator to be the indicator with data" done() ).catch((err) -> console.error err console.error err.stack throw err ) ) test(".hasData returns true when an indicator has data", (done)-> indicatorWithData = null helpers.createIndicatorModels([{}]).then((indicators) -> indicatorWithData = indicators[0] helpers.createIndicatorData({ indicator: indicatorWithData data: [{some: 'data'}] }) ).then((indicatorData) -> indicatorWithData.hasData() ).then((hasData) -> try assert.isTrue hasData done() catch err done(err) ).catch(done) ) test(".hasData returns false when an indicator has no data", (done)-> helpers.createIndicatorModels([{}]).then((indicators) -> indicators[0].hasData() ).then((hasData) -> try assert.isFalse hasData done() catch err done(err) ).catch(done) ) test('#populatePages given an array of indicators, populates their page attributes', (done) -> indicator = new Indicator() page = new Page() sinon.stub(indicator, 'populatePage', -> indicator.page = page Promise.resolve() ) Indicator.populatePages([indicator]).then( -> assert.ok _.isEqual(indicator.page, page), "Expected the page attribute to be populated with the indicator page" done() ).catch((err) -> console.error err throw err ) ) test("#calculateBoundsForType when given an unkown type returns null", -> bounds = Indicator.calculateBoundsForType("party", [], 'fieldName') assert.isNull bounds, "Expected returned bounds to be null" ) test("#calculateBoundsForType given an array of dates returns the correct bounds", -> dates = [ {value: new Date("2011")}, {value: new Date("2016")}, {value: new Date("2014")} ] bounds = Indicator.calculateBoundsForType("date", dates, 'value') assert.strictEqual bounds.min.getFullYear(), 2011 assert.strictEqual bounds.max.getFullYear(), 2016 ) test("#calculateBoundsForType given text returns null", -> text = [ {value: 'hat'}, {value: 'boat'} ] bounds = Indicator.calculateBoundsForType("text", text, 'value') assert.isNull bounds ) test('.convertNestedParametersToAssociationIds converts a Theme object to a Theme ID', -> indicator = new Indicator() theme = new Theme() indicatorAttributes = indicator.toObject() indicatorAttributes.theme = theme.toObject() indicatorWithThemeId = Indicator.convertNestedParametersToAssociationIds(indicatorAttributes) assert.strictEqual( indicatorWithThemeId.theme, theme.id, 'Expected indicator theme to be an ID only' ) ) test(".generateMetadataCSV returns CSV arrays containing the name, theme, period and data date", (done) -> theIndicator = theTheme = newestHeadlineStub = null Q.nsend( Theme, 'create', { title: 'Air Quality' } ).then( (theme) -> theTheme = theme Q.nsend( Indicator, 'create', { name: "<NAME>" theme: theme indicatorDefinition: period: 'quarterly' xAxis: 'year' } ) ).then( (indicator) -> theIndicator = indicator newestHeadlineStub = sinon.stub(HeadlineService::, 'getNewestHeadline', -> Q.fcall(-> year: 2006 ) ) theIndicator.generateMetadataCSV() ).then((csvData) -> try assert.lengthOf csvData, 2, "Expected data to have 2 rows: header and data" titleRow = csvData[0] dataRow = csvData[1] assert.strictEqual titleRow[0], 'Indicator', "Expected the first column to be the indicator name" assert.strictEqual dataRow[0], theIndicator.name, "Expected the indicator name to be the name of the indicator" assert.strictEqual titleRow[1], 'Theme', "Expected the second column to be the theme" assert.strictEqual dataRow[1], theTheme.title, "Expected the theme to be the name of the indicator's theme" assert.strictEqual titleRow[2], 'Collection Frequency', "Expected the 3rd column to be the collection frequency" assert.strictEqual dataRow[2], theIndicator.indicatorDefinition.period, "Expected the Collection Frequency to be the indicator's period" assert.strictEqual titleRow[3], 'Date Updated', "Expected the 4th column to be the date updated" assert.strictEqual dataRow[3], 2006, "Expected the date updated to be 2006" done() catch e done(e) finally newestHeadlineStub.restore() ).catch( (err) -> done(err) newestHeadlineStub.restore() ) ) test(".generateMetadataCSV on an indicator with no theme or indicator defintion returns blank values for those fields", (done) -> indicator = new Indicator() indicator.generateMetadataCSV().then( (csvData)-> try assert.lengthOf csvData, 2, "Expected data to have 2 rows: header and data" titleRow = csvData[0] dataRow = csvData[1] assert.strictEqual titleRow[1], 'Theme', "Expected the second column to be the theme" assert.isUndefined dataRow[1], "Expected the theme to be blank" assert.strictEqual titleRow[2], 'Collection Frequency', "Expected the 3rd column to be the collection frequency" assert.isUndefined dataRow[2], "Expected the Collection Frequency to be blank" assert.strictEqual titleRow[3], 'Date Updated', "Expected the 4th column to be the date updated" assert.strictEqual dataRow[3], '', "Expected the date updated to be blank" done() catch e done(e) ).catch( (err) -> done(err) ) ) test("#seedData when no seed file exist reports an appropriate error", (done) -> fs = require('fs') existsSyncStub = sinon.stub(fs, 'existsSync', -> false) Indicator.seedData('./config/seeds/indicators.json').then( -> done("Expected Indicator.seedData to fail") ).catch( (err)-> assert.strictEqual( err.message, "Unable to load indicator seed file, have you copied seeds from config/instances/ to config/seeds/?" ) done() ).finally( -> existsSyncStub.restore() ) ) test('#CONDITIONS.IS_PRIMARY only returns indicators with indicators with primary: true', (done) -> helpers.createIndicatorModels([{ primary: true }, { primary: false }]).then(-> Indicator.find(Indicator.CONDITIONS.IS_PRIMARY).exec() ).then((indicators)-> try assert.lengthOf indicators, 1, "Only expected the primary indicator to be returned" done() catch err done(err) ).catch(done) ) test('creating a new Indicator without an "indicatorationConfig" attribute initialises it with a empty object', -> indicator = new Indicator() assert.deepEqual indicator.indicatorationConfig, {}, "Expected indicator.indicatoration to be defaulted to {}" )
true
assert = require('chai').assert helpers = require '../helpers' _ = require('underscore') Q = require('q') Promise = require('bluebird') sinon = require('sinon') Theme = require('../../models/theme').model Indicator = require('../../models/indicator').model IndicatorData = require('../../models/indicator_data').model Page = require('../../models/page').model HeadlineService = require '../../lib/services/headline' suite('Indicator') test('.getIndicatorDataForCSV with no filters returns all indicator data in a 2D array', (done) -> data = [ { "year": 2000, "value": 4 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] expectedData = [ ['year', 'value'], ["2000","4"], ["2001","4"], ["2002","4"] ] indicator = new Indicator( indicatorDefinition: xAxis: 'year' yAxis: 'value' ) indicatorData = new IndicatorData( data: data ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorDataForCSV( (err, indicatorData) -> assert.ok( _.isEqual(indicatorData, expectedData), "Expected \n#{JSON.stringify(indicatorData)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorDataForCSV converts all fields to String', (done) -> data = [ { "date": new Date(2000, 12), "value": 4 } ] indicator = new Indicator( indicatorDefinition: xAxis: 'date' yAxis: 'value' ) getIndicatorDataStub = sinon.stub(indicator, 'getIndicatorData', (filters, callback) -> callback(null, data) ) try indicator.getIndicatorDataForCSV( (err, indicatorData) -> if err? getIndicatorDataStub.restore() return done(err) date = indicatorData[1][0] value = indicatorData[1][1] assert.typeOf date, 'string' assert.typeOf value, 'string' assert.match date, /Mon Jan 01 2001 00:00:00 GMT\+0000/ assert.strictEqual value, "4" done() ) catch err getIndicatorDataStub.restore() done(err) ) test('.getIndicatorDataForCSV with filters returns data matching filters in a 2D array', (done) -> data = [ { "year": 2000, "value": 3 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] expectedData = [ ['year', 'value'], ["2001","4"], ["2002","4"] ] indicator = new Indicator( indicatorDefinition: xAxis: 'year' yAxis: 'value' ) indicatorData = new IndicatorData( data: data ) filters = value: min: '4' Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorDataForCSV( filters, (err, indicatorData) -> assert.ok( _.isEqual(indicatorData, expectedData), "Expected \n#{JSON.stringify(indicatorData)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData with no filters returns all indicator data for this indicator', (done) -> expectedData = [ { "year": 2000, "value": 4 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 4 } ] indicator = new Indicator() indicatorData = new IndicatorData( data: expectedData ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorData((err, data) -> assert.ok( _.isEqual(data, expectedData), "Expected \n#{JSON.stringify(data)} \nto equal \n#{JSON.stringify(expectedData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData with an integer filter \'min\' value returns the data correctly filtered', (done) -> fullData = [ { "year": 2000, "value": 3 }, { "year": 2001, "value": 4 }, { "year": 2002, "value": 7 } ] expectedFilteredData = [fullData[1], fullData[2]] indicator = new Indicator() indicatorData = new IndicatorData( data: fullData ) filters = value: min: '4' Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.getIndicatorData(filters, (err, data) -> assert.ok( _.isEqual(data, expectedFilteredData), "Expected \n#{JSON.stringify(data)} \nto equal \n#{JSON.stringify(expectedFilteredData)}" ) done() ) ).catch((err) -> console.error err throw err ) ) test('.getIndicatorData on an indicator with no indicator data returns an empty array', (done) -> indicator = new Indicator() indicator.getIndicatorData((err, data) -> if err? throw err assert.ok _.isEqual(data, []), "Expected returned data to be an empty array" done() ) ) test('#calculateIndicatorDataBounds should return the upper and lower bounds of data', (done) -> indicatorData = [ { "year": 2000, "value": 2 }, { "year": 2001, "value": 9 }, { "year": 2002, "value": 4 } ] indicator = new Indicator( indicatorDefinition: fields: [{ name: 'year' type: 'integer' }, { name: "value", type: "integer" }] ) indicatorData = new IndicatorData( data: indicatorData ) Q.nsend( indicator, 'save' ).then(-> indicatorData.indicator = indicator Q.nsend( indicatorData, 'save' ) ).then( -> indicator.calculateIndicatorDataBounds((err, data) -> assert.property( data, 'year' ) assert.property( data, 'value' ) assert.strictEqual(data.year.min, 2000) assert.strictEqual(data.year.max, 2002) assert.strictEqual(data.value.min, 2) assert.strictEqual(data.value.max, 9) done() ) ).catch((err) -> console.error err throw err ) ) test('.getPage should be mixed in', -> indicator = new Indicator() assert.typeOf indicator.getPage, 'Function' ) test('.getFatPage should be mixed in', -> indicator = new Indicator() assert.typeOf indicator.getFatPage, 'Function' ) test(".toObjectWithNestedPage is mixed in", -> indicator = new Indicator() assert.typeOf indicator.toObjectWithNestedPage, 'Function' ) test("#findWhereIndicatorHasData returns only indicators with indicator data", (done)-> indicatorWithData = indicatorWithoutData = null helpers.createIndicatorModels([{},{}]).then((indicators) -> indicatorWithData = indicators[0] indicatorWithoutData = indicators[1] helpers.createIndicatorData({ indicator: indicatorWithData data: [{some: 'data'}] }) ).then((indicatorData) -> Indicator.findWhereIndicatorHasData() ).then((indicators) -> assert.lengthOf indicators, 1, "Expected only the one indicator with data to be returned" assert.strictEqual indicators[0]._id.toString(), indicatorWithData._id.toString(), "Expected the returned indicator to be the indicator with data" done() ).catch((err) -> console.error err console.error err.stack throw err ) ) test("#findWhereIndicatorHasData respects the given filters", (done)-> indicatorToFind = indicatorToFilterOut = null helpers.createIndicatorModels([{},{}]).then((indicators) -> indicatorToFind = indicators[0] indicatorToFilterOut = indicators[1] helpers.createIndicatorData({ indicator: indicatorToFind data: [{some: 'data'}] }) ).then((indicatorData) -> helpers.createIndicatorData({ indicator: indicatorToFilterOut data: [{some: 'data'}] }) ).then((indicatorData) -> Indicator.findWhereIndicatorHasData(_id: indicatorToFind._id) ).then((indicators) -> assert.lengthOf indicators, 1, "Expected only the one indicator with data to be returned" assert.strictEqual indicators[0]._id.toString(), indicatorToFind._id.toString(), "Expected the returned indicator to be the indicator with data" done() ).catch((err) -> console.error err console.error err.stack throw err ) ) test(".hasData returns true when an indicator has data", (done)-> indicatorWithData = null helpers.createIndicatorModels([{}]).then((indicators) -> indicatorWithData = indicators[0] helpers.createIndicatorData({ indicator: indicatorWithData data: [{some: 'data'}] }) ).then((indicatorData) -> indicatorWithData.hasData() ).then((hasData) -> try assert.isTrue hasData done() catch err done(err) ).catch(done) ) test(".hasData returns false when an indicator has no data", (done)-> helpers.createIndicatorModels([{}]).then((indicators) -> indicators[0].hasData() ).then((hasData) -> try assert.isFalse hasData done() catch err done(err) ).catch(done) ) test('#populatePages given an array of indicators, populates their page attributes', (done) -> indicator = new Indicator() page = new Page() sinon.stub(indicator, 'populatePage', -> indicator.page = page Promise.resolve() ) Indicator.populatePages([indicator]).then( -> assert.ok _.isEqual(indicator.page, page), "Expected the page attribute to be populated with the indicator page" done() ).catch((err) -> console.error err throw err ) ) test("#calculateBoundsForType when given an unkown type returns null", -> bounds = Indicator.calculateBoundsForType("party", [], 'fieldName') assert.isNull bounds, "Expected returned bounds to be null" ) test("#calculateBoundsForType given an array of dates returns the correct bounds", -> dates = [ {value: new Date("2011")}, {value: new Date("2016")}, {value: new Date("2014")} ] bounds = Indicator.calculateBoundsForType("date", dates, 'value') assert.strictEqual bounds.min.getFullYear(), 2011 assert.strictEqual bounds.max.getFullYear(), 2016 ) test("#calculateBoundsForType given text returns null", -> text = [ {value: 'hat'}, {value: 'boat'} ] bounds = Indicator.calculateBoundsForType("text", text, 'value') assert.isNull bounds ) test('.convertNestedParametersToAssociationIds converts a Theme object to a Theme ID', -> indicator = new Indicator() theme = new Theme() indicatorAttributes = indicator.toObject() indicatorAttributes.theme = theme.toObject() indicatorWithThemeId = Indicator.convertNestedParametersToAssociationIds(indicatorAttributes) assert.strictEqual( indicatorWithThemeId.theme, theme.id, 'Expected indicator theme to be an ID only' ) ) test(".generateMetadataCSV returns CSV arrays containing the name, theme, period and data date", (done) -> theIndicator = theTheme = newestHeadlineStub = null Q.nsend( Theme, 'create', { title: 'Air Quality' } ).then( (theme) -> theTheme = theme Q.nsend( Indicator, 'create', { name: "PI:NAME:<NAME>END_PI" theme: theme indicatorDefinition: period: 'quarterly' xAxis: 'year' } ) ).then( (indicator) -> theIndicator = indicator newestHeadlineStub = sinon.stub(HeadlineService::, 'getNewestHeadline', -> Q.fcall(-> year: 2006 ) ) theIndicator.generateMetadataCSV() ).then((csvData) -> try assert.lengthOf csvData, 2, "Expected data to have 2 rows: header and data" titleRow = csvData[0] dataRow = csvData[1] assert.strictEqual titleRow[0], 'Indicator', "Expected the first column to be the indicator name" assert.strictEqual dataRow[0], theIndicator.name, "Expected the indicator name to be the name of the indicator" assert.strictEqual titleRow[1], 'Theme', "Expected the second column to be the theme" assert.strictEqual dataRow[1], theTheme.title, "Expected the theme to be the name of the indicator's theme" assert.strictEqual titleRow[2], 'Collection Frequency', "Expected the 3rd column to be the collection frequency" assert.strictEqual dataRow[2], theIndicator.indicatorDefinition.period, "Expected the Collection Frequency to be the indicator's period" assert.strictEqual titleRow[3], 'Date Updated', "Expected the 4th column to be the date updated" assert.strictEqual dataRow[3], 2006, "Expected the date updated to be 2006" done() catch e done(e) finally newestHeadlineStub.restore() ).catch( (err) -> done(err) newestHeadlineStub.restore() ) ) test(".generateMetadataCSV on an indicator with no theme or indicator defintion returns blank values for those fields", (done) -> indicator = new Indicator() indicator.generateMetadataCSV().then( (csvData)-> try assert.lengthOf csvData, 2, "Expected data to have 2 rows: header and data" titleRow = csvData[0] dataRow = csvData[1] assert.strictEqual titleRow[1], 'Theme', "Expected the second column to be the theme" assert.isUndefined dataRow[1], "Expected the theme to be blank" assert.strictEqual titleRow[2], 'Collection Frequency', "Expected the 3rd column to be the collection frequency" assert.isUndefined dataRow[2], "Expected the Collection Frequency to be blank" assert.strictEqual titleRow[3], 'Date Updated', "Expected the 4th column to be the date updated" assert.strictEqual dataRow[3], '', "Expected the date updated to be blank" done() catch e done(e) ).catch( (err) -> done(err) ) ) test("#seedData when no seed file exist reports an appropriate error", (done) -> fs = require('fs') existsSyncStub = sinon.stub(fs, 'existsSync', -> false) Indicator.seedData('./config/seeds/indicators.json').then( -> done("Expected Indicator.seedData to fail") ).catch( (err)-> assert.strictEqual( err.message, "Unable to load indicator seed file, have you copied seeds from config/instances/ to config/seeds/?" ) done() ).finally( -> existsSyncStub.restore() ) ) test('#CONDITIONS.IS_PRIMARY only returns indicators with indicators with primary: true', (done) -> helpers.createIndicatorModels([{ primary: true }, { primary: false }]).then(-> Indicator.find(Indicator.CONDITIONS.IS_PRIMARY).exec() ).then((indicators)-> try assert.lengthOf indicators, 1, "Only expected the primary indicator to be returned" done() catch err done(err) ).catch(done) ) test('creating a new Indicator without an "indicatorationConfig" attribute initialises it with a empty object', -> indicator = new Indicator() assert.deepEqual indicator.indicatorationConfig, {}, "Expected indicator.indicatoration to be defaulted to {}" )
[ { "context": "###\n available-time-slots\n \n Copyright (c) 2022 Yoshiaki Murakami(https://github.com/ysakmrkm)\n \n This software i", "end": 70, "score": 0.9998617172241211, "start": 53, "tag": "NAME", "value": "Yoshiaki Murakami" }, { "context": "ght (c) 2022 Yoshiaki Murakami...
src/cs/locales.coffee
ysakmrkm/available-time-slots
1
### available-time-slots Copyright (c) 2022 Yoshiaki Murakami(https://github.com/ysakmrkm) This software is released under the MIT License. http://opensource.org/licenses/mit-license.php ### 'use strict' en = { code: 'en' months: ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] weekdays: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] } ja = { code: 'ja' months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] weekdays: ['日', '月', '火', '水', '木', '金', '土'] } locales = [en, ja]
150365
### available-time-slots Copyright (c) 2022 <NAME>(https://github.com/ysakmrkm) This software is released under the MIT License. http://opensource.org/licenses/mit-license.php ### 'use strict' en = { code: 'en' months: ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] weekdays: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] } ja = { code: 'ja' months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] weekdays: ['日', '月', '火', '水', '木', '金', '土'] } locales = [en, ja]
true
### available-time-slots Copyright (c) 2022 PI:NAME:<NAME>END_PI(https://github.com/ysakmrkm) This software is released under the MIT License. http://opensource.org/licenses/mit-license.php ### 'use strict' en = { code: 'en' months: ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] weekdays: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] } ja = { code: 'ja' months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] weekdays: ['日', '月', '火', '水', '木', '金', '土'] } locales = [en, ja]
[ { "context": "fileTypes: [\n \"ceylon\"\n]\nname: \"Ceylon\"\npatterns: [\n {\n include: \"#module\"\n }\n ", "end": 36, "score": 0.5828410387039185, "start": 33, "tag": "NAME", "value": "Cey" }, { "context": "fileTypes: [\n \"ceylon\"\n]\nname: \"Ceylon\"\npatterns: [\n {\n...
grammars/ceylon.cson
clementi/language-ceylon
0
fileTypes: [ "ceylon" ] name: "Ceylon" patterns: [ { include: "#module" } { include: "#package" } { include: "#imports" } { include: "#code" } ] repository: annotations: patterns: [ { include: "#ceylondoc" } { captures: "1": name: "support.function.annotation.ceylon" patterns: [ { match: "abstract" name: "storage.modifier.abstract.ceylon" } { match: "actual" name: "storage.modifier.actual.ceylon" } { match: "default" name: "storage.modifier.default.ceylon" } { match: "formal" name: "storage.modifier.formal.ceylon" } { match: "final" name: "storage.modifier.final.ceylon" } { match: "late" name: "storage.modifier.formal.ceylon" } { match: "sealed" name: "storage.modifier.sealed.ceylon" } { match: "shared" name: "storage.modifier.shared.ceylon" } ] match: "\\b(abstract|actual|annotation|default|formal|final|late|optional|sealed|shared|variable)\\s+" name: "meta.declaration.annotation.language.ceylon" } { begin: "\\b(deprecated|by|native|license|tagged)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" contentName: "storage.type.annotation.ceylon" end: "(\\))" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#strings" } ] } { begin: "\\b(doc)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" end: "(\\))" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#ceylondoc" } ] } { begin: "\\b(see|throws)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" end: "\\)" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#strings" } ] } {} ] repository: ceylondoc: patterns: [ { begin: "^\\s*(\"(?:\"\")?)" beginCaptures: "1": name: "punctuation.definition.comment.begin.ceylondoc" end: "(\\1)\\s*$" endCaptures: "1": name: "punctuation.definition.comment.end.ceylondoc" name: "comment.block.documentation.ceylon" } ] "class-body": {} code: patterns: [ { include: "#comments" } { include: "#annotations" } { include: "#interfaces" } ] comments: patterns: [ { captures: "0": name: "punctuation.definition.comment.ceylon" match: "/\\*\\*/" name: "comment.block.empty.ceylon" } { include: "#comments-inline" } ] "comments-inline": patterns: [ { begin: "^\\s*(//)" beginCaptures: "1": name: "punctuation.definition.comment.ceylon" name: "comment.line.double-slash.ceylon" while: "^\\s*(//)" whileCaptures: "1": name: "punctuation.definition.comment.ceylon" } ] "constants-and-special-vars": patterns: [ { match: "\\b(true|false|null|nothing)\\b" name: "constant.language.ceylon" } { match: "\\b(this|super|outer)\\b" name: "variable.language.ceylon" } { match: "(?<!\\w)\\$([01]+|[01]{1,4}(_[01]{4})+)(?!\\w|\\.)" name: "constant.numeric.bin.ceylon" } { match: "(?<!\\w)\\#(\\h+|\\h{1,4}(_\\h{4})+|\\h{1,2}(_\\h{2})+)(?!\\w|\\.)" name: "constant.numeric.hex.ceylon" } { match: "\\b([0-9]{1,3}(_[0-9]{3})+|[0-9]+)[kMGTP]?(?!\\w|\\.)" name: "constant.numeric.integer.ceylon" } { match: ''' (?x) (?> ( ([0-9]{1,3}(_[0-9]{3})+|[0-9]+) # Leading digits (?=[eEkMGTPmunpf.]) # Allow for numbers without . )? ( (?<=[0-9])(?=[eEkMGTPmunpf]) # Allow for numbers without . | \\. ) ( (([0-9]{3}_)+[0-9]{1,3}|[0-9]+) # Numbers after . )? ( [eE][+-]?[0-9]+ # Exponent | [kMGTP] # Magnitude | [munpf] # Fractional magnitude )? ) (?!\\w) # Ensure word boundry ''' name: "constant.numeric.float.ceylon" } { match: "'[^\\\\']'" name: "constant.character.literal.ceylon" } { captures: "1": name: "constant.character.escape.ceylon" match: "'(\\\\[btnfre\\\\\"'`0])'" name: "constant.character.literal.ceylon" } { captures: "1": name: "punctuation.definition.character.begin.ceylon" "2": name: "constant.character.escape.ceylon" "3": name: "punctuation.definition.character.end.ceylon" match: "(')(\\\\[btnfre\\\\\"'`0])(')" name: "constant.character.literal.ceylon" } { begin: "'(?=\\\\\\{)" end: "'" name: "constant.character.literal.ceylon" patterns: [ { match: "\\\\\\{#\\h{2,6}\\}" name: "constant.character.escape.unicode.code.ceylon" } { match: "\\\\\\{(?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?)(?: (?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?))*\\}" name: "constant.character.escape.unicode.name.ceylon" } { match: "\\\\\\{.*}?(?=')" name: "invalid.illegal.character.escape.ceylon" } ] } { captures: "1": name: "invalid.illagal.character.literal" match: "'(.{2,})'" name: "constant.character.literal.ceylon" } ] expression: patterns: [ { include: "#strings" } { include: "#constants-and-special-vars" } ] imports: patterns: [ { begin: "^\\b(import)\\s+([^\\s{;.]+(?:\\.[^\\s{;.]+)+)+\\s*(\\{)" beginCaptures: "1": name: "keyword.control.import.ceylon" "2": name: "variable.other.package.ceylon" "3": name: "meta.bracket.ceylon" contentName: "meta.import.selector.ceylon" end: "(\\})" endCaptures: "1": name: "meta.bracket.ceylon" name: "meta.import.ceylon" patterns: [ { include: "#nested-import-element" } { include: "#import-element" } { include: "#import-wildcard" } ] } ] repository: "import-element": patterns: [ { captures: "1": name: "meta.import.alias.ceylon" "2": name: "variable.other.import.alias.ceylon" "3": name: "keyword.operator.assignment.ceylon" "4": name: "constant.character.escape.case-modifier.ceylon" "5": name: "variable.other.import.ceylon" match: "\\s*(([[:word:]]+)\\s*(=+)\\s*)?(\\\\[iI])?([[:word:]]+)\\s*" name: "meta.import.element.ceylon" } ] "import-wildcard": patterns: [ { contentName: "keyword.operator.import.wildcard.ceylon" match: "\\.{3}" name: "meta.import.element" } ] "nested-import-element": patterns: [ { begin: "\\s*(([[:word:]]+)\\s*(=+)\\s*)?(\\\\[iI])?([[:word:]]+)\\s*(\\{)" beginCaptures: "1": name: "meta.import.alias.ceylon" "2": name: "variable.other.import.alias.ceylon" "3": name: "keyword.operator.assignment.ceylon" "4": name: "constant.character.escape.case-modifier.ceylon" "5": name: "variable.other.import.ceylon" "6": name: "meta.bracket.ceylon" end: "(\\})" patterns: [ { include: "#nested-import-element" } { include: "#import-element" } { include: "#import-wildcard" } ] } ] interfaces: patterns: [ { begin: "(?=\\w?[\\w\\s]*(?:interface|dynamic)\\s+(?:(?:\\\\[iI])?\\w+))" end: "}" endCaptures: "0": name: "punctuation.section.class.end.ceylon" name: "meta.interface.ceylon" patterns: [ { include: "#annotations" } { include: "#comments" } { begin: "\\b(interface|dynamic)\\s+((?:\\\\[iI])?\\w+)" captures: "1": name: "keyword.other.interface.ceylon" "2": name: "entity.name.type.interface.ceylon" patterns: [ { match: "\\b([:lower:]|\\\\i)(?=\\w*)" name: "invalid.illegal.lowercase_character_not_allowed_here.ceylon" } ] end: "(?=\\{|of|extends|satisfies|given)" name: "meta.definition.interface.identifier.ceylon" } { begin: "\\b(of)\\s+" beginCaptures: "1": name: "keyword.other.of.ceylon" end: "(?=\\{|extends|satisfies|given)" name: "meta.definition.case.enumeration.ceylon" patterns: [ { captures: "1": name: "constant.character.escape.initial-uppercase.ceylon" "2": name: "entity.other.case-class.ceylon" match: "(\\\\I)([\\w_]+)\\s*" name: "meta.other.case-class.ceylon" } { captures: "1": name: "entity.other.case-class.ceylon" match: "\\b([[:upper:]][\\w_]*)\\s*" name: "meta.other.case-class.ceylon" } { captures: "1": name: "constant.character.escape.initial-lowercase.ceylon" "2": name: "entity.other.case-value.ceylon" match: "(\\\\i)([\\w_]+)\\s*" name: "meta.other.case-value.ceylon" } { captures: "1": name: "entity.other.case-value.ceylon" match: "\\b([[:lower:]][\\w_]*)\\s*" name: "meta.other.case-value.ceylon" } { match: "\\|{1}(?=\\s*[\\\\\\w_])" name: "keyword.operator.type.union.ceylon" } { match: "[^\\s]" name: "invalid.illegal.character_not_allowed.ceylon" } ] } { begin: "\\b(satisfies)\\s+" beginCaptures: "1": name: "keyword.other.satisfies.ceylon" end: "(?:\\{|given)" name: "meta.definition.interface.satisfies.ceylon" patterns: [ { match: "\\|{1}" name: "keyword.operator.type.union.ceylon" } { match: "&{1}" name: "keyword.operator.type.intersection.ceylon" } { include: "#type-specifier" } ] } { begin: "{" beginCaptures: "0": name: "punctuation.section.class.begin.ceylon" end: "(?=})" name: "meta.interface.body.ceylon" patterns: [ { include: "#class-body" } ] } ] } ] repository: "keyword-given": patterns: [] "keyword-of": patterns: [] "keyword-satisfies": patterns: [] module: patterns: [ { include: "#annotations" } { begin: "\\b(module)\\s*" beginCaptures: "1": name: "keyword.other.module.ceylon" end: "(?<=[\\n;])" name: "meta.module.ceylon" patterns: [ { include: "#comments" } { captures: "1": name: "variable.other.module.ceylon" "2": name: "string.other.module.version.ceylon" match: "([^\\s;\"{]+)\\s*(\"[^\"]+\")\\s*" } { begin: "{" end: "}" name: "meta.module.body.ceylon" patterns: [ { include: "#annotations" } { captures: "1": name: "keyword.other.import.ceylon" "2": name: "variable.other.import.module.ceylon" "3": name: "string.other.maven.module.ceylon" "4": name: "string.other.module.import.version.ceylon" "5": name: "punctuation.terminator.ceylon" contentName: "storage.modifier.import.ceylon" match: "\\b(import)\\b\\s*((?:[^\\s;\"]+)|(\"[^\"]+\"))\\s*(\"[^\"]+\")\\s*(;)" name: "meta.module.import.ceylon" } ] } ] } ] package: patterns: [ { captures: "1": name: "keyword.other.package.ceylon" "2": name: "variable.other.package.ceylon" "3": name: "punctuation.terminator.ceylon" match: "\\b(package)\\b(?:\\s*([^ ;$]+)\\s*(;))" name: "meta.package.ceylon" } ] strings: patterns: [ { begin: "\"\"\"" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "\"\"\"" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.triple" } { begin: "\"" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "\"" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.double.ceylon" patterns: [ { include: "#character-escapes" } { include: "#string-interpolation" } ] } { begin: "`" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "`" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.other.metamodel.reference.ceylon" } ] repository: "character-escapes": patterns: [ { match: "\\\\[btnfre\\\\\"'`0]" name: "constant.character.escape.ceylon" } { begin: "\\\\(?=\\{)" end: "(?<=\\})" name: "constant.character.escape.ceylon" patterns: [ { match: "\\{#\\h{2,6}\\}" name: "constant.character.escape.unicode.code.ceylon" } { match: "\\{(?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?)(?: (?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?))*\\}" name: "constant.character.escape.unicode.name.ceylon" } { match: "\\{[^\\}]*\\}" name: "invalid.illegal.unknown-escape.ceylon" } ] } { match: "\\\\." name: "invalid.illegal.unknown-escape.ceylon" } ] "string-interpolation": patterns: [ { begin: "``" beginCaptures: "0": name: "punctuation.definition.string-interpolation.begin.ceylon" end: "``" endCaptures: "0": name: "punctuation.definition.string-interpolation.end.ceylon" name: "string.interpolated.ceylon" patterns: [ { include: "#expression" } ] } ] "type-name": {} scopeName: "source.ceylon"
152825
fileTypes: [ "ceylon" ] name: "<NAME>lon" patterns: [ { include: "#module" } { include: "#package" } { include: "#imports" } { include: "#code" } ] repository: annotations: patterns: [ { include: "#ceylondoc" } { captures: "1": name: "support.function.annotation.ceylon" patterns: [ { match: "abstract" name: "storage.modifier.abstract.ceylon" } { match: "actual" name: "storage.modifier.actual.ceylon" } { match: "default" name: "storage.modifier.default.ceylon" } { match: "formal" name: "storage.modifier.formal.ceylon" } { match: "final" name: "storage.modifier.final.ceylon" } { match: "late" name: "storage.modifier.formal.ceylon" } { match: "sealed" name: "storage.modifier.sealed.ceylon" } { match: "shared" name: "storage.modifier.shared.ceylon" } ] match: "\\b(abstract|actual|annotation|default|formal|final|late|optional|sealed|shared|variable)\\s+" name: "meta.declaration.annotation.language.ceylon" } { begin: "\\b(deprecated|by|native|license|tagged)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" contentName: "storage.type.annotation.ceylon" end: "(\\))" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#strings" } ] } { begin: "\\b(doc)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" end: "(\\))" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#ceylondoc" } ] } { begin: "\\b(see|throws)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" end: "\\)" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#strings" } ] } {} ] repository: ceylondoc: patterns: [ { begin: "^\\s*(\"(?:\"\")?)" beginCaptures: "1": name: "punctuation.definition.comment.begin.ceylondoc" end: "(\\1)\\s*$" endCaptures: "1": name: "punctuation.definition.comment.end.ceylondoc" name: "comment.block.documentation.ceylon" } ] "class-body": {} code: patterns: [ { include: "#comments" } { include: "#annotations" } { include: "#interfaces" } ] comments: patterns: [ { captures: "0": name: "punctuation.definition.comment.ceylon" match: "/\\*\\*/" name: "comment.block.empty.ceylon" } { include: "#comments-inline" } ] "comments-inline": patterns: [ { begin: "^\\s*(//)" beginCaptures: "1": name: "punctuation.definition.comment.ceylon" name: "comment.line.double-slash.ceylon" while: "^\\s*(//)" whileCaptures: "1": name: "punctuation.definition.comment.ceylon" } ] "constants-and-special-vars": patterns: [ { match: "\\b(true|false|null|nothing)\\b" name: "constant.language.ceylon" } { match: "\\b(this|super|outer)\\b" name: "variable.language.ceylon" } { match: "(?<!\\w)\\$([01]+|[01]{1,4}(_[01]{4})+)(?!\\w|\\.)" name: "constant.numeric.bin.ceylon" } { match: "(?<!\\w)\\#(\\h+|\\h{1,4}(_\\h{4})+|\\h{1,2}(_\\h{2})+)(?!\\w|\\.)" name: "constant.numeric.hex.ceylon" } { match: "\\b([0-9]{1,3}(_[0-9]{3})+|[0-9]+)[kMGTP]?(?!\\w|\\.)" name: "constant.numeric.integer.ceylon" } { match: ''' (?x) (?> ( ([0-9]{1,3}(_[0-9]{3})+|[0-9]+) # Leading digits (?=[eEkMGTPmunpf.]) # Allow for numbers without . )? ( (?<=[0-9])(?=[eEkMGTPmunpf]) # Allow for numbers without . | \\. ) ( (([0-9]{3}_)+[0-9]{1,3}|[0-9]+) # Numbers after . )? ( [eE][+-]?[0-9]+ # Exponent | [kMGTP] # Magnitude | [munpf] # Fractional magnitude )? ) (?!\\w) # Ensure word boundry ''' name: "constant.numeric.float.ceylon" } { match: "'[^\\\\']'" name: "constant.character.literal.ceylon" } { captures: "1": name: "constant.character.escape.ceylon" match: "'(\\\\[btnfre\\\\\"'`0])'" name: "constant.character.literal.ceylon" } { captures: "1": name: "punctuation.definition.character.begin.ceylon" "2": name: "constant.character.escape.ceylon" "3": name: "punctuation.definition.character.end.ceylon" match: "(')(\\\\[btnfre\\\\\"'`0])(')" name: "constant.character.literal.ceylon" } { begin: "'(?=\\\\\\{)" end: "'" name: "constant.character.literal.ceylon" patterns: [ { match: "\\\\\\{#\\h{2,6}\\}" name: "constant.character.escape.unicode.code.ceylon" } { match: "\\\\\\{(?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?)(?: (?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?))*\\}" name: "constant.character.escape.unicode.name.ceylon" } { match: "\\\\\\{.*}?(?=')" name: "invalid.illegal.character.escape.ceylon" } ] } { captures: "1": name: "invalid.illagal.character.literal" match: "'(.{2,})'" name: "constant.character.literal.ceylon" } ] expression: patterns: [ { include: "#strings" } { include: "#constants-and-special-vars" } ] imports: patterns: [ { begin: "^\\b(import)\\s+([^\\s{;.]+(?:\\.[^\\s{;.]+)+)+\\s*(\\{)" beginCaptures: "1": name: "keyword.control.import.ceylon" "2": name: "variable.other.package.ceylon" "3": name: "meta.bracket.ceylon" contentName: "meta.import.selector.ceylon" end: "(\\})" endCaptures: "1": name: "meta.bracket.ceylon" name: "meta.import.ceylon" patterns: [ { include: "#nested-import-element" } { include: "#import-element" } { include: "#import-wildcard" } ] } ] repository: "import-element": patterns: [ { captures: "1": name: "meta.import.alias.ceylon" "2": name: "variable.other.import.alias.ceylon" "3": name: "keyword.operator.assignment.ceylon" "4": name: "constant.character.escape.case-modifier.ceylon" "5": name: "variable.other.import.ceylon" match: "\\s*(([[:word:]]+)\\s*(=+)\\s*)?(\\\\[iI])?([[:word:]]+)\\s*" name: "meta.import.element.ceylon" } ] "import-wildcard": patterns: [ { contentName: "keyword.operator.import.wildcard.ceylon" match: "\\.{3}" name: "meta.import.element" } ] "nested-import-element": patterns: [ { begin: "\\s*(([[:word:]]+)\\s*(=+)\\s*)?(\\\\[iI])?([[:word:]]+)\\s*(\\{)" beginCaptures: "1": name: "meta.import.alias.ceylon" "2": name: "variable.other.import.alias.ceylon" "3": name: "keyword.operator.assignment.ceylon" "4": name: "constant.character.escape.case-modifier.ceylon" "5": name: "variable.other.import.ceylon" "6": name: "meta.bracket.ceylon" end: "(\\})" patterns: [ { include: "#nested-import-element" } { include: "#import-element" } { include: "#import-wildcard" } ] } ] interfaces: patterns: [ { begin: "(?=\\w?[\\w\\s]*(?:interface|dynamic)\\s+(?:(?:\\\\[iI])?\\w+))" end: "}" endCaptures: "0": name: "punctuation.section.class.end.ceylon" name: "meta.interface.ceylon" patterns: [ { include: "#annotations" } { include: "#comments" } { begin: "\\b(interface|dynamic)\\s+((?:\\\\[iI])?\\w+)" captures: "1": name: "keyword.other.interface.ceylon" "2": name: "entity.name.type.interface.ceylon" patterns: [ { match: "\\b([:lower:]|\\\\i)(?=\\w*)" name: "invalid.illegal.lowercase_character_not_allowed_here.ceylon" } ] end: "(?=\\{|of|extends|satisfies|given)" name: "meta.definition.interface.identifier.ceylon" } { begin: "\\b(of)\\s+" beginCaptures: "1": name: "keyword.other.of.ceylon" end: "(?=\\{|extends|satisfies|given)" name: "meta.definition.case.enumeration.ceylon" patterns: [ { captures: "1": name: "constant.character.escape.initial-uppercase.ceylon" "2": name: "entity.other.case-class.ceylon" match: "(\\\\I)([\\w_]+)\\s*" name: "meta.other.case-class.ceylon" } { captures: "1": name: "entity.other.case-class.ceylon" match: "\\b([[:upper:]][\\w_]*)\\s*" name: "meta.other.case-class.ceylon" } { captures: "1": name: "constant.character.escape.initial-lowercase.ceylon" "2": name: "entity.other.case-value.ceylon" match: "(\\\\i)([\\w_]+)\\s*" name: "meta.other.case-value.ceylon" } { captures: "1": name: "entity.other.case-value.ceylon" match: "\\b([[:lower:]][\\w_]*)\\s*" name: "meta.other.case-value.ceylon" } { match: "\\|{1}(?=\\s*[\\\\\\w_])" name: "keyword.operator.type.union.ceylon" } { match: "[^\\s]" name: "invalid.illegal.character_not_allowed.ceylon" } ] } { begin: "\\b(satisfies)\\s+" beginCaptures: "1": name: "keyword.other.satisfies.ceylon" end: "(?:\\{|given)" name: "meta.definition.interface.satisfies.ceylon" patterns: [ { match: "\\|{1}" name: "keyword.operator.type.union.ceylon" } { match: "&{1}" name: "keyword.operator.type.intersection.ceylon" } { include: "#type-specifier" } ] } { begin: "{" beginCaptures: "0": name: "punctuation.section.class.begin.ceylon" end: "(?=})" name: "meta.interface.body.ceylon" patterns: [ { include: "#class-body" } ] } ] } ] repository: "keyword-given": patterns: [] "keyword-of": patterns: [] "keyword-satisfies": patterns: [] module: patterns: [ { include: "#annotations" } { begin: "\\b(module)\\s*" beginCaptures: "1": name: "keyword.other.module.ceylon" end: "(?<=[\\n;])" name: "meta.module.ceylon" patterns: [ { include: "#comments" } { captures: "1": name: "variable.other.module.ceylon" "2": name: "string.other.module.version.ceylon" match: "([^\\s;\"{]+)\\s*(\"[^\"]+\")\\s*" } { begin: "{" end: "}" name: "meta.module.body.ceylon" patterns: [ { include: "#annotations" } { captures: "1": name: "keyword.other.import.ceylon" "2": name: "variable.other.import.module.ceylon" "3": name: "string.other.maven.module.ceylon" "4": name: "string.other.module.import.version.ceylon" "5": name: "punctuation.terminator.ceylon" contentName: "storage.modifier.import.ceylon" match: "\\b(import)\\b\\s*((?:[^\\s;\"]+)|(\"[^\"]+\"))\\s*(\"[^\"]+\")\\s*(;)" name: "meta.module.import.ceylon" } ] } ] } ] package: patterns: [ { captures: "1": name: "keyword.other.package.ceylon" "2": name: "variable.other.package.ceylon" "3": name: "punctuation.terminator.ceylon" match: "\\b(package)\\b(?:\\s*([^ ;$]+)\\s*(;))" name: "meta.package.ceylon" } ] strings: patterns: [ { begin: "\"\"\"" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "\"\"\"" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.triple" } { begin: "\"" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "\"" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.double.ceylon" patterns: [ { include: "#character-escapes" } { include: "#string-interpolation" } ] } { begin: "`" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "`" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.other.metamodel.reference.ceylon" } ] repository: "character-escapes": patterns: [ { match: "\\\\[btnfre\\\\\"'`0]" name: "constant.character.escape.ceylon" } { begin: "\\\\(?=\\{)" end: "(?<=\\})" name: "constant.character.escape.ceylon" patterns: [ { match: "\\{#\\h{2,6}\\}" name: "constant.character.escape.unicode.code.ceylon" } { match: "\\{(?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?)(?: (?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?))*\\}" name: "constant.character.escape.unicode.name.ceylon" } { match: "\\{[^\\}]*\\}" name: "invalid.illegal.unknown-escape.ceylon" } ] } { match: "\\\\." name: "invalid.illegal.unknown-escape.ceylon" } ] "string-interpolation": patterns: [ { begin: "``" beginCaptures: "0": name: "punctuation.definition.string-interpolation.begin.ceylon" end: "``" endCaptures: "0": name: "punctuation.definition.string-interpolation.end.ceylon" name: "string.interpolated.ceylon" patterns: [ { include: "#expression" } ] } ] "type-name": {} scopeName: "source.ceylon"
true
fileTypes: [ "ceylon" ] name: "PI:NAME:<NAME>END_PIlon" patterns: [ { include: "#module" } { include: "#package" } { include: "#imports" } { include: "#code" } ] repository: annotations: patterns: [ { include: "#ceylondoc" } { captures: "1": name: "support.function.annotation.ceylon" patterns: [ { match: "abstract" name: "storage.modifier.abstract.ceylon" } { match: "actual" name: "storage.modifier.actual.ceylon" } { match: "default" name: "storage.modifier.default.ceylon" } { match: "formal" name: "storage.modifier.formal.ceylon" } { match: "final" name: "storage.modifier.final.ceylon" } { match: "late" name: "storage.modifier.formal.ceylon" } { match: "sealed" name: "storage.modifier.sealed.ceylon" } { match: "shared" name: "storage.modifier.shared.ceylon" } ] match: "\\b(abstract|actual|annotation|default|formal|final|late|optional|sealed|shared|variable)\\s+" name: "meta.declaration.annotation.language.ceylon" } { begin: "\\b(deprecated|by|native|license|tagged)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" contentName: "storage.type.annotation.ceylon" end: "(\\))" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#strings" } ] } { begin: "\\b(doc)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" end: "(\\))" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#ceylondoc" } ] } { begin: "\\b(see|throws)\\s*(\\()" beginCaptures: "1": name: "support.function.annotation.ceylon" "2": name: "punctuation.definition.annotation-arguments.begin.ceylon" end: "\\)" endCaptures: "1": name: "punctuation.definition.annotation-arguments.end.ceylon" name: "meta.declaration.annotation.language.ceylon" patterns: [ { include: "#strings" } ] } {} ] repository: ceylondoc: patterns: [ { begin: "^\\s*(\"(?:\"\")?)" beginCaptures: "1": name: "punctuation.definition.comment.begin.ceylondoc" end: "(\\1)\\s*$" endCaptures: "1": name: "punctuation.definition.comment.end.ceylondoc" name: "comment.block.documentation.ceylon" } ] "class-body": {} code: patterns: [ { include: "#comments" } { include: "#annotations" } { include: "#interfaces" } ] comments: patterns: [ { captures: "0": name: "punctuation.definition.comment.ceylon" match: "/\\*\\*/" name: "comment.block.empty.ceylon" } { include: "#comments-inline" } ] "comments-inline": patterns: [ { begin: "^\\s*(//)" beginCaptures: "1": name: "punctuation.definition.comment.ceylon" name: "comment.line.double-slash.ceylon" while: "^\\s*(//)" whileCaptures: "1": name: "punctuation.definition.comment.ceylon" } ] "constants-and-special-vars": patterns: [ { match: "\\b(true|false|null|nothing)\\b" name: "constant.language.ceylon" } { match: "\\b(this|super|outer)\\b" name: "variable.language.ceylon" } { match: "(?<!\\w)\\$([01]+|[01]{1,4}(_[01]{4})+)(?!\\w|\\.)" name: "constant.numeric.bin.ceylon" } { match: "(?<!\\w)\\#(\\h+|\\h{1,4}(_\\h{4})+|\\h{1,2}(_\\h{2})+)(?!\\w|\\.)" name: "constant.numeric.hex.ceylon" } { match: "\\b([0-9]{1,3}(_[0-9]{3})+|[0-9]+)[kMGTP]?(?!\\w|\\.)" name: "constant.numeric.integer.ceylon" } { match: ''' (?x) (?> ( ([0-9]{1,3}(_[0-9]{3})+|[0-9]+) # Leading digits (?=[eEkMGTPmunpf.]) # Allow for numbers without . )? ( (?<=[0-9])(?=[eEkMGTPmunpf]) # Allow for numbers without . | \\. ) ( (([0-9]{3}_)+[0-9]{1,3}|[0-9]+) # Numbers after . )? ( [eE][+-]?[0-9]+ # Exponent | [kMGTP] # Magnitude | [munpf] # Fractional magnitude )? ) (?!\\w) # Ensure word boundry ''' name: "constant.numeric.float.ceylon" } { match: "'[^\\\\']'" name: "constant.character.literal.ceylon" } { captures: "1": name: "constant.character.escape.ceylon" match: "'(\\\\[btnfre\\\\\"'`0])'" name: "constant.character.literal.ceylon" } { captures: "1": name: "punctuation.definition.character.begin.ceylon" "2": name: "constant.character.escape.ceylon" "3": name: "punctuation.definition.character.end.ceylon" match: "(')(\\\\[btnfre\\\\\"'`0])(')" name: "constant.character.literal.ceylon" } { begin: "'(?=\\\\\\{)" end: "'" name: "constant.character.literal.ceylon" patterns: [ { match: "\\\\\\{#\\h{2,6}\\}" name: "constant.character.escape.unicode.code.ceylon" } { match: "\\\\\\{(?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?)(?: (?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?))*\\}" name: "constant.character.escape.unicode.name.ceylon" } { match: "\\\\\\{.*}?(?=')" name: "invalid.illegal.character.escape.ceylon" } ] } { captures: "1": name: "invalid.illagal.character.literal" match: "'(.{2,})'" name: "constant.character.literal.ceylon" } ] expression: patterns: [ { include: "#strings" } { include: "#constants-and-special-vars" } ] imports: patterns: [ { begin: "^\\b(import)\\s+([^\\s{;.]+(?:\\.[^\\s{;.]+)+)+\\s*(\\{)" beginCaptures: "1": name: "keyword.control.import.ceylon" "2": name: "variable.other.package.ceylon" "3": name: "meta.bracket.ceylon" contentName: "meta.import.selector.ceylon" end: "(\\})" endCaptures: "1": name: "meta.bracket.ceylon" name: "meta.import.ceylon" patterns: [ { include: "#nested-import-element" } { include: "#import-element" } { include: "#import-wildcard" } ] } ] repository: "import-element": patterns: [ { captures: "1": name: "meta.import.alias.ceylon" "2": name: "variable.other.import.alias.ceylon" "3": name: "keyword.operator.assignment.ceylon" "4": name: "constant.character.escape.case-modifier.ceylon" "5": name: "variable.other.import.ceylon" match: "\\s*(([[:word:]]+)\\s*(=+)\\s*)?(\\\\[iI])?([[:word:]]+)\\s*" name: "meta.import.element.ceylon" } ] "import-wildcard": patterns: [ { contentName: "keyword.operator.import.wildcard.ceylon" match: "\\.{3}" name: "meta.import.element" } ] "nested-import-element": patterns: [ { begin: "\\s*(([[:word:]]+)\\s*(=+)\\s*)?(\\\\[iI])?([[:word:]]+)\\s*(\\{)" beginCaptures: "1": name: "meta.import.alias.ceylon" "2": name: "variable.other.import.alias.ceylon" "3": name: "keyword.operator.assignment.ceylon" "4": name: "constant.character.escape.case-modifier.ceylon" "5": name: "variable.other.import.ceylon" "6": name: "meta.bracket.ceylon" end: "(\\})" patterns: [ { include: "#nested-import-element" } { include: "#import-element" } { include: "#import-wildcard" } ] } ] interfaces: patterns: [ { begin: "(?=\\w?[\\w\\s]*(?:interface|dynamic)\\s+(?:(?:\\\\[iI])?\\w+))" end: "}" endCaptures: "0": name: "punctuation.section.class.end.ceylon" name: "meta.interface.ceylon" patterns: [ { include: "#annotations" } { include: "#comments" } { begin: "\\b(interface|dynamic)\\s+((?:\\\\[iI])?\\w+)" captures: "1": name: "keyword.other.interface.ceylon" "2": name: "entity.name.type.interface.ceylon" patterns: [ { match: "\\b([:lower:]|\\\\i)(?=\\w*)" name: "invalid.illegal.lowercase_character_not_allowed_here.ceylon" } ] end: "(?=\\{|of|extends|satisfies|given)" name: "meta.definition.interface.identifier.ceylon" } { begin: "\\b(of)\\s+" beginCaptures: "1": name: "keyword.other.of.ceylon" end: "(?=\\{|extends|satisfies|given)" name: "meta.definition.case.enumeration.ceylon" patterns: [ { captures: "1": name: "constant.character.escape.initial-uppercase.ceylon" "2": name: "entity.other.case-class.ceylon" match: "(\\\\I)([\\w_]+)\\s*" name: "meta.other.case-class.ceylon" } { captures: "1": name: "entity.other.case-class.ceylon" match: "\\b([[:upper:]][\\w_]*)\\s*" name: "meta.other.case-class.ceylon" } { captures: "1": name: "constant.character.escape.initial-lowercase.ceylon" "2": name: "entity.other.case-value.ceylon" match: "(\\\\i)([\\w_]+)\\s*" name: "meta.other.case-value.ceylon" } { captures: "1": name: "entity.other.case-value.ceylon" match: "\\b([[:lower:]][\\w_]*)\\s*" name: "meta.other.case-value.ceylon" } { match: "\\|{1}(?=\\s*[\\\\\\w_])" name: "keyword.operator.type.union.ceylon" } { match: "[^\\s]" name: "invalid.illegal.character_not_allowed.ceylon" } ] } { begin: "\\b(satisfies)\\s+" beginCaptures: "1": name: "keyword.other.satisfies.ceylon" end: "(?:\\{|given)" name: "meta.definition.interface.satisfies.ceylon" patterns: [ { match: "\\|{1}" name: "keyword.operator.type.union.ceylon" } { match: "&{1}" name: "keyword.operator.type.intersection.ceylon" } { include: "#type-specifier" } ] } { begin: "{" beginCaptures: "0": name: "punctuation.section.class.begin.ceylon" end: "(?=})" name: "meta.interface.body.ceylon" patterns: [ { include: "#class-body" } ] } ] } ] repository: "keyword-given": patterns: [] "keyword-of": patterns: [] "keyword-satisfies": patterns: [] module: patterns: [ { include: "#annotations" } { begin: "\\b(module)\\s*" beginCaptures: "1": name: "keyword.other.module.ceylon" end: "(?<=[\\n;])" name: "meta.module.ceylon" patterns: [ { include: "#comments" } { captures: "1": name: "variable.other.module.ceylon" "2": name: "string.other.module.version.ceylon" match: "([^\\s;\"{]+)\\s*(\"[^\"]+\")\\s*" } { begin: "{" end: "}" name: "meta.module.body.ceylon" patterns: [ { include: "#annotations" } { captures: "1": name: "keyword.other.import.ceylon" "2": name: "variable.other.import.module.ceylon" "3": name: "string.other.maven.module.ceylon" "4": name: "string.other.module.import.version.ceylon" "5": name: "punctuation.terminator.ceylon" contentName: "storage.modifier.import.ceylon" match: "\\b(import)\\b\\s*((?:[^\\s;\"]+)|(\"[^\"]+\"))\\s*(\"[^\"]+\")\\s*(;)" name: "meta.module.import.ceylon" } ] } ] } ] package: patterns: [ { captures: "1": name: "keyword.other.package.ceylon" "2": name: "variable.other.package.ceylon" "3": name: "punctuation.terminator.ceylon" match: "\\b(package)\\b(?:\\s*([^ ;$]+)\\s*(;))" name: "meta.package.ceylon" } ] strings: patterns: [ { begin: "\"\"\"" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "\"\"\"" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.triple" } { begin: "\"" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "\"" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.double.ceylon" patterns: [ { include: "#character-escapes" } { include: "#string-interpolation" } ] } { begin: "`" beginCaptures: "0": name: "punctuation.definition.string.begin.ceylon" end: "`" endCaptures: "0": name: "punctuation.definition.string.end.ceylon" name: "string.quoted.other.metamodel.reference.ceylon" } ] repository: "character-escapes": patterns: [ { match: "\\\\[btnfre\\\\\"'`0]" name: "constant.character.escape.ceylon" } { begin: "\\\\(?=\\{)" end: "(?<=\\})" name: "constant.character.escape.ceylon" patterns: [ { match: "\\{#\\h{2,6}\\}" name: "constant.character.escape.unicode.code.ceylon" } { match: "\\{(?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?)(?: (?:[A-Z](?:[A-Z0-9\\-]*?[A-Z0-9])?))*\\}" name: "constant.character.escape.unicode.name.ceylon" } { match: "\\{[^\\}]*\\}" name: "invalid.illegal.unknown-escape.ceylon" } ] } { match: "\\\\." name: "invalid.illegal.unknown-escape.ceylon" } ] "string-interpolation": patterns: [ { begin: "``" beginCaptures: "0": name: "punctuation.definition.string-interpolation.begin.ceylon" end: "``" endCaptures: "0": name: "punctuation.definition.string-interpolation.end.ceylon" name: "string.interpolated.ceylon" patterns: [ { include: "#expression" } ] } ] "type-name": {} scopeName: "source.ceylon"
[ { "context": "##\n knockback.js 1.2.3\n Copyright (c) 2011-2016 Kevin Malakoff.\n License: MIT (http://www.opensource.org/licens", "end": 66, "score": 0.9998412728309631, "start": 52, "tag": "NAME", "value": "Kevin Malakoff" } ]
src/core/index.coffee
kmalakoff/knockback
160
### knockback.js 1.2.3 Copyright (c) 2011-2016 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. ### module.exports = kb = require './kb' kb.configure = require './configure' # re-expose modules kb.modules = {underscore: kb._, backbone: kb.Parse or kb.Backbone, knockout: kb.ko}
219658
### knockback.js 1.2.3 Copyright (c) 2011-2016 <NAME>. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. ### module.exports = kb = require './kb' kb.configure = require './configure' # re-expose modules kb.modules = {underscore: kb._, backbone: kb.Parse or kb.Backbone, knockout: kb.ko}
true
### knockback.js 1.2.3 Copyright (c) 2011-2016 PI:NAME:<NAME>END_PI. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. ### module.exports = kb = require './kb' kb.configure = require './configure' # re-expose modules kb.modules = {underscore: kb._, backbone: kb.Parse or kb.Backbone, knockout: kb.ko}
[ { "context": "nerateUserInfo()\n userInfo.passwordStatus = 'some invalid passwordStatus'\n JUser.createUser userInfo, (err) ->\n ", "end": 985, "score": 0.9991891384124756, "start": 958, "tag": "PASSWORD", "value": "some invalid passwordStatus" }, { "context": "dData u...
workers/social/lib/social/models/user/index.test.coffee
lionheart1022/koding
0
JLog = require '../log/index' JUser = require './index' JName = require '../name' JAccount = require '../account' JSession = require '../session' Speakeasy = require 'speakeasy' { async expect withDummyClient generateUserInfo withConvertedUser generateDummyClient generateCredentials generateRandomEmail generateRandomString generateRandomUsername checkBongoConnectivity generateDummyUserFormData } = require '../../../../testhelper' # this function will be called once before running any test beforeTests = -> before (done) -> checkBongoConnectivity done # this function will be called after all tests are executed afterTests = -> after -> # here we have actual tests runTests = -> describe 'workers.social.user.index', -> describe '#createUser', -> it 'should pass error passwordStatus type is not valid', (done) -> userInfo = generateUserInfo() userInfo.passwordStatus = 'some invalid passwordStatus' JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal 'Errors were encountered during validation.' done() it 'should error if username is not set', (done) -> userInfo = generateUserInfo() userInfo.username = '' JUser.createUser userInfo, (err) -> expect(err).to.exist done() it 'should pass error if username is in use', (done) -> userInfo = generateUserInfo() queue = [ (next) -> JUser.createUser userInfo, (err) -> expect(err).to.not.exist next() (next) -> # setting a different email, username will be duplicate userInfo.email = generateRandomEmail() expectedError = "The slug #{userInfo.username} is not available." JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal expectedError next() ] async.series queue, done it 'should pass error if email is in use', (done) -> userInfo = generateUserInfo() queue = [ (next) -> JUser.createUser userInfo, (err) -> expect(err).to.not.exist next() (next) -> # setting a different username, email will be duplicate userInfo.username = generateRandomString() expectedError = "Sorry, \"#{userInfo.email}\" is already in use!" JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal expectedError next() ] async.series queue, done describe 'when user data is valid', -> testCreateUserWithValidData = (userInfo, callback) -> queue = [ (next) -> # expecting user to be created JUser.createUser userInfo, (err) -> expect(err).to.not.exist # after the user is created, lower casing username because # we expect to see the username to be lower cased in jmodel documents userInfo.username = userInfo.username.toLowerCase() next() (next) -> # expecting user to be saved params = { username : userInfo.username } JUser.one params, (err, user) -> expect(err).to.not.exist expect(user.username).to.be.equal userInfo.username next() (next) -> # expecting account to be created and saved params = { 'profile.nickname' : userInfo.username } JAccount.one params, (err, account) -> expect(err).to.not.exist expect(account).to.exist next() (next) -> # expecting name to be created and saved params = { 'name' : userInfo.username } JName.one params, (err, name) -> expect(err).to.not.exist expect(name).to.exist next() ] async.series queue, callback it 'should be able to create user with lower case username', (done) -> userInfo = generateUserInfo() userInfo.username = userInfo.username.toLowerCase() testCreateUserWithValidData userInfo, done it 'should be able to create user with upper case username', (done) -> userInfo = generateUserInfo() userInfo.username = userInfo.username.toUpperCase() testCreateUserWithValidData userInfo, done it 'should save email frequencies correctly', (done) -> userInfo = generateUserInfo() userInfo.emailFrequency = global : off daily : off followActions : off privateMessage : off testCreateUserWithValidData userInfo, -> params = { username : userInfo.username } JUser.one params, (err, user) -> expect(err).to.not.exist expect(user.emailFrequency.global).to.be.false expect(user.emailFrequency.daily).to.be.false expect(user.emailFrequency.privateMessage).to.be.false expect(user.emailFrequency.followActions).to.be.false done() describe '#login()', -> describe 'when request is valid', -> testLoginWithValidData = (options, callback) -> lastLoginDate = null { loginCredentials, username } = options username ?= loginCredentials.username queue = [ (next) -> # expecting successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # keeping last login date JUser.one { username }, (err, user) -> expect(err).to.not.exist lastLoginDate = user.lastLoginDate next() (next) -> # expecting another successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # expecting last login date to be changed JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(lastLoginDate) .not.to.be.equal user.lastLoginDate next() ] async.series queue, callback it 'should be able to login user with lower case username', (done) -> # trying to login with username withConvertedUser ({ userFormData : { username, password } }) -> loginCredentials = generateCredentials { username, password } testLoginWithValidData { loginCredentials }, done it 'should be able to login with uppercase username', (done) -> # trying to login with username withConvertedUser ({ userFormData : { username, password } }) -> opts = { username : username.toUpperCase(), password } loginCredentials = generateCredentials opts testLoginWithValidData { loginCredentials, username }, done it 'should handle username normalizing correctly', (done) -> # trying to login with email instead of username withConvertedUser ({ userFormData : { username, password, email } }) -> loginCredentials = generateCredentials { username : email, password } testLoginWithValidData { loginCredentials, username }, done it 'should handle two factor authentication correctly', (done) -> withConvertedUser ({ userFormData : { username, password } }) -> tfcode = null loginCredentials = generateCredentials { username, password } queue = [ (next) -> # setting two factor authentication on by adding twofactorkey field JUser.update { username }, { $set: { twofactorkey: 'somekey' } }, (err) -> expect(err).to.not.exist next() (next) -> # trying to login with empty tf code loginCredentials.tfcode = '' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'TwoFactor auth Enabled' next() (next) -> # trying to login with invalid tfcode loginCredentials.tfcode = 'invalidtfcode' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'Access denied!' next() (next) -> # generating a 2fa key and saving it in mongo { base32 : tfcode } = Speakeasy.generate_key length : 20 encoding : 'base32' JUser.update { username }, { $set: { twofactorkey: tfcode } }, (err) -> expect(err).to.not.exist next() (next) -> # generating a verificationCode and expecting a successful login verificationCode = Speakeasy.totp key : tfcode encoding : 'base32' loginCredentials.tfcode = verificationCode JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() ] async.series queue, done it 'should pass error if account is not found', (done) -> { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() (next) -> # removing users account JAccount.remove { 'profile.nickname': username }, (err) -> expect(err).to.not.exist next() (next) -> # expecting not to able to login without an account JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'No account found!' next() ] async.series queue, done it 'should check if the user is blocked', (done) -> # generating user info with random username and password user = null { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user_) -> user = user_ expect(err).to.not.exist next() (next) -> # expecting successful login with the newly generated user JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # blocking user for 1 day untilDate = new Date(Date.now() + 1000 * 60 * 60 * 24) user.block untilDate, (err) -> expect(err).to.not.exist next() (next) -> # expecting login attempt to fail and return blocked message JUser.login null, loginCredentials, (err) -> toDate = user.blockedUntil.toUTCString() expect(err.message).to.be.equal JUser.getBlockedMessage toDate next() (next) -> # unblocking user user.unblock (err) -> expect(err).to.not.exist next() (next) -> # expecting user to be able to login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() ] async.series queue, done it 'should pass error if user\'s password needs reset', (done) -> # generating user info with random username and password { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } setUserPasswordStatus = (username, status, callback) -> JUser.update { username }, { $set: { passwordStatus: status } }, (err) -> expect(err).to.not.exist callback() queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() (next) -> setUserPasswordStatus username, 'valid', next (next) -> # expecting successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> setUserPasswordStatus username, 'needs reset', next (next) -> # expecting unsuccessful login attempt JUser.login null, loginCredentials, (err) -> expect(err).to.exist next() (next) -> setUserPasswordStatus username, 'valid', next ] async.series queue, done it 'should create a new session if clientId is not specified', (done) -> loginCredentials = generateCredentials() # when client id is not specified, a new session should be created JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist done() it 'should should pass error if username is not registered', (done) -> loginCredentials = generateCredentials username : 'herecomesanunregisteredusername' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'Unknown user name' done() # this case also tests if logging is working correctly it 'should check for brute force attack', (done) -> queue = [] { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials username : username password : 'someInvalidPassword' addRemoveUserLogsToQueue = (queue, username) -> queue.push (next) -> JLog.remove { username }, (err) -> expect(err).to.not.exist next() addLoginTrialToQueue = (queue, tryCount) -> queue.push (next) -> JUser.login null, loginCredentials, (err) -> expectedError = switch when tryCount < JLog.tryLimit() 'Access denied!' else "Your login access is blocked for #{JLog.timeLimit()} minutes." expect(err.message).to.be.equal expectedError next() queue.push (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() # removing logs for a fresh start addRemoveUserLogsToQueue queue, loginCredentials.username # this loop adds try_limit + 1 trials to queue for i in [0..JLog.tryLimit()] addLoginTrialToQueue queue, i # removing logs for this username after test passes addRemoveUserLogsToQueue queue, loginCredentials.username async.series queue, done it 'should pass error if invitationToken is set but not valid', (done) -> loginCredentials = generateCredentials invitationToken : 'someinvalidtoken' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'invitation is not valid' done() it 'should pass error if group doesnt exist and groupIsBeingCreated is false', (done) -> loginCredentials = generateCredentials groupName : 'someinvalidgroupName' groupIsBeingCreated : no JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'group doesnt exist' done() it 'should be able to login if group doesnt exist but groupIsBeingCreated is true', (done) -> loginCredentials = generateCredentials groupName : 'someinvalidgroupName' groupIsBeingCreated : yes JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist done() describe '#convert()', -> it 'should pass error if account is already registered', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() client.connection.delegate.type = 'registered' JUser.convert client, userFormData, (err) -> expect(err) .to.exist expect(err.message) .to.be.equal 'This account is already registered.' done() it 'should pass error if username is a reserved one', (done) -> withDummyClient ({ client }) -> queue = [] userFormData = generateDummyUserFormData() reservedUsernames = ['guestuser', 'guest-'] for username in reservedUsernames userFormData.username = username queue.push (next) -> JUser.convert client, userFormData, (err) -> expect(err.message).to.exist next() async.series queue, done it 'should pass error if passwords do not match', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.password = 'somePassword' userFormData.passwordConfirm = 'anotherPassword' JUser.convert client, userFormData, (err) -> expect(err) .to.exist expect(err.message) .to.be.equal 'Passwords must match!' done() it 'should pass error if username is in use', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> # sending a different email address, username will remain same(duplicate) userFormData.email = generateRandomEmail() JUser.convert client, userFormData, (err) -> expect(err.message).to.be.equal 'Errors were encountered during validation' next() ] async.series queue, done it 'should pass error if email is in use', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> # sending a different username, email address will remain same(duplicate) userFormData.username = generateRandomUsername() JUser.convert client, userFormData, (err) -> expect(err?.message).to.be.equal 'Email is already in use!' next() ] async.series queue, done describe 'when user data is valid', -> testConvertWithValidData = (client, userFormData, callback) -> queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> params = { username : userFormData.username } JUser.one params, (err, { data : { email, registeredFrom } }) -> expect(err).to.not.exist expect(email).to.be.equal userFormData.email expect(registeredFrom.ip).to.be.equal client.clientIP next() (next) -> params = { 'profile.nickname' : userFormData.username } JAccount.one params, (err, { data : { profile } }) -> expect(err).to.not.exist expect(profile.nickname).to.be.equal userFormData.username next() ] async.series queue, callback it 'should be able to register user with lower case username', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.username = userFormData.username.toLowerCase() testConvertWithValidData client, userFormData, done it 'should be able to register user with upper case username', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.username = userFormData.username.toUpperCase() testConvertWithValidData client, userFormData, done describe '#unregister()', -> describe 'when user is not registered', -> it 'should return err', (done) -> client = {} queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> # username won't matter, only client's account will be checked JUser.unregister client, generateRandomUsername(), (err) -> expect(err?.message).to.be.equal 'You are not registered!' next() ] async.series queue, done describe 'when user is registered', -> it 'should return error if requester doesnt have right to unregister', (done) -> client = {} userFormData = generateDummyUserFormData() queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> JUser.convert client, userFormData, (err, data) -> expect(err).to.not.exist # set credentials { account, newToken } = data client.sessionToken = newToken client.connection.delegate = account next() (next) -> # username won't matter, only client's account will be checked JUser.unregister client, generateRandomUsername(), (err) -> expect(err?.message).to.be.equal 'You must confirm this action!' next() ] async.series queue, done it 'user should be updated if requester has the right to unregister', (done) -> client = {} userFormData = generateDummyUserFormData() { email, username } = userFormData queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> # registering user JUser.convert client, userFormData, (err, data) -> expect(err).to.not.exist # set credentials { account, newToken } = data client.sessionToken = newToken client.connection.delegate = account next() (next) -> # expecting user to exist before unregister JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(user) .to.exist expect(user.email) .to.be.equal email expect(user.username) .to.be.equal username next() (next) -> # expecting name to exist before unregister JName.one { name : username }, (err, name) -> expect(err) .to.not.exist expect(name) .to.exist next() (next) -> # expecting user account to exist before unregister JAccount.one { 'profile.nickname' : username }, (err, account) -> expect(err) .to.not.exist expect(account) .to.exist expect(account.type) .to.be.equal 'registered' expect(account.onlineStatus) .to.be.equal 'online' next() (next) -> # expecting successful unregister JUser.unregister client, username, (err) -> expect(err).to.not.exist next() (next) -> # expecting user to be deleted after unregister JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(user) .to.not.exist next() (next) -> # expecting name to be deleted JName.one { name : username }, (err, name) -> expect(err) .to.not.exist expect(name) .to.not.exist next() (next) -> # expecting user account to be deleted after unregister JAccount.one { 'profile.nickname' : username }, (err, account) -> expect(err) .to.not.exist expect(account) .to.not.exist next() ] async.series queue, done describe '#verifyRecaptcha()', -> it 'should pass error if captcha code is empty', (done) -> params = { slug: 'koding' } captchaCode = '' JUser.verifyRecaptcha captchaCode, params, (err) -> expect(err?.message).to.be.equal 'Captcha not valid. Please try again.' done() it 'should pass error if captcha code is invalid', (done) -> params = { slug: 'koding' } captchaCode = 'someInvalidCaptchaCode' JUser.verifyRecaptcha captchaCode, params, (err) -> expect(err?.message).to.be.equal 'Captcha not valid. Please try again.' done() describe '#authenticateClient()', -> describe 'when there is no session for the given clientId', -> it 'should create a new session', (done) -> JUser.authenticateClient 'someInvalidClientId', (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.session).to.have.property 'clientId' expect(data.session).to.have.property 'username' expect(data.account).to.be.an 'object' expect(data.account).to.have.property 'socialApiId' expect(data.account).to.have.property 'profile' done() describe 'when there is a session for the given clientId', -> it 'should return error if username doesnt exist in session', (done) -> sessionToken = null queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $unset : { username : 1 } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err?.message).to.be.equal 'no username found' next() ] async.series queue, done it 'should be handle guest user if username starts with guest-', (done) -> guestUsername = "guest-#{generateRandomString 10}" sessionToken = null queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $set : { username : guestUsername } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.account).to.be.an 'object' expect(data.account.profile.nickname).to.be.equal guestUsername expect(data.account.type).to.be.equal 'unregistered' next() ] async.series queue, done it 'should return error if username doesnt match any user', (done) -> sessionToken = null invalidUsername = 'someInvalidUsername' queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $set : { username : invalidUsername } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err?.message).to.be.equal "no user found with #{invalidUsername} and sessionId" next() ] async.series queue, done it 'should return session and account if session is valid', (done) -> sessionToken = null queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.session).to.have.property 'clientId' expect(data.session).to.have.property 'username' expect(data.account).to.be.an 'object' expect(data.account).to.have.property 'socialApiId' expect(data.account).to.have.property 'profile' next() ] async.series queue, done beforeTests() runTests() afterTests()
142224
JLog = require '../log/index' JUser = require './index' JName = require '../name' JAccount = require '../account' JSession = require '../session' Speakeasy = require 'speakeasy' { async expect withDummyClient generateUserInfo withConvertedUser generateDummyClient generateCredentials generateRandomEmail generateRandomString generateRandomUsername checkBongoConnectivity generateDummyUserFormData } = require '../../../../testhelper' # this function will be called once before running any test beforeTests = -> before (done) -> checkBongoConnectivity done # this function will be called after all tests are executed afterTests = -> after -> # here we have actual tests runTests = -> describe 'workers.social.user.index', -> describe '#createUser', -> it 'should pass error passwordStatus type is not valid', (done) -> userInfo = generateUserInfo() userInfo.passwordStatus = '<PASSWORD>' JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal 'Errors were encountered during validation.' done() it 'should error if username is not set', (done) -> userInfo = generateUserInfo() userInfo.username = '' JUser.createUser userInfo, (err) -> expect(err).to.exist done() it 'should pass error if username is in use', (done) -> userInfo = generateUserInfo() queue = [ (next) -> JUser.createUser userInfo, (err) -> expect(err).to.not.exist next() (next) -> # setting a different email, username will be duplicate userInfo.email = generateRandomEmail() expectedError = "The slug #{userInfo.username} is not available." JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal expectedError next() ] async.series queue, done it 'should pass error if email is in use', (done) -> userInfo = generateUserInfo() queue = [ (next) -> JUser.createUser userInfo, (err) -> expect(err).to.not.exist next() (next) -> # setting a different username, email will be duplicate userInfo.username = generateRandomString() expectedError = "Sorry, \"#{userInfo.email}\" is already in use!" JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal expectedError next() ] async.series queue, done describe 'when user data is valid', -> testCreateUserWithValidData = (userInfo, callback) -> queue = [ (next) -> # expecting user to be created JUser.createUser userInfo, (err) -> expect(err).to.not.exist # after the user is created, lower casing username because # we expect to see the username to be lower cased in jmodel documents userInfo.username = userInfo.username.toLowerCase() next() (next) -> # expecting user to be saved params = { username : userInfo.username } JUser.one params, (err, user) -> expect(err).to.not.exist expect(user.username).to.be.equal userInfo.username next() (next) -> # expecting account to be created and saved params = { 'profile.nickname' : userInfo.username } JAccount.one params, (err, account) -> expect(err).to.not.exist expect(account).to.exist next() (next) -> # expecting name to be created and saved params = { 'name' : userInfo.username } JName.one params, (err, name) -> expect(err).to.not.exist expect(name).to.exist next() ] async.series queue, callback it 'should be able to create user with lower case username', (done) -> userInfo = generateUserInfo() userInfo.username = userInfo.username.toLowerCase() testCreateUserWithValidData userInfo, done it 'should be able to create user with upper case username', (done) -> userInfo = generateUserInfo() userInfo.username = userInfo.username.toUpperCase() testCreateUserWithValidData userInfo, done it 'should save email frequencies correctly', (done) -> userInfo = generateUserInfo() userInfo.emailFrequency = global : off daily : off followActions : off privateMessage : off testCreateUserWithValidData userInfo, -> params = { username : userInfo.username } JUser.one params, (err, user) -> expect(err).to.not.exist expect(user.emailFrequency.global).to.be.false expect(user.emailFrequency.daily).to.be.false expect(user.emailFrequency.privateMessage).to.be.false expect(user.emailFrequency.followActions).to.be.false done() describe '#login()', -> describe 'when request is valid', -> testLoginWithValidData = (options, callback) -> lastLoginDate = null { loginCredentials, username } = options username ?= loginCredentials.username queue = [ (next) -> # expecting successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # keeping last login date JUser.one { username }, (err, user) -> expect(err).to.not.exist lastLoginDate = user.lastLoginDate next() (next) -> # expecting another successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # expecting last login date to be changed JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(lastLoginDate) .not.to.be.equal user.lastLoginDate next() ] async.series queue, callback it 'should be able to login user with lower case username', (done) -> # trying to login with username withConvertedUser ({ userFormData : { username, password } }) -> loginCredentials = generateCredentials { username, password } testLoginWithValidData { loginCredentials }, done it 'should be able to login with uppercase username', (done) -> # trying to login with username withConvertedUser ({ userFormData : { username, password } }) -> opts = { username : username.toUpperCase(), password } loginCredentials = generateCredentials opts testLoginWithValidData { loginCredentials, username }, done it 'should handle username normalizing correctly', (done) -> # trying to login with email instead of username withConvertedUser ({ userFormData : { username, password, email } }) -> loginCredentials = generateCredentials { username : email, password } testLoginWithValidData { loginCredentials, username }, done it 'should handle two factor authentication correctly', (done) -> withConvertedUser ({ userFormData : { username, password } }) -> tfcode = null loginCredentials = generateCredentials { username, password } queue = [ (next) -> # setting two factor authentication on by adding twofactorkey field JUser.update { username }, { $set: { twofactorkey: 'somekey' } }, (err) -> expect(err).to.not.exist next() (next) -> # trying to login with empty tf code loginCredentials.tfcode = '' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'TwoFactor auth Enabled' next() (next) -> # trying to login with invalid tfcode loginCredentials.tfcode = 'invalidtfcode' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'Access denied!' next() (next) -> # generating a 2fa key and saving it in mongo { base32 : tfcode } = Speakeasy.generate_key length : 20 encoding : 'base32' JUser.update { username }, { $set: { twofactorkey: tfcode } }, (err) -> expect(err).to.not.exist next() (next) -> # generating a verificationCode and expecting a successful login verificationCode = Speakeasy.totp key : tfcode encoding : 'base32' loginCredentials.tfcode = verificationCode JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() ] async.series queue, done it 'should pass error if account is not found', (done) -> { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() (next) -> # removing users account JAccount.remove { 'profile.nickname': username }, (err) -> expect(err).to.not.exist next() (next) -> # expecting not to able to login without an account JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'No account found!' next() ] async.series queue, done it 'should check if the user is blocked', (done) -> # generating user info with random username and password user = null { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user_) -> user = user_ expect(err).to.not.exist next() (next) -> # expecting successful login with the newly generated user JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # blocking user for 1 day untilDate = new Date(Date.now() + 1000 * 60 * 60 * 24) user.block untilDate, (err) -> expect(err).to.not.exist next() (next) -> # expecting login attempt to fail and return blocked message JUser.login null, loginCredentials, (err) -> toDate = user.blockedUntil.toUTCString() expect(err.message).to.be.equal JUser.getBlockedMessage toDate next() (next) -> # unblocking user user.unblock (err) -> expect(err).to.not.exist next() (next) -> # expecting user to be able to login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() ] async.series queue, done it 'should pass error if user\'s password needs reset', (done) -> # generating user info with random username and password { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } setUserPasswordStatus = (username, status, callback) -> JUser.update { username }, { $set: { passwordStatus: status } }, (err) -> expect(err).to.not.exist callback() queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() (next) -> setUserPasswordStatus username, 'valid', next (next) -> # expecting successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> setUserPasswordStatus username, 'needs reset', next (next) -> # expecting unsuccessful login attempt JUser.login null, loginCredentials, (err) -> expect(err).to.exist next() (next) -> setUserPasswordStatus username, 'valid', next ] async.series queue, done it 'should create a new session if clientId is not specified', (done) -> loginCredentials = generateCredentials() # when client id is not specified, a new session should be created JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist done() it 'should should pass error if username is not registered', (done) -> loginCredentials = generateCredentials username : 'herecomesanunregisteredusername' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'Unknown user name' done() # this case also tests if logging is working correctly it 'should check for brute force attack', (done) -> queue = [] { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials username : username password : '<PASSWORD>' addRemoveUserLogsToQueue = (queue, username) -> queue.push (next) -> JLog.remove { username }, (err) -> expect(err).to.not.exist next() addLoginTrialToQueue = (queue, tryCount) -> queue.push (next) -> JUser.login null, loginCredentials, (err) -> expectedError = switch when tryCount < JLog.tryLimit() 'Access denied!' else "Your login access is blocked for #{JLog.timeLimit()} minutes." expect(err.message).to.be.equal expectedError next() queue.push (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() # removing logs for a fresh start addRemoveUserLogsToQueue queue, loginCredentials.username # this loop adds try_limit + 1 trials to queue for i in [0..JLog.tryLimit()] addLoginTrialToQueue queue, i # removing logs for this username after test passes addRemoveUserLogsToQueue queue, loginCredentials.username async.series queue, done it 'should pass error if invitationToken is set but not valid', (done) -> loginCredentials = generateCredentials invitationToken : '<PASSWORD>' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'invitation is not valid' done() it 'should pass error if group doesnt exist and groupIsBeingCreated is false', (done) -> loginCredentials = generateCredentials groupName : 'someinvalidgroupName' groupIsBeingCreated : no JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'group doesnt exist' done() it 'should be able to login if group doesnt exist but groupIsBeingCreated is true', (done) -> loginCredentials = generateCredentials groupName : 'someinvalidgroupName' groupIsBeingCreated : yes JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist done() describe '#convert()', -> it 'should pass error if account is already registered', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() client.connection.delegate.type = 'registered' JUser.convert client, userFormData, (err) -> expect(err) .to.exist expect(err.message) .to.be.equal 'This account is already registered.' done() it 'should pass error if username is a reserved one', (done) -> withDummyClient ({ client }) -> queue = [] userFormData = generateDummyUserFormData() reservedUsernames = ['guestuser', 'guest-'] for username in reservedUsernames userFormData.username = username queue.push (next) -> JUser.convert client, userFormData, (err) -> expect(err.message).to.exist next() async.series queue, done it 'should pass error if passwords do not match', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.password = '<PASSWORD>' userFormData.passwordConfirm = '<PASSWORD>' JUser.convert client, userFormData, (err) -> expect(err) .to.exist expect(err.message) .to.be.equal 'Passwords must match!' done() it 'should pass error if username is in use', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> # sending a different email address, username will remain same(duplicate) userFormData.email = generateRandomEmail() JUser.convert client, userFormData, (err) -> expect(err.message).to.be.equal 'Errors were encountered during validation' next() ] async.series queue, done it 'should pass error if email is in use', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> # sending a different username, email address will remain same(duplicate) userFormData.username = generateRandomUsername() JUser.convert client, userFormData, (err) -> expect(err?.message).to.be.equal 'Email is already in use!' next() ] async.series queue, done describe 'when user data is valid', -> testConvertWithValidData = (client, userFormData, callback) -> queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> params = { username : userFormData.username } JUser.one params, (err, { data : { email, registeredFrom } }) -> expect(err).to.not.exist expect(email).to.be.equal userFormData.email expect(registeredFrom.ip).to.be.equal client.clientIP next() (next) -> params = { 'profile.nickname' : userFormData.username } JAccount.one params, (err, { data : { profile } }) -> expect(err).to.not.exist expect(profile.nickname).to.be.equal userFormData.username next() ] async.series queue, callback it 'should be able to register user with lower case username', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.username = userFormData.username.toLowerCase() testConvertWithValidData client, userFormData, done it 'should be able to register user with upper case username', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.username = userFormData.username.toUpperCase() testConvertWithValidData client, userFormData, done describe '#unregister()', -> describe 'when user is not registered', -> it 'should return err', (done) -> client = {} queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> # username won't matter, only client's account will be checked JUser.unregister client, generateRandomUsername(), (err) -> expect(err?.message).to.be.equal 'You are not registered!' next() ] async.series queue, done describe 'when user is registered', -> it 'should return error if requester doesnt have right to unregister', (done) -> client = {} userFormData = generateDummyUserFormData() queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> JUser.convert client, userFormData, (err, data) -> expect(err).to.not.exist # set credentials { account, newToken } = data client.sessionToken = newToken client.connection.delegate = account next() (next) -> # username won't matter, only client's account will be checked JUser.unregister client, generateRandomUsername(), (err) -> expect(err?.message).to.be.equal 'You must confirm this action!' next() ] async.series queue, done it 'user should be updated if requester has the right to unregister', (done) -> client = {} userFormData = generateDummyUserFormData() { email, username } = userFormData queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> # registering user JUser.convert client, userFormData, (err, data) -> expect(err).to.not.exist # set credentials { account, newToken } = data client.sessionToken = newToken client.connection.delegate = account next() (next) -> # expecting user to exist before unregister JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(user) .to.exist expect(user.email) .to.be.equal email expect(user.username) .to.be.equal username next() (next) -> # expecting name to exist before unregister JName.one { name : username }, (err, name) -> expect(err) .to.not.exist expect(name) .to.exist next() (next) -> # expecting user account to exist before unregister JAccount.one { 'profile.nickname' : username }, (err, account) -> expect(err) .to.not.exist expect(account) .to.exist expect(account.type) .to.be.equal 'registered' expect(account.onlineStatus) .to.be.equal 'online' next() (next) -> # expecting successful unregister JUser.unregister client, username, (err) -> expect(err).to.not.exist next() (next) -> # expecting user to be deleted after unregister JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(user) .to.not.exist next() (next) -> # expecting name to be deleted JName.one { name : username }, (err, name) -> expect(err) .to.not.exist expect(name) .to.not.exist next() (next) -> # expecting user account to be deleted after unregister JAccount.one { 'profile.nickname' : username }, (err, account) -> expect(err) .to.not.exist expect(account) .to.not.exist next() ] async.series queue, done describe '#verifyRecaptcha()', -> it 'should pass error if captcha code is empty', (done) -> params = { slug: 'koding' } captchaCode = '' JUser.verifyRecaptcha captchaCode, params, (err) -> expect(err?.message).to.be.equal 'Captcha not valid. Please try again.' done() it 'should pass error if captcha code is invalid', (done) -> params = { slug: 'koding' } captchaCode = 'someInvalidCaptchaCode' JUser.verifyRecaptcha captchaCode, params, (err) -> expect(err?.message).to.be.equal 'Captcha not valid. Please try again.' done() describe '#authenticateClient()', -> describe 'when there is no session for the given clientId', -> it 'should create a new session', (done) -> JUser.authenticateClient 'someInvalidClientId', (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.session).to.have.property 'clientId' expect(data.session).to.have.property 'username' expect(data.account).to.be.an 'object' expect(data.account).to.have.property 'socialApiId' expect(data.account).to.have.property 'profile' done() describe 'when there is a session for the given clientId', -> it 'should return error if username doesnt exist in session', (done) -> sessionToken = null queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $unset : { username : 1 } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err?.message).to.be.equal 'no username found' next() ] async.series queue, done it 'should be handle guest user if username starts with guest-', (done) -> guestUsername = "guest-#{generateRandomString 10}" sessionToken = null queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $set : { username : guestUsername } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.account).to.be.an 'object' expect(data.account.profile.nickname).to.be.equal guestUsername expect(data.account.type).to.be.equal 'unregistered' next() ] async.series queue, done it 'should return error if username doesnt match any user', (done) -> sessionToken = null invalidUsername = 'someInvalidUsername' queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $set : { username : invalidUsername } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err?.message).to.be.equal "no user found with #{invalidUsername} and sessionId" next() ] async.series queue, done it 'should return session and account if session is valid', (done) -> sessionToken = null queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.session).to.have.property 'clientId' expect(data.session).to.have.property 'username' expect(data.account).to.be.an 'object' expect(data.account).to.have.property 'socialApiId' expect(data.account).to.have.property 'profile' next() ] async.series queue, done beforeTests() runTests() afterTests()
true
JLog = require '../log/index' JUser = require './index' JName = require '../name' JAccount = require '../account' JSession = require '../session' Speakeasy = require 'speakeasy' { async expect withDummyClient generateUserInfo withConvertedUser generateDummyClient generateCredentials generateRandomEmail generateRandomString generateRandomUsername checkBongoConnectivity generateDummyUserFormData } = require '../../../../testhelper' # this function will be called once before running any test beforeTests = -> before (done) -> checkBongoConnectivity done # this function will be called after all tests are executed afterTests = -> after -> # here we have actual tests runTests = -> describe 'workers.social.user.index', -> describe '#createUser', -> it 'should pass error passwordStatus type is not valid', (done) -> userInfo = generateUserInfo() userInfo.passwordStatus = 'PI:PASSWORD:<PASSWORD>END_PI' JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal 'Errors were encountered during validation.' done() it 'should error if username is not set', (done) -> userInfo = generateUserInfo() userInfo.username = '' JUser.createUser userInfo, (err) -> expect(err).to.exist done() it 'should pass error if username is in use', (done) -> userInfo = generateUserInfo() queue = [ (next) -> JUser.createUser userInfo, (err) -> expect(err).to.not.exist next() (next) -> # setting a different email, username will be duplicate userInfo.email = generateRandomEmail() expectedError = "The slug #{userInfo.username} is not available." JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal expectedError next() ] async.series queue, done it 'should pass error if email is in use', (done) -> userInfo = generateUserInfo() queue = [ (next) -> JUser.createUser userInfo, (err) -> expect(err).to.not.exist next() (next) -> # setting a different username, email will be duplicate userInfo.username = generateRandomString() expectedError = "Sorry, \"#{userInfo.email}\" is already in use!" JUser.createUser userInfo, (err) -> expect(err.message).to.be.equal expectedError next() ] async.series queue, done describe 'when user data is valid', -> testCreateUserWithValidData = (userInfo, callback) -> queue = [ (next) -> # expecting user to be created JUser.createUser userInfo, (err) -> expect(err).to.not.exist # after the user is created, lower casing username because # we expect to see the username to be lower cased in jmodel documents userInfo.username = userInfo.username.toLowerCase() next() (next) -> # expecting user to be saved params = { username : userInfo.username } JUser.one params, (err, user) -> expect(err).to.not.exist expect(user.username).to.be.equal userInfo.username next() (next) -> # expecting account to be created and saved params = { 'profile.nickname' : userInfo.username } JAccount.one params, (err, account) -> expect(err).to.not.exist expect(account).to.exist next() (next) -> # expecting name to be created and saved params = { 'name' : userInfo.username } JName.one params, (err, name) -> expect(err).to.not.exist expect(name).to.exist next() ] async.series queue, callback it 'should be able to create user with lower case username', (done) -> userInfo = generateUserInfo() userInfo.username = userInfo.username.toLowerCase() testCreateUserWithValidData userInfo, done it 'should be able to create user with upper case username', (done) -> userInfo = generateUserInfo() userInfo.username = userInfo.username.toUpperCase() testCreateUserWithValidData userInfo, done it 'should save email frequencies correctly', (done) -> userInfo = generateUserInfo() userInfo.emailFrequency = global : off daily : off followActions : off privateMessage : off testCreateUserWithValidData userInfo, -> params = { username : userInfo.username } JUser.one params, (err, user) -> expect(err).to.not.exist expect(user.emailFrequency.global).to.be.false expect(user.emailFrequency.daily).to.be.false expect(user.emailFrequency.privateMessage).to.be.false expect(user.emailFrequency.followActions).to.be.false done() describe '#login()', -> describe 'when request is valid', -> testLoginWithValidData = (options, callback) -> lastLoginDate = null { loginCredentials, username } = options username ?= loginCredentials.username queue = [ (next) -> # expecting successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # keeping last login date JUser.one { username }, (err, user) -> expect(err).to.not.exist lastLoginDate = user.lastLoginDate next() (next) -> # expecting another successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # expecting last login date to be changed JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(lastLoginDate) .not.to.be.equal user.lastLoginDate next() ] async.series queue, callback it 'should be able to login user with lower case username', (done) -> # trying to login with username withConvertedUser ({ userFormData : { username, password } }) -> loginCredentials = generateCredentials { username, password } testLoginWithValidData { loginCredentials }, done it 'should be able to login with uppercase username', (done) -> # trying to login with username withConvertedUser ({ userFormData : { username, password } }) -> opts = { username : username.toUpperCase(), password } loginCredentials = generateCredentials opts testLoginWithValidData { loginCredentials, username }, done it 'should handle username normalizing correctly', (done) -> # trying to login with email instead of username withConvertedUser ({ userFormData : { username, password, email } }) -> loginCredentials = generateCredentials { username : email, password } testLoginWithValidData { loginCredentials, username }, done it 'should handle two factor authentication correctly', (done) -> withConvertedUser ({ userFormData : { username, password } }) -> tfcode = null loginCredentials = generateCredentials { username, password } queue = [ (next) -> # setting two factor authentication on by adding twofactorkey field JUser.update { username }, { $set: { twofactorkey: 'somekey' } }, (err) -> expect(err).to.not.exist next() (next) -> # trying to login with empty tf code loginCredentials.tfcode = '' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'TwoFactor auth Enabled' next() (next) -> # trying to login with invalid tfcode loginCredentials.tfcode = 'invalidtfcode' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'Access denied!' next() (next) -> # generating a 2fa key and saving it in mongo { base32 : tfcode } = Speakeasy.generate_key length : 20 encoding : 'base32' JUser.update { username }, { $set: { twofactorkey: tfcode } }, (err) -> expect(err).to.not.exist next() (next) -> # generating a verificationCode and expecting a successful login verificationCode = Speakeasy.totp key : tfcode encoding : 'base32' loginCredentials.tfcode = verificationCode JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() ] async.series queue, done it 'should pass error if account is not found', (done) -> { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() (next) -> # removing users account JAccount.remove { 'profile.nickname': username }, (err) -> expect(err).to.not.exist next() (next) -> # expecting not to able to login without an account JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'No account found!' next() ] async.series queue, done it 'should check if the user is blocked', (done) -> # generating user info with random username and password user = null { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user_) -> user = user_ expect(err).to.not.exist next() (next) -> # expecting successful login with the newly generated user JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> # blocking user for 1 day untilDate = new Date(Date.now() + 1000 * 60 * 60 * 24) user.block untilDate, (err) -> expect(err).to.not.exist next() (next) -> # expecting login attempt to fail and return blocked message JUser.login null, loginCredentials, (err) -> toDate = user.blockedUntil.toUTCString() expect(err.message).to.be.equal JUser.getBlockedMessage toDate next() (next) -> # unblocking user user.unblock (err) -> expect(err).to.not.exist next() (next) -> # expecting user to be able to login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() ] async.series queue, done it 'should pass error if user\'s password needs reset', (done) -> # generating user info with random username and password { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials { username, password } setUserPasswordStatus = (username, status, callback) -> JUser.update { username }, { $set: { passwordStatus: status } }, (err) -> expect(err).to.not.exist callback() queue = [ (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() (next) -> setUserPasswordStatus username, 'valid', next (next) -> # expecting successful login JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist next() (next) -> setUserPasswordStatus username, 'needs reset', next (next) -> # expecting unsuccessful login attempt JUser.login null, loginCredentials, (err) -> expect(err).to.exist next() (next) -> setUserPasswordStatus username, 'valid', next ] async.series queue, done it 'should create a new session if clientId is not specified', (done) -> loginCredentials = generateCredentials() # when client id is not specified, a new session should be created JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist done() it 'should should pass error if username is not registered', (done) -> loginCredentials = generateCredentials username : 'herecomesanunregisteredusername' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'Unknown user name' done() # this case also tests if logging is working correctly it 'should check for brute force attack', (done) -> queue = [] { username, password } = userInfo = generateUserInfo() loginCredentials = generateCredentials username : username password : 'PI:PASSWORD:<PASSWORD>END_PI' addRemoveUserLogsToQueue = (queue, username) -> queue.push (next) -> JLog.remove { username }, (err) -> expect(err).to.not.exist next() addLoginTrialToQueue = (queue, tryCount) -> queue.push (next) -> JUser.login null, loginCredentials, (err) -> expectedError = switch when tryCount < JLog.tryLimit() 'Access denied!' else "Your login access is blocked for #{JLog.timeLimit()} minutes." expect(err.message).to.be.equal expectedError next() queue.push (next) -> # creating a new user with the newly generated userinfo JUser.createUser userInfo, (err, user) -> expect(err).to.not.exist next() # removing logs for a fresh start addRemoveUserLogsToQueue queue, loginCredentials.username # this loop adds try_limit + 1 trials to queue for i in [0..JLog.tryLimit()] addLoginTrialToQueue queue, i # removing logs for this username after test passes addRemoveUserLogsToQueue queue, loginCredentials.username async.series queue, done it 'should pass error if invitationToken is set but not valid', (done) -> loginCredentials = generateCredentials invitationToken : 'PI:PASSWORD:<PASSWORD>END_PI' JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'invitation is not valid' done() it 'should pass error if group doesnt exist and groupIsBeingCreated is false', (done) -> loginCredentials = generateCredentials groupName : 'someinvalidgroupName' groupIsBeingCreated : no JUser.login null, loginCredentials, (err) -> expect(err.message).to.be.equal 'group doesnt exist' done() it 'should be able to login if group doesnt exist but groupIsBeingCreated is true', (done) -> loginCredentials = generateCredentials groupName : 'someinvalidgroupName' groupIsBeingCreated : yes JUser.login null, loginCredentials, (err) -> expect(err).to.not.exist done() describe '#convert()', -> it 'should pass error if account is already registered', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() client.connection.delegate.type = 'registered' JUser.convert client, userFormData, (err) -> expect(err) .to.exist expect(err.message) .to.be.equal 'This account is already registered.' done() it 'should pass error if username is a reserved one', (done) -> withDummyClient ({ client }) -> queue = [] userFormData = generateDummyUserFormData() reservedUsernames = ['guestuser', 'guest-'] for username in reservedUsernames userFormData.username = username queue.push (next) -> JUser.convert client, userFormData, (err) -> expect(err.message).to.exist next() async.series queue, done it 'should pass error if passwords do not match', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.password = 'PI:PASSWORD:<PASSWORD>END_PI' userFormData.passwordConfirm = 'PI:PASSWORD:<PASSWORD>END_PI' JUser.convert client, userFormData, (err) -> expect(err) .to.exist expect(err.message) .to.be.equal 'Passwords must match!' done() it 'should pass error if username is in use', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> # sending a different email address, username will remain same(duplicate) userFormData.email = generateRandomEmail() JUser.convert client, userFormData, (err) -> expect(err.message).to.be.equal 'Errors were encountered during validation' next() ] async.series queue, done it 'should pass error if email is in use', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> # sending a different username, email address will remain same(duplicate) userFormData.username = generateRandomUsername() JUser.convert client, userFormData, (err) -> expect(err?.message).to.be.equal 'Email is already in use!' next() ] async.series queue, done describe 'when user data is valid', -> testConvertWithValidData = (client, userFormData, callback) -> queue = [ (next) -> JUser.convert client, userFormData, (err) -> expect(err).to.not.exist next() (next) -> params = { username : userFormData.username } JUser.one params, (err, { data : { email, registeredFrom } }) -> expect(err).to.not.exist expect(email).to.be.equal userFormData.email expect(registeredFrom.ip).to.be.equal client.clientIP next() (next) -> params = { 'profile.nickname' : userFormData.username } JAccount.one params, (err, { data : { profile } }) -> expect(err).to.not.exist expect(profile.nickname).to.be.equal userFormData.username next() ] async.series queue, callback it 'should be able to register user with lower case username', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.username = userFormData.username.toLowerCase() testConvertWithValidData client, userFormData, done it 'should be able to register user with upper case username', (done) -> withDummyClient ({ client }) -> userFormData = generateDummyUserFormData() userFormData.username = userFormData.username.toUpperCase() testConvertWithValidData client, userFormData, done describe '#unregister()', -> describe 'when user is not registered', -> it 'should return err', (done) -> client = {} queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> # username won't matter, only client's account will be checked JUser.unregister client, generateRandomUsername(), (err) -> expect(err?.message).to.be.equal 'You are not registered!' next() ] async.series queue, done describe 'when user is registered', -> it 'should return error if requester doesnt have right to unregister', (done) -> client = {} userFormData = generateDummyUserFormData() queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> JUser.convert client, userFormData, (err, data) -> expect(err).to.not.exist # set credentials { account, newToken } = data client.sessionToken = newToken client.connection.delegate = account next() (next) -> # username won't matter, only client's account will be checked JUser.unregister client, generateRandomUsername(), (err) -> expect(err?.message).to.be.equal 'You must confirm this action!' next() ] async.series queue, done it 'user should be updated if requester has the right to unregister', (done) -> client = {} userFormData = generateDummyUserFormData() { email, username } = userFormData queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist client = client_ next() (next) -> # registering user JUser.convert client, userFormData, (err, data) -> expect(err).to.not.exist # set credentials { account, newToken } = data client.sessionToken = newToken client.connection.delegate = account next() (next) -> # expecting user to exist before unregister JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(user) .to.exist expect(user.email) .to.be.equal email expect(user.username) .to.be.equal username next() (next) -> # expecting name to exist before unregister JName.one { name : username }, (err, name) -> expect(err) .to.not.exist expect(name) .to.exist next() (next) -> # expecting user account to exist before unregister JAccount.one { 'profile.nickname' : username }, (err, account) -> expect(err) .to.not.exist expect(account) .to.exist expect(account.type) .to.be.equal 'registered' expect(account.onlineStatus) .to.be.equal 'online' next() (next) -> # expecting successful unregister JUser.unregister client, username, (err) -> expect(err).to.not.exist next() (next) -> # expecting user to be deleted after unregister JUser.one { username }, (err, user) -> expect(err) .to.not.exist expect(user) .to.not.exist next() (next) -> # expecting name to be deleted JName.one { name : username }, (err, name) -> expect(err) .to.not.exist expect(name) .to.not.exist next() (next) -> # expecting user account to be deleted after unregister JAccount.one { 'profile.nickname' : username }, (err, account) -> expect(err) .to.not.exist expect(account) .to.not.exist next() ] async.series queue, done describe '#verifyRecaptcha()', -> it 'should pass error if captcha code is empty', (done) -> params = { slug: 'koding' } captchaCode = '' JUser.verifyRecaptcha captchaCode, params, (err) -> expect(err?.message).to.be.equal 'Captcha not valid. Please try again.' done() it 'should pass error if captcha code is invalid', (done) -> params = { slug: 'koding' } captchaCode = 'someInvalidCaptchaCode' JUser.verifyRecaptcha captchaCode, params, (err) -> expect(err?.message).to.be.equal 'Captcha not valid. Please try again.' done() describe '#authenticateClient()', -> describe 'when there is no session for the given clientId', -> it 'should create a new session', (done) -> JUser.authenticateClient 'someInvalidClientId', (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.session).to.have.property 'clientId' expect(data.session).to.have.property 'username' expect(data.account).to.be.an 'object' expect(data.account).to.have.property 'socialApiId' expect(data.account).to.have.property 'profile' done() describe 'when there is a session for the given clientId', -> it 'should return error if username doesnt exist in session', (done) -> sessionToken = null queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $unset : { username : 1 } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err?.message).to.be.equal 'no username found' next() ] async.series queue, done it 'should be handle guest user if username starts with guest-', (done) -> guestUsername = "guest-#{generateRandomString 10}" sessionToken = null queue = [ (next) -> generateDummyClient { group : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $set : { username : guestUsername } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.account).to.be.an 'object' expect(data.account.profile.nickname).to.be.equal guestUsername expect(data.account.type).to.be.equal 'unregistered' next() ] async.series queue, done it 'should return error if username doesnt match any user', (done) -> sessionToken = null invalidUsername = 'someInvalidUsername' queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> selector = { clientId : sessionToken } modifier = { $set : { username : invalidUsername } } JSession.update selector, modifier, (err) -> expect(err).to.not.exist next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err?.message).to.be.equal "no user found with #{invalidUsername} and sessionId" next() ] async.series queue, done it 'should return session and account if session is valid', (done) -> sessionToken = null queue = [ (next) -> generateDummyClient { gorup : 'koding' }, (err, client_) -> expect(err).to.not.exist { sessionToken } = client_ next() (next) -> JUser.authenticateClient sessionToken, (err, data) -> expect(err).to.not.exist expect(data.session).to.be.an 'object' expect(data.session).to.have.property 'clientId' expect(data.session).to.have.property 'username' expect(data.account).to.be.an 'object' expect(data.account).to.have.property 'socialApiId' expect(data.account).to.have.property 'profile' next() ] async.series queue, done beforeTests() runTests() afterTests()
[ { "context": "atter, you can also send an email to the team at [contact@zooniverse.org](mailto:contact@zooniverse.org). Please understan", "end": 516, "score": 0.9999262690544128, "start": 494, "tag": "EMAIL", "value": "contact@zooniverse.org" }, { "context": "il to the team at [cont...
app/pages/about/contact-page.cjsx
alexbfree/Panoptes-Front-End
0
counterpart = require 'counterpart' React = require 'react' {Markdown} = (require 'markdownz').default counterpart.registerTranslations 'en', contactPage: content: ''' ## Contact & Social Media Most of the time, the best way to reach the Zooniverse team, or any project teams, especially about any project-specific issues, is through the discussion boards. If you need to contact the Zooniverse team about a general matter, you can also send an email to the team at [contact@zooniverse.org](mailto:contact@zooniverse.org). Please understand that the Zooniverse team is relatively small and very busy, so unfortunately we cannot reply to all of the emails we receive. If you are interested in collaborating with the Zooniverse, for instance on a custom-built project, please email [collab@zooniverse.org](mailto:collab@zooniverse.org). (Note that our [Project Builder](/lab) offers an effective way to set up a new project without needing to contact the team!) For press inquires, please contact the Zooniverse directors Chris Lintott at [chris@zooniverse.org](mailto:chris@zooniverse.org) or +44 (0) 7808 167288 or Laura Trouille at [trouille@zooniverse.org](mailto:trouille@zooniverse.org) or +1 312 322 0820. If you want to keep up to date with what's going on across the Zooniverse and our latest results, check out the [Daily Zooniverse](http://daily.zooniverse.org/) or the main [Zooniverse blog](http://blog.zooniverse.org/). You can also follow the Zooniverse on [Twitter](http://twitter.com/the_zooniverse), [Facebook](http://facebook.com/therealzooniverse), and [Google+](https://plus.google.com/+ZooniverseOrgReal). ''' module.exports = React.createClass displayName: 'ContactPage' componentDidMount: -> document.documentElement.classList.add 'on-secondary-page' componentWillUnmount: -> document.documentElement.classList.remove 'on-secondary-page' render: -> <Markdown>{counterpart "contactPage.content"}</Markdown>
222493
counterpart = require 'counterpart' React = require 'react' {Markdown} = (require 'markdownz').default counterpart.registerTranslations 'en', contactPage: content: ''' ## Contact & Social Media Most of the time, the best way to reach the Zooniverse team, or any project teams, especially about any project-specific issues, is through the discussion boards. If you need to contact the Zooniverse team about a general matter, you can also send an email to the team at [<EMAIL>](mailto:<EMAIL>). Please understand that the Zooniverse team is relatively small and very busy, so unfortunately we cannot reply to all of the emails we receive. If you are interested in collaborating with the Zooniverse, for instance on a custom-built project, please email [<EMAIL>](mailto:<EMAIL>). (Note that our [Project Builder](/lab) offers an effective way to set up a new project without needing to contact the team!) For press inquires, please contact the Zooniverse directors <NAME> at [<EMAIL>](mailto:<EMAIL>) or +44 (0) 7808 167288 or <NAME> Trouille at [<EMAIL>](mailto:<EMAIL>) or +1 312 322 0820. If you want to keep up to date with what's going on across the Zooniverse and our latest results, check out the [Daily Zooniverse](http://daily.zooniverse.org/) or the main [Zooniverse blog](http://blog.zooniverse.org/). You can also follow the Zooniverse on [Twitter](http://twitter.com/the_zooniverse), [Facebook](http://facebook.com/therealzooniverse), and [Google+](https://plus.google.com/+ZooniverseOrgReal). ''' module.exports = React.createClass displayName: 'ContactPage' componentDidMount: -> document.documentElement.classList.add 'on-secondary-page' componentWillUnmount: -> document.documentElement.classList.remove 'on-secondary-page' render: -> <Markdown>{counterpart "contactPage.content"}</Markdown>
true
counterpart = require 'counterpart' React = require 'react' {Markdown} = (require 'markdownz').default counterpart.registerTranslations 'en', contactPage: content: ''' ## Contact & Social Media Most of the time, the best way to reach the Zooniverse team, or any project teams, especially about any project-specific issues, is through the discussion boards. If you need to contact the Zooniverse team about a general matter, you can also send an email to the team at [PI:EMAIL:<EMAIL>END_PI](mailto:PI:EMAIL:<EMAIL>END_PI). Please understand that the Zooniverse team is relatively small and very busy, so unfortunately we cannot reply to all of the emails we receive. If you are interested in collaborating with the Zooniverse, for instance on a custom-built project, please email [PI:EMAIL:<EMAIL>END_PI](mailto:PI:EMAIL:<EMAIL>END_PI). (Note that our [Project Builder](/lab) offers an effective way to set up a new project without needing to contact the team!) For press inquires, please contact the Zooniverse directors PI:NAME:<NAME>END_PI at [PI:EMAIL:<EMAIL>END_PI](mailto:PI:EMAIL:<EMAIL>END_PI) or +44 (0) 7808 167288 or PI:NAME:<NAME>END_PI Trouille at [PI:EMAIL:<EMAIL>END_PI](mailto:PI:EMAIL:<EMAIL>END_PI) or +1 312 322 0820. If you want to keep up to date with what's going on across the Zooniverse and our latest results, check out the [Daily Zooniverse](http://daily.zooniverse.org/) or the main [Zooniverse blog](http://blog.zooniverse.org/). You can also follow the Zooniverse on [Twitter](http://twitter.com/the_zooniverse), [Facebook](http://facebook.com/therealzooniverse), and [Google+](https://plus.google.com/+ZooniverseOrgReal). ''' module.exports = React.createClass displayName: 'ContactPage' componentDidMount: -> document.documentElement.classList.add 'on-secondary-page' componentWillUnmount: -> document.documentElement.classList.remove 'on-secondary-page' render: -> <Markdown>{counterpart "contactPage.content"}</Markdown>
[ { "context": "###\n * grunt-mysql-dump\n * https:#github.com/digitalcuisine/grunt-mysql-dump\n *\n * Copyright (c) 2013 David S", "end": 59, "score": 0.9993506669998169, "start": 45, "tag": "USERNAME", "value": "digitalcuisine" }, { "context": "lcuisine/grunt-mysql-dump\n *\n * Copyr...
src/db_dump.js.coffee
UseAllFive/grunt-mysql-dump
0
### * grunt-mysql-dump * https:#github.com/digitalcuisine/grunt-mysql-dump * * Copyright (c) 2013 David Smith, Digital Cuisine * Licensed under the MIT license. ### # Dependencies chalk = require 'chalk' shell = require 'shelljs' path = require 'path' _ = require 'lodash' ### * Lo-Dash Template Helpers * http:#lodash.com/docs/#template * https:#github.com/gruntjs/grunt/wiki/grunt.template ### commandTemplates = mysqldump: "mysqldump -h <%= host %> -P <%= port %> -u<%= user %> <%= pass %> --databases <%= database %>", mysql: 'mysql -h <%= host %> -P <%= port %> -u<%= user %> <%= pass %> < "<%= backup_to %>"', ssh: "ssh <%= host %>" module.exports = (grunt) -> ### DB DUMP * dump database to specified ### grunt.registerMultiTask 'db_dump', 'Dump database', -> # Get tasks options + set default port options = @options pass: "" port: 3306 backup_to: "db/backups/<%= grunt.template.today('yyyy-mm-dd') %> - <%= target %>.sql" paths = generate_backup_paths(@target, options) grunt.log.subhead "Dumping database '#{options.title}' to '#{paths.file}'" if db_dump(options, paths) grunt.log.success "Database dump succesfully exported" return true else grunt.log.fail "Database dump failed!" return false # db_import grunt.registerMultiTask 'db_import', 'Import database', -> # Get tasks options + set default port options = @options pass: "" port: 3306 backup_to: "db/backups/<%= grunt.template.today('yyyy-mm-dd') %> - <%= target %>.sql" paths = generate_backup_paths this.target, options grunt.log.subhead "Importing database '#{options.title}' to '#{paths.file}'" if db_import options, paths grunt.log.success "Database dump succesfully imported" else grunt.log.fail "Database import failed!" false generate_backup_paths = (target, options) -> paths = {} paths.file = grunt.template.process(options.backup_to, { data: target: target }) paths.dir = path.dirname paths.file paths add_untemplated_properties_to_command = (command, options) -> additional_properties = [] default_option_keys = ["user", "pass", "database", "host", "port", "ssh_host", "backup_to", "title"] #-- Find the additional option keys not part of the default list additional_options_keys = _.reject _.keys(options), (option) -> _.contains(default_option_keys, option) #-- For each additional option key, add it's key + value to the # additional_properties object array _.each additional_options_keys, (key) -> value = options[key] #-- Modify socket parameter to be --socket key = "--socket" if key is "socket" if value is "" additional_properties.push key else additional_properties.push key + " \"" + value + "\"" #-- Add the properties to the command if additional_properties.length isnt 0 command += " " + additional_properties.join " " command ### * Dumps a MYSQL database to a suitable backup location ### db_dump = (options, paths) -> grunt.file.mkdir paths.dir tpl_mysqldump = grunt.template.process commandTemplates.mysqldump, data: user: options.user pass: if options.pass isnt "" then '-p' + options.pass else '' database: options.database host: options.host port: options.port # Test whether we should connect via SSH first if not options.ssh_host? # it's a local/direct connection cmd = tpl_mysqldump else # it's a remote connection tpl_ssh = grunt.template.process commandTemplates.ssh, data: host: options.ssh_host cmd = tpl_ssh + " \\ " + tpl_mysqldump cmd = add_untemplated_properties_to_command cmd, options #-- Write command if being verbose grunt.verbose.writeln "Command: " + chalk.cyan(cmd) # Capture output... ret = shell.exec cmd, {silent: true} if ret.code isnt 0 grunt.log.error ret.output return false # Write output to file using native Grunt methods grunt.file.write paths.file, ret.output return true ### * Import a MYSQL database from a file * * @author: Justin Anastos <janastos@useallfive.com> ### db_import = (options, paths) -> tpl_mysql = grunt.template.process commandTemplates.mysql, data: user: options.user pass: if options.pass isnt "" then '-p' + options.pass else '' host: options.host port: options.port backup_to: options.backup_to # Test whether we should connect via SSH first if not options.ssh_host? # it's a local/direct connection cmd = tpl_mysql else # it's a remote connection tpl_ssh = grunt.template.process commandTemplates.ssh, data: host: options.ssh_host cmd = tpl_ssh + " \\ " + tpl_mysql cmd = add_untemplated_properties_to_command cmd, options #-- Write command if being verbose grunt.verbose.writeln "Command: " + chalk.cyan(cmd) # Capture output... ret = shell.exec cmd, {silent: true} if(ret.code != 0) grunt.log.error ret.output return false true
52550
### * grunt-mysql-dump * https:#github.com/digitalcuisine/grunt-mysql-dump * * Copyright (c) 2013 <NAME>, Digital Cuisine * Licensed under the MIT license. ### # Dependencies chalk = require 'chalk' shell = require 'shelljs' path = require 'path' _ = require 'lodash' ### * Lo-Dash Template Helpers * http:#lodash.com/docs/#template * https:#github.com/gruntjs/grunt/wiki/grunt.template ### commandTemplates = mysqldump: "mysqldump -h <%= host %> -P <%= port %> -u<%= user %> <%= pass %> --databases <%= database %>", mysql: 'mysql -h <%= host %> -P <%= port %> -u<%= user %> <%= pass %> < "<%= backup_to %>"', ssh: "ssh <%= host %>" module.exports = (grunt) -> ### DB DUMP * dump database to specified ### grunt.registerMultiTask 'db_dump', 'Dump database', -> # Get tasks options + set default port options = @options pass: "" port: 3306 backup_to: "db/backups/<%= grunt.template.today('yyyy-mm-dd') %> - <%= target %>.sql" paths = generate_backup_paths(@target, options) grunt.log.subhead "Dumping database '#{options.title}' to '#{paths.file}'" if db_dump(options, paths) grunt.log.success "Database dump succesfully exported" return true else grunt.log.fail "Database dump failed!" return false # db_import grunt.registerMultiTask 'db_import', 'Import database', -> # Get tasks options + set default port options = @options pass: "" port: 3306 backup_to: "db/backups/<%= grunt.template.today('yyyy-mm-dd') %> - <%= target %>.sql" paths = generate_backup_paths this.target, options grunt.log.subhead "Importing database '#{options.title}' to '#{paths.file}'" if db_import options, paths grunt.log.success "Database dump succesfully imported" else grunt.log.fail "Database import failed!" false generate_backup_paths = (target, options) -> paths = {} paths.file = grunt.template.process(options.backup_to, { data: target: target }) paths.dir = path.dirname paths.file paths add_untemplated_properties_to_command = (command, options) -> additional_properties = [] default_option_keys = ["user<KEY>, "pass", "database", "host", "port", "ssh_host", "backup_to", "title"] #-- Find the additional option keys not part of the default list additional_options_keys = _.reject _.keys(options), (option) -> _.contains(default_option_keys, option) #-- For each additional option key, add it's key + value to the # additional_properties object array _.each additional_options_keys, (key) -> value = options[key] #-- Modify socket parameter to be --socket key = <KEY>" if key is "<KEY>" if value is "" additional_properties.push key else additional_properties.push key + " \"" + value + "\"" #-- Add the properties to the command if additional_properties.length isnt 0 command += " " + additional_properties.join " " command ### * Dumps a MYSQL database to a suitable backup location ### db_dump = (options, paths) -> grunt.file.mkdir paths.dir tpl_mysqldump = grunt.template.process commandTemplates.mysqldump, data: user: options.user pass: if options.pass isnt "" then '-p' + options.pass else '' database: options.database host: options.host port: options.port # Test whether we should connect via SSH first if not options.ssh_host? # it's a local/direct connection cmd = tpl_mysqldump else # it's a remote connection tpl_ssh = grunt.template.process commandTemplates.ssh, data: host: options.ssh_host cmd = tpl_ssh + " \\ " + tpl_mysqldump cmd = add_untemplated_properties_to_command cmd, options #-- Write command if being verbose grunt.verbose.writeln "Command: " + chalk.cyan(cmd) # Capture output... ret = shell.exec cmd, {silent: true} if ret.code isnt 0 grunt.log.error ret.output return false # Write output to file using native Grunt methods grunt.file.write paths.file, ret.output return true ### * Import a MYSQL database from a file * * @author: <NAME> <<EMAIL>> ### db_import = (options, paths) -> tpl_mysql = grunt.template.process commandTemplates.mysql, data: user: options.user pass: if options.pass isnt "" then <PASSWORD>' + options.pass else '' host: options.host port: options.port backup_to: options.backup_to # Test whether we should connect via SSH first if not options.ssh_host? # it's a local/direct connection cmd = tpl_mysql else # it's a remote connection tpl_ssh = grunt.template.process commandTemplates.ssh, data: host: options.ssh_host cmd = tpl_ssh + " \\ " + tpl_mysql cmd = add_untemplated_properties_to_command cmd, options #-- Write command if being verbose grunt.verbose.writeln "Command: " + chalk.cyan(cmd) # Capture output... ret = shell.exec cmd, {silent: true} if(ret.code != 0) grunt.log.error ret.output return false true
true
### * grunt-mysql-dump * https:#github.com/digitalcuisine/grunt-mysql-dump * * Copyright (c) 2013 PI:NAME:<NAME>END_PI, Digital Cuisine * Licensed under the MIT license. ### # Dependencies chalk = require 'chalk' shell = require 'shelljs' path = require 'path' _ = require 'lodash' ### * Lo-Dash Template Helpers * http:#lodash.com/docs/#template * https:#github.com/gruntjs/grunt/wiki/grunt.template ### commandTemplates = mysqldump: "mysqldump -h <%= host %> -P <%= port %> -u<%= user %> <%= pass %> --databases <%= database %>", mysql: 'mysql -h <%= host %> -P <%= port %> -u<%= user %> <%= pass %> < "<%= backup_to %>"', ssh: "ssh <%= host %>" module.exports = (grunt) -> ### DB DUMP * dump database to specified ### grunt.registerMultiTask 'db_dump', 'Dump database', -> # Get tasks options + set default port options = @options pass: "" port: 3306 backup_to: "db/backups/<%= grunt.template.today('yyyy-mm-dd') %> - <%= target %>.sql" paths = generate_backup_paths(@target, options) grunt.log.subhead "Dumping database '#{options.title}' to '#{paths.file}'" if db_dump(options, paths) grunt.log.success "Database dump succesfully exported" return true else grunt.log.fail "Database dump failed!" return false # db_import grunt.registerMultiTask 'db_import', 'Import database', -> # Get tasks options + set default port options = @options pass: "" port: 3306 backup_to: "db/backups/<%= grunt.template.today('yyyy-mm-dd') %> - <%= target %>.sql" paths = generate_backup_paths this.target, options grunt.log.subhead "Importing database '#{options.title}' to '#{paths.file}'" if db_import options, paths grunt.log.success "Database dump succesfully imported" else grunt.log.fail "Database import failed!" false generate_backup_paths = (target, options) -> paths = {} paths.file = grunt.template.process(options.backup_to, { data: target: target }) paths.dir = path.dirname paths.file paths add_untemplated_properties_to_command = (command, options) -> additional_properties = [] default_option_keys = ["userPI:KEY:<KEY>END_PI, "pass", "database", "host", "port", "ssh_host", "backup_to", "title"] #-- Find the additional option keys not part of the default list additional_options_keys = _.reject _.keys(options), (option) -> _.contains(default_option_keys, option) #-- For each additional option key, add it's key + value to the # additional_properties object array _.each additional_options_keys, (key) -> value = options[key] #-- Modify socket parameter to be --socket key = PI:KEY:<KEY>END_PI" if key is "PI:KEY:<KEY>END_PI" if value is "" additional_properties.push key else additional_properties.push key + " \"" + value + "\"" #-- Add the properties to the command if additional_properties.length isnt 0 command += " " + additional_properties.join " " command ### * Dumps a MYSQL database to a suitable backup location ### db_dump = (options, paths) -> grunt.file.mkdir paths.dir tpl_mysqldump = grunt.template.process commandTemplates.mysqldump, data: user: options.user pass: if options.pass isnt "" then '-p' + options.pass else '' database: options.database host: options.host port: options.port # Test whether we should connect via SSH first if not options.ssh_host? # it's a local/direct connection cmd = tpl_mysqldump else # it's a remote connection tpl_ssh = grunt.template.process commandTemplates.ssh, data: host: options.ssh_host cmd = tpl_ssh + " \\ " + tpl_mysqldump cmd = add_untemplated_properties_to_command cmd, options #-- Write command if being verbose grunt.verbose.writeln "Command: " + chalk.cyan(cmd) # Capture output... ret = shell.exec cmd, {silent: true} if ret.code isnt 0 grunt.log.error ret.output return false # Write output to file using native Grunt methods grunt.file.write paths.file, ret.output return true ### * Import a MYSQL database from a file * * @author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### db_import = (options, paths) -> tpl_mysql = grunt.template.process commandTemplates.mysql, data: user: options.user pass: if options.pass isnt "" then PI:PASSWORD:<PASSWORD>END_PI' + options.pass else '' host: options.host port: options.port backup_to: options.backup_to # Test whether we should connect via SSH first if not options.ssh_host? # it's a local/direct connection cmd = tpl_mysql else # it's a remote connection tpl_ssh = grunt.template.process commandTemplates.ssh, data: host: options.ssh_host cmd = tpl_ssh + " \\ " + tpl_mysql cmd = add_untemplated_properties_to_command cmd, options #-- Write command if being verbose grunt.verbose.writeln "Command: " + chalk.cyan(cmd) # Capture output... ret = shell.exec cmd, {silent: true} if(ret.code != 0) grunt.log.error ret.output return false true
[ { "context": "describe 'Destructive malefic testing', ->\n key = '@_$vp€R~k3y'\n auth = null\n\n describe 'bad formed .authrc fi", "end": 125, "score": 0.9996210336685181, "start": 113, "tag": "KEY", "value": "'@_$vp€R~k3y" } ]
test/destructiveSpec.coffee
h2non/node-authrc
1
{ expect } = require 'chai' Authrc = require '../lib/authrc' describe 'Destructive malefic testing', -> key = '@_$vp€R~k3y' auth = null describe 'bad formed .authrc file', -> describe 'bad formed host regular expression', -> it 'should not throw an exception while read the file', -> expect(-> auth = new Authrc('test/fixtures/bad_formed/.authrc') ).to.not.throw describe 'host matching', -> before -> auth = new Authrc('test/fixtures/bad_formed/.authrc') it 'should be an valid file with contents', -> expect(auth.exists()).to.be.true it 'should host to be invalid regex', -> expect(auth.host('my.server.org').valid()).to.be.false it 'should return an empty username', -> expect(auth.host('my.server.org').user()).to.be.null it 'should return an empty password', -> expect(auth.host('my.server.org').password()).to.be.null it 'should return an empty auth object', -> expect(auth.host('my.server.org').auth()).to.be.null describe 'bad formed JSON', -> it 'should throw a sintax Error exception', -> expect(-> new Authrc('test/fixtures/bad_formed/json/.authrc')).to.be.throw(Error) describe 'empty .authrc file', -> it 'should not throw an exception', -> expect(-> new Authrc('test/fixtures/empty/.authrc') ).to.not.throw it 'should not exists', -> expect(new Authrc('test/fixtures/empty/.authrc').exists()).to.be.false describe 'error on password decryption', -> beforeEach -> auth = new Authrc('test/fixtures/bad_encrypted/.authrc') describe 'bad cipher for the encrypted password', -> it 'should be an encrypted password', -> expect(auth.host('bad.cipher.org').encrypted()).to.be.true it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.cipher.org').descrypt(key) ).to.be.throw(Error) describe 'bad encrypted password value', -> it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.encryption.org').descrypt(key) ).to.be.throw(Error) it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.encryption.org/idea').descrypt(key) ).to.be.throw(Error) describe 'non supported cipher', -> it 'should throw a sintax Error exception', -> expect(-> auth.host('non.existant.org').descrypt(key) ).to.be.throw(Error) it 'should throw a sintax Error exception', -> expect(-> auth.host('non.existant.org/bad-encrypted').descrypt(key) ).to.be.throw(Error) describe 'bad authtentication types values', -> beforeEach -> auth = new Authrc('test/fixtures/bad_auth/') describe 'invalid username', -> it 'should not be a valid auth config', -> expect(auth.host('bad.username.org').exists()).to.be.true expect(auth.host('bad.username.org').valid()).to.be.false describe 'invalid both username and password values', -> it 'should not be a valid auth config', -> expect(auth.host('bad.auth.org').exists()).to.be.true expect(auth.host('bad.auth.org').valid()).to.be.false # more malefic test cases in process...
173778
{ expect } = require 'chai' Authrc = require '../lib/authrc' describe 'Destructive malefic testing', -> key = <KEY>' auth = null describe 'bad formed .authrc file', -> describe 'bad formed host regular expression', -> it 'should not throw an exception while read the file', -> expect(-> auth = new Authrc('test/fixtures/bad_formed/.authrc') ).to.not.throw describe 'host matching', -> before -> auth = new Authrc('test/fixtures/bad_formed/.authrc') it 'should be an valid file with contents', -> expect(auth.exists()).to.be.true it 'should host to be invalid regex', -> expect(auth.host('my.server.org').valid()).to.be.false it 'should return an empty username', -> expect(auth.host('my.server.org').user()).to.be.null it 'should return an empty password', -> expect(auth.host('my.server.org').password()).to.be.null it 'should return an empty auth object', -> expect(auth.host('my.server.org').auth()).to.be.null describe 'bad formed JSON', -> it 'should throw a sintax Error exception', -> expect(-> new Authrc('test/fixtures/bad_formed/json/.authrc')).to.be.throw(Error) describe 'empty .authrc file', -> it 'should not throw an exception', -> expect(-> new Authrc('test/fixtures/empty/.authrc') ).to.not.throw it 'should not exists', -> expect(new Authrc('test/fixtures/empty/.authrc').exists()).to.be.false describe 'error on password decryption', -> beforeEach -> auth = new Authrc('test/fixtures/bad_encrypted/.authrc') describe 'bad cipher for the encrypted password', -> it 'should be an encrypted password', -> expect(auth.host('bad.cipher.org').encrypted()).to.be.true it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.cipher.org').descrypt(key) ).to.be.throw(Error) describe 'bad encrypted password value', -> it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.encryption.org').descrypt(key) ).to.be.throw(Error) it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.encryption.org/idea').descrypt(key) ).to.be.throw(Error) describe 'non supported cipher', -> it 'should throw a sintax Error exception', -> expect(-> auth.host('non.existant.org').descrypt(key) ).to.be.throw(Error) it 'should throw a sintax Error exception', -> expect(-> auth.host('non.existant.org/bad-encrypted').descrypt(key) ).to.be.throw(Error) describe 'bad authtentication types values', -> beforeEach -> auth = new Authrc('test/fixtures/bad_auth/') describe 'invalid username', -> it 'should not be a valid auth config', -> expect(auth.host('bad.username.org').exists()).to.be.true expect(auth.host('bad.username.org').valid()).to.be.false describe 'invalid both username and password values', -> it 'should not be a valid auth config', -> expect(auth.host('bad.auth.org').exists()).to.be.true expect(auth.host('bad.auth.org').valid()).to.be.false # more malefic test cases in process...
true
{ expect } = require 'chai' Authrc = require '../lib/authrc' describe 'Destructive malefic testing', -> key = PI:KEY:<KEY>END_PI' auth = null describe 'bad formed .authrc file', -> describe 'bad formed host regular expression', -> it 'should not throw an exception while read the file', -> expect(-> auth = new Authrc('test/fixtures/bad_formed/.authrc') ).to.not.throw describe 'host matching', -> before -> auth = new Authrc('test/fixtures/bad_formed/.authrc') it 'should be an valid file with contents', -> expect(auth.exists()).to.be.true it 'should host to be invalid regex', -> expect(auth.host('my.server.org').valid()).to.be.false it 'should return an empty username', -> expect(auth.host('my.server.org').user()).to.be.null it 'should return an empty password', -> expect(auth.host('my.server.org').password()).to.be.null it 'should return an empty auth object', -> expect(auth.host('my.server.org').auth()).to.be.null describe 'bad formed JSON', -> it 'should throw a sintax Error exception', -> expect(-> new Authrc('test/fixtures/bad_formed/json/.authrc')).to.be.throw(Error) describe 'empty .authrc file', -> it 'should not throw an exception', -> expect(-> new Authrc('test/fixtures/empty/.authrc') ).to.not.throw it 'should not exists', -> expect(new Authrc('test/fixtures/empty/.authrc').exists()).to.be.false describe 'error on password decryption', -> beforeEach -> auth = new Authrc('test/fixtures/bad_encrypted/.authrc') describe 'bad cipher for the encrypted password', -> it 'should be an encrypted password', -> expect(auth.host('bad.cipher.org').encrypted()).to.be.true it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.cipher.org').descrypt(key) ).to.be.throw(Error) describe 'bad encrypted password value', -> it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.encryption.org').descrypt(key) ).to.be.throw(Error) it 'should throw a sintax Error exception', -> expect(-> auth.host('bad.encryption.org/idea').descrypt(key) ).to.be.throw(Error) describe 'non supported cipher', -> it 'should throw a sintax Error exception', -> expect(-> auth.host('non.existant.org').descrypt(key) ).to.be.throw(Error) it 'should throw a sintax Error exception', -> expect(-> auth.host('non.existant.org/bad-encrypted').descrypt(key) ).to.be.throw(Error) describe 'bad authtentication types values', -> beforeEach -> auth = new Authrc('test/fixtures/bad_auth/') describe 'invalid username', -> it 'should not be a valid auth config', -> expect(auth.host('bad.username.org').exists()).to.be.true expect(auth.host('bad.username.org').valid()).to.be.false describe 'invalid both username and password values', -> it 'should not be a valid auth config', -> expect(auth.host('bad.auth.org').exists()).to.be.true expect(auth.host('bad.auth.org').valid()).to.be.false # more malefic test cases in process...
[ { "context": "object', ->\n\t\t\tapps = {\n\t\t\t\t'1234': {\n\t\t\t\t\tname: 'something'\n\t\t\t\t\treleaseId: 123\n\t\t\t\t\tcommit: 'bar'\n\t\t\t\t\tserv", "end": 3949, "score": 0.978777289390564, "start": 3940, "tag": "NAME", "value": "something" }, { "context": "onment', ->\n\t\...
test/07-validation.spec.coffee
XevoInc/balena-supervisor
0
_ = require 'lodash' { expect } = require './lib/chai-config' validation = require '../src/lib/validation' almostTooLongText = _.map([0...255], -> 'a').join('') describe 'validation', -> describe 'checkTruthy', -> it 'returns true for a truthy value', -> expect(validation.checkTruthy(true)).to.equal(true) expect(validation.checkTruthy('true')).to.equal(true) expect(validation.checkTruthy('1')).to.equal(true) expect(validation.checkTruthy(1)).to.equal(true) expect(validation.checkTruthy('on')).to.equal(true) it 'returns false for a falsy value', -> expect(validation.checkTruthy(false)).to.equal(false) expect(validation.checkTruthy('false')).to.equal(false) expect(validation.checkTruthy('0')).to.equal(false) expect(validation.checkTruthy(0)).to.equal(false) expect(validation.checkTruthy('off')).to.equal(false) it 'returns undefined for invalid values', -> expect(validation.checkTruthy({})).to.be.undefined expect(validation.checkTruthy(10)).to.be.undefined expect(validation.checkTruthy('on1')).to.be.undefined expect(validation.checkTruthy('foo')).to.be.undefined expect(validation.checkTruthy(undefined)).to.be.undefined expect(validation.checkTruthy(null)).to.be.undefined expect(validation.checkTruthy('')).to.be.undefined describe 'checkString', -> it 'validates a string', -> expect(validation.checkString('foo')).to.equal('foo') expect(validation.checkString('bar')).to.equal('bar') it 'returns undefined for empty strings or strings that equal null or undefined', -> expect(validation.checkString('')).to.be.undefined expect(validation.checkString('null')).to.be.undefined expect(validation.checkString('undefined')).to.be.undefined it 'returns undefined for things that are not strings', -> expect(validation.checkString({})).to.be.undefined expect(validation.checkString([])).to.be.undefined expect(validation.checkString(123)).to.be.undefined expect(validation.checkString(0)).to.be.undefined expect(validation.checkString(null)).to.be.undefined expect(validation.checkString(undefined)).to.be.undefined describe 'checkInt', -> it 'returns an integer for a string that can be parsed as one', -> expect(validation.checkInt('200')).to.equal(200) expect(validation.checkInt('0')).to.equal(0) expect(validation.checkInt('-3')).to.equal(-3) it 'returns the same integer when passed an integer', -> expect(validation.checkInt(345)).to.equal(345) expect(validation.checkInt(-345)).to.equal(-345) it 'returns undefined when passed something that can\'t be parsed as int', -> expect(validation.checkInt({})).to.be.undefined expect(validation.checkInt([])).to.be.undefined expect(validation.checkInt('foo')).to.be.undefined expect(validation.checkInt(null)).to.be.undefined expect(validation.checkInt(undefined)).to.be.undefined it 'returns undefined when passed a negative or zero value and the positive option is set', -> expect(validation.checkInt('-3', positive: true)).to.be.undefined expect(validation.checkInt('0', positive: true)).to.be.undefined describe 'isValidShortText', -> it 'returns true for a short text', -> expect(validation.isValidShortText('foo')).to.equal(true) expect(validation.isValidShortText('')).to.equal(true) expect(validation.isValidShortText(almostTooLongText)).to.equal(true) it 'returns false for a text longer than 255 characters', -> expect(validation.isValidShortText(almostTooLongText + 'a')).to.equal(false) it 'returns false when passed a non-string', -> expect(validation.isValidShortText({})).to.equal(false) expect(validation.isValidShortText(1)).to.equal(false) expect(validation.isValidShortText(null)).to.equal(false) expect(validation.isValidShortText(undefined)).to.equal(false) describe 'isValidAppsObject', -> it 'returns true for a valid object', -> apps = { '1234': { name: 'something' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) it 'returns false with an invalid environment', -> apps = { '1234': { name: 'something' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: { ' baz': 'bat' } labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(false) it 'returns false with an invalid appId', -> apps = { 'boo': { name: 'something' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(false) it 'returns true with a missing releaseId', -> apps = { '1234': { name: 'something' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) it 'returns false with an invalid releaseId', -> apps = { '1234': { name: 'something' releaseId: '123a' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) describe 'isValidDependentDevicesObject', -> it 'returns true for a valid object', -> devices = {} devices[almostTooLongText] = { name: 'foo' apps: { '234': { config: { bar: 'baz' } environment: { dead: 'beef' } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(true) it 'returns false with a missing apps object', -> devices = { 'abcd1234': { name: 'foo' } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false) it 'returns false with an invalid environment', -> devices = { 'abcd1234': { name: 'foo' apps: { '234': { config: { bar: 'baz' } environment: { dead: 1 } } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false) it 'returns false if the uuid is too long', -> devices = {} devices[almostTooLongText + 'a'] = { name: 'foo' apps: { '234': { config: { bar: 'baz' } environment: { dead: 'beef' } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false)
141618
_ = require 'lodash' { expect } = require './lib/chai-config' validation = require '../src/lib/validation' almostTooLongText = _.map([0...255], -> 'a').join('') describe 'validation', -> describe 'checkTruthy', -> it 'returns true for a truthy value', -> expect(validation.checkTruthy(true)).to.equal(true) expect(validation.checkTruthy('true')).to.equal(true) expect(validation.checkTruthy('1')).to.equal(true) expect(validation.checkTruthy(1)).to.equal(true) expect(validation.checkTruthy('on')).to.equal(true) it 'returns false for a falsy value', -> expect(validation.checkTruthy(false)).to.equal(false) expect(validation.checkTruthy('false')).to.equal(false) expect(validation.checkTruthy('0')).to.equal(false) expect(validation.checkTruthy(0)).to.equal(false) expect(validation.checkTruthy('off')).to.equal(false) it 'returns undefined for invalid values', -> expect(validation.checkTruthy({})).to.be.undefined expect(validation.checkTruthy(10)).to.be.undefined expect(validation.checkTruthy('on1')).to.be.undefined expect(validation.checkTruthy('foo')).to.be.undefined expect(validation.checkTruthy(undefined)).to.be.undefined expect(validation.checkTruthy(null)).to.be.undefined expect(validation.checkTruthy('')).to.be.undefined describe 'checkString', -> it 'validates a string', -> expect(validation.checkString('foo')).to.equal('foo') expect(validation.checkString('bar')).to.equal('bar') it 'returns undefined for empty strings or strings that equal null or undefined', -> expect(validation.checkString('')).to.be.undefined expect(validation.checkString('null')).to.be.undefined expect(validation.checkString('undefined')).to.be.undefined it 'returns undefined for things that are not strings', -> expect(validation.checkString({})).to.be.undefined expect(validation.checkString([])).to.be.undefined expect(validation.checkString(123)).to.be.undefined expect(validation.checkString(0)).to.be.undefined expect(validation.checkString(null)).to.be.undefined expect(validation.checkString(undefined)).to.be.undefined describe 'checkInt', -> it 'returns an integer for a string that can be parsed as one', -> expect(validation.checkInt('200')).to.equal(200) expect(validation.checkInt('0')).to.equal(0) expect(validation.checkInt('-3')).to.equal(-3) it 'returns the same integer when passed an integer', -> expect(validation.checkInt(345)).to.equal(345) expect(validation.checkInt(-345)).to.equal(-345) it 'returns undefined when passed something that can\'t be parsed as int', -> expect(validation.checkInt({})).to.be.undefined expect(validation.checkInt([])).to.be.undefined expect(validation.checkInt('foo')).to.be.undefined expect(validation.checkInt(null)).to.be.undefined expect(validation.checkInt(undefined)).to.be.undefined it 'returns undefined when passed a negative or zero value and the positive option is set', -> expect(validation.checkInt('-3', positive: true)).to.be.undefined expect(validation.checkInt('0', positive: true)).to.be.undefined describe 'isValidShortText', -> it 'returns true for a short text', -> expect(validation.isValidShortText('foo')).to.equal(true) expect(validation.isValidShortText('')).to.equal(true) expect(validation.isValidShortText(almostTooLongText)).to.equal(true) it 'returns false for a text longer than 255 characters', -> expect(validation.isValidShortText(almostTooLongText + 'a')).to.equal(false) it 'returns false when passed a non-string', -> expect(validation.isValidShortText({})).to.equal(false) expect(validation.isValidShortText(1)).to.equal(false) expect(validation.isValidShortText(null)).to.equal(false) expect(validation.isValidShortText(undefined)).to.equal(false) describe 'isValidAppsObject', -> it 'returns true for a valid object', -> apps = { '1234': { name: '<NAME>' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) it 'returns false with an invalid environment', -> apps = { '1234': { name: '<NAME>' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: { ' baz': 'bat' } labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(false) it 'returns false with an invalid appId', -> apps = { 'boo': { name: '<NAME>' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(false) it 'returns true with a missing releaseId', -> apps = { '1234': { name: '<NAME>' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) it 'returns false with an invalid releaseId', -> apps = { '1234': { name: 'something' releaseId: '123a' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) describe 'isValidDependentDevicesObject', -> it 'returns true for a valid object', -> devices = {} devices[almostTooLongText] = { name: '<NAME>' apps: { '234': { config: { bar: 'baz' } environment: { dead: 'beef' } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(true) it 'returns false with a missing apps object', -> devices = { 'abcd1234': { name: '<NAME>' } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false) it 'returns false with an invalid environment', -> devices = { 'abcd1234': { name: '<NAME>' apps: { '234': { config: { bar: 'baz' } environment: { dead: 1 } } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false) it 'returns false if the uuid is too long', -> devices = {} devices[almostTooLongText + 'a'] = { name: '<NAME>' apps: { '234': { config: { bar: 'baz' } environment: { dead: 'beef' } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false)
true
_ = require 'lodash' { expect } = require './lib/chai-config' validation = require '../src/lib/validation' almostTooLongText = _.map([0...255], -> 'a').join('') describe 'validation', -> describe 'checkTruthy', -> it 'returns true for a truthy value', -> expect(validation.checkTruthy(true)).to.equal(true) expect(validation.checkTruthy('true')).to.equal(true) expect(validation.checkTruthy('1')).to.equal(true) expect(validation.checkTruthy(1)).to.equal(true) expect(validation.checkTruthy('on')).to.equal(true) it 'returns false for a falsy value', -> expect(validation.checkTruthy(false)).to.equal(false) expect(validation.checkTruthy('false')).to.equal(false) expect(validation.checkTruthy('0')).to.equal(false) expect(validation.checkTruthy(0)).to.equal(false) expect(validation.checkTruthy('off')).to.equal(false) it 'returns undefined for invalid values', -> expect(validation.checkTruthy({})).to.be.undefined expect(validation.checkTruthy(10)).to.be.undefined expect(validation.checkTruthy('on1')).to.be.undefined expect(validation.checkTruthy('foo')).to.be.undefined expect(validation.checkTruthy(undefined)).to.be.undefined expect(validation.checkTruthy(null)).to.be.undefined expect(validation.checkTruthy('')).to.be.undefined describe 'checkString', -> it 'validates a string', -> expect(validation.checkString('foo')).to.equal('foo') expect(validation.checkString('bar')).to.equal('bar') it 'returns undefined for empty strings or strings that equal null or undefined', -> expect(validation.checkString('')).to.be.undefined expect(validation.checkString('null')).to.be.undefined expect(validation.checkString('undefined')).to.be.undefined it 'returns undefined for things that are not strings', -> expect(validation.checkString({})).to.be.undefined expect(validation.checkString([])).to.be.undefined expect(validation.checkString(123)).to.be.undefined expect(validation.checkString(0)).to.be.undefined expect(validation.checkString(null)).to.be.undefined expect(validation.checkString(undefined)).to.be.undefined describe 'checkInt', -> it 'returns an integer for a string that can be parsed as one', -> expect(validation.checkInt('200')).to.equal(200) expect(validation.checkInt('0')).to.equal(0) expect(validation.checkInt('-3')).to.equal(-3) it 'returns the same integer when passed an integer', -> expect(validation.checkInt(345)).to.equal(345) expect(validation.checkInt(-345)).to.equal(-345) it 'returns undefined when passed something that can\'t be parsed as int', -> expect(validation.checkInt({})).to.be.undefined expect(validation.checkInt([])).to.be.undefined expect(validation.checkInt('foo')).to.be.undefined expect(validation.checkInt(null)).to.be.undefined expect(validation.checkInt(undefined)).to.be.undefined it 'returns undefined when passed a negative or zero value and the positive option is set', -> expect(validation.checkInt('-3', positive: true)).to.be.undefined expect(validation.checkInt('0', positive: true)).to.be.undefined describe 'isValidShortText', -> it 'returns true for a short text', -> expect(validation.isValidShortText('foo')).to.equal(true) expect(validation.isValidShortText('')).to.equal(true) expect(validation.isValidShortText(almostTooLongText)).to.equal(true) it 'returns false for a text longer than 255 characters', -> expect(validation.isValidShortText(almostTooLongText + 'a')).to.equal(false) it 'returns false when passed a non-string', -> expect(validation.isValidShortText({})).to.equal(false) expect(validation.isValidShortText(1)).to.equal(false) expect(validation.isValidShortText(null)).to.equal(false) expect(validation.isValidShortText(undefined)).to.equal(false) describe 'isValidAppsObject', -> it 'returns true for a valid object', -> apps = { '1234': { name: 'PI:NAME:<NAME>END_PI' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) it 'returns false with an invalid environment', -> apps = { '1234': { name: 'PI:NAME:<NAME>END_PI' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: { ' baz': 'bat' } labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(false) it 'returns false with an invalid appId', -> apps = { 'boo': { name: 'PI:NAME:<NAME>END_PI' releaseId: 123 commit: 'bar' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(false) it 'returns true with a missing releaseId', -> apps = { '1234': { name: 'PI:NAME:<NAME>END_PI' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) it 'returns false with an invalid releaseId', -> apps = { '1234': { name: 'something' releaseId: '123a' services: { '45': { serviceName: 'bazbaz' imageId: 34 image: 'foo' environment: {} labels: {} } } } } expect(validation.isValidAppsObject(apps)).to.equal(true) describe 'isValidDependentDevicesObject', -> it 'returns true for a valid object', -> devices = {} devices[almostTooLongText] = { name: 'PI:NAME:<NAME>END_PI' apps: { '234': { config: { bar: 'baz' } environment: { dead: 'beef' } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(true) it 'returns false with a missing apps object', -> devices = { 'abcd1234': { name: 'PI:NAME:<NAME>END_PI' } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false) it 'returns false with an invalid environment', -> devices = { 'abcd1234': { name: 'PI:NAME:<NAME>END_PI' apps: { '234': { config: { bar: 'baz' } environment: { dead: 1 } } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false) it 'returns false if the uuid is too long', -> devices = {} devices[almostTooLongText + 'a'] = { name: 'PI:NAME:<NAME>END_PI' apps: { '234': { config: { bar: 'baz' } environment: { dead: 'beef' } } } } expect(validation.isValidDependentDevicesObject(devices)).to.equal(false)
[ { "context": "\ttransport.sendMail\n\t\t\t\t\tfrom: 'Knownodes System <system@knownodes.com>',\n\t\t\t\t\tto: user.email,\n\t\t\t\t\tsubject: emailSubjec", "end": 637, "score": 0.9999247193336487, "start": 617, "tag": "EMAIL", "value": "system@knownodes.com" } ]
modules/email/eMail.coffee
CyberCRI/KnowNodes
5
emailTemplates = require('email-templates') path = require('path') templatesDir = path.resolve(__dirname, 'templates') nodemailer = require('nodemailer') emailConf = require('../../config/email.conf.js') exports.sendTemplateEmailToUser = (chosenTemplate, emailSubject, user, callback) -> emailTemplates(templatesDir, (err, template) -> return console.log(err) if (err) transport = nodemailer.createTransport "SMTP", emailConf.getEmailConfiguration template chosenTemplate, user, (err, html, text) -> return console.log err if err transport.sendMail from: 'Knownodes System <system@knownodes.com>', to: user.email, subject: emailSubject, html: html, # generateTextFromHTML: true, text: text, (err, responseStatus) -> if (err) console.log(err) return callback(err) else console.log responseStatus.message return callback null, responseStatus.message )
188568
emailTemplates = require('email-templates') path = require('path') templatesDir = path.resolve(__dirname, 'templates') nodemailer = require('nodemailer') emailConf = require('../../config/email.conf.js') exports.sendTemplateEmailToUser = (chosenTemplate, emailSubject, user, callback) -> emailTemplates(templatesDir, (err, template) -> return console.log(err) if (err) transport = nodemailer.createTransport "SMTP", emailConf.getEmailConfiguration template chosenTemplate, user, (err, html, text) -> return console.log err if err transport.sendMail from: 'Knownodes System <<EMAIL>>', to: user.email, subject: emailSubject, html: html, # generateTextFromHTML: true, text: text, (err, responseStatus) -> if (err) console.log(err) return callback(err) else console.log responseStatus.message return callback null, responseStatus.message )
true
emailTemplates = require('email-templates') path = require('path') templatesDir = path.resolve(__dirname, 'templates') nodemailer = require('nodemailer') emailConf = require('../../config/email.conf.js') exports.sendTemplateEmailToUser = (chosenTemplate, emailSubject, user, callback) -> emailTemplates(templatesDir, (err, template) -> return console.log(err) if (err) transport = nodemailer.createTransport "SMTP", emailConf.getEmailConfiguration template chosenTemplate, user, (err, html, text) -> return console.log err if err transport.sendMail from: 'Knownodes System <PI:EMAIL:<EMAIL>END_PI>', to: user.email, subject: emailSubject, html: html, # generateTextFromHTML: true, text: text, (err, responseStatus) -> if (err) console.log(err) return callback(err) else console.log responseStatus.message return callback null, responseStatus.message )
[ { "context": "ontents = new String contents\n options.Name = 'Comment'\n options.color ?= [243, 223, 92]\n @annotat", "end": 740, "score": 0.9970726370811462, "start": 733, "tag": "NAME", "value": "Comment" } ]
lib/mixins/annotations.coffee
sureshamk/pdfkit
2
module.exports = annotate: (x, y, w, h, options) -> options.Type = 'Annot' options.Rect = @_convertRect x, y, w, h options.Border = [0, 0, 0] options.C ?= @_normalizeColor(options.color or [0, 0, 0]) unless options.Subtype is 'Link' # convert colors delete options.color if typeof options.Dest is 'string' options.Dest = new String options.Dest # Capitalize keys for key, val of options options[key[0].toUpperCase() + key.slice(1)] = val ref = @ref options @page.annotations.push ref ref.end() return this note: (x, y, w, h, contents, options = {}) -> options.Subtype = 'Text' options.Contents = new String contents options.Name = 'Comment' options.color ?= [243, 223, 92] @annotate x, y, w, h, options link: (x, y, w, h, url, options = {}) -> options.Subtype = 'Link' if typeof url is 'number' # Link to a page in the document (the page must already exist) pages = @_root.data.Pages.data if url >= 0 and url < pages.Kids.length options.A = @ref S: 'GoTo' D: [pages.Kids[url], 'XYZ', null, null, null] options.A.end() else throw new Error "The document has no page #{url}" else # Link to an external url options.A = @ref S: 'URI' URI: new String url options.A.end() @annotate x, y, w, h, options _markup: (x, y, w, h, options = {}) -> [x1, y1, x2, y2] = @_convertRect x, y, w, h options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1] options.Contents = new String @annotate x, y, w, h, options highlight: (x, y, w, h, options = {}) -> options.Subtype = 'Highlight' options.color ?= [241, 238, 148] @_markup x, y, w, h, options underline: (x, y, w, h, options = {}) -> options.Subtype = 'Underline' @_markup x, y, w, h, options strike: (x, y, w, h, options = {}) -> options.Subtype = 'StrikeOut' @_markup x, y, w, h, options lineAnnotation: (x1, y1, x2, y2, options = {}) -> options.Subtype = 'Line' options.Contents = new String options.L = [x1, @page.height - y1, x2, @page.height - y2] @annotate x1, y1, x2, y2, options rectAnnotation: (x, y, w, h, options = {}) -> options.Subtype = 'Square' options.Contents = new String @annotate x, y, w, h, options ellipseAnnotation: (x, y, w, h, options = {}) -> options.Subtype = 'Circle' options.Contents = new String @annotate x, y, w, h, options textAnnotation: (x, y, w, h, text, options = {}) -> options.Subtype = 'FreeText' options.Contents = new String text options.DA = new String @annotate x, y, w, h, options _convertRect: (x1, y1, w, h) -> # flip y1 and y2 y2 = y1 y1 += h # make x2 x2 = x1 + w # apply current transformation matrix to points [m0, m1, m2, m3, m4, m5] = @_ctm x1 = m0 * x1 + m2 * y1 + m4 y1 = m1 * x1 + m3 * y1 + m5 x2 = m0 * x2 + m2 * y2 + m4 y2 = m1 * x2 + m3 * y2 + m5 return [x1, y1, x2, y2]
51057
module.exports = annotate: (x, y, w, h, options) -> options.Type = 'Annot' options.Rect = @_convertRect x, y, w, h options.Border = [0, 0, 0] options.C ?= @_normalizeColor(options.color or [0, 0, 0]) unless options.Subtype is 'Link' # convert colors delete options.color if typeof options.Dest is 'string' options.Dest = new String options.Dest # Capitalize keys for key, val of options options[key[0].toUpperCase() + key.slice(1)] = val ref = @ref options @page.annotations.push ref ref.end() return this note: (x, y, w, h, contents, options = {}) -> options.Subtype = 'Text' options.Contents = new String contents options.Name = '<NAME>' options.color ?= [243, 223, 92] @annotate x, y, w, h, options link: (x, y, w, h, url, options = {}) -> options.Subtype = 'Link' if typeof url is 'number' # Link to a page in the document (the page must already exist) pages = @_root.data.Pages.data if url >= 0 and url < pages.Kids.length options.A = @ref S: 'GoTo' D: [pages.Kids[url], 'XYZ', null, null, null] options.A.end() else throw new Error "The document has no page #{url}" else # Link to an external url options.A = @ref S: 'URI' URI: new String url options.A.end() @annotate x, y, w, h, options _markup: (x, y, w, h, options = {}) -> [x1, y1, x2, y2] = @_convertRect x, y, w, h options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1] options.Contents = new String @annotate x, y, w, h, options highlight: (x, y, w, h, options = {}) -> options.Subtype = 'Highlight' options.color ?= [241, 238, 148] @_markup x, y, w, h, options underline: (x, y, w, h, options = {}) -> options.Subtype = 'Underline' @_markup x, y, w, h, options strike: (x, y, w, h, options = {}) -> options.Subtype = 'StrikeOut' @_markup x, y, w, h, options lineAnnotation: (x1, y1, x2, y2, options = {}) -> options.Subtype = 'Line' options.Contents = new String options.L = [x1, @page.height - y1, x2, @page.height - y2] @annotate x1, y1, x2, y2, options rectAnnotation: (x, y, w, h, options = {}) -> options.Subtype = 'Square' options.Contents = new String @annotate x, y, w, h, options ellipseAnnotation: (x, y, w, h, options = {}) -> options.Subtype = 'Circle' options.Contents = new String @annotate x, y, w, h, options textAnnotation: (x, y, w, h, text, options = {}) -> options.Subtype = 'FreeText' options.Contents = new String text options.DA = new String @annotate x, y, w, h, options _convertRect: (x1, y1, w, h) -> # flip y1 and y2 y2 = y1 y1 += h # make x2 x2 = x1 + w # apply current transformation matrix to points [m0, m1, m2, m3, m4, m5] = @_ctm x1 = m0 * x1 + m2 * y1 + m4 y1 = m1 * x1 + m3 * y1 + m5 x2 = m0 * x2 + m2 * y2 + m4 y2 = m1 * x2 + m3 * y2 + m5 return [x1, y1, x2, y2]
true
module.exports = annotate: (x, y, w, h, options) -> options.Type = 'Annot' options.Rect = @_convertRect x, y, w, h options.Border = [0, 0, 0] options.C ?= @_normalizeColor(options.color or [0, 0, 0]) unless options.Subtype is 'Link' # convert colors delete options.color if typeof options.Dest is 'string' options.Dest = new String options.Dest # Capitalize keys for key, val of options options[key[0].toUpperCase() + key.slice(1)] = val ref = @ref options @page.annotations.push ref ref.end() return this note: (x, y, w, h, contents, options = {}) -> options.Subtype = 'Text' options.Contents = new String contents options.Name = 'PI:NAME:<NAME>END_PI' options.color ?= [243, 223, 92] @annotate x, y, w, h, options link: (x, y, w, h, url, options = {}) -> options.Subtype = 'Link' if typeof url is 'number' # Link to a page in the document (the page must already exist) pages = @_root.data.Pages.data if url >= 0 and url < pages.Kids.length options.A = @ref S: 'GoTo' D: [pages.Kids[url], 'XYZ', null, null, null] options.A.end() else throw new Error "The document has no page #{url}" else # Link to an external url options.A = @ref S: 'URI' URI: new String url options.A.end() @annotate x, y, w, h, options _markup: (x, y, w, h, options = {}) -> [x1, y1, x2, y2] = @_convertRect x, y, w, h options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1] options.Contents = new String @annotate x, y, w, h, options highlight: (x, y, w, h, options = {}) -> options.Subtype = 'Highlight' options.color ?= [241, 238, 148] @_markup x, y, w, h, options underline: (x, y, w, h, options = {}) -> options.Subtype = 'Underline' @_markup x, y, w, h, options strike: (x, y, w, h, options = {}) -> options.Subtype = 'StrikeOut' @_markup x, y, w, h, options lineAnnotation: (x1, y1, x2, y2, options = {}) -> options.Subtype = 'Line' options.Contents = new String options.L = [x1, @page.height - y1, x2, @page.height - y2] @annotate x1, y1, x2, y2, options rectAnnotation: (x, y, w, h, options = {}) -> options.Subtype = 'Square' options.Contents = new String @annotate x, y, w, h, options ellipseAnnotation: (x, y, w, h, options = {}) -> options.Subtype = 'Circle' options.Contents = new String @annotate x, y, w, h, options textAnnotation: (x, y, w, h, text, options = {}) -> options.Subtype = 'FreeText' options.Contents = new String text options.DA = new String @annotate x, y, w, h, options _convertRect: (x1, y1, w, h) -> # flip y1 and y2 y2 = y1 y1 += h # make x2 x2 = x1 + w # apply current transformation matrix to points [m0, m1, m2, m3, m4, m5] = @_ctm x1 = m0 * x1 + m2 * y1 + m4 y1 = m1 * x1 + m3 * y1 + m5 x2 = m0 * x2 + m2 * y2 + m4 y2 = m1 * x2 + m3 * y2 + m5 return [x1, y1, x2, y2]
[ { "context": " schemas.users.update\n username : user.username\n ,\n status : 'ACTIVE'\n ", "end": 762, "score": 0.9979378581047058, "start": 749, "tag": "USERNAME", "value": "user.username" }, { "context": " status : 'ACTIVE'\n ...
src/routes/user/passwd.coffee
rabrux/creze-api
0
randomstring = require 'randomstring' validator = require 'validator' module.exports = ( router, bcrypt, schemas, _dates ) -> router.put '/passwd', ( req, res ) -> data = req.body # bad request error if not data?.key or not data?.password return res.sendStatus 400 schemas.users.findOne key : data.key status : 'PASSWORD_RECOVERY' , ( user ) -> return res.sendStatus 404 if not user # generate password hash bcrypt.genSalt 10, ( err, salt ) -> return res.status( 500 ).send err if err bcrypt.hash data.password, salt, ( err, hash ) -> return res.status( 500 ).send err if err # save user schemas.users.update username : user.username , status : 'ACTIVE' password : hash , ( count ) -> return res.sendStatus 500 if count is 0 return res.sendStatus 200
137600
randomstring = require 'randomstring' validator = require 'validator' module.exports = ( router, bcrypt, schemas, _dates ) -> router.put '/passwd', ( req, res ) -> data = req.body # bad request error if not data?.key or not data?.password return res.sendStatus 400 schemas.users.findOne key : data.key status : 'PASSWORD_RECOVERY' , ( user ) -> return res.sendStatus 404 if not user # generate password hash bcrypt.genSalt 10, ( err, salt ) -> return res.status( 500 ).send err if err bcrypt.hash data.password, salt, ( err, hash ) -> return res.status( 500 ).send err if err # save user schemas.users.update username : user.username , status : 'ACTIVE' password : <PASSWORD> , ( count ) -> return res.sendStatus 500 if count is 0 return res.sendStatus 200
true
randomstring = require 'randomstring' validator = require 'validator' module.exports = ( router, bcrypt, schemas, _dates ) -> router.put '/passwd', ( req, res ) -> data = req.body # bad request error if not data?.key or not data?.password return res.sendStatus 400 schemas.users.findOne key : data.key status : 'PASSWORD_RECOVERY' , ( user ) -> return res.sendStatus 404 if not user # generate password hash bcrypt.genSalt 10, ( err, salt ) -> return res.status( 500 ).send err if err bcrypt.hash data.password, salt, ( err, hash ) -> return res.status( 500 ).send err if err # save user schemas.users.update username : user.username , status : 'ACTIVE' password : PI:PASSWORD:<PASSWORD>END_PI , ( count ) -> return res.sendStatus 500 if count is 0 return res.sendStatus 200
[ { "context": " account: @syno.account\n passwd: @syno.passwd\n session: session\n # Set the sy", "end": 522, "score": 0.9985548257827759, "start": 510, "tag": "PASSWORD", "value": "@syno.passwd" } ]
src/syno/Auth.coffee
leolin310148/syno
0
# Auth API class Auth extends API # API name api = 'SYNO.API.Auth' # API version version = 3 # API path path = 'auth.cgi' # Login to Syno # `done` [Function] Callback called when the login processed is complete login: (done)-> # API method is `login` method = 'login' # Use a unique session session = 'SYNO_SESSION_' + Date.now() # Init the request parameters params = account: @syno.account passwd: @syno.passwd session: session # Set the syno session name @syno.session = session # Request login @request {api, version, path, method, params}, done # Logout to syno # `done` [Function] Callback called when the logout process is complete logout: (done)-> # Don't do anything if there is no session if not @syno.session then return null # API method is `logout` method = 'logout' # Init logout parameters params = session: @syno.session # Remove session property of syno @syno.session = null # Request logout @request {api, version, path, method, params}, done # Handle auth specific errors error: (code)-> switch code when 400 then return 'No such account or incorrect password' when 401 then return 'Account disabled' when 402 then return 'Permission denied' when 403 then return '2-step verification code required' when 404 then return 'Failed to authenticate 2-step verification code' # No specific error, so call super function return super
71485
# Auth API class Auth extends API # API name api = 'SYNO.API.Auth' # API version version = 3 # API path path = 'auth.cgi' # Login to Syno # `done` [Function] Callback called when the login processed is complete login: (done)-> # API method is `login` method = 'login' # Use a unique session session = 'SYNO_SESSION_' + Date.now() # Init the request parameters params = account: @syno.account passwd: <PASSWORD> session: session # Set the syno session name @syno.session = session # Request login @request {api, version, path, method, params}, done # Logout to syno # `done` [Function] Callback called when the logout process is complete logout: (done)-> # Don't do anything if there is no session if not @syno.session then return null # API method is `logout` method = 'logout' # Init logout parameters params = session: @syno.session # Remove session property of syno @syno.session = null # Request logout @request {api, version, path, method, params}, done # Handle auth specific errors error: (code)-> switch code when 400 then return 'No such account or incorrect password' when 401 then return 'Account disabled' when 402 then return 'Permission denied' when 403 then return '2-step verification code required' when 404 then return 'Failed to authenticate 2-step verification code' # No specific error, so call super function return super
true
# Auth API class Auth extends API # API name api = 'SYNO.API.Auth' # API version version = 3 # API path path = 'auth.cgi' # Login to Syno # `done` [Function] Callback called when the login processed is complete login: (done)-> # API method is `login` method = 'login' # Use a unique session session = 'SYNO_SESSION_' + Date.now() # Init the request parameters params = account: @syno.account passwd: PI:PASSWORD:<PASSWORD>END_PI session: session # Set the syno session name @syno.session = session # Request login @request {api, version, path, method, params}, done # Logout to syno # `done` [Function] Callback called when the logout process is complete logout: (done)-> # Don't do anything if there is no session if not @syno.session then return null # API method is `logout` method = 'logout' # Init logout parameters params = session: @syno.session # Remove session property of syno @syno.session = null # Request logout @request {api, version, path, method, params}, done # Handle auth specific errors error: (code)-> switch code when 400 then return 'No such account or incorrect password' when 401 then return 'Account disabled' when 402 then return 'Permission denied' when 403 then return '2-step verification code required' when 404 then return 'Failed to authenticate 2-step verification code' # No specific error, so call super function return super
[ { "context": "###\n\nThe DOM configuration for WolfCage.\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@l", "end": 64, "score": 0.9998787045478821, "start": 50, "tag": "NAME", "value": "Destin Moulton" }, { "context": ".\n\n@author Destin Moulton\n@git ht...
src/DOM.coffee
destinmoulton/cagen
0
### The DOM configuration for WolfCage. @author Destin Moulton @git https://github.com/destinmoulton/wolfcage @license MIT Component of the Wolfram Cellular Automata Generator (WolfCage) Contains the settings for the DOM objects. Holds ids and classes of relevant DOM objects. ### class DOM @ids = { 'BOARD':{ 'CONTAINER':'wolfcage-board', 'MESSAGE_CONTAINER':'wolfcage-generatemessage-container' }, 'WOLFCAGE':{ 'MAIN_CONTAINER':'wolfcage-container' }, 'GENERATOR':{ 'CONTENT_CONTAINER':'wolfcage-generator-board', 'BOARD':'wolfcage-board', 'RULE_PREVIEW_CONTAINER':'wolfcage-rules-preview-container', 'RULE_GENERATE_BUTTON':'wolfcage-generator-generate-button', 'THUMBMONTAGE_BUTTON':'wolfcage-generator-thumbmontage-button', }, 'COLORBUTTONS':{ 'CONTAINER':'wolfcage-colorbuttons-container' 'ACTIVECOLOR_BUTTON':'wolfcage-colorbuttons-activecolor-button', 'INACTIVECOLOR_BUTTON':'wolfcage-colorbuttons-inactivecolor-button', 'BORDERCOLOR_BUTTON':'wolfcage-colorbuttons-bordercolor-button', 'ACTIVECOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-activecolor-button-preview', 'INACTIVECOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-inactivecolor-button-preview', 'BORDERCOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-bordercolor-button-preview', }, 'COLORSMODAL':{ 'CONTAINER':'wolfcage-colorsmodal-blocks-container' }, 'RULEPREVIEW': { 'MASK_BOX':'wolfcage-rulepreview-mask', 'RULE_NUM': 'wolfcage-rulepreview-rulenum' }, 'MODAL':{ 'VEIL': 'wolfcage-veil', 'MODAL': 'wolfcage-modal', 'TITLE': 'wolfcage-modal-title', 'CLOSE': 'wolfcage-modal-close', 'BODY': 'wolfcage-modal-body' }, 'TABS':{ 'CONTAINER':'wolfcage-tab-container' }, 'THUMBNAILSMODAL': { 'CONTAINER':'wolfcage-thumbnailsmodal-montage-container' }, 'TOPROWEDITOR':{ 'BUTTON_GENERATE': 'wolfcage-rowed-button-generate', 'BUTTON_RESET': 'wolfcage-rowed-button-resetrow', 'EDITOR_CONTAINER': 'wolfcage-rowed-editor-container', 'ROW_CONTAINER': 'wolfcage-rowed-slider-row-container', 'SLIDER_CONTAINER': 'wolfcage-rowed-slider-container', 'SLIDER':'wolfcage-rowed-slider', 'SLIDER_TEXT':'wolfcage-rowed-slider-text', }, } @classes = { 'BOARD':{ 'CELL_ACTIVE_CLASS':'wolfcage-board-cell-active', 'CELL_BASE_CLASS':'wolfcage-board-cell', }, 'COLORSMODAL':{ 'BLOCK': 'wolfcage-colorsmodal-block' }, 'GENERATOR':{ 'RULE_PREVIEW_CELL_ACTIVE':'wolfcage-generator-preview-cell-active' }, 'TABS':{ 'ACTIVE':'active' }, 'THUMBNAILSMODAL':{ 'THUMB_BOX':'wolfcage-thumbnailsmodal-rulethumb-box', }, 'TOPROWEDITOR':{ 'EDITOR_CELL':'wolfcage-rowed-editor-cell', 'EDITOR_CELL_ACTIVE':'wolfcage-rowed-editor-cell-active', 'SLIDER_CELL_ACTIVE':'wolfcage-board-cell-active' }, } @prefixes = { 'BOARD':{ 'CELL':'sb_' }, 'GENERATOR':{ 'RULE_PREVIEW_CELL':'wolfcage-generator-preview-', 'RULE_PREVIEW_DIGIT':'wolfcage-generator-preview-digit-' }, 'TABS':{ 'TAB_PREFIX':'wolfcage-tab-' }, 'TOPROWEDITOR':{ 'SLIDER_COL':'wolfcage-rowed-slider-col-' }, } # # Get an element by id # @elemById:(section, element) -> return document.getElementById(@getID(section, element)) @elemByPrefix:(section, prefix, suffix) -> return document.getElementById(@getPrefix(section, prefix) + suffix) @elemsByClass:(section, className) -> return document.querySelectorAll(".#{@getClass(section, className)}") @getClass:(section, element) -> if not @classes.hasOwnProperty(section) console.log("DOM::getClasses() - Unable to find `"+section+"`") return undefined if not @classes[section].hasOwnProperty(element) console.log("DOM::getClasses() - Unable to find `"+element+"`") return undefined return @classes[section][element] @getID:(section, element) -> if not @ids.hasOwnProperty(section) console.log("DOM::getID() - Unable to find `"+section+"`") return undefined if not @ids[section].hasOwnProperty(element) console.log("DOM::getID() - Unable to find `"+element+"`") return undefined return @ids[section][element] @getPrefix:(section, prefix)-> return @prefixes[section][prefix] module.exports = DOM
147139
### The DOM configuration for WolfCage. @author <NAME> @git https://github.com/destinmoulton/wolfcage @license MIT Component of the Wolfram Cellular Automata Generator (WolfCage) Contains the settings for the DOM objects. Holds ids and classes of relevant DOM objects. ### class DOM @ids = { 'BOARD':{ 'CONTAINER':'wolfcage-board', 'MESSAGE_CONTAINER':'wolfcage-generatemessage-container' }, 'WOLFCAGE':{ 'MAIN_CONTAINER':'wolfcage-container' }, 'GENERATOR':{ 'CONTENT_CONTAINER':'wolfcage-generator-board', 'BOARD':'wolfcage-board', 'RULE_PREVIEW_CONTAINER':'wolfcage-rules-preview-container', 'RULE_GENERATE_BUTTON':'wolfcage-generator-generate-button', 'THUMBMONTAGE_BUTTON':'wolfcage-generator-thumbmontage-button', }, 'COLORBUTTONS':{ 'CONTAINER':'wolfcage-colorbuttons-container' 'ACTIVECOLOR_BUTTON':'wolfcage-colorbuttons-activecolor-button', 'INACTIVECOLOR_BUTTON':'wolfcage-colorbuttons-inactivecolor-button', 'BORDERCOLOR_BUTTON':'wolfcage-colorbuttons-bordercolor-button', 'ACTIVECOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-activecolor-button-preview', 'INACTIVECOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-inactivecolor-button-preview', 'BORDERCOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-bordercolor-button-preview', }, 'COLORSMODAL':{ 'CONTAINER':'wolfcage-colorsmodal-blocks-container' }, 'RULEPREVIEW': { 'MASK_BOX':'wolfcage-rulepreview-mask', 'RULE_NUM': 'wolfcage-rulepreview-rulenum' }, 'MODAL':{ 'VEIL': 'wolfcage-veil', 'MODAL': 'wolfcage-modal', 'TITLE': 'wolfcage-modal-title', 'CLOSE': 'wolfcage-modal-close', 'BODY': 'wolfcage-modal-body' }, 'TABS':{ 'CONTAINER':'wolfcage-tab-container' }, 'THUMBNAILSMODAL': { 'CONTAINER':'wolfcage-thumbnailsmodal-montage-container' }, 'TOPROWEDITOR':{ 'BUTTON_GENERATE': 'wolfcage-rowed-button-generate', 'BUTTON_RESET': 'wolfcage-rowed-button-resetrow', 'EDITOR_CONTAINER': 'wolfcage-rowed-editor-container', 'ROW_CONTAINER': 'wolfcage-rowed-slider-row-container', 'SLIDER_CONTAINER': 'wolfcage-rowed-slider-container', 'SLIDER':'wolfcage-rowed-slider', 'SLIDER_TEXT':'wolfcage-rowed-slider-text', }, } @classes = { 'BOARD':{ 'CELL_ACTIVE_CLASS':'wolfcage-board-cell-active', 'CELL_BASE_CLASS':'wolfcage-board-cell', }, 'COLORSMODAL':{ 'BLOCK': 'wolfcage-colorsmodal-block' }, 'GENERATOR':{ 'RULE_PREVIEW_CELL_ACTIVE':'wolfcage-generator-preview-cell-active' }, 'TABS':{ 'ACTIVE':'active' }, 'THUMBNAILSMODAL':{ 'THUMB_BOX':'wolfcage-thumbnailsmodal-rulethumb-box', }, 'TOPROWEDITOR':{ 'EDITOR_CELL':'wolfcage-rowed-editor-cell', 'EDITOR_CELL_ACTIVE':'wolfcage-rowed-editor-cell-active', 'SLIDER_CELL_ACTIVE':'wolfcage-board-cell-active' }, } @prefixes = { 'BOARD':{ 'CELL':'sb_' }, 'GENERATOR':{ 'RULE_PREVIEW_CELL':'wolfcage-generator-preview-', 'RULE_PREVIEW_DIGIT':'wolfcage-generator-preview-digit-' }, 'TABS':{ 'TAB_PREFIX':'wolfcage-tab-' }, 'TOPROWEDITOR':{ 'SLIDER_COL':'wolfcage-rowed-slider-col-' }, } # # Get an element by id # @elemById:(section, element) -> return document.getElementById(@getID(section, element)) @elemByPrefix:(section, prefix, suffix) -> return document.getElementById(@getPrefix(section, prefix) + suffix) @elemsByClass:(section, className) -> return document.querySelectorAll(".#{@getClass(section, className)}") @getClass:(section, element) -> if not @classes.hasOwnProperty(section) console.log("DOM::getClasses() - Unable to find `"+section+"`") return undefined if not @classes[section].hasOwnProperty(element) console.log("DOM::getClasses() - Unable to find `"+element+"`") return undefined return @classes[section][element] @getID:(section, element) -> if not @ids.hasOwnProperty(section) console.log("DOM::getID() - Unable to find `"+section+"`") return undefined if not @ids[section].hasOwnProperty(element) console.log("DOM::getID() - Unable to find `"+element+"`") return undefined return @ids[section][element] @getPrefix:(section, prefix)-> return @prefixes[section][prefix] module.exports = DOM
true
### The DOM configuration for WolfCage. @author PI:NAME:<NAME>END_PI @git https://github.com/destinmoulton/wolfcage @license MIT Component of the Wolfram Cellular Automata Generator (WolfCage) Contains the settings for the DOM objects. Holds ids and classes of relevant DOM objects. ### class DOM @ids = { 'BOARD':{ 'CONTAINER':'wolfcage-board', 'MESSAGE_CONTAINER':'wolfcage-generatemessage-container' }, 'WOLFCAGE':{ 'MAIN_CONTAINER':'wolfcage-container' }, 'GENERATOR':{ 'CONTENT_CONTAINER':'wolfcage-generator-board', 'BOARD':'wolfcage-board', 'RULE_PREVIEW_CONTAINER':'wolfcage-rules-preview-container', 'RULE_GENERATE_BUTTON':'wolfcage-generator-generate-button', 'THUMBMONTAGE_BUTTON':'wolfcage-generator-thumbmontage-button', }, 'COLORBUTTONS':{ 'CONTAINER':'wolfcage-colorbuttons-container' 'ACTIVECOLOR_BUTTON':'wolfcage-colorbuttons-activecolor-button', 'INACTIVECOLOR_BUTTON':'wolfcage-colorbuttons-inactivecolor-button', 'BORDERCOLOR_BUTTON':'wolfcage-colorbuttons-bordercolor-button', 'ACTIVECOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-activecolor-button-preview', 'INACTIVECOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-inactivecolor-button-preview', 'BORDERCOLOR_BUTTON_PREVIEW':'wolfcage-colorbuttons-bordercolor-button-preview', }, 'COLORSMODAL':{ 'CONTAINER':'wolfcage-colorsmodal-blocks-container' }, 'RULEPREVIEW': { 'MASK_BOX':'wolfcage-rulepreview-mask', 'RULE_NUM': 'wolfcage-rulepreview-rulenum' }, 'MODAL':{ 'VEIL': 'wolfcage-veil', 'MODAL': 'wolfcage-modal', 'TITLE': 'wolfcage-modal-title', 'CLOSE': 'wolfcage-modal-close', 'BODY': 'wolfcage-modal-body' }, 'TABS':{ 'CONTAINER':'wolfcage-tab-container' }, 'THUMBNAILSMODAL': { 'CONTAINER':'wolfcage-thumbnailsmodal-montage-container' }, 'TOPROWEDITOR':{ 'BUTTON_GENERATE': 'wolfcage-rowed-button-generate', 'BUTTON_RESET': 'wolfcage-rowed-button-resetrow', 'EDITOR_CONTAINER': 'wolfcage-rowed-editor-container', 'ROW_CONTAINER': 'wolfcage-rowed-slider-row-container', 'SLIDER_CONTAINER': 'wolfcage-rowed-slider-container', 'SLIDER':'wolfcage-rowed-slider', 'SLIDER_TEXT':'wolfcage-rowed-slider-text', }, } @classes = { 'BOARD':{ 'CELL_ACTIVE_CLASS':'wolfcage-board-cell-active', 'CELL_BASE_CLASS':'wolfcage-board-cell', }, 'COLORSMODAL':{ 'BLOCK': 'wolfcage-colorsmodal-block' }, 'GENERATOR':{ 'RULE_PREVIEW_CELL_ACTIVE':'wolfcage-generator-preview-cell-active' }, 'TABS':{ 'ACTIVE':'active' }, 'THUMBNAILSMODAL':{ 'THUMB_BOX':'wolfcage-thumbnailsmodal-rulethumb-box', }, 'TOPROWEDITOR':{ 'EDITOR_CELL':'wolfcage-rowed-editor-cell', 'EDITOR_CELL_ACTIVE':'wolfcage-rowed-editor-cell-active', 'SLIDER_CELL_ACTIVE':'wolfcage-board-cell-active' }, } @prefixes = { 'BOARD':{ 'CELL':'sb_' }, 'GENERATOR':{ 'RULE_PREVIEW_CELL':'wolfcage-generator-preview-', 'RULE_PREVIEW_DIGIT':'wolfcage-generator-preview-digit-' }, 'TABS':{ 'TAB_PREFIX':'wolfcage-tab-' }, 'TOPROWEDITOR':{ 'SLIDER_COL':'wolfcage-rowed-slider-col-' }, } # # Get an element by id # @elemById:(section, element) -> return document.getElementById(@getID(section, element)) @elemByPrefix:(section, prefix, suffix) -> return document.getElementById(@getPrefix(section, prefix) + suffix) @elemsByClass:(section, className) -> return document.querySelectorAll(".#{@getClass(section, className)}") @getClass:(section, element) -> if not @classes.hasOwnProperty(section) console.log("DOM::getClasses() - Unable to find `"+section+"`") return undefined if not @classes[section].hasOwnProperty(element) console.log("DOM::getClasses() - Unable to find `"+element+"`") return undefined return @classes[section][element] @getID:(section, element) -> if not @ids.hasOwnProperty(section) console.log("DOM::getID() - Unable to find `"+section+"`") return undefined if not @ids[section].hasOwnProperty(element) console.log("DOM::getID() - Unable to find `"+element+"`") return undefined return @ids[section][element] @getPrefix:(section, prefix)-> return @prefixes[section][prefix] module.exports = DOM
[ { "context": "ctor: (@name, @age) ->\n\n peter = new Person(\"Peter\", 37)\n duplicate = fk.util.clone peter\n\n ", "end": 270, "score": 0.9997761249542236, "start": 265, "tag": "NAME", "value": "Peter" }, { "context": "ctor: (@name, @age) ->\n\n peter = new Person(...
test/03-util.coffee
marcuswendt/FieldKit.js
3
# mocha unit test should = require 'should' fk = require '../lib/fieldkit' describe 'Util', -> describe '#clone()', -> it 'should work with simple objects & properties', -> class Person constructor: (@name, @age) -> peter = new Person("Peter", 37) duplicate = fk.util.clone peter duplicate.name.should.equal peter.name duplicate.age.should.equal peter.age it 'should work with object hierarchies', -> class Person constructor: (@name, @age) -> peter = new Person("Peter", 37) peter.friend = new Person("Mike", 27) duplicate = fk.util.clone peter duplicate.friend.name.should.equal "Mike" duplicate.friend.age.should.equal 27 it 'should return true object copies', -> class Person constructor: (@name, @age) -> peter = new Person("Peter", 37) peter.friend = new Person("Mike", 27) duplicate = fk.util.clone peter duplicate.friend.name = "Zorro" peter.friend.name.should.equal "Mike" duplicate.friend.name.should.equal "Zorro"
138434
# mocha unit test should = require 'should' fk = require '../lib/fieldkit' describe 'Util', -> describe '#clone()', -> it 'should work with simple objects & properties', -> class Person constructor: (@name, @age) -> peter = new Person("<NAME>", 37) duplicate = fk.util.clone peter duplicate.name.should.equal peter.name duplicate.age.should.equal peter.age it 'should work with object hierarchies', -> class Person constructor: (@name, @age) -> peter = new Person("<NAME>", 37) peter.friend = new Person("<NAME>", 27) duplicate = fk.util.clone peter duplicate.friend.name.should.equal "<NAME>" duplicate.friend.age.should.equal 27 it 'should return true object copies', -> class Person constructor: (@name, @age) -> peter = new Person("<NAME>", 37) peter.friend = new Person("<NAME>", 27) duplicate = fk.util.clone peter duplicate.friend.name = "<NAME>" peter.friend.name.should.equal "<NAME>" duplicate.friend.name.should.equal "<NAME>"
true
# mocha unit test should = require 'should' fk = require '../lib/fieldkit' describe 'Util', -> describe '#clone()', -> it 'should work with simple objects & properties', -> class Person constructor: (@name, @age) -> peter = new Person("PI:NAME:<NAME>END_PI", 37) duplicate = fk.util.clone peter duplicate.name.should.equal peter.name duplicate.age.should.equal peter.age it 'should work with object hierarchies', -> class Person constructor: (@name, @age) -> peter = new Person("PI:NAME:<NAME>END_PI", 37) peter.friend = new Person("PI:NAME:<NAME>END_PI", 27) duplicate = fk.util.clone peter duplicate.friend.name.should.equal "PI:NAME:<NAME>END_PI" duplicate.friend.age.should.equal 27 it 'should return true object copies', -> class Person constructor: (@name, @age) -> peter = new Person("PI:NAME:<NAME>END_PI", 37) peter.friend = new Person("PI:NAME:<NAME>END_PI", 27) duplicate = fk.util.clone peter duplicate.friend.name = "PI:NAME:<NAME>END_PI" peter.friend.name.should.equal "PI:NAME:<NAME>END_PI" duplicate.friend.name.should.equal "PI:NAME:<NAME>END_PI"
[ { "context": "ton 'Sign in'\n fill textfield('login'), with: 'marty'\n fill textfield('password'), with: 'marty'\n ", "end": 188, "score": 0.9996007680892944, "start": 183, "tag": "USERNAME", "value": "marty" }, { "context": "h: 'marty'\n fill textfield('password'), with: '...
spec/features/javascripts/login.js.coffee
arman000/marty
6
describe 'Marty::AuthApp', -> it 'logs the marty user in', (done) -> Netzke.page.martyAuthApp.authSpecMode = true click button 'Sign in' fill textfield('login'), with: 'marty' fill textfield('password'), with: 'marty' click button 'OK' done()
202729
describe 'Marty::AuthApp', -> it 'logs the marty user in', (done) -> Netzke.page.martyAuthApp.authSpecMode = true click button 'Sign in' fill textfield('login'), with: 'marty' fill textfield('password'), with: '<PASSWORD>' click button 'OK' done()
true
describe 'Marty::AuthApp', -> it 'logs the marty user in', (done) -> Netzke.page.martyAuthApp.authSpecMode = true click button 'Sign in' fill textfield('login'), with: 'marty' fill textfield('password'), with: 'PI:PASSWORD:<PASSWORD>END_PI' click button 'OK' done()
[ { "context": "#!/usr/bin/coffee\n# copyright 2015, r. brian harrison. all rights reserved.\n\nassert = ", "end": 37, "score": 0.9939523935317993, "start": 36, "tag": "NAME", "value": "r" }, { "context": "#!/usr/bin/coffee\n# copyright 2015, r. brian harrison. all rights reserved.\...
twitter.coffee
idiomatic/twittersurvey
0
#!/usr/bin/coffee # copyright 2015, r. brian harrison. all rights reserved. assert = require 'assert' util = require 'util' co = require 'co' redis = require 'redis' coRedis = require 'co-redis' limits = require 'co-limits' wait = require 'co-wait' Twit = require 'twit' influential = 4950 untilSignal = (signal='SIGTERM') -> forever = null process.on signal, -> clearTimeout(forever) yield (cb) -> forever = setTimeout(cb, 2147483647) parseOptionalInt = (n) -> n = parseInt(n) n = undefined if isNaN(n) return n createRedisClient = -> return coRedis(redis.createClient(process.env.REDIS_URL)) class Queue constructor: (@queueName, {@pushedCap, @queueCap}={}) -> @redis = createRedisClient() @blockingRedis = undefined push: (value) -> # encourage reactive shrinkage (remove more than adding) # encourage pushed-value freshness (preferring the new values) # discarded values may be serendipitiously repushed # for popped influencers, this will update their collected data if @pushedCap? and (@pushedCap < yield @redis.scard("#{@queueName}-pushed")) yield @redis.spop("#{@queueName}-pushed") yield @redis.spop("#{@queueName}-pushed") yield @redis.incrby("#{@queueName}-discarded", 2) # there's no room in the queue; do nothing further with value if @queueCap? and (@queueCap < yield @redis.llen("#{@queueName}-queue")) yield @redis.incr("#{@queueName}-discarded") return # do nothing further if this value is currently here return unless yield @redis.sadd("#{@queueName}-pushed", value) yield @redis.rpush("#{@queueName}-queue", value) pop: (timeout) -> # correct Redis sentinel value screwup: # timeout=null -> blocking # timeout=0 -> instant return if timeout == 0 value = yield @redis.lpop("#{@queueName}-queue") else @blockingRedis ?= createRedisClient() [_, value] = yield @blockingRedis.blpop("#{@queueName}-queue", timeout ? 0) yield @redis.incr("#{@queueName}-popped") return value stats: -> # prefer frozen stats (where available) stats = yield @redis.hgetall("#{@queueName}-stats") stats or= pushed: yield @redis.scard("#{@queueName}-pushed") popped: yield @redis.get("#{@queueName}-popped") queue: yield @redis.llen("#{@queueName}-queue") discarded: yield @redis.get("#{@queueName}-discarded") return stats # function decorator to apply x-rate-limit headers rateLimiter = (options) -> {disciplinaryNaptime=60000, voluntaryNaptime=0} = options or {} waitUntil = 0 now = -> return new Date().getTime() f = (fn) -> delay = waitUntil - now() if delay > 0 yield wait(delay) # HACK eat errors [data, response] = yield (cb) -> fn (err, args...) -> cb(null, args...) waitUntil = voluntaryNaptime + now() if response?.headers['x-rate-limit-remaining'] is '0' waitUntil = Math.max(waitUntil, 1000 * parseInt(response.headers['x-rate-limit-reset'])) if response?.statusCode is 429 waitUntil = Math.max(waitUntil, disciplinaryNaptime + now()) # tail recurse yield f(fn) return [data, response] return f class Surveyer constructor: (@twitter=null) -> # TODO make {options} not process.env # needs to be considerably bigger than 'ZCARD influence' pushedCap = parseOptionalInt(process.env.USER_PUSHED_CAP) queueCap = parseOptionalInt(process.env.USER_QUEUE_CAP) @userQueue = new Queue('user', {pushedCap, queueCap}) pushedCap = parseOptionalInt(process.env.FOLLOWERS_PUSHED_CAP) queueCap = parseOptionalInt(process.env.FOLLOWERS_QUEUE_CAP) @followersQueue = new Queue('follower', {pushedCap, queueCap}) pushedCap = parseOptionalInt(process.env.FRIENDS_PUSHED_CAP) queueCap = parseOptionalInt(process.env.FRIENDS_QUEUE_CAP) @friendsQueue = new Queue('friend', {pushedCap, queueCap}) @usersLookupLimit = rateLimiter() # 180/15min @followersIdsLimit = rateLimiter() # 15/15min @friendsIdsLimit = rateLimiter() # 15/15min @redis = createRedisClient() seed: => yield @userQueue.push(237845487) stats: -> user: yield @userQueue.stats() followers: yield @followersQueue.stats() friends: yield @friendsQueue.stats() influencers: yield @redis.zcard('influence') lastInfluencer: yield => influencer = yield @redis.get('lastinfluencer') return JSON.parse(influencer or 'null') paused: yield @redis.get('paused') users: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue followedIds = [yield @userQueue.pop()] # HACK since blpop(..., timeout) does not work; 100ms queue top-off yield wait(100) # add up to 99 more possible influencers for i in [1...100] id = yield @userQueue.pop(0) break unless id followedIds.push(id) # bulk user retrieval [users] = yield @usersLookupLimit (cb) => @twitter.get('users/lookup', user_id:followedIds.join(','), cb) # discriminate for user in users or [] {followers_count, screen_name, id} = user if followers_count >= influential yield @redis.zadd('influence', followers_count, screen_name) userBrief = name: user.name followers_count: user.followers_count description: user.description location: user.location url: user.url yield @redis.hset('influencers', screen_name, JSON.stringify(userBrief)) # virally check out influcencers' followers yield @followersQueue.push(id) lastInfluencer = user # HACK if lastInfluencer yield @redis.set('lastinfluencer', JSON.stringify(lastInfluencer)) followers: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue id = yield @followersQueue.pop() [{ids}] = yield @followersIdsLimit (cb) => @twitter.get('followers/ids', {user_id:id, count:5000}, cb) for follower in ids or [] yield @userQueue.push(follower) yield @friendsQueue.push(follower) friends: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue id = yield @friendsQueue.pop() [{ids}] = yield @friendsIdsLimit (cb) => @twitter.get('friends/ids', {user_id:id, count:5000}, cb) for friend in ids or [] yield @userQueue.push(friend) authenticate = (consumer_key, consumer_secret) -> return new Twit {consumer_key, consumer_secret, app_only_auth: true} start = -> credentials = {} {TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET} = process.env if TWITTER_CONSUMER_KEY credentials[TWITTER_CONSUMER_KEY] = TWITTER_CONSUMER_SECRET redisClient = createRedisClient() for credential in yield redisClient.lrange('credentials', 0, -1) [key, secret] = credential.split(':') continue if key is TWITTER_CONSUMER_KEY credentials[key] = secret redisClient.quit() credentialCount = 0 for key, secret of credentials twitter = authenticate(key, secret) surveyer = new Surveyer(twitter) yield surveyer.seed() # parallel execution # TODO error propagation chainError = (err) -> setImmediate -> throw err #chainError = (err) -> console.error err.stack co(surveyer.users).catch chainError co(surveyer.followers).catch chainError co(surveyer.friends).catch chainError ++credentialCount console.log "#{credentialCount} Twitter app credential(s) in use" # XXX #yield untilSignal() if require.main is module co(start).catch (err) -> console.error err.stack module.exports = {start, createRedisClient, Queue, Surveyer}
4683
#!/usr/bin/coffee # copyright 2015, <NAME>. <NAME>. all rights reserved. assert = require 'assert' util = require 'util' co = require 'co' redis = require 'redis' coRedis = require 'co-redis' limits = require 'co-limits' wait = require 'co-wait' Twit = require 'twit' influential = 4950 untilSignal = (signal='SIGTERM') -> forever = null process.on signal, -> clearTimeout(forever) yield (cb) -> forever = setTimeout(cb, 2147483647) parseOptionalInt = (n) -> n = parseInt(n) n = undefined if isNaN(n) return n createRedisClient = -> return coRedis(redis.createClient(process.env.REDIS_URL)) class Queue constructor: (@queueName, {@pushedCap, @queueCap}={}) -> @redis = createRedisClient() @blockingRedis = undefined push: (value) -> # encourage reactive shrinkage (remove more than adding) # encourage pushed-value freshness (preferring the new values) # discarded values may be serendipitiously repushed # for popped influencers, this will update their collected data if @pushedCap? and (@pushedCap < yield @redis.scard("#{@queueName}-pushed")) yield @redis.spop("#{@queueName}-pushed") yield @redis.spop("#{@queueName}-pushed") yield @redis.incrby("#{@queueName}-discarded", 2) # there's no room in the queue; do nothing further with value if @queueCap? and (@queueCap < yield @redis.llen("#{@queueName}-queue")) yield @redis.incr("#{@queueName}-discarded") return # do nothing further if this value is currently here return unless yield @redis.sadd("#{@queueName}-pushed", value) yield @redis.rpush("#{@queueName}-queue", value) pop: (timeout) -> # correct Redis sentinel value screwup: # timeout=null -> blocking # timeout=0 -> instant return if timeout == 0 value = yield @redis.lpop("#{@queueName}-queue") else @blockingRedis ?= createRedisClient() [_, value] = yield @blockingRedis.blpop("#{@queueName}-queue", timeout ? 0) yield @redis.incr("#{@queueName}-popped") return value stats: -> # prefer frozen stats (where available) stats = yield @redis.hgetall("#{@queueName}-stats") stats or= pushed: yield @redis.scard("#{@queueName}-pushed") popped: yield @redis.get("#{@queueName}-popped") queue: yield @redis.llen("#{@queueName}-queue") discarded: yield @redis.get("#{@queueName}-discarded") return stats # function decorator to apply x-rate-limit headers rateLimiter = (options) -> {disciplinaryNaptime=60000, voluntaryNaptime=0} = options or {} waitUntil = 0 now = -> return new Date().getTime() f = (fn) -> delay = waitUntil - now() if delay > 0 yield wait(delay) # HACK eat errors [data, response] = yield (cb) -> fn (err, args...) -> cb(null, args...) waitUntil = voluntaryNaptime + now() if response?.headers['x-rate-limit-remaining'] is '0' waitUntil = Math.max(waitUntil, 1000 * parseInt(response.headers['x-rate-limit-reset'])) if response?.statusCode is 429 waitUntil = Math.max(waitUntil, disciplinaryNaptime + now()) # tail recurse yield f(fn) return [data, response] return f class Surveyer constructor: (@twitter=null) -> # TODO make {options} not process.env # needs to be considerably bigger than 'ZCARD influence' pushedCap = parseOptionalInt(process.env.USER_PUSHED_CAP) queueCap = parseOptionalInt(process.env.USER_QUEUE_CAP) @userQueue = new Queue('user', {pushedCap, queueCap}) pushedCap = parseOptionalInt(process.env.FOLLOWERS_PUSHED_CAP) queueCap = parseOptionalInt(process.env.FOLLOWERS_QUEUE_CAP) @followersQueue = new Queue('follower', {pushedCap, queueCap}) pushedCap = parseOptionalInt(process.env.FRIENDS_PUSHED_CAP) queueCap = parseOptionalInt(process.env.FRIENDS_QUEUE_CAP) @friendsQueue = new Queue('friend', {pushedCap, queueCap}) @usersLookupLimit = rateLimiter() # 180/15min @followersIdsLimit = rateLimiter() # 15/15min @friendsIdsLimit = rateLimiter() # 15/15min @redis = createRedisClient() seed: => yield @userQueue.push(237845487) stats: -> user: yield @userQueue.stats() followers: yield @followersQueue.stats() friends: yield @friendsQueue.stats() influencers: yield @redis.zcard('influence') lastInfluencer: yield => influencer = yield @redis.get('lastinfluencer') return JSON.parse(influencer or 'null') paused: yield @redis.get('paused') users: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue followedIds = [yield @userQueue.pop()] # HACK since blpop(..., timeout) does not work; 100ms queue top-off yield wait(100) # add up to 99 more possible influencers for i in [1...100] id = yield @userQueue.pop(0) break unless id followedIds.push(id) # bulk user retrieval [users] = yield @usersLookupLimit (cb) => @twitter.get('users/lookup', user_id:followedIds.join(','), cb) # discriminate for user in users or [] {followers_count, screen_name, id} = user if followers_count >= influential yield @redis.zadd('influence', followers_count, screen_name) userBrief = name: user.name followers_count: user.followers_count description: user.description location: user.location url: user.url yield @redis.hset('influencers', screen_name, JSON.stringify(userBrief)) # virally check out influcencers' followers yield @followersQueue.push(id) lastInfluencer = user # HACK if lastInfluencer yield @redis.set('lastinfluencer', JSON.stringify(lastInfluencer)) followers: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue id = yield @followersQueue.pop() [{ids}] = yield @followersIdsLimit (cb) => @twitter.get('followers/ids', {user_id:id, count:5000}, cb) for follower in ids or [] yield @userQueue.push(follower) yield @friendsQueue.push(follower) friends: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue id = yield @friendsQueue.pop() [{ids}] = yield @friendsIdsLimit (cb) => @twitter.get('friends/ids', {user_id:id, count:5000}, cb) for friend in ids or [] yield @userQueue.push(friend) authenticate = (consumer_key, consumer_secret) -> return new Twit {consumer_key, consumer_secret, app_only_auth: true} start = -> credentials = {} {TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET} = process.env if TWITTER_CONSUMER_KEY credentials[TWITTER_CONSUMER_KEY] = TWITTER_CONSUMER_SECRET redisClient = createRedisClient() for credential in yield redisClient.lrange('credentials', 0, -1) [key, secret] = credential.split(':') continue if key is TWITTER_CONSUMER_KEY credentials[key] = secret redisClient.quit() credentialCount = 0 for key, secret of credentials twitter = authenticate(key, secret) surveyer = new Surveyer(twitter) yield surveyer.seed() # parallel execution # TODO error propagation chainError = (err) -> setImmediate -> throw err #chainError = (err) -> console.error err.stack co(surveyer.users).catch chainError co(surveyer.followers).catch chainError co(surveyer.friends).catch chainError ++credentialCount console.log "#{credentialCount} Twitter app credential(s) in use" # XXX #yield untilSignal() if require.main is module co(start).catch (err) -> console.error err.stack module.exports = {start, createRedisClient, Queue, Surveyer}
true
#!/usr/bin/coffee # copyright 2015, PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI. all rights reserved. assert = require 'assert' util = require 'util' co = require 'co' redis = require 'redis' coRedis = require 'co-redis' limits = require 'co-limits' wait = require 'co-wait' Twit = require 'twit' influential = 4950 untilSignal = (signal='SIGTERM') -> forever = null process.on signal, -> clearTimeout(forever) yield (cb) -> forever = setTimeout(cb, 2147483647) parseOptionalInt = (n) -> n = parseInt(n) n = undefined if isNaN(n) return n createRedisClient = -> return coRedis(redis.createClient(process.env.REDIS_URL)) class Queue constructor: (@queueName, {@pushedCap, @queueCap}={}) -> @redis = createRedisClient() @blockingRedis = undefined push: (value) -> # encourage reactive shrinkage (remove more than adding) # encourage pushed-value freshness (preferring the new values) # discarded values may be serendipitiously repushed # for popped influencers, this will update their collected data if @pushedCap? and (@pushedCap < yield @redis.scard("#{@queueName}-pushed")) yield @redis.spop("#{@queueName}-pushed") yield @redis.spop("#{@queueName}-pushed") yield @redis.incrby("#{@queueName}-discarded", 2) # there's no room in the queue; do nothing further with value if @queueCap? and (@queueCap < yield @redis.llen("#{@queueName}-queue")) yield @redis.incr("#{@queueName}-discarded") return # do nothing further if this value is currently here return unless yield @redis.sadd("#{@queueName}-pushed", value) yield @redis.rpush("#{@queueName}-queue", value) pop: (timeout) -> # correct Redis sentinel value screwup: # timeout=null -> blocking # timeout=0 -> instant return if timeout == 0 value = yield @redis.lpop("#{@queueName}-queue") else @blockingRedis ?= createRedisClient() [_, value] = yield @blockingRedis.blpop("#{@queueName}-queue", timeout ? 0) yield @redis.incr("#{@queueName}-popped") return value stats: -> # prefer frozen stats (where available) stats = yield @redis.hgetall("#{@queueName}-stats") stats or= pushed: yield @redis.scard("#{@queueName}-pushed") popped: yield @redis.get("#{@queueName}-popped") queue: yield @redis.llen("#{@queueName}-queue") discarded: yield @redis.get("#{@queueName}-discarded") return stats # function decorator to apply x-rate-limit headers rateLimiter = (options) -> {disciplinaryNaptime=60000, voluntaryNaptime=0} = options or {} waitUntil = 0 now = -> return new Date().getTime() f = (fn) -> delay = waitUntil - now() if delay > 0 yield wait(delay) # HACK eat errors [data, response] = yield (cb) -> fn (err, args...) -> cb(null, args...) waitUntil = voluntaryNaptime + now() if response?.headers['x-rate-limit-remaining'] is '0' waitUntil = Math.max(waitUntil, 1000 * parseInt(response.headers['x-rate-limit-reset'])) if response?.statusCode is 429 waitUntil = Math.max(waitUntil, disciplinaryNaptime + now()) # tail recurse yield f(fn) return [data, response] return f class Surveyer constructor: (@twitter=null) -> # TODO make {options} not process.env # needs to be considerably bigger than 'ZCARD influence' pushedCap = parseOptionalInt(process.env.USER_PUSHED_CAP) queueCap = parseOptionalInt(process.env.USER_QUEUE_CAP) @userQueue = new Queue('user', {pushedCap, queueCap}) pushedCap = parseOptionalInt(process.env.FOLLOWERS_PUSHED_CAP) queueCap = parseOptionalInt(process.env.FOLLOWERS_QUEUE_CAP) @followersQueue = new Queue('follower', {pushedCap, queueCap}) pushedCap = parseOptionalInt(process.env.FRIENDS_PUSHED_CAP) queueCap = parseOptionalInt(process.env.FRIENDS_QUEUE_CAP) @friendsQueue = new Queue('friend', {pushedCap, queueCap}) @usersLookupLimit = rateLimiter() # 180/15min @followersIdsLimit = rateLimiter() # 15/15min @friendsIdsLimit = rateLimiter() # 15/15min @redis = createRedisClient() seed: => yield @userQueue.push(237845487) stats: -> user: yield @userQueue.stats() followers: yield @followersQueue.stats() friends: yield @friendsQueue.stats() influencers: yield @redis.zcard('influence') lastInfluencer: yield => influencer = yield @redis.get('lastinfluencer') return JSON.parse(influencer or 'null') paused: yield @redis.get('paused') users: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue followedIds = [yield @userQueue.pop()] # HACK since blpop(..., timeout) does not work; 100ms queue top-off yield wait(100) # add up to 99 more possible influencers for i in [1...100] id = yield @userQueue.pop(0) break unless id followedIds.push(id) # bulk user retrieval [users] = yield @usersLookupLimit (cb) => @twitter.get('users/lookup', user_id:followedIds.join(','), cb) # discriminate for user in users or [] {followers_count, screen_name, id} = user if followers_count >= influential yield @redis.zadd('influence', followers_count, screen_name) userBrief = name: user.name followers_count: user.followers_count description: user.description location: user.location url: user.url yield @redis.hset('influencers', screen_name, JSON.stringify(userBrief)) # virally check out influcencers' followers yield @followersQueue.push(id) lastInfluencer = user # HACK if lastInfluencer yield @redis.set('lastinfluencer', JSON.stringify(lastInfluencer)) followers: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue id = yield @followersQueue.pop() [{ids}] = yield @followersIdsLimit (cb) => @twitter.get('followers/ids', {user_id:id, count:5000}, cb) for follower in ids or [] yield @userQueue.push(follower) yield @friendsQueue.push(follower) friends: => assert @twitter loop if yield @redis.get('paused') yield wait(5000) continue id = yield @friendsQueue.pop() [{ids}] = yield @friendsIdsLimit (cb) => @twitter.get('friends/ids', {user_id:id, count:5000}, cb) for friend in ids or [] yield @userQueue.push(friend) authenticate = (consumer_key, consumer_secret) -> return new Twit {consumer_key, consumer_secret, app_only_auth: true} start = -> credentials = {} {TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET} = process.env if TWITTER_CONSUMER_KEY credentials[TWITTER_CONSUMER_KEY] = TWITTER_CONSUMER_SECRET redisClient = createRedisClient() for credential in yield redisClient.lrange('credentials', 0, -1) [key, secret] = credential.split(':') continue if key is TWITTER_CONSUMER_KEY credentials[key] = secret redisClient.quit() credentialCount = 0 for key, secret of credentials twitter = authenticate(key, secret) surveyer = new Surveyer(twitter) yield surveyer.seed() # parallel execution # TODO error propagation chainError = (err) -> setImmediate -> throw err #chainError = (err) -> console.error err.stack co(surveyer.users).catch chainError co(surveyer.followers).catch chainError co(surveyer.friends).catch chainError ++credentialCount console.log "#{credentialCount} Twitter app credential(s) in use" # XXX #yield untilSignal() if require.main is module co(start).catch (err) -> console.error err.stack module.exports = {start, createRedisClient, Queue, Surveyer}
[ { "context": "nput class='mdl-textfield__input' type='text' id='username' name='username' autofocus autocorrect='off' auto", "end": 937, "score": 0.994416356086731, "start": 929, "tag": "USERNAME", "value": "username" }, { "context": "textfield__input' type='text' id='username' name=...
_attachments/app/views/LoginView.coffee
Coconut-Data/coconut-mobile
0
$ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ Form2js = require 'form2js' User = require '../models/User' class LoginView extends Backbone.View el: '#content' render: => # If we try to login while on the logout page it will automatically log out upon successful login if document.location.hash.match("/logout") Coconut.router.navigate("", trigger: true) return @displayHeader() $('.mdl-layout__drawer-button').hide() @$el.html " <div class='mdl-card mdl-shadow--8dp coconut-mdl-card' id='login_wrapper'> <div id='logo-title'><img src='images/cocoLogo.png' id='cslogo_sm'> Coconut</div> <div class='mdl-card__title coconut-mdl-card__title' id='loginErrMsg'></div> <form id='login_form'> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='text' id='username' name='username' autofocus autocorrect='off' autocapitalize='none' style='text-transform:lowercase;'> <label class='mdl-textfield__label' for='username'>Username</label> </div> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='password' name='password'> <label class='mdl-textfield__label' for='password'>Password</label> </div> <div class='mdl-card__actions' id='login_actions'> <button type='button' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent' id='login_button'>Log in</button> <button type='button' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect' id='login_cancel_button'>Cancel</button> </div> </form> </div> " componentHandler.upgradeDom() events: "click #login_button": "login" "click #login_cancel_button": "cancel" "keypress #password": "submitIfEnter" submitIfEnter: (event) -> @login() if event.which == 10 or event.which == 13 cancel: -> Coconut.router.navigate("", true) return document.location.reload() login: => # Useful for reusing the login screen - like for database encryption if $("#username").val() is "" or $("#password").val() is "" return @displayErr("Please enter a username and a password") username = @$("#username").val().toLowerCase() Coconut.toggleSpinner(true) Coconut.openDatabase username: username password: @$("#password").val() .catch (error) => console.error error Coconut.toggleSpinner(false) @render() if error is "invalid user" @displayErr "#{username} is not a valid user. If #{username} has been added since your last sync, then you need to login with a user already loaded on this tablet and sync, then logout and try again. Alternatively you can <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." else if error is "failed decryption check" @displayErr "#{username} is a valid user, but the password is incorrect. If the password has been changed since your last sync, then you need to login with a different user on this tablet and sync, then logout and try again. Alternatively you can <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." else if _(error).isEmpty() and not @hasRetried? _.delay => console.log "Retrying to login" @hasRetried = true @login() ,500 else console.error error @displayErr "#{JSON.stringify error}. Recommendation: try to login again or <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." throw "Need to login to proceed" .then => Coconut.toggleSpinner(false) $('#login_wrapper').hide() @callback() .catch (error) => console.log "ERROR" console.error error displayErr: (msg) => $('.coconut-mdl-card__title').html "<i style='padding-right:10px' class='mdi mdi-information-outline mdi-36px'></i> #{msg}" displayHeader: => $(".mdl-layout__header-row").html("<div id='appName'>#{Coconut.databaseName}</div> <div id='right_top_menu'> <button class='mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon' id='top-menu-lower-right'> <i class='mdi mdi-dots-vertical mdi-36px'></i> </button> <ul class='mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect' for='top-menu-lower-right'> <li class='mdl-menu__item'><a id='refresh' class='mdl-color-text--blue-grey-400' onclick='window.location.reload()'><i class='mdi mdi-rotate-right mdi-24px'></i> Refresh screen</a></li> <li class='mdl-menu__item'> <div id='version'>Version: 1.0.0 - <a href='https://github.com/ICTatRTI/coconut-mobile/commit/ac436b0'>ac436b0</a></div> <i class='mdi mdi-rotate-right mdi-24px'></i> Refresh screen</a></li> </ul> </div> ") module.exports = LoginView
151668
$ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ Form2js = require 'form2js' User = require '../models/User' class LoginView extends Backbone.View el: '#content' render: => # If we try to login while on the logout page it will automatically log out upon successful login if document.location.hash.match("/logout") Coconut.router.navigate("", trigger: true) return @displayHeader() $('.mdl-layout__drawer-button').hide() @$el.html " <div class='mdl-card mdl-shadow--8dp coconut-mdl-card' id='login_wrapper'> <div id='logo-title'><img src='images/cocoLogo.png' id='cslogo_sm'> Coconut</div> <div class='mdl-card__title coconut-mdl-card__title' id='loginErrMsg'></div> <form id='login_form'> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='text' id='username' name='username' autofocus autocorrect='off' autocapitalize='none' style='text-transform:lowercase;'> <label class='mdl-textfield__label' for='username'>Username</label> </div> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='<PASSWORD>' id='<PASSWORD>' name='<PASSWORD>'> <label class='mdl-textfield__label' for='password'><PASSWORD></label> </div> <div class='mdl-card__actions' id='login_actions'> <button type='button' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent' id='login_button'>Log in</button> <button type='button' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect' id='login_cancel_button'>Cancel</button> </div> </form> </div> " componentHandler.upgradeDom() events: "click #login_button": "login" "click #login_cancel_button": "cancel" "keypress #password": "submitIfEnter" submitIfEnter: (event) -> @login() if event.which == 10 or event.which == 13 cancel: -> Coconut.router.navigate("", true) return document.location.reload() login: => # Useful for reusing the login screen - like for database encryption if $("#username").val() is "" or $("#password").val() is "" return @displayErr("Please enter a username and a password") username = @$("#username").val().toLowerCase() Coconut.toggleSpinner(true) Coconut.openDatabase username: username password: @$("#password").val() .catch (error) => console.error error Coconut.toggleSpinner(false) @render() if error is "invalid user" @displayErr "#{username} is not a valid user. If #{username} has been added since your last sync, then you need to login with a user already loaded on this tablet and sync, then logout and try again. Alternatively you can <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." else if error is "failed decryption check" @displayErr "#{username} is a valid user, but the password is incorrect. If the password has been changed since your last sync, then you need to login with a different user on this tablet and sync, then logout and try again. Alternatively you can <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." else if _(error).isEmpty() and not @hasRetried? _.delay => console.log "Retrying to login" @hasRetried = true @login() ,500 else console.error error @displayErr "#{JSON.stringify error}. Recommendation: try to login again or <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." throw "Need to login to proceed" .then => Coconut.toggleSpinner(false) $('#login_wrapper').hide() @callback() .catch (error) => console.log "ERROR" console.error error displayErr: (msg) => $('.coconut-mdl-card__title').html "<i style='padding-right:10px' class='mdi mdi-information-outline mdi-36px'></i> #{msg}" displayHeader: => $(".mdl-layout__header-row").html("<div id='appName'>#{Coconut.databaseName}</div> <div id='right_top_menu'> <button class='mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon' id='top-menu-lower-right'> <i class='mdi mdi-dots-vertical mdi-36px'></i> </button> <ul class='mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect' for='top-menu-lower-right'> <li class='mdl-menu__item'><a id='refresh' class='mdl-color-text--blue-grey-400' onclick='window.location.reload()'><i class='mdi mdi-rotate-right mdi-24px'></i> Refresh screen</a></li> <li class='mdl-menu__item'> <div id='version'>Version: 1.0.0 - <a href='https://github.com/ICTatRTI/coconut-mobile/commit/ac436b0'>ac436b0</a></div> <i class='mdi mdi-rotate-right mdi-24px'></i> Refresh screen</a></li> </ul> </div> ") module.exports = LoginView
true
$ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ Form2js = require 'form2js' User = require '../models/User' class LoginView extends Backbone.View el: '#content' render: => # If we try to login while on the logout page it will automatically log out upon successful login if document.location.hash.match("/logout") Coconut.router.navigate("", trigger: true) return @displayHeader() $('.mdl-layout__drawer-button').hide() @$el.html " <div class='mdl-card mdl-shadow--8dp coconut-mdl-card' id='login_wrapper'> <div id='logo-title'><img src='images/cocoLogo.png' id='cslogo_sm'> Coconut</div> <div class='mdl-card__title coconut-mdl-card__title' id='loginErrMsg'></div> <form id='login_form'> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='text' id='username' name='username' autofocus autocorrect='off' autocapitalize='none' style='text-transform:lowercase;'> <label class='mdl-textfield__label' for='username'>Username</label> </div> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='PI:PASSWORD:<PASSWORD>END_PI' id='PI:PASSWORD:<PASSWORD>END_PI' name='PI:PASSWORD:<PASSWORD>END_PI'> <label class='mdl-textfield__label' for='password'>PI:PASSWORD:<PASSWORD>END_PI</label> </div> <div class='mdl-card__actions' id='login_actions'> <button type='button' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent' id='login_button'>Log in</button> <button type='button' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect' id='login_cancel_button'>Cancel</button> </div> </form> </div> " componentHandler.upgradeDom() events: "click #login_button": "login" "click #login_cancel_button": "cancel" "keypress #password": "submitIfEnter" submitIfEnter: (event) -> @login() if event.which == 10 or event.which == 13 cancel: -> Coconut.router.navigate("", true) return document.location.reload() login: => # Useful for reusing the login screen - like for database encryption if $("#username").val() is "" or $("#password").val() is "" return @displayErr("Please enter a username and a password") username = @$("#username").val().toLowerCase() Coconut.toggleSpinner(true) Coconut.openDatabase username: username password: @$("#password").val() .catch (error) => console.error error Coconut.toggleSpinner(false) @render() if error is "invalid user" @displayErr "#{username} is not a valid user. If #{username} has been added since your last sync, then you need to login with a user already loaded on this tablet and sync, then logout and try again. Alternatively you can <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." else if error is "failed decryption check" @displayErr "#{username} is a valid user, but the password is incorrect. If the password has been changed since your last sync, then you need to login with a different user on this tablet and sync, then logout and try again. Alternatively you can <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." else if _(error).isEmpty() and not @hasRetried? _.delay => console.log "Retrying to login" @hasRetried = true @login() ,500 else console.error error @displayErr "#{JSON.stringify error}. Recommendation: try to login again or <a onClick='Coconut.promptToUpdate();return false' href='#'>update the database</a>." throw "Need to login to proceed" .then => Coconut.toggleSpinner(false) $('#login_wrapper').hide() @callback() .catch (error) => console.log "ERROR" console.error error displayErr: (msg) => $('.coconut-mdl-card__title').html "<i style='padding-right:10px' class='mdi mdi-information-outline mdi-36px'></i> #{msg}" displayHeader: => $(".mdl-layout__header-row").html("<div id='appName'>#{Coconut.databaseName}</div> <div id='right_top_menu'> <button class='mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon' id='top-menu-lower-right'> <i class='mdi mdi-dots-vertical mdi-36px'></i> </button> <ul class='mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect' for='top-menu-lower-right'> <li class='mdl-menu__item'><a id='refresh' class='mdl-color-text--blue-grey-400' onclick='window.location.reload()'><i class='mdi mdi-rotate-right mdi-24px'></i> Refresh screen</a></li> <li class='mdl-menu__item'> <div id='version'>Version: 1.0.0 - <a href='https://github.com/ICTatRTI/coconut-mobile/commit/ac436b0'>ac436b0</a></div> <i class='mdi mdi-rotate-right mdi-24px'></i> Refresh screen</a></li> </ul> </div> ") module.exports = LoginView
[ { "context": "#donation-form\", {\n \"customer.first_name\" : \"Foo\", \n \"customer.last_name\" : \"Bar\", \n \"cu", "end": 710, "score": 0.9995806813240051, "start": 707, "tag": "NAME", "value": "Foo" }, { "context": "rst_name\" : \"Foo\", \n \"customer.last_nam...
src/coffee/test/complete-a-valid-form-feature.coffee
controlshift/prague-client
3
casper.test.begin "completing a valid form", 3, (test) -> casper.on 'remote.alert', (message) -> this.log('remote alert message: ' + message, 'warning'); casper.on 'remote.message', (message) -> this.log('remote console message: ' + message, 'warning'); casper.on 'page.error', (message, trace) -> this.log("page js error: " + message, 'warning'); casper.start "public/test/casper.html" casper.waitUntilVisible '.donation-btn' casper.then -> @click ".donation-btn" @click ".donation-next-btn" test.assertVisible(".donation-text-field[name='customer.first_name']", "Step 2 is visible") @fill("form#donation-form", { "customer.first_name" : "Foo", "customer.last_name" : "Bar", "customer.email" : "foo@bar.com" }, false) @click "#donation-second-next-btn" test.assertVisible("#cc-num-input", "Step 3 is visible") @fill("form#donation-form", { "cc-num" : "4242 4242 4242 4242", "month" : "02", "year" : "#{(new Date).getFullYear() + 1}", "cvc" : "4242" }, false) noErrors = document.querySelector(".donation-text-field-error") test.assertEquals(noErrors, null, "No errors are present") return casper.run -> test.done() return return
108740
casper.test.begin "completing a valid form", 3, (test) -> casper.on 'remote.alert', (message) -> this.log('remote alert message: ' + message, 'warning'); casper.on 'remote.message', (message) -> this.log('remote console message: ' + message, 'warning'); casper.on 'page.error', (message, trace) -> this.log("page js error: " + message, 'warning'); casper.start "public/test/casper.html" casper.waitUntilVisible '.donation-btn' casper.then -> @click ".donation-btn" @click ".donation-next-btn" test.assertVisible(".donation-text-field[name='customer.first_name']", "Step 2 is visible") @fill("form#donation-form", { "customer.first_name" : "<NAME>", "customer.last_name" : "<NAME>", "customer.email" : "<EMAIL>" }, false) @click "#donation-second-next-btn" test.assertVisible("#cc-num-input", "Step 3 is visible") @fill("form#donation-form", { "cc-num" : "4242 4242 4242 4242", "month" : "02", "year" : "#{(new Date).getFullYear() + 1}", "cvc" : "4242" }, false) noErrors = document.querySelector(".donation-text-field-error") test.assertEquals(noErrors, null, "No errors are present") return casper.run -> test.done() return return
true
casper.test.begin "completing a valid form", 3, (test) -> casper.on 'remote.alert', (message) -> this.log('remote alert message: ' + message, 'warning'); casper.on 'remote.message', (message) -> this.log('remote console message: ' + message, 'warning'); casper.on 'page.error', (message, trace) -> this.log("page js error: " + message, 'warning'); casper.start "public/test/casper.html" casper.waitUntilVisible '.donation-btn' casper.then -> @click ".donation-btn" @click ".donation-next-btn" test.assertVisible(".donation-text-field[name='customer.first_name']", "Step 2 is visible") @fill("form#donation-form", { "customer.first_name" : "PI:NAME:<NAME>END_PI", "customer.last_name" : "PI:NAME:<NAME>END_PI", "customer.email" : "PI:EMAIL:<EMAIL>END_PI" }, false) @click "#donation-second-next-btn" test.assertVisible("#cc-num-input", "Step 3 is visible") @fill("form#donation-form", { "cc-num" : "4242 4242 4242 4242", "month" : "02", "year" : "#{(new Date).getFullYear() + 1}", "cvc" : "4242" }, false) noErrors = document.querySelector(".donation-text-field-error") test.assertEquals(noErrors, null, "No errors are present") return casper.run -> test.done() return return
[ { "context": "ubot bitcoin price (in) <currency>\n#\n# Author:\n# Fred Wu\n\ncheerio = require('cheerio')\n\nmodule.exports = (", "end": 212, "score": 0.9998478889465332, "start": 205, "tag": "NAME", "value": "Fred Wu" } ]
src/scripts/bitcoin.coffee
Reelhouse/hubot-scripts
1,450
# Description: # Find the latest Bitcoin price in specified currency # # Dependencies: # "cheerio": "" # # Configuration: # None # # Commands: # hubot bitcoin price (in) <currency> # # Author: # Fred Wu cheerio = require('cheerio') module.exports = (robot) -> robot.respond /bitcoin price\s(in\s)?(.*)/i, (msg) -> currency = msg.match[2].trim().toUpperCase() bitcoinPrice(msg, currency) bitcoinPrice = (msg, currency) -> msg .send "Looking up... sit tight..." msg .http("http://bitcoinprices.com/") .get() (err, res, body) -> msg.send "#{getPrice(currency, body)}" getPrice = (currency, body) -> $ = cheerio.load(body) lastPrice = null highPrice = null lowPrice = null priceSymbol = null $('table.currencies td.symbol').each (i) -> if $(this).text() == currency priceSymbol = $(this).next().next().next().next().next().next().text() lastPrice = "#{priceSymbol}#{$(this).next().next().next().next().next().text()}" highPrice = "#{priceSymbol}#{$(this).next().next().next().text()}" lowPrice = "#{priceSymbol}#{$(this).next().next().next().next().text()}" false if lastPrice == null "Can't find the price for #{currency}. :(" else "#{currency}: #{lastPrice} (H: #{highPrice} | L: #{lowPrice})"
148376
# Description: # Find the latest Bitcoin price in specified currency # # Dependencies: # "cheerio": "" # # Configuration: # None # # Commands: # hubot bitcoin price (in) <currency> # # Author: # <NAME> cheerio = require('cheerio') module.exports = (robot) -> robot.respond /bitcoin price\s(in\s)?(.*)/i, (msg) -> currency = msg.match[2].trim().toUpperCase() bitcoinPrice(msg, currency) bitcoinPrice = (msg, currency) -> msg .send "Looking up... sit tight..." msg .http("http://bitcoinprices.com/") .get() (err, res, body) -> msg.send "#{getPrice(currency, body)}" getPrice = (currency, body) -> $ = cheerio.load(body) lastPrice = null highPrice = null lowPrice = null priceSymbol = null $('table.currencies td.symbol').each (i) -> if $(this).text() == currency priceSymbol = $(this).next().next().next().next().next().next().text() lastPrice = "#{priceSymbol}#{$(this).next().next().next().next().next().text()}" highPrice = "#{priceSymbol}#{$(this).next().next().next().text()}" lowPrice = "#{priceSymbol}#{$(this).next().next().next().next().text()}" false if lastPrice == null "Can't find the price for #{currency}. :(" else "#{currency}: #{lastPrice} (H: #{highPrice} | L: #{lowPrice})"
true
# Description: # Find the latest Bitcoin price in specified currency # # Dependencies: # "cheerio": "" # # Configuration: # None # # Commands: # hubot bitcoin price (in) <currency> # # Author: # PI:NAME:<NAME>END_PI cheerio = require('cheerio') module.exports = (robot) -> robot.respond /bitcoin price\s(in\s)?(.*)/i, (msg) -> currency = msg.match[2].trim().toUpperCase() bitcoinPrice(msg, currency) bitcoinPrice = (msg, currency) -> msg .send "Looking up... sit tight..." msg .http("http://bitcoinprices.com/") .get() (err, res, body) -> msg.send "#{getPrice(currency, body)}" getPrice = (currency, body) -> $ = cheerio.load(body) lastPrice = null highPrice = null lowPrice = null priceSymbol = null $('table.currencies td.symbol').each (i) -> if $(this).text() == currency priceSymbol = $(this).next().next().next().next().next().next().text() lastPrice = "#{priceSymbol}#{$(this).next().next().next().next().next().text()}" highPrice = "#{priceSymbol}#{$(this).next().next().next().text()}" lowPrice = "#{priceSymbol}#{$(this).next().next().next().next().text()}" false if lastPrice == null "Can't find the price for #{currency}. :(" else "#{currency}: #{lastPrice} (H: #{highPrice} | L: #{lowPrice})"
[ { "context": "지역> 대기오염도! - 원하는 지역의 대기오염도를 알려줍니다.\n#\n# Author:\n# myoungho.pak and jelly\n\n# require\nhttp = require 'http'\nmoment", "end": 175, "score": 0.8993144631385803, "start": 163, "tag": "NAME", "value": "myoungho.pak" }, { "context": "지역의 대기오염도를 알려줍니다.\n#\n# Author:\n# ...
scripts/dust.coffee
qkraudghgh/9xd-bot
33
# Description # API를 통해 대기오염도를 알려준다. # # Dependencies: # "http" # "moment" # "q" # # Commands: # 9xd <지역> 대기오염도! - 원하는 지역의 대기오염도를 알려줍니다. # # Author: # myoungho.pak and jelly # require http = require 'http' moment = require 'moment' q = require 'q' config = require '../config.json' # define constant dust_api_key = config.dust.key module.exports = (robot) -> robot.respond /(.*) 대기오염도!/i, (msg) -> location = decodeURIComponent(unescape(msg.match[1])) getGeocode(msg, location) .then (geoCode) -> getDust(msg, geoCode, location) .catch -> msg.send '지역 불러오기를 실패하였습니다.' getGeocode = (msg, location) -> deferred= q.defer() msg.http("https://maps.googleapis.com/maps/api/geocode/json") .query({ address: location }) .get() (err, res, body) -> response = JSON.parse(body) geo = response.results[0].geometry.location if response.status is "OK" geoCode = { lat : geo.lat lng : geo.lng } deferred.resolve(geoCode) else deferred.reject(err) return deferred.promise getDust = (msg, geoCode, location) -> msg.http("https://api.waqi.info/feed/geo:#{geoCode.lat};#{geoCode.lng}/?token=#{dust_api_key}") .get() (err, res, body) -> data = JSON.parse(body).data aqi = data.aqi if aqi > 300 grade = "위험(환자군 및 민감군에게 응급 조치가 발생되거나, 일반인에게 유해한 영향이 유발될 수 있는 수준)" else if aqi > 200 grade = "매우 나쁨(환자군 및 민감군에게 급성 노출시 심각한 영향 유발, 일반인도 약한 영향이 유발될 수 있는 수준)" else if aqi > 150 grade = "나쁨(환자군 및 민감군[어린이, 노약자 등]에게 유해한 영향 유발, 일반인도 건강상 불쾌감을 경험할 수 있는 수준)" else if aqi > 100 grade = "민감군 영향(환자군 및 민감군에게 유해한 영향이 유발될 수 있는 수준)" else if aqi > 50 grade = "보통(환자군에게 만성 노출시 경미한 영향이 유발될 수 있는 수준)" else grade = "좋음(대기오염 관련 질환자군에서도 영향이 유발되지 않을 수준)" time = moment().add(9, 'h').format('MM월 DD일 HH시') msg.send "현재시각 #{time} #{location}의 대기 품질 지수(AQI)는 `#{aqi}`이며 현재 대기상황 `#{grade}`입니다."
129002
# Description # API를 통해 대기오염도를 알려준다. # # Dependencies: # "http" # "moment" # "q" # # Commands: # 9xd <지역> 대기오염도! - 원하는 지역의 대기오염도를 알려줍니다. # # Author: # <NAME> and jelly # require http = require 'http' moment = require 'moment' q = require 'q' config = require '../config.json' # define constant dust_api_key = config.dust.key module.exports = (robot) -> robot.respond /(.*) 대기오염도!/i, (msg) -> location = decodeURIComponent(unescape(msg.match[1])) getGeocode(msg, location) .then (geoCode) -> getDust(msg, geoCode, location) .catch -> msg.send '지역 불러오기를 실패하였습니다.' getGeocode = (msg, location) -> deferred= q.defer() msg.http("https://maps.googleapis.com/maps/api/geocode/json") .query({ address: location }) .get() (err, res, body) -> response = JSON.parse(body) geo = response.results[0].geometry.location if response.status is "OK" geoCode = { lat : geo.lat lng : geo.lng } deferred.resolve(geoCode) else deferred.reject(err) return deferred.promise getDust = (msg, geoCode, location) -> msg.http("https://api.waqi.info/feed/geo:#{geoCode.lat};#{geoCode.lng}/?token=#{dust_api_key}") .get() (err, res, body) -> data = JSON.parse(body).data aqi = data.aqi if aqi > 300 grade = "위험(환자군 및 민감군에게 응급 조치가 발생되거나, 일반인에게 유해한 영향이 유발될 수 있는 수준)" else if aqi > 200 grade = "매우 나쁨(환자군 및 민감군에게 급성 노출시 심각한 영향 유발, 일반인도 약한 영향이 유발될 수 있는 수준)" else if aqi > 150 grade = "나쁨(환자군 및 민감군[어린이, 노약자 등]에게 유해한 영향 유발, 일반인도 건강상 불쾌감을 경험할 수 있는 수준)" else if aqi > 100 grade = "민감군 영향(환자군 및 민감군에게 유해한 영향이 유발될 수 있는 수준)" else if aqi > 50 grade = "보통(환자군에게 만성 노출시 경미한 영향이 유발될 수 있는 수준)" else grade = "좋음(대기오염 관련 질환자군에서도 영향이 유발되지 않을 수준)" time = moment().add(9, 'h').format('MM월 DD일 HH시') msg.send "현재시각 #{time} #{location}의 대기 품질 지수(AQI)는 `#{aqi}`이며 현재 대기상황 `#{grade}`입니다."
true
# Description # API를 통해 대기오염도를 알려준다. # # Dependencies: # "http" # "moment" # "q" # # Commands: # 9xd <지역> 대기오염도! - 원하는 지역의 대기오염도를 알려줍니다. # # Author: # PI:NAME:<NAME>END_PI and jelly # require http = require 'http' moment = require 'moment' q = require 'q' config = require '../config.json' # define constant dust_api_key = config.dust.key module.exports = (robot) -> robot.respond /(.*) 대기오염도!/i, (msg) -> location = decodeURIComponent(unescape(msg.match[1])) getGeocode(msg, location) .then (geoCode) -> getDust(msg, geoCode, location) .catch -> msg.send '지역 불러오기를 실패하였습니다.' getGeocode = (msg, location) -> deferred= q.defer() msg.http("https://maps.googleapis.com/maps/api/geocode/json") .query({ address: location }) .get() (err, res, body) -> response = JSON.parse(body) geo = response.results[0].geometry.location if response.status is "OK" geoCode = { lat : geo.lat lng : geo.lng } deferred.resolve(geoCode) else deferred.reject(err) return deferred.promise getDust = (msg, geoCode, location) -> msg.http("https://api.waqi.info/feed/geo:#{geoCode.lat};#{geoCode.lng}/?token=#{dust_api_key}") .get() (err, res, body) -> data = JSON.parse(body).data aqi = data.aqi if aqi > 300 grade = "위험(환자군 및 민감군에게 응급 조치가 발생되거나, 일반인에게 유해한 영향이 유발될 수 있는 수준)" else if aqi > 200 grade = "매우 나쁨(환자군 및 민감군에게 급성 노출시 심각한 영향 유발, 일반인도 약한 영향이 유발될 수 있는 수준)" else if aqi > 150 grade = "나쁨(환자군 및 민감군[어린이, 노약자 등]에게 유해한 영향 유발, 일반인도 건강상 불쾌감을 경험할 수 있는 수준)" else if aqi > 100 grade = "민감군 영향(환자군 및 민감군에게 유해한 영향이 유발될 수 있는 수준)" else if aqi > 50 grade = "보통(환자군에게 만성 노출시 경미한 영향이 유발될 수 있는 수준)" else grade = "좋음(대기오염 관련 질환자군에서도 영향이 유발되지 않을 수준)" time = moment().add(9, 'h').format('MM월 DD일 HH시') msg.send "현재시각 #{time} #{location}의 대기 품질 지수(AQI)는 `#{aqi}`이며 현재 대기상황 `#{grade}`입니다."
[ { "context": "')\n data = {\n persons: [\n { name: 'Wilfred' }, { name: 'Levi' }\n ]\n }\n expect(tem", "end": 346, "score": 0.9998116493225098, "start": 339, "tag": "NAME", "value": "Wilfred" }, { "context": " persons: [\n { name: 'Wilfred' }, { name...
test/model/pi-tests.coffee
admariner/cruftless
19
cruftless = require('../../src/cruftless') { element, attr, text, parse } = cruftless() describe 'processing instructions', -> it 'should allow you to use processing instructions to bind data', -> template = parse('<persons><person><?bind persons|array?>{{name}}</person></persons>') data = { persons: [ { name: 'Wilfred' }, { name: 'Levi' } ] } expect(template.toXML(data)).toEqual('<persons><person>Wilfred</person><person>Levi</person></persons>')
35108
cruftless = require('../../src/cruftless') { element, attr, text, parse } = cruftless() describe 'processing instructions', -> it 'should allow you to use processing instructions to bind data', -> template = parse('<persons><person><?bind persons|array?>{{name}}</person></persons>') data = { persons: [ { name: '<NAME>' }, { name: '<NAME>' } ] } expect(template.toXML(data)).toEqual('<persons><person><NAME></person><person><NAME></person></persons>')
true
cruftless = require('../../src/cruftless') { element, attr, text, parse } = cruftless() describe 'processing instructions', -> it 'should allow you to use processing instructions to bind data', -> template = parse('<persons><person><?bind persons|array?>{{name}}</person></persons>') data = { persons: [ { name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' } ] } expect(template.toXML(data)).toEqual('<persons><person>PI:NAME:<NAME>END_PI</person><person>PI:NAME:<NAME>END_PI</person></persons>')
[ { "context": "# Selector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Rubber band", "end": 26, "score": 0.9990269541740417, "start": 20, "tag": "NAME", "value": "Tomasz" }, { "context": "# Selector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Rubber band...
src/Selector.coffee
SachithDassanayaka/sachithdassanayaka.github.io
0
# Selector.coffee # Tomasz (Tomek) Zemla # tomek@datacratic.com # Rubber band style selector machanism that works in 3D. # The 3D selector is actually composed from three 2D selectors on each side of the cube. Utility = require('./Utility.coffee') Palette = require('./Palette.coffee') class Selector # M E M B E R S active : false # visible and active when true direction : Utility.DIRECTION.TOP # default 2D view is from top selectorTop : null # THREE.Line - top (along y axis) view selector selectorFront : null # THREE.Line - front (along z axis) view selector selectorSide : null # THREE.Line - top (along x axis) view selector mouseStart : null # mouse touch down mouse : null # mouse moving updates mouseEnd : null # mouse take off min : null # 3D selection bounds - minimum max : null # 3D selection bounds - maximum # C O N S T R U C T O R # Create selector and add it to the parent in 3D world. constructor : (parent) -> @mouseStart = new THREE.Vector3() @mouse = new THREE.Vector3() @mouseEnd = new THREE.Vector3() @min = new THREE.Vector3() @max = new THREE.Vector3() # top view @selectorTop = @createSelector(Utility.DIRECTION.TOP) parent.add(@selectorTop) # front view @selectorFront = @createSelector(Utility.DIRECTION.FRONT) parent.add(@selectorFront) # side view @selectorSide = @createSelector(Utility.DIRECTION.SIDE) parent.add(@selectorSide) @setActive(false) # M E T H D O S # Set selector active/visible on/off. # All side components work together. setActive : (@active) -> @selectorTop.visible = @active @selectorFront.visible = @active @selectorSide.visible = @active return @active # Set direction. setDirection : (@direction) -> console.log "Selector.setDirection " + @direction # Check if currently active/visible. isActive : => return @active # Toggle selector on/off toggle : => return @setActive(not @active) # Called at the start of the selection. start : (@mouse) -> @setActive(true) # automatically enable # two options: start new selection or adjust existing... if not @contains(mouse, @direction) # mouse outside the selector - restart anew @mouseStart = mouse else # mouse inside the selector - make adjustment # determine which corner is closest to the mouse switch @direction when Utility.DIRECTION.TOP @mouseStart = @getStart(mouse, @selectorTop) when Utility.DIRECTION.FRONT @mouseStart = @getStart(mouse, @selectorFront) when Utility.DIRECTION.SIDE @mouseStart = @getStart(mouse, @selectorSide) getStart : (mouse, selector) -> # determine which corner is closest to the mouse # TODO Set up array + loop... distanceTo0 = mouse.distanceTo(selector.geometry.vertices[0]) distanceTo1 = mouse.distanceTo(selector.geometry.vertices[1]) distanceTo2 = mouse.distanceTo(selector.geometry.vertices[2]) distanceTo3 = mouse.distanceTo(selector.geometry.vertices[3]) shortest = Math.min(distanceTo0, distanceTo1, distanceTo2, distanceTo3) # make the closest corner the end point and the opposite one the start point if shortest is distanceTo0 then start = selector.geometry.vertices[2].clone() if shortest is distanceTo1 then start = selector.geometry.vertices[3].clone() if shortest is distanceTo2 then start = selector.geometry.vertices[0].clone() if shortest is distanceTo3 then start = selector.geometry.vertices[1].clone() return start # Called when selection in progress to update mouse position. update : (@mouse) -> switch @direction when Utility.DIRECTION.TOP # Modifying : Top @selectorTop.geometry.vertices[0].x = @mouseStart.x @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[0].z = @mouseStart.z @selectorTop.geometry.vertices[1].x = @mouse.x @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[1].z = @mouseStart.z @selectorTop.geometry.vertices[2].x = @mouse.x @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[2].z = @mouse.z @selectorTop.geometry.vertices[3].x = @mouseStart.x @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[3].z = @mouse.z @selectorTop.geometry.vertices[4].x = @mouseStart.x @selectorTop.geometry.vertices[4].y = 100 @selectorTop.geometry.vertices[4].z = @mouseStart.z # Adjusting : Front @selectorFront.geometry.vertices[0].x = @mouseStart.x @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].x = @mouse.x @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].x = @mouse.x @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].x = @mouseStart.x @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].x = @mouseStart.x @selectorFront.geometry.vertices[4].z = 100 # Adjusting : Side @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].z = @mouseStart.z @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].z = @mouseStart.z @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].z = @mouse.z @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].z = @mouse.z @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].z = @mouseStart.z when Utility.DIRECTION.FRONT # Modifying : FRONT @selectorFront.geometry.vertices[0].x = @mouseStart.x @selectorFront.geometry.vertices[0].y = @mouseStart.y @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].x = @mouse.x @selectorFront.geometry.vertices[1].y = @mouseStart.y @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].x = @mouse.x @selectorFront.geometry.vertices[2].y = @mouse.y @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].x = @mouseStart.x @selectorFront.geometry.vertices[3].y = @mouse.y @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].x = @mouseStart.x @selectorFront.geometry.vertices[4].y = @mouseStart.y @selectorFront.geometry.vertices[4].z = 100 # Adjusting : TOP @selectorTop.geometry.vertices[0].x = @mouseStart.x @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[1].x = @mouse.x @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[2].x = @mouse.x @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[3].x = @mouseStart.x @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[4].x = @mouseStart.x @selectorTop.geometry.vertices[4].y = 100 # Adjusting : SIDE @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].y = @mouseStart.y @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].y = @mouse.y @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].y = @mouse.y @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].y = @mouseStart.y @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].y = @mouseStart.y when Utility.DIRECTION.SIDE # Modifying : SIDE @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].y = @mouseStart.y @selectorSide.geometry.vertices[0].z = @mouseStart.z @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].y = @mouse.y @selectorSide.geometry.vertices[1].z = @mouseStart.z @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].y = @mouse.y @selectorSide.geometry.vertices[2].z = @mouse.z @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].y = @mouseStart.y @selectorSide.geometry.vertices[3].z = @mouse.z @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].y = @mouseStart.y @selectorSide.geometry.vertices[4].z = @mouseStart.z # Adjusting : TOP @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[0].z = @mouseStart.z @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[1].z = @mouseStart.z @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[2].z = @mouse.z @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[3].z = @mouse.z @selectorTop.geometry.vertices[4].y = 100 @selectorTop.geometry.vertices[4].z = @mouseStart.z # Adjusting : FRONT @selectorFront.geometry.vertices[0].y = @mouseStart.y @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].y = @mouseStart.y @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].y = @mouse.y @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].y = @mouse.y @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].y = @mouseStart.y @selectorFront.geometry.vertices[4].z = 100 @selectorTop.geometry.verticesNeedUpdate = true @selectorFront.geometry.verticesNeedUpdate = true @selectorSide.geometry.verticesNeedUpdate = true # Called at the end of the selection. end : (mouseEnd) -> @mouseEnd = mouseEnd @updateBounds() updateBounds : -> @min.x = Math.min( @getMinX(@selectorTop), @getMinX(@selectorFront) ) @max.x = Math.max( @getMaxX(@selectorTop), @getMaxX(@selectorFront) ) @min.y = Math.min( @getMinY(@selectorFront), @getMinY(@selectorSide) ) @max.y = Math.max( @getMaxY(@selectorFront), @getMaxY(@selectorSide) ) @min.z = Math.min( @getMinZ(@selectorTop), @getMinZ(@selectorSide) ) @max.z = Math.max( @getMaxZ(@selectorTop), @getMaxZ(@selectorSide) ) # DEBUG # Utility.printVector3(@min) # Utility.printVector3(@max) # Return true if given point is within the selector, false otherwise. # NOTE For each individual direction only two coordinates are checked. # NOTE In case of direction ALL, all three coordinates are tested. contains : (point, direction) -> inside = true switch direction when Utility.DIRECTION.ALL if point.x < @min.x or point.x > @max.x then inside = false if point.y < @min.y or point.y > @max.y then inside = false if point.z < @min.z or point.z > @max.z then inside = false when Utility.DIRECTION.TOP if point.x < @min.x or point.x > @max.x then inside = false if point.z < @min.z or point.z > @max.z then inside = false when Utility.DIRECTION.FRONT if point.x < @min.x or point.x > @max.x then inside = false if point.y < @min.y or point.y > @max.y then inside = false when Utility.DIRECTION.SIDE if point.z < @min.z or point.z > @max.z then inside = false if point.y < @min.y or point.y > @max.y then inside = false return inside getMinX : (selector) -> vertices = selector.geometry.vertices minX = vertices[0].x for i in [1..4] if vertices[i].x < minX then minX = vertices[i].x return minX getMaxX : (selector) -> vertices = selector.geometry.vertices maxX = vertices[0].x for i in [1..4] if vertices[i].x > maxX then maxX = vertices[i].x return maxX getMinY : (selector) -> vertices = selector.geometry.vertices minY = vertices[0].y for i in [1..4] if vertices[i].y < minY then minY = vertices[i].y return minY getMaxY : (selector) -> vertices = selector.geometry.vertices maxY = vertices[0].y for i in [1..4] if vertices[i].y > maxY then maxY = vertices[i].y return maxY getMinZ : (selector) -> vertices = selector.geometry.vertices minZ = vertices[0].z for i in [1..4] if vertices[i].z < minZ then minZ = vertices[i].z return minZ getMaxZ : (selector) -> vertices = selector.geometry.vertices maxZ = vertices[0].z for i in [1..4] if vertices[i].z > maxZ then maxZ = vertices[i].z return maxZ # Create selector rectangle line for given direction. createSelector : (direction) -> SIZE = 100 geometry = new THREE.Geometry() # five points in each case, last one is the first one switch direction when Utility.DIRECTION.TOP geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) when Utility.DIRECTION.FRONT geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) when Utility.DIRECTION.SIDE geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) selector = new THREE.Line(geometry, new THREE.LineBasicMaterial( { color : Palette.SELECTOR.getHex() } ), THREE.LineStrip) module.exports = Selector
429
# Selector.coffee # <NAME> (<NAME> # <EMAIL> # Rubber band style selector machanism that works in 3D. # The 3D selector is actually composed from three 2D selectors on each side of the cube. Utility = require('./Utility.coffee') Palette = require('./Palette.coffee') class Selector # M E M B E R S active : false # visible and active when true direction : Utility.DIRECTION.TOP # default 2D view is from top selectorTop : null # THREE.Line - top (along y axis) view selector selectorFront : null # THREE.Line - front (along z axis) view selector selectorSide : null # THREE.Line - top (along x axis) view selector mouseStart : null # mouse touch down mouse : null # mouse moving updates mouseEnd : null # mouse take off min : null # 3D selection bounds - minimum max : null # 3D selection bounds - maximum # C O N S T R U C T O R # Create selector and add it to the parent in 3D world. constructor : (parent) -> @mouseStart = new THREE.Vector3() @mouse = new THREE.Vector3() @mouseEnd = new THREE.Vector3() @min = new THREE.Vector3() @max = new THREE.Vector3() # top view @selectorTop = @createSelector(Utility.DIRECTION.TOP) parent.add(@selectorTop) # front view @selectorFront = @createSelector(Utility.DIRECTION.FRONT) parent.add(@selectorFront) # side view @selectorSide = @createSelector(Utility.DIRECTION.SIDE) parent.add(@selectorSide) @setActive(false) # M E T H D O S # Set selector active/visible on/off. # All side components work together. setActive : (@active) -> @selectorTop.visible = @active @selectorFront.visible = @active @selectorSide.visible = @active return @active # Set direction. setDirection : (@direction) -> console.log "Selector.setDirection " + @direction # Check if currently active/visible. isActive : => return @active # Toggle selector on/off toggle : => return @setActive(not @active) # Called at the start of the selection. start : (@mouse) -> @setActive(true) # automatically enable # two options: start new selection or adjust existing... if not @contains(mouse, @direction) # mouse outside the selector - restart anew @mouseStart = mouse else # mouse inside the selector - make adjustment # determine which corner is closest to the mouse switch @direction when Utility.DIRECTION.TOP @mouseStart = @getStart(mouse, @selectorTop) when Utility.DIRECTION.FRONT @mouseStart = @getStart(mouse, @selectorFront) when Utility.DIRECTION.SIDE @mouseStart = @getStart(mouse, @selectorSide) getStart : (mouse, selector) -> # determine which corner is closest to the mouse # TODO Set up array + loop... distanceTo0 = mouse.distanceTo(selector.geometry.vertices[0]) distanceTo1 = mouse.distanceTo(selector.geometry.vertices[1]) distanceTo2 = mouse.distanceTo(selector.geometry.vertices[2]) distanceTo3 = mouse.distanceTo(selector.geometry.vertices[3]) shortest = Math.min(distanceTo0, distanceTo1, distanceTo2, distanceTo3) # make the closest corner the end point and the opposite one the start point if shortest is distanceTo0 then start = selector.geometry.vertices[2].clone() if shortest is distanceTo1 then start = selector.geometry.vertices[3].clone() if shortest is distanceTo2 then start = selector.geometry.vertices[0].clone() if shortest is distanceTo3 then start = selector.geometry.vertices[1].clone() return start # Called when selection in progress to update mouse position. update : (@mouse) -> switch @direction when Utility.DIRECTION.TOP # Modifying : Top @selectorTop.geometry.vertices[0].x = @mouseStart.x @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[0].z = @mouseStart.z @selectorTop.geometry.vertices[1].x = @mouse.x @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[1].z = @mouseStart.z @selectorTop.geometry.vertices[2].x = @mouse.x @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[2].z = @mouse.z @selectorTop.geometry.vertices[3].x = @mouseStart.x @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[3].z = @mouse.z @selectorTop.geometry.vertices[4].x = @mouseStart.x @selectorTop.geometry.vertices[4].y = 100 @selectorTop.geometry.vertices[4].z = @mouseStart.z # Adjusting : Front @selectorFront.geometry.vertices[0].x = @mouseStart.x @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].x = @mouse.x @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].x = @mouse.x @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].x = @mouseStart.x @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].x = @mouseStart.x @selectorFront.geometry.vertices[4].z = 100 # Adjusting : Side @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].z = @mouseStart.z @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].z = @mouseStart.z @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].z = @mouse.z @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].z = @mouse.z @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].z = @mouseStart.z when Utility.DIRECTION.FRONT # Modifying : FRONT @selectorFront.geometry.vertices[0].x = @mouseStart.x @selectorFront.geometry.vertices[0].y = @mouseStart.y @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].x = @mouse.x @selectorFront.geometry.vertices[1].y = @mouseStart.y @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].x = @mouse.x @selectorFront.geometry.vertices[2].y = @mouse.y @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].x = @mouseStart.x @selectorFront.geometry.vertices[3].y = @mouse.y @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].x = @mouseStart.x @selectorFront.geometry.vertices[4].y = @mouseStart.y @selectorFront.geometry.vertices[4].z = 100 # Adjusting : TOP @selectorTop.geometry.vertices[0].x = @mouseStart.x @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[1].x = @mouse.x @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[2].x = @mouse.x @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[3].x = @mouseStart.x @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[4].x = @mouseStart.x @selectorTop.geometry.vertices[4].y = 100 # Adjusting : SIDE @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].y = @mouseStart.y @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].y = @mouse.y @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].y = @mouse.y @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].y = @mouseStart.y @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].y = @mouseStart.y when Utility.DIRECTION.SIDE # Modifying : SIDE @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].y = @mouseStart.y @selectorSide.geometry.vertices[0].z = @mouseStart.z @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].y = @mouse.y @selectorSide.geometry.vertices[1].z = @mouseStart.z @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].y = @mouse.y @selectorSide.geometry.vertices[2].z = @mouse.z @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].y = @mouseStart.y @selectorSide.geometry.vertices[3].z = @mouse.z @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].y = @mouseStart.y @selectorSide.geometry.vertices[4].z = @mouseStart.z # Adjusting : TOP @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[0].z = @mouseStart.z @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[1].z = @mouseStart.z @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[2].z = @mouse.z @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[3].z = @mouse.z @selectorTop.geometry.vertices[4].y = 100 @selectorTop.geometry.vertices[4].z = @mouseStart.z # Adjusting : FRONT @selectorFront.geometry.vertices[0].y = @mouseStart.y @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].y = @mouseStart.y @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].y = @mouse.y @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].y = @mouse.y @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].y = @mouseStart.y @selectorFront.geometry.vertices[4].z = 100 @selectorTop.geometry.verticesNeedUpdate = true @selectorFront.geometry.verticesNeedUpdate = true @selectorSide.geometry.verticesNeedUpdate = true # Called at the end of the selection. end : (mouseEnd) -> @mouseEnd = mouseEnd @updateBounds() updateBounds : -> @min.x = Math.min( @getMinX(@selectorTop), @getMinX(@selectorFront) ) @max.x = Math.max( @getMaxX(@selectorTop), @getMaxX(@selectorFront) ) @min.y = Math.min( @getMinY(@selectorFront), @getMinY(@selectorSide) ) @max.y = Math.max( @getMaxY(@selectorFront), @getMaxY(@selectorSide) ) @min.z = Math.min( @getMinZ(@selectorTop), @getMinZ(@selectorSide) ) @max.z = Math.max( @getMaxZ(@selectorTop), @getMaxZ(@selectorSide) ) # DEBUG # Utility.printVector3(@min) # Utility.printVector3(@max) # Return true if given point is within the selector, false otherwise. # NOTE For each individual direction only two coordinates are checked. # NOTE In case of direction ALL, all three coordinates are tested. contains : (point, direction) -> inside = true switch direction when Utility.DIRECTION.ALL if point.x < @min.x or point.x > @max.x then inside = false if point.y < @min.y or point.y > @max.y then inside = false if point.z < @min.z or point.z > @max.z then inside = false when Utility.DIRECTION.TOP if point.x < @min.x or point.x > @max.x then inside = false if point.z < @min.z or point.z > @max.z then inside = false when Utility.DIRECTION.FRONT if point.x < @min.x or point.x > @max.x then inside = false if point.y < @min.y or point.y > @max.y then inside = false when Utility.DIRECTION.SIDE if point.z < @min.z or point.z > @max.z then inside = false if point.y < @min.y or point.y > @max.y then inside = false return inside getMinX : (selector) -> vertices = selector.geometry.vertices minX = vertices[0].x for i in [1..4] if vertices[i].x < minX then minX = vertices[i].x return minX getMaxX : (selector) -> vertices = selector.geometry.vertices maxX = vertices[0].x for i in [1..4] if vertices[i].x > maxX then maxX = vertices[i].x return maxX getMinY : (selector) -> vertices = selector.geometry.vertices minY = vertices[0].y for i in [1..4] if vertices[i].y < minY then minY = vertices[i].y return minY getMaxY : (selector) -> vertices = selector.geometry.vertices maxY = vertices[0].y for i in [1..4] if vertices[i].y > maxY then maxY = vertices[i].y return maxY getMinZ : (selector) -> vertices = selector.geometry.vertices minZ = vertices[0].z for i in [1..4] if vertices[i].z < minZ then minZ = vertices[i].z return minZ getMaxZ : (selector) -> vertices = selector.geometry.vertices maxZ = vertices[0].z for i in [1..4] if vertices[i].z > maxZ then maxZ = vertices[i].z return maxZ # Create selector rectangle line for given direction. createSelector : (direction) -> SIZE = 100 geometry = new THREE.Geometry() # five points in each case, last one is the first one switch direction when Utility.DIRECTION.TOP geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) when Utility.DIRECTION.FRONT geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) when Utility.DIRECTION.SIDE geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) selector = new THREE.Line(geometry, new THREE.LineBasicMaterial( { color : Palette.SELECTOR.getHex() } ), THREE.LineStrip) module.exports = Selector
true
# Selector.coffee # PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI # PI:EMAIL:<EMAIL>END_PI # Rubber band style selector machanism that works in 3D. # The 3D selector is actually composed from three 2D selectors on each side of the cube. Utility = require('./Utility.coffee') Palette = require('./Palette.coffee') class Selector # M E M B E R S active : false # visible and active when true direction : Utility.DIRECTION.TOP # default 2D view is from top selectorTop : null # THREE.Line - top (along y axis) view selector selectorFront : null # THREE.Line - front (along z axis) view selector selectorSide : null # THREE.Line - top (along x axis) view selector mouseStart : null # mouse touch down mouse : null # mouse moving updates mouseEnd : null # mouse take off min : null # 3D selection bounds - minimum max : null # 3D selection bounds - maximum # C O N S T R U C T O R # Create selector and add it to the parent in 3D world. constructor : (parent) -> @mouseStart = new THREE.Vector3() @mouse = new THREE.Vector3() @mouseEnd = new THREE.Vector3() @min = new THREE.Vector3() @max = new THREE.Vector3() # top view @selectorTop = @createSelector(Utility.DIRECTION.TOP) parent.add(@selectorTop) # front view @selectorFront = @createSelector(Utility.DIRECTION.FRONT) parent.add(@selectorFront) # side view @selectorSide = @createSelector(Utility.DIRECTION.SIDE) parent.add(@selectorSide) @setActive(false) # M E T H D O S # Set selector active/visible on/off. # All side components work together. setActive : (@active) -> @selectorTop.visible = @active @selectorFront.visible = @active @selectorSide.visible = @active return @active # Set direction. setDirection : (@direction) -> console.log "Selector.setDirection " + @direction # Check if currently active/visible. isActive : => return @active # Toggle selector on/off toggle : => return @setActive(not @active) # Called at the start of the selection. start : (@mouse) -> @setActive(true) # automatically enable # two options: start new selection or adjust existing... if not @contains(mouse, @direction) # mouse outside the selector - restart anew @mouseStart = mouse else # mouse inside the selector - make adjustment # determine which corner is closest to the mouse switch @direction when Utility.DIRECTION.TOP @mouseStart = @getStart(mouse, @selectorTop) when Utility.DIRECTION.FRONT @mouseStart = @getStart(mouse, @selectorFront) when Utility.DIRECTION.SIDE @mouseStart = @getStart(mouse, @selectorSide) getStart : (mouse, selector) -> # determine which corner is closest to the mouse # TODO Set up array + loop... distanceTo0 = mouse.distanceTo(selector.geometry.vertices[0]) distanceTo1 = mouse.distanceTo(selector.geometry.vertices[1]) distanceTo2 = mouse.distanceTo(selector.geometry.vertices[2]) distanceTo3 = mouse.distanceTo(selector.geometry.vertices[3]) shortest = Math.min(distanceTo0, distanceTo1, distanceTo2, distanceTo3) # make the closest corner the end point and the opposite one the start point if shortest is distanceTo0 then start = selector.geometry.vertices[2].clone() if shortest is distanceTo1 then start = selector.geometry.vertices[3].clone() if shortest is distanceTo2 then start = selector.geometry.vertices[0].clone() if shortest is distanceTo3 then start = selector.geometry.vertices[1].clone() return start # Called when selection in progress to update mouse position. update : (@mouse) -> switch @direction when Utility.DIRECTION.TOP # Modifying : Top @selectorTop.geometry.vertices[0].x = @mouseStart.x @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[0].z = @mouseStart.z @selectorTop.geometry.vertices[1].x = @mouse.x @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[1].z = @mouseStart.z @selectorTop.geometry.vertices[2].x = @mouse.x @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[2].z = @mouse.z @selectorTop.geometry.vertices[3].x = @mouseStart.x @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[3].z = @mouse.z @selectorTop.geometry.vertices[4].x = @mouseStart.x @selectorTop.geometry.vertices[4].y = 100 @selectorTop.geometry.vertices[4].z = @mouseStart.z # Adjusting : Front @selectorFront.geometry.vertices[0].x = @mouseStart.x @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].x = @mouse.x @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].x = @mouse.x @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].x = @mouseStart.x @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].x = @mouseStart.x @selectorFront.geometry.vertices[4].z = 100 # Adjusting : Side @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].z = @mouseStart.z @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].z = @mouseStart.z @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].z = @mouse.z @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].z = @mouse.z @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].z = @mouseStart.z when Utility.DIRECTION.FRONT # Modifying : FRONT @selectorFront.geometry.vertices[0].x = @mouseStart.x @selectorFront.geometry.vertices[0].y = @mouseStart.y @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].x = @mouse.x @selectorFront.geometry.vertices[1].y = @mouseStart.y @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].x = @mouse.x @selectorFront.geometry.vertices[2].y = @mouse.y @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].x = @mouseStart.x @selectorFront.geometry.vertices[3].y = @mouse.y @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].x = @mouseStart.x @selectorFront.geometry.vertices[4].y = @mouseStart.y @selectorFront.geometry.vertices[4].z = 100 # Adjusting : TOP @selectorTop.geometry.vertices[0].x = @mouseStart.x @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[1].x = @mouse.x @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[2].x = @mouse.x @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[3].x = @mouseStart.x @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[4].x = @mouseStart.x @selectorTop.geometry.vertices[4].y = 100 # Adjusting : SIDE @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].y = @mouseStart.y @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].y = @mouse.y @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].y = @mouse.y @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].y = @mouseStart.y @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].y = @mouseStart.y when Utility.DIRECTION.SIDE # Modifying : SIDE @selectorSide.geometry.vertices[0].x = 100 @selectorSide.geometry.vertices[0].y = @mouseStart.y @selectorSide.geometry.vertices[0].z = @mouseStart.z @selectorSide.geometry.vertices[1].x = 100 @selectorSide.geometry.vertices[1].y = @mouse.y @selectorSide.geometry.vertices[1].z = @mouseStart.z @selectorSide.geometry.vertices[2].x = 100 @selectorSide.geometry.vertices[2].y = @mouse.y @selectorSide.geometry.vertices[2].z = @mouse.z @selectorSide.geometry.vertices[3].x = 100 @selectorSide.geometry.vertices[3].y = @mouseStart.y @selectorSide.geometry.vertices[3].z = @mouse.z @selectorSide.geometry.vertices[4].x = 100 @selectorSide.geometry.vertices[4].y = @mouseStart.y @selectorSide.geometry.vertices[4].z = @mouseStart.z # Adjusting : TOP @selectorTop.geometry.vertices[0].y = 100 @selectorTop.geometry.vertices[0].z = @mouseStart.z @selectorTop.geometry.vertices[1].y = 100 @selectorTop.geometry.vertices[1].z = @mouseStart.z @selectorTop.geometry.vertices[2].y = 100 @selectorTop.geometry.vertices[2].z = @mouse.z @selectorTop.geometry.vertices[3].y = 100 @selectorTop.geometry.vertices[3].z = @mouse.z @selectorTop.geometry.vertices[4].y = 100 @selectorTop.geometry.vertices[4].z = @mouseStart.z # Adjusting : FRONT @selectorFront.geometry.vertices[0].y = @mouseStart.y @selectorFront.geometry.vertices[0].z = 100 @selectorFront.geometry.vertices[1].y = @mouseStart.y @selectorFront.geometry.vertices[1].z = 100 @selectorFront.geometry.vertices[2].y = @mouse.y @selectorFront.geometry.vertices[2].z = 100 @selectorFront.geometry.vertices[3].y = @mouse.y @selectorFront.geometry.vertices[3].z = 100 @selectorFront.geometry.vertices[4].y = @mouseStart.y @selectorFront.geometry.vertices[4].z = 100 @selectorTop.geometry.verticesNeedUpdate = true @selectorFront.geometry.verticesNeedUpdate = true @selectorSide.geometry.verticesNeedUpdate = true # Called at the end of the selection. end : (mouseEnd) -> @mouseEnd = mouseEnd @updateBounds() updateBounds : -> @min.x = Math.min( @getMinX(@selectorTop), @getMinX(@selectorFront) ) @max.x = Math.max( @getMaxX(@selectorTop), @getMaxX(@selectorFront) ) @min.y = Math.min( @getMinY(@selectorFront), @getMinY(@selectorSide) ) @max.y = Math.max( @getMaxY(@selectorFront), @getMaxY(@selectorSide) ) @min.z = Math.min( @getMinZ(@selectorTop), @getMinZ(@selectorSide) ) @max.z = Math.max( @getMaxZ(@selectorTop), @getMaxZ(@selectorSide) ) # DEBUG # Utility.printVector3(@min) # Utility.printVector3(@max) # Return true if given point is within the selector, false otherwise. # NOTE For each individual direction only two coordinates are checked. # NOTE In case of direction ALL, all three coordinates are tested. contains : (point, direction) -> inside = true switch direction when Utility.DIRECTION.ALL if point.x < @min.x or point.x > @max.x then inside = false if point.y < @min.y or point.y > @max.y then inside = false if point.z < @min.z or point.z > @max.z then inside = false when Utility.DIRECTION.TOP if point.x < @min.x or point.x > @max.x then inside = false if point.z < @min.z or point.z > @max.z then inside = false when Utility.DIRECTION.FRONT if point.x < @min.x or point.x > @max.x then inside = false if point.y < @min.y or point.y > @max.y then inside = false when Utility.DIRECTION.SIDE if point.z < @min.z or point.z > @max.z then inside = false if point.y < @min.y or point.y > @max.y then inside = false return inside getMinX : (selector) -> vertices = selector.geometry.vertices minX = vertices[0].x for i in [1..4] if vertices[i].x < minX then minX = vertices[i].x return minX getMaxX : (selector) -> vertices = selector.geometry.vertices maxX = vertices[0].x for i in [1..4] if vertices[i].x > maxX then maxX = vertices[i].x return maxX getMinY : (selector) -> vertices = selector.geometry.vertices minY = vertices[0].y for i in [1..4] if vertices[i].y < minY then minY = vertices[i].y return minY getMaxY : (selector) -> vertices = selector.geometry.vertices maxY = vertices[0].y for i in [1..4] if vertices[i].y > maxY then maxY = vertices[i].y return maxY getMinZ : (selector) -> vertices = selector.geometry.vertices minZ = vertices[0].z for i in [1..4] if vertices[i].z < minZ then minZ = vertices[i].z return minZ getMaxZ : (selector) -> vertices = selector.geometry.vertices maxZ = vertices[0].z for i in [1..4] if vertices[i].z > maxZ then maxZ = vertices[i].z return maxZ # Create selector rectangle line for given direction. createSelector : (direction) -> SIZE = 100 geometry = new THREE.Geometry() # five points in each case, last one is the first one switch direction when Utility.DIRECTION.TOP geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) when Utility.DIRECTION.FRONT geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( -SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) when Utility.DIRECTION.SIDE geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, +SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, -SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, -SIZE ) ) geometry.vertices.push( new THREE.Vector3( +SIZE, +SIZE, +SIZE ) ) selector = new THREE.Line(geometry, new THREE.LineBasicMaterial( { color : Palette.SELECTOR.getHex() } ), THREE.LineStrip) module.exports = Selector
[ { "context": "->\n @action = 'posts/index'\n @name = 'default'\n @response = JSON.stringify({ posts: [{ title", "end": 153, "score": 0.8754228353500366, "start": 146, "tag": "USERNAME", "value": "default" }, { "context": " @response = JSON.stringify({ posts: [{ title...
spec/javascripts/alfred/sinon_adapter_spec.js.coffee
jhnvz/alfred
1
#= require alfred #= require alfred/sinon_adapter describe 'Alfred.SinonAdapter', -> before -> @action = 'posts/index' @name = 'default' @response = JSON.stringify({ posts: [{ title: 'Hi there' }] }) @meta = { path: 'posts' method: 'GET' status: 200 type: 'application/json' } Alfred.register({ action: @action, name: @name, meta: @meta, response: @response }) @scenario = Alfred.scenarios[@action][@name] describe 'serve', -> it 'should setup a sinon fakeServer', -> server = Alfred.SinonAdapter.serve(@action, @name) response = server.responses[0] response.method.should.equal('GET') response.url.should.equal('posts')
148833
#= require alfred #= require alfred/sinon_adapter describe 'Alfred.SinonAdapter', -> before -> @action = 'posts/index' @name = 'default' @response = JSON.stringify({ posts: [{ title: '<NAME>' }] }) @meta = { path: 'posts' method: 'GET' status: 200 type: 'application/json' } Alfred.register({ action: @action, name: @name, meta: @meta, response: @response }) @scenario = Alfred.scenarios[@action][@name] describe 'serve', -> it 'should setup a sinon fakeServer', -> server = Alfred.SinonAdapter.serve(@action, @name) response = server.responses[0] response.method.should.equal('GET') response.url.should.equal('posts')
true
#= require alfred #= require alfred/sinon_adapter describe 'Alfred.SinonAdapter', -> before -> @action = 'posts/index' @name = 'default' @response = JSON.stringify({ posts: [{ title: 'PI:NAME:<NAME>END_PI' }] }) @meta = { path: 'posts' method: 'GET' status: 200 type: 'application/json' } Alfred.register({ action: @action, name: @name, meta: @meta, response: @response }) @scenario = Alfred.scenarios[@action][@name] describe 'serve', -> it 'should setup a sinon fakeServer', -> server = Alfred.SinonAdapter.serve(@action, @name) response = server.responses[0] response.method.should.equal('GET') response.url.should.equal('posts')
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992628693580627, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-next-tick-error-spin.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") if process.argv[2] isnt "child" spawn = require("child_process").spawn child = spawn(process.execPath, [ __filename "child" ], stdio: "pipe" #'inherit' ) timer = setTimeout(-> throw new Error("child is hung")return , 3000) child.on "exit", (code) -> console.error "ok" assert not code clearTimeout timer return else # in the error handler, we trigger several MakeCallback events f = -> process.nextTick -> d.run -> throw (new Error("x"))return return return domain = require("domain") d = domain.create() process.maxTickDepth = 10 d.on "error", (e) -> console.log "a" console.log "b" console.log "c" console.log "d" console.log "e" f() return f() setTimeout -> console.error "broke in!" #process.stdout.close(); #process.stderr.close(); process.exit 0 return
30136
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") if process.argv[2] isnt "child" spawn = require("child_process").spawn child = spawn(process.execPath, [ __filename "child" ], stdio: "pipe" #'inherit' ) timer = setTimeout(-> throw new Error("child is hung")return , 3000) child.on "exit", (code) -> console.error "ok" assert not code clearTimeout timer return else # in the error handler, we trigger several MakeCallback events f = -> process.nextTick -> d.run -> throw (new Error("x"))return return return domain = require("domain") d = domain.create() process.maxTickDepth = 10 d.on "error", (e) -> console.log "a" console.log "b" console.log "c" console.log "d" console.log "e" f() return f() setTimeout -> console.error "broke in!" #process.stdout.close(); #process.stderr.close(); process.exit 0 return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") if process.argv[2] isnt "child" spawn = require("child_process").spawn child = spawn(process.execPath, [ __filename "child" ], stdio: "pipe" #'inherit' ) timer = setTimeout(-> throw new Error("child is hung")return , 3000) child.on "exit", (code) -> console.error "ok" assert not code clearTimeout timer return else # in the error handler, we trigger several MakeCallback events f = -> process.nextTick -> d.run -> throw (new Error("x"))return return return domain = require("domain") d = domain.create() process.maxTickDepth = 10 d.on "error", (e) -> console.log "a" console.log "b" console.log "c" console.log "d" console.log "e" f() return f() setTimeout -> console.error "broke in!" #process.stdout.close(); #process.stderr.close(); process.exit 0 return
[ { "context": "##\n backbone-mongo.js 0.6.10\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo\n Li", "end": 60, "score": 0.9992162585258484, "start": 52, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/...
src/lib/connection.coffee
vidigami/backbone-mongo
1
### backbone-mongo.js 0.6.10 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {MongoClient} = require 'mongodb' {_, Queue, DatabaseURL, ConnectionPool} = require 'backbone-orm' BackboneMongo = require '../core' CONNECTION_QUERIES = require './connection_queries' module.exports = class Connection constructor: (@url, @schema={}, options={}) -> throw new Error 'Expecting a string url' unless _.isString(@url) @connection_options = _.extend({}, BackboneMongo.connection_options, options) @collection_requests = [] @db = null database_url = new DatabaseURL(@url, true) @collection_name = database_url.table # configure query options and regenerate URL database_url.query or= {}; delete database_url.search # allow for non-url options to be specified on the url (for example, journal) @connection_options[key] = value for key, value of database_url.query database_url.query = {} # transfer options to the url (database_url.query[key] = @connection_options[key]; delete @connection_options[key]) for key in CONNECTION_QUERIES when @connection_options.hasOwnProperty(key) @url = database_url.format({exclude_table: true}) @_connect() destroy: -> return unless @db # already closed collection_requests = _.clone(@collection_requests); @collection_requests = [] request(new Error('Client closed')) for request in collection_requests @_collection = null @db.close(); @db = null collection: (callback) -> return callback(null, @_collection) if @_collection # wait for connection @collection_requests.push(callback) # try to reconnect (@connection_error = null; @_connect()) if @connection_error _connect: -> queue = new Queue(1) # use pooled connection or create new queue.defer (callback) => return callback() if (@db = ConnectionPool.get(@url)) MongoClient.connect @url, @connection_options, (err, db) => return callback(err) if err # it may have already been connected to asynchronously, release new if (@db = ConnectionPool.get(@url)) then db.close() else ConnectionPool.set(@url, @db = db) callback() # get the collection queue.defer (callback) => @db.collection @collection_name, (err, collection) => if err then callback(err) else callback(null, @_collection = collection) # process awaiting requests queue.await (err) => collection_requests = @collection_requests.splice(0, @collection_requests.length) if (@connection_error = err) console.log "BackboneMongo: unable to create connection. Error:", err request(new Error("Connection failed. Error: #{err.message or err}")) for request in collection_requests else request(null, @_collection) for request in collection_requests
20194
### backbone-mongo.js 0.6.10 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {MongoClient} = require 'mongodb' {_, Queue, DatabaseURL, ConnectionPool} = require 'backbone-orm' BackboneMongo = require '../core' CONNECTION_QUERIES = require './connection_queries' module.exports = class Connection constructor: (@url, @schema={}, options={}) -> throw new Error 'Expecting a string url' unless _.isString(@url) @connection_options = _.extend({}, BackboneMongo.connection_options, options) @collection_requests = [] @db = null database_url = new DatabaseURL(@url, true) @collection_name = database_url.table # configure query options and regenerate URL database_url.query or= {}; delete database_url.search # allow for non-url options to be specified on the url (for example, journal) @connection_options[key] = value for key, value of database_url.query database_url.query = {} # transfer options to the url (database_url.query[key] = @connection_options[key]; delete @connection_options[key]) for key in CONNECTION_QUERIES when @connection_options.hasOwnProperty(key) @url = database_url.format({exclude_table: true}) @_connect() destroy: -> return unless @db # already closed collection_requests = _.clone(@collection_requests); @collection_requests = [] request(new Error('Client closed')) for request in collection_requests @_collection = null @db.close(); @db = null collection: (callback) -> return callback(null, @_collection) if @_collection # wait for connection @collection_requests.push(callback) # try to reconnect (@connection_error = null; @_connect()) if @connection_error _connect: -> queue = new Queue(1) # use pooled connection or create new queue.defer (callback) => return callback() if (@db = ConnectionPool.get(@url)) MongoClient.connect @url, @connection_options, (err, db) => return callback(err) if err # it may have already been connected to asynchronously, release new if (@db = ConnectionPool.get(@url)) then db.close() else ConnectionPool.set(@url, @db = db) callback() # get the collection queue.defer (callback) => @db.collection @collection_name, (err, collection) => if err then callback(err) else callback(null, @_collection = collection) # process awaiting requests queue.await (err) => collection_requests = @collection_requests.splice(0, @collection_requests.length) if (@connection_error = err) console.log "BackboneMongo: unable to create connection. Error:", err request(new Error("Connection failed. Error: #{err.message or err}")) for request in collection_requests else request(null, @_collection) for request in collection_requests
true
### backbone-mongo.js 0.6.10 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {MongoClient} = require 'mongodb' {_, Queue, DatabaseURL, ConnectionPool} = require 'backbone-orm' BackboneMongo = require '../core' CONNECTION_QUERIES = require './connection_queries' module.exports = class Connection constructor: (@url, @schema={}, options={}) -> throw new Error 'Expecting a string url' unless _.isString(@url) @connection_options = _.extend({}, BackboneMongo.connection_options, options) @collection_requests = [] @db = null database_url = new DatabaseURL(@url, true) @collection_name = database_url.table # configure query options and regenerate URL database_url.query or= {}; delete database_url.search # allow for non-url options to be specified on the url (for example, journal) @connection_options[key] = value for key, value of database_url.query database_url.query = {} # transfer options to the url (database_url.query[key] = @connection_options[key]; delete @connection_options[key]) for key in CONNECTION_QUERIES when @connection_options.hasOwnProperty(key) @url = database_url.format({exclude_table: true}) @_connect() destroy: -> return unless @db # already closed collection_requests = _.clone(@collection_requests); @collection_requests = [] request(new Error('Client closed')) for request in collection_requests @_collection = null @db.close(); @db = null collection: (callback) -> return callback(null, @_collection) if @_collection # wait for connection @collection_requests.push(callback) # try to reconnect (@connection_error = null; @_connect()) if @connection_error _connect: -> queue = new Queue(1) # use pooled connection or create new queue.defer (callback) => return callback() if (@db = ConnectionPool.get(@url)) MongoClient.connect @url, @connection_options, (err, db) => return callback(err) if err # it may have already been connected to asynchronously, release new if (@db = ConnectionPool.get(@url)) then db.close() else ConnectionPool.set(@url, @db = db) callback() # get the collection queue.defer (callback) => @db.collection @collection_name, (err, collection) => if err then callback(err) else callback(null, @_collection = collection) # process awaiting requests queue.await (err) => collection_requests = @collection_requests.splice(0, @collection_requests.length) if (@connection_error = err) console.log "BackboneMongo: unable to create connection. Error:", err request(new Error("Connection failed. Error: #{err.message or err}")) for request in collection_requests else request(null, @_collection) for request in collection_requests
[ { "context": " @setHalfHours()\n\n setInstructor: ->\n # [ 'Nguyen,Trien T' ] => \"Trien T Nguyen\"\n @attributes.in", "end": 194, "score": 0.9997231364250183, "start": 188, "tag": "NAME", "value": "Nguyen" }, { "context": "tHalfHours()\n\n setInstructor: ->\n # [ 'Nguy...
app/models/class_meeting.coffee
christhomson/roomular
1
module.exports = class ClassMeeting constructor: (attributes) -> @attributes = attributes @setInstructor() @setClassType() @setHalfHours() setInstructor: -> # [ 'Nguyen,Trien T' ] => "Trien T Nguyen" @attributes.instructor = @attributes.instructors?[0]?.split(',')?.reverse()?.join(' ') || "Unknown Instructor" setClassType: -> # See https://uwaterloo.ca/quest/undergraduate-students/glossary-of-terms. @attributes.classType = switch(@attributes.section.split(' ')[0]) when 'CLN' then 'Clinic' when 'DIS' then 'Discussion' when 'ENS' then 'Ensemble' when 'ESS' then 'Essay' when 'FLD' then 'Field Studies' when 'LAB' then 'Lab' when 'LEC' then 'Lecture' when 'ORL' then 'Oral Conversation' when 'PRA' then 'Practicum' when 'PRJ' then 'Project' when 'RDG' then 'Reading' when 'SEM' then 'Seminar' when 'STU' then 'Studio' when 'TLC' then 'Test Slot - Lecture' when 'TST' then 'Test Slot' when 'TUT' then 'Tutorial' when 'WRK' then 'Work Term' when 'WSP' then 'Workshop' else 'Meeting' setHalfHours: -> startTime = @attributes.start_time.split(':') endTime = @attributes.end_time.split(':') hours = endTime[0] - startTime[0] minutes = endTime[1] - startTime[1] @attributes.halfHours = (hours * 2) + (Math.ceil(minutes / 30.0))
17197
module.exports = class ClassMeeting constructor: (attributes) -> @attributes = attributes @setInstructor() @setClassType() @setHalfHours() setInstructor: -> # [ '<NAME>,<NAME>' ] => "<NAME>" @attributes.instructor = @attributes.instructors?[0]?.split(',')?.reverse()?.join(' ') || "Unknown Instructor" setClassType: -> # See https://uwaterloo.ca/quest/undergraduate-students/glossary-of-terms. @attributes.classType = switch(@attributes.section.split(' ')[0]) when 'CLN' then 'Clinic' when 'DIS' then 'Discussion' when 'ENS' then 'Ensemble' when 'ESS' then 'Essay' when 'FLD' then 'Field Studies' when 'LAB' then 'Lab' when 'LEC' then 'Lecture' when 'ORL' then 'Oral Conversation' when 'PRA' then 'Practicum' when 'PRJ' then 'Project' when 'RDG' then 'Reading' when 'SEM' then 'Seminar' when 'STU' then 'Studio' when 'TLC' then 'Test Slot - Lecture' when 'TST' then 'Test Slot' when 'TUT' then 'Tutorial' when 'WRK' then 'Work Term' when 'WSP' then 'Workshop' else 'Meeting' setHalfHours: -> startTime = @attributes.start_time.split(':') endTime = @attributes.end_time.split(':') hours = endTime[0] - startTime[0] minutes = endTime[1] - startTime[1] @attributes.halfHours = (hours * 2) + (Math.ceil(minutes / 30.0))
true
module.exports = class ClassMeeting constructor: (attributes) -> @attributes = attributes @setInstructor() @setClassType() @setHalfHours() setInstructor: -> # [ 'PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI' ] => "PI:NAME:<NAME>END_PI" @attributes.instructor = @attributes.instructors?[0]?.split(',')?.reverse()?.join(' ') || "Unknown Instructor" setClassType: -> # See https://uwaterloo.ca/quest/undergraduate-students/glossary-of-terms. @attributes.classType = switch(@attributes.section.split(' ')[0]) when 'CLN' then 'Clinic' when 'DIS' then 'Discussion' when 'ENS' then 'Ensemble' when 'ESS' then 'Essay' when 'FLD' then 'Field Studies' when 'LAB' then 'Lab' when 'LEC' then 'Lecture' when 'ORL' then 'Oral Conversation' when 'PRA' then 'Practicum' when 'PRJ' then 'Project' when 'RDG' then 'Reading' when 'SEM' then 'Seminar' when 'STU' then 'Studio' when 'TLC' then 'Test Slot - Lecture' when 'TST' then 'Test Slot' when 'TUT' then 'Tutorial' when 'WRK' then 'Work Term' when 'WSP' then 'Workshop' else 'Meeting' setHalfHours: -> startTime = @attributes.start_time.split(':') endTime = @attributes.end_time.split(':') hours = endTime[0] - startTime[0] minutes = endTime[1] - startTime[1] @attributes.halfHours = (hours * 2) + (Math.ceil(minutes / 30.0))
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.9998359680175781, "start": 66, "tag": "NAME", "value": "Henri Bergius" }, { "context": "ense\n#\n# Image insertion plugin\n# ...
src/client/hallo/hallo/plugins/image.coffee
HansPinckaers/ShareJS-editor
4
# Hallo - a rich text editing jQuery UI widget # (c) 2011 Henri Bergius, IKS Consortium # Hallo may be freely distributed under the MIT license # # Image insertion plugin # Liip AG: Colin Frei, Reto Ryter, David Buchmann, Fabian Vogler, Bartosz Podlewski ((jQuery) -> jQuery.widget "Liip.halloimage", options: editable: null toolbar: null uuid: "" # number of thumbnails for paging in search results limit: 8 # this function is responsible to fetch search results # query: terms to search # limit: how many results to show at max # offset: offset for the returned result # successCallback: function that will be called with the response json object # the object has fields offset (the requested offset), total (total number of results) and assets (list of url and alt text for each image) search: null # this function is responsible to fetch suggestions for images to insert # this could for example be based on tags of the entity or some semantic enhancement, ... # # tags: tag information - TODO: do not expect that here but get it from context # limit: how many results to show at max # offset: offset for the returned result # successCallback: function that will be called with the response json object # the object has fields offset (the requested offset), total (total number of results) and assets (list of url and alt text for each image) suggestions: null loaded: null upload: null uploadUrl: null dialogOpts: autoOpen: false width: 270 height: "auto" title: "Insert Images" modal: false resizable: false draggable: true dialogClass: 'halloimage-dialog' close: (ev, ui) -> jQuery('.image_button').removeClass('ui-state-clicked') dialog: null buttonCssClass: null _create: -> widget = this dialogId = "#{@options.uuid}-image-dialog" @options.dialog = jQuery "<div id=\"#{dialogId}\"> <div class=\"nav\"> <ul class=\"tabs\"> </ul> <div id=\"#{@options.uuid}-tab-activeIndicator\" class=\"tab-activeIndicator\" /> </div> <div class=\"dialogcontent\"> </div>" if widget.options.uploadUrl and !widget.options.upload widget.options.upload = widget._iframeUpload if widget.options.suggestions @_addGuiTabSuggestions jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) if widget.options.search @_addGuiTabSearch jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) if widget.options.upload @_addGuiTabUpload jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>" id = "#{@options.uuid}-image" buttonHolder = jQuery '<span></span>' buttonHolder.hallobutton label: 'Images' icon: 'icon-picture' editable: @options.editable command: null queryState: false uuid: @options.uuid cssClass: @options.buttonCssClass buttonset.append buttonHolder button = buttonHolder button.bind "change", (event) -> if widget.options.dialog.dialog "isOpen" widget._closeDialog() else widget._openDialog() @options.editable.element.bind "hallodeactivated", (event) -> widget._closeDialog() jQuery(@options.editable.element).delegate "img", "click", (event) -> widget._openDialog() jQuery(@options.dialog).find(".nav li").click () -> jQuery(".#{widget.widgetName}-tab").each () -> jQuery(this).hide() id = jQuery(this).attr("id") jQuery("##{id}-content").show() jQuery("##{widget.options.uuid}-tab-activeIndicator").css("margin-left", jQuery(this).position().left + (jQuery(this).width()/2)) # Add action to image thumbnails jQuery(".#{widget.widgetName}-tab .imageThumbnail").live "click", (event) -> scope = jQuery(this).closest(".#{widget.widgetName}-tab") jQuery(".imageThumbnail", scope).removeClass "imageThumbnailActive" jQuery(this).addClass "imageThumbnailActive" jQuery(".activeImage", scope).attr "src", jQuery(this).attr "src" jQuery(".activeImageBg", scope).attr "src", jQuery(this).attr "src" buttonset.buttonset() @options.toolbar.append buttonset @options.dialog.dialog(@options.dialogOpts) # Add DragnDrop @_addDragnDrop() _init: -> _openDialog: -> widget = this cleanUp = -> window.setTimeout (-> thumbnails = jQuery(".imageThumbnail") jQuery(thumbnails).each -> size = jQuery("#" + @id).width() if size <= 20 jQuery("#" + @id).parent("li").remove() ), 15000 # cleanup after 15 sec repoImagesFound = false showResults = (response) -> # TODO: paging jQuery.each response.assets, (key, val) -> jQuery(".imageThumbnailContainer ul").append "<li><img src=\"" + val.url + "\" class=\"imageThumbnail\"></li>" repoImagesFound = true if response.assets.length > 0 jQuery("#activitySpinner").hide() # Update state of button in toolbar jQuery('.image_button').addClass('ui-state-clicked') # Update active Image jQuery("##{@options.uuid}-sugg-activeImage").attr "src", jQuery("##{@options.uuid}-tab-suggestions-content .imageThumbnailActive").first().attr "src" jQuery("##{@options.uuid}-sugg-activeImageBg").attr "src", jQuery("##{@options.uuid}-tab-suggestions-content .imageThumbnailActive").first().attr "src" # Save current caret point @lastSelection = @options.editable.getSelection() # Position correctly xposition = jQuery(@options.editable.element).offset().left + jQuery(@options.editable.element).outerWidth() - 3 # 3 is the border width of the contenteditable border yposition = jQuery(@options.toolbar).offset().top - jQuery(document).scrollTop() - 29 @options.dialog.dialog("option", "position", [xposition, yposition]) if widget.options.loaded is null && widget.options.suggestions articleTags = [] jQuery("#activitySpinner").show() tmpArticleTags = jQuery(".inEditMode").parent().find(".articleTags input").val() tmpArticleTags = tmpArticleTags.split(",") for i of tmpArticleTags tagType = typeof tmpArticleTags[i] if "string" == tagType && tmpArticleTags[i].indexOf("http") != -1 articleTags.push tmpArticleTags[i] jQuery(".imageThumbnailContainer ul").empty() widget.options.suggestions(jQuery(".inEditMode").parent().find(".articleTags input").val(), widget.options.limit, 0, showResults) vie = new VIE() vie.use new vie.DBPediaService( url: "http://dev.iks-project.eu/stanbolfull" proxyDisabled: true ) thumbId = 1 if articleTags.length is 0 jQuery("#activitySpinner").html "No images found." jQuery(articleTags).each -> vie.load(entity: this + "").using("dbpedia").execute().done (entity) -> jQuery(entity).each -> if @attributes["<http://dbpedia.org/ontology/thumbnail>"] responseType = typeof (@attributes["<http://dbpedia.org/ontology/thumbnail>"]) if responseType is "string" img = @attributes["<http://dbpedia.org/ontology/thumbnail>"] img = img.substring(1, img.length - 1) if responseType is "object" img = "" img = @attributes["<http://dbpedia.org/ontology/thumbnail>"][0].value jQuery(".imageThumbnailContainer ul").append "<li><img id=\"si-#{thumbId}\" src=\"#{img}\" class=\"imageThumbnail\"></li>" thumbId++ jQuery("#activitySpinner").hide() cleanUp() widget.options.loaded = 1 @options.dialog.dialog("open") @options.editable.protectFocusFrom @options.dialog _closeDialog: -> @options.dialog.dialog("close") _addGuiTabSuggestions: (tabs, element) -> widget = this tabs.append jQuery "<li id=\"#{@options.uuid}-tab-suggestions\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-suggestions\"><span>Suggestions</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-suggestions-content\" class=\"#{widget.widgetName}-tab tab-suggestions\"> <div class=\"imageThumbnailContainer fixed\"><div id=\"activitySpinner\">Loading Images...</div><ul><li> <img src=\"http://imagesus.homeaway.com/mda01/badf2e69babf2f6a0e4b680fc373c041c705b891\" class=\"imageThumbnail imageThumbnailActive\" /> </li></ul><br style=\"clear:both\"/> </div> <div class=\"activeImageContainer\"> <div class=\"rotationWrapper\"> <div class=\"hintArrow\"></div> <img src=\"\" id=\"#{@options.uuid}-sugg-activeImage\" class=\"activeImage\" /> </div> <img src=\"\" id=\"#{@options.uuid}-sugg-activeImageBg\" class=\"activeImage activeImageBg\" /> </div> <div class=\"metadata\"> <label for=\"caption-sugg\">Caption</label><input type=\"text\" id=\"caption-sugg\" /> </div> </div>" _addGuiTabSearch: (tabs, element) -> widget = this dialogId = "#{@options.uuid}-image-dialog" tabs.append jQuery "<li id=\"#{@options.uuid}-tab-search\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-search\"><span>Search</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-search-content\" class=\"#{widget.widgetName}-tab tab-search\"> <form type=\"get\" id=\"#{@options.uuid}-#{widget.widgetName}-searchForm\"> <input type=\"text\" class=\"searchInput\" /><input type=\"submit\" id=\"#{@options.uuid}-#{widget.widgetName}-searchButton\" class=\"button searchButton\" value=\"OK\"/> </form> <div class=\"searchResults imageThumbnailContainer\"></div> <div id=\"#{@options.uuid}-search-activeImageContainer\" class=\"search-activeImageContainer activeImageContainer\"> <div class=\"rotationWrapper\"> <div class=\"hintArrow\"></div> <img src=\"\" id=\"#{@options.uuid}-search-activeImageBg\" class=\"activeImage\" /> </div> <img src=\"\" id=\"#{@options.uuid}-search-activeImage\" class=\"activeImage activeImageBg\" /> </div> <div class=\"metadata\" id=\"metadata-search\" style=\"display: none;\"> <label for=\"caption-search\">Caption</label><input type=\"text\" id=\"caption-search\" /> <!--<button id=\"#{@options.uuid}-#{widget.widgetName}-addimage\">Add Image</button>--> </div> </div>" jQuery(".tab-search form", element).submit (event) -> event.preventDefault() that = this showResults = (response) -> items = [] items.push("<div class=\"pager-prev\" style=\"display:none\"></div>"); jQuery.each response.assets, (key, val) -> items.push("<img src=\"#{val.url}\" class=\"imageThumbnail #{widget.widgetName}-search-imageThumbnail\" /> "); items.push("<div class=\"pager-next\" style=\"display:none\"></div>"); container = jQuery("##{dialogId} .tab-search .searchResults") container.html items.join("") # handle pagers if response.offset > 0 jQuery('.pager-prev', container).show() if response.offset < response.total jQuery('.pager-next', container).show() jQuery('.pager-prev', container).click (event) -> widget.options.search(null, widget.options.limit, response.offset - widget.options.limit, showResults) jQuery('.pager-next', container).click (event) -> widget.options.search(null, widget.options.limit, response.offset + widget.options.limit, showResults) # Add action to image thumbnails jQuery("##{widget.options.uuid}-search-activeImageContainer").show() firstimage = jQuery(".#{widget.widgetName}-search-imageThumbnail").first().addClass "imageThumbnailActive" jQuery("##{widget.options.uuid}-search-activeImage, ##{widget.options.uuid}-search-activeImageBg").attr "src", firstimage.attr "src" jQuery("#metadata-search").show() widget.options.search(null, widget.options.limit, 0, showResults) _prepareIframe: (widget) -> widget.options.iframeName = "#{widget.options.uuid}-#{widget.widgetName}-postframe" iframe = jQuery "<iframe name=\"#{widget.options.iframeName}\" id=\"#{widget.options.iframeName}\" class=\"hidden\" src=\"javascript:false;\" style=\"display:none\" />" jQuery("##{widget.options.uuid}-#{widget.widgetName}-iframe").append iframe iframe.get(0).name = widget.options.iframeName _iframeUpload: (data) -> widget = data.widget widget._prepareIframe widget jQuery("##{widget.options.uuid}-#{widget.widgetName}-tags").val jQuery(".inEditMode").parent().find(".articleTags input").val() uploadForm = jQuery("##{widget.options.uuid}-#{widget.widgetName}-uploadform") uploadForm.attr "action", widget.options.uploadUrl uploadForm.attr "method", "post" uploadForm.attr "userfile", data.file uploadForm.attr "enctype", "multipart/form-data" uploadForm.attr "encoding", "multipart/form-data" uploadForm.attr "target", widget.options.iframeName uploadForm.submit() jQuery("##{widget.options.iframeName}").load -> data.success jQuery("##{widget.options.iframeName}")[0].contentWindow.location.href _addGuiTabUpload: (tabs, element) -> widget = this tabs.append jQuery "<li id=\"#{@options.uuid}-tab-upload\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-upload\"><span>Upload</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-upload-content\" class=\"#{widget.widgetName}-tab tab-upload\"> <form id=\"#{@options.uuid}-#{widget.widgetName}-uploadform\"> <input id=\"#{@options.uuid}-#{widget.widgetName}-file\" name=\"#{@options.uuid}-#{widget.widgetName}-file\" type=\"file\" class=\"file\" accept=\"image/*\"> <input id=\"#{@options.uuid}-#{widget.widgetName}-tags\" name=\"tags\" type=\"hidden\" /> <br /> <input type=\"submit\" value=\"Upload\" id=\"#{@options.uuid}-#{widget.widgetName}-upload\"> </form> <div id=\"#{@options.uuid}-#{widget.widgetName}-iframe\"></div> </div>" iframe = jQuery("<iframe name=\"postframe\" id=\"postframe\" class=\"hidden\" src=\"about:none\" style=\"display:none\" />") jQuery("##{widget.options.uuid}-#{widget.widgetName}-upload").live "click", (e) -> e.preventDefault() userFile = jQuery("##{widget.options.uuid}-#{widget.widgetName}-file").val() widget.options.upload widget: widget file: userFile success: (imageUrl) -> imageID = "si" + Math.floor(Math.random() * (400 - 300 + 1) + 400) + "ab" if jQuery(".imageThumbnailContainer ul", widget.options.dialog).length is 0 list = jQuery '<ul></ul>' jQuery('.imageThumbnailContainer').append list jQuery(".imageThumbnailContainer ul", widget.options.dialog).append "<li><img src=\"#{imageUrl}\" id=\"#{imageID}\" class=\"imageThumbnail\"></li>" jQuery("#" + imageID).trigger "click" jQuery(widget.options.dialog).find(".nav li").first().trigger "click" return false; insertImage = () -> #This may need to insert an image that does not have the same URL as the preview image, since it may be a different size # Check if we have a selection and fall back to @lastSelection otherwise try if not widget.options.editable.getSelection() throw new Error "SelectionNotSet" catch error widget.options.editable.restoreSelection(widget.lastSelection) document.execCommand "insertImage", null, jQuery(this).attr('src') img = document.getSelection().anchorNode.firstChild jQuery(img).attr "alt", jQuery(".caption").value triggerModified = () -> widget.element.trigger "hallomodified" window.setTimeout triggerModified, 100 widget._closeDialog() @options.dialog.find(".halloimage-activeImage, ##{widget.options.uuid}-#{widget.widgetName}-addimage").click insertImage _addDragnDrop: -> helper = # Delay the execution of a function delayAction: (functionToCall, delay) -> timer = clearTimeout(timer) timer = setTimeout(functionToCall, delay) unless timer # Calculate position on an initial drag calcPosition: (offset, event) -> position = offset.left + third if event.pageX >= position and event.pageX <= (offset.left + third * 2) "middle" else if event.pageX < position "left" else if event.pageX > (offset.left + third * 2) "right" # create image to be inserted createInsertElement: (image, tmp) -> maxWidth = 250 maxHeight = 250 tmpImg = new Image() tmpImg.src = image.src if not tmp if @startPlace.parents(".tab-suggestions").length > 0 altText = jQuery("#caption-sugg").val() else if @startPlace.parents(".tab-search").length > 0 altText = jQuery("#caption-search").val() else altText = jQuery(image).attr("alt") width = tmpImg.width height = tmpImg.height if width > maxWidth or height > maxHeight if width > height ratio = (tmpImg.width / maxWidth).toFixed() else ratio = (tmpImg.height / maxHeight).toFixed() width = (tmpImg.width / ratio).toFixed() height = (tmpImg.height / ratio).toFixed() imageInsert = jQuery("<img>").attr( src: tmpImg.src width: width height: height alt: altText class: (if tmp then "tmp" else "") ).show() imageInsert createLineFeedbackElement: -> jQuery("<div/>").addClass "tmpLine" removeFeedbackElements: -> jQuery('.tmp, .tmpLine', editable).remove() removeCustomHelper: -> jQuery(".customHelper").remove() showOverlay: (position) -> eHeight = editable.height() + parseFloat(editable.css('paddingTop')) + parseFloat(editable.css('paddingBottom')) overlay.big.css height: eHeight overlay.left.css height: eHeight overlay.right.css height: eHeight switch position when "left" overlay.big.addClass("bigOverlayLeft").removeClass("bigOverlayRight").css(left: third).show() overlay.left.hide() overlay.right.hide() when "middle" overlay.big.removeClass "bigOverlayLeft bigOverlayRight" overlay.big.hide() overlay.left.show() overlay.right.show() when "right" overlay.big.addClass("bigOverlayRight").removeClass("bigOverlayLeft").css(left: 0).show() overlay.left.hide() overlay.right.hide() else # check if the element was dragged into or within a contenteditable checkOrigin: (event) -> unless jQuery(event.target).parents("[contenteditable]").length is 0 true else false startPlace: "" dnd = createTmpFeedback: (image, position)-> if position is 'middle' return helper.createLineFeedbackElement() else el = helper.createInsertElement(image, true) el.addClass("inlineImage-" + position) handleOverEvent: (event, ui) -> postPone = -> window.waitWithTrash = clearTimeout(window.waitWithTrash) position = helper.calcPosition(offset, event) jQuery('.trashcan', ui.helper).remove() editable.append overlay.big editable.append overlay.left editable.append overlay.right helper.removeFeedbackElements() jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], position) # already create the other feedback elements here, because we have a reference to the droppable if position is "middle" jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], 'right') jQuery('.tmp', jQuery(event.target)).hide() else jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], 'middle') jQuery('.tmpLine', jQuery(event.target)).hide() helper.showOverlay position # we need to postpone the handleOverEvent execution of the function for a tiny bit to avoid # the handleLeaveEvent to be fired after the handleOverEvent. Removing this timeout will break things setTimeout(postPone, 5) handleDragEvent: (event, ui) -> position = helper.calcPosition(offset, event) # help perfs if position == dnd.lastPositionDrag return dnd.lastPositionDrag = position tmpFeedbackLR = jQuery('.tmp', editable) tmpFeedbackMiddle = jQuery('.tmpLine', editable) if position is "middle" tmpFeedbackMiddle.show() tmpFeedbackLR.hide() else tmpFeedbackMiddle.hide() tmpFeedbackLR.removeClass("inlineImage-left inlineImage-right").addClass("inlineImage-" + position).show() helper.showOverlay position handleLeaveEvent: (event, ui) -> func = -> if not jQuery('div.trashcan', ui.helper).length jQuery(ui.helper).append(jQuery('<div class="trashcan"></div>')) jQuery('.bigOverlay, .smallOverlay').remove() # only remove the trash after being outside of an editable more than X milliseconds window.waitWithTrash = setTimeout(func, 200) helper.removeFeedbackElements() handleStartEvent: (event, ui) -> internalDrop = helper.checkOrigin(event) if internalDrop jQuery(event.target).remove() jQuery(document).trigger('startPreventSave') helper.startPlace = jQuery(event.target) handleStopEvent: (event, ui) -> internalDrop = helper.checkOrigin(event) if internalDrop jQuery(event.target).remove() else editable.trigger('change') overlay.big.hide() overlay.left.hide() overlay.right.hide() jQuery(document).trigger('stopPreventSave'); handleDropEvent: (event, ui) -> # check whether it is an internal drop or not internalDrop = helper.checkOrigin(event) position = helper.calcPosition(offset, event) helper.removeFeedbackElements() helper.removeCustomHelper() imageInsert = helper.createInsertElement(ui.draggable[0], false) if position is "middle" imageInsert.show() imageInsert.removeClass("inlineImage-middle inlineImage-left inlineImage-right").addClass("inlineImage-" + position).css position: "relative" left: ((editable.width() + parseFloat(editable.css('paddingLeft')) + parseFloat(editable.css('paddingRight'))) - imageInsert.attr('width')) / 2 imageInsert.insertBefore jQuery(event.target) else imageInsert.removeClass("inlineImage-middle inlineImage-left inlineImage-right").addClass("inlineImage-" + position).css "display", "block" jQuery(event.target).prepend imageInsert overlay.big.hide() overlay.left.hide() overlay.right.hide() # Let the editor know we did a change editable.trigger('change') # init the new image in the content dnd.init(editable) createHelper: (event) -> jQuery('<div>').css({ backgroundImage: "url(" + jQuery(event.currentTarget).attr('src') + ")" }).addClass('customHelper').appendTo('body'); # initialize draggable and droppable elements in the page # Safe to be called multiple times init: () -> draggable = [] initDraggable = (elem) -> if not elem.jquery_draggable_initialized elem.jquery_draggable_initialized = true jQuery(elem).draggable cursor: "move" helper: dnd.createHelper drag: dnd.handleDragEvent start: dnd.handleStartEvent stop: dnd.handleStopEvent disabled: not editable.hasClass('inEditMode') cursorAt: {top: 50, left: 50} draggables.push elem jQuery(".rotationWrapper img", widgetOptions.dialog).each (index, elem) -> initDraggable(elem) if not elem.jquery_draggable_initialized jQuery('img', editable).each (index, elem) -> elem.contentEditable = false if not elem.jquery_draggable_initialized initDraggable(elem) jQuery('p', editable).each (index, elem) -> return if jQuery(elem).data 'jquery_droppable_initialized' jQuery(elem).droppable tolerance: "pointer" drop: dnd.handleDropEvent over: dnd.handleOverEvent out: dnd.handleLeaveEvent jQuery(elem).data 'jquery_droppable_initialized', true enableDragging: () -> jQuery.each draggables, (index, d) -> jQuery(d).draggable('option', 'disabled', false) disableDragging: () -> jQuery.each draggables, (index, d) -> jQuery(d).draggable('option', 'disabled', true) draggables = [] editable = jQuery(@options.editable.element) # keep a reference of options for context changes widgetOptions = @options offset = editable.offset() third = parseFloat(editable.width() / 3) overlayMiddleConfig = width: third height: editable.height() overlay = big: jQuery("<div/>").addClass("bigOverlay").css( width: third * 2 height: editable.height() ) left: jQuery("<div/>").addClass("smallOverlay smallOverlayLeft").css(overlayMiddleConfig) right: jQuery("<div/>").addClass("smallOverlay smallOverlayRight").css(overlayMiddleConfig).css("left", third * 2) dnd.init() editable.bind 'halloactivated', dnd.enableDragging editable.bind 'hallodeactivated', dnd.disableDragging )(jQuery)
101841
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license # # Image insertion plugin # Liip AG: <NAME>, <NAME>, <NAME>, <NAME>, <NAME> ((jQuery) -> jQuery.widget "Liip.halloimage", options: editable: null toolbar: null uuid: "" # number of thumbnails for paging in search results limit: 8 # this function is responsible to fetch search results # query: terms to search # limit: how many results to show at max # offset: offset for the returned result # successCallback: function that will be called with the response json object # the object has fields offset (the requested offset), total (total number of results) and assets (list of url and alt text for each image) search: null # this function is responsible to fetch suggestions for images to insert # this could for example be based on tags of the entity or some semantic enhancement, ... # # tags: tag information - TODO: do not expect that here but get it from context # limit: how many results to show at max # offset: offset for the returned result # successCallback: function that will be called with the response json object # the object has fields offset (the requested offset), total (total number of results) and assets (list of url and alt text for each image) suggestions: null loaded: null upload: null uploadUrl: null dialogOpts: autoOpen: false width: 270 height: "auto" title: "Insert Images" modal: false resizable: false draggable: true dialogClass: 'halloimage-dialog' close: (ev, ui) -> jQuery('.image_button').removeClass('ui-state-clicked') dialog: null buttonCssClass: null _create: -> widget = this dialogId = "#{@options.uuid}-image-dialog" @options.dialog = jQuery "<div id=\"#{dialogId}\"> <div class=\"nav\"> <ul class=\"tabs\"> </ul> <div id=\"#{@options.uuid}-tab-activeIndicator\" class=\"tab-activeIndicator\" /> </div> <div class=\"dialogcontent\"> </div>" if widget.options.uploadUrl and !widget.options.upload widget.options.upload = widget._iframeUpload if widget.options.suggestions @_addGuiTabSuggestions jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) if widget.options.search @_addGuiTabSearch jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) if widget.options.upload @_addGuiTabUpload jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>" id = "#{@options.uuid}-image" buttonHolder = jQuery '<span></span>' buttonHolder.hallobutton label: 'Images' icon: 'icon-picture' editable: @options.editable command: null queryState: false uuid: @options.uuid cssClass: @options.buttonCssClass buttonset.append buttonHolder button = buttonHolder button.bind "change", (event) -> if widget.options.dialog.dialog "isOpen" widget._closeDialog() else widget._openDialog() @options.editable.element.bind "hallodeactivated", (event) -> widget._closeDialog() jQuery(@options.editable.element).delegate "img", "click", (event) -> widget._openDialog() jQuery(@options.dialog).find(".nav li").click () -> jQuery(".#{widget.widgetName}-tab").each () -> jQuery(this).hide() id = jQuery(this).attr("id") jQuery("##{id}-content").show() jQuery("##{widget.options.uuid}-tab-activeIndicator").css("margin-left", jQuery(this).position().left + (jQuery(this).width()/2)) # Add action to image thumbnails jQuery(".#{widget.widgetName}-tab .imageThumbnail").live "click", (event) -> scope = jQuery(this).closest(".#{widget.widgetName}-tab") jQuery(".imageThumbnail", scope).removeClass "imageThumbnailActive" jQuery(this).addClass "imageThumbnailActive" jQuery(".activeImage", scope).attr "src", jQuery(this).attr "src" jQuery(".activeImageBg", scope).attr "src", jQuery(this).attr "src" buttonset.buttonset() @options.toolbar.append buttonset @options.dialog.dialog(@options.dialogOpts) # Add DragnDrop @_addDragnDrop() _init: -> _openDialog: -> widget = this cleanUp = -> window.setTimeout (-> thumbnails = jQuery(".imageThumbnail") jQuery(thumbnails).each -> size = jQuery("#" + @id).width() if size <= 20 jQuery("#" + @id).parent("li").remove() ), 15000 # cleanup after 15 sec repoImagesFound = false showResults = (response) -> # TODO: paging jQuery.each response.assets, (key, val) -> jQuery(".imageThumbnailContainer ul").append "<li><img src=\"" + val.url + "\" class=\"imageThumbnail\"></li>" repoImagesFound = true if response.assets.length > 0 jQuery("#activitySpinner").hide() # Update state of button in toolbar jQuery('.image_button').addClass('ui-state-clicked') # Update active Image jQuery("##{@options.uuid}-sugg-activeImage").attr "src", jQuery("##{@options.uuid}-tab-suggestions-content .imageThumbnailActive").first().attr "src" jQuery("##{@options.uuid}-sugg-activeImageBg").attr "src", jQuery("##{@options.uuid}-tab-suggestions-content .imageThumbnailActive").first().attr "src" # Save current caret point @lastSelection = @options.editable.getSelection() # Position correctly xposition = jQuery(@options.editable.element).offset().left + jQuery(@options.editable.element).outerWidth() - 3 # 3 is the border width of the contenteditable border yposition = jQuery(@options.toolbar).offset().top - jQuery(document).scrollTop() - 29 @options.dialog.dialog("option", "position", [xposition, yposition]) if widget.options.loaded is null && widget.options.suggestions articleTags = [] jQuery("#activitySpinner").show() tmpArticleTags = jQuery(".inEditMode").parent().find(".articleTags input").val() tmpArticleTags = tmpArticleTags.split(",") for i of tmpArticleTags tagType = typeof tmpArticleTags[i] if "string" == tagType && tmpArticleTags[i].indexOf("http") != -1 articleTags.push tmpArticleTags[i] jQuery(".imageThumbnailContainer ul").empty() widget.options.suggestions(jQuery(".inEditMode").parent().find(".articleTags input").val(), widget.options.limit, 0, showResults) vie = new VIE() vie.use new vie.DBPediaService( url: "http://dev.iks-project.eu/stanbolfull" proxyDisabled: true ) thumbId = 1 if articleTags.length is 0 jQuery("#activitySpinner").html "No images found." jQuery(articleTags).each -> vie.load(entity: this + "").using("dbpedia").execute().done (entity) -> jQuery(entity).each -> if @attributes["<http://dbpedia.org/ontology/thumbnail>"] responseType = typeof (@attributes["<http://dbpedia.org/ontology/thumbnail>"]) if responseType is "string" img = @attributes["<http://dbpedia.org/ontology/thumbnail>"] img = img.substring(1, img.length - 1) if responseType is "object" img = "" img = @attributes["<http://dbpedia.org/ontology/thumbnail>"][0].value jQuery(".imageThumbnailContainer ul").append "<li><img id=\"si-#{thumbId}\" src=\"#{img}\" class=\"imageThumbnail\"></li>" thumbId++ jQuery("#activitySpinner").hide() cleanUp() widget.options.loaded = 1 @options.dialog.dialog("open") @options.editable.protectFocusFrom @options.dialog _closeDialog: -> @options.dialog.dialog("close") _addGuiTabSuggestions: (tabs, element) -> widget = this tabs.append jQuery "<li id=\"#{@options.uuid}-tab-suggestions\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-suggestions\"><span>Suggestions</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-suggestions-content\" class=\"#{widget.widgetName}-tab tab-suggestions\"> <div class=\"imageThumbnailContainer fixed\"><div id=\"activitySpinner\">Loading Images...</div><ul><li> <img src=\"http://imagesus.homeaway.com/mda01/badf2e69babf2f6a0e4b680fc373c041c705b891\" class=\"imageThumbnail imageThumbnailActive\" /> </li></ul><br style=\"clear:both\"/> </div> <div class=\"activeImageContainer\"> <div class=\"rotationWrapper\"> <div class=\"hintArrow\"></div> <img src=\"\" id=\"#{@options.uuid}-sugg-activeImage\" class=\"activeImage\" /> </div> <img src=\"\" id=\"#{@options.uuid}-sugg-activeImageBg\" class=\"activeImage activeImageBg\" /> </div> <div class=\"metadata\"> <label for=\"caption-sugg\">Caption</label><input type=\"text\" id=\"caption-sugg\" /> </div> </div>" _addGuiTabSearch: (tabs, element) -> widget = this dialogId = "#{@options.uuid}-image-dialog" tabs.append jQuery "<li id=\"#{@options.uuid}-tab-search\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-search\"><span>Search</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-search-content\" class=\"#{widget.widgetName}-tab tab-search\"> <form type=\"get\" id=\"#{@options.uuid}-#{widget.widgetName}-searchForm\"> <input type=\"text\" class=\"searchInput\" /><input type=\"submit\" id=\"#{@options.uuid}-#{widget.widgetName}-searchButton\" class=\"button searchButton\" value=\"OK\"/> </form> <div class=\"searchResults imageThumbnailContainer\"></div> <div id=\"#{@options.uuid}-search-activeImageContainer\" class=\"search-activeImageContainer activeImageContainer\"> <div class=\"rotationWrapper\"> <div class=\"hintArrow\"></div> <img src=\"\" id=\"#{@options.uuid}-search-activeImageBg\" class=\"activeImage\" /> </div> <img src=\"\" id=\"#{@options.uuid}-search-activeImage\" class=\"activeImage activeImageBg\" /> </div> <div class=\"metadata\" id=\"metadata-search\" style=\"display: none;\"> <label for=\"caption-search\">Caption</label><input type=\"text\" id=\"caption-search\" /> <!--<button id=\"#{@options.uuid}-#{widget.widgetName}-addimage\">Add Image</button>--> </div> </div>" jQuery(".tab-search form", element).submit (event) -> event.preventDefault() that = this showResults = (response) -> items = [] items.push("<div class=\"pager-prev\" style=\"display:none\"></div>"); jQuery.each response.assets, (key, val) -> items.push("<img src=\"#{val.url}\" class=\"imageThumbnail #{widget.widgetName}-search-imageThumbnail\" /> "); items.push("<div class=\"pager-next\" style=\"display:none\"></div>"); container = jQuery("##{dialogId} .tab-search .searchResults") container.html items.join("") # handle pagers if response.offset > 0 jQuery('.pager-prev', container).show() if response.offset < response.total jQuery('.pager-next', container).show() jQuery('.pager-prev', container).click (event) -> widget.options.search(null, widget.options.limit, response.offset - widget.options.limit, showResults) jQuery('.pager-next', container).click (event) -> widget.options.search(null, widget.options.limit, response.offset + widget.options.limit, showResults) # Add action to image thumbnails jQuery("##{widget.options.uuid}-search-activeImageContainer").show() firstimage = jQuery(".#{widget.widgetName}-search-imageThumbnail").first().addClass "imageThumbnailActive" jQuery("##{widget.options.uuid}-search-activeImage, ##{widget.options.uuid}-search-activeImageBg").attr "src", firstimage.attr "src" jQuery("#metadata-search").show() widget.options.search(null, widget.options.limit, 0, showResults) _prepareIframe: (widget) -> widget.options.iframeName = "#{widget.options.uuid}-#{widget.widgetName}-postframe" iframe = jQuery "<iframe name=\"#{widget.options.iframeName}\" id=\"#{widget.options.iframeName}\" class=\"hidden\" src=\"javascript:false;\" style=\"display:none\" />" jQuery("##{widget.options.uuid}-#{widget.widgetName}-iframe").append iframe iframe.get(0).name = widget.options.iframeName _iframeUpload: (data) -> widget = data.widget widget._prepareIframe widget jQuery("##{widget.options.uuid}-#{widget.widgetName}-tags").val jQuery(".inEditMode").parent().find(".articleTags input").val() uploadForm = jQuery("##{widget.options.uuid}-#{widget.widgetName}-uploadform") uploadForm.attr "action", widget.options.uploadUrl uploadForm.attr "method", "post" uploadForm.attr "userfile", data.file uploadForm.attr "enctype", "multipart/form-data" uploadForm.attr "encoding", "multipart/form-data" uploadForm.attr "target", widget.options.iframeName uploadForm.submit() jQuery("##{widget.options.iframeName}").load -> data.success jQuery("##{widget.options.iframeName}")[0].contentWindow.location.href _addGuiTabUpload: (tabs, element) -> widget = this tabs.append jQuery "<li id=\"#{@options.uuid}-tab-upload\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-upload\"><span>Upload</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-upload-content\" class=\"#{widget.widgetName}-tab tab-upload\"> <form id=\"#{@options.uuid}-#{widget.widgetName}-uploadform\"> <input id=\"#{@options.uuid}-#{widget.widgetName}-file\" name=\"#{@options.uuid}-#{widget.widgetName}-file\" type=\"file\" class=\"file\" accept=\"image/*\"> <input id=\"#{@options.uuid}-#{widget.widgetName}-tags\" name=\"tags\" type=\"hidden\" /> <br /> <input type=\"submit\" value=\"Upload\" id=\"#{@options.uuid}-#{widget.widgetName}-upload\"> </form> <div id=\"#{@options.uuid}-#{widget.widgetName}-iframe\"></div> </div>" iframe = jQuery("<iframe name=\"postframe\" id=\"postframe\" class=\"hidden\" src=\"about:none\" style=\"display:none\" />") jQuery("##{widget.options.uuid}-#{widget.widgetName}-upload").live "click", (e) -> e.preventDefault() userFile = jQuery("##{widget.options.uuid}-#{widget.widgetName}-file").val() widget.options.upload widget: widget file: userFile success: (imageUrl) -> imageID = "si" + Math.floor(Math.random() * (400 - 300 + 1) + 400) + "ab" if jQuery(".imageThumbnailContainer ul", widget.options.dialog).length is 0 list = jQuery '<ul></ul>' jQuery('.imageThumbnailContainer').append list jQuery(".imageThumbnailContainer ul", widget.options.dialog).append "<li><img src=\"#{imageUrl}\" id=\"#{imageID}\" class=\"imageThumbnail\"></li>" jQuery("#" + imageID).trigger "click" jQuery(widget.options.dialog).find(".nav li").first().trigger "click" return false; insertImage = () -> #This may need to insert an image that does not have the same URL as the preview image, since it may be a different size # Check if we have a selection and fall back to @lastSelection otherwise try if not widget.options.editable.getSelection() throw new Error "SelectionNotSet" catch error widget.options.editable.restoreSelection(widget.lastSelection) document.execCommand "insertImage", null, jQuery(this).attr('src') img = document.getSelection().anchorNode.firstChild jQuery(img).attr "alt", jQuery(".caption").value triggerModified = () -> widget.element.trigger "hallomodified" window.setTimeout triggerModified, 100 widget._closeDialog() @options.dialog.find(".halloimage-activeImage, ##{widget.options.uuid}-#{widget.widgetName}-addimage").click insertImage _addDragnDrop: -> helper = # Delay the execution of a function delayAction: (functionToCall, delay) -> timer = clearTimeout(timer) timer = setTimeout(functionToCall, delay) unless timer # Calculate position on an initial drag calcPosition: (offset, event) -> position = offset.left + third if event.pageX >= position and event.pageX <= (offset.left + third * 2) "middle" else if event.pageX < position "left" else if event.pageX > (offset.left + third * 2) "right" # create image to be inserted createInsertElement: (image, tmp) -> maxWidth = 250 maxHeight = 250 tmpImg = new Image() tmpImg.src = image.src if not tmp if @startPlace.parents(".tab-suggestions").length > 0 altText = jQuery("#caption-sugg").val() else if @startPlace.parents(".tab-search").length > 0 altText = jQuery("#caption-search").val() else altText = jQuery(image).attr("alt") width = tmpImg.width height = tmpImg.height if width > maxWidth or height > maxHeight if width > height ratio = (tmpImg.width / maxWidth).toFixed() else ratio = (tmpImg.height / maxHeight).toFixed() width = (tmpImg.width / ratio).toFixed() height = (tmpImg.height / ratio).toFixed() imageInsert = jQuery("<img>").attr( src: tmpImg.src width: width height: height alt: altText class: (if tmp then "tmp" else "") ).show() imageInsert createLineFeedbackElement: -> jQuery("<div/>").addClass "tmpLine" removeFeedbackElements: -> jQuery('.tmp, .tmpLine', editable).remove() removeCustomHelper: -> jQuery(".customHelper").remove() showOverlay: (position) -> eHeight = editable.height() + parseFloat(editable.css('paddingTop')) + parseFloat(editable.css('paddingBottom')) overlay.big.css height: eHeight overlay.left.css height: eHeight overlay.right.css height: eHeight switch position when "left" overlay.big.addClass("bigOverlayLeft").removeClass("bigOverlayRight").css(left: third).show() overlay.left.hide() overlay.right.hide() when "middle" overlay.big.removeClass "bigOverlayLeft bigOverlayRight" overlay.big.hide() overlay.left.show() overlay.right.show() when "right" overlay.big.addClass("bigOverlayRight").removeClass("bigOverlayLeft").css(left: 0).show() overlay.left.hide() overlay.right.hide() else # check if the element was dragged into or within a contenteditable checkOrigin: (event) -> unless jQuery(event.target).parents("[contenteditable]").length is 0 true else false startPlace: "" dnd = createTmpFeedback: (image, position)-> if position is 'middle' return helper.createLineFeedbackElement() else el = helper.createInsertElement(image, true) el.addClass("inlineImage-" + position) handleOverEvent: (event, ui) -> postPone = -> window.waitWithTrash = clearTimeout(window.waitWithTrash) position = helper.calcPosition(offset, event) jQuery('.trashcan', ui.helper).remove() editable.append overlay.big editable.append overlay.left editable.append overlay.right helper.removeFeedbackElements() jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], position) # already create the other feedback elements here, because we have a reference to the droppable if position is "middle" jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], 'right') jQuery('.tmp', jQuery(event.target)).hide() else jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], 'middle') jQuery('.tmpLine', jQuery(event.target)).hide() helper.showOverlay position # we need to postpone the handleOverEvent execution of the function for a tiny bit to avoid # the handleLeaveEvent to be fired after the handleOverEvent. Removing this timeout will break things setTimeout(postPone, 5) handleDragEvent: (event, ui) -> position = helper.calcPosition(offset, event) # help perfs if position == dnd.lastPositionDrag return dnd.lastPositionDrag = position tmpFeedbackLR = jQuery('.tmp', editable) tmpFeedbackMiddle = jQuery('.tmpLine', editable) if position is "middle" tmpFeedbackMiddle.show() tmpFeedbackLR.hide() else tmpFeedbackMiddle.hide() tmpFeedbackLR.removeClass("inlineImage-left inlineImage-right").addClass("inlineImage-" + position).show() helper.showOverlay position handleLeaveEvent: (event, ui) -> func = -> if not jQuery('div.trashcan', ui.helper).length jQuery(ui.helper).append(jQuery('<div class="trashcan"></div>')) jQuery('.bigOverlay, .smallOverlay').remove() # only remove the trash after being outside of an editable more than X milliseconds window.waitWithTrash = setTimeout(func, 200) helper.removeFeedbackElements() handleStartEvent: (event, ui) -> internalDrop = helper.checkOrigin(event) if internalDrop jQuery(event.target).remove() jQuery(document).trigger('startPreventSave') helper.startPlace = jQuery(event.target) handleStopEvent: (event, ui) -> internalDrop = helper.checkOrigin(event) if internalDrop jQuery(event.target).remove() else editable.trigger('change') overlay.big.hide() overlay.left.hide() overlay.right.hide() jQuery(document).trigger('stopPreventSave'); handleDropEvent: (event, ui) -> # check whether it is an internal drop or not internalDrop = helper.checkOrigin(event) position = helper.calcPosition(offset, event) helper.removeFeedbackElements() helper.removeCustomHelper() imageInsert = helper.createInsertElement(ui.draggable[0], false) if position is "middle" imageInsert.show() imageInsert.removeClass("inlineImage-middle inlineImage-left inlineImage-right").addClass("inlineImage-" + position).css position: "relative" left: ((editable.width() + parseFloat(editable.css('paddingLeft')) + parseFloat(editable.css('paddingRight'))) - imageInsert.attr('width')) / 2 imageInsert.insertBefore jQuery(event.target) else imageInsert.removeClass("inlineImage-middle inlineImage-left inlineImage-right").addClass("inlineImage-" + position).css "display", "block" jQuery(event.target).prepend imageInsert overlay.big.hide() overlay.left.hide() overlay.right.hide() # Let the editor know we did a change editable.trigger('change') # init the new image in the content dnd.init(editable) createHelper: (event) -> jQuery('<div>').css({ backgroundImage: "url(" + jQuery(event.currentTarget).attr('src') + ")" }).addClass('customHelper').appendTo('body'); # initialize draggable and droppable elements in the page # Safe to be called multiple times init: () -> draggable = [] initDraggable = (elem) -> if not elem.jquery_draggable_initialized elem.jquery_draggable_initialized = true jQuery(elem).draggable cursor: "move" helper: dnd.createHelper drag: dnd.handleDragEvent start: dnd.handleStartEvent stop: dnd.handleStopEvent disabled: not editable.hasClass('inEditMode') cursorAt: {top: 50, left: 50} draggables.push elem jQuery(".rotationWrapper img", widgetOptions.dialog).each (index, elem) -> initDraggable(elem) if not elem.jquery_draggable_initialized jQuery('img', editable).each (index, elem) -> elem.contentEditable = false if not elem.jquery_draggable_initialized initDraggable(elem) jQuery('p', editable).each (index, elem) -> return if jQuery(elem).data 'jquery_droppable_initialized' jQuery(elem).droppable tolerance: "pointer" drop: dnd.handleDropEvent over: dnd.handleOverEvent out: dnd.handleLeaveEvent jQuery(elem).data 'jquery_droppable_initialized', true enableDragging: () -> jQuery.each draggables, (index, d) -> jQuery(d).draggable('option', 'disabled', false) disableDragging: () -> jQuery.each draggables, (index, d) -> jQuery(d).draggable('option', 'disabled', true) draggables = [] editable = jQuery(@options.editable.element) # keep a reference of options for context changes widgetOptions = @options offset = editable.offset() third = parseFloat(editable.width() / 3) overlayMiddleConfig = width: third height: editable.height() overlay = big: jQuery("<div/>").addClass("bigOverlay").css( width: third * 2 height: editable.height() ) left: jQuery("<div/>").addClass("smallOverlay smallOverlayLeft").css(overlayMiddleConfig) right: jQuery("<div/>").addClass("smallOverlay smallOverlayRight").css(overlayMiddleConfig).css("left", third * 2) dnd.init() editable.bind 'halloactivated', dnd.enableDragging editable.bind 'hallodeactivated', dnd.disableDragging )(jQuery)
true
# Hallo - a rich text editing jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Hallo may be freely distributed under the MIT license # # Image insertion plugin # Liip AG: 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 ((jQuery) -> jQuery.widget "Liip.halloimage", options: editable: null toolbar: null uuid: "" # number of thumbnails for paging in search results limit: 8 # this function is responsible to fetch search results # query: terms to search # limit: how many results to show at max # offset: offset for the returned result # successCallback: function that will be called with the response json object # the object has fields offset (the requested offset), total (total number of results) and assets (list of url and alt text for each image) search: null # this function is responsible to fetch suggestions for images to insert # this could for example be based on tags of the entity or some semantic enhancement, ... # # tags: tag information - TODO: do not expect that here but get it from context # limit: how many results to show at max # offset: offset for the returned result # successCallback: function that will be called with the response json object # the object has fields offset (the requested offset), total (total number of results) and assets (list of url and alt text for each image) suggestions: null loaded: null upload: null uploadUrl: null dialogOpts: autoOpen: false width: 270 height: "auto" title: "Insert Images" modal: false resizable: false draggable: true dialogClass: 'halloimage-dialog' close: (ev, ui) -> jQuery('.image_button').removeClass('ui-state-clicked') dialog: null buttonCssClass: null _create: -> widget = this dialogId = "#{@options.uuid}-image-dialog" @options.dialog = jQuery "<div id=\"#{dialogId}\"> <div class=\"nav\"> <ul class=\"tabs\"> </ul> <div id=\"#{@options.uuid}-tab-activeIndicator\" class=\"tab-activeIndicator\" /> </div> <div class=\"dialogcontent\"> </div>" if widget.options.uploadUrl and !widget.options.upload widget.options.upload = widget._iframeUpload if widget.options.suggestions @_addGuiTabSuggestions jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) if widget.options.search @_addGuiTabSearch jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) if widget.options.upload @_addGuiTabUpload jQuery(".tabs", @options.dialog), jQuery(".dialogcontent", @options.dialog) buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>" id = "#{@options.uuid}-image" buttonHolder = jQuery '<span></span>' buttonHolder.hallobutton label: 'Images' icon: 'icon-picture' editable: @options.editable command: null queryState: false uuid: @options.uuid cssClass: @options.buttonCssClass buttonset.append buttonHolder button = buttonHolder button.bind "change", (event) -> if widget.options.dialog.dialog "isOpen" widget._closeDialog() else widget._openDialog() @options.editable.element.bind "hallodeactivated", (event) -> widget._closeDialog() jQuery(@options.editable.element).delegate "img", "click", (event) -> widget._openDialog() jQuery(@options.dialog).find(".nav li").click () -> jQuery(".#{widget.widgetName}-tab").each () -> jQuery(this).hide() id = jQuery(this).attr("id") jQuery("##{id}-content").show() jQuery("##{widget.options.uuid}-tab-activeIndicator").css("margin-left", jQuery(this).position().left + (jQuery(this).width()/2)) # Add action to image thumbnails jQuery(".#{widget.widgetName}-tab .imageThumbnail").live "click", (event) -> scope = jQuery(this).closest(".#{widget.widgetName}-tab") jQuery(".imageThumbnail", scope).removeClass "imageThumbnailActive" jQuery(this).addClass "imageThumbnailActive" jQuery(".activeImage", scope).attr "src", jQuery(this).attr "src" jQuery(".activeImageBg", scope).attr "src", jQuery(this).attr "src" buttonset.buttonset() @options.toolbar.append buttonset @options.dialog.dialog(@options.dialogOpts) # Add DragnDrop @_addDragnDrop() _init: -> _openDialog: -> widget = this cleanUp = -> window.setTimeout (-> thumbnails = jQuery(".imageThumbnail") jQuery(thumbnails).each -> size = jQuery("#" + @id).width() if size <= 20 jQuery("#" + @id).parent("li").remove() ), 15000 # cleanup after 15 sec repoImagesFound = false showResults = (response) -> # TODO: paging jQuery.each response.assets, (key, val) -> jQuery(".imageThumbnailContainer ul").append "<li><img src=\"" + val.url + "\" class=\"imageThumbnail\"></li>" repoImagesFound = true if response.assets.length > 0 jQuery("#activitySpinner").hide() # Update state of button in toolbar jQuery('.image_button').addClass('ui-state-clicked') # Update active Image jQuery("##{@options.uuid}-sugg-activeImage").attr "src", jQuery("##{@options.uuid}-tab-suggestions-content .imageThumbnailActive").first().attr "src" jQuery("##{@options.uuid}-sugg-activeImageBg").attr "src", jQuery("##{@options.uuid}-tab-suggestions-content .imageThumbnailActive").first().attr "src" # Save current caret point @lastSelection = @options.editable.getSelection() # Position correctly xposition = jQuery(@options.editable.element).offset().left + jQuery(@options.editable.element).outerWidth() - 3 # 3 is the border width of the contenteditable border yposition = jQuery(@options.toolbar).offset().top - jQuery(document).scrollTop() - 29 @options.dialog.dialog("option", "position", [xposition, yposition]) if widget.options.loaded is null && widget.options.suggestions articleTags = [] jQuery("#activitySpinner").show() tmpArticleTags = jQuery(".inEditMode").parent().find(".articleTags input").val() tmpArticleTags = tmpArticleTags.split(",") for i of tmpArticleTags tagType = typeof tmpArticleTags[i] if "string" == tagType && tmpArticleTags[i].indexOf("http") != -1 articleTags.push tmpArticleTags[i] jQuery(".imageThumbnailContainer ul").empty() widget.options.suggestions(jQuery(".inEditMode").parent().find(".articleTags input").val(), widget.options.limit, 0, showResults) vie = new VIE() vie.use new vie.DBPediaService( url: "http://dev.iks-project.eu/stanbolfull" proxyDisabled: true ) thumbId = 1 if articleTags.length is 0 jQuery("#activitySpinner").html "No images found." jQuery(articleTags).each -> vie.load(entity: this + "").using("dbpedia").execute().done (entity) -> jQuery(entity).each -> if @attributes["<http://dbpedia.org/ontology/thumbnail>"] responseType = typeof (@attributes["<http://dbpedia.org/ontology/thumbnail>"]) if responseType is "string" img = @attributes["<http://dbpedia.org/ontology/thumbnail>"] img = img.substring(1, img.length - 1) if responseType is "object" img = "" img = @attributes["<http://dbpedia.org/ontology/thumbnail>"][0].value jQuery(".imageThumbnailContainer ul").append "<li><img id=\"si-#{thumbId}\" src=\"#{img}\" class=\"imageThumbnail\"></li>" thumbId++ jQuery("#activitySpinner").hide() cleanUp() widget.options.loaded = 1 @options.dialog.dialog("open") @options.editable.protectFocusFrom @options.dialog _closeDialog: -> @options.dialog.dialog("close") _addGuiTabSuggestions: (tabs, element) -> widget = this tabs.append jQuery "<li id=\"#{@options.uuid}-tab-suggestions\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-suggestions\"><span>Suggestions</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-suggestions-content\" class=\"#{widget.widgetName}-tab tab-suggestions\"> <div class=\"imageThumbnailContainer fixed\"><div id=\"activitySpinner\">Loading Images...</div><ul><li> <img src=\"http://imagesus.homeaway.com/mda01/badf2e69babf2f6a0e4b680fc373c041c705b891\" class=\"imageThumbnail imageThumbnailActive\" /> </li></ul><br style=\"clear:both\"/> </div> <div class=\"activeImageContainer\"> <div class=\"rotationWrapper\"> <div class=\"hintArrow\"></div> <img src=\"\" id=\"#{@options.uuid}-sugg-activeImage\" class=\"activeImage\" /> </div> <img src=\"\" id=\"#{@options.uuid}-sugg-activeImageBg\" class=\"activeImage activeImageBg\" /> </div> <div class=\"metadata\"> <label for=\"caption-sugg\">Caption</label><input type=\"text\" id=\"caption-sugg\" /> </div> </div>" _addGuiTabSearch: (tabs, element) -> widget = this dialogId = "#{@options.uuid}-image-dialog" tabs.append jQuery "<li id=\"#{@options.uuid}-tab-search\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-search\"><span>Search</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-search-content\" class=\"#{widget.widgetName}-tab tab-search\"> <form type=\"get\" id=\"#{@options.uuid}-#{widget.widgetName}-searchForm\"> <input type=\"text\" class=\"searchInput\" /><input type=\"submit\" id=\"#{@options.uuid}-#{widget.widgetName}-searchButton\" class=\"button searchButton\" value=\"OK\"/> </form> <div class=\"searchResults imageThumbnailContainer\"></div> <div id=\"#{@options.uuid}-search-activeImageContainer\" class=\"search-activeImageContainer activeImageContainer\"> <div class=\"rotationWrapper\"> <div class=\"hintArrow\"></div> <img src=\"\" id=\"#{@options.uuid}-search-activeImageBg\" class=\"activeImage\" /> </div> <img src=\"\" id=\"#{@options.uuid}-search-activeImage\" class=\"activeImage activeImageBg\" /> </div> <div class=\"metadata\" id=\"metadata-search\" style=\"display: none;\"> <label for=\"caption-search\">Caption</label><input type=\"text\" id=\"caption-search\" /> <!--<button id=\"#{@options.uuid}-#{widget.widgetName}-addimage\">Add Image</button>--> </div> </div>" jQuery(".tab-search form", element).submit (event) -> event.preventDefault() that = this showResults = (response) -> items = [] items.push("<div class=\"pager-prev\" style=\"display:none\"></div>"); jQuery.each response.assets, (key, val) -> items.push("<img src=\"#{val.url}\" class=\"imageThumbnail #{widget.widgetName}-search-imageThumbnail\" /> "); items.push("<div class=\"pager-next\" style=\"display:none\"></div>"); container = jQuery("##{dialogId} .tab-search .searchResults") container.html items.join("") # handle pagers if response.offset > 0 jQuery('.pager-prev', container).show() if response.offset < response.total jQuery('.pager-next', container).show() jQuery('.pager-prev', container).click (event) -> widget.options.search(null, widget.options.limit, response.offset - widget.options.limit, showResults) jQuery('.pager-next', container).click (event) -> widget.options.search(null, widget.options.limit, response.offset + widget.options.limit, showResults) # Add action to image thumbnails jQuery("##{widget.options.uuid}-search-activeImageContainer").show() firstimage = jQuery(".#{widget.widgetName}-search-imageThumbnail").first().addClass "imageThumbnailActive" jQuery("##{widget.options.uuid}-search-activeImage, ##{widget.options.uuid}-search-activeImageBg").attr "src", firstimage.attr "src" jQuery("#metadata-search").show() widget.options.search(null, widget.options.limit, 0, showResults) _prepareIframe: (widget) -> widget.options.iframeName = "#{widget.options.uuid}-#{widget.widgetName}-postframe" iframe = jQuery "<iframe name=\"#{widget.options.iframeName}\" id=\"#{widget.options.iframeName}\" class=\"hidden\" src=\"javascript:false;\" style=\"display:none\" />" jQuery("##{widget.options.uuid}-#{widget.widgetName}-iframe").append iframe iframe.get(0).name = widget.options.iframeName _iframeUpload: (data) -> widget = data.widget widget._prepareIframe widget jQuery("##{widget.options.uuid}-#{widget.widgetName}-tags").val jQuery(".inEditMode").parent().find(".articleTags input").val() uploadForm = jQuery("##{widget.options.uuid}-#{widget.widgetName}-uploadform") uploadForm.attr "action", widget.options.uploadUrl uploadForm.attr "method", "post" uploadForm.attr "userfile", data.file uploadForm.attr "enctype", "multipart/form-data" uploadForm.attr "encoding", "multipart/form-data" uploadForm.attr "target", widget.options.iframeName uploadForm.submit() jQuery("##{widget.options.iframeName}").load -> data.success jQuery("##{widget.options.iframeName}")[0].contentWindow.location.href _addGuiTabUpload: (tabs, element) -> widget = this tabs.append jQuery "<li id=\"#{@options.uuid}-tab-upload\" class=\"#{widget.widgetName}-tabselector #{widget.widgetName}-tab-upload\"><span>Upload</span></li>" element.append jQuery "<div id=\"#{@options.uuid}-tab-upload-content\" class=\"#{widget.widgetName}-tab tab-upload\"> <form id=\"#{@options.uuid}-#{widget.widgetName}-uploadform\"> <input id=\"#{@options.uuid}-#{widget.widgetName}-file\" name=\"#{@options.uuid}-#{widget.widgetName}-file\" type=\"file\" class=\"file\" accept=\"image/*\"> <input id=\"#{@options.uuid}-#{widget.widgetName}-tags\" name=\"tags\" type=\"hidden\" /> <br /> <input type=\"submit\" value=\"Upload\" id=\"#{@options.uuid}-#{widget.widgetName}-upload\"> </form> <div id=\"#{@options.uuid}-#{widget.widgetName}-iframe\"></div> </div>" iframe = jQuery("<iframe name=\"postframe\" id=\"postframe\" class=\"hidden\" src=\"about:none\" style=\"display:none\" />") jQuery("##{widget.options.uuid}-#{widget.widgetName}-upload").live "click", (e) -> e.preventDefault() userFile = jQuery("##{widget.options.uuid}-#{widget.widgetName}-file").val() widget.options.upload widget: widget file: userFile success: (imageUrl) -> imageID = "si" + Math.floor(Math.random() * (400 - 300 + 1) + 400) + "ab" if jQuery(".imageThumbnailContainer ul", widget.options.dialog).length is 0 list = jQuery '<ul></ul>' jQuery('.imageThumbnailContainer').append list jQuery(".imageThumbnailContainer ul", widget.options.dialog).append "<li><img src=\"#{imageUrl}\" id=\"#{imageID}\" class=\"imageThumbnail\"></li>" jQuery("#" + imageID).trigger "click" jQuery(widget.options.dialog).find(".nav li").first().trigger "click" return false; insertImage = () -> #This may need to insert an image that does not have the same URL as the preview image, since it may be a different size # Check if we have a selection and fall back to @lastSelection otherwise try if not widget.options.editable.getSelection() throw new Error "SelectionNotSet" catch error widget.options.editable.restoreSelection(widget.lastSelection) document.execCommand "insertImage", null, jQuery(this).attr('src') img = document.getSelection().anchorNode.firstChild jQuery(img).attr "alt", jQuery(".caption").value triggerModified = () -> widget.element.trigger "hallomodified" window.setTimeout triggerModified, 100 widget._closeDialog() @options.dialog.find(".halloimage-activeImage, ##{widget.options.uuid}-#{widget.widgetName}-addimage").click insertImage _addDragnDrop: -> helper = # Delay the execution of a function delayAction: (functionToCall, delay) -> timer = clearTimeout(timer) timer = setTimeout(functionToCall, delay) unless timer # Calculate position on an initial drag calcPosition: (offset, event) -> position = offset.left + third if event.pageX >= position and event.pageX <= (offset.left + third * 2) "middle" else if event.pageX < position "left" else if event.pageX > (offset.left + third * 2) "right" # create image to be inserted createInsertElement: (image, tmp) -> maxWidth = 250 maxHeight = 250 tmpImg = new Image() tmpImg.src = image.src if not tmp if @startPlace.parents(".tab-suggestions").length > 0 altText = jQuery("#caption-sugg").val() else if @startPlace.parents(".tab-search").length > 0 altText = jQuery("#caption-search").val() else altText = jQuery(image).attr("alt") width = tmpImg.width height = tmpImg.height if width > maxWidth or height > maxHeight if width > height ratio = (tmpImg.width / maxWidth).toFixed() else ratio = (tmpImg.height / maxHeight).toFixed() width = (tmpImg.width / ratio).toFixed() height = (tmpImg.height / ratio).toFixed() imageInsert = jQuery("<img>").attr( src: tmpImg.src width: width height: height alt: altText class: (if tmp then "tmp" else "") ).show() imageInsert createLineFeedbackElement: -> jQuery("<div/>").addClass "tmpLine" removeFeedbackElements: -> jQuery('.tmp, .tmpLine', editable).remove() removeCustomHelper: -> jQuery(".customHelper").remove() showOverlay: (position) -> eHeight = editable.height() + parseFloat(editable.css('paddingTop')) + parseFloat(editable.css('paddingBottom')) overlay.big.css height: eHeight overlay.left.css height: eHeight overlay.right.css height: eHeight switch position when "left" overlay.big.addClass("bigOverlayLeft").removeClass("bigOverlayRight").css(left: third).show() overlay.left.hide() overlay.right.hide() when "middle" overlay.big.removeClass "bigOverlayLeft bigOverlayRight" overlay.big.hide() overlay.left.show() overlay.right.show() when "right" overlay.big.addClass("bigOverlayRight").removeClass("bigOverlayLeft").css(left: 0).show() overlay.left.hide() overlay.right.hide() else # check if the element was dragged into or within a contenteditable checkOrigin: (event) -> unless jQuery(event.target).parents("[contenteditable]").length is 0 true else false startPlace: "" dnd = createTmpFeedback: (image, position)-> if position is 'middle' return helper.createLineFeedbackElement() else el = helper.createInsertElement(image, true) el.addClass("inlineImage-" + position) handleOverEvent: (event, ui) -> postPone = -> window.waitWithTrash = clearTimeout(window.waitWithTrash) position = helper.calcPosition(offset, event) jQuery('.trashcan', ui.helper).remove() editable.append overlay.big editable.append overlay.left editable.append overlay.right helper.removeFeedbackElements() jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], position) # already create the other feedback elements here, because we have a reference to the droppable if position is "middle" jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], 'right') jQuery('.tmp', jQuery(event.target)).hide() else jQuery(event.target).prepend(dnd.createTmpFeedback ui.draggable[0], 'middle') jQuery('.tmpLine', jQuery(event.target)).hide() helper.showOverlay position # we need to postpone the handleOverEvent execution of the function for a tiny bit to avoid # the handleLeaveEvent to be fired after the handleOverEvent. Removing this timeout will break things setTimeout(postPone, 5) handleDragEvent: (event, ui) -> position = helper.calcPosition(offset, event) # help perfs if position == dnd.lastPositionDrag return dnd.lastPositionDrag = position tmpFeedbackLR = jQuery('.tmp', editable) tmpFeedbackMiddle = jQuery('.tmpLine', editable) if position is "middle" tmpFeedbackMiddle.show() tmpFeedbackLR.hide() else tmpFeedbackMiddle.hide() tmpFeedbackLR.removeClass("inlineImage-left inlineImage-right").addClass("inlineImage-" + position).show() helper.showOverlay position handleLeaveEvent: (event, ui) -> func = -> if not jQuery('div.trashcan', ui.helper).length jQuery(ui.helper).append(jQuery('<div class="trashcan"></div>')) jQuery('.bigOverlay, .smallOverlay').remove() # only remove the trash after being outside of an editable more than X milliseconds window.waitWithTrash = setTimeout(func, 200) helper.removeFeedbackElements() handleStartEvent: (event, ui) -> internalDrop = helper.checkOrigin(event) if internalDrop jQuery(event.target).remove() jQuery(document).trigger('startPreventSave') helper.startPlace = jQuery(event.target) handleStopEvent: (event, ui) -> internalDrop = helper.checkOrigin(event) if internalDrop jQuery(event.target).remove() else editable.trigger('change') overlay.big.hide() overlay.left.hide() overlay.right.hide() jQuery(document).trigger('stopPreventSave'); handleDropEvent: (event, ui) -> # check whether it is an internal drop or not internalDrop = helper.checkOrigin(event) position = helper.calcPosition(offset, event) helper.removeFeedbackElements() helper.removeCustomHelper() imageInsert = helper.createInsertElement(ui.draggable[0], false) if position is "middle" imageInsert.show() imageInsert.removeClass("inlineImage-middle inlineImage-left inlineImage-right").addClass("inlineImage-" + position).css position: "relative" left: ((editable.width() + parseFloat(editable.css('paddingLeft')) + parseFloat(editable.css('paddingRight'))) - imageInsert.attr('width')) / 2 imageInsert.insertBefore jQuery(event.target) else imageInsert.removeClass("inlineImage-middle inlineImage-left inlineImage-right").addClass("inlineImage-" + position).css "display", "block" jQuery(event.target).prepend imageInsert overlay.big.hide() overlay.left.hide() overlay.right.hide() # Let the editor know we did a change editable.trigger('change') # init the new image in the content dnd.init(editable) createHelper: (event) -> jQuery('<div>').css({ backgroundImage: "url(" + jQuery(event.currentTarget).attr('src') + ")" }).addClass('customHelper').appendTo('body'); # initialize draggable and droppable elements in the page # Safe to be called multiple times init: () -> draggable = [] initDraggable = (elem) -> if not elem.jquery_draggable_initialized elem.jquery_draggable_initialized = true jQuery(elem).draggable cursor: "move" helper: dnd.createHelper drag: dnd.handleDragEvent start: dnd.handleStartEvent stop: dnd.handleStopEvent disabled: not editable.hasClass('inEditMode') cursorAt: {top: 50, left: 50} draggables.push elem jQuery(".rotationWrapper img", widgetOptions.dialog).each (index, elem) -> initDraggable(elem) if not elem.jquery_draggable_initialized jQuery('img', editable).each (index, elem) -> elem.contentEditable = false if not elem.jquery_draggable_initialized initDraggable(elem) jQuery('p', editable).each (index, elem) -> return if jQuery(elem).data 'jquery_droppable_initialized' jQuery(elem).droppable tolerance: "pointer" drop: dnd.handleDropEvent over: dnd.handleOverEvent out: dnd.handleLeaveEvent jQuery(elem).data 'jquery_droppable_initialized', true enableDragging: () -> jQuery.each draggables, (index, d) -> jQuery(d).draggable('option', 'disabled', false) disableDragging: () -> jQuery.each draggables, (index, d) -> jQuery(d).draggable('option', 'disabled', true) draggables = [] editable = jQuery(@options.editable.element) # keep a reference of options for context changes widgetOptions = @options offset = editable.offset() third = parseFloat(editable.width() / 3) overlayMiddleConfig = width: third height: editable.height() overlay = big: jQuery("<div/>").addClass("bigOverlay").css( width: third * 2 height: editable.height() ) left: jQuery("<div/>").addClass("smallOverlay smallOverlayLeft").css(overlayMiddleConfig) right: jQuery("<div/>").addClass("smallOverlay smallOverlayRight").css(overlayMiddleConfig).css("left", third * 2) dnd.init() editable.bind 'halloactivated', dnd.enableDragging editable.bind 'hallodeactivated', dnd.disableDragging )(jQuery)
[ { "context": "###\n backbone-rest.js 0.5.3\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-rest\n Lic", "end": 58, "score": 0.9989028573036194, "start": 50, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/v...
src/index.coffee
founderlab/fl-backbone-rest
0
### backbone-rest.js 0.5.3 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-rest License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {_} = BackboneORM = require 'backbone-orm' module.exports = BackboneREST = require './core' # avoid circular dependencies publish = configure: require './lib/configure' _.extend(BackboneREST, publish) # re-expose modules BackboneREST.modules = {'backbone-orm': BackboneORM}
117101
### backbone-rest.js 0.5.3 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-rest License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {_} = BackboneORM = require 'backbone-orm' module.exports = BackboneREST = require './core' # avoid circular dependencies publish = configure: require './lib/configure' _.extend(BackboneREST, publish) # re-expose modules BackboneREST.modules = {'backbone-orm': BackboneORM}
true
### backbone-rest.js 0.5.3 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-rest License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {_} = BackboneORM = require 'backbone-orm' module.exports = BackboneREST = require './core' # avoid circular dependencies publish = configure: require './lib/configure' _.extend(BackboneREST, publish) # re-expose modules BackboneREST.modules = {'backbone-orm': BackboneORM}
[ { "context": "ata_sale\":\n\t\t\t\t\t\"id_movie\": 1\n\t\t\t\t\t\"name_movie\": \"MISION RESCATE\"\n\t\t\t\t\t\"sl_terminal_id\" : 1\n\t\t\t\t\t\"sl_type_sale_id\"", "end": 327, "score": 0.7919585704803467, "start": 313, "tag": "NAME", "value": "MISION RESCATE" } ]
frontend/frontend/resources/coffee/modules/all/testingJson.coffee
ronnyfly2/delicores
0
define ['libJqueryUi'], () -> st = btn: 'button' dom = {} catchDom = (st) -> dom.btn = $(st.btn) return suscribeEvents = () -> dom.btn.on 'click', events.getJson return events = getJson : (e) -> losDatos = "operation":"Transaction" "data_sale": "id_movie": 1 "name_movie": "MISION RESCATE" "sl_terminal_id" : 1 "sl_type_sale_id" : 1 "card_operation" : "" "customer" : "81" "amount" : "29.000000" "pr_type_pay_id" : 2 "card_code" : "" "total_movies": 17.00 "total_products": 12.00 "EntityList" : "moviesCardEntityList" :[{ "category" : 1 "seat" : "A2" "id" : "1" "codefun" : "16F8" "description" : "Jubilados" "hall" : 2 "uvkcard" : 0 }] "productsCardEntityList" : [{ "category" : 1 "seat" : "" "id" : "135" "codefun" : "16F8" "description" : "COMBO OTTIS" "hall" : "" "uvkcard" : "" }] "employee" : 1 "number" : 1 "turn" : 1 "serie" : 1 "doc_user" : null "extra_detail" : "none" "sale_id" : 0 "payment" : "29.000000" "subsidiaries" : "6" $.ajax method: "POST" url: 'http://10.10.0.61/uvk_middleware/source/public/transactions/createTransactionMobile' dataType: "JSON" data: losDatos beforeSend: ()-> utils.loader $('.pay_section'), true return success: (response)-> if response.status == 1 utils.loader $('.pay_section'), false $('.form_register').submit() $('.error_form').text(response.msg) return else utils.loader $('.pay_section'), false $('.error_form').text(response.msg) return return return catchDom(st) suscribeEvents() return
114697
define ['libJqueryUi'], () -> st = btn: 'button' dom = {} catchDom = (st) -> dom.btn = $(st.btn) return suscribeEvents = () -> dom.btn.on 'click', events.getJson return events = getJson : (e) -> losDatos = "operation":"Transaction" "data_sale": "id_movie": 1 "name_movie": "<NAME>" "sl_terminal_id" : 1 "sl_type_sale_id" : 1 "card_operation" : "" "customer" : "81" "amount" : "29.000000" "pr_type_pay_id" : 2 "card_code" : "" "total_movies": 17.00 "total_products": 12.00 "EntityList" : "moviesCardEntityList" :[{ "category" : 1 "seat" : "A2" "id" : "1" "codefun" : "16F8" "description" : "Jubilados" "hall" : 2 "uvkcard" : 0 }] "productsCardEntityList" : [{ "category" : 1 "seat" : "" "id" : "135" "codefun" : "16F8" "description" : "COMBO OTTIS" "hall" : "" "uvkcard" : "" }] "employee" : 1 "number" : 1 "turn" : 1 "serie" : 1 "doc_user" : null "extra_detail" : "none" "sale_id" : 0 "payment" : "29.000000" "subsidiaries" : "6" $.ajax method: "POST" url: 'http://10.10.0.61/uvk_middleware/source/public/transactions/createTransactionMobile' dataType: "JSON" data: losDatos beforeSend: ()-> utils.loader $('.pay_section'), true return success: (response)-> if response.status == 1 utils.loader $('.pay_section'), false $('.form_register').submit() $('.error_form').text(response.msg) return else utils.loader $('.pay_section'), false $('.error_form').text(response.msg) return return return catchDom(st) suscribeEvents() return
true
define ['libJqueryUi'], () -> st = btn: 'button' dom = {} catchDom = (st) -> dom.btn = $(st.btn) return suscribeEvents = () -> dom.btn.on 'click', events.getJson return events = getJson : (e) -> losDatos = "operation":"Transaction" "data_sale": "id_movie": 1 "name_movie": "PI:NAME:<NAME>END_PI" "sl_terminal_id" : 1 "sl_type_sale_id" : 1 "card_operation" : "" "customer" : "81" "amount" : "29.000000" "pr_type_pay_id" : 2 "card_code" : "" "total_movies": 17.00 "total_products": 12.00 "EntityList" : "moviesCardEntityList" :[{ "category" : 1 "seat" : "A2" "id" : "1" "codefun" : "16F8" "description" : "Jubilados" "hall" : 2 "uvkcard" : 0 }] "productsCardEntityList" : [{ "category" : 1 "seat" : "" "id" : "135" "codefun" : "16F8" "description" : "COMBO OTTIS" "hall" : "" "uvkcard" : "" }] "employee" : 1 "number" : 1 "turn" : 1 "serie" : 1 "doc_user" : null "extra_detail" : "none" "sale_id" : 0 "payment" : "29.000000" "subsidiaries" : "6" $.ajax method: "POST" url: 'http://10.10.0.61/uvk_middleware/source/public/transactions/createTransactionMobile' dataType: "JSON" data: losDatos beforeSend: ()-> utils.loader $('.pay_section'), true return success: (response)-> if response.status == 1 utils.loader $('.pay_section'), false $('.form_register').submit() $('.error_form').text(response.msg) return else utils.loader $('.pay_section'), false $('.error_form').text(response.msg) return return return catchDom(st) suscribeEvents() return
[ { "context": "unt #signin': 'signinacc'\n '.sync .username': 'username'\n '.account .name': 'accusername'\n '.about'", "end": 358, "score": 0.999329149723053, "start": 350, "tag": "USERNAME", "value": "username" }, { "context": " .signedout': 'accsignedout'\n '#accusernam...
app/controllers/settings.coffee
sarthakganguly/notes
191
Spine = require 'spine' $ = Spine.$ shell = window.require('shell') if window.require Sync = require './sync.coffee' Account = require '../controllers/account.coffee' class Settings extends Spine.Controller elements: '.sync #signin': 'signinbtn' '.sync #signout': 'signoutbtn' '.account #signin': 'signinacc' '.sync .username': 'username' '.account .name': 'accusername' '.about': 'aboutPage' '.general': 'generalPage' '.sync .signedin': 'signedin' '.sync .signedout': 'signedout' '.account .signedin': 'accsignedin' '.account .signedout': 'accsignedout' '#accusername': 'usernameinput' '#accpassword': 'passwordinput' '.account .signedin #pro': 'pro' '.account .signedin #alreadypro': 'alreadypro' events: 'click .tabs li': 'tabs' 'click .sync #signin': 'signin' 'click .sync #signout': 'signout' 'click .account #signin': 'accountSignin' 'click .account #signout': 'accountSignout' state: off constructor: -> super # A really bad hack Spine.bind 'sync:authorized', => @hide() @signedout.hide() @signedin.show() $.ajax( Sync.generateRequest {request: "me"} ).done((data) => @username.text data.email ) Spine.bind 'sync:unauthorized', => @signedout.show() @signedin.hide() @signinbtn.text 'Sign In' setInterval () => if Account.isSignedIn() @accsignedout.hide() @accsignedin.show() @accusername.text(Account.get().first_name + " " + Account.get().last_name) if Account.get().pro @pro.hide() @alreadypro.show() else @accsignedin.hide() @accsignedout.show() @pro.show() @alreadypro.hide() ,100 accountSignin: -> if Account.signin(@usernameinput.val(), @passwordinput.val()) if Account.isSignedIn() @hide() Account.enableChecks() else @signinacc.text "Wrong Username/Password" setTimeout () => @signinacc.text "Sign in" , 5000 accountSignout: -> Account.signout() tabs: (e) -> # This is ugly. Shoot me later. Could not think of a better implementation. @el.find('.current').removeClass 'current' @el.find('div.'+$(e.target).addClass('current').attr('data-id')).addClass 'current' show: (tab) -> return unless @state is off @state = on @el.show(0).addClass("show") setTimeout ( => @el.on "click.modal", (event) => if event.target.className.indexOf('modal') > -1 then @hide() ), 500 if Account.isSignedIn() @accsignedin.show() @accsignedout.hide() else @accsignedout.show() @accsignedin.hide() if tab is not null $('.tabs ul li[data-id="'+tab+'"]').click() hide: -> return unless @state is on @state = off @el.removeClass("show") setTimeout ( => @el.hide(0)), 350 @el.off("click.modal") signin: -> @signinbtn.text 'Connecting...' Sync.auth (data) => shell.openExternal(data.url) signout: -> Sync.signOut() settings = null # Temp module.exports = get: -> return settings init: -> settings = new Settings el: $('.modal.preferences')
203568
Spine = require 'spine' $ = Spine.$ shell = window.require('shell') if window.require Sync = require './sync.coffee' Account = require '../controllers/account.coffee' class Settings extends Spine.Controller elements: '.sync #signin': 'signinbtn' '.sync #signout': 'signoutbtn' '.account #signin': 'signinacc' '.sync .username': 'username' '.account .name': 'accusername' '.about': 'aboutPage' '.general': 'generalPage' '.sync .signedin': 'signedin' '.sync .signedout': 'signedout' '.account .signedin': 'accsignedin' '.account .signedout': 'accsignedout' '#accusername': 'usernameinput' '#accpassword': '<PASSWORD>' '.account .signedin #pro': 'pro' '.account .signedin #alreadypro': 'alreadypro' events: 'click .tabs li': 'tabs' 'click .sync #signin': 'signin' 'click .sync #signout': 'signout' 'click .account #signin': 'accountSignin' 'click .account #signout': 'accountSignout' state: off constructor: -> super # A really bad hack Spine.bind 'sync:authorized', => @hide() @signedout.hide() @signedin.show() $.ajax( Sync.generateRequest {request: "me"} ).done((data) => @username.text data.email ) Spine.bind 'sync:unauthorized', => @signedout.show() @signedin.hide() @signinbtn.text 'Sign In' setInterval () => if Account.isSignedIn() @accsignedout.hide() @accsignedin.show() @accusername.text(Account.get().first_name + " " + Account.get().last_name) if Account.get().pro @pro.hide() @alreadypro.show() else @accsignedin.hide() @accsignedout.show() @pro.show() @alreadypro.hide() ,100 accountSignin: -> if Account.signin(@usernameinput.val(), @passwordinput.val()) if Account.isSignedIn() @hide() Account.enableChecks() else @signinacc.text "Wrong Username/Password" setTimeout () => @signinacc.text "Sign in" , 5000 accountSignout: -> Account.signout() tabs: (e) -> # This is ugly. Shoot me later. Could not think of a better implementation. @el.find('.current').removeClass 'current' @el.find('div.'+$(e.target).addClass('current').attr('data-id')).addClass 'current' show: (tab) -> return unless @state is off @state = on @el.show(0).addClass("show") setTimeout ( => @el.on "click.modal", (event) => if event.target.className.indexOf('modal') > -1 then @hide() ), 500 if Account.isSignedIn() @accsignedin.show() @accsignedout.hide() else @accsignedout.show() @accsignedin.hide() if tab is not null $('.tabs ul li[data-id="'+tab+'"]').click() hide: -> return unless @state is on @state = off @el.removeClass("show") setTimeout ( => @el.hide(0)), 350 @el.off("click.modal") signin: -> @signinbtn.text 'Connecting...' Sync.auth (data) => shell.openExternal(data.url) signout: -> Sync.signOut() settings = null # Temp module.exports = get: -> return settings init: -> settings = new Settings el: $('.modal.preferences')
true
Spine = require 'spine' $ = Spine.$ shell = window.require('shell') if window.require Sync = require './sync.coffee' Account = require '../controllers/account.coffee' class Settings extends Spine.Controller elements: '.sync #signin': 'signinbtn' '.sync #signout': 'signoutbtn' '.account #signin': 'signinacc' '.sync .username': 'username' '.account .name': 'accusername' '.about': 'aboutPage' '.general': 'generalPage' '.sync .signedin': 'signedin' '.sync .signedout': 'signedout' '.account .signedin': 'accsignedin' '.account .signedout': 'accsignedout' '#accusername': 'usernameinput' '#accpassword': 'PI:PASSWORD:<PASSWORD>END_PI' '.account .signedin #pro': 'pro' '.account .signedin #alreadypro': 'alreadypro' events: 'click .tabs li': 'tabs' 'click .sync #signin': 'signin' 'click .sync #signout': 'signout' 'click .account #signin': 'accountSignin' 'click .account #signout': 'accountSignout' state: off constructor: -> super # A really bad hack Spine.bind 'sync:authorized', => @hide() @signedout.hide() @signedin.show() $.ajax( Sync.generateRequest {request: "me"} ).done((data) => @username.text data.email ) Spine.bind 'sync:unauthorized', => @signedout.show() @signedin.hide() @signinbtn.text 'Sign In' setInterval () => if Account.isSignedIn() @accsignedout.hide() @accsignedin.show() @accusername.text(Account.get().first_name + " " + Account.get().last_name) if Account.get().pro @pro.hide() @alreadypro.show() else @accsignedin.hide() @accsignedout.show() @pro.show() @alreadypro.hide() ,100 accountSignin: -> if Account.signin(@usernameinput.val(), @passwordinput.val()) if Account.isSignedIn() @hide() Account.enableChecks() else @signinacc.text "Wrong Username/Password" setTimeout () => @signinacc.text "Sign in" , 5000 accountSignout: -> Account.signout() tabs: (e) -> # This is ugly. Shoot me later. Could not think of a better implementation. @el.find('.current').removeClass 'current' @el.find('div.'+$(e.target).addClass('current').attr('data-id')).addClass 'current' show: (tab) -> return unless @state is off @state = on @el.show(0).addClass("show") setTimeout ( => @el.on "click.modal", (event) => if event.target.className.indexOf('modal') > -1 then @hide() ), 500 if Account.isSignedIn() @accsignedin.show() @accsignedout.hide() else @accsignedout.show() @accsignedin.hide() if tab is not null $('.tabs ul li[data-id="'+tab+'"]').click() hide: -> return unless @state is on @state = off @el.removeClass("show") setTimeout ( => @el.hide(0)), 350 @el.off("click.modal") signin: -> @signinbtn.text 'Connecting...' Sync.auth (data) => shell.openExternal(data.url) signout: -> Sync.signOut() settings = null # Temp module.exports = get: -> return settings init: -> settings = new Settings el: $('.modal.preferences')
[ { "context": "e\n #\n # @example\n # values =\n # email: \"john@doe.com\"\n # firstName: \"John\"\n # lastName: \"Doe", "end": 583, "score": 0.9999071359634399, "start": 571, "tag": "EMAIL", "value": "john@doe.com" }, { "context": " # email: \"john@doe.com\"\...
src/ObjectRenderer.coffee
dbartholomae/node-object-renderer
0
((modules, factory) -> # Use define if amd compatible define function is defined if typeof define is 'function' && define.amd define modules, factory # Use node require if not else module.exports = factory (require m for m in modules)... )( ['path', 'when', 'when/keys', 'consolidate'], (pathLib, When, whenKeys, consolidate) -> # Renders an object of templates. Each entry must either be an engine object # {engine: templatePath} or a rendering function ([Object] values) -> [String] rendered template # # @example # values = # email: "john@doe.com" # firstName: "John" # lastName: "Doe" # link: "http://www.example.com/ResetPasswordLink" # # templates = # to: (values) -> values.email # subject: -> "Example.com password reset request" # text: jade: "textTemplate" # # new ObjectRenderer({basePath: "templates"}).render(templates, values).done(console.log) # result = # to: "john@doe.com" # subject: "Example.com password reset request" # text: "Hello John, [...]" # class ObjectRenderer # Create a new ObjectRenderer. # # @param [Object] (options) Optional set of options # @option options [String] basePath A base path to append to all templates. Default: "" # @option options [Boolean] addExtensions add ".{engine}" to all templatePaths in templateObjects {engine: templatePath}. Default: true constructor: (@options) -> @options ?= {} @options.basePath ?= "" @options.addExtensions ?= true # Render the properties of the template object to strings. The resulting # object has the same keys as the templates object set in the constructor. # templates needs to be an object with each property either being an # object {engine: templatePath}, or a rendering function # ([Object] values) -> [String] rendered template # render can either be called with a callback, or, if called without, # will return a promise. # # @overload render(templates, values, callback) # @param [Object] templates The template object # @param [Object] values The values to render # @param [Function] callback The callback to call with (err, result) # # @overload render(templates, values) # @param [Object] templates The template object # @param [Object] values The values to render # @return [Object] A promise for an object containing the rendered strings # @throw "templates should be an object, is " + typeof templates + " instead" # @throw keys " should be of length 1" # @throw key " isn't a renderer engine supported by consolidate" # @throw templates should be an object of functions and template objects render: (templates, values, callback) -> if typeof values is 'function' callback = values values = null unless typeof templates == "object" throw new TypeError "templates should be an object, is " + typeof templates + " instead" for key, template of templates if typeof template is 'object' keys = Object.keys template if keys.length isnt 1 throw new TypeError key + " should be of length 1" else unless consolidate[keys[0]]? throw new TypeError keys[0] + " isn't a renderer engine supported by consolidate" else unless typeof template is 'function' throw new TypeError "templates should be an object of functions and template objects" obj = {} for key, template of templates obj[key] = if typeof template is "object" (for engine, path of template When.promise (resolve, reject) => templatePath = pathLib.join @options.basePath, path + if @options.addExtensions then "." + engine else "" consolidate[engine] templatePath, values, (err, content) -> return reject err if err resolve content )[0] else template(values) promise = whenKeys.all obj if callback promise.done ((result) -> callback null, result), ((err) -> callback err) else return promise )
59405
((modules, factory) -> # Use define if amd compatible define function is defined if typeof define is 'function' && define.amd define modules, factory # Use node require if not else module.exports = factory (require m for m in modules)... )( ['path', 'when', 'when/keys', 'consolidate'], (pathLib, When, whenKeys, consolidate) -> # Renders an object of templates. Each entry must either be an engine object # {engine: templatePath} or a rendering function ([Object] values) -> [String] rendered template # # @example # values = # email: "<EMAIL>" # firstName: "<NAME>" # lastName: "<NAME>" # link: "http://www.example.com/ResetPasswordLink" # # templates = # to: (values) -> values.email # subject: -> "Example.com password reset request" # text: jade: "textTemplate" # # new ObjectRenderer({basePath: "templates"}).render(templates, values).done(console.log) # result = # to: "<EMAIL>" # subject: "Example.com password reset request" # text: "Hello <NAME>, [...]" # class ObjectRenderer # Create a new ObjectRenderer. # # @param [Object] (options) Optional set of options # @option options [String] basePath A base path to append to all templates. Default: "" # @option options [Boolean] addExtensions add ".{engine}" to all templatePaths in templateObjects {engine: templatePath}. Default: true constructor: (@options) -> @options ?= {} @options.basePath ?= "" @options.addExtensions ?= true # Render the properties of the template object to strings. The resulting # object has the same keys as the templates object set in the constructor. # templates needs to be an object with each property either being an # object {engine: templatePath}, or a rendering function # ([Object] values) -> [String] rendered template # render can either be called with a callback, or, if called without, # will return a promise. # # @overload render(templates, values, callback) # @param [Object] templates The template object # @param [Object] values The values to render # @param [Function] callback The callback to call with (err, result) # # @overload render(templates, values) # @param [Object] templates The template object # @param [Object] values The values to render # @return [Object] A promise for an object containing the rendered strings # @throw "templates should be an object, is " + typeof templates + " instead" # @throw keys " should be of length 1" # @throw key " isn't a renderer engine supported by consolidate" # @throw templates should be an object of functions and template objects render: (templates, values, callback) -> if typeof values is 'function' callback = values values = null unless typeof templates == "object" throw new TypeError "templates should be an object, is " + typeof templates + " instead" for key, template of templates if typeof template is 'object' keys = Object.keys template if keys.length isnt 1 throw new TypeError key + " should be of length 1" else unless consolidate[keys[0]]? throw new TypeError keys[0] + " isn't a renderer engine supported by consolidate" else unless typeof template is 'function' throw new TypeError "templates should be an object of functions and template objects" obj = {} for key, template of templates obj[key] = if typeof template is "object" (for engine, path of template When.promise (resolve, reject) => templatePath = pathLib.join @options.basePath, path + if @options.addExtensions then "." + engine else "" consolidate[engine] templatePath, values, (err, content) -> return reject err if err resolve content )[0] else template(values) promise = whenKeys.all obj if callback promise.done ((result) -> callback null, result), ((err) -> callback err) else return promise )
true
((modules, factory) -> # Use define if amd compatible define function is defined if typeof define is 'function' && define.amd define modules, factory # Use node require if not else module.exports = factory (require m for m in modules)... )( ['path', 'when', 'when/keys', 'consolidate'], (pathLib, When, whenKeys, consolidate) -> # Renders an object of templates. Each entry must either be an engine object # {engine: templatePath} or a rendering function ([Object] values) -> [String] rendered template # # @example # values = # email: "PI:EMAIL:<EMAIL>END_PI" # firstName: "PI:NAME:<NAME>END_PI" # lastName: "PI:NAME:<NAME>END_PI" # link: "http://www.example.com/ResetPasswordLink" # # templates = # to: (values) -> values.email # subject: -> "Example.com password reset request" # text: jade: "textTemplate" # # new ObjectRenderer({basePath: "templates"}).render(templates, values).done(console.log) # result = # to: "PI:EMAIL:<EMAIL>END_PI" # subject: "Example.com password reset request" # text: "Hello PI:NAME:<NAME>END_PI, [...]" # class ObjectRenderer # Create a new ObjectRenderer. # # @param [Object] (options) Optional set of options # @option options [String] basePath A base path to append to all templates. Default: "" # @option options [Boolean] addExtensions add ".{engine}" to all templatePaths in templateObjects {engine: templatePath}. Default: true constructor: (@options) -> @options ?= {} @options.basePath ?= "" @options.addExtensions ?= true # Render the properties of the template object to strings. The resulting # object has the same keys as the templates object set in the constructor. # templates needs to be an object with each property either being an # object {engine: templatePath}, or a rendering function # ([Object] values) -> [String] rendered template # render can either be called with a callback, or, if called without, # will return a promise. # # @overload render(templates, values, callback) # @param [Object] templates The template object # @param [Object] values The values to render # @param [Function] callback The callback to call with (err, result) # # @overload render(templates, values) # @param [Object] templates The template object # @param [Object] values The values to render # @return [Object] A promise for an object containing the rendered strings # @throw "templates should be an object, is " + typeof templates + " instead" # @throw keys " should be of length 1" # @throw key " isn't a renderer engine supported by consolidate" # @throw templates should be an object of functions and template objects render: (templates, values, callback) -> if typeof values is 'function' callback = values values = null unless typeof templates == "object" throw new TypeError "templates should be an object, is " + typeof templates + " instead" for key, template of templates if typeof template is 'object' keys = Object.keys template if keys.length isnt 1 throw new TypeError key + " should be of length 1" else unless consolidate[keys[0]]? throw new TypeError keys[0] + " isn't a renderer engine supported by consolidate" else unless typeof template is 'function' throw new TypeError "templates should be an object of functions and template objects" obj = {} for key, template of templates obj[key] = if typeof template is "object" (for engine, path of template When.promise (resolve, reject) => templatePath = pathLib.join @options.basePath, path + if @options.addExtensions then "." + engine else "" consolidate[engine] templatePath, values, (err, content) -> return reject err if err resolve content )[0] else template(values) promise = whenKeys.all obj if callback promise.done ((result) -> callback null, result), ((err) -> callback err) else return promise )
[ { "context": "\nnikita = require '@nikitajs/core/lib'\n{tags, config} = require './test'\nthey ", "end": 28, "score": 0.7920845150947571, "start": 26, "tag": "USERNAME", "value": "js" }, { "context": "store: \"#{tmpdir}/keystore\"\n storepass: \"changeit\"\n caname:...
packages/java/test/keystore_add.coffee
shivaylamba/meilisearch-gatsby-plugin-guide
31
nikita = require '@nikitajs/core/lib' {tags, config} = require './test' they = require('mocha-they')(config) return unless tags.posix describe 'java.keystore_add', -> describe 'schema', -> it 'cacert implies caname', -> await nikita.java.keystore_add $handler: (->) keystore: "ok" storepass: "ok" cacert: "ok" caname: 'ok' await nikita.java.keystore_add keystore: "ok" storepass: "ok" cacert: "implies caname" .should.be.rejectedWith [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'one error was found in the configuration of action `java.keystore_add`:' '#/dependencies/cacert/required config must have required property \'caname\'.' ].join ' ' it 'cert implies key, keypass and name', -> await nikita.java.keystore_add $handler: (->) keystore: "ok" storepass: "ok" cert: "ok" key: "ok" keypass: "ok" name: 'ok' await nikita.java.keystore_add keystore: "ok" storepass: "ok" cert: "implies key, keypass and name" .should.be.rejectedWith [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `java.keystore_add`:' '#/dependencies/cert/required config must have required property \'key\';' '#/dependencies/cert/required config must have required property \'keypass\';' '#/dependencies/cert/required config must have required property \'name\'.' ].join ' ' describe 'config', -> they 'caname, cacert, cert, name, key, keypass are provided', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_caname" cacert: "#{__dirname}/keystore/certs1/cacert.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" name: "my_name" key: "#{__dirname}/keystore/certs1/node_1_key.pem" keypass: 'mypassword' $status.should.be.true() describe 'cacert', -> they 'create new cacerts file', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() they 'create parent directory', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/a/dir/cacerts" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() they 'detect existing cacert signature', ({ssh}) -> nikita $ssh: null $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add $shy: true keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.false() they 'update a new cacert with same alias', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add $shy: true keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" $status.should.be.true() await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias" content: /^my_alias,/m they 'fail if CA file does not exist', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: '/path/to/missing/ca.cert.pem' .should.be.rejectedWith message: 'CA file does not exist: /path/to/missing/ca.cert.pem' they 'import certificate chain', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @execute command: """ mkdir #{tmpdir}/tmp cd #{tmpdir}/tmp openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2.req -keyout ca_int2.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2.cert.pem > ca.cert.pem """ {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{tmpdir}/tmp/ca.cert.pem" $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{tmpdir}/tmp/ca.cert.pem" $status.should.be.false() await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-0" content: /^my_alias-0,/m await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-1" content: /^my_alias-1,/m await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-2" content: /^my_alias-2,/m they 'honors status with certificate chain', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @execute command: """ mkdir #{tmpdir}/ca cd #{tmpdir}/ca openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2a.req -keyout ca_int2a.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2a.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2a.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2a.cert.pem > ca.a.cert.pem openssl req -new -nodes -out ca_int2b.req -keyout ca_int2b.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2b.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2b.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2b.cert.pem > ca.b.cert.pem """ {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{tmpdir}/ca/ca.a.cert.pem" $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{tmpdir}/ca/ca.b.cert.pem" $status.should.be.true() describe 'key', -> they 'create new cacerts file', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' $status.should.be.true() they 'detect existing cacert signature', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' $status.should.be.false() they 'update a new cacert with same alias', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' $status.should.be.true() describe 'keystore', -> they.skip 'change password', ({ssh}) -> nikita $ssh: ssh tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changednow" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() describe 'config openssl', -> they 'throw error if not detected', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'mypassword' openssl: '/doesnt/not/exists' name: 'node_1' .should.be.rejectedWith message: 'OpenSSL command line tool not detected'
140730
nikita = require '@nikitajs/core/lib' {tags, config} = require './test' they = require('mocha-they')(config) return unless tags.posix describe 'java.keystore_add', -> describe 'schema', -> it 'cacert implies caname', -> await nikita.java.keystore_add $handler: (->) keystore: "ok" storepass: "ok" cacert: "ok" caname: 'ok' await nikita.java.keystore_add keystore: "ok" storepass: "ok" cacert: "implies caname" .should.be.rejectedWith [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'one error was found in the configuration of action `java.keystore_add`:' '#/dependencies/cacert/required config must have required property \'caname\'.' ].join ' ' it 'cert implies key, keypass and name', -> await nikita.java.keystore_add $handler: (->) keystore: "ok" storepass: "ok" cert: "ok" key: "ok" keypass: "ok" name: 'ok' await nikita.java.keystore_add keystore: "ok" storepass: "ok" cert: "implies key, keypass and name" .should.be.rejectedWith [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `java.keystore_add`:' '#/dependencies/cert/required config must have required property \'key\';' '#/dependencies/cert/required config must have required property \'keypass\';' '#/dependencies/cert/required config must have required property \'name\'.' ].join ' ' describe 'config', -> they 'caname, cacert, cert, name, key, keypass are provided', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_caname" cacert: "#{__dirname}/keystore/certs1/cacert.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" name: "my_name" key: "#{__dirname}/keystore/certs1/node_1_key.pem" keypass: '<PASSWORD>' $status.should.be.true() describe 'cacert', -> they 'create new cacerts file', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() they 'create parent directory', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/a/dir/cacerts" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() they 'detect existing cacert signature', ({ssh}) -> nikita $ssh: null $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add $shy: true keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.false() they 'update a new cacert with same alias', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add $shy: true keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" $status.should.be.true() await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias" content: /^my_alias,/m they 'fail if CA file does not exist', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: '/path/to/missing/ca.cert.pem' .should.be.rejectedWith message: 'CA file does not exist: /path/to/missing/ca.cert.pem' they 'import certificate chain', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @execute command: """ mkdir #{tmpdir}/tmp cd #{tmpdir}/tmp openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2.req -keyout ca_int2.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2.cert.pem > ca.cert.pem """ {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{tmpdir}/tmp/ca.cert.pem" $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{tmpdir}/tmp/ca.cert.pem" $status.should.be.false() await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-0" content: /^my_alias-0,/m await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-1" content: /^my_alias-1,/m await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-2" content: /^my_alias-2,/m they 'honors status with certificate chain', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @execute command: """ mkdir #{tmpdir}/ca cd #{tmpdir}/ca openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2a.req -keyout ca_int2a.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2a.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2a.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2a.cert.pem > ca.a.cert.pem openssl req -new -nodes -out ca_int2b.req -keyout ca_int2b.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2b.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2b.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2b.cert.pem > ca.b.cert.pem """ {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{tmpdir}/ca/ca.a.cert.pem" $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{tmpdir}/ca/ca.b.cert.pem" $status.should.be.true() describe 'key', -> they 'create new cacerts file', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' $status.should.be.true() they 'detect existing cacert signature', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' $status.should.be.false() they 'update a new cacert with same alias', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' $status.should.be.true() describe 'keystore', -> they.skip 'change password', ({ssh}) -> nikita $ssh: ssh tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() describe 'config openssl', -> they 'throw error if not detected', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node<KEY>_1<KEY>_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: '<PASSWORD>' openssl: '/doesnt/not/exists' name: 'node_1' .should.be.rejectedWith message: 'OpenSSL command line tool not detected'
true
nikita = require '@nikitajs/core/lib' {tags, config} = require './test' they = require('mocha-they')(config) return unless tags.posix describe 'java.keystore_add', -> describe 'schema', -> it 'cacert implies caname', -> await nikita.java.keystore_add $handler: (->) keystore: "ok" storepass: "ok" cacert: "ok" caname: 'ok' await nikita.java.keystore_add keystore: "ok" storepass: "ok" cacert: "implies caname" .should.be.rejectedWith [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'one error was found in the configuration of action `java.keystore_add`:' '#/dependencies/cacert/required config must have required property \'caname\'.' ].join ' ' it 'cert implies key, keypass and name', -> await nikita.java.keystore_add $handler: (->) keystore: "ok" storepass: "ok" cert: "ok" key: "ok" keypass: "ok" name: 'ok' await nikita.java.keystore_add keystore: "ok" storepass: "ok" cert: "implies key, keypass and name" .should.be.rejectedWith [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `java.keystore_add`:' '#/dependencies/cert/required config must have required property \'key\';' '#/dependencies/cert/required config must have required property \'keypass\';' '#/dependencies/cert/required config must have required property \'name\'.' ].join ' ' describe 'config', -> they 'caname, cacert, cert, name, key, keypass are provided', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_caname" cacert: "#{__dirname}/keystore/certs1/cacert.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" name: "my_name" key: "#{__dirname}/keystore/certs1/node_1_key.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.true() describe 'cacert', -> they 'create new cacerts file', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() they 'create parent directory', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/a/dir/cacerts" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() they 'detect existing cacert signature', ({ssh}) -> nikita $ssh: null $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add $shy: true keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.false() they 'update a new cacert with same alias', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add $shy: true keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" $status.should.be.true() await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias" content: /^my_alias,/m they 'fail if CA file does not exist', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: '/path/to/missing/ca.cert.pem' .should.be.rejectedWith message: 'CA file does not exist: /path/to/missing/ca.cert.pem' they 'import certificate chain', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @execute command: """ mkdir #{tmpdir}/tmp cd #{tmpdir}/tmp openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2.req -keyout ca_int2.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2.cert.pem > ca.cert.pem """ {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{tmpdir}/tmp/ca.cert.pem" $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{tmpdir}/tmp/ca.cert.pem" $status.should.be.false() await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-0" content: /^my_alias-0,/m await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-1" content: /^my_alias-1,/m await @execute.assert command: "keytool -list -keystore #{tmpdir}/keystore -storepass changeit -alias my_alias-2" content: /^my_alias-2,/m they 'honors status with certificate chain', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @execute command: """ mkdir #{tmpdir}/ca cd #{tmpdir}/ca openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2a.req -keyout ca_int2a.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2a.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2a.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2a.cert.pem > ca.a.cert.pem openssl req -new -nodes -out ca_int2b.req -keyout ca_int2b.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2b.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2b.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2b.cert.pem > ca.b.cert.pem """ {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{tmpdir}/ca/ca.a.cert.pem" $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{tmpdir}/ca/ca.b.cert.pem" $status.should.be.true() describe 'key', -> they 'create new cacerts file', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' $status.should.be.true() they 'detect existing cacert signature', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' $status.should.be.true() {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' $status.should.be.false() they 'update a new cacert with same alias', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' $status.should.be.true() describe 'keystore', -> they.skip 'change password', ({ssh}) -> nikita $ssh: ssh tmpdir: true , ({metadata: {tmpdir}}) -> await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" {$status} = await @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" $status.should.be.true() describe 'config openssl', -> they 'throw error if not detected', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @java.keystore_add keystore: "#{tmpdir}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/nodePI:KEY:<KEY>END_PI_1PI:KEY:<KEY>END_PI_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' openssl: '/doesnt/not/exists' name: 'node_1' .should.be.rejectedWith message: 'OpenSSL command line tool not detected'
[ { "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/Component/Console/Input/ArgvInput.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. ### Input = use('@Konsserto/Component/Console/Input/Input') Tools = use('@Konsserto/Component/Static/Tools') # # ArgvInput is a set of inputs as a argv command line # # @author Jessym Reziga <jessym@konsserto.com> # class ArgvInput extends Input constructor:(argv,definition,command,@standalone = false) -> @tokens = null @parsed = null if !argv? argv = process.argv.slice(1) # Unshift the command name argv.shift() @tokens = argv super definition,command setTokens:(tokens) -> @tokens = tokens parse:() -> parseOptions = true @parsed = @tokens.slice(0) while undefined != token = @parsed.shift() if parseOptions && token == '' @parseArgument(token) else if parseOptions && token == '--' parseOptions = false else if parseOptions && token.indexOf('--') == 0 @parseLongOption(token) else if parseOptions && '-' == token[0] && '-' != token @parseShortOption(token) else @parseArgument(token) parseShortOption:(token) -> name = token.substr(1) if name.length > 1 if @definition.hasShortcut(name[0]) && @definition.getOptionForShortcut(name[0]).acceptValue() @addShortOption(name[0], name.substr(1)) else @parseShortOptionSet(name) else @addShortOption(name, undefined) parseShortOptionSet:(name) -> len = name.length for i in [0..len] if !@definition.hasShortcut(name[i]) throw new Error('The -'+name[i]+' option does not exist.') option = @definition.getOptionForShortcut(name[i]) if option.acceptValue() @addLongOption(option.getName(), i == len - 1 ? null : name.substr(i + 1)) break else @addLongOption(option.getName(), undefined) parseLongOption:(token) -> name = token.substr(2) pos = name.indexOf('=') if pos >= 0 @addLongOption( name.substr(0,pos), name.substr(pos+1)) else @addLongOption(name, undefined) parseArgument:(token) -> c = Object.keys(@arguments).length if @definition.hasArgument(c) arg = @definition.getArgument(c) @arguments[arg.getName()] = if arg.isArray() then [token] else token else if @definition.hasArgument(c - 1) && @definition.getArgument(c - 1).isArray() arg = @definition.getArgument(c - 1) if @arguments[arg.getName()] == undefined @arguments[arg.getName()] = [] @arguments[arg.getName()].push(token) else if !@standalone throw new Error('Too many arguments.') addShortOption:(shortcut, value) -> if !@definition.hasShortcut(shortcut) throw new Error('The -'+shortcut+' option does not exist.') @addLongOption(@definition.getOptionForShortcut(shortcut).getName(), value) addLongOption:(name, value) -> if !@definition.hasOption(name) throw new Error('The --'+name+' option does not exist.') option = @definition.getOption(name) if undefined != value && !option.acceptValue() throw new Error('The --'+name+' option does not accept a value : '+value) if undefined == value && option.acceptValue() && @parsed.length next = @parsed.shift() if next[0] != undefined && '-' != next[0] value = next else if ( next == '') value = '' else @parsed.unshift(next) if undefined == value if option.isValueRequired() throw new Error('The --'+name+' option requires a value.') if !option.isArray() value = if option.isValueOptional() then option.getDefault() else true if option.isArray() if @options[name] == undefined @options[name] = [] @options[name].push(value) else @options[name] = value getFirstArgument:() -> for token in @tokens if '-' == token.charAt(0) continue return token hasParameterOption:(values) -> for token in @tokens for value in values if token == value || 0 == token.indexOf(value+'=') return true return false getParameterOption:(values,def) -> tokens = @tokens.slice(0) while token = tokens.shift() for value in values if token == value || 0 == token.indexOf(value+'=') if false != pos = token.indexOf('=') return token.substr(pos + 1) return tokens.shift() return def __toString:() -> tokens = @tokens.map( (token) => if (match = token.match('^(-[^=]+=)(.+)')) return match[1] + @escapeToken(match[2]) if token && token[0] != '-' return @escapeToken(token) return token ) return tokens.join(' ') module.exports = ArgvInput;
130006
### * 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. ### Input = use('@Konsserto/Component/Console/Input/Input') Tools = use('@Konsserto/Component/Static/Tools') # # ArgvInput is a set of inputs as a argv command line # # @author <NAME> <<EMAIL>> # class ArgvInput extends Input constructor:(argv,definition,command,@standalone = false) -> @tokens = null @parsed = null if !argv? argv = process.argv.slice(1) # Unshift the command name argv.shift() @tokens = argv super definition,command setTokens:(tokens) -> @tokens = tokens parse:() -> parseOptions = true @parsed = @tokens.slice(0) while undefined != token = @parsed.shift() if parseOptions && token == '' @parseArgument(token) else if parseOptions && token == '--' parseOptions = false else if parseOptions && token.indexOf('--') == 0 @parseLongOption(token) else if parseOptions && '-' == token[0] && '-' != token @parseShortOption(token) else @parseArgument(token) parseShortOption:(token) -> name = token.substr(1) if name.length > 1 if @definition.hasShortcut(name[0]) && @definition.getOptionForShortcut(name[0]).acceptValue() @addShortOption(name[0], name.substr(1)) else @parseShortOptionSet(name) else @addShortOption(name, undefined) parseShortOptionSet:(name) -> len = name.length for i in [0..len] if !@definition.hasShortcut(name[i]) throw new Error('The -'+name[i]+' option does not exist.') option = @definition.getOptionForShortcut(name[i]) if option.acceptValue() @addLongOption(option.getName(), i == len - 1 ? null : name.substr(i + 1)) break else @addLongOption(option.getName(), undefined) parseLongOption:(token) -> name = token.substr(2) pos = name.indexOf('=') if pos >= 0 @addLongOption( name.substr(0,pos), name.substr(pos+1)) else @addLongOption(name, undefined) parseArgument:(token) -> c = Object.keys(@arguments).length if @definition.hasArgument(c) arg = @definition.getArgument(c) @arguments[arg.getName()] = if arg.isArray() then [token] else token else if @definition.hasArgument(c - 1) && @definition.getArgument(c - 1).isArray() arg = @definition.getArgument(c - 1) if @arguments[arg.getName()] == undefined @arguments[arg.getName()] = [] @arguments[arg.getName()].push(token) else if !@standalone throw new Error('Too many arguments.') addShortOption:(shortcut, value) -> if !@definition.hasShortcut(shortcut) throw new Error('The -'+shortcut+' option does not exist.') @addLongOption(@definition.getOptionForShortcut(shortcut).getName(), value) addLongOption:(name, value) -> if !@definition.hasOption(name) throw new Error('The --'+name+' option does not exist.') option = @definition.getOption(name) if undefined != value && !option.acceptValue() throw new Error('The --'+name+' option does not accept a value : '+value) if undefined == value && option.acceptValue() && @parsed.length next = @parsed.shift() if next[0] != undefined && '-' != next[0] value = next else if ( next == '') value = '' else @parsed.unshift(next) if undefined == value if option.isValueRequired() throw new Error('The --'+name+' option requires a value.') if !option.isArray() value = if option.isValueOptional() then option.getDefault() else true if option.isArray() if @options[name] == undefined @options[name] = [] @options[name].push(value) else @options[name] = value getFirstArgument:() -> for token in @tokens if '-' == token.charAt(0) continue return token hasParameterOption:(values) -> for token in @tokens for value in values if token == value || 0 == token.indexOf(value+'=') return true return false getParameterOption:(values,def) -> tokens = @tokens.slice(0) while token = tokens.shift() for value in values if token == value || 0 == token.indexOf(value+'=') if false != pos = token.indexOf('=') return token.substr(pos + 1) return tokens.shift() return def __toString:() -> tokens = @tokens.map( (token) => if (match = token.match('^(-[^=]+=)(.+)')) return match[1] + @escapeToken(match[2]) if token && token[0] != '-' return @escapeToken(token) return token ) return tokens.join(' ') module.exports = ArgvInput;
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. ### Input = use('@Konsserto/Component/Console/Input/Input') Tools = use('@Konsserto/Component/Static/Tools') # # ArgvInput is a set of inputs as a argv command line # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class ArgvInput extends Input constructor:(argv,definition,command,@standalone = false) -> @tokens = null @parsed = null if !argv? argv = process.argv.slice(1) # Unshift the command name argv.shift() @tokens = argv super definition,command setTokens:(tokens) -> @tokens = tokens parse:() -> parseOptions = true @parsed = @tokens.slice(0) while undefined != token = @parsed.shift() if parseOptions && token == '' @parseArgument(token) else if parseOptions && token == '--' parseOptions = false else if parseOptions && token.indexOf('--') == 0 @parseLongOption(token) else if parseOptions && '-' == token[0] && '-' != token @parseShortOption(token) else @parseArgument(token) parseShortOption:(token) -> name = token.substr(1) if name.length > 1 if @definition.hasShortcut(name[0]) && @definition.getOptionForShortcut(name[0]).acceptValue() @addShortOption(name[0], name.substr(1)) else @parseShortOptionSet(name) else @addShortOption(name, undefined) parseShortOptionSet:(name) -> len = name.length for i in [0..len] if !@definition.hasShortcut(name[i]) throw new Error('The -'+name[i]+' option does not exist.') option = @definition.getOptionForShortcut(name[i]) if option.acceptValue() @addLongOption(option.getName(), i == len - 1 ? null : name.substr(i + 1)) break else @addLongOption(option.getName(), undefined) parseLongOption:(token) -> name = token.substr(2) pos = name.indexOf('=') if pos >= 0 @addLongOption( name.substr(0,pos), name.substr(pos+1)) else @addLongOption(name, undefined) parseArgument:(token) -> c = Object.keys(@arguments).length if @definition.hasArgument(c) arg = @definition.getArgument(c) @arguments[arg.getName()] = if arg.isArray() then [token] else token else if @definition.hasArgument(c - 1) && @definition.getArgument(c - 1).isArray() arg = @definition.getArgument(c - 1) if @arguments[arg.getName()] == undefined @arguments[arg.getName()] = [] @arguments[arg.getName()].push(token) else if !@standalone throw new Error('Too many arguments.') addShortOption:(shortcut, value) -> if !@definition.hasShortcut(shortcut) throw new Error('The -'+shortcut+' option does not exist.') @addLongOption(@definition.getOptionForShortcut(shortcut).getName(), value) addLongOption:(name, value) -> if !@definition.hasOption(name) throw new Error('The --'+name+' option does not exist.') option = @definition.getOption(name) if undefined != value && !option.acceptValue() throw new Error('The --'+name+' option does not accept a value : '+value) if undefined == value && option.acceptValue() && @parsed.length next = @parsed.shift() if next[0] != undefined && '-' != next[0] value = next else if ( next == '') value = '' else @parsed.unshift(next) if undefined == value if option.isValueRequired() throw new Error('The --'+name+' option requires a value.') if !option.isArray() value = if option.isValueOptional() then option.getDefault() else true if option.isArray() if @options[name] == undefined @options[name] = [] @options[name].push(value) else @options[name] = value getFirstArgument:() -> for token in @tokens if '-' == token.charAt(0) continue return token hasParameterOption:(values) -> for token in @tokens for value in values if token == value || 0 == token.indexOf(value+'=') return true return false getParameterOption:(values,def) -> tokens = @tokens.slice(0) while token = tokens.shift() for value in values if token == value || 0 == token.indexOf(value+'=') if false != pos = token.indexOf('=') return token.substr(pos + 1) return tokens.shift() return def __toString:() -> tokens = @tokens.map( (token) => if (match = token.match('^(-[^=]+=)(.+)')) return match[1] + @escapeToken(match[2]) if token && token[0] != '-' return @escapeToken(token) return token ) return tokens.join(' ') module.exports = ArgvInput;
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9995062947273254, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "\nassert = require(\"assert\")\n\n# https://github.com/joyent/node/issues/2079 - zero timeout ...
test/simple/test-timers-zero-timeout.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") # https://github.com/joyent/node/issues/2079 - zero timeout drops extra args (-> f = (a, b, c) -> assert.equal a, "foo" assert.equal b, "bar" assert.equal c, "baz" ncalled++ return ncalled = 0 setTimeout f, 0, "foo", "bar", "baz" timer = setTimeout(-> , 0) process.on "exit", -> assert.equal ncalled, 1 return return )() (-> f = (a, b, c) -> assert.equal a, "foo" assert.equal b, "bar" assert.equal c, "baz" clearTimeout iv if ++ncalled is 3 return ncalled = 0 iv = setInterval(f, 0, "foo", "bar", "baz") process.on "exit", -> assert.equal ncalled, 3 return return )()
134887
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") # https://github.com/joyent/node/issues/2079 - zero timeout drops extra args (-> f = (a, b, c) -> assert.equal a, "foo" assert.equal b, "bar" assert.equal c, "baz" ncalled++ return ncalled = 0 setTimeout f, 0, "foo", "bar", "baz" timer = setTimeout(-> , 0) process.on "exit", -> assert.equal ncalled, 1 return return )() (-> f = (a, b, c) -> assert.equal a, "foo" assert.equal b, "bar" assert.equal c, "baz" clearTimeout iv if ++ncalled is 3 return ncalled = 0 iv = setInterval(f, 0, "foo", "bar", "baz") process.on "exit", -> assert.equal ncalled, 3 return return )()
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") # https://github.com/joyent/node/issues/2079 - zero timeout drops extra args (-> f = (a, b, c) -> assert.equal a, "foo" assert.equal b, "bar" assert.equal c, "baz" ncalled++ return ncalled = 0 setTimeout f, 0, "foo", "bar", "baz" timer = setTimeout(-> , 0) process.on "exit", -> assert.equal ncalled, 1 return return )() (-> f = (a, b, c) -> assert.equal a, "foo" assert.equal b, "bar" assert.equal c, "baz" clearTimeout iv if ++ncalled is 3 return ncalled = 0 iv = setInterval(f, 0, "foo", "bar", "baz") process.on "exit", -> assert.equal ncalled, 3 return return )()
[ { "context": "ittle Mocha Reference ========\nhttps://github.com/visionmedia/should.js\nhttps://github.com/visionmedia/mocha\n##", "end": 167, "score": 0.9994863271713257, "start": 156, "tag": "USERNAME", "value": "visionmedia" }, { "context": "thub.com/visionmedia/should.js\nhttps:/...
nodejs/flarebyte.net/0.8/node/magma/node_modules/magma-constant/test/magma-constant_test.coffee
flarebyte/wonderful-bazar
0
'use strict' magma_constant = require('magma-constant') should = require('should') ### ======== A Handy Little Mocha Reference ======== https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha ### REQUIRED= "required" OPTIONAL= "optional" describe 'magma-constant', ()-> describe '#REGEX_GATE_ID()', ()-> it 'captures correct gate id ', ()-> v=magma_constant.EX_GATE_ID magma_constant.REGEX_GATE_ID.test(v).should.be.true it 'rejects incorrect gate id ', ()-> v= magma_constant.EX_GATE_ID+"000" magma_constant.REGEX_GATE_ID.test(v).should.be.false describe '#REGEX_UNIVERSE_ID()', ()-> it 'captures correct universe id ', ()-> v=magma_constant.EX_UNIVERSE_ID magma_constant.REGEX_UNIVERSE_ID.test(v).should.be.true it 'rejects incorrect gate id ', ()-> v= magma_constant.EX_UNIVERSE_ID+";" magma_constant.REGEX_UNIVERSE_ID.test(v).should.be.false describe '#REGEX_VIEW_ID()', ()-> it 'captures correct view id ', ()-> v=magma_constant.EX_VIEW_ID magma_constant.REGEX_VIEW_ID.test(v).should.be.true it 'rejects incorrect view id ', ()-> v= magma_constant.EX_VIEW_ID+"aa" magma_constant.REGEX_VIEW_ID.test(v).should.be.false describe '#REGEX_USER_ID()', ()-> it 'captures correct user id ', ()-> v=magma_constant.EX_USER_ID magma_constant.REGEX_USER_ID.test(v).should.be.true it 'rejects incorrect user id ', ()-> v= magma_constant.EX_USER_ID+";" magma_constant.REGEX_USER_ID.test(v).should.be.false describe '#REGEX_MESSAGE_ID()', ()-> it 'captures correct message id ', ()-> v=magma_constant.EX_MESSAGE_ID magma_constant.REGEX_MESSAGE_ID.test(v).should.be.true it 'rejects incorrect message id ', ()-> v= magma_constant.EX_MESSAGE_ID+";" magma_constant.REGEX_MESSAGE_ID.test(v).should.be.false describe '#REGEX_ROLE_ID()', ()-> it 'captures correct role id ', ()-> v=magma_constant.EX_ROLE_ID magma_constant.REGEX_ROLE_ID.test(v).should.be.true it 'rejects incorrect role id ', ()-> v= magma_constant.EX_ROLE_ID+"<<" magma_constant.REGEX_ROLE_ID.test(v).should.be.false describe '#REGEX_TENANT_ID()', ()-> it 'captures correct tenant id ', ()-> v=magma_constant.EX_TENANT_ID magma_constant.REGEX_TENANT_ID.test(v).should.be.true it 'rejects incorrect tenant id ', ()-> v= magma_constant.EX_TENANT_ID+"?" magma_constant.REGEX_TENANT_ID.test(v).should.be.false describe '#REGEX_PLUGIN_ID()', ()-> it 'captures correct plugin id ', ()-> v=magma_constant.EX_PLUGIN_ID magma_constant.REGEX_PLUGIN_ID.test(v).should.be.true it 'rejects incorrect plugin id ', ()-> v= magma_constant.EX_PLUGIN_ID+"<<" magma_constant.REGEX_PLUGIN_ID.test(v).should.be.false describe '#REGEX_TASKTYPE_ID()', ()-> it 'captures correct tasktype id ', ()-> v=magma_constant.TASKTYPE_PARALLEL magma_constant.REGEX_TASKTYPE_ID.test(v).should.be.true it 'rejects incorrect tasktype id ', ()-> v= magma_constant.TASKTYPE_PARALLEL+"<<" magma_constant.REGEX_TASKTYPE_ID.test(v).should.be.false describe '#REGEX_PREDICATE_ID()', ()-> it 'captures correct predicate id ', ()-> v=magma_constant.EX_PREDICATE_ID magma_constant.REGEX_PREDICATE_ID.test(v).should.be.true it 'rejects incorrect predicate id ', ()-> v= magma_constant.EX_PREDICATE_ID+"<<" magma_constant.REGEX_PREDICATE_ID.test(v).should.be.false describe '#REGEX_AGREEMENT_ID()', ()-> it 'captures correct agreement id ', ()-> v=magma_constant.EX_AGREEMENT_ID magma_constant.REGEX_AGREEMENT_ID.test(v).should.be.true it 'rejects incorrect agreement id ', ()-> v= magma_constant.EX_AGREEMENT_ID+"<<" magma_constant.REGEX_AGREEMENT_ID.test(v).should.be.false describe '#REGEX_VIEW_PROPS_ID()', ()-> it 'captures correct view props id ', ()-> v=magma_constant.EX_VIEW_PROPS_ID magma_constant.REGEX_VIEW_PROPS_ID.test(v).should.be.true it 'rejects incorrect view props id ', ()-> v= magma_constant.EX_VIEW_PROPS_ID+"<<" magma_constant.REGEX_VIEW_PROPS_ID.test(v).should.be.false describe '#REGEX_VIEW_I18N_ID()', ()-> it 'captures correct view i18n id ', ()-> v=magma_constant.EX_VIEW_I18N_ID magma_constant.REGEX_VIEW_I18N_ID.test(v).should.be.true it 'rejects incorrect view i18n id ', ()-> v= magma_constant.EX_VIEW_I18N_ID+"<<" magma_constant.REGEX_VIEW_I18N_ID.test(v).should.be.false describe '#REGEX_NAME()', ()-> it 'captures correct name ', ()-> v= "good name" magma_constant.REGEX_NAME.test(v).should.be.true it 'rejects incorrect name ', ()-> v= "<<bad name" magma_constant.REGEX_NAME.test(v).should.be.false it 'rejects incorrect space in name ', ()-> v= "big space" magma_constant.REGEX_NAME.test(v).should.be.false describe '#REGEX_VERB_ID()', ()-> it 'captures correct verb id ', ()-> v=magma_constant.VERB_GET magma_constant.REGEX_VERB_ID.test(v).should.be.true it 'rejects incorrect verb id ', ()-> v= magma_constant.VERT_PUT+"<<" magma_constant.REGEX_VERB_ID.test(v).should.be.false describe '#REGEX_ISO_DATE()', ()-> it 'captures correct iso date', ()-> v=magma_constant.EX_ISO_DATE magma_constant.REGEX_ISO_DATE.test(v).should.be.true it 'rejects incorrect iso date', ()-> v= "01-02-2013" magma_constant.REGEX_ISO_DATE.test(v).should.be.false describe '#REGEX_ISO_DATETIME()', ()-> it 'captures correct iso date time', ()-> v=magma_constant.EX_ISO_DATETIME magma_constant.REGEX_ISO_DATETIME.test(v).should.be.true it 'rejects incorrect iso date time', ()-> v= "01-02-2013" magma_constant.REGEX_ISO_DATE.test(v).should.be.false describe '#REGEX_DOMAIN_ID()', ()-> it 'captures correct domain id ', ()-> v= magma_constant.EX_DOMAIN_ID magma_constant.REGEX_DOMAIN_ID.test(v).should.be.true it 'rejects incorrect domain id ', ()-> v= magma_constant.EX_DOMAIN_ID+"<<" magma_constant.REGEX_DOMAIN_ID.test(v).should.be.false describe '#REGEX_DOMAIN_NAME()', ()-> it 'captures correct domain name ', ()-> v= magma_constant.EX_DOMAIN_NAME magma_constant.REGEX_DOMAIN_NAME.test(v).should.be.true it 'rejects incorrect domain name', ()-> v= magma_constant.EX_DOMAIN_NAME+"<<" magma_constant.REGEX_DOMAIN_NAME.test(v).should.be.false describe 'hashId()', ()-> it 'generate hash for an id', ()-> v= magma_constant.hashId("charles.baudelaire@gmail.com") v.should.be.eql( 'ae663b54786aed38f8043055a9d022beb37b18d455d3908eb3d8f9aebf20f14d') describe 'validObjectFromModel()', ()-> modelGood= key1:[OPTIONAL,'val2'] it 'validate an object from model', ()-> v= magma_constant.validObjectFromModel({},modelGood) (v == null).should.be.true
89510
'use strict' magma_constant = require('magma-constant') should = require('should') ### ======== A Handy Little Mocha Reference ======== https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha ### REQUIRED= "required" OPTIONAL= "optional" describe 'magma-constant', ()-> describe '#REGEX_GATE_ID()', ()-> it 'captures correct gate id ', ()-> v=magma_constant.EX_GATE_ID magma_constant.REGEX_GATE_ID.test(v).should.be.true it 'rejects incorrect gate id ', ()-> v= magma_constant.EX_GATE_ID+"000" magma_constant.REGEX_GATE_ID.test(v).should.be.false describe '#REGEX_UNIVERSE_ID()', ()-> it 'captures correct universe id ', ()-> v=magma_constant.EX_UNIVERSE_ID magma_constant.REGEX_UNIVERSE_ID.test(v).should.be.true it 'rejects incorrect gate id ', ()-> v= magma_constant.EX_UNIVERSE_ID+";" magma_constant.REGEX_UNIVERSE_ID.test(v).should.be.false describe '#REGEX_VIEW_ID()', ()-> it 'captures correct view id ', ()-> v=magma_constant.EX_VIEW_ID magma_constant.REGEX_VIEW_ID.test(v).should.be.true it 'rejects incorrect view id ', ()-> v= magma_constant.EX_VIEW_ID+"aa" magma_constant.REGEX_VIEW_ID.test(v).should.be.false describe '#REGEX_USER_ID()', ()-> it 'captures correct user id ', ()-> v=magma_constant.EX_USER_ID magma_constant.REGEX_USER_ID.test(v).should.be.true it 'rejects incorrect user id ', ()-> v= magma_constant.EX_USER_ID+";" magma_constant.REGEX_USER_ID.test(v).should.be.false describe '#REGEX_MESSAGE_ID()', ()-> it 'captures correct message id ', ()-> v=magma_constant.EX_MESSAGE_ID magma_constant.REGEX_MESSAGE_ID.test(v).should.be.true it 'rejects incorrect message id ', ()-> v= magma_constant.EX_MESSAGE_ID+";" magma_constant.REGEX_MESSAGE_ID.test(v).should.be.false describe '#REGEX_ROLE_ID()', ()-> it 'captures correct role id ', ()-> v=magma_constant.EX_ROLE_ID magma_constant.REGEX_ROLE_ID.test(v).should.be.true it 'rejects incorrect role id ', ()-> v= magma_constant.EX_ROLE_ID+"<<" magma_constant.REGEX_ROLE_ID.test(v).should.be.false describe '#REGEX_TENANT_ID()', ()-> it 'captures correct tenant id ', ()-> v=magma_constant.EX_TENANT_ID magma_constant.REGEX_TENANT_ID.test(v).should.be.true it 'rejects incorrect tenant id ', ()-> v= magma_constant.EX_TENANT_ID+"?" magma_constant.REGEX_TENANT_ID.test(v).should.be.false describe '#REGEX_PLUGIN_ID()', ()-> it 'captures correct plugin id ', ()-> v=magma_constant.EX_PLUGIN_ID magma_constant.REGEX_PLUGIN_ID.test(v).should.be.true it 'rejects incorrect plugin id ', ()-> v= magma_constant.EX_PLUGIN_ID+"<<" magma_constant.REGEX_PLUGIN_ID.test(v).should.be.false describe '#REGEX_TASKTYPE_ID()', ()-> it 'captures correct tasktype id ', ()-> v=magma_constant.TASKTYPE_PARALLEL magma_constant.REGEX_TASKTYPE_ID.test(v).should.be.true it 'rejects incorrect tasktype id ', ()-> v= magma_constant.TASKTYPE_PARALLEL+"<<" magma_constant.REGEX_TASKTYPE_ID.test(v).should.be.false describe '#REGEX_PREDICATE_ID()', ()-> it 'captures correct predicate id ', ()-> v=magma_constant.EX_PREDICATE_ID magma_constant.REGEX_PREDICATE_ID.test(v).should.be.true it 'rejects incorrect predicate id ', ()-> v= magma_constant.EX_PREDICATE_ID+"<<" magma_constant.REGEX_PREDICATE_ID.test(v).should.be.false describe '#REGEX_AGREEMENT_ID()', ()-> it 'captures correct agreement id ', ()-> v=magma_constant.EX_AGREEMENT_ID magma_constant.REGEX_AGREEMENT_ID.test(v).should.be.true it 'rejects incorrect agreement id ', ()-> v= magma_constant.EX_AGREEMENT_ID+"<<" magma_constant.REGEX_AGREEMENT_ID.test(v).should.be.false describe '#REGEX_VIEW_PROPS_ID()', ()-> it 'captures correct view props id ', ()-> v=magma_constant.EX_VIEW_PROPS_ID magma_constant.REGEX_VIEW_PROPS_ID.test(v).should.be.true it 'rejects incorrect view props id ', ()-> v= magma_constant.EX_VIEW_PROPS_ID+"<<" magma_constant.REGEX_VIEW_PROPS_ID.test(v).should.be.false describe '#REGEX_VIEW_I18N_ID()', ()-> it 'captures correct view i18n id ', ()-> v=magma_constant.EX_VIEW_I18N_ID magma_constant.REGEX_VIEW_I18N_ID.test(v).should.be.true it 'rejects incorrect view i18n id ', ()-> v= magma_constant.EX_VIEW_I18N_ID+"<<" magma_constant.REGEX_VIEW_I18N_ID.test(v).should.be.false describe '#REGEX_NAME()', ()-> it 'captures correct name ', ()-> v= "good name" magma_constant.REGEX_NAME.test(v).should.be.true it 'rejects incorrect name ', ()-> v= "<<bad name" magma_constant.REGEX_NAME.test(v).should.be.false it 'rejects incorrect space in name ', ()-> v= "big space" magma_constant.REGEX_NAME.test(v).should.be.false describe '#REGEX_VERB_ID()', ()-> it 'captures correct verb id ', ()-> v=magma_constant.VERB_GET magma_constant.REGEX_VERB_ID.test(v).should.be.true it 'rejects incorrect verb id ', ()-> v= magma_constant.VERT_PUT+"<<" magma_constant.REGEX_VERB_ID.test(v).should.be.false describe '#REGEX_ISO_DATE()', ()-> it 'captures correct iso date', ()-> v=magma_constant.EX_ISO_DATE magma_constant.REGEX_ISO_DATE.test(v).should.be.true it 'rejects incorrect iso date', ()-> v= "01-02-2013" magma_constant.REGEX_ISO_DATE.test(v).should.be.false describe '#REGEX_ISO_DATETIME()', ()-> it 'captures correct iso date time', ()-> v=magma_constant.EX_ISO_DATETIME magma_constant.REGEX_ISO_DATETIME.test(v).should.be.true it 'rejects incorrect iso date time', ()-> v= "01-02-2013" magma_constant.REGEX_ISO_DATE.test(v).should.be.false describe '#REGEX_DOMAIN_ID()', ()-> it 'captures correct domain id ', ()-> v= magma_constant.EX_DOMAIN_ID magma_constant.REGEX_DOMAIN_ID.test(v).should.be.true it 'rejects incorrect domain id ', ()-> v= magma_constant.EX_DOMAIN_ID+"<<" magma_constant.REGEX_DOMAIN_ID.test(v).should.be.false describe '#REGEX_DOMAIN_NAME()', ()-> it 'captures correct domain name ', ()-> v= magma_constant.EX_DOMAIN_NAME magma_constant.REGEX_DOMAIN_NAME.test(v).should.be.true it 'rejects incorrect domain name', ()-> v= magma_constant.EX_DOMAIN_NAME+"<<" magma_constant.REGEX_DOMAIN_NAME.test(v).should.be.false describe 'hashId()', ()-> it 'generate hash for an id', ()-> v= magma_constant.hashId("<EMAIL>") v.should.be.eql( 'ae663b54786aed38f8043055a9d022beb37b18d455d3908eb3d8f9aebf20f14d') describe 'validObjectFromModel()', ()-> modelGood= key1:[OPTIONAL,'val<KEY>'] it 'validate an object from model', ()-> v= magma_constant.validObjectFromModel({},modelGood) (v == null).should.be.true
true
'use strict' magma_constant = require('magma-constant') should = require('should') ### ======== A Handy Little Mocha Reference ======== https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha ### REQUIRED= "required" OPTIONAL= "optional" describe 'magma-constant', ()-> describe '#REGEX_GATE_ID()', ()-> it 'captures correct gate id ', ()-> v=magma_constant.EX_GATE_ID magma_constant.REGEX_GATE_ID.test(v).should.be.true it 'rejects incorrect gate id ', ()-> v= magma_constant.EX_GATE_ID+"000" magma_constant.REGEX_GATE_ID.test(v).should.be.false describe '#REGEX_UNIVERSE_ID()', ()-> it 'captures correct universe id ', ()-> v=magma_constant.EX_UNIVERSE_ID magma_constant.REGEX_UNIVERSE_ID.test(v).should.be.true it 'rejects incorrect gate id ', ()-> v= magma_constant.EX_UNIVERSE_ID+";" magma_constant.REGEX_UNIVERSE_ID.test(v).should.be.false describe '#REGEX_VIEW_ID()', ()-> it 'captures correct view id ', ()-> v=magma_constant.EX_VIEW_ID magma_constant.REGEX_VIEW_ID.test(v).should.be.true it 'rejects incorrect view id ', ()-> v= magma_constant.EX_VIEW_ID+"aa" magma_constant.REGEX_VIEW_ID.test(v).should.be.false describe '#REGEX_USER_ID()', ()-> it 'captures correct user id ', ()-> v=magma_constant.EX_USER_ID magma_constant.REGEX_USER_ID.test(v).should.be.true it 'rejects incorrect user id ', ()-> v= magma_constant.EX_USER_ID+";" magma_constant.REGEX_USER_ID.test(v).should.be.false describe '#REGEX_MESSAGE_ID()', ()-> it 'captures correct message id ', ()-> v=magma_constant.EX_MESSAGE_ID magma_constant.REGEX_MESSAGE_ID.test(v).should.be.true it 'rejects incorrect message id ', ()-> v= magma_constant.EX_MESSAGE_ID+";" magma_constant.REGEX_MESSAGE_ID.test(v).should.be.false describe '#REGEX_ROLE_ID()', ()-> it 'captures correct role id ', ()-> v=magma_constant.EX_ROLE_ID magma_constant.REGEX_ROLE_ID.test(v).should.be.true it 'rejects incorrect role id ', ()-> v= magma_constant.EX_ROLE_ID+"<<" magma_constant.REGEX_ROLE_ID.test(v).should.be.false describe '#REGEX_TENANT_ID()', ()-> it 'captures correct tenant id ', ()-> v=magma_constant.EX_TENANT_ID magma_constant.REGEX_TENANT_ID.test(v).should.be.true it 'rejects incorrect tenant id ', ()-> v= magma_constant.EX_TENANT_ID+"?" magma_constant.REGEX_TENANT_ID.test(v).should.be.false describe '#REGEX_PLUGIN_ID()', ()-> it 'captures correct plugin id ', ()-> v=magma_constant.EX_PLUGIN_ID magma_constant.REGEX_PLUGIN_ID.test(v).should.be.true it 'rejects incorrect plugin id ', ()-> v= magma_constant.EX_PLUGIN_ID+"<<" magma_constant.REGEX_PLUGIN_ID.test(v).should.be.false describe '#REGEX_TASKTYPE_ID()', ()-> it 'captures correct tasktype id ', ()-> v=magma_constant.TASKTYPE_PARALLEL magma_constant.REGEX_TASKTYPE_ID.test(v).should.be.true it 'rejects incorrect tasktype id ', ()-> v= magma_constant.TASKTYPE_PARALLEL+"<<" magma_constant.REGEX_TASKTYPE_ID.test(v).should.be.false describe '#REGEX_PREDICATE_ID()', ()-> it 'captures correct predicate id ', ()-> v=magma_constant.EX_PREDICATE_ID magma_constant.REGEX_PREDICATE_ID.test(v).should.be.true it 'rejects incorrect predicate id ', ()-> v= magma_constant.EX_PREDICATE_ID+"<<" magma_constant.REGEX_PREDICATE_ID.test(v).should.be.false describe '#REGEX_AGREEMENT_ID()', ()-> it 'captures correct agreement id ', ()-> v=magma_constant.EX_AGREEMENT_ID magma_constant.REGEX_AGREEMENT_ID.test(v).should.be.true it 'rejects incorrect agreement id ', ()-> v= magma_constant.EX_AGREEMENT_ID+"<<" magma_constant.REGEX_AGREEMENT_ID.test(v).should.be.false describe '#REGEX_VIEW_PROPS_ID()', ()-> it 'captures correct view props id ', ()-> v=magma_constant.EX_VIEW_PROPS_ID magma_constant.REGEX_VIEW_PROPS_ID.test(v).should.be.true it 'rejects incorrect view props id ', ()-> v= magma_constant.EX_VIEW_PROPS_ID+"<<" magma_constant.REGEX_VIEW_PROPS_ID.test(v).should.be.false describe '#REGEX_VIEW_I18N_ID()', ()-> it 'captures correct view i18n id ', ()-> v=magma_constant.EX_VIEW_I18N_ID magma_constant.REGEX_VIEW_I18N_ID.test(v).should.be.true it 'rejects incorrect view i18n id ', ()-> v= magma_constant.EX_VIEW_I18N_ID+"<<" magma_constant.REGEX_VIEW_I18N_ID.test(v).should.be.false describe '#REGEX_NAME()', ()-> it 'captures correct name ', ()-> v= "good name" magma_constant.REGEX_NAME.test(v).should.be.true it 'rejects incorrect name ', ()-> v= "<<bad name" magma_constant.REGEX_NAME.test(v).should.be.false it 'rejects incorrect space in name ', ()-> v= "big space" magma_constant.REGEX_NAME.test(v).should.be.false describe '#REGEX_VERB_ID()', ()-> it 'captures correct verb id ', ()-> v=magma_constant.VERB_GET magma_constant.REGEX_VERB_ID.test(v).should.be.true it 'rejects incorrect verb id ', ()-> v= magma_constant.VERT_PUT+"<<" magma_constant.REGEX_VERB_ID.test(v).should.be.false describe '#REGEX_ISO_DATE()', ()-> it 'captures correct iso date', ()-> v=magma_constant.EX_ISO_DATE magma_constant.REGEX_ISO_DATE.test(v).should.be.true it 'rejects incorrect iso date', ()-> v= "01-02-2013" magma_constant.REGEX_ISO_DATE.test(v).should.be.false describe '#REGEX_ISO_DATETIME()', ()-> it 'captures correct iso date time', ()-> v=magma_constant.EX_ISO_DATETIME magma_constant.REGEX_ISO_DATETIME.test(v).should.be.true it 'rejects incorrect iso date time', ()-> v= "01-02-2013" magma_constant.REGEX_ISO_DATE.test(v).should.be.false describe '#REGEX_DOMAIN_ID()', ()-> it 'captures correct domain id ', ()-> v= magma_constant.EX_DOMAIN_ID magma_constant.REGEX_DOMAIN_ID.test(v).should.be.true it 'rejects incorrect domain id ', ()-> v= magma_constant.EX_DOMAIN_ID+"<<" magma_constant.REGEX_DOMAIN_ID.test(v).should.be.false describe '#REGEX_DOMAIN_NAME()', ()-> it 'captures correct domain name ', ()-> v= magma_constant.EX_DOMAIN_NAME magma_constant.REGEX_DOMAIN_NAME.test(v).should.be.true it 'rejects incorrect domain name', ()-> v= magma_constant.EX_DOMAIN_NAME+"<<" magma_constant.REGEX_DOMAIN_NAME.test(v).should.be.false describe 'hashId()', ()-> it 'generate hash for an id', ()-> v= magma_constant.hashId("PI:EMAIL:<EMAIL>END_PI") v.should.be.eql( 'ae663b54786aed38f8043055a9d022beb37b18d455d3908eb3d8f9aebf20f14d') describe 'validObjectFromModel()', ()-> modelGood= key1:[OPTIONAL,'valPI:KEY:<KEY>END_PI'] it 'validate an object from model', ()-> v= magma_constant.validObjectFromModel({},modelGood) (v == null).should.be.true
[ { "context": "string.\n #\n # Examples\n #\n # auth.setToken('eyJh...9jQ3I')\n #\n # Returns nothing.\n setToken: (token) ->", "end": 4331, "score": 0.9680439829826355, "start": 4319, "tag": "PASSWORD", "value": "eyJh...9jQ3I" }, { "context": "urn\n\n if this.haveValidTok...
inception-html-editor/src/main/js/annotatorjs/src/plugin/auth.coffee
CPHI-TVHS/inception
377
# Public: Creates a Date object from an ISO8601 formatted date String. # # string - ISO8601 formatted date String. # # Returns Date instance. createDateFromISO8601 = (string) -> regexp = ( "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?" ) d = string.match(new RegExp(regexp)) offset = 0 date = new Date(d[1], 0, 1) date.setMonth(d[3] - 1) if d[3] date.setDate(d[5]) if d[5] date.setHours(d[7]) if d[7] date.setMinutes(d[8]) if d[8] date.setSeconds(d[10]) if d[10] date.setMilliseconds(Number("0." + d[12]) * 1000) if d[12] if d[14] offset = (Number(d[16]) * 60) + Number(d[17]) offset *= ((d[15] == '-') ? 1 : -1) offset -= date.getTimezoneOffset() time = (Number(date) + (offset * 60 * 1000)) date.setTime(Number(time)) date base64Decode = (data) -> if atob? # Gecko and Webkit provide native code for this atob(data) else # Adapted from MIT/BSD licensed code at http://phpjs.org/functions/base64_decode # version 1109.2015 b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" i = 0 ac = 0 dec = "" tmp_arr = [] if not data return data data += '' while i < data.length # unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)) h2 = b64.indexOf(data.charAt(i++)) h3 = b64.indexOf(data.charAt(i++)) h4 = b64.indexOf(data.charAt(i++)) bits = h1 << 18 | h2 << 12 | h3 << 6 | h4 o1 = bits >> 16 & 0xff o2 = bits >> 8 & 0xff o3 = bits & 0xff if h3 == 64 tmp_arr[ac++] = String.fromCharCode(o1) else if h4 == 64 tmp_arr[ac++] = String.fromCharCode(o1, o2) else tmp_arr[ac++] = String.fromCharCode(o1, o2, o3) tmp_arr.join('') base64UrlDecode = (data) -> m = data.length % 4 if m != 0 for i in [0...4 - m] data += '=' data = data.replace(/-/g, '+') data = data.replace(/_/g, '/') base64Decode(data) parseToken = (token) -> [head, payload, sig] = token.split('.') JSON.parse(base64UrlDecode(payload)) # Public: Supports the Store plugin by providing Authentication headers. class Annotator.Plugin.Auth extends Annotator.Plugin # User options that can be provided. options: # An authentication token. Used to skip the request to the server for a # a token. token: null # The URL on the local server to request an authentication token. tokenUrl: '/auth/token' # If true will try and fetch a token when the plugin is initialised. autoFetch: true # Public: Create a new instance of the Auth plugin. # # element - The element to bind all events to. Usually the Annotator#element. # options - An Object literal containing user options. # # Examples # # plugin = new Annotator.Plugin.Auth(annotator.element, { # tokenUrl: '/my/custom/path' # }) # # Returns instance of Auth. constructor: (element, options) -> super # List of functions to be executed when we have a valid token. @waitingForToken = [] if @options.token this.setToken(@options.token) else this.requestToken() # Public: Makes a request to the local server for an authentication token. # # Examples # # auth.requestToken() # # Returns jqXHR object. requestToken: -> @requestInProgress = true $.ajax url: @options.tokenUrl dataType: 'text' xhrFields:      withCredentials: true # Send any auth cookies to the backend # on success, set the auth token .done (data, status, xhr) => this.setToken(data) # on failure, relay any message given by the server to the user with a notification .fail (xhr, status, err) => msg = Annotator._t("Couldn't get auth token:") console.error "#{msg} #{err}", xhr Annotator.showNotification("#{msg} #{xhr.responseText}", Annotator.Notification.ERROR) # always reset the requestInProgress indicator .always => @requestInProgress = false # Public: Sets the @token and checks it's validity. If the token is invalid # requests a new one from the server. # # token - A token string. # # Examples # # auth.setToken('eyJh...9jQ3I') # # Returns nothing. setToken: (token) -> @token = token # Parse the token without verifying its authenticity: @_unsafeToken = parseToken(token) if this.haveValidToken() if @options.autoFetch # Set timeout to fetch new token 2 seconds before current token expiry @refreshTimeout = setTimeout (() => this.requestToken()), (this.timeToExpiry() - 2) * 1000 # Set headers field on this.element this.updateHeaders() # Run callbacks waiting for token while @waitingForToken.length > 0 @waitingForToken.pop()(@_unsafeToken) else console.warn Annotator._t("Didn't get a valid token.") if @options.autoFetch console.warn Annotator._t("Getting a new token in 10s.") setTimeout (() => this.requestToken()), 10 * 1000 # Public: Checks the validity of the current token. Note that this *does # not* check the authenticity of the token. # # Examples # # auth.haveValidToken() # => Returns true if valid. # # Returns true if the token is valid. haveValidToken: () -> allFields = ( @_unsafeToken and @_unsafeToken.issuedAt and @_unsafeToken.ttl and @_unsafeToken.consumerKey ) if allFields && this.timeToExpiry() > 0 return true else return false # Public: Calculates the time in seconds until the current token expires. # # Returns Number of seconds until token expires. timeToExpiry: -> now = new Date().getTime() / 1000 issue = createDateFromISO8601(@_unsafeToken.issuedAt).getTime() / 1000 expiry = issue + @_unsafeToken.ttl timeToExpiry = expiry - now if (timeToExpiry > 0) then timeToExpiry else 0 # Public: Updates the headers to be sent with the Store requests. This is # achieved by updating the 'annotator:headers' key in the @element.data() # store. # # Returns nothing. updateHeaders: -> current = @element.data('annotator:headers') @element.data('annotator:headers', $.extend(current, { 'x-annotator-auth-token': @token, })) # Runs the provided callback if a valid token is available. Otherwise requests # a token until it recieves a valid one. # # callback - A callback function to call once a valid token is obtained. # # Examples # # auth.withToken -> # store.loadAnnotations() # # Returns nothing. withToken: (callback) -> if not callback? return if this.haveValidToken() callback(@_unsafeToken) else this.waitingForToken.push(callback) if not @requestInProgress this.requestToken()
150259
# Public: Creates a Date object from an ISO8601 formatted date String. # # string - ISO8601 formatted date String. # # Returns Date instance. createDateFromISO8601 = (string) -> regexp = ( "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?" ) d = string.match(new RegExp(regexp)) offset = 0 date = new Date(d[1], 0, 1) date.setMonth(d[3] - 1) if d[3] date.setDate(d[5]) if d[5] date.setHours(d[7]) if d[7] date.setMinutes(d[8]) if d[8] date.setSeconds(d[10]) if d[10] date.setMilliseconds(Number("0." + d[12]) * 1000) if d[12] if d[14] offset = (Number(d[16]) * 60) + Number(d[17]) offset *= ((d[15] == '-') ? 1 : -1) offset -= date.getTimezoneOffset() time = (Number(date) + (offset * 60 * 1000)) date.setTime(Number(time)) date base64Decode = (data) -> if atob? # Gecko and Webkit provide native code for this atob(data) else # Adapted from MIT/BSD licensed code at http://phpjs.org/functions/base64_decode # version 1109.2015 b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" i = 0 ac = 0 dec = "" tmp_arr = [] if not data return data data += '' while i < data.length # unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)) h2 = b64.indexOf(data.charAt(i++)) h3 = b64.indexOf(data.charAt(i++)) h4 = b64.indexOf(data.charAt(i++)) bits = h1 << 18 | h2 << 12 | h3 << 6 | h4 o1 = bits >> 16 & 0xff o2 = bits >> 8 & 0xff o3 = bits & 0xff if h3 == 64 tmp_arr[ac++] = String.fromCharCode(o1) else if h4 == 64 tmp_arr[ac++] = String.fromCharCode(o1, o2) else tmp_arr[ac++] = String.fromCharCode(o1, o2, o3) tmp_arr.join('') base64UrlDecode = (data) -> m = data.length % 4 if m != 0 for i in [0...4 - m] data += '=' data = data.replace(/-/g, '+') data = data.replace(/_/g, '/') base64Decode(data) parseToken = (token) -> [head, payload, sig] = token.split('.') JSON.parse(base64UrlDecode(payload)) # Public: Supports the Store plugin by providing Authentication headers. class Annotator.Plugin.Auth extends Annotator.Plugin # User options that can be provided. options: # An authentication token. Used to skip the request to the server for a # a token. token: null # The URL on the local server to request an authentication token. tokenUrl: '/auth/token' # If true will try and fetch a token when the plugin is initialised. autoFetch: true # Public: Create a new instance of the Auth plugin. # # element - The element to bind all events to. Usually the Annotator#element. # options - An Object literal containing user options. # # Examples # # plugin = new Annotator.Plugin.Auth(annotator.element, { # tokenUrl: '/my/custom/path' # }) # # Returns instance of Auth. constructor: (element, options) -> super # List of functions to be executed when we have a valid token. @waitingForToken = [] if @options.token this.setToken(@options.token) else this.requestToken() # Public: Makes a request to the local server for an authentication token. # # Examples # # auth.requestToken() # # Returns jqXHR object. requestToken: -> @requestInProgress = true $.ajax url: @options.tokenUrl dataType: 'text' xhrFields:      withCredentials: true # Send any auth cookies to the backend # on success, set the auth token .done (data, status, xhr) => this.setToken(data) # on failure, relay any message given by the server to the user with a notification .fail (xhr, status, err) => msg = Annotator._t("Couldn't get auth token:") console.error "#{msg} #{err}", xhr Annotator.showNotification("#{msg} #{xhr.responseText}", Annotator.Notification.ERROR) # always reset the requestInProgress indicator .always => @requestInProgress = false # Public: Sets the @token and checks it's validity. If the token is invalid # requests a new one from the server. # # token - A token string. # # Examples # # auth.setToken('<PASSWORD>') # # Returns nothing. setToken: (token) -> @token = token # Parse the token without verifying its authenticity: @_unsafeToken = parseToken(token) if this.haveValidToken() if @options.autoFetch # Set timeout to fetch new token 2 seconds before current token expiry @refreshTimeout = setTimeout (() => this.requestToken()), (this.timeToExpiry() - 2) * 1000 # Set headers field on this.element this.updateHeaders() # Run callbacks waiting for token while @waitingForToken.length > 0 @waitingForToken.pop()(@_unsafeToken) else console.warn Annotator._t("Didn't get a valid token.") if @options.autoFetch console.warn Annotator._t("Getting a new token in 10s.") setTimeout (() => this.requestToken()), 10 * 1000 # Public: Checks the validity of the current token. Note that this *does # not* check the authenticity of the token. # # Examples # # auth.haveValidToken() # => Returns true if valid. # # Returns true if the token is valid. haveValidToken: () -> allFields = ( @_unsafeToken and @_unsafeToken.issuedAt and @_unsafeToken.ttl and @_unsafeToken.consumerKey ) if allFields && this.timeToExpiry() > 0 return true else return false # Public: Calculates the time in seconds until the current token expires. # # Returns Number of seconds until token expires. timeToExpiry: -> now = new Date().getTime() / 1000 issue = createDateFromISO8601(@_unsafeToken.issuedAt).getTime() / 1000 expiry = issue + @_unsafeToken.ttl timeToExpiry = expiry - now if (timeToExpiry > 0) then timeToExpiry else 0 # Public: Updates the headers to be sent with the Store requests. This is # achieved by updating the 'annotator:headers' key in the @element.data() # store. # # Returns nothing. updateHeaders: -> current = @element.data('annotator:headers') @element.data('annotator:headers', $.extend(current, { 'x-annotator-auth-token': @token, })) # Runs the provided callback if a valid token is available. Otherwise requests # a token until it recieves a valid one. # # callback - A callback function to call once a valid token is obtained. # # Examples # # auth.withToken -> # store.loadAnnotations() # # Returns nothing. withToken: (callback) -> if not callback? return if this.haveValidToken() callback(@_unsafeToken) else this.waitingForToken.push(callback) if not @requestInProgress this.requestToken()
true
# Public: Creates a Date object from an ISO8601 formatted date String. # # string - ISO8601 formatted date String. # # Returns Date instance. createDateFromISO8601 = (string) -> regexp = ( "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?" ) d = string.match(new RegExp(regexp)) offset = 0 date = new Date(d[1], 0, 1) date.setMonth(d[3] - 1) if d[3] date.setDate(d[5]) if d[5] date.setHours(d[7]) if d[7] date.setMinutes(d[8]) if d[8] date.setSeconds(d[10]) if d[10] date.setMilliseconds(Number("0." + d[12]) * 1000) if d[12] if d[14] offset = (Number(d[16]) * 60) + Number(d[17]) offset *= ((d[15] == '-') ? 1 : -1) offset -= date.getTimezoneOffset() time = (Number(date) + (offset * 60 * 1000)) date.setTime(Number(time)) date base64Decode = (data) -> if atob? # Gecko and Webkit provide native code for this atob(data) else # Adapted from MIT/BSD licensed code at http://phpjs.org/functions/base64_decode # version 1109.2015 b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" i = 0 ac = 0 dec = "" tmp_arr = [] if not data return data data += '' while i < data.length # unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)) h2 = b64.indexOf(data.charAt(i++)) h3 = b64.indexOf(data.charAt(i++)) h4 = b64.indexOf(data.charAt(i++)) bits = h1 << 18 | h2 << 12 | h3 << 6 | h4 o1 = bits >> 16 & 0xff o2 = bits >> 8 & 0xff o3 = bits & 0xff if h3 == 64 tmp_arr[ac++] = String.fromCharCode(o1) else if h4 == 64 tmp_arr[ac++] = String.fromCharCode(o1, o2) else tmp_arr[ac++] = String.fromCharCode(o1, o2, o3) tmp_arr.join('') base64UrlDecode = (data) -> m = data.length % 4 if m != 0 for i in [0...4 - m] data += '=' data = data.replace(/-/g, '+') data = data.replace(/_/g, '/') base64Decode(data) parseToken = (token) -> [head, payload, sig] = token.split('.') JSON.parse(base64UrlDecode(payload)) # Public: Supports the Store plugin by providing Authentication headers. class Annotator.Plugin.Auth extends Annotator.Plugin # User options that can be provided. options: # An authentication token. Used to skip the request to the server for a # a token. token: null # The URL on the local server to request an authentication token. tokenUrl: '/auth/token' # If true will try and fetch a token when the plugin is initialised. autoFetch: true # Public: Create a new instance of the Auth plugin. # # element - The element to bind all events to. Usually the Annotator#element. # options - An Object literal containing user options. # # Examples # # plugin = new Annotator.Plugin.Auth(annotator.element, { # tokenUrl: '/my/custom/path' # }) # # Returns instance of Auth. constructor: (element, options) -> super # List of functions to be executed when we have a valid token. @waitingForToken = [] if @options.token this.setToken(@options.token) else this.requestToken() # Public: Makes a request to the local server for an authentication token. # # Examples # # auth.requestToken() # # Returns jqXHR object. requestToken: -> @requestInProgress = true $.ajax url: @options.tokenUrl dataType: 'text' xhrFields:      withCredentials: true # Send any auth cookies to the backend # on success, set the auth token .done (data, status, xhr) => this.setToken(data) # on failure, relay any message given by the server to the user with a notification .fail (xhr, status, err) => msg = Annotator._t("Couldn't get auth token:") console.error "#{msg} #{err}", xhr Annotator.showNotification("#{msg} #{xhr.responseText}", Annotator.Notification.ERROR) # always reset the requestInProgress indicator .always => @requestInProgress = false # Public: Sets the @token and checks it's validity. If the token is invalid # requests a new one from the server. # # token - A token string. # # Examples # # auth.setToken('PI:PASSWORD:<PASSWORD>END_PI') # # Returns nothing. setToken: (token) -> @token = token # Parse the token without verifying its authenticity: @_unsafeToken = parseToken(token) if this.haveValidToken() if @options.autoFetch # Set timeout to fetch new token 2 seconds before current token expiry @refreshTimeout = setTimeout (() => this.requestToken()), (this.timeToExpiry() - 2) * 1000 # Set headers field on this.element this.updateHeaders() # Run callbacks waiting for token while @waitingForToken.length > 0 @waitingForToken.pop()(@_unsafeToken) else console.warn Annotator._t("Didn't get a valid token.") if @options.autoFetch console.warn Annotator._t("Getting a new token in 10s.") setTimeout (() => this.requestToken()), 10 * 1000 # Public: Checks the validity of the current token. Note that this *does # not* check the authenticity of the token. # # Examples # # auth.haveValidToken() # => Returns true if valid. # # Returns true if the token is valid. haveValidToken: () -> allFields = ( @_unsafeToken and @_unsafeToken.issuedAt and @_unsafeToken.ttl and @_unsafeToken.consumerKey ) if allFields && this.timeToExpiry() > 0 return true else return false # Public: Calculates the time in seconds until the current token expires. # # Returns Number of seconds until token expires. timeToExpiry: -> now = new Date().getTime() / 1000 issue = createDateFromISO8601(@_unsafeToken.issuedAt).getTime() / 1000 expiry = issue + @_unsafeToken.ttl timeToExpiry = expiry - now if (timeToExpiry > 0) then timeToExpiry else 0 # Public: Updates the headers to be sent with the Store requests. This is # achieved by updating the 'annotator:headers' key in the @element.data() # store. # # Returns nothing. updateHeaders: -> current = @element.data('annotator:headers') @element.data('annotator:headers', $.extend(current, { 'x-annotator-auth-token': @token, })) # Runs the provided callback if a valid token is available. Otherwise requests # a token until it recieves a valid one. # # callback - A callback function to call once a valid token is obtained. # # Examples # # auth.withToken -> # store.loadAnnotations() # # Returns nothing. withToken: (callback) -> if not callback? return if this.haveValidToken() callback(@_unsafeToken) else this.waitingForToken.push(callback) if not @requestInProgress this.requestToken()
[ { "context": "eplace'\n 'body': \"\"\"\n \tstr_replace(\"world\",\"Peter\",${1:\"Hello_world\"})\n \"\"\"\n 'G3ck/PHP - if fil", "end": 278, "score": 0.9995339512825012, "start": 273, "tag": "NAME", "value": "Peter" } ]
snippets/php.cson
g3ck/atom-g3ck-snippets
1
'.source.php': 'G3ck/PHP - print array in pre': 'prefix': 'printPre' 'body': """ echo '<pre>'; print_r(${1:$_GET}); echo '</pre>'; """ 'G3ck/PHP - string replace': 'prefix': 'stringReplace' 'body': """ str_replace("world","Peter",${1:"Hello_world"}) """ 'G3ck/PHP - if file exists': 'prefix': 'fileExists' 'body': """ if (file_exists(${1:$filename}) AND is_file(${1:$filename})): ${2} endif; """ 'G3ck/PHP - if string contains': 'prefix': 'stringContains' 'body': """ if (strpos($a, 'are') !== false): ${1} endif; """ 'G3ck/PHP - get files in folder': 'prefix': 'filesInFolder' 'body': """ $dirs = array_filter(glob('*'), 'is_file'); foreach ($dirs as $key => $value): echo $key . ' = ' . $value; endforeach; """ 'G3ck/PHP - foreach text lines': 'prefix': 'foreachTextLines' 'body': """ foreach(preg_split("/((\r?\n)|(\r\n?))/", ${$subject}) as $line){ // do stuff with $line } """ 'G3ck/PHP - foreach': 'prefix': 'foreach' 'body': """ foreach ($array as $key => $value): ${1} endforeach; """ '.source.php, .text.html.php, .text.html.basic': 'G3ck/PHP - foreach separated': 'prefix': 'foreachSeparated' 'body': """ <?php foreach ($array as $key => $value): ?> ${1} <?php endforeach; ?> """
4116
'.source.php': 'G3ck/PHP - print array in pre': 'prefix': 'printPre' 'body': """ echo '<pre>'; print_r(${1:$_GET}); echo '</pre>'; """ 'G3ck/PHP - string replace': 'prefix': 'stringReplace' 'body': """ str_replace("world","<NAME>",${1:"Hello_world"}) """ 'G3ck/PHP - if file exists': 'prefix': 'fileExists' 'body': """ if (file_exists(${1:$filename}) AND is_file(${1:$filename})): ${2} endif; """ 'G3ck/PHP - if string contains': 'prefix': 'stringContains' 'body': """ if (strpos($a, 'are') !== false): ${1} endif; """ 'G3ck/PHP - get files in folder': 'prefix': 'filesInFolder' 'body': """ $dirs = array_filter(glob('*'), 'is_file'); foreach ($dirs as $key => $value): echo $key . ' = ' . $value; endforeach; """ 'G3ck/PHP - foreach text lines': 'prefix': 'foreachTextLines' 'body': """ foreach(preg_split("/((\r?\n)|(\r\n?))/", ${$subject}) as $line){ // do stuff with $line } """ 'G3ck/PHP - foreach': 'prefix': 'foreach' 'body': """ foreach ($array as $key => $value): ${1} endforeach; """ '.source.php, .text.html.php, .text.html.basic': 'G3ck/PHP - foreach separated': 'prefix': 'foreachSeparated' 'body': """ <?php foreach ($array as $key => $value): ?> ${1} <?php endforeach; ?> """
true
'.source.php': 'G3ck/PHP - print array in pre': 'prefix': 'printPre' 'body': """ echo '<pre>'; print_r(${1:$_GET}); echo '</pre>'; """ 'G3ck/PHP - string replace': 'prefix': 'stringReplace' 'body': """ str_replace("world","PI:NAME:<NAME>END_PI",${1:"Hello_world"}) """ 'G3ck/PHP - if file exists': 'prefix': 'fileExists' 'body': """ if (file_exists(${1:$filename}) AND is_file(${1:$filename})): ${2} endif; """ 'G3ck/PHP - if string contains': 'prefix': 'stringContains' 'body': """ if (strpos($a, 'are') !== false): ${1} endif; """ 'G3ck/PHP - get files in folder': 'prefix': 'filesInFolder' 'body': """ $dirs = array_filter(glob('*'), 'is_file'); foreach ($dirs as $key => $value): echo $key . ' = ' . $value; endforeach; """ 'G3ck/PHP - foreach text lines': 'prefix': 'foreachTextLines' 'body': """ foreach(preg_split("/((\r?\n)|(\r\n?))/", ${$subject}) as $line){ // do stuff with $line } """ 'G3ck/PHP - foreach': 'prefix': 'foreach' 'body': """ foreach ($array as $key => $value): ${1} endforeach; """ '.source.php, .text.html.php, .text.html.basic': 'G3ck/PHP - foreach separated': 'prefix': 'foreachSeparated' 'body': """ <?php foreach ($array as $key => $value): ?> ${1} <?php endforeach; ?> """
[ { "context": "sibilities\n- unit test downlinkMax.coffee\n\n@author Daniel Lamb <dlamb.open.source@gmail.com>\n###\n\ndescribe 'down", "end": 82, "score": 0.9997289776802063, "start": 71, "tag": "NAME", "value": "Daniel Lamb" }, { "context": "nit test downlinkMax.coffee\n\n@author Da...
test/spec/downlinkmax.spec.coffee
johngeorgewright/downlinkMax
68
### @file ## Responsibilities - unit test downlinkMax.coffee @author Daniel Lamb <dlamb.open.source@gmail.com> ### describe 'downlinkmax.coffee', -> org = window.navigator arrange = (obj) -> # arrange global environment window.navigator = obj afterEach -> # reset global environment window.navigator = org it 'should have a working test harness', -> # arrange # act # assert expect(yes).not.toBe no it 'should exist', -> # arrange # act # assert expect(typeof downlinkmax).toBe 'function' describe 'navigator.connection supported', -> beforeEach -> arrange connection: downlinkMax: 'foo' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'foo' describe 'navigator.mozConnection supported', -> beforeEach -> arrange mozConnection: downlinkMax: 'bar' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'bar' describe 'navigator.webkitConnection supported', -> beforeEach -> arrange webkitConnection: downlinkMax: 'baz' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'baz' describe 'API not supported', -> beforeEach -> arrange {} it 'should return Infinity', -> # arrange # act result = downlinkmax() # assert expect(result).toBe Infinity describe 'connection.bandwidth supported', -> beforeEach -> arrange connection: bandwidth: 1 # in MB/s it "should convert MB/s to Mbit/s", -> # arrange # act result = downlinkmax() # assert expect(result).toBe 8 describe 'connection.type supported', -> it 'should map the type none', -> # arrange arrange connection: type: 'none' # act result = downlinkmax() # assert expect(result).toBe 0 it 'should map the type 2g', -> # arrange arrange connection: type: '2g' # act result = downlinkmax() # assert expect(result).toBe 0.134 it 'should map the type bluetooth', -> # arrange arrange connection: type: 'bluetooth' # act result = downlinkmax() # assert expect(result).toBe 2 it 'should map the type cellular', -> # arrange arrange connection: type: 'cellular' # act result = downlinkmax() # assert expect(result).toBe 2 it 'should map the type 3g', -> # arrange arrange connection: type: '3g' # act result = downlinkmax() # assert expect(result).toBe 8.95 it 'should map the type 4g', -> # arrange arrange connection: type: '4g' # act result = downlinkmax() # assert expect(result).toBe 100 it 'should map the type ethernet', -> # arrange arrange connection: type: 'ethernet' # act result = downlinkmax() # assert expect(result).toBe 550 it 'should map the type wifi', -> # arrange arrange connection: type: 'wifi' # act result = downlinkmax() # assert expect(result).toBe 600 it 'should map the type other', -> # arrange arrange connection: type: 'other' # act result = downlinkmax() # assert expect(result).toBe Infinity it 'should map the type unknown', -> # arrange arrange connection: type: 'unknown' # act result = downlinkmax() # assert expect(result).toBe Infinity it 'should map any type', -> # arrange arrange connection: type: 'foobarbaz' # act result = downlinkmax() # assert expect(result).toBe Infinity
139547
### @file ## Responsibilities - unit test downlinkMax.coffee @author <NAME> <<EMAIL>> ### describe 'downlinkmax.coffee', -> org = window.navigator arrange = (obj) -> # arrange global environment window.navigator = obj afterEach -> # reset global environment window.navigator = org it 'should have a working test harness', -> # arrange # act # assert expect(yes).not.toBe no it 'should exist', -> # arrange # act # assert expect(typeof downlinkmax).toBe 'function' describe 'navigator.connection supported', -> beforeEach -> arrange connection: downlinkMax: 'foo' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'foo' describe 'navigator.mozConnection supported', -> beforeEach -> arrange mozConnection: downlinkMax: 'bar' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'bar' describe 'navigator.webkitConnection supported', -> beforeEach -> arrange webkitConnection: downlinkMax: 'baz' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'baz' describe 'API not supported', -> beforeEach -> arrange {} it 'should return Infinity', -> # arrange # act result = downlinkmax() # assert expect(result).toBe Infinity describe 'connection.bandwidth supported', -> beforeEach -> arrange connection: bandwidth: 1 # in MB/s it "should convert MB/s to Mbit/s", -> # arrange # act result = downlinkmax() # assert expect(result).toBe 8 describe 'connection.type supported', -> it 'should map the type none', -> # arrange arrange connection: type: 'none' # act result = downlinkmax() # assert expect(result).toBe 0 it 'should map the type 2g', -> # arrange arrange connection: type: '2g' # act result = downlinkmax() # assert expect(result).toBe 0.134 it 'should map the type bluetooth', -> # arrange arrange connection: type: 'bluetooth' # act result = downlinkmax() # assert expect(result).toBe 2 it 'should map the type cellular', -> # arrange arrange connection: type: 'cellular' # act result = downlinkmax() # assert expect(result).toBe 2 it 'should map the type 3g', -> # arrange arrange connection: type: '3g' # act result = downlinkmax() # assert expect(result).toBe 8.95 it 'should map the type 4g', -> # arrange arrange connection: type: '4g' # act result = downlinkmax() # assert expect(result).toBe 100 it 'should map the type ethernet', -> # arrange arrange connection: type: 'ethernet' # act result = downlinkmax() # assert expect(result).toBe 550 it 'should map the type wifi', -> # arrange arrange connection: type: 'wifi' # act result = downlinkmax() # assert expect(result).toBe 600 it 'should map the type other', -> # arrange arrange connection: type: 'other' # act result = downlinkmax() # assert expect(result).toBe Infinity it 'should map the type unknown', -> # arrange arrange connection: type: 'unknown' # act result = downlinkmax() # assert expect(result).toBe Infinity it 'should map any type', -> # arrange arrange connection: type: 'foobarbaz' # act result = downlinkmax() # assert expect(result).toBe Infinity
true
### @file ## Responsibilities - unit test downlinkMax.coffee @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### describe 'downlinkmax.coffee', -> org = window.navigator arrange = (obj) -> # arrange global environment window.navigator = obj afterEach -> # reset global environment window.navigator = org it 'should have a working test harness', -> # arrange # act # assert expect(yes).not.toBe no it 'should exist', -> # arrange # act # assert expect(typeof downlinkmax).toBe 'function' describe 'navigator.connection supported', -> beforeEach -> arrange connection: downlinkMax: 'foo' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'foo' describe 'navigator.mozConnection supported', -> beforeEach -> arrange mozConnection: downlinkMax: 'bar' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'bar' describe 'navigator.webkitConnection supported', -> beforeEach -> arrange webkitConnection: downlinkMax: 'baz' it 'should return the API value', -> # arrange # act result = downlinkmax() # assert expect(result).toBe 'baz' describe 'API not supported', -> beforeEach -> arrange {} it 'should return Infinity', -> # arrange # act result = downlinkmax() # assert expect(result).toBe Infinity describe 'connection.bandwidth supported', -> beforeEach -> arrange connection: bandwidth: 1 # in MB/s it "should convert MB/s to Mbit/s", -> # arrange # act result = downlinkmax() # assert expect(result).toBe 8 describe 'connection.type supported', -> it 'should map the type none', -> # arrange arrange connection: type: 'none' # act result = downlinkmax() # assert expect(result).toBe 0 it 'should map the type 2g', -> # arrange arrange connection: type: '2g' # act result = downlinkmax() # assert expect(result).toBe 0.134 it 'should map the type bluetooth', -> # arrange arrange connection: type: 'bluetooth' # act result = downlinkmax() # assert expect(result).toBe 2 it 'should map the type cellular', -> # arrange arrange connection: type: 'cellular' # act result = downlinkmax() # assert expect(result).toBe 2 it 'should map the type 3g', -> # arrange arrange connection: type: '3g' # act result = downlinkmax() # assert expect(result).toBe 8.95 it 'should map the type 4g', -> # arrange arrange connection: type: '4g' # act result = downlinkmax() # assert expect(result).toBe 100 it 'should map the type ethernet', -> # arrange arrange connection: type: 'ethernet' # act result = downlinkmax() # assert expect(result).toBe 550 it 'should map the type wifi', -> # arrange arrange connection: type: 'wifi' # act result = downlinkmax() # assert expect(result).toBe 600 it 'should map the type other', -> # arrange arrange connection: type: 'other' # act result = downlinkmax() # assert expect(result).toBe Infinity it 'should map the type unknown', -> # arrange arrange connection: type: 'unknown' # act result = downlinkmax() # assert expect(result).toBe Infinity it 'should map any type', -> # arrange arrange connection: type: 'foobarbaz' # act result = downlinkmax() # assert expect(result).toBe Infinity
[ { "context": "ram: 0x00000040\n NTLM_NegotiateLanManagerKey: 0x00000080\n NTLM_Unknown8: 0x00000100\n NTLM_NegotiateNTLM", "end": 1740, "score": 0.5788441896438599, "start": 1734, "tag": "KEY", "value": "000008" }, { "context": "ssword || ''\n password = new Buffer(password, 'u...
src/login7-payload.coffee
sgermain06/tedious-int64-native
0
WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer') require('./buffertools') os= require('os') sprintf = require('sprintf').sprintf libraryName = require('./library').name versions = require('./tds-versions').versions FLAGS_1 = ENDIAN_LITTLE: 0x00, ENDIAN_BIG: 0x01, CHARSET_ASCII: 0x00, CHARSET_EBCDIC: 0x02, FLOAT_IEEE_754: 0x00, FLOAT_VAX: 0x04, FLOAT_ND5000: 0x08, BCP_DUMPLOAD_ON: 0x00, BCP_DUMPLOAD_OFF: 0x10, USE_DB_ON: 0x00, USE_DB_OFF: 0x20, INIT_DB_WARN: 0x00, INIT_DB_FATAL: 0x40, SET_LANG_WARN_OFF: 0x00, SET_LANG_WARN_ON: 0x80, FLAGS_2 = INIT_LANG_WARN: 0x00, INIT_LANG_FATAL: 0x01, ODBC_OFF: 0x00, ODBC_ON: 0x02, F_TRAN_BOUNDARY: 0x04, # Removed in TDS 7.2 F_CACHE_CONNECT: 0x08, # Removed in TDS 7.2 USER_NORMAL: 0x00, USER_SERVER: 0x10, USER_REMUSER: 0x20, USER_SQLREPL: 0x40, INTEGRATED_SECURITY_OFF: 0x00, INTEGRATED_SECURITY_ON: 0x80 TYPE_FLAGS = SQL_DFLT: 0x00, SQL_TSQL: 0x08, OLEDB_OFF: 0x00, OLEDB_ON: 0x10, # Introduced in TDS 7.2 READ_WRITE_INTENT: 0x00, READ_ONLY_INTENT: 0x20 # Introduced in TDS 7.4 FLAGS_3 = CHANGE_PASSWORD_NO: 0x00, CHANGE_PASSWORD_YES: 0x01, # Introduced in TDS 7.2 BINARY_XML: 0x02, # Introduced in TDS 7.2 SPAWN_USER_INSTANCE: 0x04, # Introduced in TDS 7.2 UNKNOWN_COLLATION_HANDLING: 0x08 # Introduced in TDS 7.3 NTLMFlags = NTLM_NegotiateUnicode: 0x00000001 NTLM_NegotiateOEM: 0x00000002 NTLM_RequestTarget: 0x00000004 NTLM_Unknown9: 0x00000008 NTLM_NegotiateSign: 0x00000010 NTLM_NegotiateSeal: 0x00000020 NTLM_NegotiateDatagram: 0x00000040 NTLM_NegotiateLanManagerKey: 0x00000080 NTLM_Unknown8: 0x00000100 NTLM_NegotiateNTLM: 0x00000200 NTLM_NegotiateNTOnly: 0x00000400 NTLM_Anonymous: 0x00000800 NTLM_NegotiateOemDomainSupplied: 0x00001000 NTLM_NegotiateOemWorkstationSupplied: 0x00002000 NTLM_Unknown6: 0x00004000 NTLM_NegotiateAlwaysSign: 0x00008000 NTLM_TargetTypeDomain: 0x00010000 NTLM_TargetTypeServer: 0x00020000 NTLM_TargetTypeShare: 0x00040000 NTLM_NegotiateExtendedSecurity: 0x00080000 # Negotiate NTLM2 Key NTLM_NegotiateIdentify: 0x00100000 # Request Init Response NTLM_Unknown5: 0x00200000 # Request Accept Response NTLM_RequestNonNTSessionKey: 0x00400000 NTLM_NegotiateTargetInfo: 0x00800000 NTLM_Unknown4: 0x01000000 NTLM_NegotiateVersion: 0x02000000 NTLM_Unknown3: 0x04000000 NTLM_Unknown2: 0x08000000 NTLM_Unknown1: 0x10000000 NTLM_Negotiate128: 0x20000000 NTLM_NegotiateKeyExchange: 0x40000000 NTLM_Negotiate56: 0x80000000 ### s2.2.6.3 ### class Login7Payload constructor: (@loginData) -> lengthLength = 4 fixed = @createFixedData() variable = @createVariableData(lengthLength + fixed.length) length = lengthLength + fixed.length + variable.length data = new WritableTrackingBuffer(300) data.writeUInt32LE(length) data.writeBuffer(fixed) data.writeBuffer(variable) @data = data.data createFixedData: -> @tdsVersion = versions[@loginData.tdsVersion] @packetSize = @loginData.packetSize @clientProgVer = 0 @clientPid = process.pid @connectionId = 0 @clientTimeZone = new Date().getTimezoneOffset() @clientLcid = 0x00000409 #Can't figure what form this should take. @flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCD_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.SET_LANG_WARN_ON if @loginData.initDbFatal @flags1 |= FLAGS_1.INIT_DB_FATAL else @flags1 |= FLAGS_1.INIT_DB_WARN @flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL if @loginData.domain @flags2 |= FLAGS_2.INTEGRATED_SECURITY_ON else @flags2 |= FLAGS_2.INTEGRATED_SECURITY_OFF @flags3 = FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING @typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF if @loginData.readOnlyIntent @typeFlags |= TYPE_FLAGS.READ_ONLY_INTENT else @typeFlags |= TYPE_FLAGS.READ_WRITE_INTENT buffer = new WritableTrackingBuffer(100) buffer.writeUInt32LE(@tdsVersion) buffer.writeUInt32LE(@packetSize) buffer.writeUInt32LE(@clientProgVer) buffer.writeUInt32LE(@clientPid) buffer.writeUInt32LE(@connectionId) buffer.writeUInt8(@flags1) buffer.writeUInt8(@flags2) buffer.writeUInt8(@typeFlags) buffer.writeUInt8(@flags3) buffer.writeInt32LE(@clientTimeZone) buffer.writeUInt32LE(@clientLcid) buffer.data createVariableData: (offset) -> @variableLengthsLength = ((9 * 4) + 6 + (3 * 4) + 4) if @loginData.tdsVersion == '7_1' @variableLengthsLength = ((9 * 4) + 6 + (2 * 4)) variableData = offsetsAndLengths: new WritableTrackingBuffer(200) data: new WritableTrackingBuffer(200, 'ucs2') offset: offset + @variableLengthsLength @hostname = os.hostname() @loginData = @loginData || {} @loginData.appName = @loginData.appName || 'Tedious' @libraryName = libraryName # Client ID, should be MAC address or other randomly generated GUID like value. @clientId = new Buffer([1, 2, 3, 4, 5, 6]) unless @loginData.domain @sspi = '' @sspiLong = 0 @attachDbFile = '' @changePassword = '' @addVariableDataString(variableData, @hostname) @addVariableDataString(variableData, @loginData.userName) @addVariableDataBuffer(variableData, @createPasswordBuffer()) @addVariableDataString(variableData, @loginData.appName) @addVariableDataString(variableData, @loginData.serverName) @addVariableDataString(variableData, '') # Reserved for future use. @addVariableDataString(variableData, @libraryName) @addVariableDataString(variableData, @loginData.language) @addVariableDataString(variableData, @loginData.database) variableData.offsetsAndLengths.writeBuffer(@clientId) if @loginData.domain @ntlmPacket = @createNTLMRequest(@loginData) @sspiLong = @ntlmPacket.length variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(@ntlmPacket.length) variableData.data.writeBuffer(@ntlmPacket) variableData.offset += @ntlmPacket.length else @addVariableDataString(variableData, @sspi) @addVariableDataString(variableData, @attachDbFile) if @loginData.tdsVersion > '7_1' @addVariableDataString(variableData, @changePassword) # Introduced in TDS 7.2 variableData.offsetsAndLengths.writeUInt32LE(@sspiLong) # Introduced in TDS 7.2 variableData.offsetsAndLengths.data = Buffer.concat([variableData.offsetsAndLengths.data, variableData.data.data]) addVariableDataBuffer: (variableData, buffer) -> variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(buffer.length / 2) variableData.data.writeBuffer(buffer) variableData.offset += buffer.length addVariableDataString: (variableData, value) -> value ||= '' variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(value.length) variableData.data.writeString(value); variableData.offset += value.length * 2 createNTLMRequest: (options) -> domain = escape(options.domain.toUpperCase()) workstation = if options.workstation then escape( options.workstation.toUpperCase() ) else '' protocol = 'NTLMSSP\u0000' BODY_LENGTH = 40 type1flags = @getNTLMFlags() type1flags -= NTLMFlags.NTLM_NegotiateOemWorkstationSupplied if workstation is '' bufferLength = BODY_LENGTH + domain.length buffer = new WritableTrackingBuffer(bufferLength) buffer.writeString(protocol, 'utf8') # protocol buffer.writeUInt32LE(1) # type 1 buffer.writeUInt32LE(type1flags) # TYPE1 flag buffer.writeUInt16LE(domain.length) # domain length buffer.writeUInt16LE(domain.length) # domain max length buffer.writeUInt32LE(BODY_LENGTH + workstation.length) # domain buffer offset buffer.writeUInt16LE(workstation.length) # workstation length buffer.writeUInt16LE(workstation.length) # workstation max length buffer.writeUInt32LE(BODY_LENGTH) # domain buffer offset buffer.writeUInt8(5) #ProductMajorVersion buffer.writeUInt8(0) #ProductMinorVersion buffer.writeUInt16LE(2195) #ProductBuild buffer.writeUInt8(0) #VersionReserved1 buffer.writeUInt8(0) #VersionReserved2 buffer.writeUInt8(0) #VersionReserved3 buffer.writeUInt8(15) #NTLMRevisionCurrent buffer.writeString(workstation, 'ascii') buffer.writeString(domain, 'ascii') buffer.data createPasswordBuffer: -> password = @loginData.password || '' password = new Buffer(password, 'ucs2') for b in [0..password.length - 1] byte = password[b] lowNibble = byte & 0x0f highNibble = (byte >> 4) byte = (lowNibble << 4) | highNibble byte = byte ^ 0xa5 password[b] = byte password getNTLMFlags: -> (NTLMFlags.NTLM_NegotiateUnicode + NTLMFlags.NTLM_NegotiateOEM + NTLMFlags.NTLM_RequestTarget + NTLMFlags.NTLM_NegotiateNTLM + NTLMFlags.NTLM_NegotiateOemDomainSupplied + NTLMFlags.NTLM_NegotiateOemWorkstationSupplied + NTLMFlags.NTLM_NegotiateAlwaysSign + NTLMFlags.NTLM_NegotiateVersion + NTLMFlags.NTLM_NegotiateExtendedSecurity + NTLMFlags.NTLM_Negotiate128 + NTLMFlags.NTLM_Negotiate56) toString: (indent) -> indent ||= '' indent + 'Login7 - ' + sprintf('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', @tdsVersion, @packetSize, @clientProgVer, @clientPid, @connectionId ) + '\n' + indent + ' ' + sprintf('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', @flags1, @flags2, @typeFlags, @flags3, @clientTimeZone, @clientLcid ) + '\n' + indent + ' ' + sprintf("Hostname:'%s', Username:'%s', Password:'%s', AppName:'%s', ServerName:'%s', LibraryName:'%s'", @hostname, @loginData.userName, @loginData.password, @loginData.appName, @loginData.serverName, libraryName ) + '\n' + indent + ' ' + sprintf("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'%s'", @loginData.language, @loginData.database, @sspi, @attachDbFile @changePassword ) module.exports = Login7Payload
15251
WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer') require('./buffertools') os= require('os') sprintf = require('sprintf').sprintf libraryName = require('./library').name versions = require('./tds-versions').versions FLAGS_1 = ENDIAN_LITTLE: 0x00, ENDIAN_BIG: 0x01, CHARSET_ASCII: 0x00, CHARSET_EBCDIC: 0x02, FLOAT_IEEE_754: 0x00, FLOAT_VAX: 0x04, FLOAT_ND5000: 0x08, BCP_DUMPLOAD_ON: 0x00, BCP_DUMPLOAD_OFF: 0x10, USE_DB_ON: 0x00, USE_DB_OFF: 0x20, INIT_DB_WARN: 0x00, INIT_DB_FATAL: 0x40, SET_LANG_WARN_OFF: 0x00, SET_LANG_WARN_ON: 0x80, FLAGS_2 = INIT_LANG_WARN: 0x00, INIT_LANG_FATAL: 0x01, ODBC_OFF: 0x00, ODBC_ON: 0x02, F_TRAN_BOUNDARY: 0x04, # Removed in TDS 7.2 F_CACHE_CONNECT: 0x08, # Removed in TDS 7.2 USER_NORMAL: 0x00, USER_SERVER: 0x10, USER_REMUSER: 0x20, USER_SQLREPL: 0x40, INTEGRATED_SECURITY_OFF: 0x00, INTEGRATED_SECURITY_ON: 0x80 TYPE_FLAGS = SQL_DFLT: 0x00, SQL_TSQL: 0x08, OLEDB_OFF: 0x00, OLEDB_ON: 0x10, # Introduced in TDS 7.2 READ_WRITE_INTENT: 0x00, READ_ONLY_INTENT: 0x20 # Introduced in TDS 7.4 FLAGS_3 = CHANGE_PASSWORD_NO: 0x00, CHANGE_PASSWORD_YES: 0x01, # Introduced in TDS 7.2 BINARY_XML: 0x02, # Introduced in TDS 7.2 SPAWN_USER_INSTANCE: 0x04, # Introduced in TDS 7.2 UNKNOWN_COLLATION_HANDLING: 0x08 # Introduced in TDS 7.3 NTLMFlags = NTLM_NegotiateUnicode: 0x00000001 NTLM_NegotiateOEM: 0x00000002 NTLM_RequestTarget: 0x00000004 NTLM_Unknown9: 0x00000008 NTLM_NegotiateSign: 0x00000010 NTLM_NegotiateSeal: 0x00000020 NTLM_NegotiateDatagram: 0x00000040 NTLM_NegotiateLanManagerKey: 0x0<KEY>0 NTLM_Unknown8: 0x00000100 NTLM_NegotiateNTLM: 0x00000200 NTLM_NegotiateNTOnly: 0x00000400 NTLM_Anonymous: 0x00000800 NTLM_NegotiateOemDomainSupplied: 0x00001000 NTLM_NegotiateOemWorkstationSupplied: 0x00002000 NTLM_Unknown6: 0x00004000 NTLM_NegotiateAlwaysSign: 0x00008000 NTLM_TargetTypeDomain: 0x00010000 NTLM_TargetTypeServer: 0x00020000 NTLM_TargetTypeShare: 0x00040000 NTLM_NegotiateExtendedSecurity: 0x00080000 # Negotiate NTLM2 Key NTLM_NegotiateIdentify: 0x00100000 # Request Init Response NTLM_Unknown5: 0x00200000 # Request Accept Response NTLM_RequestNonNTSessionKey: 0x00400000 NTLM_NegotiateTargetInfo: 0x00800000 NTLM_Unknown4: 0x01000000 NTLM_NegotiateVersion: 0x02000000 NTLM_Unknown3: 0x04000000 NTLM_Unknown2: 0x08000000 NTLM_Unknown1: 0x10000000 NTLM_Negotiate128: 0x20000000 NTLM_NegotiateKeyExchange: 0x40000000 NTLM_Negotiate56: 0x80000000 ### s2.2.6.3 ### class Login7Payload constructor: (@loginData) -> lengthLength = 4 fixed = @createFixedData() variable = @createVariableData(lengthLength + fixed.length) length = lengthLength + fixed.length + variable.length data = new WritableTrackingBuffer(300) data.writeUInt32LE(length) data.writeBuffer(fixed) data.writeBuffer(variable) @data = data.data createFixedData: -> @tdsVersion = versions[@loginData.tdsVersion] @packetSize = @loginData.packetSize @clientProgVer = 0 @clientPid = process.pid @connectionId = 0 @clientTimeZone = new Date().getTimezoneOffset() @clientLcid = 0x00000409 #Can't figure what form this should take. @flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCD_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.SET_LANG_WARN_ON if @loginData.initDbFatal @flags1 |= FLAGS_1.INIT_DB_FATAL else @flags1 |= FLAGS_1.INIT_DB_WARN @flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL if @loginData.domain @flags2 |= FLAGS_2.INTEGRATED_SECURITY_ON else @flags2 |= FLAGS_2.INTEGRATED_SECURITY_OFF @flags3 = FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING @typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF if @loginData.readOnlyIntent @typeFlags |= TYPE_FLAGS.READ_ONLY_INTENT else @typeFlags |= TYPE_FLAGS.READ_WRITE_INTENT buffer = new WritableTrackingBuffer(100) buffer.writeUInt32LE(@tdsVersion) buffer.writeUInt32LE(@packetSize) buffer.writeUInt32LE(@clientProgVer) buffer.writeUInt32LE(@clientPid) buffer.writeUInt32LE(@connectionId) buffer.writeUInt8(@flags1) buffer.writeUInt8(@flags2) buffer.writeUInt8(@typeFlags) buffer.writeUInt8(@flags3) buffer.writeInt32LE(@clientTimeZone) buffer.writeUInt32LE(@clientLcid) buffer.data createVariableData: (offset) -> @variableLengthsLength = ((9 * 4) + 6 + (3 * 4) + 4) if @loginData.tdsVersion == '7_1' @variableLengthsLength = ((9 * 4) + 6 + (2 * 4)) variableData = offsetsAndLengths: new WritableTrackingBuffer(200) data: new WritableTrackingBuffer(200, 'ucs2') offset: offset + @variableLengthsLength @hostname = os.hostname() @loginData = @loginData || {} @loginData.appName = @loginData.appName || 'Tedious' @libraryName = libraryName # Client ID, should be MAC address or other randomly generated GUID like value. @clientId = new Buffer([1, 2, 3, 4, 5, 6]) unless @loginData.domain @sspi = '' @sspiLong = 0 @attachDbFile = '' @changePassword = '' @addVariableDataString(variableData, @hostname) @addVariableDataString(variableData, @loginData.userName) @addVariableDataBuffer(variableData, @createPasswordBuffer()) @addVariableDataString(variableData, @loginData.appName) @addVariableDataString(variableData, @loginData.serverName) @addVariableDataString(variableData, '') # Reserved for future use. @addVariableDataString(variableData, @libraryName) @addVariableDataString(variableData, @loginData.language) @addVariableDataString(variableData, @loginData.database) variableData.offsetsAndLengths.writeBuffer(@clientId) if @loginData.domain @ntlmPacket = @createNTLMRequest(@loginData) @sspiLong = @ntlmPacket.length variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(@ntlmPacket.length) variableData.data.writeBuffer(@ntlmPacket) variableData.offset += @ntlmPacket.length else @addVariableDataString(variableData, @sspi) @addVariableDataString(variableData, @attachDbFile) if @loginData.tdsVersion > '7_1' @addVariableDataString(variableData, @changePassword) # Introduced in TDS 7.2 variableData.offsetsAndLengths.writeUInt32LE(@sspiLong) # Introduced in TDS 7.2 variableData.offsetsAndLengths.data = Buffer.concat([variableData.offsetsAndLengths.data, variableData.data.data]) addVariableDataBuffer: (variableData, buffer) -> variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(buffer.length / 2) variableData.data.writeBuffer(buffer) variableData.offset += buffer.length addVariableDataString: (variableData, value) -> value ||= '' variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(value.length) variableData.data.writeString(value); variableData.offset += value.length * 2 createNTLMRequest: (options) -> domain = escape(options.domain.toUpperCase()) workstation = if options.workstation then escape( options.workstation.toUpperCase() ) else '' protocol = 'NTLMSSP\u0000' BODY_LENGTH = 40 type1flags = @getNTLMFlags() type1flags -= NTLMFlags.NTLM_NegotiateOemWorkstationSupplied if workstation is '' bufferLength = BODY_LENGTH + domain.length buffer = new WritableTrackingBuffer(bufferLength) buffer.writeString(protocol, 'utf8') # protocol buffer.writeUInt32LE(1) # type 1 buffer.writeUInt32LE(type1flags) # TYPE1 flag buffer.writeUInt16LE(domain.length) # domain length buffer.writeUInt16LE(domain.length) # domain max length buffer.writeUInt32LE(BODY_LENGTH + workstation.length) # domain buffer offset buffer.writeUInt16LE(workstation.length) # workstation length buffer.writeUInt16LE(workstation.length) # workstation max length buffer.writeUInt32LE(BODY_LENGTH) # domain buffer offset buffer.writeUInt8(5) #ProductMajorVersion buffer.writeUInt8(0) #ProductMinorVersion buffer.writeUInt16LE(2195) #ProductBuild buffer.writeUInt8(0) #VersionReserved1 buffer.writeUInt8(0) #VersionReserved2 buffer.writeUInt8(0) #VersionReserved3 buffer.writeUInt8(15) #NTLMRevisionCurrent buffer.writeString(workstation, 'ascii') buffer.writeString(domain, 'ascii') buffer.data createPasswordBuffer: -> password = @loginData.password || '' password = new Buffer(password, '<PASSWORD>') for b in [0..password.length - 1] byte = password[b] lowNibble = byte & 0x0f highNibble = (byte >> 4) byte = (lowNibble << 4) | highNibble byte = byte ^ 0xa5 password[b] = byte password getNTLMFlags: -> (NTLMFlags.NTLM_NegotiateUnicode + NTLMFlags.NTLM_NegotiateOEM + NTLMFlags.NTLM_RequestTarget + NTLMFlags.NTLM_NegotiateNTLM + NTLMFlags.NTLM_NegotiateOemDomainSupplied + NTLMFlags.NTLM_NegotiateOemWorkstationSupplied + NTLMFlags.NTLM_NegotiateAlwaysSign + NTLMFlags.NTLM_NegotiateVersion + NTLMFlags.NTLM_NegotiateExtendedSecurity + NTLMFlags.NTLM_Negotiate128 + NTLMFlags.NTLM_Negotiate56) toString: (indent) -> indent ||= '' indent + 'Login7 - ' + sprintf('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', @tdsVersion, @packetSize, @clientProgVer, @clientPid, @connectionId ) + '\n' + indent + ' ' + sprintf('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', @flags1, @flags2, @typeFlags, @flags3, @clientTimeZone, @clientLcid ) + '\n' + indent + ' ' + sprintf("Hostname:'%s', Username:'%s', Password:'<PASSWORD>', AppName:'%s', ServerName:'%s', LibraryName:'%s'", @hostname, @loginData.userName, @loginData.password, @loginData.appName, @loginData.serverName, libraryName ) + '\n' + indent + ' ' + sprintf("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'<PASSWORD>'", @loginData.language, @loginData.database, @sspi, @attachDbFile @changePassword ) module.exports = Login7Payload
true
WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer') require('./buffertools') os= require('os') sprintf = require('sprintf').sprintf libraryName = require('./library').name versions = require('./tds-versions').versions FLAGS_1 = ENDIAN_LITTLE: 0x00, ENDIAN_BIG: 0x01, CHARSET_ASCII: 0x00, CHARSET_EBCDIC: 0x02, FLOAT_IEEE_754: 0x00, FLOAT_VAX: 0x04, FLOAT_ND5000: 0x08, BCP_DUMPLOAD_ON: 0x00, BCP_DUMPLOAD_OFF: 0x10, USE_DB_ON: 0x00, USE_DB_OFF: 0x20, INIT_DB_WARN: 0x00, INIT_DB_FATAL: 0x40, SET_LANG_WARN_OFF: 0x00, SET_LANG_WARN_ON: 0x80, FLAGS_2 = INIT_LANG_WARN: 0x00, INIT_LANG_FATAL: 0x01, ODBC_OFF: 0x00, ODBC_ON: 0x02, F_TRAN_BOUNDARY: 0x04, # Removed in TDS 7.2 F_CACHE_CONNECT: 0x08, # Removed in TDS 7.2 USER_NORMAL: 0x00, USER_SERVER: 0x10, USER_REMUSER: 0x20, USER_SQLREPL: 0x40, INTEGRATED_SECURITY_OFF: 0x00, INTEGRATED_SECURITY_ON: 0x80 TYPE_FLAGS = SQL_DFLT: 0x00, SQL_TSQL: 0x08, OLEDB_OFF: 0x00, OLEDB_ON: 0x10, # Introduced in TDS 7.2 READ_WRITE_INTENT: 0x00, READ_ONLY_INTENT: 0x20 # Introduced in TDS 7.4 FLAGS_3 = CHANGE_PASSWORD_NO: 0x00, CHANGE_PASSWORD_YES: 0x01, # Introduced in TDS 7.2 BINARY_XML: 0x02, # Introduced in TDS 7.2 SPAWN_USER_INSTANCE: 0x04, # Introduced in TDS 7.2 UNKNOWN_COLLATION_HANDLING: 0x08 # Introduced in TDS 7.3 NTLMFlags = NTLM_NegotiateUnicode: 0x00000001 NTLM_NegotiateOEM: 0x00000002 NTLM_RequestTarget: 0x00000004 NTLM_Unknown9: 0x00000008 NTLM_NegotiateSign: 0x00000010 NTLM_NegotiateSeal: 0x00000020 NTLM_NegotiateDatagram: 0x00000040 NTLM_NegotiateLanManagerKey: 0x0PI:KEY:<KEY>END_PI0 NTLM_Unknown8: 0x00000100 NTLM_NegotiateNTLM: 0x00000200 NTLM_NegotiateNTOnly: 0x00000400 NTLM_Anonymous: 0x00000800 NTLM_NegotiateOemDomainSupplied: 0x00001000 NTLM_NegotiateOemWorkstationSupplied: 0x00002000 NTLM_Unknown6: 0x00004000 NTLM_NegotiateAlwaysSign: 0x00008000 NTLM_TargetTypeDomain: 0x00010000 NTLM_TargetTypeServer: 0x00020000 NTLM_TargetTypeShare: 0x00040000 NTLM_NegotiateExtendedSecurity: 0x00080000 # Negotiate NTLM2 Key NTLM_NegotiateIdentify: 0x00100000 # Request Init Response NTLM_Unknown5: 0x00200000 # Request Accept Response NTLM_RequestNonNTSessionKey: 0x00400000 NTLM_NegotiateTargetInfo: 0x00800000 NTLM_Unknown4: 0x01000000 NTLM_NegotiateVersion: 0x02000000 NTLM_Unknown3: 0x04000000 NTLM_Unknown2: 0x08000000 NTLM_Unknown1: 0x10000000 NTLM_Negotiate128: 0x20000000 NTLM_NegotiateKeyExchange: 0x40000000 NTLM_Negotiate56: 0x80000000 ### s2.2.6.3 ### class Login7Payload constructor: (@loginData) -> lengthLength = 4 fixed = @createFixedData() variable = @createVariableData(lengthLength + fixed.length) length = lengthLength + fixed.length + variable.length data = new WritableTrackingBuffer(300) data.writeUInt32LE(length) data.writeBuffer(fixed) data.writeBuffer(variable) @data = data.data createFixedData: -> @tdsVersion = versions[@loginData.tdsVersion] @packetSize = @loginData.packetSize @clientProgVer = 0 @clientPid = process.pid @connectionId = 0 @clientTimeZone = new Date().getTimezoneOffset() @clientLcid = 0x00000409 #Can't figure what form this should take. @flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCD_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.SET_LANG_WARN_ON if @loginData.initDbFatal @flags1 |= FLAGS_1.INIT_DB_FATAL else @flags1 |= FLAGS_1.INIT_DB_WARN @flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL if @loginData.domain @flags2 |= FLAGS_2.INTEGRATED_SECURITY_ON else @flags2 |= FLAGS_2.INTEGRATED_SECURITY_OFF @flags3 = FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING @typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF if @loginData.readOnlyIntent @typeFlags |= TYPE_FLAGS.READ_ONLY_INTENT else @typeFlags |= TYPE_FLAGS.READ_WRITE_INTENT buffer = new WritableTrackingBuffer(100) buffer.writeUInt32LE(@tdsVersion) buffer.writeUInt32LE(@packetSize) buffer.writeUInt32LE(@clientProgVer) buffer.writeUInt32LE(@clientPid) buffer.writeUInt32LE(@connectionId) buffer.writeUInt8(@flags1) buffer.writeUInt8(@flags2) buffer.writeUInt8(@typeFlags) buffer.writeUInt8(@flags3) buffer.writeInt32LE(@clientTimeZone) buffer.writeUInt32LE(@clientLcid) buffer.data createVariableData: (offset) -> @variableLengthsLength = ((9 * 4) + 6 + (3 * 4) + 4) if @loginData.tdsVersion == '7_1' @variableLengthsLength = ((9 * 4) + 6 + (2 * 4)) variableData = offsetsAndLengths: new WritableTrackingBuffer(200) data: new WritableTrackingBuffer(200, 'ucs2') offset: offset + @variableLengthsLength @hostname = os.hostname() @loginData = @loginData || {} @loginData.appName = @loginData.appName || 'Tedious' @libraryName = libraryName # Client ID, should be MAC address or other randomly generated GUID like value. @clientId = new Buffer([1, 2, 3, 4, 5, 6]) unless @loginData.domain @sspi = '' @sspiLong = 0 @attachDbFile = '' @changePassword = '' @addVariableDataString(variableData, @hostname) @addVariableDataString(variableData, @loginData.userName) @addVariableDataBuffer(variableData, @createPasswordBuffer()) @addVariableDataString(variableData, @loginData.appName) @addVariableDataString(variableData, @loginData.serverName) @addVariableDataString(variableData, '') # Reserved for future use. @addVariableDataString(variableData, @libraryName) @addVariableDataString(variableData, @loginData.language) @addVariableDataString(variableData, @loginData.database) variableData.offsetsAndLengths.writeBuffer(@clientId) if @loginData.domain @ntlmPacket = @createNTLMRequest(@loginData) @sspiLong = @ntlmPacket.length variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(@ntlmPacket.length) variableData.data.writeBuffer(@ntlmPacket) variableData.offset += @ntlmPacket.length else @addVariableDataString(variableData, @sspi) @addVariableDataString(variableData, @attachDbFile) if @loginData.tdsVersion > '7_1' @addVariableDataString(variableData, @changePassword) # Introduced in TDS 7.2 variableData.offsetsAndLengths.writeUInt32LE(@sspiLong) # Introduced in TDS 7.2 variableData.offsetsAndLengths.data = Buffer.concat([variableData.offsetsAndLengths.data, variableData.data.data]) addVariableDataBuffer: (variableData, buffer) -> variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(buffer.length / 2) variableData.data.writeBuffer(buffer) variableData.offset += buffer.length addVariableDataString: (variableData, value) -> value ||= '' variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(value.length) variableData.data.writeString(value); variableData.offset += value.length * 2 createNTLMRequest: (options) -> domain = escape(options.domain.toUpperCase()) workstation = if options.workstation then escape( options.workstation.toUpperCase() ) else '' protocol = 'NTLMSSP\u0000' BODY_LENGTH = 40 type1flags = @getNTLMFlags() type1flags -= NTLMFlags.NTLM_NegotiateOemWorkstationSupplied if workstation is '' bufferLength = BODY_LENGTH + domain.length buffer = new WritableTrackingBuffer(bufferLength) buffer.writeString(protocol, 'utf8') # protocol buffer.writeUInt32LE(1) # type 1 buffer.writeUInt32LE(type1flags) # TYPE1 flag buffer.writeUInt16LE(domain.length) # domain length buffer.writeUInt16LE(domain.length) # domain max length buffer.writeUInt32LE(BODY_LENGTH + workstation.length) # domain buffer offset buffer.writeUInt16LE(workstation.length) # workstation length buffer.writeUInt16LE(workstation.length) # workstation max length buffer.writeUInt32LE(BODY_LENGTH) # domain buffer offset buffer.writeUInt8(5) #ProductMajorVersion buffer.writeUInt8(0) #ProductMinorVersion buffer.writeUInt16LE(2195) #ProductBuild buffer.writeUInt8(0) #VersionReserved1 buffer.writeUInt8(0) #VersionReserved2 buffer.writeUInt8(0) #VersionReserved3 buffer.writeUInt8(15) #NTLMRevisionCurrent buffer.writeString(workstation, 'ascii') buffer.writeString(domain, 'ascii') buffer.data createPasswordBuffer: -> password = @loginData.password || '' password = new Buffer(password, 'PI:PASSWORD:<PASSWORD>END_PI') for b in [0..password.length - 1] byte = password[b] lowNibble = byte & 0x0f highNibble = (byte >> 4) byte = (lowNibble << 4) | highNibble byte = byte ^ 0xa5 password[b] = byte password getNTLMFlags: -> (NTLMFlags.NTLM_NegotiateUnicode + NTLMFlags.NTLM_NegotiateOEM + NTLMFlags.NTLM_RequestTarget + NTLMFlags.NTLM_NegotiateNTLM + NTLMFlags.NTLM_NegotiateOemDomainSupplied + NTLMFlags.NTLM_NegotiateOemWorkstationSupplied + NTLMFlags.NTLM_NegotiateAlwaysSign + NTLMFlags.NTLM_NegotiateVersion + NTLMFlags.NTLM_NegotiateExtendedSecurity + NTLMFlags.NTLM_Negotiate128 + NTLMFlags.NTLM_Negotiate56) toString: (indent) -> indent ||= '' indent + 'Login7 - ' + sprintf('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', @tdsVersion, @packetSize, @clientProgVer, @clientPid, @connectionId ) + '\n' + indent + ' ' + sprintf('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', @flags1, @flags2, @typeFlags, @flags3, @clientTimeZone, @clientLcid ) + '\n' + indent + ' ' + sprintf("Hostname:'%s', Username:'%s', Password:'PI:PASSWORD:<PASSWORD>END_PI', AppName:'%s', ServerName:'%s', LibraryName:'%s'", @hostname, @loginData.userName, @loginData.password, @loginData.appName, @loginData.serverName, libraryName ) + '\n' + indent + ' ' + sprintf("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'PI:PASSWORD:<PASSWORD>END_PI'", @loginData.language, @loginData.database, @sspi, @attachDbFile @changePassword ) module.exports = Login7Payload
[ { "context": "'use strict'\n\n###*\n # By Mo Binni\n###\napp = angular.module('materialDatePicker', []", "end": 33, "score": 0.9992340207099915, "start": 25, "tag": "NAME", "value": "Mo Binni" } ]
app/scripts/mbdatepicker.coffee
mnandwe/material-date-picker
0
'use strict' ###* # By Mo Binni ### app = angular.module('materialDatePicker', []) contains = (container, contained) -> node = contained.parentNode while (node != null && node != container) node = node.parentNode node != null app.directive("outsideClick", ['$document', '$parse', '$timeout', ($document, $parse, $timeout) -> link: ($scope, $element, $attributes) -> scopeExpression = $attributes.outsideClick onDocumentClick = (event) -> $timeout -> $scope.$eval scopeExpression unless contains($element[0], event.target) return $document.on "click", onDocumentClick $element.on "$destroy", -> $document.off "click", onDocumentClick return return ]) app.directive('mbDatepicker', ['$filter', ($filter)-> require: ['ngModel'] scope: { elementId: '@', dateFormat: '@' minDate: '@' maxDate: '@' inputClass: '@' inputName: '@' placeholder: '@' arrows: '=?' calendarHeader: '=?', utcMode: '=' # UTC mode can be used for fixed dates that should never be converted to local timezones (e.g., birth dates), ngDisabled: '=', label: '@', customInputClass: '@', tz: '=', } template: ' <div id="dateSelectors" class="date-selectors" outside-click="hidePicker()"> <label ng-bind="label" class="mb-input-label" for="{{inputName}}"></label> <input name="{{ inputName }}" type="text" ng-disabled="{{ngDisabled}}" ng-class="{disabled: ngDisabled}" class="mb-input-field {{customInputClass}}" ng-click="showPicker()" class="form-control" id="{{inputName}}" placeholder="{{ placeholder }}" ng-model="innerModel" ng-change="innerChange()"> <div class="mb-datepicker" ng-show="isVisible"> <table> <caption> <div class="header-year-wrapper"> <span style="display: inline-block; float: left; padding-left:20px; cursor: pointer" class="noselect" ng-click="previousYear(currentDate)"><i class="material-icons">chevron_left</i></span> <span class="header-year noselect" ng-class="noselect">{{ year }}</span> <span style="display: inline-block; float: right; padding-right:20px; cursor: pointer" class="noselect" ng-click="nextYear(currentDate)"><i class="material-icons">chevron_right</i></span> </div> <div class="header-nav-wrapper"> <span class="header-item noselect" style="float: left; cursor:pointer" ng-click="previousMonth(currentDate)"><i class="material-icons">chevron_left</i></span> <span class="header-month noselect">{{ month }}</span> <span class="header-item header-right noselect" style="float: right; cursor:pointer" ng-click="nextMonth(currentDate)"> <i class="material-icons">chevron_right</i></span> </div> </caption> <tbody> <tr> <td class="day-head">{{ ::calendarHeader.sunday }}</td> <td class="day-head">{{ ::calendarHeader.monday }}</td> <td class="day-head">{{ ::calendarHeader.tuesday }}</td> <td class="day-head">{{ ::calendarHeader.wednesday }}</td> <td class="day-head">{{ ::calendarHeader.thursday }}</td> <td class="day-head">{{ ::calendarHeader.friday }}</td> <td class="day-head">{{ ::calendarHeader.saturday }}</td> </tr> <tr class="days" ng-repeat="week in weeks track by week.id"> <td ng-click="selectDate(day)" class="noselect day-item" ng-repeat="day in week.week track by day.date" ng-class="{selected: selectedDate === day.fmt, weekend: day.isWeekend, today: day.isToday, day: day.isEnabled, disabled: !day.isEnabled}"> <div style="display: block;"> {{ ::day.value }} </div> </td> </tr> </tbody> </table> </div> </div> ' restrict: 'E', transclude: true, link: (scope, element, attrs, ngModel) -> defaultTimezone = moment.tz.guess(); # Vars selectors = element[0].querySelector('.date-selectors'); today = moment() if scope.utcMode then today.utc() scope.month = ''; scope.year = today.year(); # Casual definition if scope.inputClass then selectors.className = selectors.className + " " + scope.inputClass if !scope.dateFormat then scope.dateFormat = "YYYY-MM-DD" if scope.minDate scope.minDate = moment(scope.minDate, scope.dateFormat) if scope.utcMode then scope.minDate.utc() if scope.maxDate scope.maxDate = moment(scope.maxDate, scope.dateFormat) if scope.utcMode then scope.maxDate.utc() if !scope.calendarHeader then scope.calendarHeader = { sunday: $filter('date')(new Date(moment().isoWeekday(7)), 'EEE'), monday: $filter('date')(new Date(moment().isoWeekday(1)), 'EEE'), tuesday: $filter('date')(new Date(moment().isoWeekday(2)), 'EEE'), wednesday: $filter('date')(new Date(moment().isoWeekday(3)), 'EEE'), thursday: $filter('date')(new Date(moment().isoWeekday(4)), 'EEE'), friday: $filter('date')(new Date(moment().isoWeekday(5)), 'EEE'), saturday: $filter('date')(new Date(moment().isoWeekday(6)), 'EEE'), } # Datepicker logic to get weeks getWeeks = (monthLength, startDay, month) -> monthDays = [] # Iterate over other dates for day in [0..monthLength] start = moment(startDay) if scope.utcMode then start.utc() newDate = start.add(day, 'd') day = { date: newDate, value: newDate.format('DD'), fmt: newDate.format('YYYY-MM-DD') }; if(scope.minDate and moment(newDate, scope.dateFormat) <= moment(scope.minDate, scope.dateFormat)) day.isToday = true; day.isEnabled = false; monthDays.push(day); else if(scope.maxDate and moment(newDate, scope.dateFormat) >= moment(scope.maxDate, scope.dateFormat)) day.isToday = true; day.isEnabled = false; else if newDate.format(scope.dateFormat) == moment().tz(getTimezone()).format(scope.dateFormat) day.isToday = true; day.isEnabled = true; else if(newDate.month() == month) day.isToday = false; day.isEnabled = true; if(newDate.day() == 0 || newDate.day() == 6) day.isWeekend = true; else day.isToday = false; day.isEnabled = false; monthDays.push(day); chunk_size = 7; # Map reduce by 7 days per week weeks = monthDays.map((e, i) -> if i % chunk_size == 0 then {id:'id_'+i+'_'+month,week:monthDays.slice(i, i + chunk_size)} else null; ).filter((e) -> return e; ); if weeks then return weeks else return [] changeDisplay = (to) -> scope.year = to.year() last_day = moment(to).add(1, 'month').date(0) if (last_day.day() != 7) last_day = last_day.add(6 - last_day.day(), 'days') first_day = moment(to).date(0).startOf('isoweek').add(-1, 'day') scope.currentDate = to scope.weeks = [] scope.weeks = getWeeks( last_day.diff(first_day, 'days'), first_day, to.month() ) scope.month = to.format('MMM') # Logic to get the following month scope.nextMonth = (date) -> changeDisplay(date.date(1).add(1, 'month')); # Logic to get the previous month scope.previousMonth = (date) -> changeDisplay(date.date(1).add(-1, 'month')); # Logic to get the next year scope.nextYear = (date) -> changeDisplay(date.date(1).add(1, 'year')); # Logic to get the previous year scope.previousYear = (date) -> changeDisplay(date.date(1).add(-1, 'year')); dateChanged = (to, dontSetModel) -> scope.selectedDate = to.format('YYYY-MM-DD'); scope.innerModel = to.format(scope.dateFormat || 'YYYY-MM-DD'); if !dontSetModel ngModel[0].$setViewValue(to.format(scope.dateFormat || 'YYYY-MM-DD')); changeDisplay(to); getTimezone = -> if scope.tz return scope.tz return defaultTimezone # Logic to hide the view if a date is selected scope.selectDate = (day) -> dateChanged(day.date) scope.isVisible = false; scope.isVisible = false scope.showPicker = -> scope.isVisible = true selectedDate = moment.tz(scope.innerModel, scope.dateFormat || 'YYYY-MM-DD', getTimezone()) if scope.currentDate.tz(getTimezone()).format('YYYY-MM') != selectedDate.format('YYYY-MM') changeDisplay(selectedDate.date(1)) return scope.hidePicker = -> scope.isVisible = false return init = -> dateChanged(moment().tz(getTimezone()), true); # listen for input change scope.innerChange = () -> date = moment.tz(scope.innerModel, scope.dateFormat || 'YYYY-MM-DD', getTimezone()); if !date.isValid() return dateChanged(date) scope.$watch (() -> return scope.tz), (() -> ngModel[0].$render()) # our model changed ngModel[0].$render = () -> dateChanged(moment.tz(ngModel[0].$viewValue, scope.dateFormat || 'YYYY-MM-DD', getTimezone()), true) init() ])
26016
'use strict' ###* # By <NAME> ### app = angular.module('materialDatePicker', []) contains = (container, contained) -> node = contained.parentNode while (node != null && node != container) node = node.parentNode node != null app.directive("outsideClick", ['$document', '$parse', '$timeout', ($document, $parse, $timeout) -> link: ($scope, $element, $attributes) -> scopeExpression = $attributes.outsideClick onDocumentClick = (event) -> $timeout -> $scope.$eval scopeExpression unless contains($element[0], event.target) return $document.on "click", onDocumentClick $element.on "$destroy", -> $document.off "click", onDocumentClick return return ]) app.directive('mbDatepicker', ['$filter', ($filter)-> require: ['ngModel'] scope: { elementId: '@', dateFormat: '@' minDate: '@' maxDate: '@' inputClass: '@' inputName: '@' placeholder: '@' arrows: '=?' calendarHeader: '=?', utcMode: '=' # UTC mode can be used for fixed dates that should never be converted to local timezones (e.g., birth dates), ngDisabled: '=', label: '@', customInputClass: '@', tz: '=', } template: ' <div id="dateSelectors" class="date-selectors" outside-click="hidePicker()"> <label ng-bind="label" class="mb-input-label" for="{{inputName}}"></label> <input name="{{ inputName }}" type="text" ng-disabled="{{ngDisabled}}" ng-class="{disabled: ngDisabled}" class="mb-input-field {{customInputClass}}" ng-click="showPicker()" class="form-control" id="{{inputName}}" placeholder="{{ placeholder }}" ng-model="innerModel" ng-change="innerChange()"> <div class="mb-datepicker" ng-show="isVisible"> <table> <caption> <div class="header-year-wrapper"> <span style="display: inline-block; float: left; padding-left:20px; cursor: pointer" class="noselect" ng-click="previousYear(currentDate)"><i class="material-icons">chevron_left</i></span> <span class="header-year noselect" ng-class="noselect">{{ year }}</span> <span style="display: inline-block; float: right; padding-right:20px; cursor: pointer" class="noselect" ng-click="nextYear(currentDate)"><i class="material-icons">chevron_right</i></span> </div> <div class="header-nav-wrapper"> <span class="header-item noselect" style="float: left; cursor:pointer" ng-click="previousMonth(currentDate)"><i class="material-icons">chevron_left</i></span> <span class="header-month noselect">{{ month }}</span> <span class="header-item header-right noselect" style="float: right; cursor:pointer" ng-click="nextMonth(currentDate)"> <i class="material-icons">chevron_right</i></span> </div> </caption> <tbody> <tr> <td class="day-head">{{ ::calendarHeader.sunday }}</td> <td class="day-head">{{ ::calendarHeader.monday }}</td> <td class="day-head">{{ ::calendarHeader.tuesday }}</td> <td class="day-head">{{ ::calendarHeader.wednesday }}</td> <td class="day-head">{{ ::calendarHeader.thursday }}</td> <td class="day-head">{{ ::calendarHeader.friday }}</td> <td class="day-head">{{ ::calendarHeader.saturday }}</td> </tr> <tr class="days" ng-repeat="week in weeks track by week.id"> <td ng-click="selectDate(day)" class="noselect day-item" ng-repeat="day in week.week track by day.date" ng-class="{selected: selectedDate === day.fmt, weekend: day.isWeekend, today: day.isToday, day: day.isEnabled, disabled: !day.isEnabled}"> <div style="display: block;"> {{ ::day.value }} </div> </td> </tr> </tbody> </table> </div> </div> ' restrict: 'E', transclude: true, link: (scope, element, attrs, ngModel) -> defaultTimezone = moment.tz.guess(); # Vars selectors = element[0].querySelector('.date-selectors'); today = moment() if scope.utcMode then today.utc() scope.month = ''; scope.year = today.year(); # Casual definition if scope.inputClass then selectors.className = selectors.className + " " + scope.inputClass if !scope.dateFormat then scope.dateFormat = "YYYY-MM-DD" if scope.minDate scope.minDate = moment(scope.minDate, scope.dateFormat) if scope.utcMode then scope.minDate.utc() if scope.maxDate scope.maxDate = moment(scope.maxDate, scope.dateFormat) if scope.utcMode then scope.maxDate.utc() if !scope.calendarHeader then scope.calendarHeader = { sunday: $filter('date')(new Date(moment().isoWeekday(7)), 'EEE'), monday: $filter('date')(new Date(moment().isoWeekday(1)), 'EEE'), tuesday: $filter('date')(new Date(moment().isoWeekday(2)), 'EEE'), wednesday: $filter('date')(new Date(moment().isoWeekday(3)), 'EEE'), thursday: $filter('date')(new Date(moment().isoWeekday(4)), 'EEE'), friday: $filter('date')(new Date(moment().isoWeekday(5)), 'EEE'), saturday: $filter('date')(new Date(moment().isoWeekday(6)), 'EEE'), } # Datepicker logic to get weeks getWeeks = (monthLength, startDay, month) -> monthDays = [] # Iterate over other dates for day in [0..monthLength] start = moment(startDay) if scope.utcMode then start.utc() newDate = start.add(day, 'd') day = { date: newDate, value: newDate.format('DD'), fmt: newDate.format('YYYY-MM-DD') }; if(scope.minDate and moment(newDate, scope.dateFormat) <= moment(scope.minDate, scope.dateFormat)) day.isToday = true; day.isEnabled = false; monthDays.push(day); else if(scope.maxDate and moment(newDate, scope.dateFormat) >= moment(scope.maxDate, scope.dateFormat)) day.isToday = true; day.isEnabled = false; else if newDate.format(scope.dateFormat) == moment().tz(getTimezone()).format(scope.dateFormat) day.isToday = true; day.isEnabled = true; else if(newDate.month() == month) day.isToday = false; day.isEnabled = true; if(newDate.day() == 0 || newDate.day() == 6) day.isWeekend = true; else day.isToday = false; day.isEnabled = false; monthDays.push(day); chunk_size = 7; # Map reduce by 7 days per week weeks = monthDays.map((e, i) -> if i % chunk_size == 0 then {id:'id_'+i+'_'+month,week:monthDays.slice(i, i + chunk_size)} else null; ).filter((e) -> return e; ); if weeks then return weeks else return [] changeDisplay = (to) -> scope.year = to.year() last_day = moment(to).add(1, 'month').date(0) if (last_day.day() != 7) last_day = last_day.add(6 - last_day.day(), 'days') first_day = moment(to).date(0).startOf('isoweek').add(-1, 'day') scope.currentDate = to scope.weeks = [] scope.weeks = getWeeks( last_day.diff(first_day, 'days'), first_day, to.month() ) scope.month = to.format('MMM') # Logic to get the following month scope.nextMonth = (date) -> changeDisplay(date.date(1).add(1, 'month')); # Logic to get the previous month scope.previousMonth = (date) -> changeDisplay(date.date(1).add(-1, 'month')); # Logic to get the next year scope.nextYear = (date) -> changeDisplay(date.date(1).add(1, 'year')); # Logic to get the previous year scope.previousYear = (date) -> changeDisplay(date.date(1).add(-1, 'year')); dateChanged = (to, dontSetModel) -> scope.selectedDate = to.format('YYYY-MM-DD'); scope.innerModel = to.format(scope.dateFormat || 'YYYY-MM-DD'); if !dontSetModel ngModel[0].$setViewValue(to.format(scope.dateFormat || 'YYYY-MM-DD')); changeDisplay(to); getTimezone = -> if scope.tz return scope.tz return defaultTimezone # Logic to hide the view if a date is selected scope.selectDate = (day) -> dateChanged(day.date) scope.isVisible = false; scope.isVisible = false scope.showPicker = -> scope.isVisible = true selectedDate = moment.tz(scope.innerModel, scope.dateFormat || 'YYYY-MM-DD', getTimezone()) if scope.currentDate.tz(getTimezone()).format('YYYY-MM') != selectedDate.format('YYYY-MM') changeDisplay(selectedDate.date(1)) return scope.hidePicker = -> scope.isVisible = false return init = -> dateChanged(moment().tz(getTimezone()), true); # listen for input change scope.innerChange = () -> date = moment.tz(scope.innerModel, scope.dateFormat || 'YYYY-MM-DD', getTimezone()); if !date.isValid() return dateChanged(date) scope.$watch (() -> return scope.tz), (() -> ngModel[0].$render()) # our model changed ngModel[0].$render = () -> dateChanged(moment.tz(ngModel[0].$viewValue, scope.dateFormat || 'YYYY-MM-DD', getTimezone()), true) init() ])
true
'use strict' ###* # By PI:NAME:<NAME>END_PI ### app = angular.module('materialDatePicker', []) contains = (container, contained) -> node = contained.parentNode while (node != null && node != container) node = node.parentNode node != null app.directive("outsideClick", ['$document', '$parse', '$timeout', ($document, $parse, $timeout) -> link: ($scope, $element, $attributes) -> scopeExpression = $attributes.outsideClick onDocumentClick = (event) -> $timeout -> $scope.$eval scopeExpression unless contains($element[0], event.target) return $document.on "click", onDocumentClick $element.on "$destroy", -> $document.off "click", onDocumentClick return return ]) app.directive('mbDatepicker', ['$filter', ($filter)-> require: ['ngModel'] scope: { elementId: '@', dateFormat: '@' minDate: '@' maxDate: '@' inputClass: '@' inputName: '@' placeholder: '@' arrows: '=?' calendarHeader: '=?', utcMode: '=' # UTC mode can be used for fixed dates that should never be converted to local timezones (e.g., birth dates), ngDisabled: '=', label: '@', customInputClass: '@', tz: '=', } template: ' <div id="dateSelectors" class="date-selectors" outside-click="hidePicker()"> <label ng-bind="label" class="mb-input-label" for="{{inputName}}"></label> <input name="{{ inputName }}" type="text" ng-disabled="{{ngDisabled}}" ng-class="{disabled: ngDisabled}" class="mb-input-field {{customInputClass}}" ng-click="showPicker()" class="form-control" id="{{inputName}}" placeholder="{{ placeholder }}" ng-model="innerModel" ng-change="innerChange()"> <div class="mb-datepicker" ng-show="isVisible"> <table> <caption> <div class="header-year-wrapper"> <span style="display: inline-block; float: left; padding-left:20px; cursor: pointer" class="noselect" ng-click="previousYear(currentDate)"><i class="material-icons">chevron_left</i></span> <span class="header-year noselect" ng-class="noselect">{{ year }}</span> <span style="display: inline-block; float: right; padding-right:20px; cursor: pointer" class="noselect" ng-click="nextYear(currentDate)"><i class="material-icons">chevron_right</i></span> </div> <div class="header-nav-wrapper"> <span class="header-item noselect" style="float: left; cursor:pointer" ng-click="previousMonth(currentDate)"><i class="material-icons">chevron_left</i></span> <span class="header-month noselect">{{ month }}</span> <span class="header-item header-right noselect" style="float: right; cursor:pointer" ng-click="nextMonth(currentDate)"> <i class="material-icons">chevron_right</i></span> </div> </caption> <tbody> <tr> <td class="day-head">{{ ::calendarHeader.sunday }}</td> <td class="day-head">{{ ::calendarHeader.monday }}</td> <td class="day-head">{{ ::calendarHeader.tuesday }}</td> <td class="day-head">{{ ::calendarHeader.wednesday }}</td> <td class="day-head">{{ ::calendarHeader.thursday }}</td> <td class="day-head">{{ ::calendarHeader.friday }}</td> <td class="day-head">{{ ::calendarHeader.saturday }}</td> </tr> <tr class="days" ng-repeat="week in weeks track by week.id"> <td ng-click="selectDate(day)" class="noselect day-item" ng-repeat="day in week.week track by day.date" ng-class="{selected: selectedDate === day.fmt, weekend: day.isWeekend, today: day.isToday, day: day.isEnabled, disabled: !day.isEnabled}"> <div style="display: block;"> {{ ::day.value }} </div> </td> </tr> </tbody> </table> </div> </div> ' restrict: 'E', transclude: true, link: (scope, element, attrs, ngModel) -> defaultTimezone = moment.tz.guess(); # Vars selectors = element[0].querySelector('.date-selectors'); today = moment() if scope.utcMode then today.utc() scope.month = ''; scope.year = today.year(); # Casual definition if scope.inputClass then selectors.className = selectors.className + " " + scope.inputClass if !scope.dateFormat then scope.dateFormat = "YYYY-MM-DD" if scope.minDate scope.minDate = moment(scope.minDate, scope.dateFormat) if scope.utcMode then scope.minDate.utc() if scope.maxDate scope.maxDate = moment(scope.maxDate, scope.dateFormat) if scope.utcMode then scope.maxDate.utc() if !scope.calendarHeader then scope.calendarHeader = { sunday: $filter('date')(new Date(moment().isoWeekday(7)), 'EEE'), monday: $filter('date')(new Date(moment().isoWeekday(1)), 'EEE'), tuesday: $filter('date')(new Date(moment().isoWeekday(2)), 'EEE'), wednesday: $filter('date')(new Date(moment().isoWeekday(3)), 'EEE'), thursday: $filter('date')(new Date(moment().isoWeekday(4)), 'EEE'), friday: $filter('date')(new Date(moment().isoWeekday(5)), 'EEE'), saturday: $filter('date')(new Date(moment().isoWeekday(6)), 'EEE'), } # Datepicker logic to get weeks getWeeks = (monthLength, startDay, month) -> monthDays = [] # Iterate over other dates for day in [0..monthLength] start = moment(startDay) if scope.utcMode then start.utc() newDate = start.add(day, 'd') day = { date: newDate, value: newDate.format('DD'), fmt: newDate.format('YYYY-MM-DD') }; if(scope.minDate and moment(newDate, scope.dateFormat) <= moment(scope.minDate, scope.dateFormat)) day.isToday = true; day.isEnabled = false; monthDays.push(day); else if(scope.maxDate and moment(newDate, scope.dateFormat) >= moment(scope.maxDate, scope.dateFormat)) day.isToday = true; day.isEnabled = false; else if newDate.format(scope.dateFormat) == moment().tz(getTimezone()).format(scope.dateFormat) day.isToday = true; day.isEnabled = true; else if(newDate.month() == month) day.isToday = false; day.isEnabled = true; if(newDate.day() == 0 || newDate.day() == 6) day.isWeekend = true; else day.isToday = false; day.isEnabled = false; monthDays.push(day); chunk_size = 7; # Map reduce by 7 days per week weeks = monthDays.map((e, i) -> if i % chunk_size == 0 then {id:'id_'+i+'_'+month,week:monthDays.slice(i, i + chunk_size)} else null; ).filter((e) -> return e; ); if weeks then return weeks else return [] changeDisplay = (to) -> scope.year = to.year() last_day = moment(to).add(1, 'month').date(0) if (last_day.day() != 7) last_day = last_day.add(6 - last_day.day(), 'days') first_day = moment(to).date(0).startOf('isoweek').add(-1, 'day') scope.currentDate = to scope.weeks = [] scope.weeks = getWeeks( last_day.diff(first_day, 'days'), first_day, to.month() ) scope.month = to.format('MMM') # Logic to get the following month scope.nextMonth = (date) -> changeDisplay(date.date(1).add(1, 'month')); # Logic to get the previous month scope.previousMonth = (date) -> changeDisplay(date.date(1).add(-1, 'month')); # Logic to get the next year scope.nextYear = (date) -> changeDisplay(date.date(1).add(1, 'year')); # Logic to get the previous year scope.previousYear = (date) -> changeDisplay(date.date(1).add(-1, 'year')); dateChanged = (to, dontSetModel) -> scope.selectedDate = to.format('YYYY-MM-DD'); scope.innerModel = to.format(scope.dateFormat || 'YYYY-MM-DD'); if !dontSetModel ngModel[0].$setViewValue(to.format(scope.dateFormat || 'YYYY-MM-DD')); changeDisplay(to); getTimezone = -> if scope.tz return scope.tz return defaultTimezone # Logic to hide the view if a date is selected scope.selectDate = (day) -> dateChanged(day.date) scope.isVisible = false; scope.isVisible = false scope.showPicker = -> scope.isVisible = true selectedDate = moment.tz(scope.innerModel, scope.dateFormat || 'YYYY-MM-DD', getTimezone()) if scope.currentDate.tz(getTimezone()).format('YYYY-MM') != selectedDate.format('YYYY-MM') changeDisplay(selectedDate.date(1)) return scope.hidePicker = -> scope.isVisible = false return init = -> dateChanged(moment().tz(getTimezone()), true); # listen for input change scope.innerChange = () -> date = moment.tz(scope.innerModel, scope.dateFormat || 'YYYY-MM-DD', getTimezone()); if !date.isValid() return dateChanged(date) scope.$watch (() -> return scope.tz), (() -> ngModel[0].$render()) # our model changed ngModel[0].$render = () -> dateChanged(moment.tz(ngModel[0].$viewValue, scope.dateFormat || 'YYYY-MM-DD', getTimezone()), true) init() ])
[ { "context": "space COOLSTRAP.View\n * @class Aside\n *\n * @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n###\n\nCO", "end": 114, "score": 0.9998937249183655, "start": 99, "tag": "NAME", "value": "Abraham Barrera" }, { "context": "ew\n * @class Aside\n *\n * @aut...
coolstrap-core/app/assets/javascripts/coolstrap/view/_Coolstrap.View.Aside.coffee
cristianferrarig/coolstrap
0
### * Initialize the <Aisde> layout * * @namespace COOLSTRAP.View * @class Aside * * @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera ### COOLSTRAP.View.Aside = ((cool) -> ELEMENT = cool.Constants.ELEMENT CLASS = cool.Constants.CLASS ATTRIBUTE = cool.Constants.ATTRIBUTE TRANSITION = cool.Constants.TRANSITION ### * Display an aside element * * @method show * * @param {string} Aside id. ### show = (aside_id) -> aside = cool.dom(ELEMENT.ASIDE + aside_id) body_class = CLASS.SHOW + CLASS.ASIDE + _classFromAside(aside) _initFirstSection aside cool.dom(ELEMENT.BODY).addClass(body_class).addClass CLASS.ASIDE aside.addClass CLASS.CURRENT _initFirstSection = (aside) -> aside_id = aside.attr(ATTRIBUTE.ID) sections = cool.dom("#" + aside_id + " " + ELEMENT.SECTION + "." + CLASS.CURRENT) section_to_show = sections.first() if not section_to_show or section_to_show.length is 0 sections = cool.dom("#" + aside_id + " " + ELEMENT.SECTION) section_to_show = sections.first() section_id = "#" + section_to_show.attr(ATTRIBUTE.ID) section_to_show.addClass CLASS.CURRENT cool.Navigate.History.add section_id: section_id container_id: aside_id init_container: true ### * Hide an aside element * * @method hide * * @param {string} Aside id. ### hide = (aside_id) -> aside = cool.dom(ELEMENT.ASIDE + aside_id) body_class = CLASS.SHOW + CLASS.ASIDE + _classFromAside(aside) cool.dom(ELEMENT.BODY).removeClass(body_class).removeClass CLASS.ASIDE setTimeout (-> current_aside = ELEMENT.ASIDE + aside_id + "." + CLASS.CURRENT cool.dom(current_aside).removeClass CLASS.CURRENT ), TRANSITION.DURATION cool.Navigate.History.clear aside_id _classFromAside = (aside) -> aside_class = aside.attr(ATTRIBUTE.CLASS) aside_class or "" show: show hide: hide )(COOLSTRAP)
198354
### * Initialize the <Aisde> layout * * @namespace COOLSTRAP.View * @class Aside * * @author <NAME> <<EMAIL>> || @abraham_barrera ### COOLSTRAP.View.Aside = ((cool) -> ELEMENT = cool.Constants.ELEMENT CLASS = cool.Constants.CLASS ATTRIBUTE = cool.Constants.ATTRIBUTE TRANSITION = cool.Constants.TRANSITION ### * Display an aside element * * @method show * * @param {string} Aside id. ### show = (aside_id) -> aside = cool.dom(ELEMENT.ASIDE + aside_id) body_class = CLASS.SHOW + CLASS.ASIDE + _classFromAside(aside) _initFirstSection aside cool.dom(ELEMENT.BODY).addClass(body_class).addClass CLASS.ASIDE aside.addClass CLASS.CURRENT _initFirstSection = (aside) -> aside_id = aside.attr(ATTRIBUTE.ID) sections = cool.dom("#" + aside_id + " " + ELEMENT.SECTION + "." + CLASS.CURRENT) section_to_show = sections.first() if not section_to_show or section_to_show.length is 0 sections = cool.dom("#" + aside_id + " " + ELEMENT.SECTION) section_to_show = sections.first() section_id = "#" + section_to_show.attr(ATTRIBUTE.ID) section_to_show.addClass CLASS.CURRENT cool.Navigate.History.add section_id: section_id container_id: aside_id init_container: true ### * Hide an aside element * * @method hide * * @param {string} Aside id. ### hide = (aside_id) -> aside = cool.dom(ELEMENT.ASIDE + aside_id) body_class = CLASS.SHOW + CLASS.ASIDE + _classFromAside(aside) cool.dom(ELEMENT.BODY).removeClass(body_class).removeClass CLASS.ASIDE setTimeout (-> current_aside = ELEMENT.ASIDE + aside_id + "." + CLASS.CURRENT cool.dom(current_aside).removeClass CLASS.CURRENT ), TRANSITION.DURATION cool.Navigate.History.clear aside_id _classFromAside = (aside) -> aside_class = aside.attr(ATTRIBUTE.CLASS) aside_class or "" show: show hide: hide )(COOLSTRAP)
true
### * Initialize the <Aisde> layout * * @namespace COOLSTRAP.View * @class Aside * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @abraham_barrera ### COOLSTRAP.View.Aside = ((cool) -> ELEMENT = cool.Constants.ELEMENT CLASS = cool.Constants.CLASS ATTRIBUTE = cool.Constants.ATTRIBUTE TRANSITION = cool.Constants.TRANSITION ### * Display an aside element * * @method show * * @param {string} Aside id. ### show = (aside_id) -> aside = cool.dom(ELEMENT.ASIDE + aside_id) body_class = CLASS.SHOW + CLASS.ASIDE + _classFromAside(aside) _initFirstSection aside cool.dom(ELEMENT.BODY).addClass(body_class).addClass CLASS.ASIDE aside.addClass CLASS.CURRENT _initFirstSection = (aside) -> aside_id = aside.attr(ATTRIBUTE.ID) sections = cool.dom("#" + aside_id + " " + ELEMENT.SECTION + "." + CLASS.CURRENT) section_to_show = sections.first() if not section_to_show or section_to_show.length is 0 sections = cool.dom("#" + aside_id + " " + ELEMENT.SECTION) section_to_show = sections.first() section_id = "#" + section_to_show.attr(ATTRIBUTE.ID) section_to_show.addClass CLASS.CURRENT cool.Navigate.History.add section_id: section_id container_id: aside_id init_container: true ### * Hide an aside element * * @method hide * * @param {string} Aside id. ### hide = (aside_id) -> aside = cool.dom(ELEMENT.ASIDE + aside_id) body_class = CLASS.SHOW + CLASS.ASIDE + _classFromAside(aside) cool.dom(ELEMENT.BODY).removeClass(body_class).removeClass CLASS.ASIDE setTimeout (-> current_aside = ELEMENT.ASIDE + aside_id + "." + CLASS.CURRENT cool.dom(current_aside).removeClass CLASS.CURRENT ), TRANSITION.DURATION cool.Navigate.History.clear aside_id _classFromAside = (aside) -> aside_class = aside.attr(ATTRIBUTE.CLASS) aside_class or "" show: show hide: hide )(COOLSTRAP)
[ { "context": "ramer.Extras.Hints.disable()\n\n'''\nwatchOS\n\n@auther Jungho song (threeword.com)\n@since 2016.11.24\n'''\nclass expor", "end": 79, "score": 0.9998680949211121, "start": 68, "tag": "NAME", "value": "Jungho song" } ]
modules/watchos.coffee
framer-modules/watchos
2
# Disable hints Framer.Extras.Hints.disable() ''' watchOS @auther Jungho song (threeword.com) @since 2016.11.24 ''' class exports.WatchOS extends Framer.BaseClass ''' options: appInfo: name: "카카오증권" icon: "images/appicon.png" app: kakaostocks complications: utilitarian: [ ] modular: [ new Complication().modularSmall().simpleText("카카오증권") ] circular: [ ] ''' # Constructor constructor: (options={}) -> super options.appInfo ?= {} @appInfo = options.appInfo @app = @appInfo.app @complications = options.complications # Background @bg = new Layer name: "Background", backgroundColor: "black" # Clockface (Complication) @clockfaces = new ClockFaces width: Device.width, height: Device.height complications: @complications # Docks @docks = new Docks width: Device.width, height: Device.height # Apps @apps = new Apps width: Device.width, height: Device.height clockfaces: @clockfaces appInfo: @appInfo # Event : Digital Crown Device.onDigitalCrown => currentScreen = @_getCurrentScreen() return unless currentScreen # Clockface if currentScreen is @clockfaces # Clockface : change mode if @clockfaces.isChangeMode then @clockfaces.selected() # Clockface : normal mode else @apps.show @clockfaces # App else if currentScreen is @app @apps.show @app # Apps else if currentScreen is @apps @apps.dismiss @clockfaces # Docks else if currentScreen is @docks @docks.dismiss true # Notification else if currentScreen is @notification @notification.dismiss() # Event : Side button Device.onSide => currentScreen = @_getCurrentScreen() return unless currentScreen # Docks if currentScreen is @docks then @docks.dismiss() else # App if currentScreen is @app @docks.addRecentDock @appInfo @apps.init() # Not App else @docks.show() # ------------------------------------------------------------ # Public # ------------------------------------------------------------ # Notify notification showNotification: (options = {}) -> @notification.destroy() if @notification @notification = new Notification options # Set clockface setClockface: (index) -> @clockfaces.setClockface index # ------------------------------------------------------------ # Private # ------------------------------------------------------------ # Get current screen layer (first layer) _getCurrentScreen: -> return if _.isEmpty(@bg.siblings) layers = _.sortBy(@bg.siblings, 'index').reverse() return layers[0]
112698
# Disable hints Framer.Extras.Hints.disable() ''' watchOS @auther <NAME> (threeword.com) @since 2016.11.24 ''' class exports.WatchOS extends Framer.BaseClass ''' options: appInfo: name: "카카오증권" icon: "images/appicon.png" app: kakaostocks complications: utilitarian: [ ] modular: [ new Complication().modularSmall().simpleText("카카오증권") ] circular: [ ] ''' # Constructor constructor: (options={}) -> super options.appInfo ?= {} @appInfo = options.appInfo @app = @appInfo.app @complications = options.complications # Background @bg = new Layer name: "Background", backgroundColor: "black" # Clockface (Complication) @clockfaces = new ClockFaces width: Device.width, height: Device.height complications: @complications # Docks @docks = new Docks width: Device.width, height: Device.height # Apps @apps = new Apps width: Device.width, height: Device.height clockfaces: @clockfaces appInfo: @appInfo # Event : Digital Crown Device.onDigitalCrown => currentScreen = @_getCurrentScreen() return unless currentScreen # Clockface if currentScreen is @clockfaces # Clockface : change mode if @clockfaces.isChangeMode then @clockfaces.selected() # Clockface : normal mode else @apps.show @clockfaces # App else if currentScreen is @app @apps.show @app # Apps else if currentScreen is @apps @apps.dismiss @clockfaces # Docks else if currentScreen is @docks @docks.dismiss true # Notification else if currentScreen is @notification @notification.dismiss() # Event : Side button Device.onSide => currentScreen = @_getCurrentScreen() return unless currentScreen # Docks if currentScreen is @docks then @docks.dismiss() else # App if currentScreen is @app @docks.addRecentDock @appInfo @apps.init() # Not App else @docks.show() # ------------------------------------------------------------ # Public # ------------------------------------------------------------ # Notify notification showNotification: (options = {}) -> @notification.destroy() if @notification @notification = new Notification options # Set clockface setClockface: (index) -> @clockfaces.setClockface index # ------------------------------------------------------------ # Private # ------------------------------------------------------------ # Get current screen layer (first layer) _getCurrentScreen: -> return if _.isEmpty(@bg.siblings) layers = _.sortBy(@bg.siblings, 'index').reverse() return layers[0]
true
# Disable hints Framer.Extras.Hints.disable() ''' watchOS @auther PI:NAME:<NAME>END_PI (threeword.com) @since 2016.11.24 ''' class exports.WatchOS extends Framer.BaseClass ''' options: appInfo: name: "카카오증권" icon: "images/appicon.png" app: kakaostocks complications: utilitarian: [ ] modular: [ new Complication().modularSmall().simpleText("카카오증권") ] circular: [ ] ''' # Constructor constructor: (options={}) -> super options.appInfo ?= {} @appInfo = options.appInfo @app = @appInfo.app @complications = options.complications # Background @bg = new Layer name: "Background", backgroundColor: "black" # Clockface (Complication) @clockfaces = new ClockFaces width: Device.width, height: Device.height complications: @complications # Docks @docks = new Docks width: Device.width, height: Device.height # Apps @apps = new Apps width: Device.width, height: Device.height clockfaces: @clockfaces appInfo: @appInfo # Event : Digital Crown Device.onDigitalCrown => currentScreen = @_getCurrentScreen() return unless currentScreen # Clockface if currentScreen is @clockfaces # Clockface : change mode if @clockfaces.isChangeMode then @clockfaces.selected() # Clockface : normal mode else @apps.show @clockfaces # App else if currentScreen is @app @apps.show @app # Apps else if currentScreen is @apps @apps.dismiss @clockfaces # Docks else if currentScreen is @docks @docks.dismiss true # Notification else if currentScreen is @notification @notification.dismiss() # Event : Side button Device.onSide => currentScreen = @_getCurrentScreen() return unless currentScreen # Docks if currentScreen is @docks then @docks.dismiss() else # App if currentScreen is @app @docks.addRecentDock @appInfo @apps.init() # Not App else @docks.show() # ------------------------------------------------------------ # Public # ------------------------------------------------------------ # Notify notification showNotification: (options = {}) -> @notification.destroy() if @notification @notification = new Notification options # Set clockface setClockface: (index) -> @clockfaces.setClockface index # ------------------------------------------------------------ # Private # ------------------------------------------------------------ # Get current screen layer (first layer) _getCurrentScreen: -> return if _.isEmpty(@bg.siblings) layers = _.sortBy(@bg.siblings, 'index').reverse() return layers[0]
[ { "context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n\nLicensed under the A", "end": 39, "score": 0.9998874664306641, "start": 26, "tag": "NAME", "value": "Stephan Jorek" }, { "context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com...
src/Dom/Traversal/Level2TreeWalker.coffee
sjorek/goatee.js
0
### © Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### #~ require {Level2NodeIterator} = require './Level2NodeIterator' #~ export exports = module?.exports ? this # Level2TreeWalker # ================================ # -------------------------------- # A class to hold state for a DOM traversal. # # This implementation depends on *DOM Level ≥ 2*'s `TreeWalker`. # # @public # @class Level2TreeWalker # @extends goatee.Dom.Traversal # @namespace goatee.Dom.Traversal # @see [`TreeWalker` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker) exports.Level2TreeWalker = \ class Level2TreeWalker extends Level2NodeIterator # -------------------------------- # Create `TreeWalker` node iterator for a single root node. # # Create an iterator collecting a single node's immediate child-nodes. # # @public # @method collect # @param {Node} root The root node of the traversal. # @param {Document} doc Root's owner-document. # @return {TreeWalker} # @see [`createTreeWalker` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document.createTreeWalker) collect: (root, doc) -> doc.createTreeWalker( # Node to use as root root, # > Is an optional unsigned long representing a bitmask created by # combining the constant properties of NodeFilter. It is a convenient # way of filtering for certain types of node. It defaults to # `0xFFFFFFFF` (-1) representing the SHOW_ALL constant. @filter, # > Is an optional NodeFilter, that is an object with a method acceptNode, # which is called by the TreeWalker to determine whether or not to # accept a node that has passed the whatToShow check. @options, # > A boolean flag indicating if when discarding an EntityReference its # whole sub-tree must be discarded at the same time. # @deprecated false ) # -------------------------------- # Creates the `Traversal`-instance. # # @static # @public # @method create # @param {Function} callback A function, called for each traversed node # @return {goatee.Dom.Traversal} @create: (callback) -> new Level2TreeWalker callback
157624
### © Copyright 2013-2014 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### #~ require {Level2NodeIterator} = require './Level2NodeIterator' #~ export exports = module?.exports ? this # Level2TreeWalker # ================================ # -------------------------------- # A class to hold state for a DOM traversal. # # This implementation depends on *DOM Level ≥ 2*'s `TreeWalker`. # # @public # @class Level2TreeWalker # @extends goatee.Dom.Traversal # @namespace goatee.Dom.Traversal # @see [`TreeWalker` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker) exports.Level2TreeWalker = \ class Level2TreeWalker extends Level2NodeIterator # -------------------------------- # Create `TreeWalker` node iterator for a single root node. # # Create an iterator collecting a single node's immediate child-nodes. # # @public # @method collect # @param {Node} root The root node of the traversal. # @param {Document} doc Root's owner-document. # @return {TreeWalker} # @see [`createTreeWalker` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document.createTreeWalker) collect: (root, doc) -> doc.createTreeWalker( # Node to use as root root, # > Is an optional unsigned long representing a bitmask created by # combining the constant properties of NodeFilter. It is a convenient # way of filtering for certain types of node. It defaults to # `0xFFFFFFFF` (-1) representing the SHOW_ALL constant. @filter, # > Is an optional NodeFilter, that is an object with a method acceptNode, # which is called by the TreeWalker to determine whether or not to # accept a node that has passed the whatToShow check. @options, # > A boolean flag indicating if when discarding an EntityReference its # whole sub-tree must be discarded at the same time. # @deprecated false ) # -------------------------------- # Creates the `Traversal`-instance. # # @static # @public # @method create # @param {Function} callback A function, called for each traversed node # @return {goatee.Dom.Traversal} @create: (callback) -> new Level2TreeWalker callback
true
### © Copyright 2013-2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### #~ require {Level2NodeIterator} = require './Level2NodeIterator' #~ export exports = module?.exports ? this # Level2TreeWalker # ================================ # -------------------------------- # A class to hold state for a DOM traversal. # # This implementation depends on *DOM Level ≥ 2*'s `TreeWalker`. # # @public # @class Level2TreeWalker # @extends goatee.Dom.Traversal # @namespace goatee.Dom.Traversal # @see [`TreeWalker` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker) exports.Level2TreeWalker = \ class Level2TreeWalker extends Level2NodeIterator # -------------------------------- # Create `TreeWalker` node iterator for a single root node. # # Create an iterator collecting a single node's immediate child-nodes. # # @public # @method collect # @param {Node} root The root node of the traversal. # @param {Document} doc Root's owner-document. # @return {TreeWalker} # @see [`createTreeWalker` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document.createTreeWalker) collect: (root, doc) -> doc.createTreeWalker( # Node to use as root root, # > Is an optional unsigned long representing a bitmask created by # combining the constant properties of NodeFilter. It is a convenient # way of filtering for certain types of node. It defaults to # `0xFFFFFFFF` (-1) representing the SHOW_ALL constant. @filter, # > Is an optional NodeFilter, that is an object with a method acceptNode, # which is called by the TreeWalker to determine whether or not to # accept a node that has passed the whatToShow check. @options, # > A boolean flag indicating if when discarding an EntityReference its # whole sub-tree must be discarded at the same time. # @deprecated false ) # -------------------------------- # Creates the `Traversal`-instance. # # @static # @public # @method create # @param {Function} callback A function, called for each traversed node # @return {goatee.Dom.Traversal} @create: (callback) -> new Level2TreeWalker callback
[ { "context": "eq.body).replace(/\"password\":\".*?\"/, '\"password\":\"**********\"')\n\n # 不需要验证身份的路径\n for reqPath in [\n '/user/", "end": 1250, "score": 0.9987479448318481, "start": 1250, "tag": "PASSWORD", "value": "" } ]
src/index.coffee
liyujun1989/sealtalk-server
0
express = require 'express' cookieParser = require 'cookie-parser' bodyParser = require 'body-parser' compression = require 'compression' cors = require 'cors' Config = require './conf' Session = require './util/session' Utility = require('./util/util').Utility HTTPError = require('./util/util').HTTPError userRouter = require './routes/user' # 引用用户相关接口 friendshipRouter = require './routes/friendship' # 引用好友相关接口 groupRouter = require './routes/group' # 引用群组相关接口 miscRouter = require './routes/misc' # 引用其他功能接口 if env = process.env.NODE_ENV isnt 'development' and env isnt 'production' console.log "Error: NODE_ENV must be set to 'development' or 'production'." return process.exit() app = express() app.use compression() # 使用内容压缩 app.use cookieParser() # 使用 Cookie 解析器 app.use bodyParser.json() # 使用 Body 解析器 app.use cors # 使用 CORS,支持跨域 origin: Config.CORS_HOSTS credentials: true # 身份验证 authentication = (req, res, next) -> Utility.logPath 'Request: %s %s %s', (req.method + ' ').substr(0, 4), req.originalUrl, JSON.stringify(req.body).replace(/"password":".*?"/, '"password":"**********"') # 不需要验证身份的路径 for reqPath in [ '/user/login' '/user/register' '/user/reset_password' '/user/send_code' '/user/verify_code' '/user/get_sms_img_code' '/user/check_username_available' '/user/check_phone_available' '/misc/latest_update' '/misc/demo_square' ] if (typeof reqPath is 'string' and req.path is reqPath) or (typeof reqPath is 'object' and reqPath.test req.path) return next() # 跳过验证 currentUserId = Session.getCurrentUserId req # 无法获取用户 Id,即表示没有登录 if not currentUserId return res.status(403).send 'Not loged in.' next() # 参数预处理 parameterPreprocessor = (req, res, next) -> for prop of req.body # 参数解码 if prop.endsWith('Id') or prop.endsWith('Ids') req.body['encoded' + prop[0].toUpperCase() + prop.substr(1)] = req.body[prop] req.body[prop] = Utility.decodeIds req.body[prop] # 检测空参数 if Utility.isEmpty(req.body[prop]) and prop isnt 'displayName' return res.status(400).send "Empty #{prop}." next() # 错误处理 errorHandler = (err, req, res, next) -> if err instanceof HTTPError return res.status(err.statusCode).send err.message Utility.logError err res.status(500).send err.message || 'Unknown error.' app.options '*', cors() # 跨域支持 app.all '*', authentication # 前置身份验证 app.use parameterPreprocessor # 参数预处理 app.use '/user', userRouter # 加载用户相关接口 app.use '/friendship', friendshipRouter # 加载好友相关接口 app.use '/group', groupRouter # 加载群组相关接口 app.use '/misc', miscRouter # 加载其他功能接口 app.use errorHandler # 错误处理 # 开启端口监听 server = app.listen Config.SERVER_PORT, -> console.log 'SealTalk Server listening at http://%s:%s in %s mode.', server.address().address, server.address().port, app.get('env') module.exports = app
45029
express = require 'express' cookieParser = require 'cookie-parser' bodyParser = require 'body-parser' compression = require 'compression' cors = require 'cors' Config = require './conf' Session = require './util/session' Utility = require('./util/util').Utility HTTPError = require('./util/util').HTTPError userRouter = require './routes/user' # 引用用户相关接口 friendshipRouter = require './routes/friendship' # 引用好友相关接口 groupRouter = require './routes/group' # 引用群组相关接口 miscRouter = require './routes/misc' # 引用其他功能接口 if env = process.env.NODE_ENV isnt 'development' and env isnt 'production' console.log "Error: NODE_ENV must be set to 'development' or 'production'." return process.exit() app = express() app.use compression() # 使用内容压缩 app.use cookieParser() # 使用 Cookie 解析器 app.use bodyParser.json() # 使用 Body 解析器 app.use cors # 使用 CORS,支持跨域 origin: Config.CORS_HOSTS credentials: true # 身份验证 authentication = (req, res, next) -> Utility.logPath 'Request: %s %s %s', (req.method + ' ').substr(0, 4), req.originalUrl, JSON.stringify(req.body).replace(/"password":".*?"/, '"password":"<PASSWORD>**********"') # 不需要验证身份的路径 for reqPath in [ '/user/login' '/user/register' '/user/reset_password' '/user/send_code' '/user/verify_code' '/user/get_sms_img_code' '/user/check_username_available' '/user/check_phone_available' '/misc/latest_update' '/misc/demo_square' ] if (typeof reqPath is 'string' and req.path is reqPath) or (typeof reqPath is 'object' and reqPath.test req.path) return next() # 跳过验证 currentUserId = Session.getCurrentUserId req # 无法获取用户 Id,即表示没有登录 if not currentUserId return res.status(403).send 'Not loged in.' next() # 参数预处理 parameterPreprocessor = (req, res, next) -> for prop of req.body # 参数解码 if prop.endsWith('Id') or prop.endsWith('Ids') req.body['encoded' + prop[0].toUpperCase() + prop.substr(1)] = req.body[prop] req.body[prop] = Utility.decodeIds req.body[prop] # 检测空参数 if Utility.isEmpty(req.body[prop]) and prop isnt 'displayName' return res.status(400).send "Empty #{prop}." next() # 错误处理 errorHandler = (err, req, res, next) -> if err instanceof HTTPError return res.status(err.statusCode).send err.message Utility.logError err res.status(500).send err.message || 'Unknown error.' app.options '*', cors() # 跨域支持 app.all '*', authentication # 前置身份验证 app.use parameterPreprocessor # 参数预处理 app.use '/user', userRouter # 加载用户相关接口 app.use '/friendship', friendshipRouter # 加载好友相关接口 app.use '/group', groupRouter # 加载群组相关接口 app.use '/misc', miscRouter # 加载其他功能接口 app.use errorHandler # 错误处理 # 开启端口监听 server = app.listen Config.SERVER_PORT, -> console.log 'SealTalk Server listening at http://%s:%s in %s mode.', server.address().address, server.address().port, app.get('env') module.exports = app
true
express = require 'express' cookieParser = require 'cookie-parser' bodyParser = require 'body-parser' compression = require 'compression' cors = require 'cors' Config = require './conf' Session = require './util/session' Utility = require('./util/util').Utility HTTPError = require('./util/util').HTTPError userRouter = require './routes/user' # 引用用户相关接口 friendshipRouter = require './routes/friendship' # 引用好友相关接口 groupRouter = require './routes/group' # 引用群组相关接口 miscRouter = require './routes/misc' # 引用其他功能接口 if env = process.env.NODE_ENV isnt 'development' and env isnt 'production' console.log "Error: NODE_ENV must be set to 'development' or 'production'." return process.exit() app = express() app.use compression() # 使用内容压缩 app.use cookieParser() # 使用 Cookie 解析器 app.use bodyParser.json() # 使用 Body 解析器 app.use cors # 使用 CORS,支持跨域 origin: Config.CORS_HOSTS credentials: true # 身份验证 authentication = (req, res, next) -> Utility.logPath 'Request: %s %s %s', (req.method + ' ').substr(0, 4), req.originalUrl, JSON.stringify(req.body).replace(/"password":".*?"/, '"password":"PI:PASSWORD:<PASSWORD>END_PI**********"') # 不需要验证身份的路径 for reqPath in [ '/user/login' '/user/register' '/user/reset_password' '/user/send_code' '/user/verify_code' '/user/get_sms_img_code' '/user/check_username_available' '/user/check_phone_available' '/misc/latest_update' '/misc/demo_square' ] if (typeof reqPath is 'string' and req.path is reqPath) or (typeof reqPath is 'object' and reqPath.test req.path) return next() # 跳过验证 currentUserId = Session.getCurrentUserId req # 无法获取用户 Id,即表示没有登录 if not currentUserId return res.status(403).send 'Not loged in.' next() # 参数预处理 parameterPreprocessor = (req, res, next) -> for prop of req.body # 参数解码 if prop.endsWith('Id') or prop.endsWith('Ids') req.body['encoded' + prop[0].toUpperCase() + prop.substr(1)] = req.body[prop] req.body[prop] = Utility.decodeIds req.body[prop] # 检测空参数 if Utility.isEmpty(req.body[prop]) and prop isnt 'displayName' return res.status(400).send "Empty #{prop}." next() # 错误处理 errorHandler = (err, req, res, next) -> if err instanceof HTTPError return res.status(err.statusCode).send err.message Utility.logError err res.status(500).send err.message || 'Unknown error.' app.options '*', cors() # 跨域支持 app.all '*', authentication # 前置身份验证 app.use parameterPreprocessor # 参数预处理 app.use '/user', userRouter # 加载用户相关接口 app.use '/friendship', friendshipRouter # 加载好友相关接口 app.use '/group', groupRouter # 加载群组相关接口 app.use '/misc', miscRouter # 加载其他功能接口 app.use errorHandler # 错误处理 # 开启端口监听 server = app.listen Config.SERVER_PORT, -> console.log 'SealTalk Server listening at http://%s:%s in %s mode.', server.address().address, server.address().port, app.get('env') module.exports = app
[ { "context": "renderArticle: (article, i) ->\n article._key ?= Math.random()\n <li key={article._key} className=\"field-gui", "end": 334, "score": 0.8586716055870056, "start": 323, "tag": "KEY", "value": "Math.random" } ]
app/pages/lab/field-guide/article-list.cjsx
Crentist/Panoptes-frontend-spanish
1
React = require 'react' ArticleListItem = require './article-list-item' DragReorderable = require 'drag-reorderable' ArticleList = React.createClass getDefaultProps: -> articles: [] icons: {} onReorder: -> onSelectArticle: -> onRemoveArticle: -> renderArticle: (article, i) -> article._key ?= Math.random() <li key={article._key} className="field-guide-editor-article-list-item-container"> <ArticleListItem icon={@props.icons[article.icon]?.src} title={article.title} onClick={@props.onSelectArticle.bind null, i} /> <button type="button" className="field-guide-editor-article-list-item-remove-button" title="Remove this entry" onClick={@props.onRemoveArticle.bind null, i}> <i className="fa fa-trash-o fa-fw"></i> </button> </li> render: -> <DragReorderable tag="ul" className="field-guide-editor-article-list" items={@props.articles} render={@renderArticle} onChange={@props.onReorder} /> module.exports = ArticleList
84394
React = require 'react' ArticleListItem = require './article-list-item' DragReorderable = require 'drag-reorderable' ArticleList = React.createClass getDefaultProps: -> articles: [] icons: {} onReorder: -> onSelectArticle: -> onRemoveArticle: -> renderArticle: (article, i) -> article._key ?= <KEY>() <li key={article._key} className="field-guide-editor-article-list-item-container"> <ArticleListItem icon={@props.icons[article.icon]?.src} title={article.title} onClick={@props.onSelectArticle.bind null, i} /> <button type="button" className="field-guide-editor-article-list-item-remove-button" title="Remove this entry" onClick={@props.onRemoveArticle.bind null, i}> <i className="fa fa-trash-o fa-fw"></i> </button> </li> render: -> <DragReorderable tag="ul" className="field-guide-editor-article-list" items={@props.articles} render={@renderArticle} onChange={@props.onReorder} /> module.exports = ArticleList
true
React = require 'react' ArticleListItem = require './article-list-item' DragReorderable = require 'drag-reorderable' ArticleList = React.createClass getDefaultProps: -> articles: [] icons: {} onReorder: -> onSelectArticle: -> onRemoveArticle: -> renderArticle: (article, i) -> article._key ?= PI:KEY:<KEY>END_PI() <li key={article._key} className="field-guide-editor-article-list-item-container"> <ArticleListItem icon={@props.icons[article.icon]?.src} title={article.title} onClick={@props.onSelectArticle.bind null, i} /> <button type="button" className="field-guide-editor-article-list-item-remove-button" title="Remove this entry" onClick={@props.onRemoveArticle.bind null, i}> <i className="fa fa-trash-o fa-fw"></i> </button> </li> render: -> <DragReorderable tag="ul" className="field-guide-editor-article-list" items={@props.articles} render={@renderArticle} onChange={@props.onReorder} /> module.exports = ArticleList
[ { "context": "# Smart Time Ago v0.1.1\n\n# Copyright 2012, Terry Tai, Pragmatic.ly\n# https://pragmatic.ly/\n# Licensed ", "end": 52, "score": 0.999755859375, "start": 43, "tag": "NAME", "value": "Terry Tai" }, { "context": "ensed under the MIT license.\n# https://github.com/pragmati...
public/expand/smart-time/src/timeago.coffee
liuguodong1019/keji_school
80
# Smart Time Ago v0.1.1 # Copyright 2012, Terry Tai, Pragmatic.ly # https://pragmatic.ly/ # Licensed under the MIT license. # https://github.com/pragmaticly/smart-time-ago/blob/master/LICENSE class TimeAgo constructor: (element, options) -> @startInterval = 60000 @init(element, options) init: (element, options) -> @$element = $(element) @options = $.extend({}, $.fn.timeago.defaults, options) @updateTime() @startTimer() startTimer: -> self = @ @interval = setInterval ( -> self.refresh() ), @startInterval stopTimer: -> clearInterval(@interval) restartTimer: -> @stopTimer() @startTimer() refresh: -> @updateTime() @updateInterval() updateTime: -> self = @ @$element.findAndSelf(@options.selector).each -> timeAgoInWords = self.timeAgoInWords($(this).attr(self.options.attr)) $(this).html(timeAgoInWords) updateInterval: -> if @$element.findAndSelf(@options.selector).length > 0 if @options.dir is "up" filter = ":first" else if @options.dir is "down" filter = ":last" newestTimeSrc = @$element.findAndSelf(@options.selector).filter(filter).attr(@options.attr) newestTime = @parse(newestTimeSrc) newestTimeInMinutes = @getTimeDistanceInMinutes(newestTime) if newestTimeInMinutes >= 0 and newestTimeInMinutes <= 44 and @startInterval != 60000 #1 minute @startInterval = 60000 @restartTimer() else if newestTimeInMinutes >= 45 and newestTimeInMinutes <= 89 and @startInterval != 60000 * 22 #22 minutes @startInterval = 60000 * 22 @restartTimer() else if newestTimeInMinutes >= 90 and newestTimeInMinutes <= 2519 and @startInterval != 60000 * 30 #half hour @startInterval = 60000 * 30 @restartTimer() else if newestTimeInMinutes >= 2520 and @startInterval != 60000 * 60 * 12 #half day @startInterval = 60000 * 60 * 12 @restartTimer() timeAgoInWords: (timeString) -> absolutTime = @parse(timeString) "#{@options.lang.prefixes.ago}#{@distanceOfTimeInWords(absolutTime)}#{@options.lang.suffix}" parse: (iso8601) -> timeStr = $.trim(iso8601) timeStr = timeStr.replace(/\.\d+/,"") timeStr = timeStr.replace(/-/,"/").replace(/-/,"/") timeStr = timeStr.replace(/T/," ").replace(/Z/," UTC") timeStr = timeStr.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2") new Date(timeStr); getTimeDistanceInMinutes: (absolutTime) -> timeDistance = new Date().getTime() - absolutTime.getTime() Math.round((Math.abs(timeDistance) / 1000) / 60) distanceOfTimeInWords: (absolutTime) -> #TODO support i18n. dim = @getTimeDistanceInMinutes(absolutTime) #distance in minutes if dim == 0 "#{ @options.lang.prefixes.lt } #{ @options.lang.units.minute }" else if dim == 1 "1 #{ @options.lang.units.minute }" else if dim >= 2 and dim <= 44 "#{ dim } #{ @options.lang.units.minutes }" else if dim >= 45 and dim <= 89 "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.hour }" else if dim >= 90 and dim <= 1439 "#{ @options.lang.prefixes.about } #{ Math.round(dim / 60) } #{ @options.lang.units.hours }" else if dim >= 1440 and dim <= 2519 "1 #{ @options.lang.units.day }" else if dim >= 2520 and dim <= 43199 "#{ Math.round(dim / 1440) } #{ @options.lang.units.days }" else if dim >= 43200 and dim <= 86399 "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.month }" else if dim >= 86400 and dim <= 525599 #1 yr "#{ Math.round(dim / 43200) } #{ @options.lang.units.months }" else if dim >= 525600 and dim <= 655199 #1 yr, 3 months "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.year }" else if dim >= 655200 and dim <= 914399 #1 yr, 9 months "#{ @options.lang.prefixes.over } 1 #{ @options.lang.units.year }" else if dim >= 914400 and dim <= 1051199 #2 yr minus half minute "#{ @options.lang.prefixes.almost } 2 #{ @options.lang.units.years }" else "#{ @options.lang.prefixes.about } #{ Math.round(dim / 525600) } #{ @options.lang.units.years }" $.fn.timeago = (options = {}) -> @each -> $this = $(this) data = $this.data("timeago") if (!data) $this.data("timeago", new TimeAgo(this, options)) else if (typeof options is 'string') data[options]() $.fn.findAndSelf = (selector) -> this.find(selector).add(this.filter(selector)) $.fn.timeago.Constructor = TimeAgo $.fn.timeago.defaults = selector: 'time.timeago' attr: 'datetime' dir: 'up' lang: units: second: "second" seconds: "seconds" minute: "minute" minutes: "minutes" hour: "hour" hours: "hours" day: "day" days: "days" month: "month" months: "months" year: "year" years: "years" prefixes: lt: "less than a" about: "about" over: "over" almost: "almost" ago: "" suffix: ' ago'
219435
# Smart Time Ago v0.1.1 # Copyright 2012, <NAME>, Pragmatic.ly # https://pragmatic.ly/ # Licensed under the MIT license. # https://github.com/pragmaticly/smart-time-ago/blob/master/LICENSE class TimeAgo constructor: (element, options) -> @startInterval = 60000 @init(element, options) init: (element, options) -> @$element = $(element) @options = $.extend({}, $.fn.timeago.defaults, options) @updateTime() @startTimer() startTimer: -> self = @ @interval = setInterval ( -> self.refresh() ), @startInterval stopTimer: -> clearInterval(@interval) restartTimer: -> @stopTimer() @startTimer() refresh: -> @updateTime() @updateInterval() updateTime: -> self = @ @$element.findAndSelf(@options.selector).each -> timeAgoInWords = self.timeAgoInWords($(this).attr(self.options.attr)) $(this).html(timeAgoInWords) updateInterval: -> if @$element.findAndSelf(@options.selector).length > 0 if @options.dir is "up" filter = ":first" else if @options.dir is "down" filter = ":last" newestTimeSrc = @$element.findAndSelf(@options.selector).filter(filter).attr(@options.attr) newestTime = @parse(newestTimeSrc) newestTimeInMinutes = @getTimeDistanceInMinutes(newestTime) if newestTimeInMinutes >= 0 and newestTimeInMinutes <= 44 and @startInterval != 60000 #1 minute @startInterval = 60000 @restartTimer() else if newestTimeInMinutes >= 45 and newestTimeInMinutes <= 89 and @startInterval != 60000 * 22 #22 minutes @startInterval = 60000 * 22 @restartTimer() else if newestTimeInMinutes >= 90 and newestTimeInMinutes <= 2519 and @startInterval != 60000 * 30 #half hour @startInterval = 60000 * 30 @restartTimer() else if newestTimeInMinutes >= 2520 and @startInterval != 60000 * 60 * 12 #half day @startInterval = 60000 * 60 * 12 @restartTimer() timeAgoInWords: (timeString) -> absolutTime = @parse(timeString) "#{@options.lang.prefixes.ago}#{@distanceOfTimeInWords(absolutTime)}#{@options.lang.suffix}" parse: (iso8601) -> timeStr = $.trim(iso8601) timeStr = timeStr.replace(/\.\d+/,"") timeStr = timeStr.replace(/-/,"/").replace(/-/,"/") timeStr = timeStr.replace(/T/," ").replace(/Z/," UTC") timeStr = timeStr.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2") new Date(timeStr); getTimeDistanceInMinutes: (absolutTime) -> timeDistance = new Date().getTime() - absolutTime.getTime() Math.round((Math.abs(timeDistance) / 1000) / 60) distanceOfTimeInWords: (absolutTime) -> #TODO support i18n. dim = @getTimeDistanceInMinutes(absolutTime) #distance in minutes if dim == 0 "#{ @options.lang.prefixes.lt } #{ @options.lang.units.minute }" else if dim == 1 "1 #{ @options.lang.units.minute }" else if dim >= 2 and dim <= 44 "#{ dim } #{ @options.lang.units.minutes }" else if dim >= 45 and dim <= 89 "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.hour }" else if dim >= 90 and dim <= 1439 "#{ @options.lang.prefixes.about } #{ Math.round(dim / 60) } #{ @options.lang.units.hours }" else if dim >= 1440 and dim <= 2519 "1 #{ @options.lang.units.day }" else if dim >= 2520 and dim <= 43199 "#{ Math.round(dim / 1440) } #{ @options.lang.units.days }" else if dim >= 43200 and dim <= 86399 "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.month }" else if dim >= 86400 and dim <= 525599 #1 yr "#{ Math.round(dim / 43200) } #{ @options.lang.units.months }" else if dim >= 525600 and dim <= 655199 #1 yr, 3 months "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.year }" else if dim >= 655200 and dim <= 914399 #1 yr, 9 months "#{ @options.lang.prefixes.over } 1 #{ @options.lang.units.year }" else if dim >= 914400 and dim <= 1051199 #2 yr minus half minute "#{ @options.lang.prefixes.almost } 2 #{ @options.lang.units.years }" else "#{ @options.lang.prefixes.about } #{ Math.round(dim / 525600) } #{ @options.lang.units.years }" $.fn.timeago = (options = {}) -> @each -> $this = $(this) data = $this.data("timeago") if (!data) $this.data("timeago", new TimeAgo(this, options)) else if (typeof options is 'string') data[options]() $.fn.findAndSelf = (selector) -> this.find(selector).add(this.filter(selector)) $.fn.timeago.Constructor = TimeAgo $.fn.timeago.defaults = selector: 'time.timeago' attr: 'datetime' dir: 'up' lang: units: second: "second" seconds: "seconds" minute: "minute" minutes: "minutes" hour: "hour" hours: "hours" day: "day" days: "days" month: "month" months: "months" year: "year" years: "years" prefixes: lt: "less than a" about: "about" over: "over" almost: "almost" ago: "" suffix: ' ago'
true
# Smart Time Ago v0.1.1 # Copyright 2012, PI:NAME:<NAME>END_PI, Pragmatic.ly # https://pragmatic.ly/ # Licensed under the MIT license. # https://github.com/pragmaticly/smart-time-ago/blob/master/LICENSE class TimeAgo constructor: (element, options) -> @startInterval = 60000 @init(element, options) init: (element, options) -> @$element = $(element) @options = $.extend({}, $.fn.timeago.defaults, options) @updateTime() @startTimer() startTimer: -> self = @ @interval = setInterval ( -> self.refresh() ), @startInterval stopTimer: -> clearInterval(@interval) restartTimer: -> @stopTimer() @startTimer() refresh: -> @updateTime() @updateInterval() updateTime: -> self = @ @$element.findAndSelf(@options.selector).each -> timeAgoInWords = self.timeAgoInWords($(this).attr(self.options.attr)) $(this).html(timeAgoInWords) updateInterval: -> if @$element.findAndSelf(@options.selector).length > 0 if @options.dir is "up" filter = ":first" else if @options.dir is "down" filter = ":last" newestTimeSrc = @$element.findAndSelf(@options.selector).filter(filter).attr(@options.attr) newestTime = @parse(newestTimeSrc) newestTimeInMinutes = @getTimeDistanceInMinutes(newestTime) if newestTimeInMinutes >= 0 and newestTimeInMinutes <= 44 and @startInterval != 60000 #1 minute @startInterval = 60000 @restartTimer() else if newestTimeInMinutes >= 45 and newestTimeInMinutes <= 89 and @startInterval != 60000 * 22 #22 minutes @startInterval = 60000 * 22 @restartTimer() else if newestTimeInMinutes >= 90 and newestTimeInMinutes <= 2519 and @startInterval != 60000 * 30 #half hour @startInterval = 60000 * 30 @restartTimer() else if newestTimeInMinutes >= 2520 and @startInterval != 60000 * 60 * 12 #half day @startInterval = 60000 * 60 * 12 @restartTimer() timeAgoInWords: (timeString) -> absolutTime = @parse(timeString) "#{@options.lang.prefixes.ago}#{@distanceOfTimeInWords(absolutTime)}#{@options.lang.suffix}" parse: (iso8601) -> timeStr = $.trim(iso8601) timeStr = timeStr.replace(/\.\d+/,"") timeStr = timeStr.replace(/-/,"/").replace(/-/,"/") timeStr = timeStr.replace(/T/," ").replace(/Z/," UTC") timeStr = timeStr.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2") new Date(timeStr); getTimeDistanceInMinutes: (absolutTime) -> timeDistance = new Date().getTime() - absolutTime.getTime() Math.round((Math.abs(timeDistance) / 1000) / 60) distanceOfTimeInWords: (absolutTime) -> #TODO support i18n. dim = @getTimeDistanceInMinutes(absolutTime) #distance in minutes if dim == 0 "#{ @options.lang.prefixes.lt } #{ @options.lang.units.minute }" else if dim == 1 "1 #{ @options.lang.units.minute }" else if dim >= 2 and dim <= 44 "#{ dim } #{ @options.lang.units.minutes }" else if dim >= 45 and dim <= 89 "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.hour }" else if dim >= 90 and dim <= 1439 "#{ @options.lang.prefixes.about } #{ Math.round(dim / 60) } #{ @options.lang.units.hours }" else if dim >= 1440 and dim <= 2519 "1 #{ @options.lang.units.day }" else if dim >= 2520 and dim <= 43199 "#{ Math.round(dim / 1440) } #{ @options.lang.units.days }" else if dim >= 43200 and dim <= 86399 "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.month }" else if dim >= 86400 and dim <= 525599 #1 yr "#{ Math.round(dim / 43200) } #{ @options.lang.units.months }" else if dim >= 525600 and dim <= 655199 #1 yr, 3 months "#{ @options.lang.prefixes.about } 1 #{ @options.lang.units.year }" else if dim >= 655200 and dim <= 914399 #1 yr, 9 months "#{ @options.lang.prefixes.over } 1 #{ @options.lang.units.year }" else if dim >= 914400 and dim <= 1051199 #2 yr minus half minute "#{ @options.lang.prefixes.almost } 2 #{ @options.lang.units.years }" else "#{ @options.lang.prefixes.about } #{ Math.round(dim / 525600) } #{ @options.lang.units.years }" $.fn.timeago = (options = {}) -> @each -> $this = $(this) data = $this.data("timeago") if (!data) $this.data("timeago", new TimeAgo(this, options)) else if (typeof options is 'string') data[options]() $.fn.findAndSelf = (selector) -> this.find(selector).add(this.filter(selector)) $.fn.timeago.Constructor = TimeAgo $.fn.timeago.defaults = selector: 'time.timeago' attr: 'datetime' dir: 'up' lang: units: second: "second" seconds: "seconds" minute: "minute" minutes: "minutes" hour: "hour" hours: "hours" day: "day" days: "days" month: "month" months: "months" year: "year" years: "years" prefixes: lt: "less than a" about: "about" over: "over" almost: "almost" ago: "" suffix: ' ago'
[ { "context": "->\n pred = new Slot(true)\n name = new Slot(\"John\")\n age = new Slot(30)\n\n vals = []\n\n unsu", "end": 248, "score": 0.9997124075889587, "start": 244, "tag": "NAME", "value": "John" }, { "context": "\n vals.push val\n assert.deepEqual vals, [...
test/functions/if.coffee
trello/hearsay
5
ifFn = require 'hearsay/functions/if' Emitter = require 'hearsay/emitter' Slot = require 'hearsay/slot' defer = require 'util/defer' { assert } = require 'chai' describe "if", -> it "works", -> pred = new Slot(true) name = new Slot("John") age = new Slot(30) vals = [] unsubscribe = ifFn(pred, name, age).subscribe (val) -> vals.push val assert.deepEqual vals, ["John"] pred.set false assert.deepEqual vals, ["John", 30] age.set 40 assert.deepEqual vals, ["John", 30, 40] name.set "Mary" pred.set true assert.deepEqual vals, ["John", 30, 40, "Mary"] unsubscribe() it "distincts its if value", -> pred = new Slot(true) name = new Slot("John") age = new Slot(30) vals = [] unsubscribe = ifFn(pred, name, age).subscribe (val) -> vals.push val assert.deepEqual vals, ["John"] pred.set true pred.set true pred.set true pred.set true assert.deepEqual vals, ["John"] unsubscribe() it "does not leak subscriptions", -> disposed1 = false disposed2 = false disposed3 = false disposed4 = false pred = new Slot(true).addDisposer -> disposed1 = true name1 = new Slot("John").addDisposer -> disposed2 = true name2 = new Slot("Mark").addDisposer -> disposed3 = true ifSignal = ifFn(pred, name1, name2).addDisposer -> disposed4 = true vals = [] unsubscribe = ifSignal.subscribe (val) -> vals.push val assert.deepEqual vals, ["John"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> name1.set("Mary") assert.deepEqual vals, ["John", "Mary"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> pred.set(false) assert.deepEqual vals, ["John", "Mary", "Mark"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> pred.set(true) assert.deepEqual vals, ["John", "Mary", "Mark", "Mary"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 unsubscribe() assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> assert disposed1 assert disposed2 assert disposed3 assert disposed4 return
98267
ifFn = require 'hearsay/functions/if' Emitter = require 'hearsay/emitter' Slot = require 'hearsay/slot' defer = require 'util/defer' { assert } = require 'chai' describe "if", -> it "works", -> pred = new Slot(true) name = new Slot("<NAME>") age = new Slot(30) vals = [] unsubscribe = ifFn(pred, name, age).subscribe (val) -> vals.push val assert.deepEqual vals, ["<NAME>"] pred.set false assert.deepEqual vals, ["<NAME>", 30] age.set 40 assert.deepEqual vals, ["<NAME>", 30, 40] name.set "<NAME>" pred.set true assert.deepEqual vals, ["<NAME>", 30, 40, "<NAME>"] unsubscribe() it "distincts its if value", -> pred = new Slot(true) name = new Slot("<NAME>") age = new Slot(30) vals = [] unsubscribe = ifFn(pred, name, age).subscribe (val) -> vals.push val assert.deepEqual vals, ["<NAME>"] pred.set true pred.set true pred.set true pred.set true assert.deepEqual vals, ["<NAME>"] unsubscribe() it "does not leak subscriptions", -> disposed1 = false disposed2 = false disposed3 = false disposed4 = false pred = new Slot(true).addDisposer -> disposed1 = true name1 = new Slot("<NAME>").addDisposer -> disposed2 = true name2 = new Slot("<NAME>").addDisposer -> disposed3 = true ifSignal = ifFn(pred, name1, name2).addDisposer -> disposed4 = true vals = [] unsubscribe = ifSignal.subscribe (val) -> vals.push val assert.deepEqual vals, ["<NAME>"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> name1.set("<NAME>") assert.deepEqual vals, ["<NAME>", "<NAME>"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> pred.set(false) assert.deepEqual vals, ["<NAME>", "<NAME>", "<NAME>"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> pred.set(true) assert.deepEqual vals, ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 unsubscribe() assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> assert disposed1 assert disposed2 assert disposed3 assert disposed4 return
true
ifFn = require 'hearsay/functions/if' Emitter = require 'hearsay/emitter' Slot = require 'hearsay/slot' defer = require 'util/defer' { assert } = require 'chai' describe "if", -> it "works", -> pred = new Slot(true) name = new Slot("PI:NAME:<NAME>END_PI") age = new Slot(30) vals = [] unsubscribe = ifFn(pred, name, age).subscribe (val) -> vals.push val assert.deepEqual vals, ["PI:NAME:<NAME>END_PI"] pred.set false assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", 30] age.set 40 assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", 30, 40] name.set "PI:NAME:<NAME>END_PI" pred.set true assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", 30, 40, "PI:NAME:<NAME>END_PI"] unsubscribe() it "distincts its if value", -> pred = new Slot(true) name = new Slot("PI:NAME:<NAME>END_PI") age = new Slot(30) vals = [] unsubscribe = ifFn(pred, name, age).subscribe (val) -> vals.push val assert.deepEqual vals, ["PI:NAME:<NAME>END_PI"] pred.set true pred.set true pred.set true pred.set true assert.deepEqual vals, ["PI:NAME:<NAME>END_PI"] unsubscribe() it "does not leak subscriptions", -> disposed1 = false disposed2 = false disposed3 = false disposed4 = false pred = new Slot(true).addDisposer -> disposed1 = true name1 = new Slot("PI:NAME:<NAME>END_PI").addDisposer -> disposed2 = true name2 = new Slot("PI:NAME:<NAME>END_PI").addDisposer -> disposed3 = true ifSignal = ifFn(pred, name1, name2).addDisposer -> disposed4 = true vals = [] unsubscribe = ifSignal.subscribe (val) -> vals.push val assert.deepEqual vals, ["PI:NAME:<NAME>END_PI"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> name1.set("PI:NAME:<NAME>END_PI") assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> pred.set(false) assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> pred.set(true) assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 unsubscribe() assert !disposed1 assert !disposed2 assert !disposed3 assert !disposed4 defer() .tap -> assert disposed1 assert disposed2 assert disposed3 assert disposed4 return
[ { "context": "pile()\n return\n \n listen: ( fn ) =>\n key = \"_#{Object.keys(@_rules).length}\"\n @rule(key, fn)\n ", "end": 378, "score": 0.9941122531890869, "start": 374, "tag": "KEY", "value": "\"_#{" }, { "context": "return\n \n listen: ( fn ) =>\n key = \"_#{Obj...
src/funnel.coffee
brysgo/semantic-mapreduce
0
# # The Funnel Class # ---------------- # This is where the API and some of the setup for the rules live. class Funnel constructor: ( rules={} ) -> @_rules = {} rules.input = (arg) -> @emit arg for name, fn of rules rule = @rule(name, fn ) @[name] = ( args... ) -> rule.run( args ) @compile() return listen: ( fn ) => key = "_#{Object.keys(@_rules).length}" @rule(key, fn) @compile() # Allow other rules to register dependencies on: ( dependencies, rule ) -> [min,d] = [Infinity, undefined] for dependency in dependencies n = dependency.passes(dependencies) if n > -1 and n < min min = n d = dependency d.bind( rule ) if min > -1 and min < Infinity # Compile current set of rules compile: -> for name, rule of @_rules rule.clear() for name, rule of @_rules @on( rule.dependencies(), rule ) # Construct a new rule and pass it a reference to us rule: ( name, fn ) -> rule = new Rule( name, fn ) @_rules[name] = rule rule.constructor.f = @ return rule #### Helpers Array::remove = (object) -> @splice(@indexOf(object), 1) Array::clone = -> @[..] #### Export Funnel @Funnel = Funnel module?.exports = Funnel
154325
# # The Funnel Class # ---------------- # This is where the API and some of the setup for the rules live. class Funnel constructor: ( rules={} ) -> @_rules = {} rules.input = (arg) -> @emit arg for name, fn of rules rule = @rule(name, fn ) @[name] = ( args... ) -> rule.run( args ) @compile() return listen: ( fn ) => key = <KEY>Object.<KEY>(@_rules).<KEY> @rule(key, fn) @compile() # Allow other rules to register dependencies on: ( dependencies, rule ) -> [min,d] = [Infinity, undefined] for dependency in dependencies n = dependency.passes(dependencies) if n > -1 and n < min min = n d = dependency d.bind( rule ) if min > -1 and min < Infinity # Compile current set of rules compile: -> for name, rule of @_rules rule.clear() for name, rule of @_rules @on( rule.dependencies(), rule ) # Construct a new rule and pass it a reference to us rule: ( name, fn ) -> rule = new Rule( name, fn ) @_rules[name] = rule rule.constructor.f = @ return rule #### Helpers Array::remove = (object) -> @splice(@indexOf(object), 1) Array::clone = -> @[..] #### Export Funnel @Funnel = Funnel module?.exports = Funnel
true
# # The Funnel Class # ---------------- # This is where the API and some of the setup for the rules live. class Funnel constructor: ( rules={} ) -> @_rules = {} rules.input = (arg) -> @emit arg for name, fn of rules rule = @rule(name, fn ) @[name] = ( args... ) -> rule.run( args ) @compile() return listen: ( fn ) => key = PI:KEY:<KEY>END_PIObject.PI:KEY:<KEY>END_PI(@_rules).PI:KEY:<KEY>END_PI @rule(key, fn) @compile() # Allow other rules to register dependencies on: ( dependencies, rule ) -> [min,d] = [Infinity, undefined] for dependency in dependencies n = dependency.passes(dependencies) if n > -1 and n < min min = n d = dependency d.bind( rule ) if min > -1 and min < Infinity # Compile current set of rules compile: -> for name, rule of @_rules rule.clear() for name, rule of @_rules @on( rule.dependencies(), rule ) # Construct a new rule and pass it a reference to us rule: ( name, fn ) -> rule = new Rule( name, fn ) @_rules[name] = rule rule.constructor.f = @ return rule #### Helpers Array::remove = (object) -> @splice(@indexOf(object), 1) Array::clone = -> @[..] #### Export Funnel @Funnel = Funnel module?.exports = Funnel
[ { "context": " 'y'}\n results: [\n [{id: UUIDS[0], name: 'joe'}]\n ]\n .withOverrides ->\n exo = new Exoid(", "end": 1341, "score": 0.9996286630630493, "start": 1338, "tag": "NAME", "value": "joe" }, { "context": ">\n b users.length, 1\n b users[0].name, 'joe...
test/isomorphic.coffee
claydotio/exoid
0
require './polyfill' _isPlainObject = require 'lodash/isPlainObject' _keys = require 'lodash/keys' b = require 'b-assert' log = require 'loga' zock = require 'zock' stringify = require 'json-stable-stringify' request = require 'clay-request' Exoid = require '../src' ################################################################# # Exoid Protocol # # # request # { # requests: [ # {path: 'users', body: '123'} # {path: 'users.all', body: {x: 'y'}} # ] # } # # response # { # results: [ # {id: '123'} # [{id: '123'}] # ] # errors: [null, null] # } # # or with cache update / invalidation # { # results: [ # {id: '123'} # [{id: '123'}] # ] # cache: [ # {path: '321', result: {id: '321'}} # {path: '321'} # invalidate # {path: 'users.all', body: {x: 'y'}, result: [{id: '123'}]} NOT IMPLEMENTED # ] # } ################################################################### UUIDS = [ '2e6d9526-3df9-4179-b993-8de1029aea38' '60f752c3-4bdd-448a-a3c1-b18a55775daf' '97404ab5-40b4-4982-a596-218eb2457082' ] it 'fetches data from remote endpoint, returning a stream', -> zock .post 'http://x.com/exoid' .reply ({body}) -> b body.requests.length, 1 b body.requests[0].path, 'users.all' b body.requests[0].body, {x: 'y'} results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users.length, 1 b users[0].name, 'joe' it 'calls rpc on remote endpoint, returning a promise', -> zock .post 'http://x.com/exoid' .reply ({body}) -> b body.requests.length, 1 b body.requests[0].path, 'users.all' b body.requests[0].body, {x: 'y'} results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all', {x: 'y'} .then (users) -> b users.length, 1 b users[0].name, 'joe' it 'caches streams', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) stream1 = exo.stream 'users.all', {x: 'y'} stream2 = exo.stream 'users.all', {x: 'y'} b stream1, stream2 stream1.combineLatest(stream2).take(1).toPromise() .then -> exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' b requestCnt, 1 it 'doesnt cache calls', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all', {x: 'y'} .then -> exo.call 'users.all', {x: 'y'} .then (users) -> b users[0].name, 'joe' b requestCnt, 2 it 'batches requests', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'joe'}] [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) stream = exo.stream 'users.all', {x: 'y'} # Must be different or else it will batch into one request call = exo.call 'users.allAlso', {x: 'y'} stream.take(1).toPromise() .then -> call .then (users) -> b users[0].name, 'joe' b requestCnt, 1 it 'uses resource cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> requestCnt += 1 if body.requests[0].path is 'users' results: [ [{id: UUIDS[0], name: 'joe'}] {id: UUIDS[0], name: 'joe'} ] cache: [ {path: UUIDS[1], result: {id: UUIDS[1], name: 'fry'}} ] else if body.requests[0].path is 'users.adminify' results: [{id: UUIDS[2], name: 'admin'}] cache: [ {path: UUIDS[0], result: {id: UUIDS[0], name: 'joe-admin'}} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) # stream should update when a child ref is updated streamChildren = exo.stream 'users', {x: 'y'} # stream should update when path is updated streamUser = exo.stream 'users', UUIDS[0] streamChildren.combineLatest streamUser .take(1).toPromise() .then ([children, user]) -> b children[0].name, 'joe' b user.name, 'joe' b requestCnt, 1 .then -> exo.stream 'users.get', UUIDS[1] .take(1).toPromise() .then (fry) -> b requestCnt, 1 b fry.name, 'fry' .then -> exo.call 'users.adminify' .then (admin) -> b admin.name, 'admin' b requestCnt, 2 .then -> streamChildren.combineLatest streamUser .take(1).toPromise() .then ([children, user]) -> b children[0].name, 'joe-admin' b user.name, 'joe-admin' b requestCnt, 2 it 'invalidates resource, causing re-fetch of streams', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> requestCnt += 1 if body.requests[0].path is 'users' results: [ [{id: UUIDS[0], name: 'joe'}] ] else if body.requests[0].path is 'users.invalidate' results: [null] cache: [ {path: UUIDS[0]} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' b requestCnt, 1 .then -> exo.call 'users.invalidate' .then -> b requestCnt, 2 exo.stream 'users', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' b requestCnt, 3 # Note: if streaming errors are needed could add .streamErrors() it 'handles errors', -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] errors: [ {status: '400'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then -> throw new Error 'Expected error' , (err) -> b err instanceof Error b err.status, '400' .then -> zock .post 'http://x.com/exoid' .reply 401 .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then -> throw new Error 'error expected' , (err) -> b err instanceof Error b err.status, 401 it 'does not propagate errors to streams', -> zock .post 'http://x.com/exoid' .reply 401 .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) new Promise (resolve, reject) -> exo.stream 'users.all' .take(1).toPromise().then -> reject new Error 'Should not reject' setTimeout -> resolve null , 20 .then -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] errors: [ {status: '400'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) new Promise (resolve, reject) -> exo.stream 'users.all' .take(1).toPromise().then -> reject new Error 'Should not reject' setTimeout -> resolve null , 20 it 'expsoes cache stream', -> zock .post 'http://x.com/exoid' .reply -> results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) cache = exo.getCacheStream() cache.take(1).toPromise() .then (cache) -> b cache, {} .then -> exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then -> cache.take(1).toPromise() .then (cache) -> b _isPlainObject cache b _keys(cache).length, 2 .then -> exo.stream 'users.next' .take(1).toPromise() .then -> cache.take(1).toPromise() .then (cache) -> b _isPlainObject cache b _keys(cache).length, 3 it 'allows initializing from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: 'joe' } }) exo.stream 'users', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 0 b user.name, 'joe' it 'allows fetching values from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [null] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: 'joe' } }) exo.getCached 'users', UUIDS[0] .then (user) -> b requestCnt, 0 b user.name, 'joe' it 'watches refs when initialized from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 if requestCnt is 1 results: [ null ] cache: [ {path: UUIDS[0], result: {id: UUIDS[0], name: 'joe-changed-1'}} ] else results: [ {id: UUIDS[0], name: 'joe-changed-2'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: 'joe' } }) exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 0 b user.name, 'joe' exo.call 'users.mutate', UUIDS[0] .then (nulled) -> b nulled, null exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 1 b user.name, 'joe-changed-1' exo.call 'users.mutate', UUIDS[0] .then (user) -> b requestCnt, 2 b user.name, 'joe-changed-2' exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 2 b user.name, 'joe-changed-2' it 'allows custom fetch method to be passed in', -> exo = new Exoid({ api: 'http://x.com/exoid' fetch: (url, opts) -> Promise.resolve results: [ [{id: UUIDS[0], name: 'joe'}] ] }) exo.stream 'users' .take(1).toPromise() .then (users) -> b users.length, 1 b users[0].name, 'joe' it 'handles data races', -> # TODO - correctness unclear, currently last-write wins null it 'handles null results array', -> zock .post 'http://x.com/exoid' .reply -> results: [ [null] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, [null] it 'handles null results value', -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, null it 'handles non-resource results', -> zock .post 'http://x.com/exoid' .reply -> results: [ ['a', 'b', 'c'] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, ['a', 'b', 'c'] it 'enforces UUID ids', -> zock .post 'http://x.com/exoid' .reply -> results: [ [{id: 'NOT_UUID', name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) promise = new Promise (resolve) -> isResolved = false log.on 'error', (err) -> unless isResolved? b err.message, 'ids must be uuid' isResolved = true resolve() exo.call 'users.all', {x: 'y'} return promise it 'caches call responses', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply -> callCnt += 1 results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then (users) -> exo.stream 'users.all' .take(1).toPromise() .then (users) -> b callCnt, 1 b users.length, 1 b users[0].name, 'joe' it 'invalidates all cached data', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'jim'}] ] else results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' exo.invalidateAll() exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'jim' # TODO: improve tests around this it 'invalidates resource by id', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'jim'}] ] else results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' exo.invalidate(UUIDS[0]) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'jim' it 'updates resources', -> zock .post 'http://x.com/exoid' .reply ({body}) -> results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' exo.update({id: UUIDS[0], name: 'xxx'}) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'xxx' it 'invalidates resources by path', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'jim'}] ] else results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' exo.invalidate 'users.all' exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'jim' it 'invalidates resources by path and body', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'jim'}] ] else results: [ [{id: UUIDS[0], name: 'joe'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' exo.invalidate 'users.all', {x: 'NOT_Y'} exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'joe' exo.invalidate 'users.all', {x: 'y'} exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'jim'
62792
require './polyfill' _isPlainObject = require 'lodash/isPlainObject' _keys = require 'lodash/keys' b = require 'b-assert' log = require 'loga' zock = require 'zock' stringify = require 'json-stable-stringify' request = require 'clay-request' Exoid = require '../src' ################################################################# # Exoid Protocol # # # request # { # requests: [ # {path: 'users', body: '123'} # {path: 'users.all', body: {x: 'y'}} # ] # } # # response # { # results: [ # {id: '123'} # [{id: '123'}] # ] # errors: [null, null] # } # # or with cache update / invalidation # { # results: [ # {id: '123'} # [{id: '123'}] # ] # cache: [ # {path: '321', result: {id: '321'}} # {path: '321'} # invalidate # {path: 'users.all', body: {x: 'y'}, result: [{id: '123'}]} NOT IMPLEMENTED # ] # } ################################################################### UUIDS = [ '2e6d9526-3df9-4179-b993-8de1029aea38' '60f752c3-4bdd-448a-a3c1-b18a55775daf' '97404ab5-40b4-4982-a596-218eb2457082' ] it 'fetches data from remote endpoint, returning a stream', -> zock .post 'http://x.com/exoid' .reply ({body}) -> b body.requests.length, 1 b body.requests[0].path, 'users.all' b body.requests[0].body, {x: 'y'} results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users.length, 1 b users[0].name, '<NAME>' it 'calls rpc on remote endpoint, returning a promise', -> zock .post 'http://x.com/exoid' .reply ({body}) -> b body.requests.length, 1 b body.requests[0].path, 'users.all' b body.requests[0].body, {x: 'y'} results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all', {x: 'y'} .then (users) -> b users.length, 1 b users[0].name, '<NAME>' it 'caches streams', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) stream1 = exo.stream 'users.all', {x: 'y'} stream2 = exo.stream 'users.all', {x: 'y'} b stream1, stream2 stream1.combineLatest(stream2).take(1).toPromise() .then -> exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' b requestCnt, 1 it 'doesnt cache calls', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all', {x: 'y'} .then -> exo.call 'users.all', {x: 'y'} .then (users) -> b users[0].name, '<NAME>' b requestCnt, 2 it 'batches requests', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) stream = exo.stream 'users.all', {x: 'y'} # Must be different or else it will batch into one request call = exo.call 'users.allAlso', {x: 'y'} stream.take(1).toPromise() .then -> call .then (users) -> b users[0].name, '<NAME>' b requestCnt, 1 it 'uses resource cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> requestCnt += 1 if body.requests[0].path is 'users' results: [ [{id: UUIDS[0], name: '<NAME>'}] {id: UUIDS[0], name: '<NAME>'} ] cache: [ {path: UUIDS[1], result: {id: UUIDS[1], name: 'fry'}} ] else if body.requests[0].path is 'users.adminify' results: [{id: UUIDS[2], name: 'admin'}] cache: [ {path: UUIDS[0], result: {id: UUIDS[0], name: 'joe-admin'}} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) # stream should update when a child ref is updated streamChildren = exo.stream 'users', {x: 'y'} # stream should update when path is updated streamUser = exo.stream 'users', UUIDS[0] streamChildren.combineLatest streamUser .take(1).toPromise() .then ([children, user]) -> b children[0].name, 'jo<NAME>' b user.name, 'joe' b requestCnt, 1 .then -> exo.stream 'users.get', UUIDS[1] .take(1).toPromise() .then (fry) -> b requestCnt, 1 b fry.name, 'fry' .then -> exo.call 'users.adminify' .then (admin) -> b admin.name, 'admin' b requestCnt, 2 .then -> streamChildren.combineLatest streamUser .take(1).toPromise() .then ([children, user]) -> b children[0].name, 'joe-admin' b user.name, 'joe-admin' b requestCnt, 2 it 'invalidates resource, causing re-fetch of streams', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> requestCnt += 1 if body.requests[0].path is 'users' results: [ [{id: UUIDS[0], name: '<NAME>'}] ] else if body.requests[0].path is 'users.invalidate' results: [null] cache: [ {path: UUIDS[0]} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' b requestCnt, 1 .then -> exo.call 'users.invalidate' .then -> b requestCnt, 2 exo.stream 'users', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' b requestCnt, 3 # Note: if streaming errors are needed could add .streamErrors() it 'handles errors', -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] errors: [ {status: '400'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then -> throw new Error 'Expected error' , (err) -> b err instanceof Error b err.status, '400' .then -> zock .post 'http://x.com/exoid' .reply 401 .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then -> throw new Error 'error expected' , (err) -> b err instanceof Error b err.status, 401 it 'does not propagate errors to streams', -> zock .post 'http://x.com/exoid' .reply 401 .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) new Promise (resolve, reject) -> exo.stream 'users.all' .take(1).toPromise().then -> reject new Error 'Should not reject' setTimeout -> resolve null , 20 .then -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] errors: [ {status: '400'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) new Promise (resolve, reject) -> exo.stream 'users.all' .take(1).toPromise().then -> reject new Error 'Should not reject' setTimeout -> resolve null , 20 it 'expsoes cache stream', -> zock .post 'http://x.com/exoid' .reply -> results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) cache = exo.getCacheStream() cache.take(1).toPromise() .then (cache) -> b cache, {} .then -> exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then -> cache.take(1).toPromise() .then (cache) -> b _isPlainObject cache b _keys(cache).length, 2 .then -> exo.stream 'users.next' .take(1).toPromise() .then -> cache.take(1).toPromise() .then (cache) -> b _isPlainObject cache b _keys(cache).length, 3 it 'allows initializing from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: '<NAME>' } }) exo.stream 'users', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 0 b user.name, '<NAME>' it 'allows fetching values from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [null] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: '<NAME>' } }) exo.getCached 'users', UUIDS[0] .then (user) -> b requestCnt, 0 b user.name, '<NAME>' it 'watches refs when initialized from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 if requestCnt is 1 results: [ null ] cache: [ {path: UUIDS[0], result: {id: UUIDS[0], name: 'joe-changed-1'}} ] else results: [ {id: UUIDS[0], name: 'joe-changed-2'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: '<NAME>' } }) exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 0 b user.name, 'joe' exo.call 'users.mutate', UUIDS[0] .then (nulled) -> b nulled, null exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 1 b user.name, 'joe-changed-1' exo.call 'users.mutate', UUIDS[0] .then (user) -> b requestCnt, 2 b user.name, 'joe-changed-2' exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 2 b user.name, 'joe-changed-2' it 'allows custom fetch method to be passed in', -> exo = new Exoid({ api: 'http://x.com/exoid' fetch: (url, opts) -> Promise.resolve results: [ [{id: UUIDS[0], name: '<NAME>'}] ] }) exo.stream 'users' .take(1).toPromise() .then (users) -> b users.length, 1 b users[0].name, '<NAME>' it 'handles data races', -> # TODO - correctness unclear, currently last-write wins null it 'handles null results array', -> zock .post 'http://x.com/exoid' .reply -> results: [ [null] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, [null] it 'handles null results value', -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, null it 'handles non-resource results', -> zock .post 'http://x.com/exoid' .reply -> results: [ ['a', 'b', 'c'] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, ['a', 'b', 'c'] it 'enforces UUID ids', -> zock .post 'http://x.com/exoid' .reply -> results: [ [{id: 'NOT_UUID', name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) promise = new Promise (resolve) -> isResolved = false log.on 'error', (err) -> unless isResolved? b err.message, 'ids must be uuid' isResolved = true resolve() exo.call 'users.all', {x: 'y'} return promise it 'caches call responses', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply -> callCnt += 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then (users) -> exo.stream 'users.all' .take(1).toPromise() .then (users) -> b callCnt, 1 b users.length, 1 b users[0].name, '<NAME>' it 'invalidates all cached data', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] else results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' exo.invalidateAll() exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' # TODO: improve tests around this it 'invalidates resource by id', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] else results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' exo.invalidate(UUIDS[0]) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' it 'updates resources', -> zock .post 'http://x.com/exoid' .reply ({body}) -> results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' exo.update({id: UUIDS[0], name: 'xxx'}) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'xxx' it 'invalidates resources by path', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] else results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' exo.invalidate 'users.all' exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' it 'invalidates resources by path and body', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: '<NAME>'}] ] else results: [ [{id: UUIDS[0], name: '<NAME>'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' exo.invalidate 'users.all', {x: 'NOT_Y'} exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>' exo.invalidate 'users.all', {x: 'y'} exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, '<NAME>'
true
require './polyfill' _isPlainObject = require 'lodash/isPlainObject' _keys = require 'lodash/keys' b = require 'b-assert' log = require 'loga' zock = require 'zock' stringify = require 'json-stable-stringify' request = require 'clay-request' Exoid = require '../src' ################################################################# # Exoid Protocol # # # request # { # requests: [ # {path: 'users', body: '123'} # {path: 'users.all', body: {x: 'y'}} # ] # } # # response # { # results: [ # {id: '123'} # [{id: '123'}] # ] # errors: [null, null] # } # # or with cache update / invalidation # { # results: [ # {id: '123'} # [{id: '123'}] # ] # cache: [ # {path: '321', result: {id: '321'}} # {path: '321'} # invalidate # {path: 'users.all', body: {x: 'y'}, result: [{id: '123'}]} NOT IMPLEMENTED # ] # } ################################################################### UUIDS = [ '2e6d9526-3df9-4179-b993-8de1029aea38' '60f752c3-4bdd-448a-a3c1-b18a55775daf' '97404ab5-40b4-4982-a596-218eb2457082' ] it 'fetches data from remote endpoint, returning a stream', -> zock .post 'http://x.com/exoid' .reply ({body}) -> b body.requests.length, 1 b body.requests[0].path, 'users.all' b body.requests[0].body, {x: 'y'} results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users.length, 1 b users[0].name, 'PI:NAME:<NAME>END_PI' it 'calls rpc on remote endpoint, returning a promise', -> zock .post 'http://x.com/exoid' .reply ({body}) -> b body.requests.length, 1 b body.requests[0].path, 'users.all' b body.requests[0].body, {x: 'y'} results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all', {x: 'y'} .then (users) -> b users.length, 1 b users[0].name, 'PI:NAME:<NAME>END_PI' it 'caches streams', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) stream1 = exo.stream 'users.all', {x: 'y'} stream2 = exo.stream 'users.all', {x: 'y'} b stream1, stream2 stream1.combineLatest(stream2).take(1).toPromise() .then -> exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' b requestCnt, 1 it 'doesnt cache calls', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all', {x: 'y'} .then -> exo.call 'users.all', {x: 'y'} .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' b requestCnt, 2 it 'batches requests', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) stream = exo.stream 'users.all', {x: 'y'} # Must be different or else it will batch into one request call = exo.call 'users.allAlso', {x: 'y'} stream.take(1).toPromise() .then -> call .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' b requestCnt, 1 it 'uses resource cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> requestCnt += 1 if body.requests[0].path is 'users' results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] {id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'} ] cache: [ {path: UUIDS[1], result: {id: UUIDS[1], name: 'fry'}} ] else if body.requests[0].path is 'users.adminify' results: [{id: UUIDS[2], name: 'admin'}] cache: [ {path: UUIDS[0], result: {id: UUIDS[0], name: 'joe-admin'}} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) # stream should update when a child ref is updated streamChildren = exo.stream 'users', {x: 'y'} # stream should update when path is updated streamUser = exo.stream 'users', UUIDS[0] streamChildren.combineLatest streamUser .take(1).toPromise() .then ([children, user]) -> b children[0].name, 'joPI:NAME:<NAME>END_PI' b user.name, 'joe' b requestCnt, 1 .then -> exo.stream 'users.get', UUIDS[1] .take(1).toPromise() .then (fry) -> b requestCnt, 1 b fry.name, 'fry' .then -> exo.call 'users.adminify' .then (admin) -> b admin.name, 'admin' b requestCnt, 2 .then -> streamChildren.combineLatest streamUser .take(1).toPromise() .then ([children, user]) -> b children[0].name, 'joe-admin' b user.name, 'joe-admin' b requestCnt, 2 it 'invalidates resource, causing re-fetch of streams', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> requestCnt += 1 if body.requests[0].path is 'users' results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] else if body.requests[0].path is 'users.invalidate' results: [null] cache: [ {path: UUIDS[0]} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' b requestCnt, 1 .then -> exo.call 'users.invalidate' .then -> b requestCnt, 2 exo.stream 'users', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' b requestCnt, 3 # Note: if streaming errors are needed could add .streamErrors() it 'handles errors', -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] errors: [ {status: '400'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then -> throw new Error 'Expected error' , (err) -> b err instanceof Error b err.status, '400' .then -> zock .post 'http://x.com/exoid' .reply 401 .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then -> throw new Error 'error expected' , (err) -> b err instanceof Error b err.status, 401 it 'does not propagate errors to streams', -> zock .post 'http://x.com/exoid' .reply 401 .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) new Promise (resolve, reject) -> exo.stream 'users.all' .take(1).toPromise().then -> reject new Error 'Should not reject' setTimeout -> resolve null , 20 .then -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] errors: [ {status: '400'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) new Promise (resolve, reject) -> exo.stream 'users.all' .take(1).toPromise().then -> reject new Error 'Should not reject' setTimeout -> resolve null , 20 it 'expsoes cache stream', -> zock .post 'http://x.com/exoid' .reply -> results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) cache = exo.getCacheStream() cache.take(1).toPromise() .then (cache) -> b cache, {} .then -> exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then -> cache.take(1).toPromise() .then (cache) -> b _isPlainObject cache b _keys(cache).length, 2 .then -> exo.stream 'users.next' .take(1).toPromise() .then -> cache.take(1).toPromise() .then (cache) -> b _isPlainObject cache b _keys(cache).length, 3 it 'allows initializing from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: 'PI:NAME:<NAME>END_PI' } }) exo.stream 'users', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 0 b user.name, 'PI:NAME:<NAME>END_PI' it 'allows fetching values from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 results: [null] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: 'PI:NAME:<NAME>END_PI' } }) exo.getCached 'users', UUIDS[0] .then (user) -> b requestCnt, 0 b user.name, 'PI:NAME:<NAME>END_PI' it 'watches refs when initialized from cache', -> requestCnt = 0 zock .post 'http://x.com/exoid' .reply -> requestCnt += 1 if requestCnt is 1 results: [ null ] cache: [ {path: UUIDS[0], result: {id: UUIDS[0], name: 'joe-changed-1'}} ] else results: [ {id: UUIDS[0], name: 'joe-changed-2'} ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' cache: "#{stringify {path: 'users', body: UUIDS[0]}}": { id: UUIDS[0] name: 'PI:NAME:<NAME>END_PI' } }) exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 0 b user.name, 'joe' exo.call 'users.mutate', UUIDS[0] .then (nulled) -> b nulled, null exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 1 b user.name, 'joe-changed-1' exo.call 'users.mutate', UUIDS[0] .then (user) -> b requestCnt, 2 b user.name, 'joe-changed-2' exo.stream 'users.get', UUIDS[0] .take(1).toPromise() .then (user) -> b requestCnt, 2 b user.name, 'joe-changed-2' it 'allows custom fetch method to be passed in', -> exo = new Exoid({ api: 'http://x.com/exoid' fetch: (url, opts) -> Promise.resolve results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] }) exo.stream 'users' .take(1).toPromise() .then (users) -> b users.length, 1 b users[0].name, 'PI:NAME:<NAME>END_PI' it 'handles data races', -> # TODO - correctness unclear, currently last-write wins null it 'handles null results array', -> zock .post 'http://x.com/exoid' .reply -> results: [ [null] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, [null] it 'handles null results value', -> zock .post 'http://x.com/exoid' .reply -> results: [ null ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, null it 'handles non-resource results', -> zock .post 'http://x.com/exoid' .reply -> results: [ ['a', 'b', 'c'] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users, ['a', 'b', 'c'] it 'enforces UUID ids', -> zock .post 'http://x.com/exoid' .reply -> results: [ [{id: 'NOT_UUID', name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) promise = new Promise (resolve) -> isResolved = false log.on 'error', (err) -> unless isResolved? b err.message, 'ids must be uuid' isResolved = true resolve() exo.call 'users.all', {x: 'y'} return promise it 'caches call responses', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply -> callCnt += 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.call 'users.all' .then (users) -> exo.stream 'users.all' .take(1).toPromise() .then (users) -> b callCnt, 1 b users.length, 1 b users[0].name, 'PI:NAME:<NAME>END_PI' it 'invalidates all cached data', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] else results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' exo.invalidateAll() exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' # TODO: improve tests around this it 'invalidates resource by id', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] else results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' exo.invalidate(UUIDS[0]) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' it 'updates resources', -> zock .post 'http://x.com/exoid' .reply ({body}) -> results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' exo.update({id: UUIDS[0], name: 'xxx'}) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'xxx' it 'invalidates resources by path', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] else results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' exo.invalidate 'users.all' exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' it 'invalidates resources by path and body', -> callCnt = 0 zock .post 'http://x.com/exoid' .reply ({body}) -> callCnt += 1 if callCnt > 1 results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] else results: [ [{id: UUIDS[0], name: 'PI:NAME:<NAME>END_PI'}] ] .withOverrides -> exo = new Exoid({ api: 'http://x.com/exoid' }) exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' exo.invalidate 'users.all', {x: 'NOT_Y'} exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI' exo.invalidate 'users.all', {x: 'y'} exo.stream 'users.all', {x: 'y'} .take(1).toPromise() .then (users) -> b users[0].name, 'PI:NAME:<NAME>END_PI'
[ { "context": "out: 0\n headers: {}\n user: \"\"\n password: 0\n }\n\n _get = (type, url, options = {}) ->\n op", "end": 588, "score": 0.9923179149627686, "start": 587, "tag": "PASSWORD", "value": "0" } ]
src/util/xhrpromise.coffee
kimushu/rubic-chrome
1
# Pre dependencies # (none) ###* @class XhrPromise Promise-based XMLHttpRequest ### module.exports = class XhrPromise null @get: (url, options) -> return _get("text", url, options) @getAsText: (url, options) -> return _get("text", url, options) @getAsArrayBuffer: (url, options) -> return _get("arraybuffer", url, options) @getAsBlob: (url, options) -> return _get("blob", url, options) @getAsJSON: (url, options) -> return _get("json", url, options) DEFAULT_OPTIONS = { data: null timeout: 0 headers: {} user: "" password: 0 } _get = (type, url, options = {}) -> options.method = "GET" return _send(type, url, options) _send = (type, url, options = {}) -> for k, v of DEFAULT_OPTIONS options[k] = v unless options[k]? return new Promise((resolve, reject) -> xhr = new XMLHttpRequest() xhr.onload = -> resolve(xhr) xhr.onerror = -> error = Error(xhr.statusText) error.xhr = xhr reject(error) xhr.responseType = type xhr.timeout = options.timeout xhr.open(options.method, url, true, options.user, options.password) xhr.setRequestHeader(k, v) for k, v of options.headers xhr.send(options.data) ) # return new Promise() # Post dependencies # (none)
44008
# Pre dependencies # (none) ###* @class XhrPromise Promise-based XMLHttpRequest ### module.exports = class XhrPromise null @get: (url, options) -> return _get("text", url, options) @getAsText: (url, options) -> return _get("text", url, options) @getAsArrayBuffer: (url, options) -> return _get("arraybuffer", url, options) @getAsBlob: (url, options) -> return _get("blob", url, options) @getAsJSON: (url, options) -> return _get("json", url, options) DEFAULT_OPTIONS = { data: null timeout: 0 headers: {} user: "" password: <PASSWORD> } _get = (type, url, options = {}) -> options.method = "GET" return _send(type, url, options) _send = (type, url, options = {}) -> for k, v of DEFAULT_OPTIONS options[k] = v unless options[k]? return new Promise((resolve, reject) -> xhr = new XMLHttpRequest() xhr.onload = -> resolve(xhr) xhr.onerror = -> error = Error(xhr.statusText) error.xhr = xhr reject(error) xhr.responseType = type xhr.timeout = options.timeout xhr.open(options.method, url, true, options.user, options.password) xhr.setRequestHeader(k, v) for k, v of options.headers xhr.send(options.data) ) # return new Promise() # Post dependencies # (none)
true
# Pre dependencies # (none) ###* @class XhrPromise Promise-based XMLHttpRequest ### module.exports = class XhrPromise null @get: (url, options) -> return _get("text", url, options) @getAsText: (url, options) -> return _get("text", url, options) @getAsArrayBuffer: (url, options) -> return _get("arraybuffer", url, options) @getAsBlob: (url, options) -> return _get("blob", url, options) @getAsJSON: (url, options) -> return _get("json", url, options) DEFAULT_OPTIONS = { data: null timeout: 0 headers: {} user: "" password: PI:PASSWORD:<PASSWORD>END_PI } _get = (type, url, options = {}) -> options.method = "GET" return _send(type, url, options) _send = (type, url, options = {}) -> for k, v of DEFAULT_OPTIONS options[k] = v unless options[k]? return new Promise((resolve, reject) -> xhr = new XMLHttpRequest() xhr.onload = -> resolve(xhr) xhr.onerror = -> error = Error(xhr.statusText) error.xhr = xhr reject(error) xhr.responseType = type xhr.timeout = options.timeout xhr.open(options.method, url, true, options.user, options.password) xhr.setRequestHeader(k, v) for k, v of options.headers xhr.send(options.data) ) # return new Promise() # Post dependencies # (none)
[ { "context": "b8f14227b6e1f96\"\n name: \"New York\"\n reference: \"CoQBdAAAACZimk_9WwuhIeWFwtMeNqiAV2daRpsJ41qmyqgBQjVJiuokc6XecHVoogAisPTRLsOQNz0UOo2hfGM2I40TUkRNYveLwyiLX_EdSiFWUPNGBGkciwDInfQa7DCg2qdIkzKf5Q8YI_eCa8NbSTcJWxWTJk3cOUq4N82u3aDaGEMXEhCEDqVRiEBNj1FktOhIJ21XGhRhPghlJuXsUpx_cmTfrW34g9T8Pg\"\n ty...
src/mobile/apps/personalize/test/client/location.coffee
streamich/force
1
module.exports = address_components: [ long_name: "New York" short_name: "New York" types: ["locality", "political"] , long_name: "New York" short_name: "NY" types: ["administrative_area_level_1", "political"] , long_name: "United States" short_name: "US" types: ["country", "political"] ] adr_address: "<span class=\"locality\">New York</span>, <span class=\"region\">NY</span>, <span class=\"country-name\">USA</span>" formatted_address: "New York, NY, USA" geometry: location: lb: 40.7143528 mb: -74.0059731 lat: -> 40.7143528 lng: -> -74.0059731 viewport: ea: d: 40.496006 b: 40.91525559999999 fa: b: -74.2557349 d: -73.7002721 icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png" id: "7eae6a016a9c6f58e2044573fb8f14227b6e1f96" name: "New York" reference: "CoQBdAAAACZimk_9WwuhIeWFwtMeNqiAV2daRpsJ41qmyqgBQjVJiuokc6XecHVoogAisPTRLsOQNz0UOo2hfGM2I40TUkRNYveLwyiLX_EdSiFWUPNGBGkciwDInfQa7DCg2qdIkzKf5Q8YI_eCa8NbSTcJWxWTJk3cOUq4N82u3aDaGEMXEhCEDqVRiEBNj1FktOhIJ21XGhRhPghlJuXsUpx_cmTfrW34g9T8Pg" types: ["locality", "political"] url: "https://maps.google.com/maps/place?q=New+York&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62" vicinity: "New York" html_attributions: []
119926
module.exports = address_components: [ long_name: "New York" short_name: "New York" types: ["locality", "political"] , long_name: "New York" short_name: "NY" types: ["administrative_area_level_1", "political"] , long_name: "United States" short_name: "US" types: ["country", "political"] ] adr_address: "<span class=\"locality\">New York</span>, <span class=\"region\">NY</span>, <span class=\"country-name\">USA</span>" formatted_address: "New York, NY, USA" geometry: location: lb: 40.7143528 mb: -74.0059731 lat: -> 40.7143528 lng: -> -74.0059731 viewport: ea: d: 40.496006 b: 40.91525559999999 fa: b: -74.2557349 d: -73.7002721 icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png" id: "7eae6a016a9c6f58e2044573fb8f14227b6e1f96" name: "New York" reference: "<KEY>px_cmTfrW34g9T8Pg" types: ["locality", "political"] url: "https://maps.google.com/maps/place?q=New+York&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62" vicinity: "New York" html_attributions: []
true
module.exports = address_components: [ long_name: "New York" short_name: "New York" types: ["locality", "political"] , long_name: "New York" short_name: "NY" types: ["administrative_area_level_1", "political"] , long_name: "United States" short_name: "US" types: ["country", "political"] ] adr_address: "<span class=\"locality\">New York</span>, <span class=\"region\">NY</span>, <span class=\"country-name\">USA</span>" formatted_address: "New York, NY, USA" geometry: location: lb: 40.7143528 mb: -74.0059731 lat: -> 40.7143528 lng: -> -74.0059731 viewport: ea: d: 40.496006 b: 40.91525559999999 fa: b: -74.2557349 d: -73.7002721 icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png" id: "7eae6a016a9c6f58e2044573fb8f14227b6e1f96" name: "New York" reference: "PI:KEY:<KEY>END_PIpx_cmTfrW34g9T8Pg" types: ["locality", "political"] url: "https://maps.google.com/maps/place?q=New+York&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62" vicinity: "New York" html_attributions: []
[ { "context": "data\n friends = [\n {\n id: 0\n name: \"Scruff McGruff\"\n }\n {\n id: 1\n name: \"G.I. Joe\"\n ", "end": 263, "score": 0.9998565912246704, "start": 249, "tag": "NAME", "value": "Scruff McGruff" }, { "context": "uff McGruff\"\n }\n {...
app/js/services.coffee
henry74/ionic-angular-cordova-gulp-seed
1
### A simple example service that returns some data. ### angular.module("starter.services", []).factory "Friends", -> # Might use a resource here that returns a JSON array # Some fake testing data friends = [ { id: 0 name: "Scruff McGruff" } { id: 1 name: "G.I. Joe" } { id: 2 name: "Miss Frizzle" } { id: 3 name: "Ash Ketchum" } ] all: -> friends get: (friendId) -> # Simple index lookup friends[friendId]
160469
### A simple example service that returns some data. ### angular.module("starter.services", []).factory "Friends", -> # Might use a resource here that returns a JSON array # Some fake testing data friends = [ { id: 0 name: "<NAME>" } { id: 1 name: "<NAME>" } { id: 2 name: "<NAME>" } { id: 3 name: "<NAME>" } ] all: -> friends get: (friendId) -> # Simple index lookup friends[friendId]
true
### A simple example service that returns some data. ### angular.module("starter.services", []).factory "Friends", -> # Might use a resource here that returns a JSON array # Some fake testing data friends = [ { id: 0 name: "PI:NAME:<NAME>END_PI" } { id: 1 name: "PI:NAME:<NAME>END_PI" } { id: 2 name: "PI:NAME:<NAME>END_PI" } { id: 3 name: "PI:NAME:<NAME>END_PI" } ] all: -> friends get: (friendId) -> # Simple index lookup friends[friendId]
[ { "context": "\n# hubot uuid me - generate uuid\n#\n# Author:\n# mrinjamul <mrinjamul@gmail.com>\n\nchild_process = require 'c", "end": 172, "score": 0.9997321963310242, "start": 163, "tag": "USERNAME", "value": "mrinjamul" }, { "context": "uid me - generate uuid\n#\n# Author:\n#...
src/uuid.coffee
hew-bot/hubot-uuid
0
# Description: # Make hubot generate uuid # # Dependencies: # None # # Configuration: # None # # Commands: # hubot uuid me - generate uuid # # Author: # mrinjamul <mrinjamul@gmail.com> child_process = require 'child_process' module.exports = (robot) -> robot.respond /uuid( me)?/i, (msg) -> try child_process.exec 'uuid', (error, stdout, stderr) -> if error msg.send "can't compute: " + stderr else output = stdout+'' msg.send output catch error msg.send error+''
26955
# Description: # Make hubot generate uuid # # Dependencies: # None # # Configuration: # None # # Commands: # hubot uuid me - generate uuid # # Author: # mrinjamul <<EMAIL>> child_process = require 'child_process' module.exports = (robot) -> robot.respond /uuid( me)?/i, (msg) -> try child_process.exec 'uuid', (error, stdout, stderr) -> if error msg.send "can't compute: " + stderr else output = stdout+'' msg.send output catch error msg.send error+''
true
# Description: # Make hubot generate uuid # # Dependencies: # None # # Configuration: # None # # Commands: # hubot uuid me - generate uuid # # Author: # mrinjamul <PI:EMAIL:<EMAIL>END_PI> child_process = require 'child_process' module.exports = (robot) -> robot.respond /uuid( me)?/i, (msg) -> try child_process.exec 'uuid', (error, stdout, stderr) -> if error msg.send "can't compute: " + stderr else output = stdout+'' msg.send output catch error msg.send error+''
[ { "context": "anifest-plugin'\nbanner =\n banner: 'Copyright 2015 Thomas Yang http://thomas-yang.me/'\n entryOnly: true\n\npaths ", "end": 193, "score": 0.9993492960929871, "start": 182, "tag": "NAME", "value": "Thomas Yang" } ]
generators/app/templates/webpack.config.coffee
Hacker-YHJ/frontend-scaffold
5
webpack = require 'webpack' path = require 'path' nib = require 'nib' stylus = require 'stylus' ManifestPlugin = require 'webpack-manifest-plugin' banner = banner: 'Copyright 2015 Thomas Yang http://thomas-yang.me/' entryOnly: true paths = src: path.join(__dirname, 'src') dest: path.join(__dirname, 'dist') debugPlugins = [ new webpack.HotModuleReplacementPlugin() new webpack.BannerPlugin(banner) new webpack.LoaderOptionsPlugin({ debug: true }) ] productionPlugins = [ new ManifestPlugin() new webpack.BannerPlugin(banner) new webpack.optimize.UglifyJsPlugin({ warning: true minimize: true compress: true mangle: true }) ] baseOption = output: path: paths.dest resolve: # you can now require('file') instead of require('file.coffee') extensions: ['.js', '.json', '.coffee', '.css', '.styl'] module: rules: [ { test: /\.coffee$/ exclude: /node_modules/ use: 'coffee-loader' } { test: /\.styl$/ use: [ 'style-loader' 'css-loader' { loader: 'stylus-loader' options: use: [nib()] define: 'inline-url': stylus.url paths: [__dirname + '/src'] limit: false } ] } { test: /\.(eot|ttf|woff|otf|svg)$/ use: 'url?limit=100000' } ] makeEntry = (obj) -> throw Error 'no entry files' unless obj.entry?.length > 0 r = {} obj.entry.forEach (e) -> r[e] = ["#{paths.src}/coffee/#{e}.coffee"] if obj.isDebug hotServer = 'webpack/hot/dev-server' reloadServer = "webpack-dev-server/client?http://localhost:#{obj.port}" for k, v of r v.unshift reloadServer v.unshift hotServer r createOption = (obj = {}) -> throw Error 'specify how to build: debug or production' unless obj.build? obj.isDebug = obj.build isnt 'production' obj.port = obj.port || 5000 option = Object.create baseOption option.entry = makeEntry obj if obj.isDebug option.watch = true option.devtool = 'cheap-module-source-map' option.output.filename = '[name].js' option.plugins = debugPlugins else option.output.filename = '[name].[hash].js' option.plugins = productionPlugins option module.exports = createOption
87654
webpack = require 'webpack' path = require 'path' nib = require 'nib' stylus = require 'stylus' ManifestPlugin = require 'webpack-manifest-plugin' banner = banner: 'Copyright 2015 <NAME> http://thomas-yang.me/' entryOnly: true paths = src: path.join(__dirname, 'src') dest: path.join(__dirname, 'dist') debugPlugins = [ new webpack.HotModuleReplacementPlugin() new webpack.BannerPlugin(banner) new webpack.LoaderOptionsPlugin({ debug: true }) ] productionPlugins = [ new ManifestPlugin() new webpack.BannerPlugin(banner) new webpack.optimize.UglifyJsPlugin({ warning: true minimize: true compress: true mangle: true }) ] baseOption = output: path: paths.dest resolve: # you can now require('file') instead of require('file.coffee') extensions: ['.js', '.json', '.coffee', '.css', '.styl'] module: rules: [ { test: /\.coffee$/ exclude: /node_modules/ use: 'coffee-loader' } { test: /\.styl$/ use: [ 'style-loader' 'css-loader' { loader: 'stylus-loader' options: use: [nib()] define: 'inline-url': stylus.url paths: [__dirname + '/src'] limit: false } ] } { test: /\.(eot|ttf|woff|otf|svg)$/ use: 'url?limit=100000' } ] makeEntry = (obj) -> throw Error 'no entry files' unless obj.entry?.length > 0 r = {} obj.entry.forEach (e) -> r[e] = ["#{paths.src}/coffee/#{e}.coffee"] if obj.isDebug hotServer = 'webpack/hot/dev-server' reloadServer = "webpack-dev-server/client?http://localhost:#{obj.port}" for k, v of r v.unshift reloadServer v.unshift hotServer r createOption = (obj = {}) -> throw Error 'specify how to build: debug or production' unless obj.build? obj.isDebug = obj.build isnt 'production' obj.port = obj.port || 5000 option = Object.create baseOption option.entry = makeEntry obj if obj.isDebug option.watch = true option.devtool = 'cheap-module-source-map' option.output.filename = '[name].js' option.plugins = debugPlugins else option.output.filename = '[name].[hash].js' option.plugins = productionPlugins option module.exports = createOption
true
webpack = require 'webpack' path = require 'path' nib = require 'nib' stylus = require 'stylus' ManifestPlugin = require 'webpack-manifest-plugin' banner = banner: 'Copyright 2015 PI:NAME:<NAME>END_PI http://thomas-yang.me/' entryOnly: true paths = src: path.join(__dirname, 'src') dest: path.join(__dirname, 'dist') debugPlugins = [ new webpack.HotModuleReplacementPlugin() new webpack.BannerPlugin(banner) new webpack.LoaderOptionsPlugin({ debug: true }) ] productionPlugins = [ new ManifestPlugin() new webpack.BannerPlugin(banner) new webpack.optimize.UglifyJsPlugin({ warning: true minimize: true compress: true mangle: true }) ] baseOption = output: path: paths.dest resolve: # you can now require('file') instead of require('file.coffee') extensions: ['.js', '.json', '.coffee', '.css', '.styl'] module: rules: [ { test: /\.coffee$/ exclude: /node_modules/ use: 'coffee-loader' } { test: /\.styl$/ use: [ 'style-loader' 'css-loader' { loader: 'stylus-loader' options: use: [nib()] define: 'inline-url': stylus.url paths: [__dirname + '/src'] limit: false } ] } { test: /\.(eot|ttf|woff|otf|svg)$/ use: 'url?limit=100000' } ] makeEntry = (obj) -> throw Error 'no entry files' unless obj.entry?.length > 0 r = {} obj.entry.forEach (e) -> r[e] = ["#{paths.src}/coffee/#{e}.coffee"] if obj.isDebug hotServer = 'webpack/hot/dev-server' reloadServer = "webpack-dev-server/client?http://localhost:#{obj.port}" for k, v of r v.unshift reloadServer v.unshift hotServer r createOption = (obj = {}) -> throw Error 'specify how to build: debug or production' unless obj.build? obj.isDebug = obj.build isnt 'production' obj.port = obj.port || 5000 option = Object.create baseOption option.entry = makeEntry obj if obj.isDebug option.watch = true option.devtool = 'cheap-module-source-map' option.output.filename = '[name].js' option.plugins = debugPlugins else option.output.filename = '[name].[hash].js' option.plugins = productionPlugins option module.exports = createOption
[ { "context": " properties:\n username:\n title: 'Username'\n type: 'string'\n minLength: 3\n", "end": 341, "score": 0.7291635870933533, "start": 333, "tag": "USERNAME", "value": "Username" }, { "context": "equired: true\n password:\n ...
app/assets/javascripts/controllers/users/sign_up.coffee
zhoutong/coledger
1
angular.module("coledger").controller("SignUpController", ['$scope', '$window', '$location', 'Resources', 'flash' ($scope, $window, $location, Resources, flash) -> $scope.user = {} $scope.errorMessages = [] $scope.schema = type: 'object' title: 'User' properties: username: title: 'Username' type: 'string' minLength: 3 required: true password: title: 'Password' type: 'string' minLength: 6 required: true confirmPassword: title: 'Repeat Password' type: 'string' minLength: 6 required: true email: title: 'Email' type: 'string' required: true first_name: title: 'First Name' type: 'string' required: true last_name: title: 'Last Name' type: 'string' required: true $scope.form = [ 'username' { key: 'password', type: 'password' } { key: 'confirmPassword', type: 'password' } { key: 'email', type: 'email', validationMessage: "is not a valid email address" } { type: 'section', htmlClass: 'row', items: [ { type: 'section', htmlClass: 'col-sm-6', items: ['first_name'] } { type: 'section', htmlClass: 'col-sm-6', items: ['last_name'] } ] } { type: 'submit', style: 'btn btn-primary', title: 'Sign Up'} ] $scope.$watch("user.confirmPassword", (value) -> if (value != $scope.user.password) $scope.$broadcast('schemaForm.error.confirmPassword', 'matchPassword', "Passwords must match") else $scope.$broadcast('schemaForm.error.confirmPassword', 'matchPassword', true) ) $scope.submitForm = (form) -> $scope.$broadcast("schemaFormValidate") if (form.$valid) user = new Resources.User($scope.user) user.$save (success) -> session = new Resources.Session(username: $scope.user.username, password: $scope.user.password) session.$save (success) -> $window.sessionStorage.token = session.token flash.success = "You have successfully signed up to CoLedger!" $scope.$parent.refreshUser() $location.path("/") , (failure) -> if failure.data.error_code == "VALIDATION_ERROR" $scope.errorMessages = failure.data.errors ])
87224
angular.module("coledger").controller("SignUpController", ['$scope', '$window', '$location', 'Resources', 'flash' ($scope, $window, $location, Resources, flash) -> $scope.user = {} $scope.errorMessages = [] $scope.schema = type: 'object' title: 'User' properties: username: title: 'Username' type: 'string' minLength: 3 required: true password: title: '<PASSWORD>' type: 'string' minLength: 6 required: true confirmPassword: title: 'Repeat Password' type: 'string' minLength: 6 required: true email: title: 'Email' type: 'string' required: true first_name: title: 'First Name' type: 'string' required: true last_name: title: 'Last Name' type: 'string' required: true $scope.form = [ 'username' { key: '<PASSWORD>', type: 'password' } { key: 'confirmPassword', type: 'password' } { key: 'email', type: 'email', validationMessage: "is not a valid email address" } { type: 'section', htmlClass: 'row', items: [ { type: 'section', htmlClass: 'col-sm-6', items: ['first_name'] } { type: 'section', htmlClass: 'col-sm-6', items: ['last_name'] } ] } { type: 'submit', style: 'btn btn-primary', title: 'Sign Up'} ] $scope.$watch("user.confirmPassword", (value) -> if (value != $scope.user.password) $scope.$broadcast('schemaForm.error.confirmPassword', 'matchPassword', "Passwords must match") else $scope.$broadcast('schemaForm.error.confirmPassword', 'matchPassword', true) ) $scope.submitForm = (form) -> $scope.$broadcast("schemaFormValidate") if (form.$valid) user = new Resources.User($scope.user) user.$save (success) -> session = new Resources.Session(username: $scope.user.username, password: $scope.user.password) session.$save (success) -> $window.sessionStorage.token = session.token flash.success = "You have successfully signed up to CoLedger!" $scope.$parent.refreshUser() $location.path("/") , (failure) -> if failure.data.error_code == "VALIDATION_ERROR" $scope.errorMessages = failure.data.errors ])
true
angular.module("coledger").controller("SignUpController", ['$scope', '$window', '$location', 'Resources', 'flash' ($scope, $window, $location, Resources, flash) -> $scope.user = {} $scope.errorMessages = [] $scope.schema = type: 'object' title: 'User' properties: username: title: 'Username' type: 'string' minLength: 3 required: true password: title: 'PI:PASSWORD:<PASSWORD>END_PI' type: 'string' minLength: 6 required: true confirmPassword: title: 'Repeat Password' type: 'string' minLength: 6 required: true email: title: 'Email' type: 'string' required: true first_name: title: 'First Name' type: 'string' required: true last_name: title: 'Last Name' type: 'string' required: true $scope.form = [ 'username' { key: 'PI:PASSWORD:<PASSWORD>END_PI', type: 'password' } { key: 'confirmPassword', type: 'password' } { key: 'email', type: 'email', validationMessage: "is not a valid email address" } { type: 'section', htmlClass: 'row', items: [ { type: 'section', htmlClass: 'col-sm-6', items: ['first_name'] } { type: 'section', htmlClass: 'col-sm-6', items: ['last_name'] } ] } { type: 'submit', style: 'btn btn-primary', title: 'Sign Up'} ] $scope.$watch("user.confirmPassword", (value) -> if (value != $scope.user.password) $scope.$broadcast('schemaForm.error.confirmPassword', 'matchPassword', "Passwords must match") else $scope.$broadcast('schemaForm.error.confirmPassword', 'matchPassword', true) ) $scope.submitForm = (form) -> $scope.$broadcast("schemaFormValidate") if (form.$valid) user = new Resources.User($scope.user) user.$save (success) -> session = new Resources.Session(username: $scope.user.username, password: $scope.user.password) session.$save (success) -> $window.sessionStorage.token = session.token flash.success = "You have successfully signed up to CoLedger!" $scope.$parent.refreshUser() $location.path("/") , (failure) -> if failure.data.error_code == "VALIDATION_ERROR" $scope.errorMessages = failure.data.errors ])
[ { "context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The dot method partitions a space", "end": 163, "score": 0.9998728632926941, "start": 149, "tag": "NAME", "value": "Sherif Emabrak" } ]
src/lib/statistics/bin/dot.coffee
Sherif-Embarak/gp-test
0
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat Methods # Author | Sherif Emabrak # Description | The dot method partitions a space with an irregular mesh designed to cluster unidimensional data # ------------------------------------------------------------------------------ dot = () ->
134906
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat Methods # Author | <NAME> # Description | The dot method partitions a space with an irregular mesh designed to cluster unidimensional data # ------------------------------------------------------------------------------ dot = () ->
true
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat Methods # Author | PI:NAME:<NAME>END_PI # Description | The dot method partitions a space with an irregular mesh designed to cluster unidimensional data # ------------------------------------------------------------------------------ dot = () ->
[ { "context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ", "end": 194, "score": 0.999919593334198, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/controllers/software_update_ctrl.coffee
MakerButt/chaipcr
1
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.App.controller 'SoftwareUpdateCtrl', [ '$scope' '$uibModal' '$uibModalInstance' 'Device' '$window' '$state' 'Upload' '$timeout' '$interval' 'Status', ($scope, $uibModal, $uibModalInstance, Device, $window, $state, Upload, $timeout, $interval, Status ) -> uploadPromise = null _file = null if Device.direct_upload isnt true $scope.content = 'update_available' $scope.loading = true Device.getUpdateInfo().then (data) -> Status.fetch().then (resp) -> status = resp?.device?.update_available || 'unknown' # status = 'unknown' if status is 'available' delete data.image_http_url #remove image url so it wont display "download image" modal if data data.version = data.version || data.software_version $scope.new_update = data $scope.loading = false else $scope.content = 'upload_form' $scope.doUpdate = -> $scope.content = 'update_in_progress' Device.updateSoftware() Status.startUpdateSync() $timeout -> isUpInterval = $interval -> if Status.isUp() $scope.content = 'update_complete' $interval.cancel isUpInterval , 1000 , 60 * 1000 $scope.downloadUpdate = -> $window.open($scope.new_update.image_http_url) $scope.content = 'upload_form' $scope.done = -> $window.location.reload() $scope.close = -> if $scope.uploading $scope.cancelUpload() $uibModalInstance.close() $scope.imageSelected = (file) -> return if !file _file = file $scope.upload_error = false _filename = file.name name_length = 30 if file.name.length > name_length ext_index = _filename.lastIndexOf('.') ext = _filename.substring(ext_index, _filename.length) _filename = _filename.substring(0, name_length-ext.length-2)+'..'+ext $scope.file = name: _filename $scope.doUpload = -> return if !$scope.file return if $scope.uploading #Status.startUpdateSync() errorCB = (err) -> $scope.upload_error = err?.status?.error || 'An error occured while uploading software image. Please try again.' $scope.uploading = false progressCB = (evt) -> $scope.percent_upload = parseInt(100.0 * evt.loaded / evt.total); successCB = -> $scope.content = 'update_in_progress' Status.startUpdateSync() $timeout -> isUpInterval = $interval -> if Status.isUp() $scope.content = 'update_complete' $interval.cancel isUpInterval , 1000 , 60 * 1000 $scope.uploading = true $scope.percent_upload = 0; uploadPromise = Device.uploadImage(_file) .success(successCB) .error( errorCB) .progress( progressCB) .xhr (xhr) -> $scope.cancelUpload = -> xhr.abort() uploadPromise = null _file = null $scope.file = null $scope.uploading = false ]
85729
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.App.controller 'SoftwareUpdateCtrl', [ '$scope' '$uibModal' '$uibModalInstance' 'Device' '$window' '$state' 'Upload' '$timeout' '$interval' 'Status', ($scope, $uibModal, $uibModalInstance, Device, $window, $state, Upload, $timeout, $interval, Status ) -> uploadPromise = null _file = null if Device.direct_upload isnt true $scope.content = 'update_available' $scope.loading = true Device.getUpdateInfo().then (data) -> Status.fetch().then (resp) -> status = resp?.device?.update_available || 'unknown' # status = 'unknown' if status is 'available' delete data.image_http_url #remove image url so it wont display "download image" modal if data data.version = data.version || data.software_version $scope.new_update = data $scope.loading = false else $scope.content = 'upload_form' $scope.doUpdate = -> $scope.content = 'update_in_progress' Device.updateSoftware() Status.startUpdateSync() $timeout -> isUpInterval = $interval -> if Status.isUp() $scope.content = 'update_complete' $interval.cancel isUpInterval , 1000 , 60 * 1000 $scope.downloadUpdate = -> $window.open($scope.new_update.image_http_url) $scope.content = 'upload_form' $scope.done = -> $window.location.reload() $scope.close = -> if $scope.uploading $scope.cancelUpload() $uibModalInstance.close() $scope.imageSelected = (file) -> return if !file _file = file $scope.upload_error = false _filename = file.name name_length = 30 if file.name.length > name_length ext_index = _filename.lastIndexOf('.') ext = _filename.substring(ext_index, _filename.length) _filename = _filename.substring(0, name_length-ext.length-2)+'..'+ext $scope.file = name: _filename $scope.doUpload = -> return if !$scope.file return if $scope.uploading #Status.startUpdateSync() errorCB = (err) -> $scope.upload_error = err?.status?.error || 'An error occured while uploading software image. Please try again.' $scope.uploading = false progressCB = (evt) -> $scope.percent_upload = parseInt(100.0 * evt.loaded / evt.total); successCB = -> $scope.content = 'update_in_progress' Status.startUpdateSync() $timeout -> isUpInterval = $interval -> if Status.isUp() $scope.content = 'update_complete' $interval.cancel isUpInterval , 1000 , 60 * 1000 $scope.uploading = true $scope.percent_upload = 0; uploadPromise = Device.uploadImage(_file) .success(successCB) .error( errorCB) .progress( progressCB) .xhr (xhr) -> $scope.cancelUpload = -> xhr.abort() uploadPromise = null _file = null $scope.file = null $scope.uploading = false ]
true
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.App.controller 'SoftwareUpdateCtrl', [ '$scope' '$uibModal' '$uibModalInstance' 'Device' '$window' '$state' 'Upload' '$timeout' '$interval' 'Status', ($scope, $uibModal, $uibModalInstance, Device, $window, $state, Upload, $timeout, $interval, Status ) -> uploadPromise = null _file = null if Device.direct_upload isnt true $scope.content = 'update_available' $scope.loading = true Device.getUpdateInfo().then (data) -> Status.fetch().then (resp) -> status = resp?.device?.update_available || 'unknown' # status = 'unknown' if status is 'available' delete data.image_http_url #remove image url so it wont display "download image" modal if data data.version = data.version || data.software_version $scope.new_update = data $scope.loading = false else $scope.content = 'upload_form' $scope.doUpdate = -> $scope.content = 'update_in_progress' Device.updateSoftware() Status.startUpdateSync() $timeout -> isUpInterval = $interval -> if Status.isUp() $scope.content = 'update_complete' $interval.cancel isUpInterval , 1000 , 60 * 1000 $scope.downloadUpdate = -> $window.open($scope.new_update.image_http_url) $scope.content = 'upload_form' $scope.done = -> $window.location.reload() $scope.close = -> if $scope.uploading $scope.cancelUpload() $uibModalInstance.close() $scope.imageSelected = (file) -> return if !file _file = file $scope.upload_error = false _filename = file.name name_length = 30 if file.name.length > name_length ext_index = _filename.lastIndexOf('.') ext = _filename.substring(ext_index, _filename.length) _filename = _filename.substring(0, name_length-ext.length-2)+'..'+ext $scope.file = name: _filename $scope.doUpload = -> return if !$scope.file return if $scope.uploading #Status.startUpdateSync() errorCB = (err) -> $scope.upload_error = err?.status?.error || 'An error occured while uploading software image. Please try again.' $scope.uploading = false progressCB = (evt) -> $scope.percent_upload = parseInt(100.0 * evt.loaded / evt.total); successCB = -> $scope.content = 'update_in_progress' Status.startUpdateSync() $timeout -> isUpInterval = $interval -> if Status.isUp() $scope.content = 'update_complete' $interval.cancel isUpInterval , 1000 , 60 * 1000 $scope.uploading = true $scope.percent_upload = 0; uploadPromise = Device.uploadImage(_file) .success(successCB) .error( errorCB) .progress( progressCB) .xhr (xhr) -> $scope.cancelUpload = -> xhr.abort() uploadPromise = null _file = null $scope.file = null $scope.uploading = false ]
[ { "context": " the dom element too\n\t\t\t# See: https://github.com/koenbok/Framer/issues/63\n\t\t\t@_element.setAttribute(\"name\"", "end": 16781, "score": 0.999685525894165, "start": 16774, "tag": "USERNAME", "value": "koenbok" }, { "context": "WKUQZGwfhjB3OOHcw5djDn2MH6fBNLC42yaEn...
framer/Layer.coffee
ig-la/Framer
3,817
{_} = require "./Underscore" Utils = require "./Utils" {Config} = require "./Config" {Events} = require "./Events" {Defaults} = require "./Defaults" {BaseClass} = require "./BaseClass" {EventEmitter} = require "./EventEmitter" {Color} = require "./Color" {Gradient} = require "./Gradient" {Matrix} = require "./Matrix" {Animation} = require "./Animation" {LayerStyle} = require "./LayerStyle" {LayerStates} = require "./LayerStates" {LayerDraggable} = require "./LayerDraggable" {LayerPinchable} = require "./LayerPinchable" {Gestures} = require "./Gestures" {LayerPropertyProxy} = require "./LayerPropertyProxy" NoCacheDateKey = Date.now() delayedStyles = ["webkitTransform", "webkitFilter", "webkitPerspectiveOrigin", "webkitTransformOrigin", "webkitBackdropFilter"] layerValueTypeError = (name, value) -> throw new Error("Layer.#{name}: value '#{value}' of type '#{typeof(value)}' is not valid") layerProperty = (obj, name, cssProperty, fallback, validator, transformer, options={}, set, targetElement, includeMainElement, useSubpropertyProxy) -> result = default: fallback get: -> # console.log "Layer.#{name}.get #{@_properties[name]}", @_properties.hasOwnProperty(name) value = @_properties[name] if @_properties.hasOwnProperty(name) value ?= fallback return layerProxiedValue(value, @, name) if useSubpropertyProxy return value set: (value) -> # console.log "#{@constructor.name}.#{name}.set #{value} current:#{@[name]}", targetElement # Convert the value value = transformer(value, @, name) if transformer oldValue = @_properties[name] # Return unless we get a new value return if value is oldValue if value and validator and not validator(value) layerValueTypeError(name, value) @_properties[name] = value if cssProperty isnt null elementContainer = @ if cssProperty in @_stylesAppliedToParent elementContainer = @_parent @_parent._properties[name] = fallback mainElement = elementContainer._element if includeMainElement or not targetElement subElement = elementContainer[targetElement] if targetElement? if name is cssProperty and not LayerStyle[cssProperty]? mainElement?.style[cssProperty] = @_properties[name] subElement?.style[cssProperty] = @_properties[name] # These values are set multiple times during applyDefaults, so ignore them here, and set the style in the constructor else if not @__applyingDefaults or (cssProperty not in delayedStyles) style = LayerStyle[cssProperty](@) mainElement?.style[cssProperty] = style subElement?.style[cssProperty] = style set?(@, value) # We try to not send any events while we run the constructor, it just # doesn't make sense, because no one can listen to use yet. return if @__constructor @emit("change:#{name}", value, oldValue) @emit("change:point", value) if name in ["x", "y"] @emit("change:size", value) if name in ["width", "height"] @emit("change:frame", value) if name in ["x", "y", "width", "height"] @emit("change:rotation", value) if name in ["rotationZ"] result = _.extend(result, options) exports.layerProperty = layerProperty # Use this to wrap property values in a Proxy so setting sub-properties # will also trigger updates on the layer. # Because we’re not fully on ES6, we can’t use Proxy, so use our own wrapper. layerProxiedValue = (value, layer, property) -> return value unless _.isObject(value) new LayerPropertyProxy value, (proxiedValue, subProperty, subValue) -> proxiedValue[subProperty] = subValue layer[property] = proxiedValue exports.layerProxiedValue = layerProxiedValue layerPropertyPointTransformer = (value, layer, property) -> if _.isFunction(value) value = value(layer, property) return value layerPropertyIgnore = (options, propertyName, properties) -> return options unless options.hasOwnProperty(propertyName) for p in properties if options.hasOwnProperty(p) delete options[propertyName] return options return options asBorderRadius = (value) -> return value if _.isNumber(value) if _.isString(value) if not _.endsWith(value, "%") console.error "Layer.borderRadius only correctly supports percentages in strings" return value return 0 if not _.isObject(value) result = {} isValidObject = false for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"] isValidObject ||= _.has(value, key) result[key] = value[key] ? 0 return if not isValidObject then 0 else result asBorderWidth = (value) -> return value if _.isNumber(value) return 0 if not _.isObject(value) result = {} isValidObject = false for key in ["left", "right", "bottom", "top"] isValidObject ||= _.has(value, key) result[key] = value[key] ? 0 return if not isValidObject then 0 else result parentOrContext = (layerOrContext) -> if layerOrContext.parent? return layerOrContext.parent else return layerOrContext.context proxiedShadowValue = (layer, value, index = 0) -> v = _.defaults _.clone(value), Framer.Defaults.Shadow if v.color isnt null v?.color = new Color(v.color) layerProxiedValue(v, layer, "shadow#{index+1}") class exports.Layer extends BaseClass constructor: (options={}) -> # Make sure we never call the constructor twice throw Error("Layer.constructor #{@toInspect()} called twice") if @__constructorCalled @__constructorCalled = true @__constructor = true # Set needed private variables @_properties = {} @_style = {} @_children = [] @_stylesAppliedToParent ?= [] # Special power setting for 2d rendering path. Only enable this # if you know what you are doing. See LayerStyle for more info. @_prefer2d = false @_alwaysUseImageCache = false # Private setting for canceling of click event if wrapped in moved draggable @_cancelClickEventInDragSession = true # We have to create the element before we set the defaults @_createElement() if options.createHTMLElement @_createHTMLElementIfNeeded() # Create border element @_createBorderElement() # Sanitize calculated property setters so direct properties always win layerPropertyIgnore(options, "point", ["x", "y"]) layerPropertyIgnore(options, "midPoint", ["midX", "midY"]) layerPropertyIgnore(options, "size", ["width", "height"]) layerPropertyIgnore(options, "frame", ["x", "y", "width", "height"]) # Backwards compatibility for superLayer if not options.hasOwnProperty("parent") and options.hasOwnProperty("superLayer") options.parent = options.superLayer delete options.superLayer @__applyingDefaults = true super Defaults.getDefaults("Layer", options) delete @__applyingDefaults for cssProperty in delayedStyles element = @_element if cssProperty in @_stylesAppliedToParent element = @_parent._element element.style[cssProperty] = LayerStyle[cssProperty](@) # Add this layer to the current context @_context.addLayer(@) @_id = @_context.layerCounter # Insert the layer into the dom or the parent element if not options.parent @_insertElement() if not options.shadow else @parent = options.parent # Set some calculated properties # Make sure we set the right index if options.hasOwnProperty("index") @index = options.index # x and y always win from point, frame or size for p in ["x", "y", "width", "height"] if options.hasOwnProperty(p) @[p] = options[p] @_context.emit("layer:create", @) # Make sure the layer is always centered @label = @label delete @__constructor @updateShadowStyle() @onChange("size", @updateForSizeChange) @ExistingIdMessage: (type, id) -> "Can not set #{type}: There's already an element with id '#{id}' in this document'" ############################################################## # Properties # Readonly context property @define "context", get: -> @_context @define "label", get: -> @_label set: (value) -> return if value is @_label @_label = value Utils.labelLayer(@, @_label) # A placeholder for layer bound properties defined by the user: @define "custom", @simpleProperty("custom", undefined) # Default animation options for every animation of this layer @define "animationOptions", @simpleProperty("animationOptions", {}) # Behaviour properties @define "ignoreEvents", layerProperty(@, "ignoreEvents", "pointerEvents", true, _.isBoolean) # Css properties @define "width", layerProperty(@, "width", "width", 100, _.isNumber, null, {}, (layer, value) -> return if not layer.constraintValues? or layer.isLayouting layer.constraintValues.width = value layer.constraintValues.aspectRatioLocked = false layer.constraintValues.widthFactor = null layer._layoutX() ) @define "height", layerProperty(@, "height", "height", 100, _.isNumber, null, {}, (layer, value) -> return if not layer.constraintValues? or layer.isLayouting layer.constraintValues.height = value layer.constraintValues.aspectRatioLocked = false layer.constraintValues.heightFactor = null layer._layoutY() ) @define "visible", layerProperty(@, "visible", "display", true, _.isBoolean) @define "opacity", layerProperty(@, "opacity", "opacity", 1, _.isNumber, parseFloat) @define "index", layerProperty(@, "index", "zIndex", 0, _.isNumber, null, {importable: false, exportable: false}) @define "clip", layerProperty(@, "clip", "overflow", false, _.isBoolean, null, {}, null, "_elementHTML", true) @define "scrollHorizontal", layerProperty @, "scrollHorizontal", "overflowX", false, _.isBoolean, null, {}, (layer, value) -> layer.ignoreEvents = false if value is true @define "scrollVertical", layerProperty @, "scrollVertical", "overflowY", false, _.isBoolean, null, {}, (layer, value) -> layer.ignoreEvents = false if value is true @define "scroll", get: -> @scrollHorizontal is true or @scrollVertical is true set: (value) -> @scrollHorizontal = @scrollVertical = value # Matrix properties @define "x", layerProperty(@, "x", "webkitTransform", 0, _.isNumber, layerPropertyPointTransformer, {depends: ["width", "height"]}, (layer) -> return if layer.isLayouting layer.constraintValues = null ) @define "y", layerProperty(@, "y", "webkitTransform", 0, _.isNumber, layerPropertyPointTransformer, {depends: ["width", "height"]}, (layer) -> return if layer.isLayouting layer.constraintValues = null ) @define "z", layerProperty(@, "z", "webkitTransform", 0, _.isNumber) @define "scaleX", layerProperty(@, "scaleX", "webkitTransform", 1, _.isNumber) @define "scaleY", layerProperty(@, "scaleY", "webkitTransform", 1, _.isNumber) @define "scaleZ", layerProperty(@, "scaleZ", "webkitTransform", 1, _.isNumber) @define "scale", layerProperty(@, "scale", "webkitTransform", 1, _.isNumber) @define "skewX", layerProperty(@, "skewX", "webkitTransform", 0, _.isNumber) @define "skewY", layerProperty(@, "skewY", "webkitTransform", 0, _.isNumber) @define "skew", layerProperty(@, "skew", "webkitTransform", 0, _.isNumber) # @define "scale", # get: -> (@scaleX + @scaleY + @scaleZ) / 3.0 # set: (value) -> @scaleX = @scaleY = @scaleZ = value @define "originX", layerProperty(@, "originX", "webkitTransformOrigin", 0.5, _.isNumber) @define "originY", layerProperty(@, "originY", "webkitTransformOrigin", 0.5, _.isNumber) @define "originZ", layerProperty(@, "originZ", null, 0, _.isNumber) @define "perspective", layerProperty(@, "perspective", "webkitPerspective", 0, ((v) -> Utils.webkitPerspectiveForValue(v) isnt null)) @define "perspectiveOriginX", layerProperty(@, "perspectiveOriginX", "webkitPerspectiveOrigin", 0.5, _.isNumber) @define "perspectiveOriginY", layerProperty(@, "perspectiveOriginY", "webkitPerspectiveOrigin", 0.5, _.isNumber) @define "rotationX", layerProperty(@, "rotationX", "webkitTransform", 0, _.isNumber) @define "rotationY", layerProperty(@, "rotationY", "webkitTransform", 0, _.isNumber) @define "rotationZ", layerProperty(@, "rotationZ", "webkitTransform", 0, _.isNumber) @define "rotation", #exportable: false get: -> @rotationZ set: (value) -> @rotationZ = value # Filter properties @define "blur", layerProperty(@, "blur", "webkitFilter", 0, _.isNumber) @define "brightness", layerProperty(@, "brightness", "webkitFilter", 100, _.isNumber) @define "saturate", layerProperty(@, "saturate", "webkitFilter", 100, _.isNumber) @define "hueRotate", layerProperty(@, "hueRotate", "webkitFilter", 0, _.isNumber) @define "contrast", layerProperty(@, "contrast", "webkitFilter", 100, _.isNumber) @define "invert", layerProperty(@, "invert", "webkitFilter", 0, _.isNumber) @define "grayscale", layerProperty(@, "grayscale", "webkitFilter", 0, _.isNumber) @define "sepia", layerProperty(@, "sepia", "webkitFilter", 0, _.isNumber) @define "blending", layerProperty(@, "blending", "mixBlendMode", null, _.isString) @define "backgroundBlur", layerProperty(@, "backgroundBlur", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundBrightness", layerProperty(@, "backgroundBrightness", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundSaturate", layerProperty(@, "backgroundSaturate", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundHueRotate", layerProperty(@, "backgroundHueRotate", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundContrast", layerProperty(@, "backgroundContrast", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundInvert", layerProperty(@, "backgroundInvert", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundGrayscale", layerProperty(@, "backgroundGrayscale", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundSepia", layerProperty(@, "backgroundSepia", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundSize", layerProperty(@, "backgroundSize", "backgroundSize", "fill", _.isString) for i in [0..8] do (i) => @define "shadow#{i+1}", exportable: false depends: ["shadowX", "shadowY", "shadowBlur", "shadowSpread", "shadowColor", "shadowType"] get: -> @shadows ?= [] @shadows[i] ?= proxiedShadowValue(@, {}, i) @shadows[i] set: (value) -> @shadows ?= [] @shadows[i] = proxiedShadowValue(@, value, i) @updateShadowStyle() updateShadowsProperty: (prop, value) -> @shadows ?= [] if (@shadows.filter (s) -> s isnt null).length is 0 @shadows[0] = proxiedShadowValue(@, Framer.Defaults.Shadow) for shadow in @shadows shadow?[prop] = value @updateShadowStyle() # Shadow properties for shadowProp in ["X", "Y", "Blur", "Spread", "Color", "Type"] do (shadowProp) => @define "shadow#{shadowProp}", get: -> return null if not @shadows? or @shadows.length is 0 @shadows[0][shadowProp.toLowerCase()] set: (value) -> @updateShadowsProperty(shadowProp.toLowerCase(), value) @define "shadows", default: null get: -> @_getPropertyValue("shadows") set: (value) -> value ?= [] shadows = [] for shadow, index in value if shadow is null shadows.push null else shadows.push proxiedShadowValue(@, shadow, index) @_setPropertyValue("shadows", shadows) @updateShadowStyle() updateShadowStyle: -> return if @__constructor @_element.style.boxShadow = LayerStyle["boxShadow"](@) @_element.style.textShadow = LayerStyle["textShadow"](@) @_element.style.webkitFilter = LayerStyle["webkitFilter"](@) # Color properties @define "backgroundColor", layerProperty(@, "backgroundColor", "backgroundColor", null, Color.validColorValue, Color.toColor) @define "color", layerProperty(@, "color", "color", null, Color.validColorValue, Color.toColor, null, null, "_elementHTML", true) # Border properties @define "borderRadius", layerProperty(@, "borderRadius", "borderRadius", 0, null, asBorderRadius, null, null, "_elementBorder", true, true) @define "borderColor", layerProperty(@, "borderColor", "borderColor", null, Color.validColorValue, Color.toColor, null, null, "_elementBorder") @define "borderWidth", layerProperty(@, "borderWidth", "borderWidth", 0, null, asBorderWidth, null, null, "_elementBorder", false, true) @define "borderStyle", layerProperty(@, "borderStyle", "borderStyle", "solid", _.isString, null, null, null, "_elementBorder") @define "force2d", layerProperty(@, "force2d", "webkitTransform", false, _.isBoolean) @define "flat", layerProperty(@, "flat", "webkitTransformStyle", false, _.isBoolean) @define "backfaceVisible", layerProperty(@, "backfaceVisible", "webkitBackfaceVisibility", true, _.isBoolean) ############################################################## # Identity @define "name", default: "" get: -> name = @_getPropertyValue("name") return if name? then "#{name}" else "" set: (value) -> @_setPropertyValue("name", value) # Set the name attribute of the dom element too # See: https://github.com/koenbok/Framer/issues/63 @_element.setAttribute("name", value) ############################################################## # Matrices # matrix of layer transforms @define "matrix", get: -> if @force2d return @_matrix2d return Matrix.identity3d() .translate(@x, @y, @z) .scale(@scale) .scale(@scaleX, @scaleY, @scaleZ) .skew(@skew) .skewX(@skewX) .skewY(@skewY) .translate(0, 0, @originZ) .rotate(@rotationX, 0, 0) .rotate(0, @rotationY, 0) .rotate(0, 0, @rotationZ) .translate(0, 0, -@originZ) # matrix of layer transforms when 2d is forced @define "_matrix2d", get: -> return Matrix.identity3d() .translate(@x, @y) .scale(@scale) .scale(@scaleX, @scaleY) .skewX(@skew) .skewY(@skew) .rotate(0, 0, @rotationZ) # matrix of layer transforms with transform origin applied @define "transformMatrix", get: -> return Matrix.identity3d() .translate(@originX * @width, @originY * @height) .multiply(@matrix) .translate(-@originX * @width, -@originY * @height) # matrix of layer transforms with perspective applied @define "matrix3d", get: -> parent = @parent or @context ppm = Utils.perspectiveMatrix(parent) return Matrix.identity3d() .multiply(ppm) .multiply(@transformMatrix) ############################################################## # Border radius compatibility # Because it should be cornerRadius, we alias it here @define "cornerRadius", importable: false exportable: false # exportable: no get: -> @borderRadius set: (value) -> @borderRadius = value ############################################################## # Geometry _setGeometryValues: (input, keys) -> # If this is a number, we set everything to that number if _.isNumber(input) for k in keys if @[k] isnt input @[k] = input else # If there is nothing to work with we exit return unless input # Set every numeric value for eacht key for k in keys if _.isNumber(input[k]) and @[k] isnt input[k] @[k] = input[k] @define "point", importable: true exportable: false depends: ["width", "height", "size", "parent"] get: -> Utils.point(@) set: (input) -> input = layerPropertyPointTransformer(input, @, "point") @_setGeometryValues(input, ["x", "y"]) @define "midPoint", importable: true exportable: false depends: ["width", "height", "size", "parent", "point"] get: -> x: @midX y: @midY set: (input) -> input = layerPropertyPointTransformer(input, @, "midPoint") if not _.isNumber input input = _.pick(input, ["x", "y", "midX", "midY"]) if input.x? and not input.midX? input.midX = input.x delete input.x if input.y? and not input.midY? input.midY = input.y delete input.y @_setGeometryValues(input, ["midX", "midY"]) @define "size", importable: true exportable: false get: -> Utils.size(@) set: (input) -> @_setGeometryValues(input, ["width", "height"]) @define "frame", importable: true exportable: false get: -> Utils.frame(@) set: (input) -> @_setGeometryValues(input, ["x", "y", "width", "height"]) @define "minX", importable: true exportable: false get: -> @x set: (value) -> @x = value @define "midX", importable: true exportable: false get: -> Utils.frameGetMidX @ set: (value) -> Utils.frameSetMidX @, value @define "maxX", importable: true exportable: false get: -> Utils.frameGetMaxX @ set: (value) -> Utils.frameSetMaxX @, value @define "minY", importable: true exportable: false get: -> @y set: (value) -> @y = value @define "midY", importable: true exportable: false get: -> Utils.frameGetMidY @ set: (value) -> Utils.frameSetMidY @, value @define "maxY", importable: true exportable: false get: -> Utils.frameGetMaxY @ set: (value) -> Utils.frameSetMaxY @, value @define "constraintValues", importable: true exportable: false default: null get: -> @_getPropertyValue "constraintValues" set: (value) -> if value is null newValue = null @off "change:parent", @parentChanged Screen.off "resize", @layout else newValue = _.defaults _.clone(value), left: 0, right: null, top: 0, bottom: null, centerAnchorX: 0, centerAnchorY: 0, widthFactor: null, heightFactor: null, aspectRatioLocked: false, width: @width, height: @height if @parent? if not (@layout in @parent.listeners("change:width")) @parent.on "change:width", @layout if not (@layout in @parent.listeners("change:height")) @parent.on "change:height", @layout else if not (@layout in Screen.listeners("resize")) Screen.on "resize", @layout if not (@parentChanged in @listeners("change:parent")) @on "change:parent", @parentChanged @_setPropertyValue "constraintValues", newValue @define "htmlIntrinsicSize", importable: true exportable: true default: null get: -> @_getPropertyValue "htmlIntrinsicSize" set: (value) -> if value is null @_setPropertyValue "htmlIntrinsicSize", value else return if not _.isFinite(value.width) or not _.isFinite(value.height) @_setPropertyValue "htmlIntrinsicSize", {width: value.width, height: value.height} parentChanged: (newParent, oldParent) => if oldParent? oldParent.off "change:width", @layout oldParent.off "change:height", @layout else Screen.off "resize", @layout @constraintValues = null setParentPreservingConstraintValues: (parent) -> tmp = @constraintValues @parent = parent @constraintValues = tmp @layout() _layoutX: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @x = Utils.calculateLayoutX(parentFrame, @constraintValues, @width) @isLayouting = false _layoutY: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @y = Utils.calculateLayoutY(parentFrame, @constraintValues, @height) @isLayouting = false layout: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @frame = Utils.calculateLayoutFrame(parentFrame, @) @isLayouting = false convertPointToScreen: (point) => return Utils.convertPointToContext(point, @, false) convertPointToCanvas: (point) => return Utils.convertPointToContext(point, @, true) convertPointToLayer: (point, layer, rootContext=true) => return Utils.convertPoint(point, @, layer, rootContext) @define "canvasFrame", importable: true exportable: false get: -> return Utils.boundingFrame(@) set: (frame) -> @frame = Utils.convertFrameFromContext(frame, @, true, false) @define "screenFrame", importable: true exportable: false get: -> return Utils.boundingFrame(@, false) set: (frame) -> @frame = Utils.convertFrameFromContext(frame, @, false, false) contentFrame: -> return {x: 0, y: 0, width: 0, height: 0} unless @_children.length return Utils.frameMerge(_.map(@_children, "frame")) totalFrame: -> return Utils.frameMerge(@frame, @contentFrame()) centerFrame: -> # Get the centered frame for its parent if @parent frame = @frame Utils.frameSetMidX(frame, parseInt((@parent.width / 2.0) - @parent.borderWidth)) Utils.frameSetMidY(frame, parseInt((@parent.height / 2.0) - @parent.borderWidth)) return frame else frame = @frame Utils.frameSetMidX(frame, parseInt(@_context.innerWidth / 2.0)) Utils.frameSetMidY(frame, parseInt(@_context.innerHeight / 2.0)) return frame center: -> if @constraintValues? @constraintValues.left = null @constraintValues.right = null @constraintValues.top = null @constraintValues.bottom = null @constraintValues.centerAnchorX = 0.5 @constraintValues.centerAnchorY = 0.5 @_layoutX() @_layoutY() else @frame = @centerFrame() # Center in parent @ centerX: (offset=0) -> if @constraintValues? @constraintValues.left = null @constraintValues.right = null @constraintValues.centerAnchorX = 0.5 @_layoutX() else @x = @centerFrame().x + offset # Center x in parent @ centerY: (offset=0) -> if @constraintValues? @constraintValues.top = null @constraintValues.bottom = null @constraintValues.centerAnchorY = 0.5 @_layoutY() else @y = @centerFrame().y + offset # Center y in parent @ pixelAlign: -> @x = parseInt @x @y = parseInt @y updateForDevicePixelRatioChange: => for cssProperty in ["width", "height", "webkitTransform", "boxShadow", "textShadow", "webkitFilter", "borderRadius", "borderWidth", "fontSize", "letterSpacing", "wordSpacing", "textIndent"] @_element.style[cssProperty] = LayerStyle[cssProperty](@) updateForSizeChange: => @_elementBorder.style.borderWidth = LayerStyle["borderWidth"](@) ############################################################## # SCREEN GEOMETRY # TODO: Rotation/Skew # screenOriginX = -> # if @_parentOrContext() # return @_parentOrContext().screenOriginX() # return @originX # screenOriginY = -> # if @_parentOrContext() # return @_parentOrContext().screenOriginY() # return @originY canvasScaleX: (self=true) -> scale = 1 scale = @scale * @scaleX if self for parent in @containers(true) scale *= parent.scale if parent.scaleX? scale *= parent.scaleX return scale canvasScaleY: (self=true) -> scale = 1 scale = @scale * @scaleY if self for parent in @containers(true) scale *= parent.scale if parent.scaleY? scale *= parent.scaleY return scale screenScaleX: (self=true) -> scale = 1 scale = @scale * @scaleX if self for parent in @containers(false) scale *= parent.scale * parent.scaleX return scale screenScaleY: (self=true) -> scale = 1 scale = @scale * @scaleY if self for parent in @containers(false) scale *= parent.scale * parent.scaleY return scale screenScaledFrame: -> # TODO: Scroll position frame = x: 0 y: 0 width: @width * @screenScaleX() height: @height * @screenScaleY() layers = @containers(true) layers.push(@) layers.reverse() for parent in layers p = parentOrContext(parent) factorX = p?.screenScaleX?() ? 1 factorY = p?.screenScaleY?() ? 1 layerScaledFrame = parent.scaledFrame?() ? {x: 0, y: 0} frame.x += layerScaledFrame.x * factorX frame.y += layerScaledFrame.y * factorY return frame scaledFrame: -> # Get the scaled frame for a layer, taking into account # the transform origins. frame = @frame scaleX = @scale * @scaleX scaleY = @scale * @scaleY frame.width *= scaleX frame.height *= scaleY frame.x += (1 - scaleX) * @originX * @width frame.y += (1 - scaleY) * @originY * @height return frame ############################################################## # CSS @define "style", importable: true exportable: false get: -> @_element.style set: (value) -> _.extend @_element.style, value @emit "change:style" computedStyle: -> # This is an expensive operation getComputedStyle = document.defaultView.getComputedStyle getComputedStyle ?= window.getComputedStyle return getComputedStyle(@_element) @define "classList", importable: true exportable: false get: -> @_element.classList ############################################################## # DOM ELEMENTS _createElement: -> return if @_element? @_element = document.createElement "div" @_element.classList.add("framerLayer") _createBorderElement: -> return if @_elementBorder? @_elementBorder = document.createElement "div" @_elementBorder.style.position = "absolute" @_elementBorder.style.top = "0" @_elementBorder.style.bottom = "0" @_elementBorder.style.left = "0" @_elementBorder.style.right = "0" @_elementBorder.style.boxSizing = "border-box" @_elementBorder.style.zIndex = "1000" @_elementBorder.style.pointerEvents = "none" @_element.appendChild(@_elementBorder) _insertElement: -> @bringToFront() @_context.element.appendChild(@_element) # This method is called as soon as the @_element is part of the DOM # If layers are initialized before the DOM is complete, # the contexts calls this methods on all Layers as soon as it appends itself to the document elementInsertedIntoDocument: -> _createHTMLElementIfNeeded: -> if not @_elementHTML @_elementHTML = document.createElement "div" @_element.insertBefore @_elementHTML, @_elementBorder @define "html", get: -> @_elementHTML?.innerHTML or "" set: (value) -> # Insert some html directly into this layer. We actually create # a child node to insert it in, so it won't mess with Framers # layer hierarchy. @_createHTMLElementIfNeeded() ids = Utils.getIdAttributesFromString(value) for id in ids existingElement = document.querySelector("[id='#{id}']") if existingElement? Utils.throwInStudioOrWarnInProduction(Layer.ExistingIdMessage("html", id)) return @_elementHTML.innerHTML = value @_updateHTMLScale() # If the contents contains something else than plain text # then we turn off ignoreEvents so buttons etc will work. # if not ( # @_elementHTML.childNodes.length is 1 and # @_elementHTML.childNodes[0].nodeName is "#text") # @ignoreEvents = false @emit "change:html" _updateHTMLScale: -> return if not @_elementHTML? if not @htmlIntrinsicSize? @_elementHTML.style.zoom = @context.scale else @_elementHTML.style.transformOrigin = "0 0" @_elementHTML.style.transform = "scale(#{@context.scale * @width / @htmlIntrinsicSize.width}, #{@context.scale * @height / @htmlIntrinsicSize.height})" @_elementHTML.style.width = "#{@htmlIntrinsicSize.width}px" @_elementHTML.style.height = "#{@htmlIntrinsicSize.height}px" querySelector: (query) -> @_element.querySelector(query) querySelectorAll: (query) -> @_element.querySelectorAll(query) selectChild: (selector) -> Utils.findLayer(@descendants, selector) selectAllChildren: (selector) -> Utils.filterLayers(@descendants, selector) @select: (selector) -> Framer.CurrentContext.selectLayer(selector) @selectAll: (selector) -> Framer.CurrentContext.selectAllLayers(selector) destroy: -> # Todo: check this if @parent @parent._children = _.without(@parent._children, @) @_element.parentNode?.removeChild @_element @removeAllListeners() @_context.removeLayer(@) @_context.emit("layer:destroy", @) @_context.domEventManager.remove(@_element) ############################################################## ## COPYING copy: -> layer = @copySingle() for child in @_children copiedChild = child.copy() copiedChild.parent = layer if copiedChild isnt null return layer copySingle: -> copy = new @constructor(@props) copy.style = @style copy ############################################################## ## IMAGE _cleanupImageLoader: -> @_imageEventManager?.removeAllListeners() @_imageEventManager = null @_imageLoader = null @define "image", default: "" get: -> @_getPropertyValue "image" set: (value) -> currentValue = @_getPropertyValue "image" defaults = Defaults.getDefaults "Layer", {} isBackgroundColorDefault = @backgroundColor?.isEqual(defaults.backgroundColor) if Gradient.isGradientObject(value) @emit("change:gradient", value, currentValue) @emit("change:image", value, currentValue) @_setPropertyValue("image", value) @style["background-image"] = value.toCSS() @backgroundColor = null if isBackgroundColorDefault return if not (_.isString(value) or value is null) layerValueTypeError("image", value) if currentValue is value return @emit "load" # Unset the background color only if it’s the default color @backgroundColor = null if isBackgroundColorDefault # Set the property value @_setPropertyValue("image", value) if value in [null, ""] if @_imageLoader? @_imageEventManager.removeAllListeners() @_imageLoader.src = null @style["background-image"] = null if @_imageLoader? @emit Events.ImageLoadCancelled, @_imageLoader @_cleanupImageLoader() return # Show placeholder image on any browser that doesn't support inline pdf if _.endsWith(value.toLowerCase?(), ".pdf") and (not Utils.isWebKit() or Utils.isChrome()) @style["background-image"] = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAAVlJREFUaAXtlwEOwiAMRdF4Cr3/0fQaSre9ZFSYLCrQpSSG/FLW9v92agghXJdP3KZlCp/J2up+WiUuzMt6zNukzPDYvALCsKme1/maV8BnQHqw9/IZ6KmAz0BP9ontMwATPXafgR6s65g+A5qRlrhmBu6FhG6LXf9/+JU/YclROkVWEs/8r9FLrChb2apSqVqWZgKmtRKz9/f+CdPxoVl8CAWylcWKUQZGwfhjB3OOHcw5djDn2MH6fBNLC42yaEnyoTXB2V36+lPlz+zN9x6HKfxrZwZ/HUbf5/lJviMpoBPWBWWxFJCtLNqplItIWuvPffx5Dphz7GB9vonNv4X2zICWuMTM3p7Gv/b5iVLmFaiZgb3M/Ns/Ud68AvIGkJ6ir8xh8wrQrzAve9Jjo2PzCsC8z4Aw0WP5DPRgXcf07wHNSEvsM9CS7VIsn4ESMy3sPgMtWN6K8QKfubDo2UqVogAAAABJRU5ErkJggg==')" return imageUrl = value # Optional base image value # imageUrl = Config.baseUrl + imageUrl if @_alwaysUseImageCache is false and Utils.isLocalAssetUrl(imageUrl) imageUrl += if /\?/.test(imageUrl) then '&' else '?' imageUrl += "nocache=#{NoCacheDateKey}" # As an optimization, we will only use a loader # if something is explicitly listening to the load event if @listeners(Events.ImageLoaded, true) or @listeners(Events.ImageLoadError, true) or @listeners(Events.ImageLoadCancelled, true) @_imageLoader = new Image() @_imageLoader.name = imageUrl @_imageLoader.src = imageUrl @_imageEventManager = @_context.domEventManager.wrap(@_imageLoader) @_imageEventManager.addEventListener "load", => @style["background-image"] = "url('#{imageUrl}')" @emit Events.ImageLoaded, @_imageLoader @_cleanupImageLoader() @_imageEventManager.addEventListener "error", => @emit Events.ImageLoadError, @_imageLoader @_cleanupImageLoader() else @style["background-image"] = "url('#{imageUrl}')" @define "gradient", get: -> return layerProxiedValue(@image, @, "gradient") if Gradient.isGradientObject(@image) return null set: (value) -> # Copy semantics! if Gradient.isGradient(value) @image = new Gradient(value) else if not value and Gradient.isGradientObject(@image) @image = null ############################################################## ## HIERARCHY @define "parent", enumerable: false exportable: false importable: true get: -> @_parent or null set: (layer) -> return if layer is @_parent throw Error("Layer.parent: a layer cannot be it's own parent.") if layer is @ # Check the type if not layer instanceof Layer throw Error "Layer.parent needs to be a Layer object" # Cancel previous pending insertions Utils.domCompleteCancel(@__insertElement) # Remove from previous parent children if @_parent @_parent._children = _.pull @_parent._children, @ @_parent._element.removeChild @_element @_parent.emit "change:children", {added: [], removed: [@]} @_parent.emit "change:subLayers", {added: [], removed: [@]} # Either insert the element to the new parent element or into dom if layer layer._element.appendChild @_element layer._children.push @ layer.emit "change:children", {added: [@], removed: []} layer.emit "change:subLayers", {added: [@], removed: []} else @_insertElement() oldParent = @_parent # Set the parent @_parent = layer # Place this layer on top of its siblings @bringToFront() @emit "change:parent", @_parent, oldParent @emit "change:superLayer", @_parent, oldParent @define "children", enumerable: false exportable: false importable: false get: -> @_children.map (c) -> if c instanceof SVGLayer and c.children.length is 1 and _.startsWith(c.name, '.') return c.children[0] else return c @define "siblings", enumerable: false exportable: false importable: false get: -> # If there is no parent we need to walk through the root if @parent is null return _.filter @_context.layers, (layer) => layer isnt @ and layer.parent is null return _.without @parent.children, @ @define "descendants", enumerable: false exportable: false importable: false get: -> result = [] f = (layer) -> result.push(layer) layer.children.map(f) @children.map(f) return result addChild: (layer) -> layer.parent = @ removeChild: (layer) -> if layer not in @_children return layer.parent = null childrenWithName: (name) -> _.filter @children, (layer) -> layer.name is name siblingsWithName: (name) -> _.filter @siblingLayers, (layer) -> layer.name is name # Get all containers of this layer, including containing contexts # `toRoot` specifies if you want to bubble up across contexts, # so specifiying `false` will stop at the first context # and thus the results will never contain any context containers: (toRoot=false, result=[]) -> if @parent? result.push(@parent) return @parent.containers(toRoot, result) else if toRoot result.push(@context) return @context.containers(true, result) return result ancestors: -> return @containers() root: -> return @ if @parent is null return _.last(@ancestors()) childrenAbove: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).y < point.y childrenBelow: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).y > point.y childrenLeft: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).x < point.x childrenRight: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).x > point.x _parentOrContext: -> if @parent return @parent if @_context._parent return @_context._parent ############################################################## # Backwards superLayer and children compatibility @define "superLayer", enumerable: false exportable: false importable: false get: -> @parent set: (value) -> @parent = value @define "subLayers", enumerable: false exportable: false importable: false get: -> @children @define "siblingLayers", enumerable: false exportable: false importable: false get: -> @siblings addSubLayer: (layer) -> @addChild(layer) removeSubLayer: (layer) -> @removeChild(layer) subLayersByName: (name) -> @childrenWithName(name) siblingLayersByName: (name) -> @siblingsWithName(name) subLayersAbove: (point, originX=0, originY=0) -> @childrenAbove(point, originX, originY) subLayersBelow: (point, originX=0, originY=0) -> @childrenBelow(point, originX, originY) subLayersLeft: (point, originX=0, originY=0) -> @childrenLeft(point, originX, originY) subLayersRight: (point, originX=0, originY=0) -> @childrenRight(point, originX, originY) ############################################################## ## ANIMATION animate: (properties, options={}) -> # If the properties are a string, we assume it's a state name if _.isString(properties) stateName = properties # Support options as an object options = options.options if options.options? return @states.machine.switchTo(stateName, options) # We need to clone the properties so we don't modify them unexpectedly properties = _.clone(properties) # Support the old properties syntax, we add all properties top level and # move the options into an options property. if properties.properties? options = properties properties = options.properties delete options.properties # With the new api we treat the properties as animatable properties, and use # the special options keyword for animation options. if properties.options? options = _.defaults({}, options, properties.options) delete properties.options # Merge the animation options with the default animation options for this layer options = _.defaults({}, options, @animationOptions) options.start ?= true animation = new Animation(@, properties, options) animation.start() if options.start return animation stateCycle: (args...) -> states = _.flatten(args) if _.isObject(_.last(states)) options = states.pop() @animate(@states.machine.next(states), options) stateSwitch: (stateName, options={}) -> unless stateName? throw new Error("Missing required argument 'stateName' in stateSwitch()") return @animate(stateName, options) if options.animate is true return @animate(stateName, _.defaults({}, options, {instant: true})) animations: (includePending=false) -> # Current running animations on this layer _.filter @_context.animations, (animation) => return false unless (animation.layer is @) return includePending or not animation.isPending animatingProperties: -> properties = {} for animation in @animations() for propertyName in animation.animatingProperties() properties[propertyName] = animation return properties @define "isAnimating", enumerable: false exportable: false get: -> @animations().length isnt 0 animateStop: -> _.invokeMap(@animations(), "stop") @_draggable?.animateStop() ############################################################## ## INDEX ORDERING bringToFront: -> maxIndex = null siblings = @parent?._children ? @context._layers return if siblings.count <= 1 for layer in siblings continue if layer is @ maxIndex ?= layer.index if layer.index > maxIndex maxIndex = layer.index if maxIndex? @index = maxIndex + 1 sendToBack: -> minIndex = null siblings = @parent?._children ? @context._layers return if siblings.count <= 1 for layer in siblings continue if layer is @ minIndex ?= layer.index if layer.index < minIndex minIndex = layer.index if minIndex? @index = minIndex - 1 placeBefore: (layer) -> return if layer not in @siblingLayers for l in @siblingLayers if l.index <= layer.index l.index -= 1 @index = layer.index + 1 placeBehind: (layer) -> return if layer not in @siblingLayers for l in @siblingLayers if l.index >= layer.index l.index += 1 @index = layer.index - 1 ############################################################## ## STATES @define "states", enumerable: false exportable: false importable: false get: -> @_states ?= new LayerStates(@) return @_states set: (states) -> @states.machine.reset() _.extend(@states, states) @define "stateNames", enumerable: false exportable: false importable: false get: -> @states.machine.stateNames ############################################################################# ## Draggable, Pinchable @define "draggable", importable: false exportable: false get: -> @_draggable ?= new LayerDraggable(@) set: (value) -> @draggable.enabled = value if _.isBoolean(value) @define "pinchable", importable: false exportable: false get: -> @_pinchable ?= new LayerPinchable(@) set: (value) -> @pinchable.enabled = value if _.isBoolean(value) ############################################################## ## SCROLLING @define "scrollFrame", importable: false get: -> frame = x: @scrollX y: @scrollY width: @width height: @height set: (frame) -> @scrollX = frame.x @scrollY = frame.y @define "scrollX", get: -> @_element.scrollLeft set: (value) -> layerValueTypeError("scrollX", value) if not _.isNumber(value) @_element.scrollLeft = value @define "scrollY", get: -> @_element.scrollTop set: (value) -> layerValueTypeError("scrollY", value) if not _.isNumber(value) @_element.scrollTop = value ############################################################## ## EVENTS @define "_domEventManager", get: -> @_context.domEventManager.wrap(@_element) emit: (eventName, args...) -> # If this layer has a parent draggable view and its position moved # while dragging we automatically cancel click events. This is what # you expect when you add a button to a scroll content layer. We only # want to do this if this layer is not draggable itself because that # would break nested ScrollComponents. if @_cancelClickEventInDragSession and not @_draggable if eventName in [ Events.Click, Events.Tap, Events.TapStart, Events.TapEnd, Events.LongPress, Events.LongPressStart, Events.LongPressEnd] # If we dragged any layer, we should cancel click events return if LayerDraggable._globalDidDrag is true # See if we need to convert coordinates for this event. Mouse events by # default have the screen coordinates so we make sure that event.point and # event.contextPoint always have the proper coordinates. if args[0]?.clientX? or args[0]?.clientY? event = args[0] point = {x: event.clientX, y: event.clientY} event.point = Utils.convertPointFromContext(point, @, true) event.contextPoint = Utils.convertPointFromContext(point, @context, true) if event.touches? for touch in event.touches point = {x: touch.clientX, y: touch.clientY} touch.point = Utils.convertPointFromContext(point, @, true) touch.contextPoint = Utils.convertPointFromContext(point, @context, true) # Always scope the event this to the layer and pass the layer as # last argument for every event. super(eventName, args..., @) once: (eventName, listener) => super(eventName, listener) @_addListener(eventName, listener) addListener: (eventName, listener) => throw Error("Layer.on needs a valid event name") unless eventName throw Error("Layer.on needs an event listener") unless listener super(eventName, listener) @_addListener(eventName, listener) removeListener: (eventName, listener) -> throw Error("Layer.off needs a valid event name") unless eventName super(eventName, listener) @_removeListener(eventName, listener) _addListener: (eventName, listener) -> # Make sure we stop ignoring events once we add a user event listener if not _.startsWith(eventName, "change:") @ignoreEvents = false # If this is a dom event, we want the actual dom node to let us know # when it gets triggered, so we can emit the event through the system. if Utils.domValidEvent(@_element, eventName) or eventName in _.values(Gestures) if not @_domEventManager.listeners(eventName).length @_domEventManager.addEventListener eventName, (event) => @emit(eventName, event) _removeListener: (eventName, listener) -> # Do cleanup for dom events if this is the last one of it's type. # We are assuming we're the only ones adding dom events to the manager. if not @listeners(eventName).length @_domEventManager.removeAllListeners(eventName) _parentDraggableLayer: -> for layer in @ancestors() return layer if layer._draggable?.enabled return null on: @::addListener off: @::removeListener ############################################################## ## EVENT HELPERS onClick: (cb) -> @on(Events.Click, cb) onDoubleClick: (cb) -> @on(Events.DoubleClick, cb) onScrollStart: (cb) -> @on(Events.ScrollStart, cb) onScroll: (cb) -> @on(Events.Scroll, cb) onScrollEnd: (cb) -> @on(Events.ScrollEnd, cb) onScrollAnimationDidStart: (cb) -> @on(Events.ScrollAnimationDidStart, cb) onScrollAnimationDidEnd: (cb) -> @on(Events.ScrollAnimationDidEnd, cb) onTouchStart: (cb) -> @on(Events.TouchStart, cb) onTouchEnd: (cb) -> @on(Events.TouchEnd, cb) onTouchMove: (cb) -> @on(Events.TouchMove, cb) onMouseUp: (cb) -> @on(Events.MouseUp, cb) onMouseDown: (cb) -> @on(Events.MouseDown, cb) onMouseOver: (cb) -> @on(Events.MouseOver, cb) onMouseOut: (cb) -> @on(Events.MouseOut, cb) onMouseEnter: (cb) -> @on(Events.MouseEnter, cb) onMouseLeave: (cb) -> @on(Events.MouseLeave, cb) onMouseMove: (cb) -> @on(Events.MouseMove, cb) onMouseWheel: (cb) -> @on(Events.MouseWheel, cb) onAnimationStart: (cb) -> @on(Events.AnimationStart, cb) onAnimationStop: (cb) -> @on(Events.AnimationStop, cb) onAnimationEnd: (cb) -> @on(Events.AnimationEnd, cb) onAnimationDidStart: (cb) -> @on(Events.AnimationDidStart, cb) # Deprecated onAnimationDidStop: (cb) -> @on(Events.AnimationDidStop, cb) # Deprecated onAnimationDidEnd: (cb) -> @on(Events.AnimationDidEnd, cb) # Deprecated onImageLoaded: (cb) -> @on(Events.ImageLoaded, cb) onImageLoadError: (cb) -> @on(Events.ImageLoadError, cb) onImageLoadCancelled: (cb) -> @on(Events.ImageLoadCancelled, cb) onMove: (cb) -> @on(Events.Move, cb) onDragStart: (cb) -> @on(Events.DragStart, cb) onDragWillMove: (cb) -> @on(Events.DragWillMove, cb) onDragMove: (cb) -> @on(Events.DragMove, cb) onDragDidMove: (cb) -> @on(Events.DragDidMove, cb) onDrag: (cb) -> @on(Events.Drag, cb) onDragEnd: (cb) -> @on(Events.DragEnd, cb) onDragAnimationStart: (cb) -> @on(Events.DragAnimationStart, cb) onDragAnimationEnd: (cb) -> @on(Events.DragAnimationEnd, cb) onDirectionLockStart: (cb) -> @on(Events.DirectionLockStart, cb) onStateSwitchStart: (cb) -> @on(Events.StateSwitchStart, cb) onStateSwitchStop: (cb) -> @on(Events.StateSwitchStop, cb) onStateSwitchEnd: (cb) -> @on(Events.StateSwitchEnd, cb) onStateWillSwitch: (cb) -> @on(Events.StateSwitchStart, cb) # Deprecated onStateDidSwitch: (cb) -> @on(Events.StateSwitchEnd, cb) # Deprecated # Gestures # Tap onTap: (cb) -> @on(Events.Tap, cb) onTapStart: (cb) -> @on(Events.TapStart, cb) onTapEnd: (cb) -> @on(Events.TapEnd, cb) onDoubleTap: (cb) -> @on(Events.DoubleTap, cb) # Force Tap onForceTap: (cb) -> @on(Events.ForceTap, cb) onForceTapChange: (cb) -> @on(Events.ForceTapChange, cb) onForceTapStart: (cb) -> @on(Events.ForceTapStart, cb) onForceTapEnd: (cb) -> @on(Events.ForceTapEnd, cb) # Press onLongPress: (cb) -> @on(Events.LongPress, cb) onLongPressStart: (cb) -> @on(Events.LongPressStart, cb) onLongPressEnd: (cb) -> @on(Events.LongPressEnd, cb) # Swipe onSwipe: (cb) -> @on(Events.Swipe, cb) onSwipeStart: (cb) -> @on(Events.SwipeStart, cb) onSwipeEnd: (cb) -> @on(Events.SwipeEnd, cb) onSwipeUp: (cb) -> @on(Events.SwipeUp, cb) onSwipeUpStart: (cb) -> @on(Events.SwipeUpStart, cb) onSwipeUpEnd: (cb) -> @on(Events.SwipeUpEnd, cb) onSwipeDown: (cb) -> @on(Events.SwipeDown, cb) onSwipeDownStart: (cb) -> @on(Events.SwipeDownStart, cb) onSwipeDownEnd: (cb) -> @on(Events.SwipeDownEnd, cb) onSwipeLeft: (cb) -> @on(Events.SwipeLeft, cb) onSwipeLeftStart: (cb) -> @on(Events.SwipeLeftStart, cb) onSwipeLeftEnd: (cb) -> @on(Events.SwipeLeftEnd, cb) onSwipeRight: (cb) -> @on(Events.SwipeRight, cb) onSwipeRightStart: (cb) -> @on(Events.SwipeRightStart, cb) onSwipeRightEnd: (cb) -> @on(Events.SwipeRightEnd, cb) # Pan onPan: (cb) -> @on(Events.Pan, cb) onPanStart: (cb) -> @on(Events.PanStart, cb) onPanEnd: (cb) -> @on(Events.PanEnd, cb) onPanLeft: (cb) -> @on(Events.PanLeft, cb) onPanRight: (cb) -> @on(Events.PanRight, cb) onPanUp: (cb) -> @on(Events.PanUp, cb) onPanDown: (cb) -> @on(Events.PanDown, cb) # Pinch onPinch: (cb) -> @on(Events.Pinch, cb) onPinchStart: (cb) -> @on(Events.PinchStart, cb) onPinchEnd: (cb) -> @on(Events.PinchEnd, cb) # Scale onScale: (cb) -> @on(Events.Scale, cb) onScaleStart: (cb) -> @on(Events.ScaleStart, cb) onScaleEnd: (cb) -> @on(Events.ScaleEnd, cb) # Rotate onRotate: (cb) -> @on(Events.Rotate, cb) onRotateStart: (cb) -> @on(Events.RotateStart, cb) onRotateEnd: (cb) -> @on(Events.RotateEnd, cb) ############################################################## ## HINT _showHint: (targetLayer) -> # If this layer isnt visible we can just exit return if not @visible return if @opacity is 0 # If we don't need to show a hint exit but pass to children unless @shouldShowHint(targetLayer) layer._showHint(targetLayer) for layer in @children return null # Figure out the frame we want to show the hint in, if any of the # parent layers clip, we need to intersect the rectangle with it. frame = @canvasFrame for parent in @ancestors() if parent.clip frame = Utils.frameIntersection(frame, parent.canvasFrame) if not frame return # Show the actual hint @showHint(frame) # Tell the children to show their hints _.invokeMap(@children, "_showHint") willSeemToDoSomething: -> if @ignoreEvents return false if @_draggable if @_draggable.isDragging is false and @_draggable.isMoving is false return false return true shouldShowHint: -> # Don't show hints if the layer is not interactive if @ignoreEvents is true return false # Don't show any hints while we are animating if @isAnimating return false for parent in @ancestors() return false if parent.isAnimating # Don't show hints if there is a draggable that cannot be dragged. if @_draggable and @_draggable.horizontal is false and @_draggable.vertical is false return false # Don't show hint if this layer is invisible return false if @opacity is 0 # If we don't ignore events on this layer, make sure the layer is listening to # an interactive event so there is a decent change something is happening after # we click it. for eventName in @listenerEvents() return true if Events.isInteractive(eventName) return false showHint: (highlightFrame) -> # Don't show anything if this element covers the entire screen # if Utils.frameInFrame(@context.canvasFrame, highlightFrame) # return # Start an animation with a rectangle fading out over time layer = new Layer frame: Utils.frameInset(highlightFrame, -1) backgroundColor: null borderColor: Framer.Defaults.Hints.color borderRadius: @borderRadius * Utils.average([@canvasScaleX(), @canvasScaleY()]) borderWidth: 3 # Only show outlines for draggables if @_draggable layer.backgroundColor = null # Only show outlines if a highlight is fullscreen if Utils.frameInFrame(@context.canvasFrame, highlightFrame) layer.backgroundColor = null animation = layer.animate properties: {opacity: 0} curve: "ease-out" time: 0.5 animation.onAnimationEnd -> layer.destroy() ############################################################## ## DESCRIPTOR toName: -> return name if @name return @__framerInstanceInfo?.name or "" toInspect: (constructor) -> constructor ?= @constructor.name name = if @name then "name:#{@name} " else "" return "<#{constructor} #{@toName()} id:#{@id} #{name} (#{Utils.roundWhole(@x)}, #{Utils.roundWhole(@y)}) #{Utils.roundWhole(@width)}x#{Utils.roundWhole(@height)}>"
166710
{_} = require "./Underscore" Utils = require "./Utils" {Config} = require "./Config" {Events} = require "./Events" {Defaults} = require "./Defaults" {BaseClass} = require "./BaseClass" {EventEmitter} = require "./EventEmitter" {Color} = require "./Color" {Gradient} = require "./Gradient" {Matrix} = require "./Matrix" {Animation} = require "./Animation" {LayerStyle} = require "./LayerStyle" {LayerStates} = require "./LayerStates" {LayerDraggable} = require "./LayerDraggable" {LayerPinchable} = require "./LayerPinchable" {Gestures} = require "./Gestures" {LayerPropertyProxy} = require "./LayerPropertyProxy" NoCacheDateKey = Date.now() delayedStyles = ["webkitTransform", "webkitFilter", "webkitPerspectiveOrigin", "webkitTransformOrigin", "webkitBackdropFilter"] layerValueTypeError = (name, value) -> throw new Error("Layer.#{name}: value '#{value}' of type '#{typeof(value)}' is not valid") layerProperty = (obj, name, cssProperty, fallback, validator, transformer, options={}, set, targetElement, includeMainElement, useSubpropertyProxy) -> result = default: fallback get: -> # console.log "Layer.#{name}.get #{@_properties[name]}", @_properties.hasOwnProperty(name) value = @_properties[name] if @_properties.hasOwnProperty(name) value ?= fallback return layerProxiedValue(value, @, name) if useSubpropertyProxy return value set: (value) -> # console.log "#{@constructor.name}.#{name}.set #{value} current:#{@[name]}", targetElement # Convert the value value = transformer(value, @, name) if transformer oldValue = @_properties[name] # Return unless we get a new value return if value is oldValue if value and validator and not validator(value) layerValueTypeError(name, value) @_properties[name] = value if cssProperty isnt null elementContainer = @ if cssProperty in @_stylesAppliedToParent elementContainer = @_parent @_parent._properties[name] = fallback mainElement = elementContainer._element if includeMainElement or not targetElement subElement = elementContainer[targetElement] if targetElement? if name is cssProperty and not LayerStyle[cssProperty]? mainElement?.style[cssProperty] = @_properties[name] subElement?.style[cssProperty] = @_properties[name] # These values are set multiple times during applyDefaults, so ignore them here, and set the style in the constructor else if not @__applyingDefaults or (cssProperty not in delayedStyles) style = LayerStyle[cssProperty](@) mainElement?.style[cssProperty] = style subElement?.style[cssProperty] = style set?(@, value) # We try to not send any events while we run the constructor, it just # doesn't make sense, because no one can listen to use yet. return if @__constructor @emit("change:#{name}", value, oldValue) @emit("change:point", value) if name in ["x", "y"] @emit("change:size", value) if name in ["width", "height"] @emit("change:frame", value) if name in ["x", "y", "width", "height"] @emit("change:rotation", value) if name in ["rotationZ"] result = _.extend(result, options) exports.layerProperty = layerProperty # Use this to wrap property values in a Proxy so setting sub-properties # will also trigger updates on the layer. # Because we’re not fully on ES6, we can’t use Proxy, so use our own wrapper. layerProxiedValue = (value, layer, property) -> return value unless _.isObject(value) new LayerPropertyProxy value, (proxiedValue, subProperty, subValue) -> proxiedValue[subProperty] = subValue layer[property] = proxiedValue exports.layerProxiedValue = layerProxiedValue layerPropertyPointTransformer = (value, layer, property) -> if _.isFunction(value) value = value(layer, property) return value layerPropertyIgnore = (options, propertyName, properties) -> return options unless options.hasOwnProperty(propertyName) for p in properties if options.hasOwnProperty(p) delete options[propertyName] return options return options asBorderRadius = (value) -> return value if _.isNumber(value) if _.isString(value) if not _.endsWith(value, "%") console.error "Layer.borderRadius only correctly supports percentages in strings" return value return 0 if not _.isObject(value) result = {} isValidObject = false for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"] isValidObject ||= _.has(value, key) result[key] = value[key] ? 0 return if not isValidObject then 0 else result asBorderWidth = (value) -> return value if _.isNumber(value) return 0 if not _.isObject(value) result = {} isValidObject = false for key in ["left", "right", "bottom", "top"] isValidObject ||= _.has(value, key) result[key] = value[key] ? 0 return if not isValidObject then 0 else result parentOrContext = (layerOrContext) -> if layerOrContext.parent? return layerOrContext.parent else return layerOrContext.context proxiedShadowValue = (layer, value, index = 0) -> v = _.defaults _.clone(value), Framer.Defaults.Shadow if v.color isnt null v?.color = new Color(v.color) layerProxiedValue(v, layer, "shadow#{index+1}") class exports.Layer extends BaseClass constructor: (options={}) -> # Make sure we never call the constructor twice throw Error("Layer.constructor #{@toInspect()} called twice") if @__constructorCalled @__constructorCalled = true @__constructor = true # Set needed private variables @_properties = {} @_style = {} @_children = [] @_stylesAppliedToParent ?= [] # Special power setting for 2d rendering path. Only enable this # if you know what you are doing. See LayerStyle for more info. @_prefer2d = false @_alwaysUseImageCache = false # Private setting for canceling of click event if wrapped in moved draggable @_cancelClickEventInDragSession = true # We have to create the element before we set the defaults @_createElement() if options.createHTMLElement @_createHTMLElementIfNeeded() # Create border element @_createBorderElement() # Sanitize calculated property setters so direct properties always win layerPropertyIgnore(options, "point", ["x", "y"]) layerPropertyIgnore(options, "midPoint", ["midX", "midY"]) layerPropertyIgnore(options, "size", ["width", "height"]) layerPropertyIgnore(options, "frame", ["x", "y", "width", "height"]) # Backwards compatibility for superLayer if not options.hasOwnProperty("parent") and options.hasOwnProperty("superLayer") options.parent = options.superLayer delete options.superLayer @__applyingDefaults = true super Defaults.getDefaults("Layer", options) delete @__applyingDefaults for cssProperty in delayedStyles element = @_element if cssProperty in @_stylesAppliedToParent element = @_parent._element element.style[cssProperty] = LayerStyle[cssProperty](@) # Add this layer to the current context @_context.addLayer(@) @_id = @_context.layerCounter # Insert the layer into the dom or the parent element if not options.parent @_insertElement() if not options.shadow else @parent = options.parent # Set some calculated properties # Make sure we set the right index if options.hasOwnProperty("index") @index = options.index # x and y always win from point, frame or size for p in ["x", "y", "width", "height"] if options.hasOwnProperty(p) @[p] = options[p] @_context.emit("layer:create", @) # Make sure the layer is always centered @label = @label delete @__constructor @updateShadowStyle() @onChange("size", @updateForSizeChange) @ExistingIdMessage: (type, id) -> "Can not set #{type}: There's already an element with id '#{id}' in this document'" ############################################################## # Properties # Readonly context property @define "context", get: -> @_context @define "label", get: -> @_label set: (value) -> return if value is @_label @_label = value Utils.labelLayer(@, @_label) # A placeholder for layer bound properties defined by the user: @define "custom", @simpleProperty("custom", undefined) # Default animation options for every animation of this layer @define "animationOptions", @simpleProperty("animationOptions", {}) # Behaviour properties @define "ignoreEvents", layerProperty(@, "ignoreEvents", "pointerEvents", true, _.isBoolean) # Css properties @define "width", layerProperty(@, "width", "width", 100, _.isNumber, null, {}, (layer, value) -> return if not layer.constraintValues? or layer.isLayouting layer.constraintValues.width = value layer.constraintValues.aspectRatioLocked = false layer.constraintValues.widthFactor = null layer._layoutX() ) @define "height", layerProperty(@, "height", "height", 100, _.isNumber, null, {}, (layer, value) -> return if not layer.constraintValues? or layer.isLayouting layer.constraintValues.height = value layer.constraintValues.aspectRatioLocked = false layer.constraintValues.heightFactor = null layer._layoutY() ) @define "visible", layerProperty(@, "visible", "display", true, _.isBoolean) @define "opacity", layerProperty(@, "opacity", "opacity", 1, _.isNumber, parseFloat) @define "index", layerProperty(@, "index", "zIndex", 0, _.isNumber, null, {importable: false, exportable: false}) @define "clip", layerProperty(@, "clip", "overflow", false, _.isBoolean, null, {}, null, "_elementHTML", true) @define "scrollHorizontal", layerProperty @, "scrollHorizontal", "overflowX", false, _.isBoolean, null, {}, (layer, value) -> layer.ignoreEvents = false if value is true @define "scrollVertical", layerProperty @, "scrollVertical", "overflowY", false, _.isBoolean, null, {}, (layer, value) -> layer.ignoreEvents = false if value is true @define "scroll", get: -> @scrollHorizontal is true or @scrollVertical is true set: (value) -> @scrollHorizontal = @scrollVertical = value # Matrix properties @define "x", layerProperty(@, "x", "webkitTransform", 0, _.isNumber, layerPropertyPointTransformer, {depends: ["width", "height"]}, (layer) -> return if layer.isLayouting layer.constraintValues = null ) @define "y", layerProperty(@, "y", "webkitTransform", 0, _.isNumber, layerPropertyPointTransformer, {depends: ["width", "height"]}, (layer) -> return if layer.isLayouting layer.constraintValues = null ) @define "z", layerProperty(@, "z", "webkitTransform", 0, _.isNumber) @define "scaleX", layerProperty(@, "scaleX", "webkitTransform", 1, _.isNumber) @define "scaleY", layerProperty(@, "scaleY", "webkitTransform", 1, _.isNumber) @define "scaleZ", layerProperty(@, "scaleZ", "webkitTransform", 1, _.isNumber) @define "scale", layerProperty(@, "scale", "webkitTransform", 1, _.isNumber) @define "skewX", layerProperty(@, "skewX", "webkitTransform", 0, _.isNumber) @define "skewY", layerProperty(@, "skewY", "webkitTransform", 0, _.isNumber) @define "skew", layerProperty(@, "skew", "webkitTransform", 0, _.isNumber) # @define "scale", # get: -> (@scaleX + @scaleY + @scaleZ) / 3.0 # set: (value) -> @scaleX = @scaleY = @scaleZ = value @define "originX", layerProperty(@, "originX", "webkitTransformOrigin", 0.5, _.isNumber) @define "originY", layerProperty(@, "originY", "webkitTransformOrigin", 0.5, _.isNumber) @define "originZ", layerProperty(@, "originZ", null, 0, _.isNumber) @define "perspective", layerProperty(@, "perspective", "webkitPerspective", 0, ((v) -> Utils.webkitPerspectiveForValue(v) isnt null)) @define "perspectiveOriginX", layerProperty(@, "perspectiveOriginX", "webkitPerspectiveOrigin", 0.5, _.isNumber) @define "perspectiveOriginY", layerProperty(@, "perspectiveOriginY", "webkitPerspectiveOrigin", 0.5, _.isNumber) @define "rotationX", layerProperty(@, "rotationX", "webkitTransform", 0, _.isNumber) @define "rotationY", layerProperty(@, "rotationY", "webkitTransform", 0, _.isNumber) @define "rotationZ", layerProperty(@, "rotationZ", "webkitTransform", 0, _.isNumber) @define "rotation", #exportable: false get: -> @rotationZ set: (value) -> @rotationZ = value # Filter properties @define "blur", layerProperty(@, "blur", "webkitFilter", 0, _.isNumber) @define "brightness", layerProperty(@, "brightness", "webkitFilter", 100, _.isNumber) @define "saturate", layerProperty(@, "saturate", "webkitFilter", 100, _.isNumber) @define "hueRotate", layerProperty(@, "hueRotate", "webkitFilter", 0, _.isNumber) @define "contrast", layerProperty(@, "contrast", "webkitFilter", 100, _.isNumber) @define "invert", layerProperty(@, "invert", "webkitFilter", 0, _.isNumber) @define "grayscale", layerProperty(@, "grayscale", "webkitFilter", 0, _.isNumber) @define "sepia", layerProperty(@, "sepia", "webkitFilter", 0, _.isNumber) @define "blending", layerProperty(@, "blending", "mixBlendMode", null, _.isString) @define "backgroundBlur", layerProperty(@, "backgroundBlur", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundBrightness", layerProperty(@, "backgroundBrightness", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundSaturate", layerProperty(@, "backgroundSaturate", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundHueRotate", layerProperty(@, "backgroundHueRotate", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundContrast", layerProperty(@, "backgroundContrast", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundInvert", layerProperty(@, "backgroundInvert", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundGrayscale", layerProperty(@, "backgroundGrayscale", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundSepia", layerProperty(@, "backgroundSepia", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundSize", layerProperty(@, "backgroundSize", "backgroundSize", "fill", _.isString) for i in [0..8] do (i) => @define "shadow#{i+1}", exportable: false depends: ["shadowX", "shadowY", "shadowBlur", "shadowSpread", "shadowColor", "shadowType"] get: -> @shadows ?= [] @shadows[i] ?= proxiedShadowValue(@, {}, i) @shadows[i] set: (value) -> @shadows ?= [] @shadows[i] = proxiedShadowValue(@, value, i) @updateShadowStyle() updateShadowsProperty: (prop, value) -> @shadows ?= [] if (@shadows.filter (s) -> s isnt null).length is 0 @shadows[0] = proxiedShadowValue(@, Framer.Defaults.Shadow) for shadow in @shadows shadow?[prop] = value @updateShadowStyle() # Shadow properties for shadowProp in ["X", "Y", "Blur", "Spread", "Color", "Type"] do (shadowProp) => @define "shadow#{shadowProp}", get: -> return null if not @shadows? or @shadows.length is 0 @shadows[0][shadowProp.toLowerCase()] set: (value) -> @updateShadowsProperty(shadowProp.toLowerCase(), value) @define "shadows", default: null get: -> @_getPropertyValue("shadows") set: (value) -> value ?= [] shadows = [] for shadow, index in value if shadow is null shadows.push null else shadows.push proxiedShadowValue(@, shadow, index) @_setPropertyValue("shadows", shadows) @updateShadowStyle() updateShadowStyle: -> return if @__constructor @_element.style.boxShadow = LayerStyle["boxShadow"](@) @_element.style.textShadow = LayerStyle["textShadow"](@) @_element.style.webkitFilter = LayerStyle["webkitFilter"](@) # Color properties @define "backgroundColor", layerProperty(@, "backgroundColor", "backgroundColor", null, Color.validColorValue, Color.toColor) @define "color", layerProperty(@, "color", "color", null, Color.validColorValue, Color.toColor, null, null, "_elementHTML", true) # Border properties @define "borderRadius", layerProperty(@, "borderRadius", "borderRadius", 0, null, asBorderRadius, null, null, "_elementBorder", true, true) @define "borderColor", layerProperty(@, "borderColor", "borderColor", null, Color.validColorValue, Color.toColor, null, null, "_elementBorder") @define "borderWidth", layerProperty(@, "borderWidth", "borderWidth", 0, null, asBorderWidth, null, null, "_elementBorder", false, true) @define "borderStyle", layerProperty(@, "borderStyle", "borderStyle", "solid", _.isString, null, null, null, "_elementBorder") @define "force2d", layerProperty(@, "force2d", "webkitTransform", false, _.isBoolean) @define "flat", layerProperty(@, "flat", "webkitTransformStyle", false, _.isBoolean) @define "backfaceVisible", layerProperty(@, "backfaceVisible", "webkitBackfaceVisibility", true, _.isBoolean) ############################################################## # Identity @define "name", default: "" get: -> name = @_getPropertyValue("name") return if name? then "#{name}" else "" set: (value) -> @_setPropertyValue("name", value) # Set the name attribute of the dom element too # See: https://github.com/koenbok/Framer/issues/63 @_element.setAttribute("name", value) ############################################################## # Matrices # matrix of layer transforms @define "matrix", get: -> if @force2d return @_matrix2d return Matrix.identity3d() .translate(@x, @y, @z) .scale(@scale) .scale(@scaleX, @scaleY, @scaleZ) .skew(@skew) .skewX(@skewX) .skewY(@skewY) .translate(0, 0, @originZ) .rotate(@rotationX, 0, 0) .rotate(0, @rotationY, 0) .rotate(0, 0, @rotationZ) .translate(0, 0, -@originZ) # matrix of layer transforms when 2d is forced @define "_matrix2d", get: -> return Matrix.identity3d() .translate(@x, @y) .scale(@scale) .scale(@scaleX, @scaleY) .skewX(@skew) .skewY(@skew) .rotate(0, 0, @rotationZ) # matrix of layer transforms with transform origin applied @define "transformMatrix", get: -> return Matrix.identity3d() .translate(@originX * @width, @originY * @height) .multiply(@matrix) .translate(-@originX * @width, -@originY * @height) # matrix of layer transforms with perspective applied @define "matrix3d", get: -> parent = @parent or @context ppm = Utils.perspectiveMatrix(parent) return Matrix.identity3d() .multiply(ppm) .multiply(@transformMatrix) ############################################################## # Border radius compatibility # Because it should be cornerRadius, we alias it here @define "cornerRadius", importable: false exportable: false # exportable: no get: -> @borderRadius set: (value) -> @borderRadius = value ############################################################## # Geometry _setGeometryValues: (input, keys) -> # If this is a number, we set everything to that number if _.isNumber(input) for k in keys if @[k] isnt input @[k] = input else # If there is nothing to work with we exit return unless input # Set every numeric value for eacht key for k in keys if _.isNumber(input[k]) and @[k] isnt input[k] @[k] = input[k] @define "point", importable: true exportable: false depends: ["width", "height", "size", "parent"] get: -> Utils.point(@) set: (input) -> input = layerPropertyPointTransformer(input, @, "point") @_setGeometryValues(input, ["x", "y"]) @define "midPoint", importable: true exportable: false depends: ["width", "height", "size", "parent", "point"] get: -> x: @midX y: @midY set: (input) -> input = layerPropertyPointTransformer(input, @, "midPoint") if not _.isNumber input input = _.pick(input, ["x", "y", "midX", "midY"]) if input.x? and not input.midX? input.midX = input.x delete input.x if input.y? and not input.midY? input.midY = input.y delete input.y @_setGeometryValues(input, ["midX", "midY"]) @define "size", importable: true exportable: false get: -> Utils.size(@) set: (input) -> @_setGeometryValues(input, ["width", "height"]) @define "frame", importable: true exportable: false get: -> Utils.frame(@) set: (input) -> @_setGeometryValues(input, ["x", "y", "width", "height"]) @define "minX", importable: true exportable: false get: -> @x set: (value) -> @x = value @define "midX", importable: true exportable: false get: -> Utils.frameGetMidX @ set: (value) -> Utils.frameSetMidX @, value @define "maxX", importable: true exportable: false get: -> Utils.frameGetMaxX @ set: (value) -> Utils.frameSetMaxX @, value @define "minY", importable: true exportable: false get: -> @y set: (value) -> @y = value @define "midY", importable: true exportable: false get: -> Utils.frameGetMidY @ set: (value) -> Utils.frameSetMidY @, value @define "maxY", importable: true exportable: false get: -> Utils.frameGetMaxY @ set: (value) -> Utils.frameSetMaxY @, value @define "constraintValues", importable: true exportable: false default: null get: -> @_getPropertyValue "constraintValues" set: (value) -> if value is null newValue = null @off "change:parent", @parentChanged Screen.off "resize", @layout else newValue = _.defaults _.clone(value), left: 0, right: null, top: 0, bottom: null, centerAnchorX: 0, centerAnchorY: 0, widthFactor: null, heightFactor: null, aspectRatioLocked: false, width: @width, height: @height if @parent? if not (@layout in @parent.listeners("change:width")) @parent.on "change:width", @layout if not (@layout in @parent.listeners("change:height")) @parent.on "change:height", @layout else if not (@layout in Screen.listeners("resize")) Screen.on "resize", @layout if not (@parentChanged in @listeners("change:parent")) @on "change:parent", @parentChanged @_setPropertyValue "constraintValues", newValue @define "htmlIntrinsicSize", importable: true exportable: true default: null get: -> @_getPropertyValue "htmlIntrinsicSize" set: (value) -> if value is null @_setPropertyValue "htmlIntrinsicSize", value else return if not _.isFinite(value.width) or not _.isFinite(value.height) @_setPropertyValue "htmlIntrinsicSize", {width: value.width, height: value.height} parentChanged: (newParent, oldParent) => if oldParent? oldParent.off "change:width", @layout oldParent.off "change:height", @layout else Screen.off "resize", @layout @constraintValues = null setParentPreservingConstraintValues: (parent) -> tmp = @constraintValues @parent = parent @constraintValues = tmp @layout() _layoutX: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @x = Utils.calculateLayoutX(parentFrame, @constraintValues, @width) @isLayouting = false _layoutY: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @y = Utils.calculateLayoutY(parentFrame, @constraintValues, @height) @isLayouting = false layout: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @frame = Utils.calculateLayoutFrame(parentFrame, @) @isLayouting = false convertPointToScreen: (point) => return Utils.convertPointToContext(point, @, false) convertPointToCanvas: (point) => return Utils.convertPointToContext(point, @, true) convertPointToLayer: (point, layer, rootContext=true) => return Utils.convertPoint(point, @, layer, rootContext) @define "canvasFrame", importable: true exportable: false get: -> return Utils.boundingFrame(@) set: (frame) -> @frame = Utils.convertFrameFromContext(frame, @, true, false) @define "screenFrame", importable: true exportable: false get: -> return Utils.boundingFrame(@, false) set: (frame) -> @frame = Utils.convertFrameFromContext(frame, @, false, false) contentFrame: -> return {x: 0, y: 0, width: 0, height: 0} unless @_children.length return Utils.frameMerge(_.map(@_children, "frame")) totalFrame: -> return Utils.frameMerge(@frame, @contentFrame()) centerFrame: -> # Get the centered frame for its parent if @parent frame = @frame Utils.frameSetMidX(frame, parseInt((@parent.width / 2.0) - @parent.borderWidth)) Utils.frameSetMidY(frame, parseInt((@parent.height / 2.0) - @parent.borderWidth)) return frame else frame = @frame Utils.frameSetMidX(frame, parseInt(@_context.innerWidth / 2.0)) Utils.frameSetMidY(frame, parseInt(@_context.innerHeight / 2.0)) return frame center: -> if @constraintValues? @constraintValues.left = null @constraintValues.right = null @constraintValues.top = null @constraintValues.bottom = null @constraintValues.centerAnchorX = 0.5 @constraintValues.centerAnchorY = 0.5 @_layoutX() @_layoutY() else @frame = @centerFrame() # Center in parent @ centerX: (offset=0) -> if @constraintValues? @constraintValues.left = null @constraintValues.right = null @constraintValues.centerAnchorX = 0.5 @_layoutX() else @x = @centerFrame().x + offset # Center x in parent @ centerY: (offset=0) -> if @constraintValues? @constraintValues.top = null @constraintValues.bottom = null @constraintValues.centerAnchorY = 0.5 @_layoutY() else @y = @centerFrame().y + offset # Center y in parent @ pixelAlign: -> @x = parseInt @x @y = parseInt @y updateForDevicePixelRatioChange: => for cssProperty in ["width", "height", "webkitTransform", "boxShadow", "textShadow", "webkitFilter", "borderRadius", "borderWidth", "fontSize", "letterSpacing", "wordSpacing", "textIndent"] @_element.style[cssProperty] = LayerStyle[cssProperty](@) updateForSizeChange: => @_elementBorder.style.borderWidth = LayerStyle["borderWidth"](@) ############################################################## # SCREEN GEOMETRY # TODO: Rotation/Skew # screenOriginX = -> # if @_parentOrContext() # return @_parentOrContext().screenOriginX() # return @originX # screenOriginY = -> # if @_parentOrContext() # return @_parentOrContext().screenOriginY() # return @originY canvasScaleX: (self=true) -> scale = 1 scale = @scale * @scaleX if self for parent in @containers(true) scale *= parent.scale if parent.scaleX? scale *= parent.scaleX return scale canvasScaleY: (self=true) -> scale = 1 scale = @scale * @scaleY if self for parent in @containers(true) scale *= parent.scale if parent.scaleY? scale *= parent.scaleY return scale screenScaleX: (self=true) -> scale = 1 scale = @scale * @scaleX if self for parent in @containers(false) scale *= parent.scale * parent.scaleX return scale screenScaleY: (self=true) -> scale = 1 scale = @scale * @scaleY if self for parent in @containers(false) scale *= parent.scale * parent.scaleY return scale screenScaledFrame: -> # TODO: Scroll position frame = x: 0 y: 0 width: @width * @screenScaleX() height: @height * @screenScaleY() layers = @containers(true) layers.push(@) layers.reverse() for parent in layers p = parentOrContext(parent) factorX = p?.screenScaleX?() ? 1 factorY = p?.screenScaleY?() ? 1 layerScaledFrame = parent.scaledFrame?() ? {x: 0, y: 0} frame.x += layerScaledFrame.x * factorX frame.y += layerScaledFrame.y * factorY return frame scaledFrame: -> # Get the scaled frame for a layer, taking into account # the transform origins. frame = @frame scaleX = @scale * @scaleX scaleY = @scale * @scaleY frame.width *= scaleX frame.height *= scaleY frame.x += (1 - scaleX) * @originX * @width frame.y += (1 - scaleY) * @originY * @height return frame ############################################################## # CSS @define "style", importable: true exportable: false get: -> @_element.style set: (value) -> _.extend @_element.style, value @emit "change:style" computedStyle: -> # This is an expensive operation getComputedStyle = document.defaultView.getComputedStyle getComputedStyle ?= window.getComputedStyle return getComputedStyle(@_element) @define "classList", importable: true exportable: false get: -> @_element.classList ############################################################## # DOM ELEMENTS _createElement: -> return if @_element? @_element = document.createElement "div" @_element.classList.add("framerLayer") _createBorderElement: -> return if @_elementBorder? @_elementBorder = document.createElement "div" @_elementBorder.style.position = "absolute" @_elementBorder.style.top = "0" @_elementBorder.style.bottom = "0" @_elementBorder.style.left = "0" @_elementBorder.style.right = "0" @_elementBorder.style.boxSizing = "border-box" @_elementBorder.style.zIndex = "1000" @_elementBorder.style.pointerEvents = "none" @_element.appendChild(@_elementBorder) _insertElement: -> @bringToFront() @_context.element.appendChild(@_element) # This method is called as soon as the @_element is part of the DOM # If layers are initialized before the DOM is complete, # the contexts calls this methods on all Layers as soon as it appends itself to the document elementInsertedIntoDocument: -> _createHTMLElementIfNeeded: -> if not @_elementHTML @_elementHTML = document.createElement "div" @_element.insertBefore @_elementHTML, @_elementBorder @define "html", get: -> @_elementHTML?.innerHTML or "" set: (value) -> # Insert some html directly into this layer. We actually create # a child node to insert it in, so it won't mess with Framers # layer hierarchy. @_createHTMLElementIfNeeded() ids = Utils.getIdAttributesFromString(value) for id in ids existingElement = document.querySelector("[id='#{id}']") if existingElement? Utils.throwInStudioOrWarnInProduction(Layer.ExistingIdMessage("html", id)) return @_elementHTML.innerHTML = value @_updateHTMLScale() # If the contents contains something else than plain text # then we turn off ignoreEvents so buttons etc will work. # if not ( # @_elementHTML.childNodes.length is 1 and # @_elementHTML.childNodes[0].nodeName is "#text") # @ignoreEvents = false @emit "change:html" _updateHTMLScale: -> return if not @_elementHTML? if not @htmlIntrinsicSize? @_elementHTML.style.zoom = @context.scale else @_elementHTML.style.transformOrigin = "0 0" @_elementHTML.style.transform = "scale(#{@context.scale * @width / @htmlIntrinsicSize.width}, #{@context.scale * @height / @htmlIntrinsicSize.height})" @_elementHTML.style.width = "#{@htmlIntrinsicSize.width}px" @_elementHTML.style.height = "#{@htmlIntrinsicSize.height}px" querySelector: (query) -> @_element.querySelector(query) querySelectorAll: (query) -> @_element.querySelectorAll(query) selectChild: (selector) -> Utils.findLayer(@descendants, selector) selectAllChildren: (selector) -> Utils.filterLayers(@descendants, selector) @select: (selector) -> Framer.CurrentContext.selectLayer(selector) @selectAll: (selector) -> Framer.CurrentContext.selectAllLayers(selector) destroy: -> # Todo: check this if @parent @parent._children = _.without(@parent._children, @) @_element.parentNode?.removeChild @_element @removeAllListeners() @_context.removeLayer(@) @_context.emit("layer:destroy", @) @_context.domEventManager.remove(@_element) ############################################################## ## COPYING copy: -> layer = @copySingle() for child in @_children copiedChild = child.copy() copiedChild.parent = layer if copiedChild isnt null return layer copySingle: -> copy = new @constructor(@props) copy.style = @style copy ############################################################## ## IMAGE _cleanupImageLoader: -> @_imageEventManager?.removeAllListeners() @_imageEventManager = null @_imageLoader = null @define "image", default: "" get: -> @_getPropertyValue "image" set: (value) -> currentValue = @_getPropertyValue "image" defaults = Defaults.getDefaults "Layer", {} isBackgroundColorDefault = @backgroundColor?.isEqual(defaults.backgroundColor) if Gradient.isGradientObject(value) @emit("change:gradient", value, currentValue) @emit("change:image", value, currentValue) @_setPropertyValue("image", value) @style["background-image"] = value.toCSS() @backgroundColor = null if isBackgroundColorDefault return if not (_.isString(value) or value is null) layerValueTypeError("image", value) if currentValue is value return @emit "load" # Unset the background color only if it’s the default color @backgroundColor = null if isBackgroundColorDefault # Set the property value @_setPropertyValue("image", value) if value in [null, ""] if @_imageLoader? @_imageEventManager.removeAllListeners() @_imageLoader.src = null @style["background-image"] = null if @_imageLoader? @emit Events.ImageLoadCancelled, @_imageLoader @_cleanupImageLoader() return # Show placeholder image on any browser that doesn't support inline pdf if _.endsWith(value.toLowerCase?(), ".pdf") and (not Utils.isWebKit() or Utils.isChrome()) @style["background-image"] = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAAVlJREFUaAXtlwEOwiAMRdF4Cr3/0fQaSre9ZFSYLCrQpSSG/FLW9v92agghXJdP3KZlCp/J2up+WiUuzMt6zNukzPDYvALCsKme1/maV8BnQHqw9/IZ6KmAz0BP9ontMwATPXafgR6s65g+A5qRlrhmBu6FhG6LXf9/+JU/YclROkVWEs/8r9FLrChb2apSqVqWZgKmtRKz9/f+CdPxoVl8CAWylcWKUQZGwfhjB3OOHcw5djDn2MH6fBNLC42yaEnyoTXB2V36+lPl<KEY>')" return imageUrl = value # Optional base image value # imageUrl = Config.baseUrl + imageUrl if @_alwaysUseImageCache is false and Utils.isLocalAssetUrl(imageUrl) imageUrl += if /\?/.test(imageUrl) then '&' else '?' imageUrl += "nocache=#{NoCacheDateKey}" # As an optimization, we will only use a loader # if something is explicitly listening to the load event if @listeners(Events.ImageLoaded, true) or @listeners(Events.ImageLoadError, true) or @listeners(Events.ImageLoadCancelled, true) @_imageLoader = new Image() @_imageLoader.name = imageUrl @_imageLoader.src = imageUrl @_imageEventManager = @_context.domEventManager.wrap(@_imageLoader) @_imageEventManager.addEventListener "load", => @style["background-image"] = "url('#{imageUrl}')" @emit Events.ImageLoaded, @_imageLoader @_cleanupImageLoader() @_imageEventManager.addEventListener "error", => @emit Events.ImageLoadError, @_imageLoader @_cleanupImageLoader() else @style["background-image"] = "url('#{imageUrl}')" @define "gradient", get: -> return layerProxiedValue(@image, @, "gradient") if Gradient.isGradientObject(@image) return null set: (value) -> # Copy semantics! if Gradient.isGradient(value) @image = new Gradient(value) else if not value and Gradient.isGradientObject(@image) @image = null ############################################################## ## HIERARCHY @define "parent", enumerable: false exportable: false importable: true get: -> @_parent or null set: (layer) -> return if layer is @_parent throw Error("Layer.parent: a layer cannot be it's own parent.") if layer is @ # Check the type if not layer instanceof Layer throw Error "Layer.parent needs to be a Layer object" # Cancel previous pending insertions Utils.domCompleteCancel(@__insertElement) # Remove from previous parent children if @_parent @_parent._children = _.pull @_parent._children, @ @_parent._element.removeChild @_element @_parent.emit "change:children", {added: [], removed: [@]} @_parent.emit "change:subLayers", {added: [], removed: [@]} # Either insert the element to the new parent element or into dom if layer layer._element.appendChild @_element layer._children.push @ layer.emit "change:children", {added: [@], removed: []} layer.emit "change:subLayers", {added: [@], removed: []} else @_insertElement() oldParent = @_parent # Set the parent @_parent = layer # Place this layer on top of its siblings @bringToFront() @emit "change:parent", @_parent, oldParent @emit "change:superLayer", @_parent, oldParent @define "children", enumerable: false exportable: false importable: false get: -> @_children.map (c) -> if c instanceof SVGLayer and c.children.length is 1 and _.startsWith(c.name, '.') return c.children[0] else return c @define "siblings", enumerable: false exportable: false importable: false get: -> # If there is no parent we need to walk through the root if @parent is null return _.filter @_context.layers, (layer) => layer isnt @ and layer.parent is null return _.without @parent.children, @ @define "descendants", enumerable: false exportable: false importable: false get: -> result = [] f = (layer) -> result.push(layer) layer.children.map(f) @children.map(f) return result addChild: (layer) -> layer.parent = @ removeChild: (layer) -> if layer not in @_children return layer.parent = null childrenWithName: (name) -> _.filter @children, (layer) -> layer.name is name siblingsWithName: (name) -> _.filter @siblingLayers, (layer) -> layer.name is name # Get all containers of this layer, including containing contexts # `toRoot` specifies if you want to bubble up across contexts, # so specifiying `false` will stop at the first context # and thus the results will never contain any context containers: (toRoot=false, result=[]) -> if @parent? result.push(@parent) return @parent.containers(toRoot, result) else if toRoot result.push(@context) return @context.containers(true, result) return result ancestors: -> return @containers() root: -> return @ if @parent is null return _.last(@ancestors()) childrenAbove: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).y < point.y childrenBelow: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).y > point.y childrenLeft: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).x < point.x childrenRight: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).x > point.x _parentOrContext: -> if @parent return @parent if @_context._parent return @_context._parent ############################################################## # Backwards superLayer and children compatibility @define "superLayer", enumerable: false exportable: false importable: false get: -> @parent set: (value) -> @parent = value @define "subLayers", enumerable: false exportable: false importable: false get: -> @children @define "siblingLayers", enumerable: false exportable: false importable: false get: -> @siblings addSubLayer: (layer) -> @addChild(layer) removeSubLayer: (layer) -> @removeChild(layer) subLayersByName: (name) -> @childrenWithName(name) siblingLayersByName: (name) -> @siblingsWithName(name) subLayersAbove: (point, originX=0, originY=0) -> @childrenAbove(point, originX, originY) subLayersBelow: (point, originX=0, originY=0) -> @childrenBelow(point, originX, originY) subLayersLeft: (point, originX=0, originY=0) -> @childrenLeft(point, originX, originY) subLayersRight: (point, originX=0, originY=0) -> @childrenRight(point, originX, originY) ############################################################## ## ANIMATION animate: (properties, options={}) -> # If the properties are a string, we assume it's a state name if _.isString(properties) stateName = properties # Support options as an object options = options.options if options.options? return @states.machine.switchTo(stateName, options) # We need to clone the properties so we don't modify them unexpectedly properties = _.clone(properties) # Support the old properties syntax, we add all properties top level and # move the options into an options property. if properties.properties? options = properties properties = options.properties delete options.properties # With the new api we treat the properties as animatable properties, and use # the special options keyword for animation options. if properties.options? options = _.defaults({}, options, properties.options) delete properties.options # Merge the animation options with the default animation options for this layer options = _.defaults({}, options, @animationOptions) options.start ?= true animation = new Animation(@, properties, options) animation.start() if options.start return animation stateCycle: (args...) -> states = _.flatten(args) if _.isObject(_.last(states)) options = states.pop() @animate(@states.machine.next(states), options) stateSwitch: (stateName, options={}) -> unless stateName? throw new Error("Missing required argument 'stateName' in stateSwitch()") return @animate(stateName, options) if options.animate is true return @animate(stateName, _.defaults({}, options, {instant: true})) animations: (includePending=false) -> # Current running animations on this layer _.filter @_context.animations, (animation) => return false unless (animation.layer is @) return includePending or not animation.isPending animatingProperties: -> properties = {} for animation in @animations() for propertyName in animation.animatingProperties() properties[propertyName] = animation return properties @define "isAnimating", enumerable: false exportable: false get: -> @animations().length isnt 0 animateStop: -> _.invokeMap(@animations(), "stop") @_draggable?.animateStop() ############################################################## ## INDEX ORDERING bringToFront: -> maxIndex = null siblings = @parent?._children ? @context._layers return if siblings.count <= 1 for layer in siblings continue if layer is @ maxIndex ?= layer.index if layer.index > maxIndex maxIndex = layer.index if maxIndex? @index = maxIndex + 1 sendToBack: -> minIndex = null siblings = @parent?._children ? @context._layers return if siblings.count <= 1 for layer in siblings continue if layer is @ minIndex ?= layer.index if layer.index < minIndex minIndex = layer.index if minIndex? @index = minIndex - 1 placeBefore: (layer) -> return if layer not in @siblingLayers for l in @siblingLayers if l.index <= layer.index l.index -= 1 @index = layer.index + 1 placeBehind: (layer) -> return if layer not in @siblingLayers for l in @siblingLayers if l.index >= layer.index l.index += 1 @index = layer.index - 1 ############################################################## ## STATES @define "states", enumerable: false exportable: false importable: false get: -> @_states ?= new LayerStates(@) return @_states set: (states) -> @states.machine.reset() _.extend(@states, states) @define "stateNames", enumerable: false exportable: false importable: false get: -> @states.machine.stateNames ############################################################################# ## Draggable, Pinchable @define "draggable", importable: false exportable: false get: -> @_draggable ?= new LayerDraggable(@) set: (value) -> @draggable.enabled = value if _.isBoolean(value) @define "pinchable", importable: false exportable: false get: -> @_pinchable ?= new LayerPinchable(@) set: (value) -> @pinchable.enabled = value if _.isBoolean(value) ############################################################## ## SCROLLING @define "scrollFrame", importable: false get: -> frame = x: @scrollX y: @scrollY width: @width height: @height set: (frame) -> @scrollX = frame.x @scrollY = frame.y @define "scrollX", get: -> @_element.scrollLeft set: (value) -> layerValueTypeError("scrollX", value) if not _.isNumber(value) @_element.scrollLeft = value @define "scrollY", get: -> @_element.scrollTop set: (value) -> layerValueTypeError("scrollY", value) if not _.isNumber(value) @_element.scrollTop = value ############################################################## ## EVENTS @define "_domEventManager", get: -> @_context.domEventManager.wrap(@_element) emit: (eventName, args...) -> # If this layer has a parent draggable view and its position moved # while dragging we automatically cancel click events. This is what # you expect when you add a button to a scroll content layer. We only # want to do this if this layer is not draggable itself because that # would break nested ScrollComponents. if @_cancelClickEventInDragSession and not @_draggable if eventName in [ Events.Click, Events.Tap, Events.TapStart, Events.TapEnd, Events.LongPress, Events.LongPressStart, Events.LongPressEnd] # If we dragged any layer, we should cancel click events return if LayerDraggable._globalDidDrag is true # See if we need to convert coordinates for this event. Mouse events by # default have the screen coordinates so we make sure that event.point and # event.contextPoint always have the proper coordinates. if args[0]?.clientX? or args[0]?.clientY? event = args[0] point = {x: event.clientX, y: event.clientY} event.point = Utils.convertPointFromContext(point, @, true) event.contextPoint = Utils.convertPointFromContext(point, @context, true) if event.touches? for touch in event.touches point = {x: touch.clientX, y: touch.clientY} touch.point = Utils.convertPointFromContext(point, @, true) touch.contextPoint = Utils.convertPointFromContext(point, @context, true) # Always scope the event this to the layer and pass the layer as # last argument for every event. super(eventName, args..., @) once: (eventName, listener) => super(eventName, listener) @_addListener(eventName, listener) addListener: (eventName, listener) => throw Error("Layer.on needs a valid event name") unless eventName throw Error("Layer.on needs an event listener") unless listener super(eventName, listener) @_addListener(eventName, listener) removeListener: (eventName, listener) -> throw Error("Layer.off needs a valid event name") unless eventName super(eventName, listener) @_removeListener(eventName, listener) _addListener: (eventName, listener) -> # Make sure we stop ignoring events once we add a user event listener if not _.startsWith(eventName, "change:") @ignoreEvents = false # If this is a dom event, we want the actual dom node to let us know # when it gets triggered, so we can emit the event through the system. if Utils.domValidEvent(@_element, eventName) or eventName in _.values(Gestures) if not @_domEventManager.listeners(eventName).length @_domEventManager.addEventListener eventName, (event) => @emit(eventName, event) _removeListener: (eventName, listener) -> # Do cleanup for dom events if this is the last one of it's type. # We are assuming we're the only ones adding dom events to the manager. if not @listeners(eventName).length @_domEventManager.removeAllListeners(eventName) _parentDraggableLayer: -> for layer in @ancestors() return layer if layer._draggable?.enabled return null on: @::addListener off: @::removeListener ############################################################## ## EVENT HELPERS onClick: (cb) -> @on(Events.Click, cb) onDoubleClick: (cb) -> @on(Events.DoubleClick, cb) onScrollStart: (cb) -> @on(Events.ScrollStart, cb) onScroll: (cb) -> @on(Events.Scroll, cb) onScrollEnd: (cb) -> @on(Events.ScrollEnd, cb) onScrollAnimationDidStart: (cb) -> @on(Events.ScrollAnimationDidStart, cb) onScrollAnimationDidEnd: (cb) -> @on(Events.ScrollAnimationDidEnd, cb) onTouchStart: (cb) -> @on(Events.TouchStart, cb) onTouchEnd: (cb) -> @on(Events.TouchEnd, cb) onTouchMove: (cb) -> @on(Events.TouchMove, cb) onMouseUp: (cb) -> @on(Events.MouseUp, cb) onMouseDown: (cb) -> @on(Events.MouseDown, cb) onMouseOver: (cb) -> @on(Events.MouseOver, cb) onMouseOut: (cb) -> @on(Events.MouseOut, cb) onMouseEnter: (cb) -> @on(Events.MouseEnter, cb) onMouseLeave: (cb) -> @on(Events.MouseLeave, cb) onMouseMove: (cb) -> @on(Events.MouseMove, cb) onMouseWheel: (cb) -> @on(Events.MouseWheel, cb) onAnimationStart: (cb) -> @on(Events.AnimationStart, cb) onAnimationStop: (cb) -> @on(Events.AnimationStop, cb) onAnimationEnd: (cb) -> @on(Events.AnimationEnd, cb) onAnimationDidStart: (cb) -> @on(Events.AnimationDidStart, cb) # Deprecated onAnimationDidStop: (cb) -> @on(Events.AnimationDidStop, cb) # Deprecated onAnimationDidEnd: (cb) -> @on(Events.AnimationDidEnd, cb) # Deprecated onImageLoaded: (cb) -> @on(Events.ImageLoaded, cb) onImageLoadError: (cb) -> @on(Events.ImageLoadError, cb) onImageLoadCancelled: (cb) -> @on(Events.ImageLoadCancelled, cb) onMove: (cb) -> @on(Events.Move, cb) onDragStart: (cb) -> @on(Events.DragStart, cb) onDragWillMove: (cb) -> @on(Events.DragWillMove, cb) onDragMove: (cb) -> @on(Events.DragMove, cb) onDragDidMove: (cb) -> @on(Events.DragDidMove, cb) onDrag: (cb) -> @on(Events.Drag, cb) onDragEnd: (cb) -> @on(Events.DragEnd, cb) onDragAnimationStart: (cb) -> @on(Events.DragAnimationStart, cb) onDragAnimationEnd: (cb) -> @on(Events.DragAnimationEnd, cb) onDirectionLockStart: (cb) -> @on(Events.DirectionLockStart, cb) onStateSwitchStart: (cb) -> @on(Events.StateSwitchStart, cb) onStateSwitchStop: (cb) -> @on(Events.StateSwitchStop, cb) onStateSwitchEnd: (cb) -> @on(Events.StateSwitchEnd, cb) onStateWillSwitch: (cb) -> @on(Events.StateSwitchStart, cb) # Deprecated onStateDidSwitch: (cb) -> @on(Events.StateSwitchEnd, cb) # Deprecated # Gestures # Tap onTap: (cb) -> @on(Events.Tap, cb) onTapStart: (cb) -> @on(Events.TapStart, cb) onTapEnd: (cb) -> @on(Events.TapEnd, cb) onDoubleTap: (cb) -> @on(Events.DoubleTap, cb) # Force Tap onForceTap: (cb) -> @on(Events.ForceTap, cb) onForceTapChange: (cb) -> @on(Events.ForceTapChange, cb) onForceTapStart: (cb) -> @on(Events.ForceTapStart, cb) onForceTapEnd: (cb) -> @on(Events.ForceTapEnd, cb) # Press onLongPress: (cb) -> @on(Events.LongPress, cb) onLongPressStart: (cb) -> @on(Events.LongPressStart, cb) onLongPressEnd: (cb) -> @on(Events.LongPressEnd, cb) # Swipe onSwipe: (cb) -> @on(Events.Swipe, cb) onSwipeStart: (cb) -> @on(Events.SwipeStart, cb) onSwipeEnd: (cb) -> @on(Events.SwipeEnd, cb) onSwipeUp: (cb) -> @on(Events.SwipeUp, cb) onSwipeUpStart: (cb) -> @on(Events.SwipeUpStart, cb) onSwipeUpEnd: (cb) -> @on(Events.SwipeUpEnd, cb) onSwipeDown: (cb) -> @on(Events.SwipeDown, cb) onSwipeDownStart: (cb) -> @on(Events.SwipeDownStart, cb) onSwipeDownEnd: (cb) -> @on(Events.SwipeDownEnd, cb) onSwipeLeft: (cb) -> @on(Events.SwipeLeft, cb) onSwipeLeftStart: (cb) -> @on(Events.SwipeLeftStart, cb) onSwipeLeftEnd: (cb) -> @on(Events.SwipeLeftEnd, cb) onSwipeRight: (cb) -> @on(Events.SwipeRight, cb) onSwipeRightStart: (cb) -> @on(Events.SwipeRightStart, cb) onSwipeRightEnd: (cb) -> @on(Events.SwipeRightEnd, cb) # Pan onPan: (cb) -> @on(Events.Pan, cb) onPanStart: (cb) -> @on(Events.PanStart, cb) onPanEnd: (cb) -> @on(Events.PanEnd, cb) onPanLeft: (cb) -> @on(Events.PanLeft, cb) onPanRight: (cb) -> @on(Events.PanRight, cb) onPanUp: (cb) -> @on(Events.PanUp, cb) onPanDown: (cb) -> @on(Events.PanDown, cb) # Pinch onPinch: (cb) -> @on(Events.Pinch, cb) onPinchStart: (cb) -> @on(Events.PinchStart, cb) onPinchEnd: (cb) -> @on(Events.PinchEnd, cb) # Scale onScale: (cb) -> @on(Events.Scale, cb) onScaleStart: (cb) -> @on(Events.ScaleStart, cb) onScaleEnd: (cb) -> @on(Events.ScaleEnd, cb) # Rotate onRotate: (cb) -> @on(Events.Rotate, cb) onRotateStart: (cb) -> @on(Events.RotateStart, cb) onRotateEnd: (cb) -> @on(Events.RotateEnd, cb) ############################################################## ## HINT _showHint: (targetLayer) -> # If this layer isnt visible we can just exit return if not @visible return if @opacity is 0 # If we don't need to show a hint exit but pass to children unless @shouldShowHint(targetLayer) layer._showHint(targetLayer) for layer in @children return null # Figure out the frame we want to show the hint in, if any of the # parent layers clip, we need to intersect the rectangle with it. frame = @canvasFrame for parent in @ancestors() if parent.clip frame = Utils.frameIntersection(frame, parent.canvasFrame) if not frame return # Show the actual hint @showHint(frame) # Tell the children to show their hints _.invokeMap(@children, "_showHint") willSeemToDoSomething: -> if @ignoreEvents return false if @_draggable if @_draggable.isDragging is false and @_draggable.isMoving is false return false return true shouldShowHint: -> # Don't show hints if the layer is not interactive if @ignoreEvents is true return false # Don't show any hints while we are animating if @isAnimating return false for parent in @ancestors() return false if parent.isAnimating # Don't show hints if there is a draggable that cannot be dragged. if @_draggable and @_draggable.horizontal is false and @_draggable.vertical is false return false # Don't show hint if this layer is invisible return false if @opacity is 0 # If we don't ignore events on this layer, make sure the layer is listening to # an interactive event so there is a decent change something is happening after # we click it. for eventName in @listenerEvents() return true if Events.isInteractive(eventName) return false showHint: (highlightFrame) -> # Don't show anything if this element covers the entire screen # if Utils.frameInFrame(@context.canvasFrame, highlightFrame) # return # Start an animation with a rectangle fading out over time layer = new Layer frame: Utils.frameInset(highlightFrame, -1) backgroundColor: null borderColor: Framer.Defaults.Hints.color borderRadius: @borderRadius * Utils.average([@canvasScaleX(), @canvasScaleY()]) borderWidth: 3 # Only show outlines for draggables if @_draggable layer.backgroundColor = null # Only show outlines if a highlight is fullscreen if Utils.frameInFrame(@context.canvasFrame, highlightFrame) layer.backgroundColor = null animation = layer.animate properties: {opacity: 0} curve: "ease-out" time: 0.5 animation.onAnimationEnd -> layer.destroy() ############################################################## ## DESCRIPTOR toName: -> return name if @name return @__framerInstanceInfo?.name or "" toInspect: (constructor) -> constructor ?= @constructor.name name = if @name then "name:#{@name} " else "" return "<#{constructor} #{@toName()} id:#{@id} #{name} (#{Utils.roundWhole(@x)}, #{Utils.roundWhole(@y)}) #{Utils.roundWhole(@width)}x#{Utils.roundWhole(@height)}>"
true
{_} = require "./Underscore" Utils = require "./Utils" {Config} = require "./Config" {Events} = require "./Events" {Defaults} = require "./Defaults" {BaseClass} = require "./BaseClass" {EventEmitter} = require "./EventEmitter" {Color} = require "./Color" {Gradient} = require "./Gradient" {Matrix} = require "./Matrix" {Animation} = require "./Animation" {LayerStyle} = require "./LayerStyle" {LayerStates} = require "./LayerStates" {LayerDraggable} = require "./LayerDraggable" {LayerPinchable} = require "./LayerPinchable" {Gestures} = require "./Gestures" {LayerPropertyProxy} = require "./LayerPropertyProxy" NoCacheDateKey = Date.now() delayedStyles = ["webkitTransform", "webkitFilter", "webkitPerspectiveOrigin", "webkitTransformOrigin", "webkitBackdropFilter"] layerValueTypeError = (name, value) -> throw new Error("Layer.#{name}: value '#{value}' of type '#{typeof(value)}' is not valid") layerProperty = (obj, name, cssProperty, fallback, validator, transformer, options={}, set, targetElement, includeMainElement, useSubpropertyProxy) -> result = default: fallback get: -> # console.log "Layer.#{name}.get #{@_properties[name]}", @_properties.hasOwnProperty(name) value = @_properties[name] if @_properties.hasOwnProperty(name) value ?= fallback return layerProxiedValue(value, @, name) if useSubpropertyProxy return value set: (value) -> # console.log "#{@constructor.name}.#{name}.set #{value} current:#{@[name]}", targetElement # Convert the value value = transformer(value, @, name) if transformer oldValue = @_properties[name] # Return unless we get a new value return if value is oldValue if value and validator and not validator(value) layerValueTypeError(name, value) @_properties[name] = value if cssProperty isnt null elementContainer = @ if cssProperty in @_stylesAppliedToParent elementContainer = @_parent @_parent._properties[name] = fallback mainElement = elementContainer._element if includeMainElement or not targetElement subElement = elementContainer[targetElement] if targetElement? if name is cssProperty and not LayerStyle[cssProperty]? mainElement?.style[cssProperty] = @_properties[name] subElement?.style[cssProperty] = @_properties[name] # These values are set multiple times during applyDefaults, so ignore them here, and set the style in the constructor else if not @__applyingDefaults or (cssProperty not in delayedStyles) style = LayerStyle[cssProperty](@) mainElement?.style[cssProperty] = style subElement?.style[cssProperty] = style set?(@, value) # We try to not send any events while we run the constructor, it just # doesn't make sense, because no one can listen to use yet. return if @__constructor @emit("change:#{name}", value, oldValue) @emit("change:point", value) if name in ["x", "y"] @emit("change:size", value) if name in ["width", "height"] @emit("change:frame", value) if name in ["x", "y", "width", "height"] @emit("change:rotation", value) if name in ["rotationZ"] result = _.extend(result, options) exports.layerProperty = layerProperty # Use this to wrap property values in a Proxy so setting sub-properties # will also trigger updates on the layer. # Because we’re not fully on ES6, we can’t use Proxy, so use our own wrapper. layerProxiedValue = (value, layer, property) -> return value unless _.isObject(value) new LayerPropertyProxy value, (proxiedValue, subProperty, subValue) -> proxiedValue[subProperty] = subValue layer[property] = proxiedValue exports.layerProxiedValue = layerProxiedValue layerPropertyPointTransformer = (value, layer, property) -> if _.isFunction(value) value = value(layer, property) return value layerPropertyIgnore = (options, propertyName, properties) -> return options unless options.hasOwnProperty(propertyName) for p in properties if options.hasOwnProperty(p) delete options[propertyName] return options return options asBorderRadius = (value) -> return value if _.isNumber(value) if _.isString(value) if not _.endsWith(value, "%") console.error "Layer.borderRadius only correctly supports percentages in strings" return value return 0 if not _.isObject(value) result = {} isValidObject = false for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"] isValidObject ||= _.has(value, key) result[key] = value[key] ? 0 return if not isValidObject then 0 else result asBorderWidth = (value) -> return value if _.isNumber(value) return 0 if not _.isObject(value) result = {} isValidObject = false for key in ["left", "right", "bottom", "top"] isValidObject ||= _.has(value, key) result[key] = value[key] ? 0 return if not isValidObject then 0 else result parentOrContext = (layerOrContext) -> if layerOrContext.parent? return layerOrContext.parent else return layerOrContext.context proxiedShadowValue = (layer, value, index = 0) -> v = _.defaults _.clone(value), Framer.Defaults.Shadow if v.color isnt null v?.color = new Color(v.color) layerProxiedValue(v, layer, "shadow#{index+1}") class exports.Layer extends BaseClass constructor: (options={}) -> # Make sure we never call the constructor twice throw Error("Layer.constructor #{@toInspect()} called twice") if @__constructorCalled @__constructorCalled = true @__constructor = true # Set needed private variables @_properties = {} @_style = {} @_children = [] @_stylesAppliedToParent ?= [] # Special power setting for 2d rendering path. Only enable this # if you know what you are doing. See LayerStyle for more info. @_prefer2d = false @_alwaysUseImageCache = false # Private setting for canceling of click event if wrapped in moved draggable @_cancelClickEventInDragSession = true # We have to create the element before we set the defaults @_createElement() if options.createHTMLElement @_createHTMLElementIfNeeded() # Create border element @_createBorderElement() # Sanitize calculated property setters so direct properties always win layerPropertyIgnore(options, "point", ["x", "y"]) layerPropertyIgnore(options, "midPoint", ["midX", "midY"]) layerPropertyIgnore(options, "size", ["width", "height"]) layerPropertyIgnore(options, "frame", ["x", "y", "width", "height"]) # Backwards compatibility for superLayer if not options.hasOwnProperty("parent") and options.hasOwnProperty("superLayer") options.parent = options.superLayer delete options.superLayer @__applyingDefaults = true super Defaults.getDefaults("Layer", options) delete @__applyingDefaults for cssProperty in delayedStyles element = @_element if cssProperty in @_stylesAppliedToParent element = @_parent._element element.style[cssProperty] = LayerStyle[cssProperty](@) # Add this layer to the current context @_context.addLayer(@) @_id = @_context.layerCounter # Insert the layer into the dom or the parent element if not options.parent @_insertElement() if not options.shadow else @parent = options.parent # Set some calculated properties # Make sure we set the right index if options.hasOwnProperty("index") @index = options.index # x and y always win from point, frame or size for p in ["x", "y", "width", "height"] if options.hasOwnProperty(p) @[p] = options[p] @_context.emit("layer:create", @) # Make sure the layer is always centered @label = @label delete @__constructor @updateShadowStyle() @onChange("size", @updateForSizeChange) @ExistingIdMessage: (type, id) -> "Can not set #{type}: There's already an element with id '#{id}' in this document'" ############################################################## # Properties # Readonly context property @define "context", get: -> @_context @define "label", get: -> @_label set: (value) -> return if value is @_label @_label = value Utils.labelLayer(@, @_label) # A placeholder for layer bound properties defined by the user: @define "custom", @simpleProperty("custom", undefined) # Default animation options for every animation of this layer @define "animationOptions", @simpleProperty("animationOptions", {}) # Behaviour properties @define "ignoreEvents", layerProperty(@, "ignoreEvents", "pointerEvents", true, _.isBoolean) # Css properties @define "width", layerProperty(@, "width", "width", 100, _.isNumber, null, {}, (layer, value) -> return if not layer.constraintValues? or layer.isLayouting layer.constraintValues.width = value layer.constraintValues.aspectRatioLocked = false layer.constraintValues.widthFactor = null layer._layoutX() ) @define "height", layerProperty(@, "height", "height", 100, _.isNumber, null, {}, (layer, value) -> return if not layer.constraintValues? or layer.isLayouting layer.constraintValues.height = value layer.constraintValues.aspectRatioLocked = false layer.constraintValues.heightFactor = null layer._layoutY() ) @define "visible", layerProperty(@, "visible", "display", true, _.isBoolean) @define "opacity", layerProperty(@, "opacity", "opacity", 1, _.isNumber, parseFloat) @define "index", layerProperty(@, "index", "zIndex", 0, _.isNumber, null, {importable: false, exportable: false}) @define "clip", layerProperty(@, "clip", "overflow", false, _.isBoolean, null, {}, null, "_elementHTML", true) @define "scrollHorizontal", layerProperty @, "scrollHorizontal", "overflowX", false, _.isBoolean, null, {}, (layer, value) -> layer.ignoreEvents = false if value is true @define "scrollVertical", layerProperty @, "scrollVertical", "overflowY", false, _.isBoolean, null, {}, (layer, value) -> layer.ignoreEvents = false if value is true @define "scroll", get: -> @scrollHorizontal is true or @scrollVertical is true set: (value) -> @scrollHorizontal = @scrollVertical = value # Matrix properties @define "x", layerProperty(@, "x", "webkitTransform", 0, _.isNumber, layerPropertyPointTransformer, {depends: ["width", "height"]}, (layer) -> return if layer.isLayouting layer.constraintValues = null ) @define "y", layerProperty(@, "y", "webkitTransform", 0, _.isNumber, layerPropertyPointTransformer, {depends: ["width", "height"]}, (layer) -> return if layer.isLayouting layer.constraintValues = null ) @define "z", layerProperty(@, "z", "webkitTransform", 0, _.isNumber) @define "scaleX", layerProperty(@, "scaleX", "webkitTransform", 1, _.isNumber) @define "scaleY", layerProperty(@, "scaleY", "webkitTransform", 1, _.isNumber) @define "scaleZ", layerProperty(@, "scaleZ", "webkitTransform", 1, _.isNumber) @define "scale", layerProperty(@, "scale", "webkitTransform", 1, _.isNumber) @define "skewX", layerProperty(@, "skewX", "webkitTransform", 0, _.isNumber) @define "skewY", layerProperty(@, "skewY", "webkitTransform", 0, _.isNumber) @define "skew", layerProperty(@, "skew", "webkitTransform", 0, _.isNumber) # @define "scale", # get: -> (@scaleX + @scaleY + @scaleZ) / 3.0 # set: (value) -> @scaleX = @scaleY = @scaleZ = value @define "originX", layerProperty(@, "originX", "webkitTransformOrigin", 0.5, _.isNumber) @define "originY", layerProperty(@, "originY", "webkitTransformOrigin", 0.5, _.isNumber) @define "originZ", layerProperty(@, "originZ", null, 0, _.isNumber) @define "perspective", layerProperty(@, "perspective", "webkitPerspective", 0, ((v) -> Utils.webkitPerspectiveForValue(v) isnt null)) @define "perspectiveOriginX", layerProperty(@, "perspectiveOriginX", "webkitPerspectiveOrigin", 0.5, _.isNumber) @define "perspectiveOriginY", layerProperty(@, "perspectiveOriginY", "webkitPerspectiveOrigin", 0.5, _.isNumber) @define "rotationX", layerProperty(@, "rotationX", "webkitTransform", 0, _.isNumber) @define "rotationY", layerProperty(@, "rotationY", "webkitTransform", 0, _.isNumber) @define "rotationZ", layerProperty(@, "rotationZ", "webkitTransform", 0, _.isNumber) @define "rotation", #exportable: false get: -> @rotationZ set: (value) -> @rotationZ = value # Filter properties @define "blur", layerProperty(@, "blur", "webkitFilter", 0, _.isNumber) @define "brightness", layerProperty(@, "brightness", "webkitFilter", 100, _.isNumber) @define "saturate", layerProperty(@, "saturate", "webkitFilter", 100, _.isNumber) @define "hueRotate", layerProperty(@, "hueRotate", "webkitFilter", 0, _.isNumber) @define "contrast", layerProperty(@, "contrast", "webkitFilter", 100, _.isNumber) @define "invert", layerProperty(@, "invert", "webkitFilter", 0, _.isNumber) @define "grayscale", layerProperty(@, "grayscale", "webkitFilter", 0, _.isNumber) @define "sepia", layerProperty(@, "sepia", "webkitFilter", 0, _.isNumber) @define "blending", layerProperty(@, "blending", "mixBlendMode", null, _.isString) @define "backgroundBlur", layerProperty(@, "backgroundBlur", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundBrightness", layerProperty(@, "backgroundBrightness", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundSaturate", layerProperty(@, "backgroundSaturate", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundHueRotate", layerProperty(@, "backgroundHueRotate", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundContrast", layerProperty(@, "backgroundContrast", "webkitBackdropFilter", 100, _.isNumber) @define "backgroundInvert", layerProperty(@, "backgroundInvert", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundGrayscale", layerProperty(@, "backgroundGrayscale", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundSepia", layerProperty(@, "backgroundSepia", "webkitBackdropFilter", 0, _.isNumber) @define "backgroundSize", layerProperty(@, "backgroundSize", "backgroundSize", "fill", _.isString) for i in [0..8] do (i) => @define "shadow#{i+1}", exportable: false depends: ["shadowX", "shadowY", "shadowBlur", "shadowSpread", "shadowColor", "shadowType"] get: -> @shadows ?= [] @shadows[i] ?= proxiedShadowValue(@, {}, i) @shadows[i] set: (value) -> @shadows ?= [] @shadows[i] = proxiedShadowValue(@, value, i) @updateShadowStyle() updateShadowsProperty: (prop, value) -> @shadows ?= [] if (@shadows.filter (s) -> s isnt null).length is 0 @shadows[0] = proxiedShadowValue(@, Framer.Defaults.Shadow) for shadow in @shadows shadow?[prop] = value @updateShadowStyle() # Shadow properties for shadowProp in ["X", "Y", "Blur", "Spread", "Color", "Type"] do (shadowProp) => @define "shadow#{shadowProp}", get: -> return null if not @shadows? or @shadows.length is 0 @shadows[0][shadowProp.toLowerCase()] set: (value) -> @updateShadowsProperty(shadowProp.toLowerCase(), value) @define "shadows", default: null get: -> @_getPropertyValue("shadows") set: (value) -> value ?= [] shadows = [] for shadow, index in value if shadow is null shadows.push null else shadows.push proxiedShadowValue(@, shadow, index) @_setPropertyValue("shadows", shadows) @updateShadowStyle() updateShadowStyle: -> return if @__constructor @_element.style.boxShadow = LayerStyle["boxShadow"](@) @_element.style.textShadow = LayerStyle["textShadow"](@) @_element.style.webkitFilter = LayerStyle["webkitFilter"](@) # Color properties @define "backgroundColor", layerProperty(@, "backgroundColor", "backgroundColor", null, Color.validColorValue, Color.toColor) @define "color", layerProperty(@, "color", "color", null, Color.validColorValue, Color.toColor, null, null, "_elementHTML", true) # Border properties @define "borderRadius", layerProperty(@, "borderRadius", "borderRadius", 0, null, asBorderRadius, null, null, "_elementBorder", true, true) @define "borderColor", layerProperty(@, "borderColor", "borderColor", null, Color.validColorValue, Color.toColor, null, null, "_elementBorder") @define "borderWidth", layerProperty(@, "borderWidth", "borderWidth", 0, null, asBorderWidth, null, null, "_elementBorder", false, true) @define "borderStyle", layerProperty(@, "borderStyle", "borderStyle", "solid", _.isString, null, null, null, "_elementBorder") @define "force2d", layerProperty(@, "force2d", "webkitTransform", false, _.isBoolean) @define "flat", layerProperty(@, "flat", "webkitTransformStyle", false, _.isBoolean) @define "backfaceVisible", layerProperty(@, "backfaceVisible", "webkitBackfaceVisibility", true, _.isBoolean) ############################################################## # Identity @define "name", default: "" get: -> name = @_getPropertyValue("name") return if name? then "#{name}" else "" set: (value) -> @_setPropertyValue("name", value) # Set the name attribute of the dom element too # See: https://github.com/koenbok/Framer/issues/63 @_element.setAttribute("name", value) ############################################################## # Matrices # matrix of layer transforms @define "matrix", get: -> if @force2d return @_matrix2d return Matrix.identity3d() .translate(@x, @y, @z) .scale(@scale) .scale(@scaleX, @scaleY, @scaleZ) .skew(@skew) .skewX(@skewX) .skewY(@skewY) .translate(0, 0, @originZ) .rotate(@rotationX, 0, 0) .rotate(0, @rotationY, 0) .rotate(0, 0, @rotationZ) .translate(0, 0, -@originZ) # matrix of layer transforms when 2d is forced @define "_matrix2d", get: -> return Matrix.identity3d() .translate(@x, @y) .scale(@scale) .scale(@scaleX, @scaleY) .skewX(@skew) .skewY(@skew) .rotate(0, 0, @rotationZ) # matrix of layer transforms with transform origin applied @define "transformMatrix", get: -> return Matrix.identity3d() .translate(@originX * @width, @originY * @height) .multiply(@matrix) .translate(-@originX * @width, -@originY * @height) # matrix of layer transforms with perspective applied @define "matrix3d", get: -> parent = @parent or @context ppm = Utils.perspectiveMatrix(parent) return Matrix.identity3d() .multiply(ppm) .multiply(@transformMatrix) ############################################################## # Border radius compatibility # Because it should be cornerRadius, we alias it here @define "cornerRadius", importable: false exportable: false # exportable: no get: -> @borderRadius set: (value) -> @borderRadius = value ############################################################## # Geometry _setGeometryValues: (input, keys) -> # If this is a number, we set everything to that number if _.isNumber(input) for k in keys if @[k] isnt input @[k] = input else # If there is nothing to work with we exit return unless input # Set every numeric value for eacht key for k in keys if _.isNumber(input[k]) and @[k] isnt input[k] @[k] = input[k] @define "point", importable: true exportable: false depends: ["width", "height", "size", "parent"] get: -> Utils.point(@) set: (input) -> input = layerPropertyPointTransformer(input, @, "point") @_setGeometryValues(input, ["x", "y"]) @define "midPoint", importable: true exportable: false depends: ["width", "height", "size", "parent", "point"] get: -> x: @midX y: @midY set: (input) -> input = layerPropertyPointTransformer(input, @, "midPoint") if not _.isNumber input input = _.pick(input, ["x", "y", "midX", "midY"]) if input.x? and not input.midX? input.midX = input.x delete input.x if input.y? and not input.midY? input.midY = input.y delete input.y @_setGeometryValues(input, ["midX", "midY"]) @define "size", importable: true exportable: false get: -> Utils.size(@) set: (input) -> @_setGeometryValues(input, ["width", "height"]) @define "frame", importable: true exportable: false get: -> Utils.frame(@) set: (input) -> @_setGeometryValues(input, ["x", "y", "width", "height"]) @define "minX", importable: true exportable: false get: -> @x set: (value) -> @x = value @define "midX", importable: true exportable: false get: -> Utils.frameGetMidX @ set: (value) -> Utils.frameSetMidX @, value @define "maxX", importable: true exportable: false get: -> Utils.frameGetMaxX @ set: (value) -> Utils.frameSetMaxX @, value @define "minY", importable: true exportable: false get: -> @y set: (value) -> @y = value @define "midY", importable: true exportable: false get: -> Utils.frameGetMidY @ set: (value) -> Utils.frameSetMidY @, value @define "maxY", importable: true exportable: false get: -> Utils.frameGetMaxY @ set: (value) -> Utils.frameSetMaxY @, value @define "constraintValues", importable: true exportable: false default: null get: -> @_getPropertyValue "constraintValues" set: (value) -> if value is null newValue = null @off "change:parent", @parentChanged Screen.off "resize", @layout else newValue = _.defaults _.clone(value), left: 0, right: null, top: 0, bottom: null, centerAnchorX: 0, centerAnchorY: 0, widthFactor: null, heightFactor: null, aspectRatioLocked: false, width: @width, height: @height if @parent? if not (@layout in @parent.listeners("change:width")) @parent.on "change:width", @layout if not (@layout in @parent.listeners("change:height")) @parent.on "change:height", @layout else if not (@layout in Screen.listeners("resize")) Screen.on "resize", @layout if not (@parentChanged in @listeners("change:parent")) @on "change:parent", @parentChanged @_setPropertyValue "constraintValues", newValue @define "htmlIntrinsicSize", importable: true exportable: true default: null get: -> @_getPropertyValue "htmlIntrinsicSize" set: (value) -> if value is null @_setPropertyValue "htmlIntrinsicSize", value else return if not _.isFinite(value.width) or not _.isFinite(value.height) @_setPropertyValue "htmlIntrinsicSize", {width: value.width, height: value.height} parentChanged: (newParent, oldParent) => if oldParent? oldParent.off "change:width", @layout oldParent.off "change:height", @layout else Screen.off "resize", @layout @constraintValues = null setParentPreservingConstraintValues: (parent) -> tmp = @constraintValues @parent = parent @constraintValues = tmp @layout() _layoutX: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @x = Utils.calculateLayoutX(parentFrame, @constraintValues, @width) @isLayouting = false _layoutY: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @y = Utils.calculateLayoutY(parentFrame, @constraintValues, @height) @isLayouting = false layout: => return if not @constraintValues? return if not @parent? and not @context.autoLayout parentFrame = @parent?.frame ? @context.innerFrame @isLayouting = true @frame = Utils.calculateLayoutFrame(parentFrame, @) @isLayouting = false convertPointToScreen: (point) => return Utils.convertPointToContext(point, @, false) convertPointToCanvas: (point) => return Utils.convertPointToContext(point, @, true) convertPointToLayer: (point, layer, rootContext=true) => return Utils.convertPoint(point, @, layer, rootContext) @define "canvasFrame", importable: true exportable: false get: -> return Utils.boundingFrame(@) set: (frame) -> @frame = Utils.convertFrameFromContext(frame, @, true, false) @define "screenFrame", importable: true exportable: false get: -> return Utils.boundingFrame(@, false) set: (frame) -> @frame = Utils.convertFrameFromContext(frame, @, false, false) contentFrame: -> return {x: 0, y: 0, width: 0, height: 0} unless @_children.length return Utils.frameMerge(_.map(@_children, "frame")) totalFrame: -> return Utils.frameMerge(@frame, @contentFrame()) centerFrame: -> # Get the centered frame for its parent if @parent frame = @frame Utils.frameSetMidX(frame, parseInt((@parent.width / 2.0) - @parent.borderWidth)) Utils.frameSetMidY(frame, parseInt((@parent.height / 2.0) - @parent.borderWidth)) return frame else frame = @frame Utils.frameSetMidX(frame, parseInt(@_context.innerWidth / 2.0)) Utils.frameSetMidY(frame, parseInt(@_context.innerHeight / 2.0)) return frame center: -> if @constraintValues? @constraintValues.left = null @constraintValues.right = null @constraintValues.top = null @constraintValues.bottom = null @constraintValues.centerAnchorX = 0.5 @constraintValues.centerAnchorY = 0.5 @_layoutX() @_layoutY() else @frame = @centerFrame() # Center in parent @ centerX: (offset=0) -> if @constraintValues? @constraintValues.left = null @constraintValues.right = null @constraintValues.centerAnchorX = 0.5 @_layoutX() else @x = @centerFrame().x + offset # Center x in parent @ centerY: (offset=0) -> if @constraintValues? @constraintValues.top = null @constraintValues.bottom = null @constraintValues.centerAnchorY = 0.5 @_layoutY() else @y = @centerFrame().y + offset # Center y in parent @ pixelAlign: -> @x = parseInt @x @y = parseInt @y updateForDevicePixelRatioChange: => for cssProperty in ["width", "height", "webkitTransform", "boxShadow", "textShadow", "webkitFilter", "borderRadius", "borderWidth", "fontSize", "letterSpacing", "wordSpacing", "textIndent"] @_element.style[cssProperty] = LayerStyle[cssProperty](@) updateForSizeChange: => @_elementBorder.style.borderWidth = LayerStyle["borderWidth"](@) ############################################################## # SCREEN GEOMETRY # TODO: Rotation/Skew # screenOriginX = -> # if @_parentOrContext() # return @_parentOrContext().screenOriginX() # return @originX # screenOriginY = -> # if @_parentOrContext() # return @_parentOrContext().screenOriginY() # return @originY canvasScaleX: (self=true) -> scale = 1 scale = @scale * @scaleX if self for parent in @containers(true) scale *= parent.scale if parent.scaleX? scale *= parent.scaleX return scale canvasScaleY: (self=true) -> scale = 1 scale = @scale * @scaleY if self for parent in @containers(true) scale *= parent.scale if parent.scaleY? scale *= parent.scaleY return scale screenScaleX: (self=true) -> scale = 1 scale = @scale * @scaleX if self for parent in @containers(false) scale *= parent.scale * parent.scaleX return scale screenScaleY: (self=true) -> scale = 1 scale = @scale * @scaleY if self for parent in @containers(false) scale *= parent.scale * parent.scaleY return scale screenScaledFrame: -> # TODO: Scroll position frame = x: 0 y: 0 width: @width * @screenScaleX() height: @height * @screenScaleY() layers = @containers(true) layers.push(@) layers.reverse() for parent in layers p = parentOrContext(parent) factorX = p?.screenScaleX?() ? 1 factorY = p?.screenScaleY?() ? 1 layerScaledFrame = parent.scaledFrame?() ? {x: 0, y: 0} frame.x += layerScaledFrame.x * factorX frame.y += layerScaledFrame.y * factorY return frame scaledFrame: -> # Get the scaled frame for a layer, taking into account # the transform origins. frame = @frame scaleX = @scale * @scaleX scaleY = @scale * @scaleY frame.width *= scaleX frame.height *= scaleY frame.x += (1 - scaleX) * @originX * @width frame.y += (1 - scaleY) * @originY * @height return frame ############################################################## # CSS @define "style", importable: true exportable: false get: -> @_element.style set: (value) -> _.extend @_element.style, value @emit "change:style" computedStyle: -> # This is an expensive operation getComputedStyle = document.defaultView.getComputedStyle getComputedStyle ?= window.getComputedStyle return getComputedStyle(@_element) @define "classList", importable: true exportable: false get: -> @_element.classList ############################################################## # DOM ELEMENTS _createElement: -> return if @_element? @_element = document.createElement "div" @_element.classList.add("framerLayer") _createBorderElement: -> return if @_elementBorder? @_elementBorder = document.createElement "div" @_elementBorder.style.position = "absolute" @_elementBorder.style.top = "0" @_elementBorder.style.bottom = "0" @_elementBorder.style.left = "0" @_elementBorder.style.right = "0" @_elementBorder.style.boxSizing = "border-box" @_elementBorder.style.zIndex = "1000" @_elementBorder.style.pointerEvents = "none" @_element.appendChild(@_elementBorder) _insertElement: -> @bringToFront() @_context.element.appendChild(@_element) # This method is called as soon as the @_element is part of the DOM # If layers are initialized before the DOM is complete, # the contexts calls this methods on all Layers as soon as it appends itself to the document elementInsertedIntoDocument: -> _createHTMLElementIfNeeded: -> if not @_elementHTML @_elementHTML = document.createElement "div" @_element.insertBefore @_elementHTML, @_elementBorder @define "html", get: -> @_elementHTML?.innerHTML or "" set: (value) -> # Insert some html directly into this layer. We actually create # a child node to insert it in, so it won't mess with Framers # layer hierarchy. @_createHTMLElementIfNeeded() ids = Utils.getIdAttributesFromString(value) for id in ids existingElement = document.querySelector("[id='#{id}']") if existingElement? Utils.throwInStudioOrWarnInProduction(Layer.ExistingIdMessage("html", id)) return @_elementHTML.innerHTML = value @_updateHTMLScale() # If the contents contains something else than plain text # then we turn off ignoreEvents so buttons etc will work. # if not ( # @_elementHTML.childNodes.length is 1 and # @_elementHTML.childNodes[0].nodeName is "#text") # @ignoreEvents = false @emit "change:html" _updateHTMLScale: -> return if not @_elementHTML? if not @htmlIntrinsicSize? @_elementHTML.style.zoom = @context.scale else @_elementHTML.style.transformOrigin = "0 0" @_elementHTML.style.transform = "scale(#{@context.scale * @width / @htmlIntrinsicSize.width}, #{@context.scale * @height / @htmlIntrinsicSize.height})" @_elementHTML.style.width = "#{@htmlIntrinsicSize.width}px" @_elementHTML.style.height = "#{@htmlIntrinsicSize.height}px" querySelector: (query) -> @_element.querySelector(query) querySelectorAll: (query) -> @_element.querySelectorAll(query) selectChild: (selector) -> Utils.findLayer(@descendants, selector) selectAllChildren: (selector) -> Utils.filterLayers(@descendants, selector) @select: (selector) -> Framer.CurrentContext.selectLayer(selector) @selectAll: (selector) -> Framer.CurrentContext.selectAllLayers(selector) destroy: -> # Todo: check this if @parent @parent._children = _.without(@parent._children, @) @_element.parentNode?.removeChild @_element @removeAllListeners() @_context.removeLayer(@) @_context.emit("layer:destroy", @) @_context.domEventManager.remove(@_element) ############################################################## ## COPYING copy: -> layer = @copySingle() for child in @_children copiedChild = child.copy() copiedChild.parent = layer if copiedChild isnt null return layer copySingle: -> copy = new @constructor(@props) copy.style = @style copy ############################################################## ## IMAGE _cleanupImageLoader: -> @_imageEventManager?.removeAllListeners() @_imageEventManager = null @_imageLoader = null @define "image", default: "" get: -> @_getPropertyValue "image" set: (value) -> currentValue = @_getPropertyValue "image" defaults = Defaults.getDefaults "Layer", {} isBackgroundColorDefault = @backgroundColor?.isEqual(defaults.backgroundColor) if Gradient.isGradientObject(value) @emit("change:gradient", value, currentValue) @emit("change:image", value, currentValue) @_setPropertyValue("image", value) @style["background-image"] = value.toCSS() @backgroundColor = null if isBackgroundColorDefault return if not (_.isString(value) or value is null) layerValueTypeError("image", value) if currentValue is value return @emit "load" # Unset the background color only if it’s the default color @backgroundColor = null if isBackgroundColorDefault # Set the property value @_setPropertyValue("image", value) if value in [null, ""] if @_imageLoader? @_imageEventManager.removeAllListeners() @_imageLoader.src = null @style["background-image"] = null if @_imageLoader? @emit Events.ImageLoadCancelled, @_imageLoader @_cleanupImageLoader() return # Show placeholder image on any browser that doesn't support inline pdf if _.endsWith(value.toLowerCase?(), ".pdf") and (not Utils.isWebKit() or Utils.isChrome()) @style["background-image"] = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAAVlJREFUaAXtlwEOwiAMRdF4Cr3/0fQaSre9ZFSYLCrQpSSG/FLW9v92agghXJdP3KZlCp/J2up+WiUuzMt6zNukzPDYvALCsKme1/maV8BnQHqw9/IZ6KmAz0BP9ontMwATPXafgR6s65g+A5qRlrhmBu6FhG6LXf9/+JU/YclROkVWEs/8r9FLrChb2apSqVqWZgKmtRKz9/f+CdPxoVl8CAWylcWKUQZGwfhjB3OOHcw5djDn2MH6fBNLC42yaEnyoTXB2V36+lPlPI:KEY:<KEY>END_PI')" return imageUrl = value # Optional base image value # imageUrl = Config.baseUrl + imageUrl if @_alwaysUseImageCache is false and Utils.isLocalAssetUrl(imageUrl) imageUrl += if /\?/.test(imageUrl) then '&' else '?' imageUrl += "nocache=#{NoCacheDateKey}" # As an optimization, we will only use a loader # if something is explicitly listening to the load event if @listeners(Events.ImageLoaded, true) or @listeners(Events.ImageLoadError, true) or @listeners(Events.ImageLoadCancelled, true) @_imageLoader = new Image() @_imageLoader.name = imageUrl @_imageLoader.src = imageUrl @_imageEventManager = @_context.domEventManager.wrap(@_imageLoader) @_imageEventManager.addEventListener "load", => @style["background-image"] = "url('#{imageUrl}')" @emit Events.ImageLoaded, @_imageLoader @_cleanupImageLoader() @_imageEventManager.addEventListener "error", => @emit Events.ImageLoadError, @_imageLoader @_cleanupImageLoader() else @style["background-image"] = "url('#{imageUrl}')" @define "gradient", get: -> return layerProxiedValue(@image, @, "gradient") if Gradient.isGradientObject(@image) return null set: (value) -> # Copy semantics! if Gradient.isGradient(value) @image = new Gradient(value) else if not value and Gradient.isGradientObject(@image) @image = null ############################################################## ## HIERARCHY @define "parent", enumerable: false exportable: false importable: true get: -> @_parent or null set: (layer) -> return if layer is @_parent throw Error("Layer.parent: a layer cannot be it's own parent.") if layer is @ # Check the type if not layer instanceof Layer throw Error "Layer.parent needs to be a Layer object" # Cancel previous pending insertions Utils.domCompleteCancel(@__insertElement) # Remove from previous parent children if @_parent @_parent._children = _.pull @_parent._children, @ @_parent._element.removeChild @_element @_parent.emit "change:children", {added: [], removed: [@]} @_parent.emit "change:subLayers", {added: [], removed: [@]} # Either insert the element to the new parent element or into dom if layer layer._element.appendChild @_element layer._children.push @ layer.emit "change:children", {added: [@], removed: []} layer.emit "change:subLayers", {added: [@], removed: []} else @_insertElement() oldParent = @_parent # Set the parent @_parent = layer # Place this layer on top of its siblings @bringToFront() @emit "change:parent", @_parent, oldParent @emit "change:superLayer", @_parent, oldParent @define "children", enumerable: false exportable: false importable: false get: -> @_children.map (c) -> if c instanceof SVGLayer and c.children.length is 1 and _.startsWith(c.name, '.') return c.children[0] else return c @define "siblings", enumerable: false exportable: false importable: false get: -> # If there is no parent we need to walk through the root if @parent is null return _.filter @_context.layers, (layer) => layer isnt @ and layer.parent is null return _.without @parent.children, @ @define "descendants", enumerable: false exportable: false importable: false get: -> result = [] f = (layer) -> result.push(layer) layer.children.map(f) @children.map(f) return result addChild: (layer) -> layer.parent = @ removeChild: (layer) -> if layer not in @_children return layer.parent = null childrenWithName: (name) -> _.filter @children, (layer) -> layer.name is name siblingsWithName: (name) -> _.filter @siblingLayers, (layer) -> layer.name is name # Get all containers of this layer, including containing contexts # `toRoot` specifies if you want to bubble up across contexts, # so specifiying `false` will stop at the first context # and thus the results will never contain any context containers: (toRoot=false, result=[]) -> if @parent? result.push(@parent) return @parent.containers(toRoot, result) else if toRoot result.push(@context) return @context.containers(true, result) return result ancestors: -> return @containers() root: -> return @ if @parent is null return _.last(@ancestors()) childrenAbove: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).y < point.y childrenBelow: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).y > point.y childrenLeft: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).x < point.x childrenRight: (point, originX=0, originY=0) -> _.filter @children, (layer) -> Utils.framePointForOrigin(layer.frame, originX, originY).x > point.x _parentOrContext: -> if @parent return @parent if @_context._parent return @_context._parent ############################################################## # Backwards superLayer and children compatibility @define "superLayer", enumerable: false exportable: false importable: false get: -> @parent set: (value) -> @parent = value @define "subLayers", enumerable: false exportable: false importable: false get: -> @children @define "siblingLayers", enumerable: false exportable: false importable: false get: -> @siblings addSubLayer: (layer) -> @addChild(layer) removeSubLayer: (layer) -> @removeChild(layer) subLayersByName: (name) -> @childrenWithName(name) siblingLayersByName: (name) -> @siblingsWithName(name) subLayersAbove: (point, originX=0, originY=0) -> @childrenAbove(point, originX, originY) subLayersBelow: (point, originX=0, originY=0) -> @childrenBelow(point, originX, originY) subLayersLeft: (point, originX=0, originY=0) -> @childrenLeft(point, originX, originY) subLayersRight: (point, originX=0, originY=0) -> @childrenRight(point, originX, originY) ############################################################## ## ANIMATION animate: (properties, options={}) -> # If the properties are a string, we assume it's a state name if _.isString(properties) stateName = properties # Support options as an object options = options.options if options.options? return @states.machine.switchTo(stateName, options) # We need to clone the properties so we don't modify them unexpectedly properties = _.clone(properties) # Support the old properties syntax, we add all properties top level and # move the options into an options property. if properties.properties? options = properties properties = options.properties delete options.properties # With the new api we treat the properties as animatable properties, and use # the special options keyword for animation options. if properties.options? options = _.defaults({}, options, properties.options) delete properties.options # Merge the animation options with the default animation options for this layer options = _.defaults({}, options, @animationOptions) options.start ?= true animation = new Animation(@, properties, options) animation.start() if options.start return animation stateCycle: (args...) -> states = _.flatten(args) if _.isObject(_.last(states)) options = states.pop() @animate(@states.machine.next(states), options) stateSwitch: (stateName, options={}) -> unless stateName? throw new Error("Missing required argument 'stateName' in stateSwitch()") return @animate(stateName, options) if options.animate is true return @animate(stateName, _.defaults({}, options, {instant: true})) animations: (includePending=false) -> # Current running animations on this layer _.filter @_context.animations, (animation) => return false unless (animation.layer is @) return includePending or not animation.isPending animatingProperties: -> properties = {} for animation in @animations() for propertyName in animation.animatingProperties() properties[propertyName] = animation return properties @define "isAnimating", enumerable: false exportable: false get: -> @animations().length isnt 0 animateStop: -> _.invokeMap(@animations(), "stop") @_draggable?.animateStop() ############################################################## ## INDEX ORDERING bringToFront: -> maxIndex = null siblings = @parent?._children ? @context._layers return if siblings.count <= 1 for layer in siblings continue if layer is @ maxIndex ?= layer.index if layer.index > maxIndex maxIndex = layer.index if maxIndex? @index = maxIndex + 1 sendToBack: -> minIndex = null siblings = @parent?._children ? @context._layers return if siblings.count <= 1 for layer in siblings continue if layer is @ minIndex ?= layer.index if layer.index < minIndex minIndex = layer.index if minIndex? @index = minIndex - 1 placeBefore: (layer) -> return if layer not in @siblingLayers for l in @siblingLayers if l.index <= layer.index l.index -= 1 @index = layer.index + 1 placeBehind: (layer) -> return if layer not in @siblingLayers for l in @siblingLayers if l.index >= layer.index l.index += 1 @index = layer.index - 1 ############################################################## ## STATES @define "states", enumerable: false exportable: false importable: false get: -> @_states ?= new LayerStates(@) return @_states set: (states) -> @states.machine.reset() _.extend(@states, states) @define "stateNames", enumerable: false exportable: false importable: false get: -> @states.machine.stateNames ############################################################################# ## Draggable, Pinchable @define "draggable", importable: false exportable: false get: -> @_draggable ?= new LayerDraggable(@) set: (value) -> @draggable.enabled = value if _.isBoolean(value) @define "pinchable", importable: false exportable: false get: -> @_pinchable ?= new LayerPinchable(@) set: (value) -> @pinchable.enabled = value if _.isBoolean(value) ############################################################## ## SCROLLING @define "scrollFrame", importable: false get: -> frame = x: @scrollX y: @scrollY width: @width height: @height set: (frame) -> @scrollX = frame.x @scrollY = frame.y @define "scrollX", get: -> @_element.scrollLeft set: (value) -> layerValueTypeError("scrollX", value) if not _.isNumber(value) @_element.scrollLeft = value @define "scrollY", get: -> @_element.scrollTop set: (value) -> layerValueTypeError("scrollY", value) if not _.isNumber(value) @_element.scrollTop = value ############################################################## ## EVENTS @define "_domEventManager", get: -> @_context.domEventManager.wrap(@_element) emit: (eventName, args...) -> # If this layer has a parent draggable view and its position moved # while dragging we automatically cancel click events. This is what # you expect when you add a button to a scroll content layer. We only # want to do this if this layer is not draggable itself because that # would break nested ScrollComponents. if @_cancelClickEventInDragSession and not @_draggable if eventName in [ Events.Click, Events.Tap, Events.TapStart, Events.TapEnd, Events.LongPress, Events.LongPressStart, Events.LongPressEnd] # If we dragged any layer, we should cancel click events return if LayerDraggable._globalDidDrag is true # See if we need to convert coordinates for this event. Mouse events by # default have the screen coordinates so we make sure that event.point and # event.contextPoint always have the proper coordinates. if args[0]?.clientX? or args[0]?.clientY? event = args[0] point = {x: event.clientX, y: event.clientY} event.point = Utils.convertPointFromContext(point, @, true) event.contextPoint = Utils.convertPointFromContext(point, @context, true) if event.touches? for touch in event.touches point = {x: touch.clientX, y: touch.clientY} touch.point = Utils.convertPointFromContext(point, @, true) touch.contextPoint = Utils.convertPointFromContext(point, @context, true) # Always scope the event this to the layer and pass the layer as # last argument for every event. super(eventName, args..., @) once: (eventName, listener) => super(eventName, listener) @_addListener(eventName, listener) addListener: (eventName, listener) => throw Error("Layer.on needs a valid event name") unless eventName throw Error("Layer.on needs an event listener") unless listener super(eventName, listener) @_addListener(eventName, listener) removeListener: (eventName, listener) -> throw Error("Layer.off needs a valid event name") unless eventName super(eventName, listener) @_removeListener(eventName, listener) _addListener: (eventName, listener) -> # Make sure we stop ignoring events once we add a user event listener if not _.startsWith(eventName, "change:") @ignoreEvents = false # If this is a dom event, we want the actual dom node to let us know # when it gets triggered, so we can emit the event through the system. if Utils.domValidEvent(@_element, eventName) or eventName in _.values(Gestures) if not @_domEventManager.listeners(eventName).length @_domEventManager.addEventListener eventName, (event) => @emit(eventName, event) _removeListener: (eventName, listener) -> # Do cleanup for dom events if this is the last one of it's type. # We are assuming we're the only ones adding dom events to the manager. if not @listeners(eventName).length @_domEventManager.removeAllListeners(eventName) _parentDraggableLayer: -> for layer in @ancestors() return layer if layer._draggable?.enabled return null on: @::addListener off: @::removeListener ############################################################## ## EVENT HELPERS onClick: (cb) -> @on(Events.Click, cb) onDoubleClick: (cb) -> @on(Events.DoubleClick, cb) onScrollStart: (cb) -> @on(Events.ScrollStart, cb) onScroll: (cb) -> @on(Events.Scroll, cb) onScrollEnd: (cb) -> @on(Events.ScrollEnd, cb) onScrollAnimationDidStart: (cb) -> @on(Events.ScrollAnimationDidStart, cb) onScrollAnimationDidEnd: (cb) -> @on(Events.ScrollAnimationDidEnd, cb) onTouchStart: (cb) -> @on(Events.TouchStart, cb) onTouchEnd: (cb) -> @on(Events.TouchEnd, cb) onTouchMove: (cb) -> @on(Events.TouchMove, cb) onMouseUp: (cb) -> @on(Events.MouseUp, cb) onMouseDown: (cb) -> @on(Events.MouseDown, cb) onMouseOver: (cb) -> @on(Events.MouseOver, cb) onMouseOut: (cb) -> @on(Events.MouseOut, cb) onMouseEnter: (cb) -> @on(Events.MouseEnter, cb) onMouseLeave: (cb) -> @on(Events.MouseLeave, cb) onMouseMove: (cb) -> @on(Events.MouseMove, cb) onMouseWheel: (cb) -> @on(Events.MouseWheel, cb) onAnimationStart: (cb) -> @on(Events.AnimationStart, cb) onAnimationStop: (cb) -> @on(Events.AnimationStop, cb) onAnimationEnd: (cb) -> @on(Events.AnimationEnd, cb) onAnimationDidStart: (cb) -> @on(Events.AnimationDidStart, cb) # Deprecated onAnimationDidStop: (cb) -> @on(Events.AnimationDidStop, cb) # Deprecated onAnimationDidEnd: (cb) -> @on(Events.AnimationDidEnd, cb) # Deprecated onImageLoaded: (cb) -> @on(Events.ImageLoaded, cb) onImageLoadError: (cb) -> @on(Events.ImageLoadError, cb) onImageLoadCancelled: (cb) -> @on(Events.ImageLoadCancelled, cb) onMove: (cb) -> @on(Events.Move, cb) onDragStart: (cb) -> @on(Events.DragStart, cb) onDragWillMove: (cb) -> @on(Events.DragWillMove, cb) onDragMove: (cb) -> @on(Events.DragMove, cb) onDragDidMove: (cb) -> @on(Events.DragDidMove, cb) onDrag: (cb) -> @on(Events.Drag, cb) onDragEnd: (cb) -> @on(Events.DragEnd, cb) onDragAnimationStart: (cb) -> @on(Events.DragAnimationStart, cb) onDragAnimationEnd: (cb) -> @on(Events.DragAnimationEnd, cb) onDirectionLockStart: (cb) -> @on(Events.DirectionLockStart, cb) onStateSwitchStart: (cb) -> @on(Events.StateSwitchStart, cb) onStateSwitchStop: (cb) -> @on(Events.StateSwitchStop, cb) onStateSwitchEnd: (cb) -> @on(Events.StateSwitchEnd, cb) onStateWillSwitch: (cb) -> @on(Events.StateSwitchStart, cb) # Deprecated onStateDidSwitch: (cb) -> @on(Events.StateSwitchEnd, cb) # Deprecated # Gestures # Tap onTap: (cb) -> @on(Events.Tap, cb) onTapStart: (cb) -> @on(Events.TapStart, cb) onTapEnd: (cb) -> @on(Events.TapEnd, cb) onDoubleTap: (cb) -> @on(Events.DoubleTap, cb) # Force Tap onForceTap: (cb) -> @on(Events.ForceTap, cb) onForceTapChange: (cb) -> @on(Events.ForceTapChange, cb) onForceTapStart: (cb) -> @on(Events.ForceTapStart, cb) onForceTapEnd: (cb) -> @on(Events.ForceTapEnd, cb) # Press onLongPress: (cb) -> @on(Events.LongPress, cb) onLongPressStart: (cb) -> @on(Events.LongPressStart, cb) onLongPressEnd: (cb) -> @on(Events.LongPressEnd, cb) # Swipe onSwipe: (cb) -> @on(Events.Swipe, cb) onSwipeStart: (cb) -> @on(Events.SwipeStart, cb) onSwipeEnd: (cb) -> @on(Events.SwipeEnd, cb) onSwipeUp: (cb) -> @on(Events.SwipeUp, cb) onSwipeUpStart: (cb) -> @on(Events.SwipeUpStart, cb) onSwipeUpEnd: (cb) -> @on(Events.SwipeUpEnd, cb) onSwipeDown: (cb) -> @on(Events.SwipeDown, cb) onSwipeDownStart: (cb) -> @on(Events.SwipeDownStart, cb) onSwipeDownEnd: (cb) -> @on(Events.SwipeDownEnd, cb) onSwipeLeft: (cb) -> @on(Events.SwipeLeft, cb) onSwipeLeftStart: (cb) -> @on(Events.SwipeLeftStart, cb) onSwipeLeftEnd: (cb) -> @on(Events.SwipeLeftEnd, cb) onSwipeRight: (cb) -> @on(Events.SwipeRight, cb) onSwipeRightStart: (cb) -> @on(Events.SwipeRightStart, cb) onSwipeRightEnd: (cb) -> @on(Events.SwipeRightEnd, cb) # Pan onPan: (cb) -> @on(Events.Pan, cb) onPanStart: (cb) -> @on(Events.PanStart, cb) onPanEnd: (cb) -> @on(Events.PanEnd, cb) onPanLeft: (cb) -> @on(Events.PanLeft, cb) onPanRight: (cb) -> @on(Events.PanRight, cb) onPanUp: (cb) -> @on(Events.PanUp, cb) onPanDown: (cb) -> @on(Events.PanDown, cb) # Pinch onPinch: (cb) -> @on(Events.Pinch, cb) onPinchStart: (cb) -> @on(Events.PinchStart, cb) onPinchEnd: (cb) -> @on(Events.PinchEnd, cb) # Scale onScale: (cb) -> @on(Events.Scale, cb) onScaleStart: (cb) -> @on(Events.ScaleStart, cb) onScaleEnd: (cb) -> @on(Events.ScaleEnd, cb) # Rotate onRotate: (cb) -> @on(Events.Rotate, cb) onRotateStart: (cb) -> @on(Events.RotateStart, cb) onRotateEnd: (cb) -> @on(Events.RotateEnd, cb) ############################################################## ## HINT _showHint: (targetLayer) -> # If this layer isnt visible we can just exit return if not @visible return if @opacity is 0 # If we don't need to show a hint exit but pass to children unless @shouldShowHint(targetLayer) layer._showHint(targetLayer) for layer in @children return null # Figure out the frame we want to show the hint in, if any of the # parent layers clip, we need to intersect the rectangle with it. frame = @canvasFrame for parent in @ancestors() if parent.clip frame = Utils.frameIntersection(frame, parent.canvasFrame) if not frame return # Show the actual hint @showHint(frame) # Tell the children to show their hints _.invokeMap(@children, "_showHint") willSeemToDoSomething: -> if @ignoreEvents return false if @_draggable if @_draggable.isDragging is false and @_draggable.isMoving is false return false return true shouldShowHint: -> # Don't show hints if the layer is not interactive if @ignoreEvents is true return false # Don't show any hints while we are animating if @isAnimating return false for parent in @ancestors() return false if parent.isAnimating # Don't show hints if there is a draggable that cannot be dragged. if @_draggable and @_draggable.horizontal is false and @_draggable.vertical is false return false # Don't show hint if this layer is invisible return false if @opacity is 0 # If we don't ignore events on this layer, make sure the layer is listening to # an interactive event so there is a decent change something is happening after # we click it. for eventName in @listenerEvents() return true if Events.isInteractive(eventName) return false showHint: (highlightFrame) -> # Don't show anything if this element covers the entire screen # if Utils.frameInFrame(@context.canvasFrame, highlightFrame) # return # Start an animation with a rectangle fading out over time layer = new Layer frame: Utils.frameInset(highlightFrame, -1) backgroundColor: null borderColor: Framer.Defaults.Hints.color borderRadius: @borderRadius * Utils.average([@canvasScaleX(), @canvasScaleY()]) borderWidth: 3 # Only show outlines for draggables if @_draggable layer.backgroundColor = null # Only show outlines if a highlight is fullscreen if Utils.frameInFrame(@context.canvasFrame, highlightFrame) layer.backgroundColor = null animation = layer.animate properties: {opacity: 0} curve: "ease-out" time: 0.5 animation.onAnimationEnd -> layer.destroy() ############################################################## ## DESCRIPTOR toName: -> return name if @name return @__framerInstanceInfo?.name or "" toInspect: (constructor) -> constructor ?= @constructor.name name = if @name then "name:#{@name} " else "" return "<#{constructor} #{@toName()} id:#{@id} #{name} (#{Utils.roundWhole(@x)}, #{Utils.roundWhole(@y)}) #{Utils.roundWhole(@width)}x#{Utils.roundWhole(@height)}>"
[ { "context": "v['SCRIPT_NAME'] = \"\"\n\n env['REMOTE_ADDR'] = \"0.0.0.0\"\n env['SERVER_ADDR'] = \"0.0.0.0\"\n\n if host ", "end": 4143, "score": 0.9993206858634949, "start": 4136, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "MOTE_ADDR'] = \"0.0.0.0\"\n env[...
src/client.coffee
josh/nack
21
assert = require 'assert' fs = require 'fs' ns = require 'netstring' url = require 'url' {Socket} = require 'net' {Stream} = require 'stream' {debug} = require './util' {BufferedRequest} = require './util' # A **Client** establishes a connection to a worker process. # # It takes a `port` and `host` or a UNIX socket path. # # Its API is similar to `http.Client`. # # var conn = client.createConnection('/tmp/nack.sock'); # var request = conn.request('GET', '/', {'host', 'localhost'}); # request.end(); # request.on('response', function (response) { # console.log('STATUS: ' + response.statusCode); # console.log('HEADERS: ' + JSON.stringify(response.headers)); # response.on('data', function (chunk) { # console.log('BODY: ' + chunk); # }); # }); # exports.Client = class Client extends Socket constructor: -> super debug "client created" # Initialize outgoing array to hold pending requests @_outgoing = [] # Incoming is used to point to the current response @_incoming = null self = this # Once we've made the connect, process the next request @on 'connect', -> self._processRequest() @on 'error', (err) -> if req = self._outgoing[0] req.emit 'error', err # Finalize the request on close @on 'close', -> self._finishRequest() # Initialize the response netstring parser @_initResponseParser() _initResponseParser: -> self = this nsStream = new ns.Stream this nsStream.on 'data', (data) -> if self._incoming self._incoming._receiveData data nsStream.on 'error', (exception) -> self._incoming = null self.emit 'error', exception _processRequest: -> # Process the request now if the socket is open and # we aren't already handling a response if @readyState is 'open' and !@_incoming if request = @_outgoing[0] debug "processing outgoing request 1/#{@_outgoing.length}" @_incoming = new ClientResponse this, request # Flush the request buffer into socket request.pipe this request.flush() else # Try to reconnect and try again soon @reconnect() _finishRequest: -> debug "finishing request" req = @_outgoing.shift() req.destroy() res = @_incoming @_incoming = null if res is null or res.received is false req.emit 'error', new Error "Response was not received" else if res.readable and not res.statusCode req.emit 'error', new Error "Missing status code" else if res.readable and not res.headers req.emit 'error', new Error "Missing headers" # Anymore requests, continue processing if @_outgoing.length > 0 @_processRequest() # Reconnect if the connection is closed. reconnect: -> if @readyState is 'closed' or @readyState is 'readOnly' debug "connecting to #{@port}" @connect @port, @host # Start the connection and create a ClientRequest. request: (args...) -> request = new ClientRequest args... @_outgoing.push request @_processRequest() request # Public API for creating a **Client** exports.createConnection = (port, host) -> client = new Client client.port = port client.host = host client # A **ClientRequest** is returned when `Client.request()` is called. # # It is a Writable Stream and responds to the conventional # `write` and `end` methods. # # Its also an EventEmitter with the following events: # # > **Event 'response'** # > # > `function (response) { }` # > # > Emitted when a response is received to this request. This event is # > emitted only once. The response argument will be an instance of # > `ClientResponse`. # > # > **Event: 'error'** # > # > `function (exception) { }` # > # > Emitted when an error occurs. # exports.ClientRequest = class ClientRequest extends BufferedRequest _buildEnv: -> env = {} env['REQUEST_METHOD'] = @method {pathname, query} = url.parse @url env['PATH_INFO'] = pathname env['QUERY_STRING'] = query ? "" env['SCRIPT_NAME'] = "" env['REMOTE_ADDR'] = "0.0.0.0" env['SERVER_ADDR'] = "0.0.0.0" if host = @headers.host parts = @headers.host.split ':' env['SERVER_NAME'] = parts[0] env['SERVER_PORT'] = parts[1] env['SERVER_NAME'] ?= "localhost" env['SERVER_PORT'] ?= "80" for key, value of @headers key = key.toUpperCase().replace /-/g, '_' key = "HTTP_#{key}" unless key == 'CONTENT_TYPE' or key == 'CONTENT_LENGTH' env[key] = value for key, value of @proxyMetaVariables env[key] = value env # Write chunk to client write: (chunk, encoding) -> super ns.nsWrite chunk, 0, chunk.length, null, 0, encoding # Closes writting socket. end: (chunk, encoding) -> if (chunk) @write chunk, encoding super "" flush: -> # Write Env header if queue hasn't been flushed if @_queue debug "requesting #{@method} #{@url}" chunk = JSON.stringify @_buildEnv() nsChunk = ns.nsWrite chunk, 0, chunk.length, null, 0, 'utf8' debug "writing header #{nsChunk.length} bytes" @emit 'data', nsChunk super # A **ClientResponse** is emitted from the client request's # `response` event. # # It is a Readable Stream and emits the conventional events: # # > **Event: 'data'** # > # > `function (chunk) { }` # > # > Emitted when a piece of the message body is received. # # > **Event: 'end'** # > # > `function () { }` # > # > Emitted exactly once for each message. No arguments. After emitted # > no other events will be emitted on the request. # > # > **Event: 'error'** # > # > `function (exception) { }` # > # > Emitted when an error occurs. # exports.ClientResponse = class ClientResponse extends Stream constructor: (@socket, @request) -> @client = @socket @readable = true @writable = true @received = false @completed = false @statusCode = null @httpVersion = '1.1' @headers = null @_buffer = null _receiveData: (data) -> debug "received #{data.length} bytes" return if !@readable or @completed @received = true try if data.length > 0 # The first response part is the status if !@statusCode @statusCode = parseInt data assert.ok @statusCode >= 100, "Status must be >= 100" # The second part is the JSON encoded headers else if !@headers @headers = {} rawHeaders = JSON.parse data assert.ok rawHeaders, "Headers can not be null" assert.equal typeof rawHeaders, 'object', "Headers must be an object" for k, vs of rawHeaders # Support legacy Array headers vs = vs.join "\n" if vs.join # Split multiline Rack headers v = vs.split "\n" @headers[k] = if v.length > 1 v else vs debug "response received: #{@statusCode}" if @_path = @headers['X-Sendfile'] delete @headers['X-Sendfile'] fs.stat @_path, (err, stat) => unless stat.isFile() err = new Error "#{@_path} is not a file" if err @onError err else @headers['Content-Length'] = "#{stat.size}" @headers['Last-Modified'] = "#{stat.mtime.toUTCString()}" @request.emit 'response', this fs.createReadStream(@_path).pipe this else # Emit response once we've received the status and headers @request.emit 'response', this # Else its body parts else if data.length > 0 and not @_path @write data # Empty string means EOF else if not @_path @end() catch error # See if payload is an exception backtrace exception = try JSON.parse data if exception and exception.name and exception.message error = new Error exception.message error.name = exception.name error.stack = exception.stack @onError error onError: (error) -> debug "response error", error @readable = false @socket.emit 'error', error write: (data) -> return if not @readable or @completed @emit 'data', data end: (data) -> return if not @readable or @completed @emit 'data', data if data assert.ok @statusCode, "Missing status code" assert.ok @headers, "Missing headers" debug "response complete" @readable = false @completed = true @emit 'end' pipe: (dest, options) -> # Detect when we are piping to another HttpResponse and copy over headers if dest.writeHead # Don't enable chunked encoding dest.useChunkedEncodingByDefault = false dest.writeHead @statusCode, @headers # Force chunkedEncoding off and pass through whatever data comes from the client dest.chunkedEncoding = false super
41946
assert = require 'assert' fs = require 'fs' ns = require 'netstring' url = require 'url' {Socket} = require 'net' {Stream} = require 'stream' {debug} = require './util' {BufferedRequest} = require './util' # A **Client** establishes a connection to a worker process. # # It takes a `port` and `host` or a UNIX socket path. # # Its API is similar to `http.Client`. # # var conn = client.createConnection('/tmp/nack.sock'); # var request = conn.request('GET', '/', {'host', 'localhost'}); # request.end(); # request.on('response', function (response) { # console.log('STATUS: ' + response.statusCode); # console.log('HEADERS: ' + JSON.stringify(response.headers)); # response.on('data', function (chunk) { # console.log('BODY: ' + chunk); # }); # }); # exports.Client = class Client extends Socket constructor: -> super debug "client created" # Initialize outgoing array to hold pending requests @_outgoing = [] # Incoming is used to point to the current response @_incoming = null self = this # Once we've made the connect, process the next request @on 'connect', -> self._processRequest() @on 'error', (err) -> if req = self._outgoing[0] req.emit 'error', err # Finalize the request on close @on 'close', -> self._finishRequest() # Initialize the response netstring parser @_initResponseParser() _initResponseParser: -> self = this nsStream = new ns.Stream this nsStream.on 'data', (data) -> if self._incoming self._incoming._receiveData data nsStream.on 'error', (exception) -> self._incoming = null self.emit 'error', exception _processRequest: -> # Process the request now if the socket is open and # we aren't already handling a response if @readyState is 'open' and !@_incoming if request = @_outgoing[0] debug "processing outgoing request 1/#{@_outgoing.length}" @_incoming = new ClientResponse this, request # Flush the request buffer into socket request.pipe this request.flush() else # Try to reconnect and try again soon @reconnect() _finishRequest: -> debug "finishing request" req = @_outgoing.shift() req.destroy() res = @_incoming @_incoming = null if res is null or res.received is false req.emit 'error', new Error "Response was not received" else if res.readable and not res.statusCode req.emit 'error', new Error "Missing status code" else if res.readable and not res.headers req.emit 'error', new Error "Missing headers" # Anymore requests, continue processing if @_outgoing.length > 0 @_processRequest() # Reconnect if the connection is closed. reconnect: -> if @readyState is 'closed' or @readyState is 'readOnly' debug "connecting to #{@port}" @connect @port, @host # Start the connection and create a ClientRequest. request: (args...) -> request = new ClientRequest args... @_outgoing.push request @_processRequest() request # Public API for creating a **Client** exports.createConnection = (port, host) -> client = new Client client.port = port client.host = host client # A **ClientRequest** is returned when `Client.request()` is called. # # It is a Writable Stream and responds to the conventional # `write` and `end` methods. # # Its also an EventEmitter with the following events: # # > **Event 'response'** # > # > `function (response) { }` # > # > Emitted when a response is received to this request. This event is # > emitted only once. The response argument will be an instance of # > `ClientResponse`. # > # > **Event: 'error'** # > # > `function (exception) { }` # > # > Emitted when an error occurs. # exports.ClientRequest = class ClientRequest extends BufferedRequest _buildEnv: -> env = {} env['REQUEST_METHOD'] = @method {pathname, query} = url.parse @url env['PATH_INFO'] = pathname env['QUERY_STRING'] = query ? "" env['SCRIPT_NAME'] = "" env['REMOTE_ADDR'] = "0.0.0.0" env['SERVER_ADDR'] = "0.0.0.0" if host = @headers.host parts = @headers.host.split ':' env['SERVER_NAME'] = parts[0] env['SERVER_PORT'] = parts[1] env['SERVER_NAME'] ?= "localhost" env['SERVER_PORT'] ?= "80" for key, value of @headers key = key.toUpperCase().replace /-/g, '_' key = "<KEY> unless key == '<KEY>' or key == '<KEY>' env[key] = value for key, value of @proxyMetaVariables env[key] = value env # Write chunk to client write: (chunk, encoding) -> super ns.nsWrite chunk, 0, chunk.length, null, 0, encoding # Closes writting socket. end: (chunk, encoding) -> if (chunk) @write chunk, encoding super "" flush: -> # Write Env header if queue hasn't been flushed if @_queue debug "requesting #{@method} #{@url}" chunk = JSON.stringify @_buildEnv() nsChunk = ns.nsWrite chunk, 0, chunk.length, null, 0, 'utf8' debug "writing header #{nsChunk.length} bytes" @emit 'data', nsChunk super # A **ClientResponse** is emitted from the client request's # `response` event. # # It is a Readable Stream and emits the conventional events: # # > **Event: 'data'** # > # > `function (chunk) { }` # > # > Emitted when a piece of the message body is received. # # > **Event: 'end'** # > # > `function () { }` # > # > Emitted exactly once for each message. No arguments. After emitted # > no other events will be emitted on the request. # > # > **Event: 'error'** # > # > `function (exception) { }` # > # > Emitted when an error occurs. # exports.ClientResponse = class ClientResponse extends Stream constructor: (@socket, @request) -> @client = @socket @readable = true @writable = true @received = false @completed = false @statusCode = null @httpVersion = '1.1' @headers = null @_buffer = null _receiveData: (data) -> debug "received #{data.length} bytes" return if !@readable or @completed @received = true try if data.length > 0 # The first response part is the status if !@statusCode @statusCode = parseInt data assert.ok @statusCode >= 100, "Status must be >= 100" # The second part is the JSON encoded headers else if !@headers @headers = {} rawHeaders = JSON.parse data assert.ok rawHeaders, "Headers can not be null" assert.equal typeof rawHeaders, 'object', "Headers must be an object" for k, vs of rawHeaders # Support legacy Array headers vs = vs.join "\n" if vs.join # Split multiline Rack headers v = vs.split "\n" @headers[k] = if v.length > 1 v else vs debug "response received: #{@statusCode}" if @_path = @headers['X-Sendfile'] delete @headers['X-Sendfile'] fs.stat @_path, (err, stat) => unless stat.isFile() err = new Error "#{@_path} is not a file" if err @onError err else @headers['Content-Length'] = "#{stat.size}" @headers['Last-Modified'] = "#{stat.mtime.toUTCString()}" @request.emit 'response', this fs.createReadStream(@_path).pipe this else # Emit response once we've received the status and headers @request.emit 'response', this # Else its body parts else if data.length > 0 and not @_path @write data # Empty string means EOF else if not @_path @end() catch error # See if payload is an exception backtrace exception = try JSON.parse data if exception and exception.name and exception.message error = new Error exception.message error.name = exception.name error.stack = exception.stack @onError error onError: (error) -> debug "response error", error @readable = false @socket.emit 'error', error write: (data) -> return if not @readable or @completed @emit 'data', data end: (data) -> return if not @readable or @completed @emit 'data', data if data assert.ok @statusCode, "Missing status code" assert.ok @headers, "Missing headers" debug "response complete" @readable = false @completed = true @emit 'end' pipe: (dest, options) -> # Detect when we are piping to another HttpResponse and copy over headers if dest.writeHead # Don't enable chunked encoding dest.useChunkedEncodingByDefault = false dest.writeHead @statusCode, @headers # Force chunkedEncoding off and pass through whatever data comes from the client dest.chunkedEncoding = false super
true
assert = require 'assert' fs = require 'fs' ns = require 'netstring' url = require 'url' {Socket} = require 'net' {Stream} = require 'stream' {debug} = require './util' {BufferedRequest} = require './util' # A **Client** establishes a connection to a worker process. # # It takes a `port` and `host` or a UNIX socket path. # # Its API is similar to `http.Client`. # # var conn = client.createConnection('/tmp/nack.sock'); # var request = conn.request('GET', '/', {'host', 'localhost'}); # request.end(); # request.on('response', function (response) { # console.log('STATUS: ' + response.statusCode); # console.log('HEADERS: ' + JSON.stringify(response.headers)); # response.on('data', function (chunk) { # console.log('BODY: ' + chunk); # }); # }); # exports.Client = class Client extends Socket constructor: -> super debug "client created" # Initialize outgoing array to hold pending requests @_outgoing = [] # Incoming is used to point to the current response @_incoming = null self = this # Once we've made the connect, process the next request @on 'connect', -> self._processRequest() @on 'error', (err) -> if req = self._outgoing[0] req.emit 'error', err # Finalize the request on close @on 'close', -> self._finishRequest() # Initialize the response netstring parser @_initResponseParser() _initResponseParser: -> self = this nsStream = new ns.Stream this nsStream.on 'data', (data) -> if self._incoming self._incoming._receiveData data nsStream.on 'error', (exception) -> self._incoming = null self.emit 'error', exception _processRequest: -> # Process the request now if the socket is open and # we aren't already handling a response if @readyState is 'open' and !@_incoming if request = @_outgoing[0] debug "processing outgoing request 1/#{@_outgoing.length}" @_incoming = new ClientResponse this, request # Flush the request buffer into socket request.pipe this request.flush() else # Try to reconnect and try again soon @reconnect() _finishRequest: -> debug "finishing request" req = @_outgoing.shift() req.destroy() res = @_incoming @_incoming = null if res is null or res.received is false req.emit 'error', new Error "Response was not received" else if res.readable and not res.statusCode req.emit 'error', new Error "Missing status code" else if res.readable and not res.headers req.emit 'error', new Error "Missing headers" # Anymore requests, continue processing if @_outgoing.length > 0 @_processRequest() # Reconnect if the connection is closed. reconnect: -> if @readyState is 'closed' or @readyState is 'readOnly' debug "connecting to #{@port}" @connect @port, @host # Start the connection and create a ClientRequest. request: (args...) -> request = new ClientRequest args... @_outgoing.push request @_processRequest() request # Public API for creating a **Client** exports.createConnection = (port, host) -> client = new Client client.port = port client.host = host client # A **ClientRequest** is returned when `Client.request()` is called. # # It is a Writable Stream and responds to the conventional # `write` and `end` methods. # # Its also an EventEmitter with the following events: # # > **Event 'response'** # > # > `function (response) { }` # > # > Emitted when a response is received to this request. This event is # > emitted only once. The response argument will be an instance of # > `ClientResponse`. # > # > **Event: 'error'** # > # > `function (exception) { }` # > # > Emitted when an error occurs. # exports.ClientRequest = class ClientRequest extends BufferedRequest _buildEnv: -> env = {} env['REQUEST_METHOD'] = @method {pathname, query} = url.parse @url env['PATH_INFO'] = pathname env['QUERY_STRING'] = query ? "" env['SCRIPT_NAME'] = "" env['REMOTE_ADDR'] = "0.0.0.0" env['SERVER_ADDR'] = "0.0.0.0" if host = @headers.host parts = @headers.host.split ':' env['SERVER_NAME'] = parts[0] env['SERVER_PORT'] = parts[1] env['SERVER_NAME'] ?= "localhost" env['SERVER_PORT'] ?= "80" for key, value of @headers key = key.toUpperCase().replace /-/g, '_' key = "PI:KEY:<KEY>END_PI unless key == 'PI:KEY:<KEY>END_PI' or key == 'PI:KEY:<KEY>END_PI' env[key] = value for key, value of @proxyMetaVariables env[key] = value env # Write chunk to client write: (chunk, encoding) -> super ns.nsWrite chunk, 0, chunk.length, null, 0, encoding # Closes writting socket. end: (chunk, encoding) -> if (chunk) @write chunk, encoding super "" flush: -> # Write Env header if queue hasn't been flushed if @_queue debug "requesting #{@method} #{@url}" chunk = JSON.stringify @_buildEnv() nsChunk = ns.nsWrite chunk, 0, chunk.length, null, 0, 'utf8' debug "writing header #{nsChunk.length} bytes" @emit 'data', nsChunk super # A **ClientResponse** is emitted from the client request's # `response` event. # # It is a Readable Stream and emits the conventional events: # # > **Event: 'data'** # > # > `function (chunk) { }` # > # > Emitted when a piece of the message body is received. # # > **Event: 'end'** # > # > `function () { }` # > # > Emitted exactly once for each message. No arguments. After emitted # > no other events will be emitted on the request. # > # > **Event: 'error'** # > # > `function (exception) { }` # > # > Emitted when an error occurs. # exports.ClientResponse = class ClientResponse extends Stream constructor: (@socket, @request) -> @client = @socket @readable = true @writable = true @received = false @completed = false @statusCode = null @httpVersion = '1.1' @headers = null @_buffer = null _receiveData: (data) -> debug "received #{data.length} bytes" return if !@readable or @completed @received = true try if data.length > 0 # The first response part is the status if !@statusCode @statusCode = parseInt data assert.ok @statusCode >= 100, "Status must be >= 100" # The second part is the JSON encoded headers else if !@headers @headers = {} rawHeaders = JSON.parse data assert.ok rawHeaders, "Headers can not be null" assert.equal typeof rawHeaders, 'object', "Headers must be an object" for k, vs of rawHeaders # Support legacy Array headers vs = vs.join "\n" if vs.join # Split multiline Rack headers v = vs.split "\n" @headers[k] = if v.length > 1 v else vs debug "response received: #{@statusCode}" if @_path = @headers['X-Sendfile'] delete @headers['X-Sendfile'] fs.stat @_path, (err, stat) => unless stat.isFile() err = new Error "#{@_path} is not a file" if err @onError err else @headers['Content-Length'] = "#{stat.size}" @headers['Last-Modified'] = "#{stat.mtime.toUTCString()}" @request.emit 'response', this fs.createReadStream(@_path).pipe this else # Emit response once we've received the status and headers @request.emit 'response', this # Else its body parts else if data.length > 0 and not @_path @write data # Empty string means EOF else if not @_path @end() catch error # See if payload is an exception backtrace exception = try JSON.parse data if exception and exception.name and exception.message error = new Error exception.message error.name = exception.name error.stack = exception.stack @onError error onError: (error) -> debug "response error", error @readable = false @socket.emit 'error', error write: (data) -> return if not @readable or @completed @emit 'data', data end: (data) -> return if not @readable or @completed @emit 'data', data if data assert.ok @statusCode, "Missing status code" assert.ok @headers, "Missing headers" debug "response complete" @readable = false @completed = true @emit 'end' pipe: (dest, options) -> # Detect when we are piping to another HttpResponse and copy over headers if dest.writeHead # Don't enable chunked encoding dest.useChunkedEncodingByDefault = false dest.writeHead @statusCode, @headers # Force chunkedEncoding off and pass through whatever data comes from the client dest.chunkedEncoding = false super
[ { "context": "model\n\t\t\t\tcallback err, models[0]\n\t\t\n\t\tkey = \"#{ @collection }-#{ id.toString() }\"\n\t\t\n\t\tCache.get key, (err, result) ->\n\t\t\tif not", "end": 3433, "score": 0.7102279663085938, "start": 3404, "tag": "KEY", "value": "collection }-#{ id.toString()" }, { ...
lib/mongorito.coffee
tj/mongorito
3
mongolian = require 'mongolian' async = require 'async' memcacher = require 'memcacher' Client = undefined Cache = undefined `String.prototype.plural = function() { var s = this.trim().toLowerCase(); end = s.substr(-1); if(end == 'y') { var vowels = ['a', 'e', 'i', 'o', 'u']; s = s.substr(-2, 1) in vowels ? s + 's' : s.substr(0, s.length-1) + 'ies'; } else if(end == 'h') { s += s.substr(-2) == 'ch' || s.substr(-2) == 'sh' ? 'es' : 's'; } else if(end == 's') { s += 'es'; } else { s += 's'; } return s; } String.prototype.singular = function() { var s = this.trim().toLowerCase(); var end = s.substr(-3); if(end == 'ies') { s = s.substr(0, s.length-3) + 'y'; } else if(end == 'ses') { s = s.substr(0, s.length-2); } else { end = s.substr(-1); if(end == 's') { s = s.substr(0, s.length-1); } } return s; } String.prototype.camelize = function() { var s = 'x_' + this.trim().toLowerCase(); s = s.replace(/[\s_]/g, ' '); s = s.replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); }); return s.replace(/ /g, '').substr(1); } String.prototype.underscore = function() { return this.trim().toLowerCase().replace(/[\s]+/g, '_'); } var hasProp = Object.prototype.hasOwnProperty, extendsClass = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor(proto) { this.constructor = child; for(var method in proto) { this[method] = proto[method]; } } ctor.prototype = parent.prototype; child.prototype = new ctor(child.prototype); child.__super__ = parent.prototype; return child; } ` class Mongorito @disconnect: -> do Client.close @connect: (database = '', servers = [], username = '', password = '') -> if servers.length is 1 server = new mongolian servers[0] Client = server.db database Client.log= debug: -> info: -> warn: -> error: -> Client.auth username, password if username else # Support comes soon to Replica Sets server = new mongolian servers[0] Client = server.db database Client.log= debug: -> info: -> warn: -> error: -> Client.auth username, password if username @cache: (servers = []) -> Cache = new memcacher servers @bake: (model) -> extendsClass(model, MongoritoModel) object = new model model.collection = object.collection model.model = model model class MongoritoModel constructor: (@collection = '') -> fields: -> notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate'] fields = {} for field of @ fields[field] = @[field] if -1 is notFields.indexOf field fields @bakeModelsFromItems: (items, _model) -> models = [] for item in items item._id = item._id.toString() model = new _model model.collection = _model.collection for field of item model[field] = item[field] models.push model models @findById: (id, callback) -> that = @ query = (id, done) -> Client.collection(that.collection).find({ _id: new mongolian.ObjectId(id.toString()) }).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query id, (err, items) -> models = that.bakeModelsFromItems items, that.model callback err, models[0] key = "#{ @collection }-#{ id.toString() }" Cache.get key, (err, result) -> if not result query id, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithOrderAndLimit: (criteria, order, limit, skip, callback) -> if typeof criteria is 'object' if typeof order is 'number' if typeof limit is 'function' callback = limit limit = order order = criteria criteria = {} if typeof limit is 'number' if typeof skip is 'function' callback = skip skip = limit limit = order order = criteria criteria = {} skip = 0 if not skip that = @ query = (criteria, order, limit, skip, done) -> Client.collection(that.collection).find(criteria).sort(order).limit(limit).skip(skip).toArray (err, items) -> done err, items if not Cache return query criteria, order, limit, skip, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-order-#{ order }-limit-#{ limit }-skip-#{ skip }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, order, limit, skip, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithOrder: (criteria, order, callback) -> if typeof criteria is 'object' and typeof order is 'function' callback = order order = criteria criteria = {} order = { _id: -1 } that = @ query = (criteria, order, done) -> Client.collection(that.collection).find(criteria).sort(order).toArray (err, items) -> done err, items if not Cache return query criteria, order, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-order-#{ order }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, order, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithLimit: (criteria, limit, skip, callback) -> if typeof criteria is 'number' if typeof limit is 'function' callback = limit limit = criteria criteria = {} if typeof limit is 'number' if typeof skip is 'function' callback = skip skip = limit criteria = {} else if typeof limit is 'function' callback = limit limit = 10 if typeof skip is 'function' callback = skip skip = 0 that = @ query = (criteria, limit, skip, done) -> Client.collection(that.collection).find(criteria).limit(limit).skip(skip).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query criteria, limit, skip, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-limit-#{ limit }-skip-#{ skip }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, limit, skip, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @find: (criteria = {}, callback) -> if typeof(criteria) is 'function' callback = criteria criteria = {} that = @ query = (criteria, done) -> Client.collection(that.collection).find(criteria).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query criteria, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, (err, items) -> models = that.bakeModelsFromItems items, that.model Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models save: (callback) -> that = @ fields = do @fields notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'models'] keys = [] for field of @ keys.push field if -1 is notFields.indexOf field async.filter keys, (key, nextKey) -> if that["validate#{ key.camelize() }"] that["validate#{ key.camelize() }"] (valid) -> nextKey not valid else nextKey false , (results) -> return callback yes, results if results.length > 0 performOperation = -> if fields._id that.update callback, yes else that.create callback, yes if Cache then Cache.delByTag that.collection, performOperation else do performOperation create: (callback, fromSave = no) -> object = @fields() do @beforeCreate if @['beforeCreate'] do @aroundCreate if @['aroundCreate'] that = @ Client.collection(@collection).insert object, (err, result) -> result._id = result._id.toString() that._id = result._id do that.aroundCreate if that['aroundCreate'] do that.afterCreate if that['afterCreate'] process.nextTick -> callback err, result if callback update: (callback, fromSave = no) -> object = @fields() _id = new mongolian.ObjectId object._id delete object._id do @beforeUpdate if @['beforeUpdate'] do @aroundUpdate if @['aroundUpdate'] that = @ Client.collection(@collection).update { _id: _id }, object, (err, rowsUpdated) -> do that.aroundUpdate if that['aroundUpdate'] do that.afterUpdate if that['afterUpdate'] process.nextTick -> callback err, rowsUpdated if callback remove: (callback) -> object = @fields() _id = new mongolian.ObjectId object._id do @beforeRemove if @['beforeRemove'] do @aroundRemove if @['aroundRemove'] that = @ Cache.delByTag @collection, -> Client.collection(that.collection).remove { _id: _id }, (err) -> do that.aroundRemove if that['aroundRemove'] do that.afterRemove if that['afterRemove'] process.nextTick -> callback err if callback class GenericModel extends MongoritoModel module.exports= connect: Mongorito.connect disconnect: Mongorito.disconnect cache: Mongorito.cache bake: Mongorito.bake Model: MongoritoModel
51279
mongolian = require 'mongolian' async = require 'async' memcacher = require 'memcacher' Client = undefined Cache = undefined `String.prototype.plural = function() { var s = this.trim().toLowerCase(); end = s.substr(-1); if(end == 'y') { var vowels = ['a', 'e', 'i', 'o', 'u']; s = s.substr(-2, 1) in vowels ? s + 's' : s.substr(0, s.length-1) + 'ies'; } else if(end == 'h') { s += s.substr(-2) == 'ch' || s.substr(-2) == 'sh' ? 'es' : 's'; } else if(end == 's') { s += 'es'; } else { s += 's'; } return s; } String.prototype.singular = function() { var s = this.trim().toLowerCase(); var end = s.substr(-3); if(end == 'ies') { s = s.substr(0, s.length-3) + 'y'; } else if(end == 'ses') { s = s.substr(0, s.length-2); } else { end = s.substr(-1); if(end == 's') { s = s.substr(0, s.length-1); } } return s; } String.prototype.camelize = function() { var s = 'x_' + this.trim().toLowerCase(); s = s.replace(/[\s_]/g, ' '); s = s.replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); }); return s.replace(/ /g, '').substr(1); } String.prototype.underscore = function() { return this.trim().toLowerCase().replace(/[\s]+/g, '_'); } var hasProp = Object.prototype.hasOwnProperty, extendsClass = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor(proto) { this.constructor = child; for(var method in proto) { this[method] = proto[method]; } } ctor.prototype = parent.prototype; child.prototype = new ctor(child.prototype); child.__super__ = parent.prototype; return child; } ` class Mongorito @disconnect: -> do Client.close @connect: (database = '', servers = [], username = '', password = '') -> if servers.length is 1 server = new mongolian servers[0] Client = server.db database Client.log= debug: -> info: -> warn: -> error: -> Client.auth username, password if username else # Support comes soon to Replica Sets server = new mongolian servers[0] Client = server.db database Client.log= debug: -> info: -> warn: -> error: -> Client.auth username, password if username @cache: (servers = []) -> Cache = new memcacher servers @bake: (model) -> extendsClass(model, MongoritoModel) object = new model model.collection = object.collection model.model = model model class MongoritoModel constructor: (@collection = '') -> fields: -> notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate'] fields = {} for field of @ fields[field] = @[field] if -1 is notFields.indexOf field fields @bakeModelsFromItems: (items, _model) -> models = [] for item in items item._id = item._id.toString() model = new _model model.collection = _model.collection for field of item model[field] = item[field] models.push model models @findById: (id, callback) -> that = @ query = (id, done) -> Client.collection(that.collection).find({ _id: new mongolian.ObjectId(id.toString()) }).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query id, (err, items) -> models = that.bakeModelsFromItems items, that.model callback err, models[0] key = "#{ @<KEY> }" Cache.get key, (err, result) -> if not result query id, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithOrderAndLimit: (criteria, order, limit, skip, callback) -> if typeof criteria is 'object' if typeof order is 'number' if typeof limit is 'function' callback = limit limit = order order = criteria criteria = {} if typeof limit is 'number' if typeof skip is 'function' callback = skip skip = limit limit = order order = criteria criteria = {} skip = 0 if not skip that = @ query = (criteria, order, limit, skip, done) -> Client.collection(that.collection).find(criteria).sort(order).limit(limit).skip(skip).toArray (err, items) -> done err, items if not Cache return query criteria, order, limit, skip, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-order-#{ order }-limit-#{ limit }-skip-#{ skip }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, order, limit, skip, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithOrder: (criteria, order, callback) -> if typeof criteria is 'object' and typeof order is 'function' callback = order order = criteria criteria = {} order = { _id: -1 } that = @ query = (criteria, order, done) -> Client.collection(that.collection).find(criteria).sort(order).toArray (err, items) -> done err, items if not Cache return query criteria, order, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-order-#{ order }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, order, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithLimit: (criteria, limit, skip, callback) -> if typeof criteria is 'number' if typeof limit is 'function' callback = limit limit = criteria criteria = {} if typeof limit is 'number' if typeof skip is 'function' callback = skip skip = limit criteria = {} else if typeof limit is 'function' callback = limit limit = 10 if typeof skip is 'function' callback = skip skip = 0 that = @ query = (criteria, limit, skip, done) -> Client.collection(that.collection).find(criteria).limit(limit).skip(skip).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query criteria, limit, skip, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @<KEY> limit <KEY>#{ skip }<KEY>-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, limit, skip, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @find: (criteria = {}, callback) -> if typeof(criteria) is 'function' callback = criteria criteria = {} that = @ query = (criteria, done) -> Client.collection(that.collection).find(criteria).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query criteria, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }<KEY>-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, (err, items) -> models = that.bakeModelsFromItems items, that.model Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models save: (callback) -> that = @ fields = do @fields notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'models'] keys = [] for field of @ keys.push field if -1 is notFields.indexOf field async.filter keys, (key, nextKey) -> if that["validate#{ key.camelize() }"] that["validate#{ key.camelize() }"] (valid) -> nextKey not valid else nextKey false , (results) -> return callback yes, results if results.length > 0 performOperation = -> if fields._id that.update callback, yes else that.create callback, yes if Cache then Cache.delByTag that.collection, performOperation else do performOperation create: (callback, fromSave = no) -> object = @fields() do @beforeCreate if @['beforeCreate'] do @aroundCreate if @['aroundCreate'] that = @ Client.collection(@collection).insert object, (err, result) -> result._id = result._id.toString() that._id = result._id do that.aroundCreate if that['aroundCreate'] do that.afterCreate if that['afterCreate'] process.nextTick -> callback err, result if callback update: (callback, fromSave = no) -> object = @fields() _id = new mongolian.ObjectId object._id delete object._id do @beforeUpdate if @['beforeUpdate'] do @aroundUpdate if @['aroundUpdate'] that = @ Client.collection(@collection).update { _id: _id }, object, (err, rowsUpdated) -> do that.aroundUpdate if that['aroundUpdate'] do that.afterUpdate if that['afterUpdate'] process.nextTick -> callback err, rowsUpdated if callback remove: (callback) -> object = @fields() _id = new mongolian.ObjectId object._id do @beforeRemove if @['beforeRemove'] do @aroundRemove if @['aroundRemove'] that = @ Cache.delByTag @collection, -> Client.collection(that.collection).remove { _id: _id }, (err) -> do that.aroundRemove if that['aroundRemove'] do that.afterRemove if that['afterRemove'] process.nextTick -> callback err if callback class GenericModel extends MongoritoModel module.exports= connect: Mongorito.connect disconnect: Mongorito.disconnect cache: Mongorito.cache bake: Mongorito.bake Model: MongoritoModel
true
mongolian = require 'mongolian' async = require 'async' memcacher = require 'memcacher' Client = undefined Cache = undefined `String.prototype.plural = function() { var s = this.trim().toLowerCase(); end = s.substr(-1); if(end == 'y') { var vowels = ['a', 'e', 'i', 'o', 'u']; s = s.substr(-2, 1) in vowels ? s + 's' : s.substr(0, s.length-1) + 'ies'; } else if(end == 'h') { s += s.substr(-2) == 'ch' || s.substr(-2) == 'sh' ? 'es' : 's'; } else if(end == 's') { s += 'es'; } else { s += 's'; } return s; } String.prototype.singular = function() { var s = this.trim().toLowerCase(); var end = s.substr(-3); if(end == 'ies') { s = s.substr(0, s.length-3) + 'y'; } else if(end == 'ses') { s = s.substr(0, s.length-2); } else { end = s.substr(-1); if(end == 's') { s = s.substr(0, s.length-1); } } return s; } String.prototype.camelize = function() { var s = 'x_' + this.trim().toLowerCase(); s = s.replace(/[\s_]/g, ' '); s = s.replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); }); return s.replace(/ /g, '').substr(1); } String.prototype.underscore = function() { return this.trim().toLowerCase().replace(/[\s]+/g, '_'); } var hasProp = Object.prototype.hasOwnProperty, extendsClass = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor(proto) { this.constructor = child; for(var method in proto) { this[method] = proto[method]; } } ctor.prototype = parent.prototype; child.prototype = new ctor(child.prototype); child.__super__ = parent.prototype; return child; } ` class Mongorito @disconnect: -> do Client.close @connect: (database = '', servers = [], username = '', password = '') -> if servers.length is 1 server = new mongolian servers[0] Client = server.db database Client.log= debug: -> info: -> warn: -> error: -> Client.auth username, password if username else # Support comes soon to Replica Sets server = new mongolian servers[0] Client = server.db database Client.log= debug: -> info: -> warn: -> error: -> Client.auth username, password if username @cache: (servers = []) -> Cache = new memcacher servers @bake: (model) -> extendsClass(model, MongoritoModel) object = new model model.collection = object.collection model.model = model model class MongoritoModel constructor: (@collection = '') -> fields: -> notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'beforeCreate', 'aroundCreate', 'afterCreate', 'beforeUpdate', 'aroundUpdate', 'afterUpdate'] fields = {} for field of @ fields[field] = @[field] if -1 is notFields.indexOf field fields @bakeModelsFromItems: (items, _model) -> models = [] for item in items item._id = item._id.toString() model = new _model model.collection = _model.collection for field of item model[field] = item[field] models.push model models @findById: (id, callback) -> that = @ query = (id, done) -> Client.collection(that.collection).find({ _id: new mongolian.ObjectId(id.toString()) }).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query id, (err, items) -> models = that.bakeModelsFromItems items, that.model callback err, models[0] key = "#{ @PI:KEY:<KEY>END_PI }" Cache.get key, (err, result) -> if not result query id, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithOrderAndLimit: (criteria, order, limit, skip, callback) -> if typeof criteria is 'object' if typeof order is 'number' if typeof limit is 'function' callback = limit limit = order order = criteria criteria = {} if typeof limit is 'number' if typeof skip is 'function' callback = skip skip = limit limit = order order = criteria criteria = {} skip = 0 if not skip that = @ query = (criteria, order, limit, skip, done) -> Client.collection(that.collection).find(criteria).sort(order).limit(limit).skip(skip).toArray (err, items) -> done err, items if not Cache return query criteria, order, limit, skip, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-order-#{ order }-limit-#{ limit }-skip-#{ skip }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, order, limit, skip, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithOrder: (criteria, order, callback) -> if typeof criteria is 'object' and typeof order is 'function' callback = order order = criteria criteria = {} order = { _id: -1 } that = @ query = (criteria, order, done) -> Client.collection(that.collection).find(criteria).sort(order).toArray (err, items) -> done err, items if not Cache return query criteria, order, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }-order-#{ order }-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, order, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @findWithLimit: (criteria, limit, skip, callback) -> if typeof criteria is 'number' if typeof limit is 'function' callback = limit limit = criteria criteria = {} if typeof limit is 'number' if typeof skip is 'function' callback = skip skip = limit criteria = {} else if typeof limit is 'function' callback = limit limit = 10 if typeof skip is 'function' callback = skip skip = 0 that = @ query = (criteria, limit, skip, done) -> Client.collection(that.collection).find(criteria).limit(limit).skip(skip).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query criteria, limit, skip, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @PI:KEY:<KEY>END_PI limit PI:KEY:<KEY>END_PI#{ skip }PI:KEY:<KEY>END_PI-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, limit, skip, (err, items) -> Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models @find: (criteria = {}, callback) -> if typeof(criteria) is 'function' callback = criteria criteria = {} that = @ query = (criteria, done) -> Client.collection(that.collection).find(criteria).toArray (err, items) -> process.nextTick -> done err, items if not Cache return query criteria, (err, items) -> models = that.bakeModelsFromItems items, that.model process.nextTick -> callback err, models key = "#{ @collection }PI:KEY:<KEY>END_PI-#{ JSON.stringify(criteria) }" Cache.get key, (err, result) -> if not result query criteria, (err, items) -> models = that.bakeModelsFromItems items, that.model Cache.set key, JSON.stringify(items), 2592000, [that.collection], -> process.nextTick -> callback err, models else models = that.bakeModelsFromItems JSON.parse(result), that.model process.nextTick -> callback err, models save: (callback) -> that = @ fields = do @fields notFields = ['constructor', 'save', 'collection', 'create', 'fields', 'update', 'remove', 'models'] keys = [] for field of @ keys.push field if -1 is notFields.indexOf field async.filter keys, (key, nextKey) -> if that["validate#{ key.camelize() }"] that["validate#{ key.camelize() }"] (valid) -> nextKey not valid else nextKey false , (results) -> return callback yes, results if results.length > 0 performOperation = -> if fields._id that.update callback, yes else that.create callback, yes if Cache then Cache.delByTag that.collection, performOperation else do performOperation create: (callback, fromSave = no) -> object = @fields() do @beforeCreate if @['beforeCreate'] do @aroundCreate if @['aroundCreate'] that = @ Client.collection(@collection).insert object, (err, result) -> result._id = result._id.toString() that._id = result._id do that.aroundCreate if that['aroundCreate'] do that.afterCreate if that['afterCreate'] process.nextTick -> callback err, result if callback update: (callback, fromSave = no) -> object = @fields() _id = new mongolian.ObjectId object._id delete object._id do @beforeUpdate if @['beforeUpdate'] do @aroundUpdate if @['aroundUpdate'] that = @ Client.collection(@collection).update { _id: _id }, object, (err, rowsUpdated) -> do that.aroundUpdate if that['aroundUpdate'] do that.afterUpdate if that['afterUpdate'] process.nextTick -> callback err, rowsUpdated if callback remove: (callback) -> object = @fields() _id = new mongolian.ObjectId object._id do @beforeRemove if @['beforeRemove'] do @aroundRemove if @['aroundRemove'] that = @ Cache.delByTag @collection, -> Client.collection(that.collection).remove { _id: _id }, (err) -> do that.aroundRemove if that['aroundRemove'] do that.afterRemove if that['afterRemove'] process.nextTick -> callback err if callback class GenericModel extends MongoritoModel module.exports= connect: Mongorito.connect disconnect: Mongorito.disconnect cache: Mongorito.cache bake: Mongorito.bake Model: MongoritoModel
[ { "context": "<option 2> (and|or <option #> ...)\n#\n# Author:\n# Michi Kono\n \nmodule.exports = (robot) ->\n robot.hear new ", "end": 210, "score": 0.9998761415481567, "start": 200, "tag": "NAME", "value": "Michi Kono" } ]
src/decide.coffee
michikono/hubot-decide
0
# Description: # Decides between two or more options mentioned in a chat room. # # Commands: # [decide|choose|pick] between(:) <option 1> and|or <option 2> (and|or <option #> ...) # # Author: # Michi Kono module.exports = (robot) -> robot.hear new RegExp('((decide|choose|pick)\\s*(between):?)\\s+([^.?!]+\\s+(or|and)\\s+[^.?!]+)', 'i'), (msg) -> msg.send ('Let\'s go with ') + msg.random( msg.match[4].split(' ' + msg.match[5] + ' ').map( # trim and strip special trailing/starting characters (s) -> s.replace(/^\s+|\s+$/g, '').replace(/\b[^\w]+$|^[^\w]+\b/i, '') ).filter((x) -> !!x) # filter empty choices )
206615
# Description: # Decides between two or more options mentioned in a chat room. # # Commands: # [decide|choose|pick] between(:) <option 1> and|or <option 2> (and|or <option #> ...) # # Author: # <NAME> module.exports = (robot) -> robot.hear new RegExp('((decide|choose|pick)\\s*(between):?)\\s+([^.?!]+\\s+(or|and)\\s+[^.?!]+)', 'i'), (msg) -> msg.send ('Let\'s go with ') + msg.random( msg.match[4].split(' ' + msg.match[5] + ' ').map( # trim and strip special trailing/starting characters (s) -> s.replace(/^\s+|\s+$/g, '').replace(/\b[^\w]+$|^[^\w]+\b/i, '') ).filter((x) -> !!x) # filter empty choices )
true
# Description: # Decides between two or more options mentioned in a chat room. # # Commands: # [decide|choose|pick] between(:) <option 1> and|or <option 2> (and|or <option #> ...) # # Author: # PI:NAME:<NAME>END_PI module.exports = (robot) -> robot.hear new RegExp('((decide|choose|pick)\\s*(between):?)\\s+([^.?!]+\\s+(or|and)\\s+[^.?!]+)', 'i'), (msg) -> msg.send ('Let\'s go with ') + msg.random( msg.match[4].split(' ' + msg.match[5] + ' ').map( # trim and strip special trailing/starting characters (s) -> s.replace(/^\s+|\s+$/g, '').replace(/\b[^\w]+$|^[^\w]+\b/i, '') ).filter((x) -> !!x) # filter empty choices )
[ { "context": "calhost'\n'port': 8080\n'credentials':\n 'user': 'example'\n 'password': 'samplepass'\n", "end": 68, "score": 0.8492361903190613, "start": 61, "tag": "USERNAME", "value": "example" }, { "context": "dentials':\n 'user': 'example'\n 'password': 'samplepass'\n"...
node_modules/bool.js/node_modules/booljs-cli/boilerplate/configuration/server.cson
moreliahacks/api-morelia-tweets
0
'host': 'localhost' 'port': 8080 'credentials': 'user': 'example' 'password': 'samplepass'
219129
'host': 'localhost' 'port': 8080 'credentials': 'user': 'example' 'password': '<PASSWORD>'
true
'host': 'localhost' 'port': 8080 'credentials': 'user': 'example' 'password': 'PI:PASSWORD:<PASSWORD>END_PI'
[ { "context": "eeScript optional)'\n version: '0.1'\n authors: ['Álvaro Cuesta']\n", "end": 2937, "score": 0.9998776912689209, "start": 2924, "tag": "NAME", "value": "Álvaro Cuesta" } ]
plugins/eval.coffee
alvaro-cuesta/nerdobot
2
Sandbox = require 'sandbox' # TODO: bugged! util = require 'util' MAX_CHARS = 128 MAX_LOGS = 30 module.exports = ({coffee}) -> sayOutput = (to) => (out) => stdout = out.result.replace(/[\r|\n]/g, '') if stdout.length > MAX_CHARS stdout = stdout[...MAX_CHARS] + "... #{@BOLD}(output truncated)#{@RESET}" @say to, " #{@BOLD}=#{@RESET} #{stdout}" return unless out.console.length > 0 con = "[ " con += (util.inspect(log) for log in out.console[...MAX_LOGS]).join ', ' if out.console.length > MAX_LOGS con += ', ...' con += " ]" con = con.replace(/[\r|\n]/g, '') if con.length > MAX_CHARS con = con[...MAX_CHARS] + "... #{@BOLD}(output truncated)#{@RESET}" @say to, "#{@BOLD}>>#{@RESET} #{con}" s = new Sandbox() readBlock = (nick, readOn, end_pattern, cb) => do => buffer = '' message = (from, msg, to) -> if from.nick == nick and msg != end_pattern and to == readOn buffer += "#{msg}\n" end = (from, trailing, to) => if from.nick == nick and to == readOn cb buffer @events.removeListener 'message', message @commands.removeListener end_pattern, end @events.on 'message', message @commands.on end_pattern, end @addCommand 'eval', args: '<js code>' description: 'Evaluate JavaScript code' ({nick}, trailing, to) => s.run trailing, sayOutput to ? nick @addCommand "eval-block", description: 'Evaluate a block of JavaScript code', help: "When done, write #{@config.prefix}#{@config.prefix}end and the full block will be executed" ({nick}, trailing, to) => to ?= nnick @say to, " #{@color 'red'}! Reading JavaScript block from #{nick}#{@RESET}" readBlock nick, to, "#{@config.prefix}end", (buffer) => s.run buffer, sayOutput to if coffee cs = require 'coffee-script' @addCommand 'coffee', args: '<cs code>' description: 'Evaluate CoffeeScript code' ({nick}, trailing, to) => to ?= nick try js = cs.compile trailing, bare: true s.run js, sayOutput to catch error @say to, " #{@BOLD}=#{@RESET} '#{error}'" @addCommand "coffee-block", description: 'Evaluate a block of CoffeeScript code' help: "When done, write #{@config.prefix}#{@config.prefix}end and the full block will be executed" ({nick}, trailing, to) => to ?= nick @say to, " #{@color 'red'}! Reading CoffeeScript block from #{nick}#{@RESET}" readBlock nick, to, "#{@config.prefix}end", (buffer) => try js = cs.compile trailing, bare: true s.run js, sayOutput to catch error @say to, " #{@BOLD}=#{@RESET} '#{error}'" name: 'Eval' description: 'Evaluate sandboxed code using !eval (CoffeeScript optional)' version: '0.1' authors: ['Álvaro Cuesta']
75572
Sandbox = require 'sandbox' # TODO: bugged! util = require 'util' MAX_CHARS = 128 MAX_LOGS = 30 module.exports = ({coffee}) -> sayOutput = (to) => (out) => stdout = out.result.replace(/[\r|\n]/g, '') if stdout.length > MAX_CHARS stdout = stdout[...MAX_CHARS] + "... #{@BOLD}(output truncated)#{@RESET}" @say to, " #{@BOLD}=#{@RESET} #{stdout}" return unless out.console.length > 0 con = "[ " con += (util.inspect(log) for log in out.console[...MAX_LOGS]).join ', ' if out.console.length > MAX_LOGS con += ', ...' con += " ]" con = con.replace(/[\r|\n]/g, '') if con.length > MAX_CHARS con = con[...MAX_CHARS] + "... #{@BOLD}(output truncated)#{@RESET}" @say to, "#{@BOLD}>>#{@RESET} #{con}" s = new Sandbox() readBlock = (nick, readOn, end_pattern, cb) => do => buffer = '' message = (from, msg, to) -> if from.nick == nick and msg != end_pattern and to == readOn buffer += "#{msg}\n" end = (from, trailing, to) => if from.nick == nick and to == readOn cb buffer @events.removeListener 'message', message @commands.removeListener end_pattern, end @events.on 'message', message @commands.on end_pattern, end @addCommand 'eval', args: '<js code>' description: 'Evaluate JavaScript code' ({nick}, trailing, to) => s.run trailing, sayOutput to ? nick @addCommand "eval-block", description: 'Evaluate a block of JavaScript code', help: "When done, write #{@config.prefix}#{@config.prefix}end and the full block will be executed" ({nick}, trailing, to) => to ?= nnick @say to, " #{@color 'red'}! Reading JavaScript block from #{nick}#{@RESET}" readBlock nick, to, "#{@config.prefix}end", (buffer) => s.run buffer, sayOutput to if coffee cs = require 'coffee-script' @addCommand 'coffee', args: '<cs code>' description: 'Evaluate CoffeeScript code' ({nick}, trailing, to) => to ?= nick try js = cs.compile trailing, bare: true s.run js, sayOutput to catch error @say to, " #{@BOLD}=#{@RESET} '#{error}'" @addCommand "coffee-block", description: 'Evaluate a block of CoffeeScript code' help: "When done, write #{@config.prefix}#{@config.prefix}end and the full block will be executed" ({nick}, trailing, to) => to ?= nick @say to, " #{@color 'red'}! Reading CoffeeScript block from #{nick}#{@RESET}" readBlock nick, to, "#{@config.prefix}end", (buffer) => try js = cs.compile trailing, bare: true s.run js, sayOutput to catch error @say to, " #{@BOLD}=#{@RESET} '#{error}'" name: 'Eval' description: 'Evaluate sandboxed code using !eval (CoffeeScript optional)' version: '0.1' authors: ['<NAME>']
true
Sandbox = require 'sandbox' # TODO: bugged! util = require 'util' MAX_CHARS = 128 MAX_LOGS = 30 module.exports = ({coffee}) -> sayOutput = (to) => (out) => stdout = out.result.replace(/[\r|\n]/g, '') if stdout.length > MAX_CHARS stdout = stdout[...MAX_CHARS] + "... #{@BOLD}(output truncated)#{@RESET}" @say to, " #{@BOLD}=#{@RESET} #{stdout}" return unless out.console.length > 0 con = "[ " con += (util.inspect(log) for log in out.console[...MAX_LOGS]).join ', ' if out.console.length > MAX_LOGS con += ', ...' con += " ]" con = con.replace(/[\r|\n]/g, '') if con.length > MAX_CHARS con = con[...MAX_CHARS] + "... #{@BOLD}(output truncated)#{@RESET}" @say to, "#{@BOLD}>>#{@RESET} #{con}" s = new Sandbox() readBlock = (nick, readOn, end_pattern, cb) => do => buffer = '' message = (from, msg, to) -> if from.nick == nick and msg != end_pattern and to == readOn buffer += "#{msg}\n" end = (from, trailing, to) => if from.nick == nick and to == readOn cb buffer @events.removeListener 'message', message @commands.removeListener end_pattern, end @events.on 'message', message @commands.on end_pattern, end @addCommand 'eval', args: '<js code>' description: 'Evaluate JavaScript code' ({nick}, trailing, to) => s.run trailing, sayOutput to ? nick @addCommand "eval-block", description: 'Evaluate a block of JavaScript code', help: "When done, write #{@config.prefix}#{@config.prefix}end and the full block will be executed" ({nick}, trailing, to) => to ?= nnick @say to, " #{@color 'red'}! Reading JavaScript block from #{nick}#{@RESET}" readBlock nick, to, "#{@config.prefix}end", (buffer) => s.run buffer, sayOutput to if coffee cs = require 'coffee-script' @addCommand 'coffee', args: '<cs code>' description: 'Evaluate CoffeeScript code' ({nick}, trailing, to) => to ?= nick try js = cs.compile trailing, bare: true s.run js, sayOutput to catch error @say to, " #{@BOLD}=#{@RESET} '#{error}'" @addCommand "coffee-block", description: 'Evaluate a block of CoffeeScript code' help: "When done, write #{@config.prefix}#{@config.prefix}end and the full block will be executed" ({nick}, trailing, to) => to ?= nick @say to, " #{@color 'red'}! Reading CoffeeScript block from #{nick}#{@RESET}" readBlock nick, to, "#{@config.prefix}end", (buffer) => try js = cs.compile trailing, bare: true s.run js, sayOutput to catch error @say to, " #{@BOLD}=#{@RESET} '#{error}'" name: 'Eval' description: 'Evaluate sandboxed code using !eval (CoffeeScript optional)' version: '0.1' authors: ['PI:NAME:<NAME>END_PI']
[ { "context": "odules/.bin/coffee\n\n###\n# server.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Our NodeJS ser", "end": 70, "score": 0.9998058676719666, "start": 59, "tag": "NAME", "value": "Dan Nichols" } ]
server.coffee
dlnichols/h_media
0
#!node_modules/.bin/coffee ### # server.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Our NodeJS server application. Nothing too special here, a quick ExpressJS # app that serves a single page AngularJS app. In production all it will # handle is the single page app, as all static content will be handled by a # reverse proxy. ### 'use strict' # Register the coffee interpreter require 'coffee-script/register' # Load the environment env = require './lib/config/environment' # External libs app = require('express')() # Bootstrap mongoose require('./lib/bootstrap') env # Load models require('./lib/models') env # Configure Express require('./lib/express') app # Application Routes require('./lib/routes') app # Errors require('./lib/errors') app # Setup the mailer require('./lib/mailer') app # Start server app.listen env.port, -> console.log 'Express server listening on port %d in %s mode', env.port, app.get('env') return # Expose app module.exports = exports = app
183263
#!node_modules/.bin/coffee ### # server.coffee # # © 2014 <NAME> # See LICENSE for more details # # Our NodeJS server application. Nothing too special here, a quick ExpressJS # app that serves a single page AngularJS app. In production all it will # handle is the single page app, as all static content will be handled by a # reverse proxy. ### 'use strict' # Register the coffee interpreter require 'coffee-script/register' # Load the environment env = require './lib/config/environment' # External libs app = require('express')() # Bootstrap mongoose require('./lib/bootstrap') env # Load models require('./lib/models') env # Configure Express require('./lib/express') app # Application Routes require('./lib/routes') app # Errors require('./lib/errors') app # Setup the mailer require('./lib/mailer') app # Start server app.listen env.port, -> console.log 'Express server listening on port %d in %s mode', env.port, app.get('env') return # Expose app module.exports = exports = app
true
#!node_modules/.bin/coffee ### # server.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Our NodeJS server application. Nothing too special here, a quick ExpressJS # app that serves a single page AngularJS app. In production all it will # handle is the single page app, as all static content will be handled by a # reverse proxy. ### 'use strict' # Register the coffee interpreter require 'coffee-script/register' # Load the environment env = require './lib/config/environment' # External libs app = require('express')() # Bootstrap mongoose require('./lib/bootstrap') env # Load models require('./lib/models') env # Configure Express require('./lib/express') app # Application Routes require('./lib/routes') app # Errors require('./lib/errors') app # Setup the mailer require('./lib/mailer') app # Start server app.listen env.port, -> console.log 'Express server listening on port %d in %s mode', env.port, app.get('env') return # Expose app module.exports = exports = app
[ { "context": "on: 1, tailNumber: 1 }, { unique: true })\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass Airc", "end": 558, "score": 0.9998505115509033, "start": 546, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/schema/AircraftChecklistSchema.coffee
qrefdev/qref
0
mongoose = require('mongoose') Schema = mongoose.Schema Mixed = Schema.Types.Mixed ObjectId = Schema.ObjectId AircraftChecklistSectionSchema = require('./AircraftChecklistSectionSchema') AircraftChecklistCategorySchema = require('./AircraftChecklistCategorySchema'); ### Schema representing a manufacturer/model specific checklist. @example MongoDB Collection db.aircraft.checklists @example MongoDB Indexes db.aircraft.checklists.ensureIndex({ manufacturer: 1, model: 1, version: 1, tailNumber: 1 }, { unique: true }) @author Nathan Klick @copyright QRef 2012 @abstract ### class AircraftChecklistSchemaInternal ### @property [ObjectId] (Required) The manufacturer that this checklist is built against. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId ref: 'aircraft.manufacturers' required: true ### @property [ObjectId] (Required) The model that this checklist is built against. @see AircraftModelSchemaInternal ### model: type: ObjectId ref: 'aircraft.models' required: true ### @property [Number] (Optional) The order in which this checklist should appear relative to the other checklists. ### index: type: Number required: false default: null ### @property [String] (Optional) The tail number for a list which has been customized to a specific plane. ### tailNumber: type: String required: false default: null ### @property [ObjectId] (Optional) The user which owns this customized version of the checklist. @see UserSchemaInternal ### user: type: ObjectId ref: 'users' required: false default: null ### @property [Number] (Required) The version number of this checklist. ### version: type: Number required: true default: 1 ### @property [String] (Optional) A server-based relative path to the product icon. This path should be relative to the server root. ### productIcon: type: String required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of preflight sections. ### preflight: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of takeoff sections. ### takeoff: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of landing sections. ### landing: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of emergency sections. ### emergencies: type: [AircraftChecklistCategorySchema] required: false ### @property [Boolean] (Required) A true/false value indicating whether this record has been deleted. Required for soft-delete support. ### isDeleted: type: Boolean required: true default: false timestamp: type: Date required: false default: new Date() currentSerialNumber: type: Number required: true knownSerialNumbers: type: [Mixed] required: false default: [] lastCheckpointSerialNumber: type: Number required: true AircraftChecklistSchema = new Schema(new AircraftChecklistSchemaInternal()) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, version: 1, tailNumber: 1, user: 1 }, { unique: true }) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, user: 1 }) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, user: 1, version: 1 }) module.exports = AircraftChecklistSchema
212687
mongoose = require('mongoose') Schema = mongoose.Schema Mixed = Schema.Types.Mixed ObjectId = Schema.ObjectId AircraftChecklistSectionSchema = require('./AircraftChecklistSectionSchema') AircraftChecklistCategorySchema = require('./AircraftChecklistCategorySchema'); ### Schema representing a manufacturer/model specific checklist. @example MongoDB Collection db.aircraft.checklists @example MongoDB Indexes db.aircraft.checklists.ensureIndex({ manufacturer: 1, model: 1, version: 1, tailNumber: 1 }, { unique: true }) @author <NAME> @copyright QRef 2012 @abstract ### class AircraftChecklistSchemaInternal ### @property [ObjectId] (Required) The manufacturer that this checklist is built against. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId ref: 'aircraft.manufacturers' required: true ### @property [ObjectId] (Required) The model that this checklist is built against. @see AircraftModelSchemaInternal ### model: type: ObjectId ref: 'aircraft.models' required: true ### @property [Number] (Optional) The order in which this checklist should appear relative to the other checklists. ### index: type: Number required: false default: null ### @property [String] (Optional) The tail number for a list which has been customized to a specific plane. ### tailNumber: type: String required: false default: null ### @property [ObjectId] (Optional) The user which owns this customized version of the checklist. @see UserSchemaInternal ### user: type: ObjectId ref: 'users' required: false default: null ### @property [Number] (Required) The version number of this checklist. ### version: type: Number required: true default: 1 ### @property [String] (Optional) A server-based relative path to the product icon. This path should be relative to the server root. ### productIcon: type: String required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of preflight sections. ### preflight: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of takeoff sections. ### takeoff: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of landing sections. ### landing: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of emergency sections. ### emergencies: type: [AircraftChecklistCategorySchema] required: false ### @property [Boolean] (Required) A true/false value indicating whether this record has been deleted. Required for soft-delete support. ### isDeleted: type: Boolean required: true default: false timestamp: type: Date required: false default: new Date() currentSerialNumber: type: Number required: true knownSerialNumbers: type: [Mixed] required: false default: [] lastCheckpointSerialNumber: type: Number required: true AircraftChecklistSchema = new Schema(new AircraftChecklistSchemaInternal()) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, version: 1, tailNumber: 1, user: 1 }, { unique: true }) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, user: 1 }) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, user: 1, version: 1 }) module.exports = AircraftChecklistSchema
true
mongoose = require('mongoose') Schema = mongoose.Schema Mixed = Schema.Types.Mixed ObjectId = Schema.ObjectId AircraftChecklistSectionSchema = require('./AircraftChecklistSectionSchema') AircraftChecklistCategorySchema = require('./AircraftChecklistCategorySchema'); ### Schema representing a manufacturer/model specific checklist. @example MongoDB Collection db.aircraft.checklists @example MongoDB Indexes db.aircraft.checklists.ensureIndex({ manufacturer: 1, model: 1, version: 1, tailNumber: 1 }, { unique: true }) @author PI:NAME:<NAME>END_PI @copyright QRef 2012 @abstract ### class AircraftChecklistSchemaInternal ### @property [ObjectId] (Required) The manufacturer that this checklist is built against. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId ref: 'aircraft.manufacturers' required: true ### @property [ObjectId] (Required) The model that this checklist is built against. @see AircraftModelSchemaInternal ### model: type: ObjectId ref: 'aircraft.models' required: true ### @property [Number] (Optional) The order in which this checklist should appear relative to the other checklists. ### index: type: Number required: false default: null ### @property [String] (Optional) The tail number for a list which has been customized to a specific plane. ### tailNumber: type: String required: false default: null ### @property [ObjectId] (Optional) The user which owns this customized version of the checklist. @see UserSchemaInternal ### user: type: ObjectId ref: 'users' required: false default: null ### @property [Number] (Required) The version number of this checklist. ### version: type: Number required: true default: 1 ### @property [String] (Optional) A server-based relative path to the product icon. This path should be relative to the server root. ### productIcon: type: String required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of preflight sections. ### preflight: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of takeoff sections. ### takeoff: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of landing sections. ### landing: type: [AircraftChecklistSectionSchema] required: false ### @property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of emergency sections. ### emergencies: type: [AircraftChecklistCategorySchema] required: false ### @property [Boolean] (Required) A true/false value indicating whether this record has been deleted. Required for soft-delete support. ### isDeleted: type: Boolean required: true default: false timestamp: type: Date required: false default: new Date() currentSerialNumber: type: Number required: true knownSerialNumbers: type: [Mixed] required: false default: [] lastCheckpointSerialNumber: type: Number required: true AircraftChecklistSchema = new Schema(new AircraftChecklistSchemaInternal()) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, version: 1, tailNumber: 1, user: 1 }, { unique: true }) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, user: 1 }) AircraftChecklistSchema.index({ manufacturer: 1, model: 1, user: 1, version: 1 }) module.exports = AircraftChecklistSchema
[ { "context": "p = {}\n\n@AdminConfig = AdminConfig = {\n name: 'Hoagie Admin'\n adminEmails: ['hung.dao@me.com', 'meph", "end": 101, "score": 0.6454104781150818, "start": 99, "tag": "NAME", "value": "ag" }, { "context": "onfig = {\n name: 'Hoagie Admin'\n adminEmails: ['hung.dao@...
app/lib/app.coffee
zocoi/hoahoa
0
# App: The Global Application Namespace @App = App = {} @AdminConfig = AdminConfig = { name: 'Hoagie Admin' adminEmails: ['hung.dao@me.com', 'mephis1987@gmail.com'] collections: { # Documents: {} Groups: tableColumns: [ {label: 'Name', name: 'name'} ] auxCollections: ['Meteor.users'] } }
123760
# App: The Global Application Namespace @App = App = {} @AdminConfig = AdminConfig = { name: 'Ho<NAME>ie Admin' adminEmails: ['<EMAIL>', '<EMAIL>'] collections: { # Documents: {} Groups: tableColumns: [ {label: 'Name', name: 'name'} ] auxCollections: ['Meteor.users'] } }
true
# App: The Global Application Namespace @App = App = {} @AdminConfig = AdminConfig = { name: 'HoPI:NAME:<NAME>END_PIie Admin' adminEmails: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI'] collections: { # Documents: {} Groups: tableColumns: [ {label: 'Name', name: 'name'} ] auxCollections: ['Meteor.users'] } }
[ { "context": "00000000000\" #2002-02-14T00:00:00.000Z\n\t\t\temail: \"someone@gmail.com\"\n\t\t@AnalyticsManager =\n\t\t\tgetLastOccurrence: sino", "end": 439, "score": 0.9999217391014099, "start": 422, "tag": "EMAIL", "value": "someone@gmail.com" }, { "context": "\t\tresult = @handl...
test/unit/coffee/Announcement/AnnouncementsHandlerTests.coffee
davidmehren/web-sharelatex
1
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') modulePath = path.join __dirname, '../../../../app/js/Features/Announcements/AnnouncementsHandler' sinon = require("sinon") expect = require("chai").expect describe 'AnnouncementsHandler', -> beforeEach -> @user = _id:"3c6afe000000000000000000" #2002-02-14T00:00:00.000Z email: "someone@gmail.com" @AnalyticsManager = getLastOccurrence: sinon.stub() @BlogHandler = getLatestAnnouncements:sinon.stub() @settings = {} @handler = SandboxedModule.require modulePath, requires: "../Analytics/AnalyticsManager":@AnalyticsManager "../Blog/BlogHandler":@BlogHandler "settings-sharelatex":@settings "logger-sharelatex": log:-> describe "getUnreadAnnouncements", -> beforeEach -> @stubbedAnnouncements = [ { date: new Date(1478836800000), id: '/2016/11/01/introducting-latex-code-checker' }, { date: new Date(1308369600000), id: '/2013/08/02/thesis-series-pt1' }, { date: new Date(1108369600000), id: '/2005/08/04/somethingelse' }, { date: new Date(1208369600000), id: '/2008/04/12/title-date-irrelivant' } ] @BlogHandler.getLatestAnnouncements.callsArgWith(0, null, @stubbedAnnouncements) it "should mark all announcements as read is false", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal false announcements[1].read.should.equal false announcements[2].read.should.equal false announcements[3].read.should.equal false done() it "should should be sorted again to ensure correct order", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[3].should.equal @stubbedAnnouncements[2] announcements[2].should.equal @stubbedAnnouncements[3] announcements[1].should.equal @stubbedAnnouncements[1] announcements[0].should.equal @stubbedAnnouncements[0] done() it "should return older ones marked as read as well", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, {segmentation:{blogPostId:"/2008/04/12/title-date-irrelivant"}}) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].id.should.equal @stubbedAnnouncements[0].id announcements[0].read.should.equal false announcements[1].id.should.equal @stubbedAnnouncements[1].id announcements[1].read.should.equal false announcements[2].id.should.equal @stubbedAnnouncements[3].id announcements[2].read.should.equal true announcements[3].id.should.equal @stubbedAnnouncements[2].id announcements[3].read.should.equal true done() it "should return all of them marked as read", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, {segmentation:{blogPostId:"/2016/11/01/introducting-latex-code-checker"}}) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal true announcements[1].read.should.equal true announcements[2].read.should.equal true announcements[3].read.should.equal true done() it "should return posts older than signup date as read", (done)-> @stubbedAnnouncements.push({ date: new Date(978836800000), id: '/2001/04/12/title-date-irrelivant' }) @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal false announcements[1].read.should.equal false announcements[2].read.should.equal false announcements[3].read.should.equal false announcements[4].read.should.equal true announcements[4].id.should.equal '/2001/04/12/title-date-irrelivant' done() describe "with custom domain announcements", -> beforeEach -> @stubbedDomainSpecificAnn = [ { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"iaaa" date: new Date(1308369600000).toString() } ] @handler._domainSpecificAnnouncements = sinon.stub().returns(@stubbedDomainSpecificAnn) it "should insert the domain specific in the correct place", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[4].should.equal @stubbedAnnouncements[2] announcements[3].should.equal @stubbedAnnouncements[3] announcements[2].should.equal @stubbedAnnouncements[1] announcements[1].should.equal @stubbedDomainSpecificAnn[0] announcements[0].should.equal @stubbedAnnouncements[0] done() describe "_domainSpecificAnnouncements", -> beforeEach -> @settings.domainAnnouncements = [ { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"id1" date: new Date(1308369600000).toString() }, { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" date: new Date(1308369600000).toString() }, { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"id3" date: new Date(1308369600000).toString() } ] it "should filter announcments which don't have an id", (done) -> result = @handler._domainSpecificAnnouncements "someone@gmail.com" result.length.should.equal 2 result[0].id.should.equal "id1" result[1].id.should.equal "id3" done() it "should match on domain", (done) -> @settings.domainAnnouncements[2].domains = ["yahoo.com"] result = @handler._domainSpecificAnnouncements "someone@gmail.com" result.length.should.equal 1 result[0].id.should.equal "id1" done()
82107
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') modulePath = path.join __dirname, '../../../../app/js/Features/Announcements/AnnouncementsHandler' sinon = require("sinon") expect = require("chai").expect describe 'AnnouncementsHandler', -> beforeEach -> @user = _id:"3c6afe000000000000000000" #2002-02-14T00:00:00.000Z email: "<EMAIL>" @AnalyticsManager = getLastOccurrence: sinon.stub() @BlogHandler = getLatestAnnouncements:sinon.stub() @settings = {} @handler = SandboxedModule.require modulePath, requires: "../Analytics/AnalyticsManager":@AnalyticsManager "../Blog/BlogHandler":@BlogHandler "settings-sharelatex":@settings "logger-sharelatex": log:-> describe "getUnreadAnnouncements", -> beforeEach -> @stubbedAnnouncements = [ { date: new Date(1478836800000), id: '/2016/11/01/introducting-latex-code-checker' }, { date: new Date(1308369600000), id: '/2013/08/02/thesis-series-pt1' }, { date: new Date(1108369600000), id: '/2005/08/04/somethingelse' }, { date: new Date(1208369600000), id: '/2008/04/12/title-date-irrelivant' } ] @BlogHandler.getLatestAnnouncements.callsArgWith(0, null, @stubbedAnnouncements) it "should mark all announcements as read is false", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal false announcements[1].read.should.equal false announcements[2].read.should.equal false announcements[3].read.should.equal false done() it "should should be sorted again to ensure correct order", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[3].should.equal @stubbedAnnouncements[2] announcements[2].should.equal @stubbedAnnouncements[3] announcements[1].should.equal @stubbedAnnouncements[1] announcements[0].should.equal @stubbedAnnouncements[0] done() it "should return older ones marked as read as well", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, {segmentation:{blogPostId:"/2008/04/12/title-date-irrelivant"}}) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].id.should.equal @stubbedAnnouncements[0].id announcements[0].read.should.equal false announcements[1].id.should.equal @stubbedAnnouncements[1].id announcements[1].read.should.equal false announcements[2].id.should.equal @stubbedAnnouncements[3].id announcements[2].read.should.equal true announcements[3].id.should.equal @stubbedAnnouncements[2].id announcements[3].read.should.equal true done() it "should return all of them marked as read", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, {segmentation:{blogPostId:"/2016/11/01/introducting-latex-code-checker"}}) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal true announcements[1].read.should.equal true announcements[2].read.should.equal true announcements[3].read.should.equal true done() it "should return posts older than signup date as read", (done)-> @stubbedAnnouncements.push({ date: new Date(978836800000), id: '/2001/04/12/title-date-irrelivant' }) @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal false announcements[1].read.should.equal false announcements[2].read.should.equal false announcements[3].read.should.equal false announcements[4].read.should.equal true announcements[4].id.should.equal '/2001/04/12/title-date-irrelivant' done() describe "with custom domain announcements", -> beforeEach -> @stubbedDomainSpecificAnn = [ { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"iaaa" date: new Date(1308369600000).toString() } ] @handler._domainSpecificAnnouncements = sinon.stub().returns(@stubbedDomainSpecificAnn) it "should insert the domain specific in the correct place", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[4].should.equal @stubbedAnnouncements[2] announcements[3].should.equal @stubbedAnnouncements[3] announcements[2].should.equal @stubbedAnnouncements[1] announcements[1].should.equal @stubbedDomainSpecificAnn[0] announcements[0].should.equal @stubbedAnnouncements[0] done() describe "_domainSpecificAnnouncements", -> beforeEach -> @settings.domainAnnouncements = [ { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"id1" date: new Date(1308369600000).toString() }, { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" date: new Date(1308369600000).toString() }, { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"id3" date: new Date(1308369600000).toString() } ] it "should filter announcments which don't have an id", (done) -> result = @handler._domainSpecificAnnouncements "<EMAIL>" result.length.should.equal 2 result[0].id.should.equal "id1" result[1].id.should.equal "id3" done() it "should match on domain", (done) -> @settings.domainAnnouncements[2].domains = ["yahoo.com"] result = @handler._domainSpecificAnnouncements "<EMAIL>" result.length.should.equal 1 result[0].id.should.equal "id1" done()
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') modulePath = path.join __dirname, '../../../../app/js/Features/Announcements/AnnouncementsHandler' sinon = require("sinon") expect = require("chai").expect describe 'AnnouncementsHandler', -> beforeEach -> @user = _id:"3c6afe000000000000000000" #2002-02-14T00:00:00.000Z email: "PI:EMAIL:<EMAIL>END_PI" @AnalyticsManager = getLastOccurrence: sinon.stub() @BlogHandler = getLatestAnnouncements:sinon.stub() @settings = {} @handler = SandboxedModule.require modulePath, requires: "../Analytics/AnalyticsManager":@AnalyticsManager "../Blog/BlogHandler":@BlogHandler "settings-sharelatex":@settings "logger-sharelatex": log:-> describe "getUnreadAnnouncements", -> beforeEach -> @stubbedAnnouncements = [ { date: new Date(1478836800000), id: '/2016/11/01/introducting-latex-code-checker' }, { date: new Date(1308369600000), id: '/2013/08/02/thesis-series-pt1' }, { date: new Date(1108369600000), id: '/2005/08/04/somethingelse' }, { date: new Date(1208369600000), id: '/2008/04/12/title-date-irrelivant' } ] @BlogHandler.getLatestAnnouncements.callsArgWith(0, null, @stubbedAnnouncements) it "should mark all announcements as read is false", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal false announcements[1].read.should.equal false announcements[2].read.should.equal false announcements[3].read.should.equal false done() it "should should be sorted again to ensure correct order", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[3].should.equal @stubbedAnnouncements[2] announcements[2].should.equal @stubbedAnnouncements[3] announcements[1].should.equal @stubbedAnnouncements[1] announcements[0].should.equal @stubbedAnnouncements[0] done() it "should return older ones marked as read as well", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, {segmentation:{blogPostId:"/2008/04/12/title-date-irrelivant"}}) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].id.should.equal @stubbedAnnouncements[0].id announcements[0].read.should.equal false announcements[1].id.should.equal @stubbedAnnouncements[1].id announcements[1].read.should.equal false announcements[2].id.should.equal @stubbedAnnouncements[3].id announcements[2].read.should.equal true announcements[3].id.should.equal @stubbedAnnouncements[2].id announcements[3].read.should.equal true done() it "should return all of them marked as read", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, {segmentation:{blogPostId:"/2016/11/01/introducting-latex-code-checker"}}) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal true announcements[1].read.should.equal true announcements[2].read.should.equal true announcements[3].read.should.equal true done() it "should return posts older than signup date as read", (done)-> @stubbedAnnouncements.push({ date: new Date(978836800000), id: '/2001/04/12/title-date-irrelivant' }) @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[0].read.should.equal false announcements[1].read.should.equal false announcements[2].read.should.equal false announcements[3].read.should.equal false announcements[4].read.should.equal true announcements[4].id.should.equal '/2001/04/12/title-date-irrelivant' done() describe "with custom domain announcements", -> beforeEach -> @stubbedDomainSpecificAnn = [ { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"iaaa" date: new Date(1308369600000).toString() } ] @handler._domainSpecificAnnouncements = sinon.stub().returns(@stubbedDomainSpecificAnn) it "should insert the domain specific in the correct place", (done)-> @AnalyticsManager.getLastOccurrence.callsArgWith(2, null, []) @handler.getUnreadAnnouncements @user, (err, announcements)=> announcements[4].should.equal @stubbedAnnouncements[2] announcements[3].should.equal @stubbedAnnouncements[3] announcements[2].should.equal @stubbedAnnouncements[1] announcements[1].should.equal @stubbedDomainSpecificAnn[0] announcements[0].should.equal @stubbedAnnouncements[0] done() describe "_domainSpecificAnnouncements", -> beforeEach -> @settings.domainAnnouncements = [ { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"id1" date: new Date(1308369600000).toString() }, { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" date: new Date(1308369600000).toString() }, { domains: ["gmail.com", 'yahoo.edu'] title: "some message" excerpt: "read this" url:"http://www.sharelatex.com/i/somewhere" id:"id3" date: new Date(1308369600000).toString() } ] it "should filter announcments which don't have an id", (done) -> result = @handler._domainSpecificAnnouncements "PI:EMAIL:<EMAIL>END_PI" result.length.should.equal 2 result[0].id.should.equal "id1" result[1].id.should.equal "id3" done() it "should match on domain", (done) -> @settings.domainAnnouncements[2].domains = ["yahoo.com"] result = @handler._domainSpecificAnnouncements "PI:EMAIL:<EMAIL>END_PI" result.length.should.equal 1 result[0].id.should.equal "id1" done()
[ { "context": "rage\n setState: (key, value) ->\n keyName = \"#{@_options.name}_#{key}\"\n @_options.storage.se", "end": 1422, "score": 0.8734311461448669, "start": 1419, "tag": "KEY", "value": "\"#{" }, { "context": " setState: (key, value) ->\n keyName = \"#{@_o...
src/coffee/bootstrap-tour.coffee
ma-si/bootstrap-tour
1
(($, window) -> document = window.document class Tour constructor: (options) -> @_options = $.extend({ name: 'tour' container: 'body' keyboard: true storage: window.localStorage debug: false backdrop: false redirect: true basePath: '' template: "<div class='popover tour'> <div class='arrow'></div> <h3 class='popover-title'></h3> <div class='popover-content'></div> <nav class='popover-navigation'> <div class='btn-group'> <button class='btn btn-default' data-role='prev'>&laquo; Prev</button> <button class='btn btn-default' data-role='next'>Next &raquo;</button> </div> <button class='btn btn-default' data-role='end'>End tour</button> </nav> </div>" afterSetState: (key, value) -> afterGetState: (key, value) -> afterRemoveState: (key) -> onStart: (tour) -> onEnd: (tour) -> onShow: (tour) -> onShown: (tour) -> onHide: (tour) -> onHidden: (tour) -> onNext: (tour) -> onPrev: (tour) -> }, options) @_steps = [] @setCurrentStep() @backdrop = { overlay: null step: null background: null } # Set a state in storage setState: (key, value) -> keyName = "#{@_options.name}_#{key}" @_options.storage.setItem(keyName, value) @_options.afterSetState(keyName, value) # Remove the current state from the storage layer removeState: (key) -> keyName = "#{@_options.name}_#{key}" @_options.storage.removeItem(keyName) @_options.afterRemoveState(keyName) # Get the current state from the storage layer getState: (key) -> keyName = "#{@_options.name}_#{key}" value = @_options.storage.getItem(keyName) value = null if value == undefined || value == "null" @_options.afterGetState(key, value) return value # Add multiple steps addSteps: (steps) -> @addStep step for step in steps # Add a new step addStep: (step) -> @_steps.push step # Get a step by its indice getStep: (i) -> $.extend({ id: "step-#{i}" path: "" placement: "right" title: "" content: "<p></p>" # no empty as default, otherwise popover won't show up next: if i == @_steps.length - 1 then -1 else i + 1 prev: i - 1 animation: true container: @_options.container backdrop: @_options.backdrop redirect: @_options.redirect template: @_options.template onShow: @_options.onShow onShown: @_options.onShown onHide: @_options.onHide onHidden: @_options.onHidden onNext: @_options.onNext onPrev: @_options.onPrev }, @_steps[i]) if @_steps[i]? # Start tour from current step start: (force = false) -> return @_debug "Tour ended, start prevented." if @ended() && !force # Go to next step after click on element with attribute 'data-role=next' $(document) .off("click.bootstrap-tour", ".popover *[data-role=next]") .on "click.bootstrap-tour", ".popover *[data-role=next]:not(.disabled)", (e) => e.preventDefault() @next() # Go to previous step after click on element with attribute 'data-role=prev' $(document) .off("click.bootstrap-tour", ".popover *[data-role=prev]") .on "click.bootstrap-tour", ".popover *[data-role=prev]:not(.disabled)", (e) => e.preventDefault() @prev() # End tour after click on element with attribute 'data-role=end' $(document) .off("click.bootstrap-tour",".popover *[data-role=end]") .on "click.bootstrap-tour", ".popover *[data-role=end]", (e) => e.preventDefault() @end() # Reshow popover on window resize using debounced resize @_onResize(=> @showStep(@_current)) @_setupKeyboardNavigation() promise = @_makePromise(@_options.onStart(@) if @_options.onStart?) @_callOnPromiseDone(promise, @showStep, @_current) # Hide current step and show next step next: -> return @_debug "Tour ended, next prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @_showNextStep) # Hide current step and show prev step prev: -> return @_debug "Tour ended, prev prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @_showPrevStep) goto: (i) -> return @_debug "Tour ended, goto prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @showStep, i) # End tour end: -> endHelper = (e) => $(document).off "click.bootstrap-tour" $(document).off "keyup.bootstrap-tour" $(window).off "resize.bootstrap-tour" @setState("end", "yes") @_options.onEnd(@) if @_options.onEnd? hidePromise = @hideStep(@_current) @_callOnPromiseDone(hidePromise, endHelper) # Verify if tour is enabled ended: -> !!@getState("end") # Restart tour restart: -> @removeState("current_step") @removeState("end") @setCurrentStep(0) @start() # Hide the specified step hideStep: (i) -> step = @getStep(i) promise = @_makePromise (step.onHide(@, i) if step.onHide?) hideStepHelper = (e) => $element = $(step.element).popover("destroy") $element.css("cursor", "").off "click.bootstrap-tour" if step.reflex @_hideBackdrop() if step.backdrop step.onHidden(@) if step.onHidden? @_callOnPromiseDone(promise, hideStepHelper) promise # Show the specified step showStep: (i) -> step = @getStep(i) return unless step # If onShow returns a promise, lets wait until it's done to execute promise = @_makePromise (step.onShow(@, i) if step.onShow?) showStepHelper = (e) => @setCurrentStep(i) # Support string or function for path path = if $.isFunction(step.path) then step.path.call() else @_options.basePath + step.path # Redirect to step path if not already there current_path = [document.location.pathname, document.location.hash].join('') if @_isRedirect(path, current_path) @_redirect(step, path) return # If step element is hidden, skip step unless step.element? && $(step.element).length != 0 && $(step.element).is(":visible") @_debug "Skip the step #{@_current + 1}. The element does not exist or is not visible." @_showNextStep() return @_showBackdrop(step.element) if step.backdrop # Show popover @_showPopover(step, i) step.onShown(@) if step.onShown? @_debug "Step #{@_current + 1} of #{@_steps.length}" @_callOnPromiseDone(promise, showStepHelper) # Setup current step variable setCurrentStep: (value) -> if value? @_current = value @setState("current_step", value) else @_current = @getState("current_step") if @_current == null @_current = 0 else @_current = parseInt(@_current) # Show next step _showNextStep: -> step = @getStep(@_current) showNextStepHelper = (e) => @showStep(step.next) promise = @_makePromise (step.onNext(@) if step.onNext?) @_callOnPromiseDone(promise, showNextStepHelper) # Show prev step _showPrevStep: -> step = @getStep(@_current) showPrevStepHelper = (e) => @showStep(step.prev) promise = @_makePromise (step.onPrev(@) if step.onPrev?) @_callOnPromiseDone(promise, showPrevStepHelper) # Print message in console _debug: (text) -> window.console.log "Bootstrap Tour '#{@_options.name}' | #{text}" if @_options.debug # Check if step path equals current document path _isRedirect: (path, currentPath) -> path? and path isnt "" and path.replace(/\?.*$/, "").replace(/\/?$/, "") isnt currentPath.replace(/\/?$/, "") # Execute the redirect _redirect: (step, path) -> if $.isFunction(step.redirect) step.redirect.call(this, path) else if step.redirect == true @_debug "Redirect to #{path}" document.location.href = path # Render navigation _renderNavigation: (step, i, options) -> template = if $.isFunction(step.template) then $(step.template(i, step)) else $(step.template) navigation = template.find(".popover-navigation") if step.prev < 0 navigation.find("*[data-role=prev]").addClass("disabled") if step.next < 0 navigation.find("*[data-role=next]").addClass("disabled") # return the outerHTML of the jQuery el template.clone().wrap("<div>").parent().html() # Show step popover _showPopover: (step, i) -> options = $.extend {}, @_options if step.options $.extend options, step.options if step.reflex $(step.element).css("cursor", "pointer").on "click.bootstrap-tour", (e) => if @_current < @_steps.length - 1 @next() else @end() rendered = @_renderNavigation(step, i, options) $element = $(step.element) $element.popover({ placement: step.placement trigger: "manual" title: step.title content: step.content html: true animation: step.animation container: step.container template: rendered selector: step.element }).popover("show") $tip = if $element.data("bs.popover") then $element.data("bs.popover").tip() else $element.data("popover").tip() $tip.attr("id", step.id) @_scrollIntoView($element) @_scrollIntoView($tip) @_reposition($tip, step) # Prevent popups from crossing over the edge of the window _reposition: (tip, step) -> original_offsetWidth = tip[0].offsetWidth original_offsetHeight = tip[0].offsetHeight tipOffset = tip.offset() original_left = tipOffset.left original_top = tipOffset.top offsetBottom = $(document).outerHeight() - tipOffset.top - $(tip).outerHeight() tipOffset.top = tipOffset.top + offsetBottom if offsetBottom < 0 offsetRight = $("html").outerWidth() - tipOffset.left - $(tip).outerWidth() tipOffset.left = tipOffset.left + offsetRight if offsetRight < 0 tipOffset.top = 0 if tipOffset.top < 0 tipOffset.left = 0 if tipOffset.left < 0 tip.offset(tipOffset) # reposition the arrow if step.placement == 'bottom' or step.placement == 'top' @_replaceArrow(tip, (tipOffset.left-original_left)*2, original_offsetWidth, 'left') if original_left != tipOffset.left else @_replaceArrow(tip, (tipOffset.top-original_top)*2, original_offsetHeight, 'top') if original_top != tipOffset.top # copy pasted from bootstrap-tooltip.js # with some alterations _replaceArrow: (tip, delta, dimension, position)-> tip .find(".arrow") .css(position, if delta then (50 * (1 - delta / dimension) + "%") else '') # Scroll to the popup if it is not in the viewport _scrollIntoView: (tip) -> tipRect = tip.get(0).getBoundingClientRect() unless tipRect.top >= 0 && tipRect.bottom < $(window).height() && tipRect.left >= 0 && tipRect.right < $(window).width() tip.get(0).scrollIntoView(true) # Debounced window resize _onResize: (callback, timeout) -> $(window).on "resize.bootstrap-tour", -> clearTimeout(timeout) timeout = setTimeout(callback, 100) # Keyboard navigation _setupKeyboardNavigation: -> if @_options.keyboard $(document).on "keyup.bootstrap-tour", (e) => return unless e.which switch e.which when 39 e.preventDefault() if @_current < @_steps.length - 1 @next() else @end() when 37 e.preventDefault() if @_current > 0 @prev() when 27 e.preventDefault() @end() # Checks if the result of a callback is a promise _makePromise: (result) -> if result && $.isFunction(result.then) then result else null _callOnPromiseDone: (promise, cb, arg) -> if promise promise.then (e) => cb.call(@, arg) else cb.call(@, arg) _showBackdrop: (el) -> return unless @backdrop.overlay == null @_showOverlay() @_showOverlayElement(el) _hideBackdrop: -> return if @backdrop.overlay == null @_hideOverlayElement() @_hideOverlay() _showOverlay: -> @backdrop = $('<div/>') @backdrop.addClass('tour-backdrop') @backdrop.height $(document).innerHeight() $('body').append @backdrop _hideOverlay: -> @backdrop.remove() @backdrop.overlay = null _showOverlayElement: (el) -> step = $(el) offset = step.offset() offset.top = offset.top offset.left = offset.left background = $('<div/>') background .width(step.innerWidth()) .height(step.innerHeight()) .addClass('tour-step-background') .offset(offset) step.addClass('tour-step-backdrop') $('body').append background @backdrop.step = step @backdrop.background = background _hideOverlayElement: -> @backdrop.step.removeClass('tour-step-backdrop') @backdrop.background.remove() @backdrop.step = null @backdrop.background = null window.Tour = Tour )(jQuery, window)
181611
(($, window) -> document = window.document class Tour constructor: (options) -> @_options = $.extend({ name: 'tour' container: 'body' keyboard: true storage: window.localStorage debug: false backdrop: false redirect: true basePath: '' template: "<div class='popover tour'> <div class='arrow'></div> <h3 class='popover-title'></h3> <div class='popover-content'></div> <nav class='popover-navigation'> <div class='btn-group'> <button class='btn btn-default' data-role='prev'>&laquo; Prev</button> <button class='btn btn-default' data-role='next'>Next &raquo;</button> </div> <button class='btn btn-default' data-role='end'>End tour</button> </nav> </div>" afterSetState: (key, value) -> afterGetState: (key, value) -> afterRemoveState: (key) -> onStart: (tour) -> onEnd: (tour) -> onShow: (tour) -> onShown: (tour) -> onHide: (tour) -> onHidden: (tour) -> onNext: (tour) -> onPrev: (tour) -> }, options) @_steps = [] @setCurrentStep() @backdrop = { overlay: null step: null background: null } # Set a state in storage setState: (key, value) -> keyName = <KEY>@_<KEY>.<KEY> @_options.storage.setItem(keyName, value) @_options.afterSetState(keyName, value) # Remove the current state from the storage layer removeState: (key) -> keyName = <KEY>@_<KEY>.<KEY>key<KEY>}" @_options.storage.removeItem(keyName) @_options.afterRemoveState(keyName) # Get the current state from the storage layer getState: (key) -> keyName = <KEY>@_<KEY>.<KEY> value = @_options.storage.getItem(keyName) value = null if value == undefined || value == "null" @_options.afterGetState(key, value) return value # Add multiple steps addSteps: (steps) -> @addStep step for step in steps # Add a new step addStep: (step) -> @_steps.push step # Get a step by its indice getStep: (i) -> $.extend({ id: "step-#{i}" path: "" placement: "right" title: "" content: "<p></p>" # no empty as default, otherwise popover won't show up next: if i == @_steps.length - 1 then -1 else i + 1 prev: i - 1 animation: true container: @_options.container backdrop: @_options.backdrop redirect: @_options.redirect template: @_options.template onShow: @_options.onShow onShown: @_options.onShown onHide: @_options.onHide onHidden: @_options.onHidden onNext: @_options.onNext onPrev: @_options.onPrev }, @_steps[i]) if @_steps[i]? # Start tour from current step start: (force = false) -> return @_debug "Tour ended, start prevented." if @ended() && !force # Go to next step after click on element with attribute 'data-role=next' $(document) .off("click.bootstrap-tour", ".popover *[data-role=next]") .on "click.bootstrap-tour", ".popover *[data-role=next]:not(.disabled)", (e) => e.preventDefault() @next() # Go to previous step after click on element with attribute 'data-role=prev' $(document) .off("click.bootstrap-tour", ".popover *[data-role=prev]") .on "click.bootstrap-tour", ".popover *[data-role=prev]:not(.disabled)", (e) => e.preventDefault() @prev() # End tour after click on element with attribute 'data-role=end' $(document) .off("click.bootstrap-tour",".popover *[data-role=end]") .on "click.bootstrap-tour", ".popover *[data-role=end]", (e) => e.preventDefault() @end() # Reshow popover on window resize using debounced resize @_onResize(=> @showStep(@_current)) @_setupKeyboardNavigation() promise = @_makePromise(@_options.onStart(@) if @_options.onStart?) @_callOnPromiseDone(promise, @showStep, @_current) # Hide current step and show next step next: -> return @_debug "Tour ended, next prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @_showNextStep) # Hide current step and show prev step prev: -> return @_debug "Tour ended, prev prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @_showPrevStep) goto: (i) -> return @_debug "Tour ended, goto prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @showStep, i) # End tour end: -> endHelper = (e) => $(document).off "click.bootstrap-tour" $(document).off "keyup.bootstrap-tour" $(window).off "resize.bootstrap-tour" @setState("end", "yes") @_options.onEnd(@) if @_options.onEnd? hidePromise = @hideStep(@_current) @_callOnPromiseDone(hidePromise, endHelper) # Verify if tour is enabled ended: -> !!@getState("end") # Restart tour restart: -> @removeState("current_step") @removeState("end") @setCurrentStep(0) @start() # Hide the specified step hideStep: (i) -> step = @getStep(i) promise = @_makePromise (step.onHide(@, i) if step.onHide?) hideStepHelper = (e) => $element = $(step.element).popover("destroy") $element.css("cursor", "").off "click.bootstrap-tour" if step.reflex @_hideBackdrop() if step.backdrop step.onHidden(@) if step.onHidden? @_callOnPromiseDone(promise, hideStepHelper) promise # Show the specified step showStep: (i) -> step = @getStep(i) return unless step # If onShow returns a promise, lets wait until it's done to execute promise = @_makePromise (step.onShow(@, i) if step.onShow?) showStepHelper = (e) => @setCurrentStep(i) # Support string or function for path path = if $.isFunction(step.path) then step.path.call() else @_options.basePath + step.path # Redirect to step path if not already there current_path = [document.location.pathname, document.location.hash].join('') if @_isRedirect(path, current_path) @_redirect(step, path) return # If step element is hidden, skip step unless step.element? && $(step.element).length != 0 && $(step.element).is(":visible") @_debug "Skip the step #{@_current + 1}. The element does not exist or is not visible." @_showNextStep() return @_showBackdrop(step.element) if step.backdrop # Show popover @_showPopover(step, i) step.onShown(@) if step.onShown? @_debug "Step #{@_current + 1} of #{@_steps.length}" @_callOnPromiseDone(promise, showStepHelper) # Setup current step variable setCurrentStep: (value) -> if value? @_current = value @setState("current_step", value) else @_current = @getState("current_step") if @_current == null @_current = 0 else @_current = parseInt(@_current) # Show next step _showNextStep: -> step = @getStep(@_current) showNextStepHelper = (e) => @showStep(step.next) promise = @_makePromise (step.onNext(@) if step.onNext?) @_callOnPromiseDone(promise, showNextStepHelper) # Show prev step _showPrevStep: -> step = @getStep(@_current) showPrevStepHelper = (e) => @showStep(step.prev) promise = @_makePromise (step.onPrev(@) if step.onPrev?) @_callOnPromiseDone(promise, showPrevStepHelper) # Print message in console _debug: (text) -> window.console.log "Bootstrap Tour '#{@_options.name}' | #{text}" if @_options.debug # Check if step path equals current document path _isRedirect: (path, currentPath) -> path? and path isnt "" and path.replace(/\?.*$/, "").replace(/\/?$/, "") isnt currentPath.replace(/\/?$/, "") # Execute the redirect _redirect: (step, path) -> if $.isFunction(step.redirect) step.redirect.call(this, path) else if step.redirect == true @_debug "Redirect to #{path}" document.location.href = path # Render navigation _renderNavigation: (step, i, options) -> template = if $.isFunction(step.template) then $(step.template(i, step)) else $(step.template) navigation = template.find(".popover-navigation") if step.prev < 0 navigation.find("*[data-role=prev]").addClass("disabled") if step.next < 0 navigation.find("*[data-role=next]").addClass("disabled") # return the outerHTML of the jQuery el template.clone().wrap("<div>").parent().html() # Show step popover _showPopover: (step, i) -> options = $.extend {}, @_options if step.options $.extend options, step.options if step.reflex $(step.element).css("cursor", "pointer").on "click.bootstrap-tour", (e) => if @_current < @_steps.length - 1 @next() else @end() rendered = @_renderNavigation(step, i, options) $element = $(step.element) $element.popover({ placement: step.placement trigger: "manual" title: step.title content: step.content html: true animation: step.animation container: step.container template: rendered selector: step.element }).popover("show") $tip = if $element.data("bs.popover") then $element.data("bs.popover").tip() else $element.data("popover").tip() $tip.attr("id", step.id) @_scrollIntoView($element) @_scrollIntoView($tip) @_reposition($tip, step) # Prevent popups from crossing over the edge of the window _reposition: (tip, step) -> original_offsetWidth = tip[0].offsetWidth original_offsetHeight = tip[0].offsetHeight tipOffset = tip.offset() original_left = tipOffset.left original_top = tipOffset.top offsetBottom = $(document).outerHeight() - tipOffset.top - $(tip).outerHeight() tipOffset.top = tipOffset.top + offsetBottom if offsetBottom < 0 offsetRight = $("html").outerWidth() - tipOffset.left - $(tip).outerWidth() tipOffset.left = tipOffset.left + offsetRight if offsetRight < 0 tipOffset.top = 0 if tipOffset.top < 0 tipOffset.left = 0 if tipOffset.left < 0 tip.offset(tipOffset) # reposition the arrow if step.placement == 'bottom' or step.placement == 'top' @_replaceArrow(tip, (tipOffset.left-original_left)*2, original_offsetWidth, 'left') if original_left != tipOffset.left else @_replaceArrow(tip, (tipOffset.top-original_top)*2, original_offsetHeight, 'top') if original_top != tipOffset.top # copy pasted from bootstrap-tooltip.js # with some alterations _replaceArrow: (tip, delta, dimension, position)-> tip .find(".arrow") .css(position, if delta then (50 * (1 - delta / dimension) + "%") else '') # Scroll to the popup if it is not in the viewport _scrollIntoView: (tip) -> tipRect = tip.get(0).getBoundingClientRect() unless tipRect.top >= 0 && tipRect.bottom < $(window).height() && tipRect.left >= 0 && tipRect.right < $(window).width() tip.get(0).scrollIntoView(true) # Debounced window resize _onResize: (callback, timeout) -> $(window).on "resize.bootstrap-tour", -> clearTimeout(timeout) timeout = setTimeout(callback, 100) # Keyboard navigation _setupKeyboardNavigation: -> if @_options.keyboard $(document).on "keyup.bootstrap-tour", (e) => return unless e.which switch e.which when 39 e.preventDefault() if @_current < @_steps.length - 1 @next() else @end() when 37 e.preventDefault() if @_current > 0 @prev() when 27 e.preventDefault() @end() # Checks if the result of a callback is a promise _makePromise: (result) -> if result && $.isFunction(result.then) then result else null _callOnPromiseDone: (promise, cb, arg) -> if promise promise.then (e) => cb.call(@, arg) else cb.call(@, arg) _showBackdrop: (el) -> return unless @backdrop.overlay == null @_showOverlay() @_showOverlayElement(el) _hideBackdrop: -> return if @backdrop.overlay == null @_hideOverlayElement() @_hideOverlay() _showOverlay: -> @backdrop = $('<div/>') @backdrop.addClass('tour-backdrop') @backdrop.height $(document).innerHeight() $('body').append @backdrop _hideOverlay: -> @backdrop.remove() @backdrop.overlay = null _showOverlayElement: (el) -> step = $(el) offset = step.offset() offset.top = offset.top offset.left = offset.left background = $('<div/>') background .width(step.innerWidth()) .height(step.innerHeight()) .addClass('tour-step-background') .offset(offset) step.addClass('tour-step-backdrop') $('body').append background @backdrop.step = step @backdrop.background = background _hideOverlayElement: -> @backdrop.step.removeClass('tour-step-backdrop') @backdrop.background.remove() @backdrop.step = null @backdrop.background = null window.Tour = Tour )(jQuery, window)
true
(($, window) -> document = window.document class Tour constructor: (options) -> @_options = $.extend({ name: 'tour' container: 'body' keyboard: true storage: window.localStorage debug: false backdrop: false redirect: true basePath: '' template: "<div class='popover tour'> <div class='arrow'></div> <h3 class='popover-title'></h3> <div class='popover-content'></div> <nav class='popover-navigation'> <div class='btn-group'> <button class='btn btn-default' data-role='prev'>&laquo; Prev</button> <button class='btn btn-default' data-role='next'>Next &raquo;</button> </div> <button class='btn btn-default' data-role='end'>End tour</button> </nav> </div>" afterSetState: (key, value) -> afterGetState: (key, value) -> afterRemoveState: (key) -> onStart: (tour) -> onEnd: (tour) -> onShow: (tour) -> onShown: (tour) -> onHide: (tour) -> onHidden: (tour) -> onNext: (tour) -> onPrev: (tour) -> }, options) @_steps = [] @setCurrentStep() @backdrop = { overlay: null step: null background: null } # Set a state in storage setState: (key, value) -> keyName = PI:KEY:<KEY>END_PI@_PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI @_options.storage.setItem(keyName, value) @_options.afterSetState(keyName, value) # Remove the current state from the storage layer removeState: (key) -> keyName = PI:KEY:<KEY>END_PI@_PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}" @_options.storage.removeItem(keyName) @_options.afterRemoveState(keyName) # Get the current state from the storage layer getState: (key) -> keyName = PI:KEY:<KEY>END_PI@_PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI value = @_options.storage.getItem(keyName) value = null if value == undefined || value == "null" @_options.afterGetState(key, value) return value # Add multiple steps addSteps: (steps) -> @addStep step for step in steps # Add a new step addStep: (step) -> @_steps.push step # Get a step by its indice getStep: (i) -> $.extend({ id: "step-#{i}" path: "" placement: "right" title: "" content: "<p></p>" # no empty as default, otherwise popover won't show up next: if i == @_steps.length - 1 then -1 else i + 1 prev: i - 1 animation: true container: @_options.container backdrop: @_options.backdrop redirect: @_options.redirect template: @_options.template onShow: @_options.onShow onShown: @_options.onShown onHide: @_options.onHide onHidden: @_options.onHidden onNext: @_options.onNext onPrev: @_options.onPrev }, @_steps[i]) if @_steps[i]? # Start tour from current step start: (force = false) -> return @_debug "Tour ended, start prevented." if @ended() && !force # Go to next step after click on element with attribute 'data-role=next' $(document) .off("click.bootstrap-tour", ".popover *[data-role=next]") .on "click.bootstrap-tour", ".popover *[data-role=next]:not(.disabled)", (e) => e.preventDefault() @next() # Go to previous step after click on element with attribute 'data-role=prev' $(document) .off("click.bootstrap-tour", ".popover *[data-role=prev]") .on "click.bootstrap-tour", ".popover *[data-role=prev]:not(.disabled)", (e) => e.preventDefault() @prev() # End tour after click on element with attribute 'data-role=end' $(document) .off("click.bootstrap-tour",".popover *[data-role=end]") .on "click.bootstrap-tour", ".popover *[data-role=end]", (e) => e.preventDefault() @end() # Reshow popover on window resize using debounced resize @_onResize(=> @showStep(@_current)) @_setupKeyboardNavigation() promise = @_makePromise(@_options.onStart(@) if @_options.onStart?) @_callOnPromiseDone(promise, @showStep, @_current) # Hide current step and show next step next: -> return @_debug "Tour ended, next prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @_showNextStep) # Hide current step and show prev step prev: -> return @_debug "Tour ended, prev prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @_showPrevStep) goto: (i) -> return @_debug "Tour ended, goto prevented." if @ended() promise = @hideStep(@_current) @_callOnPromiseDone(promise, @showStep, i) # End tour end: -> endHelper = (e) => $(document).off "click.bootstrap-tour" $(document).off "keyup.bootstrap-tour" $(window).off "resize.bootstrap-tour" @setState("end", "yes") @_options.onEnd(@) if @_options.onEnd? hidePromise = @hideStep(@_current) @_callOnPromiseDone(hidePromise, endHelper) # Verify if tour is enabled ended: -> !!@getState("end") # Restart tour restart: -> @removeState("current_step") @removeState("end") @setCurrentStep(0) @start() # Hide the specified step hideStep: (i) -> step = @getStep(i) promise = @_makePromise (step.onHide(@, i) if step.onHide?) hideStepHelper = (e) => $element = $(step.element).popover("destroy") $element.css("cursor", "").off "click.bootstrap-tour" if step.reflex @_hideBackdrop() if step.backdrop step.onHidden(@) if step.onHidden? @_callOnPromiseDone(promise, hideStepHelper) promise # Show the specified step showStep: (i) -> step = @getStep(i) return unless step # If onShow returns a promise, lets wait until it's done to execute promise = @_makePromise (step.onShow(@, i) if step.onShow?) showStepHelper = (e) => @setCurrentStep(i) # Support string or function for path path = if $.isFunction(step.path) then step.path.call() else @_options.basePath + step.path # Redirect to step path if not already there current_path = [document.location.pathname, document.location.hash].join('') if @_isRedirect(path, current_path) @_redirect(step, path) return # If step element is hidden, skip step unless step.element? && $(step.element).length != 0 && $(step.element).is(":visible") @_debug "Skip the step #{@_current + 1}. The element does not exist or is not visible." @_showNextStep() return @_showBackdrop(step.element) if step.backdrop # Show popover @_showPopover(step, i) step.onShown(@) if step.onShown? @_debug "Step #{@_current + 1} of #{@_steps.length}" @_callOnPromiseDone(promise, showStepHelper) # Setup current step variable setCurrentStep: (value) -> if value? @_current = value @setState("current_step", value) else @_current = @getState("current_step") if @_current == null @_current = 0 else @_current = parseInt(@_current) # Show next step _showNextStep: -> step = @getStep(@_current) showNextStepHelper = (e) => @showStep(step.next) promise = @_makePromise (step.onNext(@) if step.onNext?) @_callOnPromiseDone(promise, showNextStepHelper) # Show prev step _showPrevStep: -> step = @getStep(@_current) showPrevStepHelper = (e) => @showStep(step.prev) promise = @_makePromise (step.onPrev(@) if step.onPrev?) @_callOnPromiseDone(promise, showPrevStepHelper) # Print message in console _debug: (text) -> window.console.log "Bootstrap Tour '#{@_options.name}' | #{text}" if @_options.debug # Check if step path equals current document path _isRedirect: (path, currentPath) -> path? and path isnt "" and path.replace(/\?.*$/, "").replace(/\/?$/, "") isnt currentPath.replace(/\/?$/, "") # Execute the redirect _redirect: (step, path) -> if $.isFunction(step.redirect) step.redirect.call(this, path) else if step.redirect == true @_debug "Redirect to #{path}" document.location.href = path # Render navigation _renderNavigation: (step, i, options) -> template = if $.isFunction(step.template) then $(step.template(i, step)) else $(step.template) navigation = template.find(".popover-navigation") if step.prev < 0 navigation.find("*[data-role=prev]").addClass("disabled") if step.next < 0 navigation.find("*[data-role=next]").addClass("disabled") # return the outerHTML of the jQuery el template.clone().wrap("<div>").parent().html() # Show step popover _showPopover: (step, i) -> options = $.extend {}, @_options if step.options $.extend options, step.options if step.reflex $(step.element).css("cursor", "pointer").on "click.bootstrap-tour", (e) => if @_current < @_steps.length - 1 @next() else @end() rendered = @_renderNavigation(step, i, options) $element = $(step.element) $element.popover({ placement: step.placement trigger: "manual" title: step.title content: step.content html: true animation: step.animation container: step.container template: rendered selector: step.element }).popover("show") $tip = if $element.data("bs.popover") then $element.data("bs.popover").tip() else $element.data("popover").tip() $tip.attr("id", step.id) @_scrollIntoView($element) @_scrollIntoView($tip) @_reposition($tip, step) # Prevent popups from crossing over the edge of the window _reposition: (tip, step) -> original_offsetWidth = tip[0].offsetWidth original_offsetHeight = tip[0].offsetHeight tipOffset = tip.offset() original_left = tipOffset.left original_top = tipOffset.top offsetBottom = $(document).outerHeight() - tipOffset.top - $(tip).outerHeight() tipOffset.top = tipOffset.top + offsetBottom if offsetBottom < 0 offsetRight = $("html").outerWidth() - tipOffset.left - $(tip).outerWidth() tipOffset.left = tipOffset.left + offsetRight if offsetRight < 0 tipOffset.top = 0 if tipOffset.top < 0 tipOffset.left = 0 if tipOffset.left < 0 tip.offset(tipOffset) # reposition the arrow if step.placement == 'bottom' or step.placement == 'top' @_replaceArrow(tip, (tipOffset.left-original_left)*2, original_offsetWidth, 'left') if original_left != tipOffset.left else @_replaceArrow(tip, (tipOffset.top-original_top)*2, original_offsetHeight, 'top') if original_top != tipOffset.top # copy pasted from bootstrap-tooltip.js # with some alterations _replaceArrow: (tip, delta, dimension, position)-> tip .find(".arrow") .css(position, if delta then (50 * (1 - delta / dimension) + "%") else '') # Scroll to the popup if it is not in the viewport _scrollIntoView: (tip) -> tipRect = tip.get(0).getBoundingClientRect() unless tipRect.top >= 0 && tipRect.bottom < $(window).height() && tipRect.left >= 0 && tipRect.right < $(window).width() tip.get(0).scrollIntoView(true) # Debounced window resize _onResize: (callback, timeout) -> $(window).on "resize.bootstrap-tour", -> clearTimeout(timeout) timeout = setTimeout(callback, 100) # Keyboard navigation _setupKeyboardNavigation: -> if @_options.keyboard $(document).on "keyup.bootstrap-tour", (e) => return unless e.which switch e.which when 39 e.preventDefault() if @_current < @_steps.length - 1 @next() else @end() when 37 e.preventDefault() if @_current > 0 @prev() when 27 e.preventDefault() @end() # Checks if the result of a callback is a promise _makePromise: (result) -> if result && $.isFunction(result.then) then result else null _callOnPromiseDone: (promise, cb, arg) -> if promise promise.then (e) => cb.call(@, arg) else cb.call(@, arg) _showBackdrop: (el) -> return unless @backdrop.overlay == null @_showOverlay() @_showOverlayElement(el) _hideBackdrop: -> return if @backdrop.overlay == null @_hideOverlayElement() @_hideOverlay() _showOverlay: -> @backdrop = $('<div/>') @backdrop.addClass('tour-backdrop') @backdrop.height $(document).innerHeight() $('body').append @backdrop _hideOverlay: -> @backdrop.remove() @backdrop.overlay = null _showOverlayElement: (el) -> step = $(el) offset = step.offset() offset.top = offset.top offset.left = offset.left background = $('<div/>') background .width(step.innerWidth()) .height(step.innerHeight()) .addClass('tour-step-background') .offset(offset) step.addClass('tour-step-backdrop') $('body').append background @backdrop.step = step @backdrop.background = background _hideOverlayElement: -> @backdrop.step.removeClass('tour-step-backdrop') @backdrop.background.remove() @backdrop.step = null @backdrop.background = null window.Tour = Tour )(jQuery, window)
[ { "context": "# # Kissmetrics Anon\n\n# ## Storage\n# ----------\n# Inspired by sto", "end": 15, "score": 0.9779617190361023, "start": 4, "tag": "NAME", "value": "Kissmetrics" }, { "context": "# # Kissmetrics Anon\n\n# ## Storage\n# ----------\n# Inspired by store.js", "end": 20,...
src/kissmetrics-anon.coffee
evansolomon/kissmetrics-js
1
# # Kissmetrics Anon # ## Storage # ---------- # Inspired by store.js # # https://github.com/deleteme/store # ### Local Storage # ----------------- # Interacts with HTML5's `localStorage`. LocalStorage = # #### Get # -------- # Retrieve data from localStorage. get: -> window.localStorage.getItem @key # #### Set # -------- # Save data to localStorage. # # ##### Arguments # # `value` (String) set: (value) -> window.localStorage.setItem @key, value # #### Clear # ---------- # Clear data from localStorage. clear: -> window.localStorage.removeItem @key # ### Cookies # ----------- # Interacts with the browser's cookies. Cookie = # #### Get # -------- # Retrieve data from cookies. get: -> key = "#{@key}=" for cookiePart in document.cookie.split /;\s*/ if cookiePart.indexOf(key) is 0 return cookiePart.substring key.length # #### Set # -------- # Save data to a cookie. # # ##### Arguments # # `value` (String) # # `options` *Optional* (Object): Only used for deleting cookies by writing # them with an expiration time in the past. set: (value, options = {expires: ''}) -> unless options.expires date = new Date date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)) options.expires = "expires=" + date.toGMTString() document.cookie = "#{@key}=#{value}; #{options.expires}; path=/" # #### Clear # ---------- # Clear a cookie. clear: -> Cookie.set @key, '', {expires: -1} # ## Anon Kissmetrics Client # -------------------------- # Wrapper for interacting with the Kissmetrics API with logged out users. The # only difference from `KissmetricsClient` is that an identifier for the user # will be automatically created and saved in their browser. # # ##### Arguments # # `apiKey` (String): Your Kissmetrics API key # # `options` *Optional* (Object): # # * `storage`: Specify which internal engine you want to # use: `'localStorage'` or `'cookie'`. Default is `'localStorage'` # * `storageKey`: Specify what key you want the assigned ID to be # stored under. Default is `'kissmetricsAnon'` # # ``` # km = new AnonKissmetricsClient(API_KEY, { # storage: 'cookie', # storageKey: 'myKissmetricsAnon' # }) # km.record('Visited signup form') # ``` class AnonKissmetricsClient extends KissmetricsClient constructor: (apiKey, options = {}) -> @_storage = if options.storage switch options.storage when 'cookie' then Cookie when 'localStorage' then LocalStorage else if window.localStorage then LocalStorage else Cookie @_storage.key = options.storageKey || 'kissmetricsAnon' unless person = @_storage.get() person = @createID() @_storage.set person super apiKey, person # ### Create ID # ------------- # Create a persistent ID for an anonymous user. # # Inspired by http://stackoverflow.com/a/105074/30098 createID: -> parts = for x in [0..10] (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) parts.join '' # ### Alias # --------- # Identify the current user and (by default) delete the logged out # identifier that was stored. # # ##### Arguments # # `newIdentity` (String): A new identifier to map to the `@person` set on # the current instance. # # `deleteStoredID` *Optional* (Boolean): Whether or not to delete the # logged-out identity that was stored. Default `true`. # # ``` # km.alias('evan+otheremail@example.com', false) # km.alias('evan+newemail@example.com') # ``` alias: (newIdentity, deleteStoredID = true) -> @_storage.clear() unless deleteStoredID is off super newIdentity # ## Exports # ---------- # Make `AnonKissmetricsClient` available as a property # on the current context in the browser. @AnonKissmetricsClient = AnonKissmetricsClient unless NODEJS is on
18546
# # <NAME> <NAME> # ## Storage # ---------- # Inspired by store.js # # https://github.com/deleteme/store # ### Local Storage # ----------------- # Interacts with HTML5's `localStorage`. LocalStorage = # #### Get # -------- # Retrieve data from localStorage. get: -> window.localStorage.getItem @key # #### Set # -------- # Save data to localStorage. # # ##### Arguments # # `value` (String) set: (value) -> window.localStorage.setItem @key, value # #### Clear # ---------- # Clear data from localStorage. clear: -> window.localStorage.removeItem @key # ### Cookies # ----------- # Interacts with the browser's cookies. Cookie = # #### Get # -------- # Retrieve data from cookies. get: -> key = <KEY> for cookiePart in document.cookie.split /;\s*/ if cookiePart.indexOf(key) is 0 return cookiePart.substring key.length # #### Set # -------- # Save data to a cookie. # # ##### Arguments # # `value` (String) # # `options` *Optional* (Object): Only used for deleting cookies by writing # them with an expiration time in the past. set: (value, options = {expires: ''}) -> unless options.expires date = new Date date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)) options.expires = "expires=" + date.toGMTString() document.cookie = "#{@key}=#{value}; #{options.expires}; path=/" # #### Clear # ---------- # Clear a cookie. clear: -> Cookie.set @key, '', {expires: -1} # ## Anon Kissmetrics Client # -------------------------- # Wrapper for interacting with the Kissmetrics API with logged out users. The # only difference from `KissmetricsClient` is that an identifier for the user # will be automatically created and saved in their browser. # # ##### Arguments # # `apiKey` (String): Your Kissmetrics API key # # `options` *Optional* (Object): # # * `storage`: Specify which internal engine you want to # use: `'localStorage'` or `'cookie'`. Default is `'localStorage'` # * `storageKey`: Specify what key you want the assigned ID to be # stored under. Default is `'<KEY>'` # # ``` # km = new AnonKissmetricsClient(API_KEY, { # storage: 'cookie', # storageKey: '<KEY>' # }) # km.record('Visited signup form') # ``` class AnonKissmetricsClient extends KissmetricsClient constructor: (apiKey, options = {}) -> @_storage = if options.storage switch options.storage when 'cookie' then Cookie when 'localStorage' then LocalStorage else if window.localStorage then LocalStorage else Cookie @_storage.key = options.storageKey || '<KEY>' unless person = @_storage.get() person = @createID() @_storage.set person super apiKey, person # ### Create ID # ------------- # Create a persistent ID for an anonymous user. # # Inspired by http://stackoverflow.com/a/105074/30098 createID: -> parts = for x in [0..10] (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) parts.join '' # ### Alias # --------- # Identify the current user and (by default) delete the logged out # identifier that was stored. # # ##### Arguments # # `newIdentity` (String): A new identifier to map to the `@person` set on # the current instance. # # `deleteStoredID` *Optional* (Boolean): Whether or not to delete the # logged-out identity that was stored. Default `true`. # # ``` # km.alias('<EMAIL>', false) # km.alias('<EMAIL>') # ``` alias: (newIdentity, deleteStoredID = true) -> @_storage.clear() unless deleteStoredID is off super newIdentity # ## Exports # ---------- # Make `AnonKissmetricsClient` available as a property # on the current context in the browser. @AnonKissmetricsClient = AnonKissmetricsClient unless NODEJS is on
true
# # PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI # ## Storage # ---------- # Inspired by store.js # # https://github.com/deleteme/store # ### Local Storage # ----------------- # Interacts with HTML5's `localStorage`. LocalStorage = # #### Get # -------- # Retrieve data from localStorage. get: -> window.localStorage.getItem @key # #### Set # -------- # Save data to localStorage. # # ##### Arguments # # `value` (String) set: (value) -> window.localStorage.setItem @key, value # #### Clear # ---------- # Clear data from localStorage. clear: -> window.localStorage.removeItem @key # ### Cookies # ----------- # Interacts with the browser's cookies. Cookie = # #### Get # -------- # Retrieve data from cookies. get: -> key = PI:KEY:<KEY>END_PI for cookiePart in document.cookie.split /;\s*/ if cookiePart.indexOf(key) is 0 return cookiePart.substring key.length # #### Set # -------- # Save data to a cookie. # # ##### Arguments # # `value` (String) # # `options` *Optional* (Object): Only used for deleting cookies by writing # them with an expiration time in the past. set: (value, options = {expires: ''}) -> unless options.expires date = new Date date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)) options.expires = "expires=" + date.toGMTString() document.cookie = "#{@key}=#{value}; #{options.expires}; path=/" # #### Clear # ---------- # Clear a cookie. clear: -> Cookie.set @key, '', {expires: -1} # ## Anon Kissmetrics Client # -------------------------- # Wrapper for interacting with the Kissmetrics API with logged out users. The # only difference from `KissmetricsClient` is that an identifier for the user # will be automatically created and saved in their browser. # # ##### Arguments # # `apiKey` (String): Your Kissmetrics API key # # `options` *Optional* (Object): # # * `storage`: Specify which internal engine you want to # use: `'localStorage'` or `'cookie'`. Default is `'localStorage'` # * `storageKey`: Specify what key you want the assigned ID to be # stored under. Default is `'PI:KEY:<KEY>END_PI'` # # ``` # km = new AnonKissmetricsClient(API_KEY, { # storage: 'cookie', # storageKey: 'PI:KEY:<KEY>END_PI' # }) # km.record('Visited signup form') # ``` class AnonKissmetricsClient extends KissmetricsClient constructor: (apiKey, options = {}) -> @_storage = if options.storage switch options.storage when 'cookie' then Cookie when 'localStorage' then LocalStorage else if window.localStorage then LocalStorage else Cookie @_storage.key = options.storageKey || 'PI:KEY:<KEY>END_PI' unless person = @_storage.get() person = @createID() @_storage.set person super apiKey, person # ### Create ID # ------------- # Create a persistent ID for an anonymous user. # # Inspired by http://stackoverflow.com/a/105074/30098 createID: -> parts = for x in [0..10] (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) parts.join '' # ### Alias # --------- # Identify the current user and (by default) delete the logged out # identifier that was stored. # # ##### Arguments # # `newIdentity` (String): A new identifier to map to the `@person` set on # the current instance. # # `deleteStoredID` *Optional* (Boolean): Whether or not to delete the # logged-out identity that was stored. Default `true`. # # ``` # km.alias('PI:EMAIL:<EMAIL>END_PI', false) # km.alias('PI:EMAIL:<EMAIL>END_PI') # ``` alias: (newIdentity, deleteStoredID = true) -> @_storage.clear() unless deleteStoredID is off super newIdentity # ## Exports # ---------- # Make `AnonKissmetricsClient` available as a property # on the current context in the browser. @AnonKissmetricsClient = AnonKissmetricsClient unless NODEJS is on
[ { "context": "[\n \"name\" : \"Based and Jedpilled\"\n \"stats\":\n \"spos\": 73.5\n \"alle\": 70.0\n ", "end": 33, "score": 0.9998399615287781, "start": 14, "tag": "NAME", "value": "Based and Jedpilled" }, { "context": "9\n \"perc\": 73.3\n \"cmdy\": 79.7\n,\n \"nam...
src/users.cson
Polcompballvalues/polcompballvalues.github.io
6
[ "name" : "Based and Jedpilled" "stats": "spos": 73.5 "alle": 70.0 "expr": 66.7 "pers": 75.0 "horn": 8.3 "fame": 59.0 "shwr": 43.5 "sani": 79.3 "rela": 73.9 "fedp": 60.7 "actn": 52.6 "purp": 78.9 "perc": 73.3 "cmdy": 79.7 , "name" : "nguyenreich" "stats": "spos": 65.0 "alle": 33.2 "expr": 56.9 "pers": 77.4 "horn": 71.7 "fame": 83.5 "shwr": 43.6 "sani": 65.3 "rela": 73.8 "fedp": 6.0 "actn": 69.3 "purp": 71.2 "perc": 76.7 "cmdy": 61.2 , "name" : "Kaiser" "stats": "spos": 42.5 "alle": 79.5 "expr": 91.7 "pers": 1.8 "horn": 10.0 "fame": 73.8 "shwr": 48.1 "sani": 27.1 "rela": 80.4 "fedp": 100.0 "actn": 17.3 "purp": 22.9 "perc": 38.6 "cmdy": 97.5 , "name" : "Erstanden" "stats": "spos": 56.8 "alle": 91.7 "expr": 34.8 "pers": 42.9 "horn": 33.3 "fame": 27.2 "shwr": 30.7 "sani": 48.7 "rela": 44.1 "fedp": 81.0 "actn": 40.9 "purp": 34.9 "perc": 51.8 "cmdy": 40.8 , "name" : "ItsDanny101" "stats": "spos": 45.8 "alle": 54.1 "expr": 77.8 "pers": 79.1 "horn": 0.0 "fame": 79.3 "shwr": 58.4 "sani": 54.1 "rela": 79.3 "fedp": 54.0 "actn": 70.1 "purp": 8.3 "perc": 66.6 "cmdy": 75.0 , "name" : "KEVIN" "stats": "spos": 55.0 "alle": 53.3 "expr": 94.5 "pers": 57.2 "horn": 76.7 "fame": 83.3 "shwr": 39.8 "sani": 65.3 "rela": 86.9 "fedp": 51.2 "actn": 64.1 "purp": 71.2 "perc": 48.4 "cmdy": 79.6 , "name" : "SteelSmasher" "stats": "spos": 70.0 "alle": 45.0 "expr": 33.3 "pers": 64.3 "horn": 40.0 "fame": 57.5 "shwr": 47.4 "sani": 70.9 "rela": 51.2 "fedp": 28.5 "actn": 71.8 "purp": 51.5 "perc": 50.0 "cmdy": 57.4 , "name" : "EugeneTLT" "stats": "spos": 33.4 "alle": 37.5 "expr": 55.5 "pers": 79.3 "horn": 8.4 "fame": 20.8 "shwr": 66.8 "sani": 45.8 "rela": 70.8 "fedp": 37.6 "actn": 66.8 "purp": 58.4 "perc": 71.0 "cmdy": 45.8 , "name" : "Froggers" "stats": "spos": 41.6 "alle": 50.0 "expr": 61.2 "pers": 60.8 "horn": 35.0 "fame": 77.4 "shwr": 65.3 "sani": 44.5 "rela": 88.2 "fedp": 60.7 "actn": 43.7 "purp": 45.5 "perc": 75.1 "cmdy": 81.6 , "name" : "Beeper" "stats": "spos": 37.5 "alle": 79.3 "expr": 61.2 "pers": 79.3 "horn": 41.6 "fame": 45.8 "shwr": 37.4 "sani": 75.1 "rela": 66.8 "fedp": 75.0 "actn": 70.1 "purp": 83.4 "perc": 54.1 "cmdy": 58.4 , "name" : "wasp_" "stats": "spos": 58.4 "alle": 33.4 "expr": 89.0 "pers": 50.0 "horn": 70.8 "fame": 79.3 "shwr": 83.4 "sani": 54.3 "rela": 54.3 "fedp": 25.0 "actn": 66.7 "purp": 54.1 "perc": 54.1 "cmdy": 45.9 , "name" : "Vizdun" "stats": "spos": 66.7 "alle": 78.4 "expr": 62.5 "pers": 32.2 "horn": 88.3 "fame": 68.2 "shwr": 19.2 "sani": 23.6 "rela": 8.3 "fedp": 46.4 "actn": 17.9 "purp": 36.3 "perc": 35.0 "cmdy": 77.8 , "name" : "Librlec" "stats": "spos": 23.2 "alle": 31.6 "expr": 23.5 "pers": 81.0 "horn": 61.7 "fame": 66.8 "shwr": 50.0 "sani": 62.5 "rela": 41.7 "fedp": 5.9 "actn": 79.6 "purp": 39.4 "perc": 41.8 "cmdy": 25.8 , "name" : "Chara" "stats": "spos": 86.7 "alle": 12.7 "expr": 86.2 "pers": 83.6 "horn": 46.3 "fame": 84.8 "shwr": 53.8 "sani": 55.9 "rela": 67.1 "fedp": 12.2 "actn": 82.7 "purp": 88.0 "perc": 65.6 "cmdy": 50.1 , "name" : "Voizen" "stats": "spos": 50.0 "alle": 38.6 "expr": 37.5 "pers": 76.8 "horn": 30.0 "fame": 64.3 "shwr": 50.0 "sani": 72.9 "rela": 78.6 "fedp": 14.5 "actn": 71.2 "purp": 18.8 "perc": 88.6 "cmdy": 57.5 , "name" : "chicken piccata" "stats": "spos": 67.5 "alle": 22.7 "expr": 8.3 "pers": 89.3 "horn": 22.5 "fame": 57.1 "shwr": 71.2 "sani": 75.0 "rela": 75.0 "fedp": 20.2 "actn": 84.6 "purp": 50.0 "perc": 75.0 "cmdy": 15.0 , "name" : "YourLocalDegenerateMao" "stats": "spos": 55.0 "alle": 56.6 "expr": 38.9 "pers": 82.3 "horn": 51.6 "fame": 65.2 "shwr": 57.7 "sani": 61.1 "rela": 73.9 "fedp": 22.6 "actn": 74.3 "purp": 36.3 "perc": 73.3 "cmdy": 55.6 , "name" : "bowie" "stats": "spos": 50.0 "alle": 50.0 "expr": 33.3 "pers": 35.7 "horn": 52.5 "fame": 65.5 "shwr": 48.1 "sani": 52.1 "rela": 62.5 "fedp": 33.1 "actn": 51.9 "purp": 33.3 "perc": 63.6 "cmdy": 65.0 , "name" : "Libtard" "stats": "spos": 65.0 "alle": 83.5 "expr": 83.4 "pers": 41.6 "horn": 60.0 "fame": 34.7 "shwr": 53.9 "sani": 55.6 "rela": 53.6 "fedp": 35.6 "actn": 48.7 "purp": 34.9 "perc": 58.3 "cmdy": 37.1 , "name" : "Rayz9989" "stats": "spos": 65.0 "alle": 20.5 "expr": 27.1 "pers": 100.0 "horn": 67.5 "fame": 100.0 "shwr": 5.8 "sani": 75.0 "rela": 60.7 "fedp": 12.9 "actn": 84.6 "purp": 37.5 "perc": 37.5 "cmdy": 75.0 , "name" : "Swoosho" "stats": "spos": 56.7 "alle": 62.5 "expr": 65.2 "pers": 56.2 "horn": 100.0 "fame": 68.8 "shwr": 77.8 "sani": 38.9 "rela": 75.0 "fedp": 31.3 "actn": 43.2 "purp": 37.5 "perc": 75.0 "cmdy": 62.5 , "name" : "Diviny" "stats": "spos": 56.3 "alle": 100.0 "expr": 41.7 "pers": 100.0 "horn": 100.0 "fame": 93.8 "shwr": 0.0 "sani": 31.3 "rela": 62.5 "fedp": 0.0 "actn": 55.0 "purp": 18.8 "perc": 0.0 "cmdy": 31.3 , "name" : "Thunder" "stats": "spos": 35.0 "alle": 50.0 "expr": 25.0 "pers": 48.2 "horn": 70.0 "fame": 47.7 "shwr": 65.4 "sani": 37.5 "rela": 25.0 "fedp": 42.9 "actn": 59.6 "purp": 34.1 "perc": 40.0 "cmdy": 30.6 , "name" : "Quark" "stats": "spos": 87.5 "alle": 100.0 "expr": 66.7 "pers": 56.3 "horn": 25.0 "fame": 100.0 "shwr": 6.3 "sani": 25.0 "rela": 0.0 "fedp": 75.0 "actn": 0.0 "purp": 56.3 "perc": 0.0 "cmdy": 25.0 , "name" : "Solar" "stats": "spos": 100.0 "alle": 100.0 "expr": 25.0 "pers": 56.3 "horn": 75.0 "fame": 6.3 "shwr": 6.3 "sani": 43.7 "rela": 0.0 "fedp": 25.0 "actn": 56.3 "purp": 93.7 "perc": 25.0 "cmdy": 0.0 , "name" : "Sven Brender" "stats": "spos": 67.5 "alle": 100.0 "expr": 100.0 "pers": 50.0 "horn": 32.5 "fame": 40.9 "shwr": 44.2 "sani": 60.4 "rela": 71.4 "fedp": 78.6 "actn": 28.8 "purp": 18.2 "perc": 45.0 "cmdy": 66.7 , "name" : "ThatoneguyG" "stats": "spos": 50.0 "alle": 100.0 "expr": 33.3 "pers": 100.0 "horn": 100.0 "fame": 0.0 "shwr": 0.0 "sani": 93.8 "rela": 68.8 "fedp": 18.8 "actn": 45.0 "purp": 31.3 "perc": 50.0 "cmdy": 62.5 , "name" : "märkl" "stats": "spos": 37.5 "alle": 25.0 "expr": 33.3 "pers": 62.5 "horn": 62.5 "fame": 25.0 "shwr": 50.0 "sani": 75.0 "rela": 75.0 "fedp": 25.0 "actn": 75.0 "purp": 50.0 "perc": 62.5 "cmdy": 62.5 , "name" : "Xerunox" "stats": "spos": 12.5 "alle": 100.0 "expr": 100.0 "pers": 12.5 "horn": 0 "fame": 68.8 "shwr": 75.0 "sani": 75.0 "rela": 50.0 "fedp": 93.8 "actn": 40.0 "purp": 0.0 "perc": 68.8 "cmdy": 93.8 , "name" : "H man" "stats": "spos": 15.0 "alle": 84.1 "expr": 100.0 "pers": 66.1 "horn": 12.5 "fame": 48.8 "shwr": 76.9 "sani": 56.3 "rela": 58.9 "fedp": 59.7 "actn": 46.2 "purp": 20.8 "perc": 59.1 "cmdy": 67.5 , "name" : "Padstar34" "stats": "spos": 37.5 "alle": 68.8 "expr": 33.3 "pers": 81.3 "horn": 50.0 "fame": 56.3 "shwr": 25.0 "sani": 62.5 "rela": 55.0 "fedp": 0.0 "actn": 70.0 "purp": 31.3 "perc": 31.3 "cmdy": 68.8 , "name" : "Arch" "stats": "spos": 47.5 "alle": 79.5 "expr": 20.8 "pers": 33.9 "horn": 72.5 "fame": 42.9 "shwr": 25.0 "sani": 47.9 "rela": 64.3 "fedp": 46.0 "actn": 46.2 "purp": 33.3 "perc": 56.8 "cmdy": 65.0 , "name" : "jao" "stats": "spos": 37.5 "alle": 68.8 "expr": 58.3 "pers": 18.8 "horn": 31.3 "fame": 56.3 "shwr": 93.8 "sani": 68.8 "rela": 65.0 "fedp": 81.3 "actn": 35.0 "purp": 93.8 "perc": 43.8 "cmdy": 43.8 , "name" : "Lego Spiny Piranha Plant " "stats": "spos": 37.5 "alle": 56.3 "expr": 75.0 "pers": 68.8 "horn": 18.8 "fame": 0.0 "shwr": 68.8 "sani": 62.5 "rela": 50.0 "fedp": 31.3 "actn": 60.0 "purp": 50.0 "perc": 62.5 "cmdy": 50.0 , "name" : "Solidarity" "stats": "spos": 92.5 "alle": 54.5 "expr": 41.7 "pers": 71.4 "horn": 70.0 "fame": 29.8 "shwr": 21.2 "sani": 39.6 "rela": 67.9 "fedp": 19.4 "actn": 51.9 "purp": 45.8 "perc": 59.1 "cmdy": 30.0 , "name" : "Cavalieria" "stats": "spos": 52.5 "alle": 54.5 "expr": 27.1 "pers": 33.9 "horn": 35.0 "fame": 53.6 "shwr": 63.5 "sani": 43.8 "rela": 51.8 "fedp": 71.0 "actn": 51.9 "purp": 56.3 "perc": 50.0 "cmdy": 50.0 , "name" : "IncendiaryBullet" "stats": "spos": 25.0 "alle": 86.4 "expr": 97.9 "pers": 35.7 "horn": 25.0 "fame": 67.9 "shwr": 44.2 "sani": 66.7 "rela": 55.4 "fedp": 95.2 "actn": 26.9 "purp": 54.2 "perc": 29.5 "cmdy": 87.5 , "name" : "Austin" "stats": "spos": 75.0 "alle": 18.8 "expr": 58.3 "pers": 93.8 "horn": 50.0 "fame": 6.3 "shwr": 75.0 "sani": 56.3 "rela": 80.0 "fedp": 18.8 "actn": 90.0 "purp": 31.3 "perc": 68.8 "cmdy": 62.5 , "name" : "Sloppy Joe" "stats": "spos": 17.5 "alle": 57.3 "expr": 90.9 "pers": 46.4 "horn": 2.5 "fame": 60.7 "shwr": 88.5 "sani": 79.2 "rela": 75.4 "fedp": 47.6 "actn": 65.8 "purp": 4.6 "perc": 84.1 "cmdy": 77.5 , "name" : "The Infinity Pizza" "stats": "spos": 50.0 "alle": 65.9 "expr": 31.3 "pers": 46.4 "horn": 62.5 "fame": 31.0 "shwr": 69.2 "sani": 60.4 "rela": 66.1 "fedp": 32.3 "actn": 59.6 "purp": 54.2 "perc": 59.1 "cmdy": 55.0 , "name" : "PastaGuy27" "stats": "spos": 56.3 "alle": 81.3 "expr": 75.0 "pers": 43.8 "horn": 37.5 "fame": 6.3 "shwr": 62.5 "sani": 75.0 "rela": 55.0 "fedp": 18.8 "actn": 85.0 "purp": 31.3 "perc": 62.5 "cmdy": 37.5 , "name" : "Sorcer Verjiloz" "stats": "spos": 90.0 "alle": 22.7 "expr": 0.0 "pers": 66.1 "horn": 5.0 "fame": 11.9 "shwr": 19.2 "sani": 39.6 "rela": 51.8 "fedp": 32.3 "actn": 50.0 "purp": 58.3 "perc": 25.0 "cmdy": 25.0 , "name" : "Res." "stats": "spos": 55.0 "alle": 45.5 "expr": 20.8 "pers": 71.4 "horn": 57.5 "fame": 14.3 "shwr": 38.5 "sani": 77.1 "rela": 44.6 "fedp": 54.8 "actn": 80.8 "purp": 25.0 "perc": 61.4 "cmdy": 57.5 , "name" : "antichristhater" "stats": "spos": 56.3 "alle": 68.8 "expr": 33.3 "pers": 37.5 "horn": 6.3 "fame": 50.0 "shwr": 75.0 "sani": 81.3 "rela": 65.0 "fedp": 50.0 "actn": 75.0 "purp": 12.5 "perc": 43.8 "cmdy": 75.0 , "name" : "oRange" "stats": "spos": 52.5 "alle": 56.8 "expr": 83.3 "pers": 66.1 "horn": 30.0 "fame": 72.6 "shwr": 42.3 "sani": 60.4 "rela": 82.1 "fedp": 43.5 "actn": 55.8 "purp": 64.6 "perc": 81.8 "cmdy": 87.5 , "name" : "Leo9" "stats": "spos": 55.0 "alle": 81.8 "expr": 29.2 "pers": 64.3 "horn": 62.5 "fame": 13.1 "shwr": 21.2 "sani": 47.9 "rela": 57.1 "fedp": 8.1 "actn": 48.1 "purp": 58.3 "perc": 65.9 "cmdy": 45.0 , "name" : "Yelling Yowie" "stats": "spos": 68.8 "alle": 50.0 "expr": 58.3 "pers": 68.8 "horn": 62.5 "fame": 6.3 "shwr": 68.8 "sani": 56.3 "rela": 45.0 "fedp": 18.8 "actn": 95.0 "purp": 50.0 "perc": 68.8 "cmdy": 31.3 , "name" : "Lexarete" "stats": "spos": 37.5 "alle": 97.7 "expr": 55.4 "pers": 35.4 "horn": 0 "fame": 60.7 "shwr": 42.3 "sani": 59.6 "rela": 43.6 "fedp": 82.3 "actn": 34.6 "purp": 22.9 "perc": 25.0 "cmdy": 85.0 , "name" : "AltarEgo" "stats": "spos": 50.0 "alle": 81.3 "expr": 66.7 "pers": 75.0 "horn": 68.8 "fame": 37.5 "shwr": 18.8 "sani": 62.5 "rela": 40.0 "fedp": 6.3 "actn": 60.0 "purp": 18.8 "perc": 56.3 "cmdy": 56.3 , "name" : "Mannerheim" "stats": "spos": 47.5 "alle": 88.6 "expr": 41.7 "pers": 69.6 "horn": 32.5 "fame": 63.1 "shwr": 67.3 "sani": 58.3 "rela": 75.0 "fedp": 39.5 "actn": 38.5 "purp": 43.8 "perc": 65.9 "cmdy": 62.5 , "name" : "Thonk" "stats": "spos": 60.0 "alle": 45.5 "expr": 25.0 "pers": 41.1 "horn": 60.0 "fame": 57.1 "shwr": 46.2 "sani": 54.2 "rela": 41.1 "fedp": 37.1 "actn": 57.7 "purp": 43.8 "perc": 56.8 "cmdy": 45.0 , "name" : "Whiprust" "stats": "spos": 68.8 "alle": 62.5 "expr": 58.3 "pers": 81.3 "horn": 93.8 "fame": 50.0 "shwr": 31.3 "sani": 68.8 "rela": 55.0 "fedp": 31.3 "actn": 80.0 "purp": 68.8 "perc": 37.5 "cmdy": 50.0 , "name" : "Jlakshan" "stats": "spos": 55.0 "alle": 81.8 "expr": 39.6 "pers": 50.0 "horn": 80.0 "fame": 58.3 "shwr": 42.3 "sani": 54.2 "rela": 55.4 "fedp": 52.4 "actn": 26.9 "purp": 50.0 "perc": 29.5 "cmdy": 62.5 , "name" : "L O R D M U S H R O O M" "stats": "spos": 43.8 "alle": 56.3 "expr": 50.0 "pers": 37.5 "horn": 43.8 "fame": 12.5 "shwr": 12.5 "sani": 43.8 "rela": 75.0 "fedp": 25.0 "actn": 80.0 "purp": 25.0 "perc": 68.8 "cmdy": 37.5 , "name" : "TheGhostOfInky" "stats": "spos": 92.5 "alle": 9.1 "expr": 66.7 "pers": 82.1 "horn": 67.5 "fame": 94.0 "shwr": 28.8 "sani": 70.8 "rela": 44.6 "fedp": 6.5 "actn": 82.7 "purp": 85.4 "perc": 50.0 "cmdy": 57.5 , "name" : "orion" "stats": "spos": 25.0 "alle": 12.5 "expr": 25.0 "pers": 87.5 "horn": 6.3 "fame": 62.5 "shwr": 75.0 "sani": 62.5 "rela": 45.0 "fedp": 12.5 "actn": 45.0 "purp": 43.8 "perc": 31.3 "cmdy": 56.3 , "name" : "Arksiane" "stats": "spos": 7.5 "alle": 95.5 "expr": 95.8 "pers": 7.1 "horn": 55.0 "fame": 67.9 "shwr": 84.6 "sani": 43.8 "rela": 62.5 "fedp": 75.8 "actn": 19.2 "purp": 22.9 "perc": 38.6 "cmdy": 82.5 , "name" : "Sauntox" "stats": "spos": 90.0 "alle": 100.0 "expr": 25.0 "pers": 37.5 "horn": 75.0 "fame": 70.2 "shwr": 23.1 "sani": 22.9 "rela": 33.9 "fedp": 21.0 "actn": 40.4 "purp": 33.3 "perc": 22.7 "cmdy": 30.0 , "name" : "Black Prussian" "stats": "spos": 47.5 "alle": 59.1 "expr": 18.8 "pers": 60.7 "horn": 60.0 "fame": 23.8 "shwr": 44.2 "sani": 50.0 "rela": 39.3 "fedp": 25.0 "actn": 65.4 "purp": 29.2 "perc": 52.3 "cmdy": 15.0 , "name" : "Ted Chadczynski" "stats": "spos": 100.0 "alle": 62.5 "expr": 8.3 "pers": 31.3 "horn": 75.0 "fame": 87.5 "shwr": 0.0 "sani": 6.3 "rela": 20.0 "fedp": 87.5 "actn": 40.0 "purp": 25.0 "perc": 0.0 "cmdy": 12.5 , "name" : "Porosha" "stats": "spos": 60.0 "alle": 38.6 "expr": 43.8 "pers": 89.3 "horn": 20.0 "fame": 47.6 "shwr": 36.5 "sani": 47.9 "rela": 85.7 "fedp": 30.6 "actn": 82.7 "purp": 35.4 "perc": 90.9 "cmdy": 75.0 , "name" : "Cynical Man" "stats": "spos": 47.5 "alle": 90.9 "expr": 22.9 "pers": 23.2 "horn": 7.5 "fame": 14.3 "shwr": 15.4 "sani": 56.3 "rela": 48.2 "fedp": 79.0 "actn": 53.8 "purp": 25.0 "perc": 77.3 "cmdy": 65.0 , "name" : "Rajun Cajun" "stats": "spos": 52.5 "alle": 36.4 "expr": 22.9 "pers": 57.1 "horn": 17.5 "fame": 38.1 "shwr": 28.8 "sani": 37.5 "rela": 67.9 "fedp": 56.5 "actn": 67.3 "purp": 37.5 "perc": 61.4 "cmdy": 52.5 , "name" : "Sykar" "stats": "spos": 56.3 "alle": 43.8 "expr": 50.0 "pers": 87.5 "horn": 25.0 "fame": 25.0 "shwr": 68.8 "sani": 43.8 "rela": 55.0 "fedp": 0.0 "actn": 65.0 "purp": 56.3 "perc": 81.3 "cmdy": 37.5 , "name" : "KiwiCommie" "stats": "spos": 65.0 "alle": 63.6 "expr": 62.5 "pers": 94.6 "horn": 55.0 "fame": 28.6 "shwr": 36.5 "sani": 66.7 "rela": 75.0 "fedp": 4.8 "actn": 63.5 "purp": 68.8 "perc": 75.0 "cmdy": 72.5 , "name" : "Byonn" "stats": "spos": 20.0 "alle": 93.2 "expr": 100.0 "pers": 16.1 "horn": 27.5 "fame": 47.6 "shwr": 69.2 "sani": 75.0 "rela": 73.2 "fedp": 90.3 "actn": 21.2 "purp": 25.0 "perc": 36.4 "cmdy": 82.5 , "name" : "Hospee" "stats": "spos": 42.5 "alle": 6.8 "expr": 20.8 "pers": 64.3 "horn": 85.0 "fame": 35.7 "shwr": 44.2 "sani": 52.1 "rela": 66.1 "fedp": 22.6 "actn": 71.2 "purp": 41.7 "perc": 63.6 "cmdy": 75.0 , "name" : "Valentine" "stats": "spos": 47.5 "alle": 70.5 "expr": 81.3 "pers": 51.8 "horn": 35.0 "fame": 44.0 "shwr": 84.6 "sani": 64.6 "rela": 66.1 "fedp": 44.4 "actn": 40.4 "purp": 39.6 "perc": 54.5 "cmdy": 65.0 , "name" : "Elitemagikarp" "stats": "spos": 27.5 "alle": 61.4 "expr": 89.6 "pers": 58.9 "horn": 17.5 "fame": 53.6 "shwr": 61.5 "sani": 52.1 "rela": 42.9 "fedp": 59.7 "actn": 42.3 "purp": 33.3 "perc": 40.9 "cmdy": 57.5 , "name" : "SomeCrusader1224" "stats": "spos": 37.5 "alle": 81.3 "expr": 25.0 "pers": 81.3 "horn": 18.8 "fame": 18.8 "shwr": 68.8 "sani": 62.5 "rela": 70.0 "fedp": 43.8 "actn": 75.0 "purp": 75.0 "perc": 25.0 "cmdy": 75.0 , "name" : "BE" "stats": "spos": 50.0 "alle": 70.5 "expr": 83.3 "pers": 76.8 "horn": 17.5 "fame": 36.9 "shwr": 48.1 "sani": 62.5 "rela": 33.9 "fedp": 53.2 "actn": 61.5 "purp": 81.3 "perc": 43.2 "cmdy": 75.0 , "name" : "ArareKINDApiggle" "stats": "spos": 75.0 "alle": 75.0 "expr": 66.7 "pers": 56.3 "horn": 25.0 "fame": 18.8 "shwr": 25.0 "sani": 68.8 "rela": 50.0 "fedp": 37.5 "actn": 80.0 "purp": 18.8 "perc": 81.3 "cmdy": 56.3 , "name" : "Kraimoco" "stats": "spos": 80.0 "alle": 50.0 "expr": 14.6 "pers": 53.6 "horn": 72.5 "fame": 13.1 "shwr": 32.7 "sani": 41.7 "rela": 50.0 "fedp": 3.2 "actn": 65.4 "purp": 52.1 "perc": 61.4 "cmdy": 30.0 , "name" : "ImJellyfish" "stats": "spos": 50.0 "alle": 75.0 "expr": 41.7 "pers": 0.0 "horn": 25.0 "fame": 0.0 "shwr": 75.0 "sani": 100.0 "rela": 65.0 "fedp": 50.0 "actn": 70.0 "purp": 37.5 "perc": 81.3 "cmdy": 56.3 , "name" : "Suno" "stats": "spos": 31.3 "alle": 81.3 "expr": 100.0 "pers": 18.8 "horn": 18.8 "fame": 68.8 "shwr": 62.5 "sani": 31.3 "rela": 65.0 "fedp": 87.5 "actn": 10.0 "purp": 0.0 "perc": 37.5 "cmdy": 81.3 , "name" : "afunhumaninter" "stats": "spos": 57.5 "alle": 36.4 "expr": 47.9 "pers": 46.4 "horn": 40.0 "fame": 38.1 "shwr": 38.5 "sani": 79.2 "rela": 66.1 "fedp": 58.1 "actn": 67.3 "purp": 33.3 "perc": 50.0 "cmdy": 40.0 , "name" : "SussyNuoh" "stats": "spos": 37.5 "alle": 75.0 "expr": 33.3 "pers": 68.8 "horn": 43.8 "fame": 25.0 "shwr": 75.0 "sani": 50.0 "rela": 90.0 "fedp": 43.8 "actn": 65.0 "purp": 31.3 "perc": 81.3 "cmdy": 81.3 , "name" : "astro200" "stats": "spos": 31.3 "alle": 56.3 "expr": 58.3 "pers": 68.8 "horn": 62.5 "fame": 50.0 "shwr": 62.5 "sani": 56.3 "rela": 65.0 "fedp": 37.5 "actn": 65.0 "purp": 18.8 "perc": 68.8 "cmdy": 31.3 , "name" : "Duck" "stats": "spos": 57.5 "alle": 36.4 "expr": 47.9 "pers": 46.4 "horn": 40.0 "fame": 38.1 "shwr": 38.5 "sani": 79.2 "rela": 66.1 "fedp": 58.1 "actn": 67.3 "purp": 33.3 "perc": 50.0 "cmdy": 40.0 , "name" : "BERNHE0504" "stats": "spos": 68.8 "alle": 37.5 "expr": 83.3 "pers": 18.8 "horn": 6.3 "fame": 43.8 "shwr": 25.0 "sani": 75.0 "rela": 75.0 "fedp": 68.8 "actn": 65.0 "purp": 62.5 "perc": 62.5 "cmdy": 87.5 , "name" : "Nikia Paige" "stats": "spos": 25.0 "alle": 37.5 "expr": 16.7 "pers": 81.3 "horn": 50.0 "fame": 25.0 "shwr": 75.0 "sani": 68.8 "rela": 75.0 "fedp": 0.0 "actn": 65.0 "purp": 50.0 "perc": 43.8 "cmdy": 43.8 , "name" : "Matmaj THM" "stats": "spos": 90.0 "alle": 0.0 "expr": 41.7 "pers": 50.0 "horn": 0.0 "fame": 19.0 "shwr": 23.1 "sani": 16.7 "rela": 0.0 "fedp": 6.5 "actn": 84.6 "purp": 66.7 "perc": 45.5 "cmdy": 10.0 , "name" : "Matmaj THM (Party Approved)" "stats": "spos": 100.0 "alle": 0.0 "expr": 41.7 "pers": 50.0 "horn": 0.0 "fame": 0.0 "shwr": 0 "sani": 0 "rela": 0.0 "fedp": 0 "actn": 100 "purp": 66.7 "perc": 100 "cmdy": 0.0 , "name" : "Cyb3klev" "stats": "spos": 77.5 "alle": 100.0 "expr": 20.8 "pers": 42.5 "horn": 82.5 "fame": 16.7 "shwr": 53.8 "sani": 60.4 "rela": 53.6 "fedp": 51.9 "actn": 32.3 "purp": 29.2 "perc": 72.7 "cmdy": 40.0 , "name" : "Sabkv" "stats": "spos": 75.0 "alle": 100.0 "expr": 66.7 "pers": 25.0 "horn": 100.0 "fame": 50.0 "shwr": 0.0 "sani": 25.0 "rela": 55.0 "fedp": 50.0 "actn": 10.0 "purp": 56.3 "perc": 50.0 "cmdy": 25.0 , "name" : "Carpenter family" "stats": "spos": 37.5 "alle": 50.0 "expr": 58.3 "pers": 68.8 "horn": 50.0 "fame": 43.8 "shwr": 56.3 "sani": 62.5 "rela": 35.0 "fedp": 25.0 "actn": 45.0 "purp": 43.8 "perc": 6.3 "cmdy": 62.5 , "name" : "Schizology" "stats": "spos": 43.8 "alle": 93.8 "expr": 91.7 "pers": 0.0 "horn": 50.0 "fame": 56.3 "shwr": 18.8 "sani": 0.0 "rela": 35.0 "fedp": 68.8 "actn": 5.0 "purp": 0.0 "perc": 56.3 "cmdy": 56.3 , "name" : "Sölvi" "stats": "spos": 72.5 "alle": 22.7 "expr": 12.5 "pers": 76.8 "horn": 67.5 "fame": 11.9 "shwr": 36.5 "sani": 50.0 "rela": 44.6 "fedp": 40.3 "actn": 65.4 "purp": 33.3 "perc": 56.8 "cmdy": 30.0 , "name" : "Erstanden" "stats": "spos": 50.0 "alle": 84.1 "expr": 31.3 "pers": 30.4 "horn": 20.0 "fame": 53.6 "shwr": 30.8 "sani": 56.3 "rela": 42.9 "fedp": 95.2 "actn": 23.1 "purp": 35.4 "perc": 31.8 "cmdy": 47.5 , "name" : "Pope Pius XV" "stats": "spos": 37.5 "alle": 79.5 "expr": 39.6 "pers": 75.0 "horn": 47.5 "fame": 32.1 "shwr": 40.4 "sani": 47.9 "rela": 48.2 "fedp": 38.7 "actn": 38.5 "purp": 35.4 "perc": 56.8 "cmdy": 77.5 , "name" : "Duckles" "stats": "spos": 70.0 "alle": 31.8 "expr": 14.6 "pers": 76.8 "horn": 80.0 "fame": 16.7 "shwr": 26.9 "sani": 39.6 "rela": 48.2 "fedp": 1.6 "actn": 69.2 "purp": 22.9 "perc": 65.9 "cmdy": 30.0 , "name" : "Duke Atom" "stats": "spos": 47.5 "alle": 84.1 "expr": 37.5 "pers": 32.1 "horn": 100.0 "fame": 54.8 "shwr": 30.8 "sani": 58.3 "rela": 80.4 "fedp": 25.8 "actn": 36.5 "purp": 81.3 "perc": 63.6 "cmdy": 82.5 , "name" : "Banana dispenser" "stats": "spos": 62.5 "alle": 68.8 "expr": 58.3 "pers": 81.3 "horn": 25.0 "fame": 50.0 "shwr": 43.8 "sani": 25.0 "rela": 60.0 "fedp": 50.0 "actn": 80.0 "purp": 37.5 "perc": 68.8 "cmdy": 43.8 , "name" : "Livony" "stats": "spos": 43.8 "alle": 6.3 "expr": 41.7 "pers": 75.0 "horn": 43.8 "fame": 25.0 "shwr": 68.8 "sani": 25.0 "rela": 55.0 "fedp": 0.0 "actn": 100.0 "purp": 18.8 "perc": 62.5 "cmdy": 50.0 , "name" : "Immorxius" "stats": "spos": 50.0 "alle": 56.3 "expr": 50.0 "pers": 37.5 "horn": 50.0 "fame": 31.3 "shwr": 43.8 "sani": 56.3 "rela": 50.0 "fedp": 37.5 "actn": 80.0 "purp": 43.8 "perc": 62.5 "cmdy": 31.3 , "name" : "Chad_Enthusiast" "stats": "spos": 70.0 "alle": 56.8 "expr": 27.1 "pers": 73.2 "horn": 20.6 "fame": 25.0 "shwr": 7.7 "sani": 48.6 "rela": 50.0 "fedp": 70.2 "actn": 45.7 "purp": 62.5 "perc": 68.2 "cmdy": 45.0 , "name" : "Heinrich Cheung" "stats": "spos": 45.0 "alle": 22.7 "expr": 33.3 "pers": 42.9 "horn": 70.0 "fame": 38.1 "shwr": 30.8 "sani": 62.5 "rela": 55.4 "fedp": 88.7 "actn": 61.5 "purp": 52.1 "perc": 70.5 "cmdy": 45.0 , "name" : "Krab Man" "stats": "spos": 50.0 "alle": 50.0 "expr": 83.3 "pers": 50.0 "horn": 62.5 "fame": 68.8 "shwr": 37.5 "sani": 62.5 "rela": 55.0 "fedp": 6.3 "actn": 55.0 "purp": 56.3 "perc": 25.0 "cmdy": 37.5 , "name" : "GweenTea" "stats": "spos": 67.5 "alle": 47.7 "expr": 29.2 "pers": 76.8 "horn": 62.5 "fame": 22.6 "shwr": 51.9 "sani": 52.1 "rela": 48.2 "fedp": 34.7 "actn": 61.5 "purp": 54.2 "perc": 72.7 "cmdy": 42.5 , "name" : "incredibledeadman" "stats": "spos": 62.5 "alle": 6.3 "expr": 58.3 "pers": 68.8 "horn": 37.5 "fame": 0.0 "shwr": 62.5 "sani": 75.0 "rela": 45.0 "fedp": 12.5 "actn": 90.0 "purp": 43.8 "perc": 56.3 "cmdy": 12.5 , "name" : "Al'Zeta" "stats": "spos": 50.0 "alle": 6.3 "expr": 41.7 "pers": 75.0 "horn": 62.5 "fame": 50.0 "shwr": 37.5 "sani": 37.5 "rela": 85.0 "fedp": 62.5 "actn": 80.0 "purp": 37.5 "perc": 75.0 "cmdy": 75.0 , "name" : "nyteulo" "stats": "spos": 22.5 "alle": 25.0 "expr": 22.9 "pers": 67.9 "horn": 32.5 "fame": 40.5 "shwr": 34.6 "sani": 77.1 "rela": 64.3 "fedp": 29.8 "actn": 67.3 "purp": 31.3 "perc": 72.7 "cmdy": 67.5 , "name" : "AquaHeart" "stats": "spos": 62.5 "alle": 25.0 "expr": 50.0 "pers": 93.8 "horn": 31.3 "fame": 0.0 "shwr": 62.5 "sani": 50.0 "rela": 75.0 "fedp": 6.3 "actn": 95.0 "purp": 43.8 "perc": 68.8 "cmdy": 18.8 , "name" : "Plant" "stats": "spos": 35.0 "alle": 79.5 "expr": 100.0 "pers": 58.9 "horn": 17.5 "fame": 65.5 "shwr": 63.5 "sani": 60.4 "rela": 73.2 "fedp": 57.3 "actn": 42.3 "purp": 16.7 "perc": 63.6 "cmdy": 65.0 , "name" : "Arunn" "stats": "spos": 35.0 "alle": 70.5 "expr": 81.3 "pers": 57.1 "horn": 12.5 "fame": 9.5 "shwr": 25.0 "sani": 70.8 "rela": 69.6 "fedp": 25.8 "actn": 61.5 "purp": 39.6 "perc": 63.6 "cmdy": 37.5 , "name" : "somi" "stats": "spos": 42.5 "alle": 59.1 "expr": 27.1 "pers": 58.9 "horn": 15.0 "fame": 44.0 "shwr": 23.1 "sani": 45.8 "rela": 60.7 "fedp": 71.0 "actn": 57.7 "purp": 39.6 "perc": 38.6 "cmdy": 72.5 , "name" : "Ukraiana" "stats": "spos": 95.0 "alle": 34.1 "expr": 25.0 "pers": 26.8 "horn": 27.5 "fame": 11.9 "shwr": 17.3 "sani": 70.8 "rela": 71.4 "fedp": 87.9 "actn": 67.3 "purp": 45.8 "perc": 65.9 "cmdy": 55.0 , "name" : "DrMorth" "stats": "spos": 55.0 "alle": 93.2 "expr": 14.6 "pers": 12.5 "horn": 42.5 "fame": 17.9 "shwr": 34.6 "sani": 50.0 "rela": 57.1 "fedp": 91.9 "actn": 21.2 "purp": 18.8 "perc": 50.0 "cmdy": 50.0 , "name" : "Ninjack-Aus" "stats": "spos": 80.0 "alle": 47.7 "expr": 39.6 "pers": 75.0 "horn": 72.5 "fame": 45.2 "shwr": 46.2 "sani": 75.0 "rela": 85.7 "fedp": 17.7 "actn": 63.5 "purp": 70.8 "perc": 77.3 "cmdy": 67.5 , "name" : "Fabius" "stats": "spos": 81.3 "alle": 18.8 "expr": 25.0 "pers": 100.0 "horn": 6.3 "fame": 31.3 "shwr": 37.5 "sani": 81.3 "rela": 75.0 "fedp": 37.5 "actn": 90.0 "purp": 25.0 "perc": 56.3 "cmdy": 75.0 , "name" : "Squide" "stats": "spos": 32.5 "alle": 97.7 "expr": 97.9 "pers": 44.6 "horn": 10.0 "fame": 40.5 "shwr": 75.0 "sani": 35.4 "rela": 37.5 "fedp": 58.9 "actn": 36.5 "purp": 16.7 "perc": 22.7 "cmdy": 25.0 , "name" : "firebender1234" "stats": "spos": 56.3 "alle": 75.0 "expr": 58.3 "pers": 75.0 "horn": 6.3 "fame": 50.0 "shwr": 25.0 "sani": 62.5 "rela": 45.0 "fedp": 87.5 "actn": 75.0 "purp": 31.3 "perc": 62.5 "cmdy": 100.0 , "name" : "Sarperen" "stats": "spos": 50.0 "alle": 43.8 "expr": 41.7 "pers": 75.0 "horn": 62.5 "fame": 6.3 "shwr": 81.3 "sani": 37.5 "rela": 70.0 "fedp": 6.3 "actn": 90.0 "purp": 31.3 "perc": 75.0 "cmdy": 43.8 , "name" : "SweatingCup2632" "stats": "spos": 40.0 "alle": 50.0 "expr": 75.0 "pers": 80.0 "horn": 0.0 "fame": 55.0 "shwr": 55.0 "sani": 85.0 "rela": 50.0 "fedp": 45.0 "actn": 90.0 "purp": 20.0 "perc": 60.0 "cmdy": 55.0 , "name" : "Antonio_1" "stats": "spos": 42.5 "alle": 54.5 "expr": 16.7 "pers": 55.4 "horn": 57.5 "fame": 14.3 "shwr": 30.8 "sani": 66.7 "rela": 64.3 "fedp": 39.5 "actn": 51.9 "purp": 43.8 "perc": 72.7 "cmdy": 60.0 , "name" : "Jack C" "stats": "spos": 75.0 "alle": 63.6 "expr": 20.8 "pers": 73.2 "horn": 27.5 "fame": 26.2 "shwr": 28.8 "sani": 85.4 "rela": 53.6 "fedp": 19.4 "actn": 71.2 "purp": 39.6 "perc": 54.5 "cmdy": 47.5 , "name" : "FANT" "stats": "spos": 47.5 "alle": 43.2 "expr": 12.5 "pers": 32.1 "horn": 60.0 "fame": 19.0 "shwr": 7.7 "sani": 60.4 "rela": 42.9 "fedp": 58.1 "actn": 48.1 "purp": 62.5 "perc": 56.8 "cmdy": 37.5 , "name" : "Lawrence" "stats": "spos": 56.3 "alle": 25.0 "expr": 50.0 "pers": 81.3 "horn": 0.0 "fame": 0.0 "shwr": 25.0 "sani": 87.5 "rela": 90.0 "fedp": 43.8 "actn": 95.0 "purp": 56.3 "perc": 87.5 "cmdy": 37.5 , "name" : "The Iced" "stats": "spos": 56.3 "alle": 12.5 "expr": 41.7 "pers": 68.8 "horn": 12.5 "fame": 37.5 "shwr": 62.5 "sani": 62.5 "rela": 75.0 "fedp": 0.0 "actn": 90.0 "purp": 18.8 "perc": 75.0 "cmdy": 62.5 , "name" : "Affiliated" "stats": "spos": 50.0 "alle": 100.0 "expr": 8.3 "pers": 37.5 "horn": 100.0 "fame": 43.8 "shwr": 0.0 "sani": 25.0 "rela": 100.0 "fedp": 18.8 "actn": 60.0 "purp": 0.0 "perc": 75.0 "cmdy": 50.0 , "name" : "Councilguy" "stats": "spos": 68.8 "alle": 43.8 "expr": 58.3 "pers": 68.8 "horn": 81.3 "fame": 62.5 "shwr": 0.0 "sani": 56.3 "rela": 70.0 "fedp": 43.8 "actn": 75.0 "purp": 37.5 "perc": 62.5 "cmdy": 62.5 , "name" : "ThisIsMyUsernameAAA" "stats": "spos": 37.5 "alle": 100.0 "expr": 83.3 "pers": 100.0 "horn": 56.3 "fame": 100.0 "shwr": 12.5 "sani": 43.8 "rela": 65.0 "fedp": 18.8 "actn": 10.0 "purp": 0.0 "perc": 12.5 "cmdy": 37.5 , "name" : "Sr Deyvid" "stats": "spos": 80.0 "alle": 27.3 "expr": 62.5 "pers": 89.3 "horn": 7.5 "fame": 75.0 "shwr": 38.5 "sani": 85.4 "rela": 96.4 "fedp": 51.6 "actn": 80.8 "purp": 56.3 "perc": 72.7 "cmdy": 62.5 , "name" : "AmericanFascist" "stats": "spos": 81.3 "alle": 43.8 "expr": 58.3 "pers": 56.3 "horn": 12.5 "fame": 62.5 "shwr": 25.0 "sani": 81.3 "rela": 65.0 "fedp": 62.5 "actn": 80.0 "purp": 18.8 "perc": 56.3 "cmdy": 81.3 ]
112495
[ "name" : "<NAME>" "stats": "spos": 73.5 "alle": 70.0 "expr": 66.7 "pers": 75.0 "horn": 8.3 "fame": 59.0 "shwr": 43.5 "sani": 79.3 "rela": 73.9 "fedp": 60.7 "actn": 52.6 "purp": 78.9 "perc": 73.3 "cmdy": 79.7 , "name" : "<NAME>" "stats": "spos": 65.0 "alle": 33.2 "expr": 56.9 "pers": 77.4 "horn": 71.7 "fame": 83.5 "shwr": 43.6 "sani": 65.3 "rela": 73.8 "fedp": 6.0 "actn": 69.3 "purp": 71.2 "perc": 76.7 "cmdy": 61.2 , "name" : "<NAME>" "stats": "spos": 42.5 "alle": 79.5 "expr": 91.7 "pers": 1.8 "horn": 10.0 "fame": 73.8 "shwr": 48.1 "sani": 27.1 "rela": 80.4 "fedp": 100.0 "actn": 17.3 "purp": 22.9 "perc": 38.6 "cmdy": 97.5 , "name" : "<NAME>" "stats": "spos": 56.8 "alle": 91.7 "expr": 34.8 "pers": 42.9 "horn": 33.3 "fame": 27.2 "shwr": 30.7 "sani": 48.7 "rela": 44.1 "fedp": 81.0 "actn": 40.9 "purp": 34.9 "perc": 51.8 "cmdy": 40.8 , "name" : "ItsDanny101" "stats": "spos": 45.8 "alle": 54.1 "expr": 77.8 "pers": 79.1 "horn": 0.0 "fame": 79.3 "shwr": 58.4 "sani": 54.1 "rela": 79.3 "fedp": 54.0 "actn": 70.1 "purp": 8.3 "perc": 66.6 "cmdy": 75.0 , "name" : "<NAME>" "stats": "spos": 55.0 "alle": 53.3 "expr": 94.5 "pers": 57.2 "horn": 76.7 "fame": 83.3 "shwr": 39.8 "sani": 65.3 "rela": 86.9 "fedp": 51.2 "actn": 64.1 "purp": 71.2 "perc": 48.4 "cmdy": 79.6 , "name" : "<NAME>elSm<NAME>" "stats": "spos": 70.0 "alle": 45.0 "expr": 33.3 "pers": 64.3 "horn": 40.0 "fame": 57.5 "shwr": 47.4 "sani": 70.9 "rela": 51.2 "fedp": 28.5 "actn": 71.8 "purp": 51.5 "perc": 50.0 "cmdy": 57.4 , "name" : "EugeneTLT" "stats": "spos": 33.4 "alle": 37.5 "expr": 55.5 "pers": 79.3 "horn": 8.4 "fame": 20.8 "shwr": 66.8 "sani": 45.8 "rela": 70.8 "fedp": 37.6 "actn": 66.8 "purp": 58.4 "perc": 71.0 "cmdy": 45.8 , "name" : "Froggers" "stats": "spos": 41.6 "alle": 50.0 "expr": 61.2 "pers": 60.8 "horn": 35.0 "fame": 77.4 "shwr": 65.3 "sani": 44.5 "rela": 88.2 "fedp": 60.7 "actn": 43.7 "purp": 45.5 "perc": 75.1 "cmdy": 81.6 , "name" : "Beeper" "stats": "spos": 37.5 "alle": 79.3 "expr": 61.2 "pers": 79.3 "horn": 41.6 "fame": 45.8 "shwr": 37.4 "sani": 75.1 "rela": 66.8 "fedp": 75.0 "actn": 70.1 "purp": 83.4 "perc": 54.1 "cmdy": 58.4 , "name" : "wasp_" "stats": "spos": 58.4 "alle": 33.4 "expr": 89.0 "pers": 50.0 "horn": 70.8 "fame": 79.3 "shwr": 83.4 "sani": 54.3 "rela": 54.3 "fedp": 25.0 "actn": 66.7 "purp": 54.1 "perc": 54.1 "cmdy": 45.9 , "name" : "<NAME>" "stats": "spos": 66.7 "alle": 78.4 "expr": 62.5 "pers": 32.2 "horn": 88.3 "fame": 68.2 "shwr": 19.2 "sani": 23.6 "rela": 8.3 "fedp": 46.4 "actn": 17.9 "purp": 36.3 "perc": 35.0 "cmdy": 77.8 , "name" : "<NAME>" "stats": "spos": 23.2 "alle": 31.6 "expr": 23.5 "pers": 81.0 "horn": 61.7 "fame": 66.8 "shwr": 50.0 "sani": 62.5 "rela": 41.7 "fedp": 5.9 "actn": 79.6 "purp": 39.4 "perc": 41.8 "cmdy": 25.8 , "name" : "<NAME>" "stats": "spos": 86.7 "alle": 12.7 "expr": 86.2 "pers": 83.6 "horn": 46.3 "fame": 84.8 "shwr": 53.8 "sani": 55.9 "rela": 67.1 "fedp": 12.2 "actn": 82.7 "purp": 88.0 "perc": 65.6 "cmdy": 50.1 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 38.6 "expr": 37.5 "pers": 76.8 "horn": 30.0 "fame": 64.3 "shwr": 50.0 "sani": 72.9 "rela": 78.6 "fedp": 14.5 "actn": 71.2 "purp": 18.8 "perc": 88.6 "cmdy": 57.5 , "name" : "chicken piccata" "stats": "spos": 67.5 "alle": 22.7 "expr": 8.3 "pers": 89.3 "horn": 22.5 "fame": 57.1 "shwr": 71.2 "sani": 75.0 "rela": 75.0 "fedp": 20.2 "actn": 84.6 "purp": 50.0 "perc": 75.0 "cmdy": 15.0 , "name" : "YourLocalDegenerateMao" "stats": "spos": 55.0 "alle": 56.6 "expr": 38.9 "pers": 82.3 "horn": 51.6 "fame": 65.2 "shwr": 57.7 "sani": 61.1 "rela": 73.9 "fedp": 22.6 "actn": 74.3 "purp": 36.3 "perc": 73.3 "cmdy": 55.6 , "name" : "bowie" "stats": "spos": 50.0 "alle": 50.0 "expr": 33.3 "pers": 35.7 "horn": 52.5 "fame": 65.5 "shwr": 48.1 "sani": 52.1 "rela": 62.5 "fedp": 33.1 "actn": 51.9 "purp": 33.3 "perc": 63.6 "cmdy": 65.0 , "name" : "<NAME>" "stats": "spos": 65.0 "alle": 83.5 "expr": 83.4 "pers": 41.6 "horn": 60.0 "fame": 34.7 "shwr": 53.9 "sani": 55.6 "rela": 53.6 "fedp": 35.6 "actn": 48.7 "purp": 34.9 "perc": 58.3 "cmdy": 37.1 , "name" : "Rayz9989" "stats": "spos": 65.0 "alle": 20.5 "expr": 27.1 "pers": 100.0 "horn": 67.5 "fame": 100.0 "shwr": 5.8 "sani": 75.0 "rela": 60.7 "fedp": 12.9 "actn": 84.6 "purp": 37.5 "perc": 37.5 "cmdy": 75.0 , "name" : "Swoosho" "stats": "spos": 56.7 "alle": 62.5 "expr": 65.2 "pers": 56.2 "horn": 100.0 "fame": 68.8 "shwr": 77.8 "sani": 38.9 "rela": 75.0 "fedp": 31.3 "actn": 43.2 "purp": 37.5 "perc": 75.0 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 56.3 "alle": 100.0 "expr": 41.7 "pers": 100.0 "horn": 100.0 "fame": 93.8 "shwr": 0.0 "sani": 31.3 "rela": 62.5 "fedp": 0.0 "actn": 55.0 "purp": 18.8 "perc": 0.0 "cmdy": 31.3 , "name" : "<NAME>" "stats": "spos": 35.0 "alle": 50.0 "expr": 25.0 "pers": 48.2 "horn": 70.0 "fame": 47.7 "shwr": 65.4 "sani": 37.5 "rela": 25.0 "fedp": 42.9 "actn": 59.6 "purp": 34.1 "perc": 40.0 "cmdy": 30.6 , "name" : "<NAME>" "stats": "spos": 87.5 "alle": 100.0 "expr": 66.7 "pers": 56.3 "horn": 25.0 "fame": 100.0 "shwr": 6.3 "sani": 25.0 "rela": 0.0 "fedp": 75.0 "actn": 0.0 "purp": 56.3 "perc": 0.0 "cmdy": 25.0 , "name" : "<NAME>" "stats": "spos": 100.0 "alle": 100.0 "expr": 25.0 "pers": 56.3 "horn": 75.0 "fame": 6.3 "shwr": 6.3 "sani": 43.7 "rela": 0.0 "fedp": 25.0 "actn": 56.3 "purp": 93.7 "perc": 25.0 "cmdy": 0.0 , "name" : "<NAME>" "stats": "spos": 67.5 "alle": 100.0 "expr": 100.0 "pers": 50.0 "horn": 32.5 "fame": 40.9 "shwr": 44.2 "sani": 60.4 "rela": 71.4 "fedp": 78.6 "actn": 28.8 "purp": 18.2 "perc": 45.0 "cmdy": 66.7 , "name" : "ThatoneguyG" "stats": "spos": 50.0 "alle": 100.0 "expr": 33.3 "pers": 100.0 "horn": 100.0 "fame": 0.0 "shwr": 0.0 "sani": 93.8 "rela": 68.8 "fedp": 18.8 "actn": 45.0 "purp": 31.3 "perc": 50.0 "cmdy": 62.5 , "name" : "märkl" "stats": "spos": 37.5 "alle": 25.0 "expr": 33.3 "pers": 62.5 "horn": 62.5 "fame": 25.0 "shwr": 50.0 "sani": 75.0 "rela": 75.0 "fedp": 25.0 "actn": 75.0 "purp": 50.0 "perc": 62.5 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 12.5 "alle": 100.0 "expr": 100.0 "pers": 12.5 "horn": 0 "fame": 68.8 "shwr": 75.0 "sani": 75.0 "rela": 50.0 "fedp": 93.8 "actn": 40.0 "purp": 0.0 "perc": 68.8 "cmdy": 93.8 , "name" : "<NAME>" "stats": "spos": 15.0 "alle": 84.1 "expr": 100.0 "pers": 66.1 "horn": 12.5 "fame": 48.8 "shwr": 76.9 "sani": 56.3 "rela": 58.9 "fedp": 59.7 "actn": 46.2 "purp": 20.8 "perc": 59.1 "cmdy": 67.5 , "name" : "Padstar34" "stats": "spos": 37.5 "alle": 68.8 "expr": 33.3 "pers": 81.3 "horn": 50.0 "fame": 56.3 "shwr": 25.0 "sani": 62.5 "rela": 55.0 "fedp": 0.0 "actn": 70.0 "purp": 31.3 "perc": 31.3 "cmdy": 68.8 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 79.5 "expr": 20.8 "pers": 33.9 "horn": 72.5 "fame": 42.9 "shwr": 25.0 "sani": 47.9 "rela": 64.3 "fedp": 46.0 "actn": 46.2 "purp": 33.3 "perc": 56.8 "cmdy": 65.0 , "name" : "<NAME>" "stats": "spos": 37.5 "alle": 68.8 "expr": 58.3 "pers": 18.8 "horn": 31.3 "fame": 56.3 "shwr": 93.8 "sani": 68.8 "rela": 65.0 "fedp": 81.3 "actn": 35.0 "purp": 93.8 "perc": 43.8 "cmdy": 43.8 , "name" : "<NAME> " "stats": "spos": 37.5 "alle": 56.3 "expr": 75.0 "pers": 68.8 "horn": 18.8 "fame": 0.0 "shwr": 68.8 "sani": 62.5 "rela": 50.0 "fedp": 31.3 "actn": 60.0 "purp": 50.0 "perc": 62.5 "cmdy": 50.0 , "name" : "<NAME>" "stats": "spos": 92.5 "alle": 54.5 "expr": 41.7 "pers": 71.4 "horn": 70.0 "fame": 29.8 "shwr": 21.2 "sani": 39.6 "rela": 67.9 "fedp": 19.4 "actn": 51.9 "purp": 45.8 "perc": 59.1 "cmdy": 30.0 , "name" : "<NAME>" "stats": "spos": 52.5 "alle": 54.5 "expr": 27.1 "pers": 33.9 "horn": 35.0 "fame": 53.6 "shwr": 63.5 "sani": 43.8 "rela": 51.8 "fedp": 71.0 "actn": 51.9 "purp": 56.3 "perc": 50.0 "cmdy": 50.0 , "name" : "IncendiaryBullet" "stats": "spos": 25.0 "alle": 86.4 "expr": 97.9 "pers": 35.7 "horn": 25.0 "fame": 67.9 "shwr": 44.2 "sani": 66.7 "rela": 55.4 "fedp": 95.2 "actn": 26.9 "purp": 54.2 "perc": 29.5 "cmdy": 87.5 , "name" : "<NAME>" "stats": "spos": 75.0 "alle": 18.8 "expr": 58.3 "pers": 93.8 "horn": 50.0 "fame": 6.3 "shwr": 75.0 "sani": 56.3 "rela": 80.0 "fedp": 18.8 "actn": 90.0 "purp": 31.3 "perc": 68.8 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 17.5 "alle": 57.3 "expr": 90.9 "pers": 46.4 "horn": 2.5 "fame": 60.7 "shwr": 88.5 "sani": 79.2 "rela": 75.4 "fedp": 47.6 "actn": 65.8 "purp": 4.6 "perc": 84.1 "cmdy": 77.5 , "name" : "The Infinity Pizza" "stats": "spos": 50.0 "alle": 65.9 "expr": 31.3 "pers": 46.4 "horn": 62.5 "fame": 31.0 "shwr": 69.2 "sani": 60.4 "rela": 66.1 "fedp": 32.3 "actn": 59.6 "purp": 54.2 "perc": 59.1 "cmdy": 55.0 , "name" : "PastaGuy27" "stats": "spos": 56.3 "alle": 81.3 "expr": 75.0 "pers": 43.8 "horn": 37.5 "fame": 6.3 "shwr": 62.5 "sani": 75.0 "rela": 55.0 "fedp": 18.8 "actn": 85.0 "purp": 31.3 "perc": 62.5 "cmdy": 37.5 , "name" : "<NAME>" "stats": "spos": 90.0 "alle": 22.7 "expr": 0.0 "pers": 66.1 "horn": 5.0 "fame": 11.9 "shwr": 19.2 "sani": 39.6 "rela": 51.8 "fedp": 32.3 "actn": 50.0 "purp": 58.3 "perc": 25.0 "cmdy": 25.0 , "name" : "<NAME>." "stats": "spos": 55.0 "alle": 45.5 "expr": 20.8 "pers": 71.4 "horn": 57.5 "fame": 14.3 "shwr": 38.5 "sani": 77.1 "rela": 44.6 "fedp": 54.8 "actn": 80.8 "purp": 25.0 "perc": 61.4 "cmdy": 57.5 , "name" : "antichristhater" "stats": "spos": 56.3 "alle": 68.8 "expr": 33.3 "pers": 37.5 "horn": 6.3 "fame": 50.0 "shwr": 75.0 "sani": 81.3 "rela": 65.0 "fedp": 50.0 "actn": 75.0 "purp": 12.5 "perc": 43.8 "cmdy": 75.0 , "name" : "oRange" "stats": "spos": 52.5 "alle": 56.8 "expr": 83.3 "pers": 66.1 "horn": 30.0 "fame": 72.6 "shwr": 42.3 "sani": 60.4 "rela": 82.1 "fedp": 43.5 "actn": 55.8 "purp": 64.6 "perc": 81.8 "cmdy": 87.5 , "name" : "Leo9" "stats": "spos": 55.0 "alle": 81.8 "expr": 29.2 "pers": 64.3 "horn": 62.5 "fame": 13.1 "shwr": 21.2 "sani": 47.9 "rela": 57.1 "fedp": 8.1 "actn": 48.1 "purp": 58.3 "perc": 65.9 "cmdy": 45.0 , "name" : "<NAME>" "stats": "spos": 68.8 "alle": 50.0 "expr": 58.3 "pers": 68.8 "horn": 62.5 "fame": 6.3 "shwr": 68.8 "sani": 56.3 "rela": 45.0 "fedp": 18.8 "actn": 95.0 "purp": 50.0 "perc": 68.8 "cmdy": 31.3 , "name" : "<NAME>" "stats": "spos": 37.5 "alle": 97.7 "expr": 55.4 "pers": 35.4 "horn": 0 "fame": 60.7 "shwr": 42.3 "sani": 59.6 "rela": 43.6 "fedp": 82.3 "actn": 34.6 "purp": 22.9 "perc": 25.0 "cmdy": 85.0 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 81.3 "expr": 66.7 "pers": 75.0 "horn": 68.8 "fame": 37.5 "shwr": 18.8 "sani": 62.5 "rela": 40.0 "fedp": 6.3 "actn": 60.0 "purp": 18.8 "perc": 56.3 "cmdy": 56.3 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 88.6 "expr": 41.7 "pers": 69.6 "horn": 32.5 "fame": 63.1 "shwr": 67.3 "sani": 58.3 "rela": 75.0 "fedp": 39.5 "actn": 38.5 "purp": 43.8 "perc": 65.9 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 60.0 "alle": 45.5 "expr": 25.0 "pers": 41.1 "horn": 60.0 "fame": 57.1 "shwr": 46.2 "sani": 54.2 "rela": 41.1 "fedp": 37.1 "actn": 57.7 "purp": 43.8 "perc": 56.8 "cmdy": 45.0 , "name" : "<NAME>" "stats": "spos": 68.8 "alle": 62.5 "expr": 58.3 "pers": 81.3 "horn": 93.8 "fame": 50.0 "shwr": 31.3 "sani": 68.8 "rela": 55.0 "fedp": 31.3 "actn": 80.0 "purp": 68.8 "perc": 37.5 "cmdy": 50.0 , "name" : "<NAME>" "stats": "spos": 55.0 "alle": 81.8 "expr": 39.6 "pers": 50.0 "horn": 80.0 "fame": 58.3 "shwr": 42.3 "sani": 54.2 "rela": 55.4 "fedp": 52.4 "actn": 26.9 "purp": 50.0 "perc": 29.5 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 43.8 "alle": 56.3 "expr": 50.0 "pers": 37.5 "horn": 43.8 "fame": 12.5 "shwr": 12.5 "sani": 43.8 "rela": 75.0 "fedp": 25.0 "actn": 80.0 "purp": 25.0 "perc": 68.8 "cmdy": 37.5 , "name" : "TheGhostOfInky" "stats": "spos": 92.5 "alle": 9.1 "expr": 66.7 "pers": 82.1 "horn": 67.5 "fame": 94.0 "shwr": 28.8 "sani": 70.8 "rela": 44.6 "fedp": 6.5 "actn": 82.7 "purp": 85.4 "perc": 50.0 "cmdy": 57.5 , "name" : "<NAME>ion" "stats": "spos": 25.0 "alle": 12.5 "expr": 25.0 "pers": 87.5 "horn": 6.3 "fame": 62.5 "shwr": 75.0 "sani": 62.5 "rela": 45.0 "fedp": 12.5 "actn": 45.0 "purp": 43.8 "perc": 31.3 "cmdy": 56.3 , "name" : "<NAME>" "stats": "spos": 7.5 "alle": 95.5 "expr": 95.8 "pers": 7.1 "horn": 55.0 "fame": 67.9 "shwr": 84.6 "sani": 43.8 "rela": 62.5 "fedp": 75.8 "actn": 19.2 "purp": 22.9 "perc": 38.6 "cmdy": 82.5 , "name" : "<NAME>" "stats": "spos": 90.0 "alle": 100.0 "expr": 25.0 "pers": 37.5 "horn": 75.0 "fame": 70.2 "shwr": 23.1 "sani": 22.9 "rela": 33.9 "fedp": 21.0 "actn": 40.4 "purp": 33.3 "perc": 22.7 "cmdy": 30.0 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 59.1 "expr": 18.8 "pers": 60.7 "horn": 60.0 "fame": 23.8 "shwr": 44.2 "sani": 50.0 "rela": 39.3 "fedp": 25.0 "actn": 65.4 "purp": 29.2 "perc": 52.3 "cmdy": 15.0 , "name" : "<NAME>" "stats": "spos": 100.0 "alle": 62.5 "expr": 8.3 "pers": 31.3 "horn": 75.0 "fame": 87.5 "shwr": 0.0 "sani": 6.3 "rela": 20.0 "fedp": 87.5 "actn": 40.0 "purp": 25.0 "perc": 0.0 "cmdy": 12.5 , "name" : "<NAME>" "stats": "spos": 60.0 "alle": 38.6 "expr": 43.8 "pers": 89.3 "horn": 20.0 "fame": 47.6 "shwr": 36.5 "sani": 47.9 "rela": 85.7 "fedp": 30.6 "actn": 82.7 "purp": 35.4 "perc": 90.9 "cmdy": 75.0 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 90.9 "expr": 22.9 "pers": 23.2 "horn": 7.5 "fame": 14.3 "shwr": 15.4 "sani": 56.3 "rela": 48.2 "fedp": 79.0 "actn": 53.8 "purp": 25.0 "perc": 77.3 "cmdy": 65.0 , "name" : "<NAME>" "stats": "spos": 52.5 "alle": 36.4 "expr": 22.9 "pers": 57.1 "horn": 17.5 "fame": 38.1 "shwr": 28.8 "sani": 37.5 "rela": 67.9 "fedp": 56.5 "actn": 67.3 "purp": 37.5 "perc": 61.4 "cmdy": 52.5 , "name" : "<NAME>" "stats": "spos": 56.3 "alle": 43.8 "expr": 50.0 "pers": 87.5 "horn": 25.0 "fame": 25.0 "shwr": 68.8 "sani": 43.8 "rela": 55.0 "fedp": 0.0 "actn": 65.0 "purp": 56.3 "perc": 81.3 "cmdy": 37.5 , "name" : "<NAME>" "stats": "spos": 65.0 "alle": 63.6 "expr": 62.5 "pers": 94.6 "horn": 55.0 "fame": 28.6 "shwr": 36.5 "sani": 66.7 "rela": 75.0 "fedp": 4.8 "actn": 63.5 "purp": 68.8 "perc": 75.0 "cmdy": 72.5 , "name" : "<NAME>" "stats": "spos": 20.0 "alle": 93.2 "expr": 100.0 "pers": 16.1 "horn": 27.5 "fame": 47.6 "shwr": 69.2 "sani": 75.0 "rela": 73.2 "fedp": 90.3 "actn": 21.2 "purp": 25.0 "perc": 36.4 "cmdy": 82.5 , "name" : "<NAME>" "stats": "spos": 42.5 "alle": 6.8 "expr": 20.8 "pers": 64.3 "horn": 85.0 "fame": 35.7 "shwr": 44.2 "sani": 52.1 "rela": 66.1 "fedp": 22.6 "actn": 71.2 "purp": 41.7 "perc": 63.6 "cmdy": 75.0 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 70.5 "expr": 81.3 "pers": 51.8 "horn": 35.0 "fame": 44.0 "shwr": 84.6 "sani": 64.6 "rela": 66.1 "fedp": 44.4 "actn": 40.4 "purp": 39.6 "perc": 54.5 "cmdy": 65.0 , "name" : "Elitemagikarp" "stats": "spos": 27.5 "alle": 61.4 "expr": 89.6 "pers": 58.9 "horn": 17.5 "fame": 53.6 "shwr": 61.5 "sani": 52.1 "rela": 42.9 "fedp": 59.7 "actn": 42.3 "purp": 33.3 "perc": 40.9 "cmdy": 57.5 , "name" : "SomeCrusader1224" "stats": "spos": 37.5 "alle": 81.3 "expr": 25.0 "pers": 81.3 "horn": 18.8 "fame": 18.8 "shwr": 68.8 "sani": 62.5 "rela": 70.0 "fedp": 43.8 "actn": 75.0 "purp": 75.0 "perc": 25.0 "cmdy": 75.0 , "name" : "BE" "stats": "spos": 50.0 "alle": 70.5 "expr": 83.3 "pers": 76.8 "horn": 17.5 "fame": 36.9 "shwr": 48.1 "sani": 62.5 "rela": 33.9 "fedp": 53.2 "actn": 61.5 "purp": 81.3 "perc": 43.2 "cmdy": 75.0 , "name" : "<NAME>" "stats": "spos": 75.0 "alle": 75.0 "expr": 66.7 "pers": 56.3 "horn": 25.0 "fame": 18.8 "shwr": 25.0 "sani": 68.8 "rela": 50.0 "fedp": 37.5 "actn": 80.0 "purp": 18.8 "perc": 81.3 "cmdy": 56.3 , "name" : "<NAME>" "stats": "spos": 80.0 "alle": 50.0 "expr": 14.6 "pers": 53.6 "horn": 72.5 "fame": 13.1 "shwr": 32.7 "sani": 41.7 "rela": 50.0 "fedp": 3.2 "actn": 65.4 "purp": 52.1 "perc": 61.4 "cmdy": 30.0 , "name" : "<NAME>J<NAME>" "stats": "spos": 50.0 "alle": 75.0 "expr": 41.7 "pers": 0.0 "horn": 25.0 "fame": 0.0 "shwr": 75.0 "sani": 100.0 "rela": 65.0 "fedp": 50.0 "actn": 70.0 "purp": 37.5 "perc": 81.3 "cmdy": 56.3 , "name" : "<NAME>uno" "stats": "spos": 31.3 "alle": 81.3 "expr": 100.0 "pers": 18.8 "horn": 18.8 "fame": 68.8 "shwr": 62.5 "sani": 31.3 "rela": 65.0 "fedp": 87.5 "actn": 10.0 "purp": 0.0 "perc": 37.5 "cmdy": 81.3 , "name" : "afunhumaninter" "stats": "spos": 57.5 "alle": 36.4 "expr": 47.9 "pers": 46.4 "horn": 40.0 "fame": 38.1 "shwr": 38.5 "sani": 79.2 "rela": 66.1 "fedp": 58.1 "actn": 67.3 "purp": 33.3 "perc": 50.0 "cmdy": 40.0 , "name" : "SussyNuoh" "stats": "spos": 37.5 "alle": 75.0 "expr": 33.3 "pers": 68.8 "horn": 43.8 "fame": 25.0 "shwr": 75.0 "sani": 50.0 "rela": 90.0 "fedp": 43.8 "actn": 65.0 "purp": 31.3 "perc": 81.3 "cmdy": 81.3 , "name" : "astro200" "stats": "spos": 31.3 "alle": 56.3 "expr": 58.3 "pers": 68.8 "horn": 62.5 "fame": 50.0 "shwr": 62.5 "sani": 56.3 "rela": 65.0 "fedp": 37.5 "actn": 65.0 "purp": 18.8 "perc": 68.8 "cmdy": 31.3 , "name" : "Duck" "stats": "spos": 57.5 "alle": 36.4 "expr": 47.9 "pers": 46.4 "horn": 40.0 "fame": 38.1 "shwr": 38.5 "sani": 79.2 "rela": 66.1 "fedp": 58.1 "actn": 67.3 "purp": 33.3 "perc": 50.0 "cmdy": 40.0 , "name" : "BERNHE0504" "stats": "spos": 68.8 "alle": 37.5 "expr": 83.3 "pers": 18.8 "horn": 6.3 "fame": 43.8 "shwr": 25.0 "sani": 75.0 "rela": 75.0 "fedp": 68.8 "actn": 65.0 "purp": 62.5 "perc": 62.5 "cmdy": 87.5 , "name" : "<NAME>" "stats": "spos": 25.0 "alle": 37.5 "expr": 16.7 "pers": 81.3 "horn": 50.0 "fame": 25.0 "shwr": 75.0 "sani": 68.8 "rela": 75.0 "fedp": 0.0 "actn": 65.0 "purp": 50.0 "perc": 43.8 "cmdy": 43.8 , "name" : "<NAME>" "stats": "spos": 90.0 "alle": 0.0 "expr": 41.7 "pers": 50.0 "horn": 0.0 "fame": 19.0 "shwr": 23.1 "sani": 16.7 "rela": 0.0 "fedp": 6.5 "actn": 84.6 "purp": 66.7 "perc": 45.5 "cmdy": 10.0 , "name" : "<NAME> (Party Approved)" "stats": "spos": 100.0 "alle": 0.0 "expr": 41.7 "pers": 50.0 "horn": 0.0 "fame": 0.0 "shwr": 0 "sani": 0 "rela": 0.0 "fedp": 0 "actn": 100 "purp": 66.7 "perc": 100 "cmdy": 0.0 , "name" : "<NAME>" "stats": "spos": 77.5 "alle": 100.0 "expr": 20.8 "pers": 42.5 "horn": 82.5 "fame": 16.7 "shwr": 53.8 "sani": 60.4 "rela": 53.6 "fedp": 51.9 "actn": 32.3 "purp": 29.2 "perc": 72.7 "cmdy": 40.0 , "name" : "<NAME> <NAME>" "stats": "spos": 75.0 "alle": 100.0 "expr": 66.7 "pers": 25.0 "horn": 100.0 "fame": 50.0 "shwr": 0.0 "sani": 25.0 "rela": 55.0 "fedp": 50.0 "actn": 10.0 "purp": 56.3 "perc": 50.0 "cmdy": 25.0 , "name" : "<NAME>" "stats": "spos": 37.5 "alle": 50.0 "expr": 58.3 "pers": 68.8 "horn": 50.0 "fame": 43.8 "shwr": 56.3 "sani": 62.5 "rela": 35.0 "fedp": 25.0 "actn": 45.0 "purp": 43.8 "perc": 6.3 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 43.8 "alle": 93.8 "expr": 91.7 "pers": 0.0 "horn": 50.0 "fame": 56.3 "shwr": 18.8 "sani": 0.0 "rela": 35.0 "fedp": 68.8 "actn": 5.0 "purp": 0.0 "perc": 56.3 "cmdy": 56.3 , "name" : "<NAME>" "stats": "spos": 72.5 "alle": 22.7 "expr": 12.5 "pers": 76.8 "horn": 67.5 "fame": 11.9 "shwr": 36.5 "sani": 50.0 "rela": 44.6 "fedp": 40.3 "actn": 65.4 "purp": 33.3 "perc": 56.8 "cmdy": 30.0 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 84.1 "expr": 31.3 "pers": 30.4 "horn": 20.0 "fame": 53.6 "shwr": 30.8 "sani": 56.3 "rela": 42.9 "fedp": 95.2 "actn": 23.1 "purp": 35.4 "perc": 31.8 "cmdy": 47.5 , "name" : "<NAME>" "stats": "spos": 37.5 "alle": 79.5 "expr": 39.6 "pers": 75.0 "horn": 47.5 "fame": 32.1 "shwr": 40.4 "sani": 47.9 "rela": 48.2 "fedp": 38.7 "actn": 38.5 "purp": 35.4 "perc": 56.8 "cmdy": 77.5 , "name" : "<NAME>" "stats": "spos": 70.0 "alle": 31.8 "expr": 14.6 "pers": 76.8 "horn": 80.0 "fame": 16.7 "shwr": 26.9 "sani": 39.6 "rela": 48.2 "fedp": 1.6 "actn": 69.2 "purp": 22.9 "perc": 65.9 "cmdy": 30.0 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 84.1 "expr": 37.5 "pers": 32.1 "horn": 100.0 "fame": 54.8 "shwr": 30.8 "sani": 58.3 "rela": 80.4 "fedp": 25.8 "actn": 36.5 "purp": 81.3 "perc": 63.6 "cmdy": 82.5 , "name" : "<NAME>" "stats": "spos": 62.5 "alle": 68.8 "expr": 58.3 "pers": 81.3 "horn": 25.0 "fame": 50.0 "shwr": 43.8 "sani": 25.0 "rela": 60.0 "fedp": 50.0 "actn": 80.0 "purp": 37.5 "perc": 68.8 "cmdy": 43.8 , "name" : "<NAME>" "stats": "spos": 43.8 "alle": 6.3 "expr": 41.7 "pers": 75.0 "horn": 43.8 "fame": 25.0 "shwr": 68.8 "sani": 25.0 "rela": 55.0 "fedp": 0.0 "actn": 100.0 "purp": 18.8 "perc": 62.5 "cmdy": 50.0 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 56.3 "expr": 50.0 "pers": 37.5 "horn": 50.0 "fame": 31.3 "shwr": 43.8 "sani": 56.3 "rela": 50.0 "fedp": 37.5 "actn": 80.0 "purp": 43.8 "perc": 62.5 "cmdy": 31.3 , "name" : "<NAME>" "stats": "spos": 70.0 "alle": 56.8 "expr": 27.1 "pers": 73.2 "horn": 20.6 "fame": 25.0 "shwr": 7.7 "sani": 48.6 "rela": 50.0 "fedp": 70.2 "actn": 45.7 "purp": 62.5 "perc": 68.2 "cmdy": 45.0 , "name" : "<NAME>" "stats": "spos": 45.0 "alle": 22.7 "expr": 33.3 "pers": 42.9 "horn": 70.0 "fame": 38.1 "shwr": 30.8 "sani": 62.5 "rela": 55.4 "fedp": 88.7 "actn": 61.5 "purp": 52.1 "perc": 70.5 "cmdy": 45.0 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 50.0 "expr": 83.3 "pers": 50.0 "horn": 62.5 "fame": 68.8 "shwr": 37.5 "sani": 62.5 "rela": 55.0 "fedp": 6.3 "actn": 55.0 "purp": 56.3 "perc": 25.0 "cmdy": 37.5 , "name" : "<NAME>weenTe<NAME>" "stats": "spos": 67.5 "alle": 47.7 "expr": 29.2 "pers": 76.8 "horn": 62.5 "fame": 22.6 "shwr": 51.9 "sani": 52.1 "rela": 48.2 "fedp": 34.7 "actn": 61.5 "purp": 54.2 "perc": 72.7 "cmdy": 42.5 , "name" : "incredibledeadman" "stats": "spos": 62.5 "alle": 6.3 "expr": 58.3 "pers": 68.8 "horn": 37.5 "fame": 0.0 "shwr": 62.5 "sani": 75.0 "rela": 45.0 "fedp": 12.5 "actn": 90.0 "purp": 43.8 "perc": 56.3 "cmdy": 12.5 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 6.3 "expr": 41.7 "pers": 75.0 "horn": 62.5 "fame": 50.0 "shwr": 37.5 "sani": 37.5 "rela": 85.0 "fedp": 62.5 "actn": 80.0 "purp": 37.5 "perc": 75.0 "cmdy": 75.0 , "name" : "nyteulo" "stats": "spos": 22.5 "alle": 25.0 "expr": 22.9 "pers": 67.9 "horn": 32.5 "fame": 40.5 "shwr": 34.6 "sani": 77.1 "rela": 64.3 "fedp": 29.8 "actn": 67.3 "purp": 31.3 "perc": 72.7 "cmdy": 67.5 , "name" : "AquaHeart" "stats": "spos": 62.5 "alle": 25.0 "expr": 50.0 "pers": 93.8 "horn": 31.3 "fame": 0.0 "shwr": 62.5 "sani": 50.0 "rela": 75.0 "fedp": 6.3 "actn": 95.0 "purp": 43.8 "perc": 68.8 "cmdy": 18.8 , "name" : "Plant" "stats": "spos": 35.0 "alle": 79.5 "expr": 100.0 "pers": 58.9 "horn": 17.5 "fame": 65.5 "shwr": 63.5 "sani": 60.4 "rela": 73.2 "fedp": 57.3 "actn": 42.3 "purp": 16.7 "perc": 63.6 "cmdy": 65.0 , "name" : "Arunn" "stats": "spos": 35.0 "alle": 70.5 "expr": 81.3 "pers": 57.1 "horn": 12.5 "fame": 9.5 "shwr": 25.0 "sani": 70.8 "rela": 69.6 "fedp": 25.8 "actn": 61.5 "purp": 39.6 "perc": 63.6 "cmdy": 37.5 , "name" : "<NAME>" "stats": "spos": 42.5 "alle": 59.1 "expr": 27.1 "pers": 58.9 "horn": 15.0 "fame": 44.0 "shwr": 23.1 "sani": 45.8 "rela": 60.7 "fedp": 71.0 "actn": 57.7 "purp": 39.6 "perc": 38.6 "cmdy": 72.5 , "name" : "<NAME>" "stats": "spos": 95.0 "alle": 34.1 "expr": 25.0 "pers": 26.8 "horn": 27.5 "fame": 11.9 "shwr": 17.3 "sani": 70.8 "rela": 71.4 "fedp": 87.9 "actn": 67.3 "purp": 45.8 "perc": 65.9 "cmdy": 55.0 , "name" : "<NAME>Morth" "stats": "spos": 55.0 "alle": 93.2 "expr": 14.6 "pers": 12.5 "horn": 42.5 "fame": 17.9 "shwr": 34.6 "sani": 50.0 "rela": 57.1 "fedp": 91.9 "actn": 21.2 "purp": 18.8 "perc": 50.0 "cmdy": 50.0 , "name" : "<NAME>" "stats": "spos": 80.0 "alle": 47.7 "expr": 39.6 "pers": 75.0 "horn": 72.5 "fame": 45.2 "shwr": 46.2 "sani": 75.0 "rela": 85.7 "fedp": 17.7 "actn": 63.5 "purp": 70.8 "perc": 77.3 "cmdy": 67.5 , "name" : "<NAME>" "stats": "spos": 81.3 "alle": 18.8 "expr": 25.0 "pers": 100.0 "horn": 6.3 "fame": 31.3 "shwr": 37.5 "sani": 81.3 "rela": 75.0 "fedp": 37.5 "actn": 90.0 "purp": 25.0 "perc": 56.3 "cmdy": 75.0 , "name" : "<NAME>" "stats": "spos": 32.5 "alle": 97.7 "expr": 97.9 "pers": 44.6 "horn": 10.0 "fame": 40.5 "shwr": 75.0 "sani": 35.4 "rela": 37.5 "fedp": 58.9 "actn": 36.5 "purp": 16.7 "perc": 22.7 "cmdy": 25.0 , "name" : "firebender1234" "stats": "spos": 56.3 "alle": 75.0 "expr": 58.3 "pers": 75.0 "horn": 6.3 "fame": 50.0 "shwr": 25.0 "sani": 62.5 "rela": 45.0 "fedp": 87.5 "actn": 75.0 "purp": 31.3 "perc": 62.5 "cmdy": 100.0 , "name" : "Sarperen" "stats": "spos": 50.0 "alle": 43.8 "expr": 41.7 "pers": 75.0 "horn": 62.5 "fame": 6.3 "shwr": 81.3 "sani": 37.5 "rela": 70.0 "fedp": 6.3 "actn": 90.0 "purp": 31.3 "perc": 75.0 "cmdy": 43.8 , "name" : "SweatingCup2632" "stats": "spos": 40.0 "alle": 50.0 "expr": 75.0 "pers": 80.0 "horn": 0.0 "fame": 55.0 "shwr": 55.0 "sani": 85.0 "rela": 50.0 "fedp": 45.0 "actn": 90.0 "purp": 20.0 "perc": 60.0 "cmdy": 55.0 , "name" : "Antonio_1" "stats": "spos": 42.5 "alle": 54.5 "expr": 16.7 "pers": 55.4 "horn": 57.5 "fame": 14.3 "shwr": 30.8 "sani": 66.7 "rela": 64.3 "fedp": 39.5 "actn": 51.9 "purp": 43.8 "perc": 72.7 "cmdy": 60.0 , "name" : "<NAME>" "stats": "spos": 75.0 "alle": 63.6 "expr": 20.8 "pers": 73.2 "horn": 27.5 "fame": 26.2 "shwr": 28.8 "sani": 85.4 "rela": 53.6 "fedp": 19.4 "actn": 71.2 "purp": 39.6 "perc": 54.5 "cmdy": 47.5 , "name" : "<NAME>" "stats": "spos": 47.5 "alle": 43.2 "expr": 12.5 "pers": 32.1 "horn": 60.0 "fame": 19.0 "shwr": 7.7 "sani": 60.4 "rela": 42.9 "fedp": 58.1 "actn": 48.1 "purp": 62.5 "perc": 56.8 "cmdy": 37.5 , "name" : "<NAME>" "stats": "spos": 56.3 "alle": 25.0 "expr": 50.0 "pers": 81.3 "horn": 0.0 "fame": 0.0 "shwr": 25.0 "sani": 87.5 "rela": 90.0 "fedp": 43.8 "actn": 95.0 "purp": 56.3 "perc": 87.5 "cmdy": 37.5 , "name" : "<NAME>" "stats": "spos": 56.3 "alle": 12.5 "expr": 41.7 "pers": 68.8 "horn": 12.5 "fame": 37.5 "shwr": 62.5 "sani": 62.5 "rela": 75.0 "fedp": 0.0 "actn": 90.0 "purp": 18.8 "perc": 75.0 "cmdy": 62.5 , "name" : "<NAME>" "stats": "spos": 50.0 "alle": 100.0 "expr": 8.3 "pers": 37.5 "horn": 100.0 "fame": 43.8 "shwr": 0.0 "sani": 25.0 "rela": 100.0 "fedp": 18.8 "actn": 60.0 "purp": 0.0 "perc": 75.0 "cmdy": 50.0 , "name" : "<NAME>" "stats": "spos": 68.8 "alle": 43.8 "expr": 58.3 "pers": 68.8 "horn": 81.3 "fame": 62.5 "shwr": 0.0 "sani": 56.3 "rela": 70.0 "fedp": 43.8 "actn": 75.0 "purp": 37.5 "perc": 62.5 "cmdy": 62.5 , "name" : "ThisIsMyUsernameAAA" "stats": "spos": 37.5 "alle": 100.0 "expr": 83.3 "pers": 100.0 "horn": 56.3 "fame": 100.0 "shwr": 12.5 "sani": 43.8 "rela": 65.0 "fedp": 18.8 "actn": 10.0 "purp": 0.0 "perc": 12.5 "cmdy": 37.5 , "name" : "<NAME>" "stats": "spos": 80.0 "alle": 27.3 "expr": 62.5 "pers": 89.3 "horn": 7.5 "fame": 75.0 "shwr": 38.5 "sani": 85.4 "rela": 96.4 "fedp": 51.6 "actn": 80.8 "purp": 56.3 "perc": 72.7 "cmdy": 62.5 , "name" : "AmericanFascist" "stats": "spos": 81.3 "alle": 43.8 "expr": 58.3 "pers": 56.3 "horn": 12.5 "fame": 62.5 "shwr": 25.0 "sani": 81.3 "rela": 65.0 "fedp": 62.5 "actn": 80.0 "purp": 18.8 "perc": 56.3 "cmdy": 81.3 ]
true
[ "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 73.5 "alle": 70.0 "expr": 66.7 "pers": 75.0 "horn": 8.3 "fame": 59.0 "shwr": 43.5 "sani": 79.3 "rela": 73.9 "fedp": 60.7 "actn": 52.6 "purp": 78.9 "perc": 73.3 "cmdy": 79.7 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 65.0 "alle": 33.2 "expr": 56.9 "pers": 77.4 "horn": 71.7 "fame": 83.5 "shwr": 43.6 "sani": 65.3 "rela": 73.8 "fedp": 6.0 "actn": 69.3 "purp": 71.2 "perc": 76.7 "cmdy": 61.2 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 42.5 "alle": 79.5 "expr": 91.7 "pers": 1.8 "horn": 10.0 "fame": 73.8 "shwr": 48.1 "sani": 27.1 "rela": 80.4 "fedp": 100.0 "actn": 17.3 "purp": 22.9 "perc": 38.6 "cmdy": 97.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 56.8 "alle": 91.7 "expr": 34.8 "pers": 42.9 "horn": 33.3 "fame": 27.2 "shwr": 30.7 "sani": 48.7 "rela": 44.1 "fedp": 81.0 "actn": 40.9 "purp": 34.9 "perc": 51.8 "cmdy": 40.8 , "name" : "ItsDanny101" "stats": "spos": 45.8 "alle": 54.1 "expr": 77.8 "pers": 79.1 "horn": 0.0 "fame": 79.3 "shwr": 58.4 "sani": 54.1 "rela": 79.3 "fedp": 54.0 "actn": 70.1 "purp": 8.3 "perc": 66.6 "cmdy": 75.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 55.0 "alle": 53.3 "expr": 94.5 "pers": 57.2 "horn": 76.7 "fame": 83.3 "shwr": 39.8 "sani": 65.3 "rela": 86.9 "fedp": 51.2 "actn": 64.1 "purp": 71.2 "perc": 48.4 "cmdy": 79.6 , "name" : "PI:NAME:<NAME>END_PIelSmPI:NAME:<NAME>END_PI" "stats": "spos": 70.0 "alle": 45.0 "expr": 33.3 "pers": 64.3 "horn": 40.0 "fame": 57.5 "shwr": 47.4 "sani": 70.9 "rela": 51.2 "fedp": 28.5 "actn": 71.8 "purp": 51.5 "perc": 50.0 "cmdy": 57.4 , "name" : "EugeneTLT" "stats": "spos": 33.4 "alle": 37.5 "expr": 55.5 "pers": 79.3 "horn": 8.4 "fame": 20.8 "shwr": 66.8 "sani": 45.8 "rela": 70.8 "fedp": 37.6 "actn": 66.8 "purp": 58.4 "perc": 71.0 "cmdy": 45.8 , "name" : "Froggers" "stats": "spos": 41.6 "alle": 50.0 "expr": 61.2 "pers": 60.8 "horn": 35.0 "fame": 77.4 "shwr": 65.3 "sani": 44.5 "rela": 88.2 "fedp": 60.7 "actn": 43.7 "purp": 45.5 "perc": 75.1 "cmdy": 81.6 , "name" : "Beeper" "stats": "spos": 37.5 "alle": 79.3 "expr": 61.2 "pers": 79.3 "horn": 41.6 "fame": 45.8 "shwr": 37.4 "sani": 75.1 "rela": 66.8 "fedp": 75.0 "actn": 70.1 "purp": 83.4 "perc": 54.1 "cmdy": 58.4 , "name" : "wasp_" "stats": "spos": 58.4 "alle": 33.4 "expr": 89.0 "pers": 50.0 "horn": 70.8 "fame": 79.3 "shwr": 83.4 "sani": 54.3 "rela": 54.3 "fedp": 25.0 "actn": 66.7 "purp": 54.1 "perc": 54.1 "cmdy": 45.9 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 66.7 "alle": 78.4 "expr": 62.5 "pers": 32.2 "horn": 88.3 "fame": 68.2 "shwr": 19.2 "sani": 23.6 "rela": 8.3 "fedp": 46.4 "actn": 17.9 "purp": 36.3 "perc": 35.0 "cmdy": 77.8 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 23.2 "alle": 31.6 "expr": 23.5 "pers": 81.0 "horn": 61.7 "fame": 66.8 "shwr": 50.0 "sani": 62.5 "rela": 41.7 "fedp": 5.9 "actn": 79.6 "purp": 39.4 "perc": 41.8 "cmdy": 25.8 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 86.7 "alle": 12.7 "expr": 86.2 "pers": 83.6 "horn": 46.3 "fame": 84.8 "shwr": 53.8 "sani": 55.9 "rela": 67.1 "fedp": 12.2 "actn": 82.7 "purp": 88.0 "perc": 65.6 "cmdy": 50.1 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 38.6 "expr": 37.5 "pers": 76.8 "horn": 30.0 "fame": 64.3 "shwr": 50.0 "sani": 72.9 "rela": 78.6 "fedp": 14.5 "actn": 71.2 "purp": 18.8 "perc": 88.6 "cmdy": 57.5 , "name" : "chicken piccata" "stats": "spos": 67.5 "alle": 22.7 "expr": 8.3 "pers": 89.3 "horn": 22.5 "fame": 57.1 "shwr": 71.2 "sani": 75.0 "rela": 75.0 "fedp": 20.2 "actn": 84.6 "purp": 50.0 "perc": 75.0 "cmdy": 15.0 , "name" : "YourLocalDegenerateMao" "stats": "spos": 55.0 "alle": 56.6 "expr": 38.9 "pers": 82.3 "horn": 51.6 "fame": 65.2 "shwr": 57.7 "sani": 61.1 "rela": 73.9 "fedp": 22.6 "actn": 74.3 "purp": 36.3 "perc": 73.3 "cmdy": 55.6 , "name" : "bowie" "stats": "spos": 50.0 "alle": 50.0 "expr": 33.3 "pers": 35.7 "horn": 52.5 "fame": 65.5 "shwr": 48.1 "sani": 52.1 "rela": 62.5 "fedp": 33.1 "actn": 51.9 "purp": 33.3 "perc": 63.6 "cmdy": 65.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 65.0 "alle": 83.5 "expr": 83.4 "pers": 41.6 "horn": 60.0 "fame": 34.7 "shwr": 53.9 "sani": 55.6 "rela": 53.6 "fedp": 35.6 "actn": 48.7 "purp": 34.9 "perc": 58.3 "cmdy": 37.1 , "name" : "Rayz9989" "stats": "spos": 65.0 "alle": 20.5 "expr": 27.1 "pers": 100.0 "horn": 67.5 "fame": 100.0 "shwr": 5.8 "sani": 75.0 "rela": 60.7 "fedp": 12.9 "actn": 84.6 "purp": 37.5 "perc": 37.5 "cmdy": 75.0 , "name" : "Swoosho" "stats": "spos": 56.7 "alle": 62.5 "expr": 65.2 "pers": 56.2 "horn": 100.0 "fame": 68.8 "shwr": 77.8 "sani": 38.9 "rela": 75.0 "fedp": 31.3 "actn": 43.2 "purp": 37.5 "perc": 75.0 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 56.3 "alle": 100.0 "expr": 41.7 "pers": 100.0 "horn": 100.0 "fame": 93.8 "shwr": 0.0 "sani": 31.3 "rela": 62.5 "fedp": 0.0 "actn": 55.0 "purp": 18.8 "perc": 0.0 "cmdy": 31.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 35.0 "alle": 50.0 "expr": 25.0 "pers": 48.2 "horn": 70.0 "fame": 47.7 "shwr": 65.4 "sani": 37.5 "rela": 25.0 "fedp": 42.9 "actn": 59.6 "purp": 34.1 "perc": 40.0 "cmdy": 30.6 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 87.5 "alle": 100.0 "expr": 66.7 "pers": 56.3 "horn": 25.0 "fame": 100.0 "shwr": 6.3 "sani": 25.0 "rela": 0.0 "fedp": 75.0 "actn": 0.0 "purp": 56.3 "perc": 0.0 "cmdy": 25.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 100.0 "alle": 100.0 "expr": 25.0 "pers": 56.3 "horn": 75.0 "fame": 6.3 "shwr": 6.3 "sani": 43.7 "rela": 0.0 "fedp": 25.0 "actn": 56.3 "purp": 93.7 "perc": 25.0 "cmdy": 0.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 67.5 "alle": 100.0 "expr": 100.0 "pers": 50.0 "horn": 32.5 "fame": 40.9 "shwr": 44.2 "sani": 60.4 "rela": 71.4 "fedp": 78.6 "actn": 28.8 "purp": 18.2 "perc": 45.0 "cmdy": 66.7 , "name" : "ThatoneguyG" "stats": "spos": 50.0 "alle": 100.0 "expr": 33.3 "pers": 100.0 "horn": 100.0 "fame": 0.0 "shwr": 0.0 "sani": 93.8 "rela": 68.8 "fedp": 18.8 "actn": 45.0 "purp": 31.3 "perc": 50.0 "cmdy": 62.5 , "name" : "märkl" "stats": "spos": 37.5 "alle": 25.0 "expr": 33.3 "pers": 62.5 "horn": 62.5 "fame": 25.0 "shwr": 50.0 "sani": 75.0 "rela": 75.0 "fedp": 25.0 "actn": 75.0 "purp": 50.0 "perc": 62.5 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 12.5 "alle": 100.0 "expr": 100.0 "pers": 12.5 "horn": 0 "fame": 68.8 "shwr": 75.0 "sani": 75.0 "rela": 50.0 "fedp": 93.8 "actn": 40.0 "purp": 0.0 "perc": 68.8 "cmdy": 93.8 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 15.0 "alle": 84.1 "expr": 100.0 "pers": 66.1 "horn": 12.5 "fame": 48.8 "shwr": 76.9 "sani": 56.3 "rela": 58.9 "fedp": 59.7 "actn": 46.2 "purp": 20.8 "perc": 59.1 "cmdy": 67.5 , "name" : "Padstar34" "stats": "spos": 37.5 "alle": 68.8 "expr": 33.3 "pers": 81.3 "horn": 50.0 "fame": 56.3 "shwr": 25.0 "sani": 62.5 "rela": 55.0 "fedp": 0.0 "actn": 70.0 "purp": 31.3 "perc": 31.3 "cmdy": 68.8 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 79.5 "expr": 20.8 "pers": 33.9 "horn": 72.5 "fame": 42.9 "shwr": 25.0 "sani": 47.9 "rela": 64.3 "fedp": 46.0 "actn": 46.2 "purp": 33.3 "perc": 56.8 "cmdy": 65.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 37.5 "alle": 68.8 "expr": 58.3 "pers": 18.8 "horn": 31.3 "fame": 56.3 "shwr": 93.8 "sani": 68.8 "rela": 65.0 "fedp": 81.3 "actn": 35.0 "purp": 93.8 "perc": 43.8 "cmdy": 43.8 , "name" : "PI:NAME:<NAME>END_PI " "stats": "spos": 37.5 "alle": 56.3 "expr": 75.0 "pers": 68.8 "horn": 18.8 "fame": 0.0 "shwr": 68.8 "sani": 62.5 "rela": 50.0 "fedp": 31.3 "actn": 60.0 "purp": 50.0 "perc": 62.5 "cmdy": 50.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 92.5 "alle": 54.5 "expr": 41.7 "pers": 71.4 "horn": 70.0 "fame": 29.8 "shwr": 21.2 "sani": 39.6 "rela": 67.9 "fedp": 19.4 "actn": 51.9 "purp": 45.8 "perc": 59.1 "cmdy": 30.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 52.5 "alle": 54.5 "expr": 27.1 "pers": 33.9 "horn": 35.0 "fame": 53.6 "shwr": 63.5 "sani": 43.8 "rela": 51.8 "fedp": 71.0 "actn": 51.9 "purp": 56.3 "perc": 50.0 "cmdy": 50.0 , "name" : "IncendiaryBullet" "stats": "spos": 25.0 "alle": 86.4 "expr": 97.9 "pers": 35.7 "horn": 25.0 "fame": 67.9 "shwr": 44.2 "sani": 66.7 "rela": 55.4 "fedp": 95.2 "actn": 26.9 "purp": 54.2 "perc": 29.5 "cmdy": 87.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 75.0 "alle": 18.8 "expr": 58.3 "pers": 93.8 "horn": 50.0 "fame": 6.3 "shwr": 75.0 "sani": 56.3 "rela": 80.0 "fedp": 18.8 "actn": 90.0 "purp": 31.3 "perc": 68.8 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 17.5 "alle": 57.3 "expr": 90.9 "pers": 46.4 "horn": 2.5 "fame": 60.7 "shwr": 88.5 "sani": 79.2 "rela": 75.4 "fedp": 47.6 "actn": 65.8 "purp": 4.6 "perc": 84.1 "cmdy": 77.5 , "name" : "The Infinity Pizza" "stats": "spos": 50.0 "alle": 65.9 "expr": 31.3 "pers": 46.4 "horn": 62.5 "fame": 31.0 "shwr": 69.2 "sani": 60.4 "rela": 66.1 "fedp": 32.3 "actn": 59.6 "purp": 54.2 "perc": 59.1 "cmdy": 55.0 , "name" : "PastaGuy27" "stats": "spos": 56.3 "alle": 81.3 "expr": 75.0 "pers": 43.8 "horn": 37.5 "fame": 6.3 "shwr": 62.5 "sani": 75.0 "rela": 55.0 "fedp": 18.8 "actn": 85.0 "purp": 31.3 "perc": 62.5 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 90.0 "alle": 22.7 "expr": 0.0 "pers": 66.1 "horn": 5.0 "fame": 11.9 "shwr": 19.2 "sani": 39.6 "rela": 51.8 "fedp": 32.3 "actn": 50.0 "purp": 58.3 "perc": 25.0 "cmdy": 25.0 , "name" : "PI:NAME:<NAME>END_PI." "stats": "spos": 55.0 "alle": 45.5 "expr": 20.8 "pers": 71.4 "horn": 57.5 "fame": 14.3 "shwr": 38.5 "sani": 77.1 "rela": 44.6 "fedp": 54.8 "actn": 80.8 "purp": 25.0 "perc": 61.4 "cmdy": 57.5 , "name" : "antichristhater" "stats": "spos": 56.3 "alle": 68.8 "expr": 33.3 "pers": 37.5 "horn": 6.3 "fame": 50.0 "shwr": 75.0 "sani": 81.3 "rela": 65.0 "fedp": 50.0 "actn": 75.0 "purp": 12.5 "perc": 43.8 "cmdy": 75.0 , "name" : "oRange" "stats": "spos": 52.5 "alle": 56.8 "expr": 83.3 "pers": 66.1 "horn": 30.0 "fame": 72.6 "shwr": 42.3 "sani": 60.4 "rela": 82.1 "fedp": 43.5 "actn": 55.8 "purp": 64.6 "perc": 81.8 "cmdy": 87.5 , "name" : "Leo9" "stats": "spos": 55.0 "alle": 81.8 "expr": 29.2 "pers": 64.3 "horn": 62.5 "fame": 13.1 "shwr": 21.2 "sani": 47.9 "rela": 57.1 "fedp": 8.1 "actn": 48.1 "purp": 58.3 "perc": 65.9 "cmdy": 45.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 68.8 "alle": 50.0 "expr": 58.3 "pers": 68.8 "horn": 62.5 "fame": 6.3 "shwr": 68.8 "sani": 56.3 "rela": 45.0 "fedp": 18.8 "actn": 95.0 "purp": 50.0 "perc": 68.8 "cmdy": 31.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 37.5 "alle": 97.7 "expr": 55.4 "pers": 35.4 "horn": 0 "fame": 60.7 "shwr": 42.3 "sani": 59.6 "rela": 43.6 "fedp": 82.3 "actn": 34.6 "purp": 22.9 "perc": 25.0 "cmdy": 85.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 81.3 "expr": 66.7 "pers": 75.0 "horn": 68.8 "fame": 37.5 "shwr": 18.8 "sani": 62.5 "rela": 40.0 "fedp": 6.3 "actn": 60.0 "purp": 18.8 "perc": 56.3 "cmdy": 56.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 88.6 "expr": 41.7 "pers": 69.6 "horn": 32.5 "fame": 63.1 "shwr": 67.3 "sani": 58.3 "rela": 75.0 "fedp": 39.5 "actn": 38.5 "purp": 43.8 "perc": 65.9 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 60.0 "alle": 45.5 "expr": 25.0 "pers": 41.1 "horn": 60.0 "fame": 57.1 "shwr": 46.2 "sani": 54.2 "rela": 41.1 "fedp": 37.1 "actn": 57.7 "purp": 43.8 "perc": 56.8 "cmdy": 45.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 68.8 "alle": 62.5 "expr": 58.3 "pers": 81.3 "horn": 93.8 "fame": 50.0 "shwr": 31.3 "sani": 68.8 "rela": 55.0 "fedp": 31.3 "actn": 80.0 "purp": 68.8 "perc": 37.5 "cmdy": 50.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 55.0 "alle": 81.8 "expr": 39.6 "pers": 50.0 "horn": 80.0 "fame": 58.3 "shwr": 42.3 "sani": 54.2 "rela": 55.4 "fedp": 52.4 "actn": 26.9 "purp": 50.0 "perc": 29.5 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 43.8 "alle": 56.3 "expr": 50.0 "pers": 37.5 "horn": 43.8 "fame": 12.5 "shwr": 12.5 "sani": 43.8 "rela": 75.0 "fedp": 25.0 "actn": 80.0 "purp": 25.0 "perc": 68.8 "cmdy": 37.5 , "name" : "TheGhostOfInky" "stats": "spos": 92.5 "alle": 9.1 "expr": 66.7 "pers": 82.1 "horn": 67.5 "fame": 94.0 "shwr": 28.8 "sani": 70.8 "rela": 44.6 "fedp": 6.5 "actn": 82.7 "purp": 85.4 "perc": 50.0 "cmdy": 57.5 , "name" : "PI:NAME:<NAME>END_PIion" "stats": "spos": 25.0 "alle": 12.5 "expr": 25.0 "pers": 87.5 "horn": 6.3 "fame": 62.5 "shwr": 75.0 "sani": 62.5 "rela": 45.0 "fedp": 12.5 "actn": 45.0 "purp": 43.8 "perc": 31.3 "cmdy": 56.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 7.5 "alle": 95.5 "expr": 95.8 "pers": 7.1 "horn": 55.0 "fame": 67.9 "shwr": 84.6 "sani": 43.8 "rela": 62.5 "fedp": 75.8 "actn": 19.2 "purp": 22.9 "perc": 38.6 "cmdy": 82.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 90.0 "alle": 100.0 "expr": 25.0 "pers": 37.5 "horn": 75.0 "fame": 70.2 "shwr": 23.1 "sani": 22.9 "rela": 33.9 "fedp": 21.0 "actn": 40.4 "purp": 33.3 "perc": 22.7 "cmdy": 30.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 59.1 "expr": 18.8 "pers": 60.7 "horn": 60.0 "fame": 23.8 "shwr": 44.2 "sani": 50.0 "rela": 39.3 "fedp": 25.0 "actn": 65.4 "purp": 29.2 "perc": 52.3 "cmdy": 15.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 100.0 "alle": 62.5 "expr": 8.3 "pers": 31.3 "horn": 75.0 "fame": 87.5 "shwr": 0.0 "sani": 6.3 "rela": 20.0 "fedp": 87.5 "actn": 40.0 "purp": 25.0 "perc": 0.0 "cmdy": 12.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 60.0 "alle": 38.6 "expr": 43.8 "pers": 89.3 "horn": 20.0 "fame": 47.6 "shwr": 36.5 "sani": 47.9 "rela": 85.7 "fedp": 30.6 "actn": 82.7 "purp": 35.4 "perc": 90.9 "cmdy": 75.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 90.9 "expr": 22.9 "pers": 23.2 "horn": 7.5 "fame": 14.3 "shwr": 15.4 "sani": 56.3 "rela": 48.2 "fedp": 79.0 "actn": 53.8 "purp": 25.0 "perc": 77.3 "cmdy": 65.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 52.5 "alle": 36.4 "expr": 22.9 "pers": 57.1 "horn": 17.5 "fame": 38.1 "shwr": 28.8 "sani": 37.5 "rela": 67.9 "fedp": 56.5 "actn": 67.3 "purp": 37.5 "perc": 61.4 "cmdy": 52.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 56.3 "alle": 43.8 "expr": 50.0 "pers": 87.5 "horn": 25.0 "fame": 25.0 "shwr": 68.8 "sani": 43.8 "rela": 55.0 "fedp": 0.0 "actn": 65.0 "purp": 56.3 "perc": 81.3 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 65.0 "alle": 63.6 "expr": 62.5 "pers": 94.6 "horn": 55.0 "fame": 28.6 "shwr": 36.5 "sani": 66.7 "rela": 75.0 "fedp": 4.8 "actn": 63.5 "purp": 68.8 "perc": 75.0 "cmdy": 72.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 20.0 "alle": 93.2 "expr": 100.0 "pers": 16.1 "horn": 27.5 "fame": 47.6 "shwr": 69.2 "sani": 75.0 "rela": 73.2 "fedp": 90.3 "actn": 21.2 "purp": 25.0 "perc": 36.4 "cmdy": 82.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 42.5 "alle": 6.8 "expr": 20.8 "pers": 64.3 "horn": 85.0 "fame": 35.7 "shwr": 44.2 "sani": 52.1 "rela": 66.1 "fedp": 22.6 "actn": 71.2 "purp": 41.7 "perc": 63.6 "cmdy": 75.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 70.5 "expr": 81.3 "pers": 51.8 "horn": 35.0 "fame": 44.0 "shwr": 84.6 "sani": 64.6 "rela": 66.1 "fedp": 44.4 "actn": 40.4 "purp": 39.6 "perc": 54.5 "cmdy": 65.0 , "name" : "Elitemagikarp" "stats": "spos": 27.5 "alle": 61.4 "expr": 89.6 "pers": 58.9 "horn": 17.5 "fame": 53.6 "shwr": 61.5 "sani": 52.1 "rela": 42.9 "fedp": 59.7 "actn": 42.3 "purp": 33.3 "perc": 40.9 "cmdy": 57.5 , "name" : "SomeCrusader1224" "stats": "spos": 37.5 "alle": 81.3 "expr": 25.0 "pers": 81.3 "horn": 18.8 "fame": 18.8 "shwr": 68.8 "sani": 62.5 "rela": 70.0 "fedp": 43.8 "actn": 75.0 "purp": 75.0 "perc": 25.0 "cmdy": 75.0 , "name" : "BE" "stats": "spos": 50.0 "alle": 70.5 "expr": 83.3 "pers": 76.8 "horn": 17.5 "fame": 36.9 "shwr": 48.1 "sani": 62.5 "rela": 33.9 "fedp": 53.2 "actn": 61.5 "purp": 81.3 "perc": 43.2 "cmdy": 75.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 75.0 "alle": 75.0 "expr": 66.7 "pers": 56.3 "horn": 25.0 "fame": 18.8 "shwr": 25.0 "sani": 68.8 "rela": 50.0 "fedp": 37.5 "actn": 80.0 "purp": 18.8 "perc": 81.3 "cmdy": 56.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 80.0 "alle": 50.0 "expr": 14.6 "pers": 53.6 "horn": 72.5 "fame": 13.1 "shwr": 32.7 "sani": 41.7 "rela": 50.0 "fedp": 3.2 "actn": 65.4 "purp": 52.1 "perc": 61.4 "cmdy": 30.0 , "name" : "PI:NAME:<NAME>END_PIJPI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 75.0 "expr": 41.7 "pers": 0.0 "horn": 25.0 "fame": 0.0 "shwr": 75.0 "sani": 100.0 "rela": 65.0 "fedp": 50.0 "actn": 70.0 "purp": 37.5 "perc": 81.3 "cmdy": 56.3 , "name" : "PI:NAME:<NAME>END_PIuno" "stats": "spos": 31.3 "alle": 81.3 "expr": 100.0 "pers": 18.8 "horn": 18.8 "fame": 68.8 "shwr": 62.5 "sani": 31.3 "rela": 65.0 "fedp": 87.5 "actn": 10.0 "purp": 0.0 "perc": 37.5 "cmdy": 81.3 , "name" : "afunhumaninter" "stats": "spos": 57.5 "alle": 36.4 "expr": 47.9 "pers": 46.4 "horn": 40.0 "fame": 38.1 "shwr": 38.5 "sani": 79.2 "rela": 66.1 "fedp": 58.1 "actn": 67.3 "purp": 33.3 "perc": 50.0 "cmdy": 40.0 , "name" : "SussyNuoh" "stats": "spos": 37.5 "alle": 75.0 "expr": 33.3 "pers": 68.8 "horn": 43.8 "fame": 25.0 "shwr": 75.0 "sani": 50.0 "rela": 90.0 "fedp": 43.8 "actn": 65.0 "purp": 31.3 "perc": 81.3 "cmdy": 81.3 , "name" : "astro200" "stats": "spos": 31.3 "alle": 56.3 "expr": 58.3 "pers": 68.8 "horn": 62.5 "fame": 50.0 "shwr": 62.5 "sani": 56.3 "rela": 65.0 "fedp": 37.5 "actn": 65.0 "purp": 18.8 "perc": 68.8 "cmdy": 31.3 , "name" : "Duck" "stats": "spos": 57.5 "alle": 36.4 "expr": 47.9 "pers": 46.4 "horn": 40.0 "fame": 38.1 "shwr": 38.5 "sani": 79.2 "rela": 66.1 "fedp": 58.1 "actn": 67.3 "purp": 33.3 "perc": 50.0 "cmdy": 40.0 , "name" : "BERNHE0504" "stats": "spos": 68.8 "alle": 37.5 "expr": 83.3 "pers": 18.8 "horn": 6.3 "fame": 43.8 "shwr": 25.0 "sani": 75.0 "rela": 75.0 "fedp": 68.8 "actn": 65.0 "purp": 62.5 "perc": 62.5 "cmdy": 87.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 25.0 "alle": 37.5 "expr": 16.7 "pers": 81.3 "horn": 50.0 "fame": 25.0 "shwr": 75.0 "sani": 68.8 "rela": 75.0 "fedp": 0.0 "actn": 65.0 "purp": 50.0 "perc": 43.8 "cmdy": 43.8 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 90.0 "alle": 0.0 "expr": 41.7 "pers": 50.0 "horn": 0.0 "fame": 19.0 "shwr": 23.1 "sani": 16.7 "rela": 0.0 "fedp": 6.5 "actn": 84.6 "purp": 66.7 "perc": 45.5 "cmdy": 10.0 , "name" : "PI:NAME:<NAME>END_PI (Party Approved)" "stats": "spos": 100.0 "alle": 0.0 "expr": 41.7 "pers": 50.0 "horn": 0.0 "fame": 0.0 "shwr": 0 "sani": 0 "rela": 0.0 "fedp": 0 "actn": 100 "purp": 66.7 "perc": 100 "cmdy": 0.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 77.5 "alle": 100.0 "expr": 20.8 "pers": 42.5 "horn": 82.5 "fame": 16.7 "shwr": 53.8 "sani": 60.4 "rela": 53.6 "fedp": 51.9 "actn": 32.3 "purp": 29.2 "perc": 72.7 "cmdy": 40.0 , "name" : "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" "stats": "spos": 75.0 "alle": 100.0 "expr": 66.7 "pers": 25.0 "horn": 100.0 "fame": 50.0 "shwr": 0.0 "sani": 25.0 "rela": 55.0 "fedp": 50.0 "actn": 10.0 "purp": 56.3 "perc": 50.0 "cmdy": 25.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 37.5 "alle": 50.0 "expr": 58.3 "pers": 68.8 "horn": 50.0 "fame": 43.8 "shwr": 56.3 "sani": 62.5 "rela": 35.0 "fedp": 25.0 "actn": 45.0 "purp": 43.8 "perc": 6.3 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 43.8 "alle": 93.8 "expr": 91.7 "pers": 0.0 "horn": 50.0 "fame": 56.3 "shwr": 18.8 "sani": 0.0 "rela": 35.0 "fedp": 68.8 "actn": 5.0 "purp": 0.0 "perc": 56.3 "cmdy": 56.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 72.5 "alle": 22.7 "expr": 12.5 "pers": 76.8 "horn": 67.5 "fame": 11.9 "shwr": 36.5 "sani": 50.0 "rela": 44.6 "fedp": 40.3 "actn": 65.4 "purp": 33.3 "perc": 56.8 "cmdy": 30.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 84.1 "expr": 31.3 "pers": 30.4 "horn": 20.0 "fame": 53.6 "shwr": 30.8 "sani": 56.3 "rela": 42.9 "fedp": 95.2 "actn": 23.1 "purp": 35.4 "perc": 31.8 "cmdy": 47.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 37.5 "alle": 79.5 "expr": 39.6 "pers": 75.0 "horn": 47.5 "fame": 32.1 "shwr": 40.4 "sani": 47.9 "rela": 48.2 "fedp": 38.7 "actn": 38.5 "purp": 35.4 "perc": 56.8 "cmdy": 77.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 70.0 "alle": 31.8 "expr": 14.6 "pers": 76.8 "horn": 80.0 "fame": 16.7 "shwr": 26.9 "sani": 39.6 "rela": 48.2 "fedp": 1.6 "actn": 69.2 "purp": 22.9 "perc": 65.9 "cmdy": 30.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 84.1 "expr": 37.5 "pers": 32.1 "horn": 100.0 "fame": 54.8 "shwr": 30.8 "sani": 58.3 "rela": 80.4 "fedp": 25.8 "actn": 36.5 "purp": 81.3 "perc": 63.6 "cmdy": 82.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 62.5 "alle": 68.8 "expr": 58.3 "pers": 81.3 "horn": 25.0 "fame": 50.0 "shwr": 43.8 "sani": 25.0 "rela": 60.0 "fedp": 50.0 "actn": 80.0 "purp": 37.5 "perc": 68.8 "cmdy": 43.8 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 43.8 "alle": 6.3 "expr": 41.7 "pers": 75.0 "horn": 43.8 "fame": 25.0 "shwr": 68.8 "sani": 25.0 "rela": 55.0 "fedp": 0.0 "actn": 100.0 "purp": 18.8 "perc": 62.5 "cmdy": 50.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 56.3 "expr": 50.0 "pers": 37.5 "horn": 50.0 "fame": 31.3 "shwr": 43.8 "sani": 56.3 "rela": 50.0 "fedp": 37.5 "actn": 80.0 "purp": 43.8 "perc": 62.5 "cmdy": 31.3 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 70.0 "alle": 56.8 "expr": 27.1 "pers": 73.2 "horn": 20.6 "fame": 25.0 "shwr": 7.7 "sani": 48.6 "rela": 50.0 "fedp": 70.2 "actn": 45.7 "purp": 62.5 "perc": 68.2 "cmdy": 45.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 45.0 "alle": 22.7 "expr": 33.3 "pers": 42.9 "horn": 70.0 "fame": 38.1 "shwr": 30.8 "sani": 62.5 "rela": 55.4 "fedp": 88.7 "actn": 61.5 "purp": 52.1 "perc": 70.5 "cmdy": 45.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 50.0 "expr": 83.3 "pers": 50.0 "horn": 62.5 "fame": 68.8 "shwr": 37.5 "sani": 62.5 "rela": 55.0 "fedp": 6.3 "actn": 55.0 "purp": 56.3 "perc": 25.0 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PIweenTePI:NAME:<NAME>END_PI" "stats": "spos": 67.5 "alle": 47.7 "expr": 29.2 "pers": 76.8 "horn": 62.5 "fame": 22.6 "shwr": 51.9 "sani": 52.1 "rela": 48.2 "fedp": 34.7 "actn": 61.5 "purp": 54.2 "perc": 72.7 "cmdy": 42.5 , "name" : "incredibledeadman" "stats": "spos": 62.5 "alle": 6.3 "expr": 58.3 "pers": 68.8 "horn": 37.5 "fame": 0.0 "shwr": 62.5 "sani": 75.0 "rela": 45.0 "fedp": 12.5 "actn": 90.0 "purp": 43.8 "perc": 56.3 "cmdy": 12.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 6.3 "expr": 41.7 "pers": 75.0 "horn": 62.5 "fame": 50.0 "shwr": 37.5 "sani": 37.5 "rela": 85.0 "fedp": 62.5 "actn": 80.0 "purp": 37.5 "perc": 75.0 "cmdy": 75.0 , "name" : "nyteulo" "stats": "spos": 22.5 "alle": 25.0 "expr": 22.9 "pers": 67.9 "horn": 32.5 "fame": 40.5 "shwr": 34.6 "sani": 77.1 "rela": 64.3 "fedp": 29.8 "actn": 67.3 "purp": 31.3 "perc": 72.7 "cmdy": 67.5 , "name" : "AquaHeart" "stats": "spos": 62.5 "alle": 25.0 "expr": 50.0 "pers": 93.8 "horn": 31.3 "fame": 0.0 "shwr": 62.5 "sani": 50.0 "rela": 75.0 "fedp": 6.3 "actn": 95.0 "purp": 43.8 "perc": 68.8 "cmdy": 18.8 , "name" : "Plant" "stats": "spos": 35.0 "alle": 79.5 "expr": 100.0 "pers": 58.9 "horn": 17.5 "fame": 65.5 "shwr": 63.5 "sani": 60.4 "rela": 73.2 "fedp": 57.3 "actn": 42.3 "purp": 16.7 "perc": 63.6 "cmdy": 65.0 , "name" : "Arunn" "stats": "spos": 35.0 "alle": 70.5 "expr": 81.3 "pers": 57.1 "horn": 12.5 "fame": 9.5 "shwr": 25.0 "sani": 70.8 "rela": 69.6 "fedp": 25.8 "actn": 61.5 "purp": 39.6 "perc": 63.6 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 42.5 "alle": 59.1 "expr": 27.1 "pers": 58.9 "horn": 15.0 "fame": 44.0 "shwr": 23.1 "sani": 45.8 "rela": 60.7 "fedp": 71.0 "actn": 57.7 "purp": 39.6 "perc": 38.6 "cmdy": 72.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 95.0 "alle": 34.1 "expr": 25.0 "pers": 26.8 "horn": 27.5 "fame": 11.9 "shwr": 17.3 "sani": 70.8 "rela": 71.4 "fedp": 87.9 "actn": 67.3 "purp": 45.8 "perc": 65.9 "cmdy": 55.0 , "name" : "PI:NAME:<NAME>END_PIMorth" "stats": "spos": 55.0 "alle": 93.2 "expr": 14.6 "pers": 12.5 "horn": 42.5 "fame": 17.9 "shwr": 34.6 "sani": 50.0 "rela": 57.1 "fedp": 91.9 "actn": 21.2 "purp": 18.8 "perc": 50.0 "cmdy": 50.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 80.0 "alle": 47.7 "expr": 39.6 "pers": 75.0 "horn": 72.5 "fame": 45.2 "shwr": 46.2 "sani": 75.0 "rela": 85.7 "fedp": 17.7 "actn": 63.5 "purp": 70.8 "perc": 77.3 "cmdy": 67.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 81.3 "alle": 18.8 "expr": 25.0 "pers": 100.0 "horn": 6.3 "fame": 31.3 "shwr": 37.5 "sani": 81.3 "rela": 75.0 "fedp": 37.5 "actn": 90.0 "purp": 25.0 "perc": 56.3 "cmdy": 75.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 32.5 "alle": 97.7 "expr": 97.9 "pers": 44.6 "horn": 10.0 "fame": 40.5 "shwr": 75.0 "sani": 35.4 "rela": 37.5 "fedp": 58.9 "actn": 36.5 "purp": 16.7 "perc": 22.7 "cmdy": 25.0 , "name" : "firebender1234" "stats": "spos": 56.3 "alle": 75.0 "expr": 58.3 "pers": 75.0 "horn": 6.3 "fame": 50.0 "shwr": 25.0 "sani": 62.5 "rela": 45.0 "fedp": 87.5 "actn": 75.0 "purp": 31.3 "perc": 62.5 "cmdy": 100.0 , "name" : "Sarperen" "stats": "spos": 50.0 "alle": 43.8 "expr": 41.7 "pers": 75.0 "horn": 62.5 "fame": 6.3 "shwr": 81.3 "sani": 37.5 "rela": 70.0 "fedp": 6.3 "actn": 90.0 "purp": 31.3 "perc": 75.0 "cmdy": 43.8 , "name" : "SweatingCup2632" "stats": "spos": 40.0 "alle": 50.0 "expr": 75.0 "pers": 80.0 "horn": 0.0 "fame": 55.0 "shwr": 55.0 "sani": 85.0 "rela": 50.0 "fedp": 45.0 "actn": 90.0 "purp": 20.0 "perc": 60.0 "cmdy": 55.0 , "name" : "Antonio_1" "stats": "spos": 42.5 "alle": 54.5 "expr": 16.7 "pers": 55.4 "horn": 57.5 "fame": 14.3 "shwr": 30.8 "sani": 66.7 "rela": 64.3 "fedp": 39.5 "actn": 51.9 "purp": 43.8 "perc": 72.7 "cmdy": 60.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 75.0 "alle": 63.6 "expr": 20.8 "pers": 73.2 "horn": 27.5 "fame": 26.2 "shwr": 28.8 "sani": 85.4 "rela": 53.6 "fedp": 19.4 "actn": 71.2 "purp": 39.6 "perc": 54.5 "cmdy": 47.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 47.5 "alle": 43.2 "expr": 12.5 "pers": 32.1 "horn": 60.0 "fame": 19.0 "shwr": 7.7 "sani": 60.4 "rela": 42.9 "fedp": 58.1 "actn": 48.1 "purp": 62.5 "perc": 56.8 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 56.3 "alle": 25.0 "expr": 50.0 "pers": 81.3 "horn": 0.0 "fame": 0.0 "shwr": 25.0 "sani": 87.5 "rela": 90.0 "fedp": 43.8 "actn": 95.0 "purp": 56.3 "perc": 87.5 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 56.3 "alle": 12.5 "expr": 41.7 "pers": 68.8 "horn": 12.5 "fame": 37.5 "shwr": 62.5 "sani": 62.5 "rela": 75.0 "fedp": 0.0 "actn": 90.0 "purp": 18.8 "perc": 75.0 "cmdy": 62.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 50.0 "alle": 100.0 "expr": 8.3 "pers": 37.5 "horn": 100.0 "fame": 43.8 "shwr": 0.0 "sani": 25.0 "rela": 100.0 "fedp": 18.8 "actn": 60.0 "purp": 0.0 "perc": 75.0 "cmdy": 50.0 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 68.8 "alle": 43.8 "expr": 58.3 "pers": 68.8 "horn": 81.3 "fame": 62.5 "shwr": 0.0 "sani": 56.3 "rela": 70.0 "fedp": 43.8 "actn": 75.0 "purp": 37.5 "perc": 62.5 "cmdy": 62.5 , "name" : "ThisIsMyUsernameAAA" "stats": "spos": 37.5 "alle": 100.0 "expr": 83.3 "pers": 100.0 "horn": 56.3 "fame": 100.0 "shwr": 12.5 "sani": 43.8 "rela": 65.0 "fedp": 18.8 "actn": 10.0 "purp": 0.0 "perc": 12.5 "cmdy": 37.5 , "name" : "PI:NAME:<NAME>END_PI" "stats": "spos": 80.0 "alle": 27.3 "expr": 62.5 "pers": 89.3 "horn": 7.5 "fame": 75.0 "shwr": 38.5 "sani": 85.4 "rela": 96.4 "fedp": 51.6 "actn": 80.8 "purp": 56.3 "perc": 72.7 "cmdy": 62.5 , "name" : "AmericanFascist" "stats": "spos": 81.3 "alle": 43.8 "expr": 58.3 "pers": 56.3 "horn": 12.5 "fame": 62.5 "shwr": 25.0 "sani": 81.3 "rela": 65.0 "fedp": 62.5 "actn": 80.0 "purp": 18.8 "perc": 56.3 "cmdy": 81.3 ]
[ { "context": "id-123\"\n\t\t@project_history_id = 987\n\t\t@user_id = \"user-id-456\"\n\t\t@brand_variation_id = 789\n\t\t@export_params = {", "end": 791, "score": 0.9418739676475525, "start": 780, "tag": "USERNAME", "value": "user-id-456" }, { "context": "y_id\n\t\t\t@user =\n\t\t\t...
test/unit/coffee/Exports/ExportsHandlerTests.coffee
davidmehren/web-sharelatex
0
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = '../../../../app/js/Features/Exports/ExportsHandler.js' SandboxedModule = require('sandboxed-module') describe 'ExportsHandler', -> beforeEach -> @ProjectGetter = {} @ProjectLocator = {} @UserGetter = {} @settings = {} @stubRequest = {} @request = defaults: => return @stubRequest @ExportsHandler = SandboxedModule.require modulePath, requires: 'logger-sharelatex': log: -> err: -> '../Project/ProjectGetter': @ProjectGetter '../Project/ProjectLocator': @ProjectLocator '../User/UserGetter': @UserGetter 'settings-sharelatex': @settings 'request': @request @project_id = "project-id-123" @project_history_id = 987 @user_id = "user-id-456" @brand_variation_id = 789 @export_params = { project_id: @project_id, brand_variation_id: @brand_variation_id, user_id: @user_id } @callback = sinon.stub() describe 'exportProject', -> beforeEach (done) -> @export_data = {iAmAnExport: true} @response_body = {iAmAResponseBody: true} @ExportsHandler._buildExport = sinon.stub().yields(null, @export_data) @ExportsHandler._requestExport = sinon.stub().yields(null, @response_body) @ExportsHandler.exportProject @export_params, (error, export_data) => @callback(error, export_data) done() it "should build the export", -> @ExportsHandler._buildExport .calledWith(@export_params) .should.equal true it "should request the export", -> @ExportsHandler._requestExport .calledWith(@export_data) .should.equal true it "should return the export", -> @callback .calledWith(null, @export_data) .should.equal true describe '_buildExport', -> beforeEach (done) -> @project = id: @project_id overleaf: history: id: @project_history_id @user = id: @user_id first_name: 'Arthur' last_name: 'Author' email: 'arthur.author@arthurauthoring.org' @rootDocPath = 'main.tex' @historyVersion = 777 @ProjectGetter.getProject = sinon.stub().yields(null, @project) @ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'main.tex'}]) @UserGetter.getUser = sinon.stub().yields(null, @user) @ExportsHandler._requestVersion = sinon.stub().yields(null, @historyVersion) done() describe "when all goes well", -> beforeEach (done) -> @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should request the project history version", -> @ExportsHandler._requestVersion.called .should.equal true it "should return export data", -> expected_export_data = project: id: @project_id rootDocPath: @rootDocPath historyId: @project_history_id historyVersion: @historyVersion user: id: @user_id firstName: @user.first_name lastName: @user.last_name email: @user.email orcidId: null destination: brandVariationId: @brand_variation_id options: callbackUrl: null @callback.calledWith(null, expected_export_data) .should.equal true describe "when we send replacement user first and last name", -> beforeEach (done) -> @custom_first_name = "FIRST" @custom_last_name = "LAST" @export_params.first_name = @custom_first_name @export_params.last_name = @custom_last_name @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should send the data from the user input", -> expected_export_data = project: id: @project_id rootDocPath: @rootDocPath historyId: @project_history_id historyVersion: @historyVersion user: id: @user_id firstName: @custom_first_name lastName: @custom_last_name email: @user.email orcidId: null destination: brandVariationId: @brand_variation_id options: callbackUrl: null @callback.calledWith(null, expected_export_data) .should.equal true describe "when project is not found", -> beforeEach (done) -> @ProjectGetter.getProject = sinon.stub().yields(new Error("project not found")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when project has no root doc", -> beforeEach (done) -> @ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, null]) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when user is not found", -> beforeEach (done) -> @UserGetter.getUser = sinon.stub().yields(new Error("user not found")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when project history request fails", -> beforeEach (done) -> @ExportsHandler._requestVersion = sinon.stub().yields(new Error("project history call failed")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe '_requestExport', -> beforeEach (done) -> @settings.apis = v1: url: 'http://localhost:5000' user: 'overleaf' pass: 'pass' @export_data = {iAmAnExport: true} @export_id = 4096 @stubPost = sinon.stub().yields(null, {statusCode: 200}, { exportId: @export_id }) done() describe "when all goes well", -> beforeEach (done) -> @stubRequest.post = @stubPost @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it 'should issue the request', -> expect(@stubPost.getCall(0).args[0]).to.deep.equal url: @settings.apis.v1.url + '/api/v1/sharelatex/exports' auth: user: @settings.apis.v1.user pass: @settings.apis.v1.pass json: @export_data it 'should return the v1 export id', -> @callback.calledWith(null, @export_id) .should.equal true describe "when the request fails", -> beforeEach (done) -> @stubRequest.post = sinon.stub().yields(new Error("export request failed")) @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when the request returns an error code", -> beforeEach (done) -> @stubRequest.post = sinon.stub().yields(null, {statusCode: 401}, { }) @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it "should return the error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe 'fetchExport', -> beforeEach (done) -> @settings.apis = v1: url: 'http://localhost:5000' user: 'overleaf' pass: 'pass' @export_id = 897 @body = "{\"id\":897, \"status_summary\":\"completed\"}" @stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body }) done() describe "when all goes well", -> beforeEach (done) -> @stubRequest.get = @stubGet @ExportsHandler.fetchExport @export_id, (error, body) => @callback(error, body) done() it 'should issue the request', -> expect(@stubGet.getCall(0).args[0]).to.deep.equal url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id auth: user: @settings.apis.v1.user pass: @settings.apis.v1.pass it 'should return the v1 export id', -> @callback.calledWith(null, { body: @body }) .should.equal true
205717
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = '../../../../app/js/Features/Exports/ExportsHandler.js' SandboxedModule = require('sandboxed-module') describe 'ExportsHandler', -> beforeEach -> @ProjectGetter = {} @ProjectLocator = {} @UserGetter = {} @settings = {} @stubRequest = {} @request = defaults: => return @stubRequest @ExportsHandler = SandboxedModule.require modulePath, requires: 'logger-sharelatex': log: -> err: -> '../Project/ProjectGetter': @ProjectGetter '../Project/ProjectLocator': @ProjectLocator '../User/UserGetter': @UserGetter 'settings-sharelatex': @settings 'request': @request @project_id = "project-id-123" @project_history_id = 987 @user_id = "user-id-456" @brand_variation_id = 789 @export_params = { project_id: @project_id, brand_variation_id: @brand_variation_id, user_id: @user_id } @callback = sinon.stub() describe 'exportProject', -> beforeEach (done) -> @export_data = {iAmAnExport: true} @response_body = {iAmAResponseBody: true} @ExportsHandler._buildExport = sinon.stub().yields(null, @export_data) @ExportsHandler._requestExport = sinon.stub().yields(null, @response_body) @ExportsHandler.exportProject @export_params, (error, export_data) => @callback(error, export_data) done() it "should build the export", -> @ExportsHandler._buildExport .calledWith(@export_params) .should.equal true it "should request the export", -> @ExportsHandler._requestExport .calledWith(@export_data) .should.equal true it "should return the export", -> @callback .calledWith(null, @export_data) .should.equal true describe '_buildExport', -> beforeEach (done) -> @project = id: @project_id overleaf: history: id: @project_history_id @user = id: @user_id first_name: '<NAME>' last_name: '<NAME>' email: '<EMAIL>' @rootDocPath = 'main.tex' @historyVersion = 777 @ProjectGetter.getProject = sinon.stub().yields(null, @project) @ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'main.tex'}]) @UserGetter.getUser = sinon.stub().yields(null, @user) @ExportsHandler._requestVersion = sinon.stub().yields(null, @historyVersion) done() describe "when all goes well", -> beforeEach (done) -> @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should request the project history version", -> @ExportsHandler._requestVersion.called .should.equal true it "should return export data", -> expected_export_data = project: id: @project_id rootDocPath: @rootDocPath historyId: @project_history_id historyVersion: @historyVersion user: id: @user_id firstName: @user.first_name lastName: @user.last_name email: @user.email orcidId: null destination: brandVariationId: @brand_variation_id options: callbackUrl: null @callback.calledWith(null, expected_export_data) .should.equal true describe "when we send replacement user first and last name", -> beforeEach (done) -> @custom_first_name = "<NAME>" @custom_last_name = "<NAME>" @export_params.first_name = @custom_first_name @export_params.last_name = @custom_last_name @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should send the data from the user input", -> expected_export_data = project: id: @project_id rootDocPath: @rootDocPath historyId: @project_history_id historyVersion: @historyVersion user: id: @user_id firstName: @custom_first_name lastName: @custom_last_name email: @user.email orcidId: null destination: brandVariationId: @brand_variation_id options: callbackUrl: null @callback.calledWith(null, expected_export_data) .should.equal true describe "when project is not found", -> beforeEach (done) -> @ProjectGetter.getProject = sinon.stub().yields(new Error("project not found")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when project has no root doc", -> beforeEach (done) -> @ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, null]) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when user is not found", -> beforeEach (done) -> @UserGetter.getUser = sinon.stub().yields(new Error("user not found")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when project history request fails", -> beforeEach (done) -> @ExportsHandler._requestVersion = sinon.stub().yields(new Error("project history call failed")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe '_requestExport', -> beforeEach (done) -> @settings.apis = v1: url: 'http://localhost:5000' user: 'overleaf' pass: '<PASSWORD>' @export_data = {iAmAnExport: true} @export_id = 4096 @stubPost = sinon.stub().yields(null, {statusCode: 200}, { exportId: @export_id }) done() describe "when all goes well", -> beforeEach (done) -> @stubRequest.post = @stubPost @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it 'should issue the request', -> expect(@stubPost.getCall(0).args[0]).to.deep.equal url: @settings.apis.v1.url + '/api/v1/sharelatex/exports' auth: user: @settings.apis.v1.user pass: @settings.apis.v1.pass json: @export_data it 'should return the v1 export id', -> @callback.calledWith(null, @export_id) .should.equal true describe "when the request fails", -> beforeEach (done) -> @stubRequest.post = sinon.stub().yields(new Error("export request failed")) @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when the request returns an error code", -> beforeEach (done) -> @stubRequest.post = sinon.stub().yields(null, {statusCode: 401}, { }) @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it "should return the error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe 'fetchExport', -> beforeEach (done) -> @settings.apis = v1: url: 'http://localhost:5000' user: 'overleaf' pass: '<PASSWORD>' @export_id = 897 @body = "{\"id\":897, \"status_summary\":\"completed\"}" @stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body }) done() describe "when all goes well", -> beforeEach (done) -> @stubRequest.get = @stubGet @ExportsHandler.fetchExport @export_id, (error, body) => @callback(error, body) done() it 'should issue the request', -> expect(@stubGet.getCall(0).args[0]).to.deep.equal url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id auth: user: @settings.apis.v1.user pass: @settings.apis.v1.pass it 'should return the v1 export id', -> @callback.calledWith(null, { body: @body }) .should.equal true
true
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = '../../../../app/js/Features/Exports/ExportsHandler.js' SandboxedModule = require('sandboxed-module') describe 'ExportsHandler', -> beforeEach -> @ProjectGetter = {} @ProjectLocator = {} @UserGetter = {} @settings = {} @stubRequest = {} @request = defaults: => return @stubRequest @ExportsHandler = SandboxedModule.require modulePath, requires: 'logger-sharelatex': log: -> err: -> '../Project/ProjectGetter': @ProjectGetter '../Project/ProjectLocator': @ProjectLocator '../User/UserGetter': @UserGetter 'settings-sharelatex': @settings 'request': @request @project_id = "project-id-123" @project_history_id = 987 @user_id = "user-id-456" @brand_variation_id = 789 @export_params = { project_id: @project_id, brand_variation_id: @brand_variation_id, user_id: @user_id } @callback = sinon.stub() describe 'exportProject', -> beforeEach (done) -> @export_data = {iAmAnExport: true} @response_body = {iAmAResponseBody: true} @ExportsHandler._buildExport = sinon.stub().yields(null, @export_data) @ExportsHandler._requestExport = sinon.stub().yields(null, @response_body) @ExportsHandler.exportProject @export_params, (error, export_data) => @callback(error, export_data) done() it "should build the export", -> @ExportsHandler._buildExport .calledWith(@export_params) .should.equal true it "should request the export", -> @ExportsHandler._requestExport .calledWith(@export_data) .should.equal true it "should return the export", -> @callback .calledWith(null, @export_data) .should.equal true describe '_buildExport', -> beforeEach (done) -> @project = id: @project_id overleaf: history: id: @project_history_id @user = id: @user_id first_name: 'PI:NAME:<NAME>END_PI' last_name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' @rootDocPath = 'main.tex' @historyVersion = 777 @ProjectGetter.getProject = sinon.stub().yields(null, @project) @ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'main.tex'}]) @UserGetter.getUser = sinon.stub().yields(null, @user) @ExportsHandler._requestVersion = sinon.stub().yields(null, @historyVersion) done() describe "when all goes well", -> beforeEach (done) -> @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should request the project history version", -> @ExportsHandler._requestVersion.called .should.equal true it "should return export data", -> expected_export_data = project: id: @project_id rootDocPath: @rootDocPath historyId: @project_history_id historyVersion: @historyVersion user: id: @user_id firstName: @user.first_name lastName: @user.last_name email: @user.email orcidId: null destination: brandVariationId: @brand_variation_id options: callbackUrl: null @callback.calledWith(null, expected_export_data) .should.equal true describe "when we send replacement user first and last name", -> beforeEach (done) -> @custom_first_name = "PI:NAME:<NAME>END_PI" @custom_last_name = "PI:NAME:<NAME>END_PI" @export_params.first_name = @custom_first_name @export_params.last_name = @custom_last_name @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should send the data from the user input", -> expected_export_data = project: id: @project_id rootDocPath: @rootDocPath historyId: @project_history_id historyVersion: @historyVersion user: id: @user_id firstName: @custom_first_name lastName: @custom_last_name email: @user.email orcidId: null destination: brandVariationId: @brand_variation_id options: callbackUrl: null @callback.calledWith(null, expected_export_data) .should.equal true describe "when project is not found", -> beforeEach (done) -> @ProjectGetter.getProject = sinon.stub().yields(new Error("project not found")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when project has no root doc", -> beforeEach (done) -> @ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, null]) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when user is not found", -> beforeEach (done) -> @UserGetter.getUser = sinon.stub().yields(new Error("user not found")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when project history request fails", -> beforeEach (done) -> @ExportsHandler._requestVersion = sinon.stub().yields(new Error("project history call failed")) @ExportsHandler._buildExport @export_params, (error, export_data) => @callback(error, export_data) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe '_requestExport', -> beforeEach (done) -> @settings.apis = v1: url: 'http://localhost:5000' user: 'overleaf' pass: 'PI:PASSWORD:<PASSWORD>END_PI' @export_data = {iAmAnExport: true} @export_id = 4096 @stubPost = sinon.stub().yields(null, {statusCode: 200}, { exportId: @export_id }) done() describe "when all goes well", -> beforeEach (done) -> @stubRequest.post = @stubPost @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it 'should issue the request', -> expect(@stubPost.getCall(0).args[0]).to.deep.equal url: @settings.apis.v1.url + '/api/v1/sharelatex/exports' auth: user: @settings.apis.v1.user pass: @settings.apis.v1.pass json: @export_data it 'should return the v1 export id', -> @callback.calledWith(null, @export_id) .should.equal true describe "when the request fails", -> beforeEach (done) -> @stubRequest.post = sinon.stub().yields(new Error("export request failed")) @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it "should return an error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe "when the request returns an error code", -> beforeEach (done) -> @stubRequest.post = sinon.stub().yields(null, {statusCode: 401}, { }) @ExportsHandler._requestExport @export_data, (error, export_v1_id) => @callback(error, export_v1_id) done() it "should return the error", -> (@callback.args[0][0] instanceof Error) .should.equal true describe 'fetchExport', -> beforeEach (done) -> @settings.apis = v1: url: 'http://localhost:5000' user: 'overleaf' pass: 'PI:PASSWORD:<PASSWORD>END_PI' @export_id = 897 @body = "{\"id\":897, \"status_summary\":\"completed\"}" @stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body }) done() describe "when all goes well", -> beforeEach (done) -> @stubRequest.get = @stubGet @ExportsHandler.fetchExport @export_id, (error, body) => @callback(error, body) done() it 'should issue the request', -> expect(@stubGet.getCall(0).args[0]).to.deep.equal url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id auth: user: @settings.apis.v1.user pass: @settings.apis.v1.pass it 'should return the v1 export id', -> @callback.calledWith(null, { body: @body }) .should.equal true